diff --git a/apps/discord-bot/src/features/TeamsGroupChatObserver.ts b/apps/discord-bot/src/features/TeamsGroupChatObserver.ts index 5570eae4d0376..ce6d72aa9ab8d 100644 --- a/apps/discord-bot/src/features/TeamsGroupChatObserver.ts +++ b/apps/discord-bot/src/features/TeamsGroupChatObserver.ts @@ -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"; @@ -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)); @@ -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, @@ -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 }; @@ -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), @@ -329,7 +326,7 @@ 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 }; } @@ -337,7 +334,7 @@ export const ingestTeamsGroupChat = Effect.fn("ingestTeamsGroupChat")(function* 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 }; } @@ -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, @@ -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" ? {} : { diff --git a/apps/discord-bot/src/teams-gateway-main.ts b/apps/discord-bot/src/teams-gateway-main.ts index e718b59c1e967..0a3bed6c21514 100644 --- a/apps/discord-bot/src/teams-gateway-main.ts +++ b/apps/discord-bot/src/teams-gateway-main.ts @@ -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"; @@ -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(); const observeGroupChat = async ( - activity: GatewayActivity & { + incoming: GatewayActivity & { readonly replyToId?: string; readonly attachments?: ReadonlyArray; }, api: Parameters[0], event: "message" | "join", ): Promise => { + 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)( diff --git a/apps/discord-bot/src/teams/groupChatTitles.test.ts b/apps/discord-bot/src/teams/groupChatTitles.test.ts new file mode 100644 index 0000000000000..7ae567df5a325 --- /dev/null +++ b/apps/discord-bot/src/teams/groupChatTitles.test.ts @@ -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 = []; + 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", + }); + }); +}); diff --git a/apps/discord-bot/src/teams/groupChatTitles.ts b/apps/discord-bot/src/teams/groupChatTitles.ts new file mode 100644 index 0000000000000..c6f7af36ef80e --- /dev/null +++ b/apps/discord-bot/src/teams/groupChatTitles.ts @@ -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; + readonly fetchImpl?: typeof globalThis.fetch; + readonly now?: () => number; +}) { + const fetchImpl = input.fetchImpl ?? globalThis.fetch; + const now = input.now ?? Date.now; + const cache = new Map(); + + const lookup = async (tenantId: string, chatId: string): Promise => { + 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 => { + 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; + }; +} diff --git a/apps/discord-bot/src/teams/weeklyThreads.test.ts b/apps/discord-bot/src/teams/weeklyThreads.test.ts new file mode 100644 index 0000000000000..a195e2c185207 --- /dev/null +++ b/apps/discord-bot/src/teams/weeklyThreads.test.ts @@ -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", + ); + }); +}); diff --git a/apps/discord-bot/src/teams/weeklyThreads.ts b/apps/discord-bot/src/teams/weeklyThreads.ts new file mode 100644 index 0000000000000..451dc06d23b0e --- /dev/null +++ b/apps/discord-bot/src/teams/weeklyThreads.ts @@ -0,0 +1,35 @@ +// @effect-diagnostics globalDate:off +/** Watched Teams group chats open a fresh log thread each week, starting Monday 00:00 here. */ +export const TEAMS_THREAD_WEEK_TIME_ZONE = "Europe/Amsterdam"; + +const WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] as const; + +/** `week-YYYY-MM-DD`, naming the Monday that starts the week containing `at`. */ +export function teamsWeekBucket(at: Date, timeZone: string = TEAMS_THREAD_WEEK_TIME_ZONE): string { + const parts = new Intl.DateTimeFormat("en-US", { + timeZone, + year: "numeric", + month: "2-digit", + day: "2-digit", + weekday: "short", + }).formatToParts(at); + const part = (type: Intl.DateTimeFormatPartTypes) => + parts.find((entry) => entry.type === type)?.value ?? ""; + const daysSinceMonday = Math.max( + WEEKDAYS.indexOf(part("weekday") as (typeof WEEKDAYS)[number]), + 0, + ); + const monday = new Date( + Date.UTC( + Number(part("year")), + Number(part("month")) - 1, + Number(part("day")) - daysSinceMonday, + ), + ); + return `week-${monday.toISOString().slice(0, 10)}`; +} + +/** Appends the week bucket to a group chat's key. */ +export function weeklyThreadKey(locationKey: string, at: Date): string { + return `${locationKey}/${teamsWeekBucket(at)}`; +}