Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 13 additions & 16 deletions apps/discord-bot/src/features/TeamsGroupChatObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
import type * as Context from "effect/Context";
import { DiscordREST } from "dfx";
import * as Context_ from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
Expand All @@ -30,6 +31,7 @@ import {
type GroupChatPlan,
type GroupChatRule,
} from "../teams/groupChats.ts";
import { weeklyThreadKey } from "../teams/weeklyThreads.ts";
import { startOrContinueLinkedTurn } from "./LinkedTurnRouter.ts";

const decodeGroupChatAnswers = Schema.decodeEffect(Schema.fromJsonString(ProviderUserInputAnswers));
Expand Down Expand Up @@ -226,7 +228,7 @@ const runGroupChatCommand = Effect.fn("runGroupChatCommand")(function* (

/**
* Observe a Teams group chat without sending anything back to it.
* One T3 thread, one Discord alerts thread, and one internal Teams channel thread.
* One T3 thread, one Discord alerts thread, and one internal Teams channel thread per week.
*/
export const ingestTeamsGroupChat = Effect.fn("ingestTeamsGroupChat")(function* (
config: DiscordBotConfig,
Expand Down Expand Up @@ -283,28 +285,23 @@ export const ingestTeamsGroupChat = Effect.fn("ingestTeamsGroupChat")(function*
return { handled: true as const };
}

// Group chats have no reply chains, so the whole chat starts a fresh thread each week.
const sourceKey = weeklyThreadKey(plan.sourceKey, DateTime.toDateUtc(yield* DateTime.now));
const links = yield* ThreadLinkStore;
const existing = yield* links.getBySourceThread("teams", plan.sourceKey);
const existing = yield* links.getBySourceThread("teams", sourceKey);
const mirrorsFile = groupChatMirrorsFile(config.dataDir);
if (plan.kind === "ignore") {
if (existing !== null) {
const line = groupChatLogLine(activity.author ?? "unknown", activity.text);
yield* postDiscord(runtime, existing.discordThreadId, line);
yield* copyToChannelThread(
poster,
mirrorsFile,
plan.sourceKey,
plan.chat.mirror,
plan.chat,
line,
);
yield* copyToChannelThread(poster, mirrorsFile, sourceKey, plan.chat.mirror, plan.chat, line);
}
return { handled: true as const };
}
if (plan.kind === "command") {
if (existing === null) {
yield* Effect.logInfo("Ignored Teams group chat command before the chat thread exists", {
sourceKey: plan.sourceKey,
sourceKey,
command: plan.command.kind,
});
return { handled: true as const };
Expand All @@ -318,7 +315,7 @@ export const ingestTeamsGroupChat = Effect.fn("ingestTeamsGroupChat")(function*
yield* copyToChannelThread(
poster,
mirrorsFile,
plan.sourceKey,
sourceKey,
plan.chat.mirror,
plan.chat,
groupChatLogLine(activity.author ?? "unknown", activity.text),
Expand All @@ -329,15 +326,15 @@ export const ingestTeamsGroupChat = Effect.fn("ingestTeamsGroupChat")(function*

if (discordRest(runtime) === null) {
yield* Effect.logError("Discord is unavailable; passive Teams group chat was not opened", {
sourceKey: plan.sourceKey,
sourceKey,
});
return { handled: true as const };
}
const alertsChannelId = config.alertsChannelId;
if (existing === null && (alertsChannelId === undefined || alertsChannelId.length === 0)) {
yield* Effect.logError(
"DISCORD_ALERTS_CHANNEL_ID is unset; passive Teams group chat was not opened",
{ sourceKey: plan.sourceKey },
{ sourceKey },
);
return { handled: true as const };
}
Expand All @@ -352,7 +349,7 @@ export const ingestTeamsGroupChat = Effect.fn("ingestTeamsGroupChat")(function*
const channelThread = yield* copyToChannelThread(
poster,
mirrorsFile,
plan.sourceKey,
sourceKey,
plan.chat.mirror,
plan.chat,
observation,
Expand All @@ -364,7 +361,7 @@ export const ingestTeamsGroupChat = Effect.fn("ingestTeamsGroupChat")(function*
const t3ThreadId = yield* useRuntime(
runtime,
startOrContinueLinkedTurn(config, {
source: { sourceKind: "teams", sourceThreadId: plan.sourceKey },
source: { sourceKind: "teams", sourceThreadId: sourceKey },
...(knownPerson === null || plan.wake !== "instruction"
? {}
: {
Expand Down
47 changes: 44 additions & 3 deletions apps/discord-bot/src/teams-gateway-main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ import { IdentityMapStore, layerFromOptionalPath as identityMapLayer } from "./i
import { layerFromOptionalPath as aliasesLayer } from "./projectAliases.ts";
import { ThreadLinkStore, layer as linksLayer } from "./store/ThreadLinkStore.ts";
import { T3Session, layer as sessionLayer } from "./t3/T3Session.ts";
import { botWasAdded } from "./teams/groupChats.ts";
import { botWasAdded, isTeamsGroupChat } from "./teams/groupChats.ts";
import { makeGroupChatTitleResolver } from "./teams/groupChatTitles.ts";
import { readGatewayConfig, readPrivateCredential } from "./teams/gatewayConfig.ts";
import { ingestTeamsGroupChat, teamsChannelPoster } from "./features/TeamsGroupChatObserver.ts";
import { mentionsTeamsRecipient, registerTeamsMessageEvents } from "./teams/messageEvents.ts";
Expand Down Expand Up @@ -280,18 +281,58 @@ const program = Effect.gen(function* () {
};
});

const groupChatTitle = makeGroupChatTitleResolver({
clientId: initial.identity.entraClientId,
clientSecret: () => readPrivateCredential(secretPath),
tokenCache: teamsTokenCache,
});
// One "not watched" line per chat per process, so a busy unwatched chat can't flood the log.
const reportedUnwatchedChats = new Set<string>();
const observeGroupChat = async (
activity: GatewayActivity & {
incoming: GatewayActivity & {
readonly replyToId?: string;
readonly attachments?: ReadonlyArray<TeamsActivityAttachment>;
},
api: Parameters<typeof teamsChannelPoster>[0],
event: "message" | "join",
): Promise<boolean> => {
if (
!isTeamsGroupChat({
conversationType: incoming.conversation.conversationType,
isGroup: incoming.conversation.isGroup,
teamId: incoming.channelData?.team?.id,
})
)
return false;
const title = await groupChatTitle({
tenantId:
incoming.channelData?.tenant?.id ??
incoming.conversation.tenantId ??
initial.identity.homeTenantId,
conversationId: incoming.conversation.id,
name: incoming.conversation.name,
});
const activity =
title.source === "graph" && title.title !== undefined
? { ...incoming, conversation: { ...incoming.conversation, name: title.title } }
: incoming;
const decision = policy.acceptGroupChat(activity);
if (decision.kind === "not-group") return false;
const unwatched = decision.kind === "silent" && decision.reason === "unmapped";
const chatId = activity.conversation.id.split(";messageid=")[0] ?? activity.conversation.id;
if (unwatched && event !== "join" && !reportedUnwatchedChats.has(chatId)) {
reportedUnwatchedChats.add(chatId);
Effect.runSyncWith(gatewayContext)(
Effect.logInfo("Teams group chat not watched", {
chat: chatId.slice(0, 24),
title: title.title ?? null,
titleSource: title.source,
graph: title.graph ?? null,
}),
);
}
const quiet =
(decision.kind === "silent" && decision.reason === "unmapped" && event !== "join") ||
(unwatched && event !== "join") ||
(decision.kind === "reject" && decision.reason === "duplicate");
if (!quiet) {
Effect.runSyncWith(gatewayContext)(
Expand Down
81 changes: 81 additions & 0 deletions apps/discord-bot/src/teams/groupChatTitles.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { describe, expect, it } from "vite-plus/test";

import { makeGroupChatTitleResolver } from "./groupChatTitles.ts";

const chat = "19:abc@thread.v2";

function harness(graph: { status: number; body?: unknown }) {
const calls: Array<string> = [];
let clock = 0;
const fetchImpl = (async (url: string | URL) => {
const href = String(url);
calls.push(href);
if (href.includes("login.microsoftonline.com"))
return new Response(JSON.stringify({ access_token: "token", expires_in: 3600 }));
return new Response(JSON.stringify(graph.body ?? {}), { status: graph.status });
}) as typeof globalThis.fetch;
const resolve = makeGroupChatTitleResolver({
clientId: "client",
clientSecret: () => "secret",
tokenCache: new Map(),
fetchImpl,
now: () => clock,
});
return {
calls,
resolve,
advance: (ms: number) => {
clock += ms;
},
};
}

describe("makeGroupChatTitleResolver", () => {
it("uses the activity's title without calling Graph", async () => {
const h = harness({ status: 200, body: { topic: "ignored" } });
expect(
await h.resolve({ tenantId: "t", conversationId: chat, name: " MAKO scanner " }),
).toEqual({
title: "MAKO scanner",
source: "activity",
});
expect(h.calls).toEqual([]);
});

it("reads the chat topic from Graph when the activity has none, and caches it", async () => {
const h = harness({ status: 200, body: { topic: "Empasa scanning" } });
const first = await h.resolve({
tenantId: "t",
conversationId: `${chat};messageid=1`,
name: undefined,
});
expect(first).toEqual({ title: "Empasa scanning", source: "graph", graph: "ok" });
expect(h.calls.at(-1)).toBe(
`https://graph.microsoft.com/v1.0/chats/${encodeURIComponent(chat)}?$select=id,topic`,
);
await h.resolve({ tenantId: "t", conversationId: chat, name: undefined });
expect(h.calls.filter((url) => url.includes("/chats/"))).toHaveLength(1);
});

it("reports a refused lookup and retries it after a while", async () => {
const h = harness({ status: 403 });
expect(await h.resolve({ tenantId: "t", conversationId: chat, name: undefined })).toEqual({
title: undefined,
source: "none",
graph: "403",
});
await h.resolve({ tenantId: "t", conversationId: chat, name: undefined });
expect(h.calls.filter((url) => url.includes("/chats/"))).toHaveLength(1);
h.advance(11 * 60 * 1000);
await h.resolve({ tenantId: "t", conversationId: chat, name: undefined });
expect(h.calls.filter((url) => url.includes("/chats/"))).toHaveLength(2);
});

it("treats an untitled chat as having no title", async () => {
const h = harness({ status: 200, body: { topic: null } });
expect(await h.resolve({ tenantId: "t", conversationId: chat, name: "" })).toMatchObject({
title: undefined,
graph: "no-topic",
});
});
});
80 changes: 80 additions & 0 deletions apps/discord-bot/src/teams/groupChatTitles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { fetchMicrosoftAppToken } from "./inboundImages.ts";

/** Where a group chat's title came from, for the "not watched" log. */
export type GroupChatTitleSource = "activity" | "graph" | "none";

export interface GroupChatTitle {
readonly title: string | undefined;
readonly source: GroupChatTitleSource;
/** Graph outcome when the activity had no title: `ok`, an HTTP status, or `error`. */
readonly graph?: string | undefined;
}

const FOUND_TTL_MS = 60 * 60 * 1000;
const MISSING_TTL_MS = 10 * 60 * 1000;

/**
* Teams often leaves `conversation.name` off group chat activities, and watched chats are matched
* by title. Fills it from Graph `GET /chats/{id}` (topic), cached per chat.
*/
export function makeGroupChatTitleResolver(input: {
readonly clientId: string;
readonly clientSecret: () => string;
readonly tokenCache: Map<string, { token: string; expiresAt: number }>;
readonly fetchImpl?: typeof globalThis.fetch;
readonly now?: () => number;
}) {
const fetchImpl = input.fetchImpl ?? globalThis.fetch;
const now = input.now ?? Date.now;
const cache = new Map<string, { readonly value: GroupChatTitle; readonly expiresAt: number }>();

const lookup = async (tenantId: string, chatId: string): Promise<GroupChatTitle> => {
const token = await fetchMicrosoftAppToken({
tenantId,
clientId: input.clientId,
clientSecret: input.clientSecret(),
scope: "https://graph.microsoft.com/.default",
fetchImpl,
cache: input.tokenCache,
});
if (token === null) return { title: undefined, source: "none", graph: "no-token" };
let response: Response;
try {
response = await fetchImpl(
`https://graph.microsoft.com/v1.0/chats/${encodeURIComponent(chatId)}?$select=id,topic`,
{
redirect: "error",
signal: AbortSignal.timeout(15_000),
headers: { authorization: `Bearer ${token}` },
},
);
} catch {
return { title: undefined, source: "none", graph: "error" };
}
if (!response.ok) return { title: undefined, source: "none", graph: String(response.status) };
const body = (await response.json().catch(() => null)) as { topic?: unknown } | null;
const topic = typeof body?.topic === "string" ? body.topic.trim() : "";
return topic.length > 0
? { title: topic, source: "graph", graph: "ok" }
: { title: undefined, source: "none", graph: "no-topic" };
};

return async (activity: {
readonly tenantId: string;
readonly conversationId: string;
readonly name: string | undefined;
}): Promise<GroupChatTitle> => {
const name = activity.name?.trim();
if (name !== undefined && name.length > 0) return { title: name, source: "activity" };
const chatId = activity.conversationId.split(";messageid=")[0] ?? activity.conversationId;
const key = `${activity.tenantId}\n${chatId}`;
const cached = cache.get(key);
if (cached !== undefined && cached.expiresAt > now()) return cached.value;
const value = await lookup(activity.tenantId, chatId);
cache.set(key, {
value,
expiresAt: now() + (value.title === undefined ? MISSING_TTL_MS : FOUND_TTL_MS),
});
return value;
};
}
28 changes: 28 additions & 0 deletions apps/discord-bot/src/teams/weeklyThreads.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// @effect-diagnostics globalDate:off
import { describe, expect, it } from "vite-plus/test";

import { teamsWeekBucket, weeklyThreadKey } from "./weeklyThreads.ts";

describe("teamsWeekBucket", () => {
it("names the Monday that starts the week", () => {
expect(teamsWeekBucket(new Date("2026-11-23T12:00:00Z"))).toBe("week-2026-11-23");
expect(teamsWeekBucket(new Date("2026-11-26T12:00:00Z"))).toBe("week-2026-11-23");
expect(teamsWeekBucket(new Date("2026-11-29T12:00:00Z"))).toBe("week-2026-11-23");
});

it("rolls over at Monday midnight in Amsterdam, not UTC", () => {
// 23:30 UTC on Sunday is already 00:30 on Monday in Amsterdam (CET, UTC+1).
expect(teamsWeekBucket(new Date("2026-11-29T23:30:00Z"))).toBe("week-2026-11-30");
expect(teamsWeekBucket(new Date("2026-11-29T22:59:00Z"))).toBe("week-2026-11-23");
});

it("crosses month and year boundaries", () => {
expect(teamsWeekBucket(new Date("2027-01-01T09:00:00Z"))).toBe("week-2026-12-28");
});

it("appends the bucket to a group chat key", () => {
expect(weeklyThreadKey("native/t/group/19:chat", new Date("2026-11-24T09:00:00Z"))).toBe(
"native/t/group/19:chat/week-2026-11-23",
);
});
});
Loading
Loading