From 8d5d8b98fc273eb5ea96b771a14d65424d370e53 Mon Sep 17 00:00:00 2001 From: T3 Code PR Stack <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:51:07 +0100 Subject: [PATCH] fix(discord-bot): stream T3 replies into Teams group-chat mirrors and name weekly threads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Watched Teams group chats only got T3 output in their Teams mirror thread after someone mentioned the bot there, and each mention posted another Omegent Info card because the mirror thread had no link of its own. The weekly T3 thread took its title from the passive-chat prompt, so the Discord thread read "This Teams group chat is passive...", and the guest bot echoed every gateway observation a second time. - After a group-chat turn, the gateway bridges the weekly T3 thread into the mirror thread through a delivery-only lease on the mirror channel's binding. The lease shares the mention lease's reference key, so it is restored after restarts and a later mention reuses it. - Mirror threads get their own delivery link, keyed by the Teams conversation, so the info card, stream tips and delivered answers persist per conversation. Restore now looks links up by conversation. - Group-chat rules take an optional `title` and `discordChannelId`; workspaces take `scannerDiscordChannelId` for the built-in scanner chats. - The weekly T3 thread is created with the title "Teams: · week ". - The guest bridge no longer echoes Teams-sourced user messages in weekly group-chat Discord threads. - The `` mention in Teams' HTML copy of a message is no longer reported as attachment text. Co-Authored-By: Claude Opus 5.5 --- .../src/features/LinkedTurnRouter.ts | 3 + .../src/features/ResponseBridge.test.ts | 31 +++ .../src/features/ResponseBridge.ts | 7 + .../features/TeamsGroupChatObserver.test.ts | 127 +++++++++++- .../src/features/TeamsGroupChatObserver.ts | 89 ++++++++- apps/discord-bot/src/teams-gateway-main.ts | 181 +++++++++++------- .../src/teams/ResponseTransport.test.ts | 61 ++++++ apps/discord-bot/src/teams/gatewayConfig.ts | 3 + .../src/teams/gatewayPolicy.test.ts | 39 +++- apps/discord-bot/src/teams/gatewayPolicy.ts | 58 +++++- apps/discord-bot/src/teams/groupChats.test.ts | 74 +++++++ apps/discord-bot/src/teams/groupChats.ts | 54 +++++- .../src/teams/inboundImages.test.ts | 51 +++++ apps/discord-bot/src/teams/inboundImages.ts | 4 +- apps/discord-bot/src/teams/weeklyThreads.ts | 8 + 15 files changed, 697 insertions(+), 93 deletions(-) diff --git a/apps/discord-bot/src/features/LinkedTurnRouter.ts b/apps/discord-bot/src/features/LinkedTurnRouter.ts index 885e6f31fb535..438b1ad19f3df 100644 --- a/apps/discord-bot/src/features/LinkedTurnRouter.ts +++ b/apps/discord-bot/src/features/LinkedTurnRouter.ts @@ -76,6 +76,8 @@ export interface TransportNeutralLinkedTurnInput { readonly stickyModelOnContinue?: boolean | undefined; readonly attachments?: ReadonlyArray | undefined; readonly promptContext?: LinkedTurnInput["promptContext"]; + /** T3 title for a new thread; otherwise it is cut from the prompt. */ + readonly title?: string | undefined; } /** Preserve the requester on every dispatch; the server keeps the first thread origin. */ @@ -214,6 +216,7 @@ export const startOrContinueT3Turn = Effect.fn("startOrContinueT3Turn")(function const { threadId, messageId } = yield* t3.startTurnWithWorktree({ project: resolved.project, prompt: enrichedPrompt, + ...(input.title === undefined ? {} : { titleSeed: input.title }), modelSelection, interactionMode: input.flags.plan ? "plan" : "default", ...launchWorkspaceFields(workspace), diff --git a/apps/discord-bot/src/features/ResponseBridge.test.ts b/apps/discord-bot/src/features/ResponseBridge.test.ts index 15817383a3ba6..82154be75943c 100644 --- a/apps/discord-bot/src/features/ResponseBridge.test.ts +++ b/apps/discord-bot/src/features/ResponseBridge.test.ts @@ -1,5 +1,6 @@ import { MessageId, TurnId, type VcsStatusResult } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; +import { isWeeklyGroupChatSourceKey } from "../teams/weeklyThreads.ts"; import { activeStreamTipIdsForDelivery, @@ -1576,6 +1577,36 @@ describe("rewriteInlinePathCodeSpansForDiscord", () => { }); describe("externalUserMessagesToEcho", () => { + it("leaves gateway observations out of a weekly Teams group-chat log, and only there", () => { + const user = (id: string, text: string, channel: "teams" | "web") => ({ + id: MessageId.make(id), + role: "user" as const, + text, + turnId: null, + streaming: false, + createdAt: "2026-11-27T00:00:00.000Z", + updatedAt: "2026-11-27T00:00:00.000Z", + source: { channel }, + }); + const messages = [ + user("observed", "This Teams group chat is passive. Do not send a message…", "teams"), + user("web", "check the scanner logs too", "web"), + ]; + const echoed = (teamsGroupChatLog: boolean) => + externalUserMessagesToEcho({ + messages, + observedInitialUserSnapshot: true, + seenUserMessageIds: [], + sentDiscordUserMessageIds: [], + teamsGroupChatLog, + }).map((message) => message.id); + const weekly = "native/tenant/group/19:chat@thread.v2/week-2026-11-23"; + expect(isWeeklyGroupChatSourceKey(weekly)).toBe(true); + expect(isWeeklyGroupChatSourceKey("native/tenant/team/19:c@thread.tacv2/conv")).toBe(false); + expect(echoed(true)).toEqual(["web"]); + expect(echoed(false)).toEqual(["observed", "web"]); + }); + it("includes unseen user messages from other clients", () => { const messages = externalUserMessagesToEcho({ messages: [ diff --git a/apps/discord-bot/src/features/ResponseBridge.ts b/apps/discord-bot/src/features/ResponseBridge.ts index d5316a23937fa..e43fddb8b991a 100644 --- a/apps/discord-bot/src/features/ResponseBridge.ts +++ b/apps/discord-bot/src/features/ResponseBridge.ts @@ -1,5 +1,6 @@ import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts"; import { type IntegrationThreadView as OrchestrationThread } from "@t3tools/shared/integrationThreadView"; +import { isWeeklyGroupChatSourceKey } from "../teams/weeklyThreads.ts"; // @effect-diagnostics anyUnknownInErrorContext:off missingEffectContext:off globalFetchInEffect:off unknownInEffectCatch:off nodeBuiltinImport:off import * as NodeCrypto from "node:crypto"; import * as NodeFSP from "node:fs/promises"; @@ -1275,6 +1276,8 @@ export function externalUserMessagesToEcho(input: { readonly observedInitialUserSnapshot: boolean; readonly seenUserMessageIds: ReadonlyArray; readonly sentDiscordUserMessageIds: ReadonlyArray; + /** Weekly Teams group-chat log: the gateway already posted each observation as a clean line. */ + readonly teamsGroupChatLog?: boolean; }): ReadonlyArray { if (!input.observedInitialUserSnapshot) return []; const seen = new Set(input.seenUserMessageIds); @@ -1282,6 +1285,7 @@ export function externalUserMessagesToEcho(input: { return input.messages.filter( (message) => message.role === "user" && + !(input.teamsGroupChatLog === true && message.source?.channel === "teams") && shouldEchoUserMessageToDiscord({ text: message.text, messageId: message.id, @@ -5262,6 +5266,9 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( observedInitialUserSnapshot: priorState.observedInitialUserSnapshot, seenUserMessageIds: priorState.seenUserMessageIds, sentDiscordUserMessageIds: priorState.sentDiscordUserMessageIds, + teamsGroupChatLog: + persistedLink?.sourceKind === "teams" && + isWeeklyGroupChatSourceKey(persistedLink.sourceThreadId), }); const pendingEchoIds = new Set(unseenExternalUserMessages.map((message) => message.id)); const unresolvedSentDiscordUserMessageIds = priorState.sentDiscordUserMessageIds.filter( diff --git a/apps/discord-bot/src/features/TeamsGroupChatObserver.test.ts b/apps/discord-bot/src/features/TeamsGroupChatObserver.test.ts index 928a1dc9a3c4e..e3846e2820253 100644 --- a/apps/discord-bot/src/features/TeamsGroupChatObserver.test.ts +++ b/apps/discord-bot/src/features/TeamsGroupChatObserver.test.ts @@ -22,9 +22,11 @@ import { T3Session, type T3SessionService } from "../t3/T3Session.ts"; import type { GroupChatRule } from "../teams/groupChats.ts"; import { parseOmegentLinkMarker } from "./linkMarker.ts"; import { + ensureTeamsMirrorLink, groupChatPlaceholderThreadId, ingestTeamsGroupChat, type TeamsChannelPoster, + type TeamsMirrorTurn, } from "./TeamsGroupChatObserver.ts"; const rules: ReadonlyArray = [ @@ -48,7 +50,10 @@ const message = (text: string) => ({ mentionedBot: false, }); -function makeHarness() { +function makeHarness( + chatRules: ReadonlyArray = rules, + base: { readonly title?: string | undefined } = {}, +) { return Effect.gen(function* () { const directory = yield* Effect.acquireRelease( Effect.promise(() => NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "group-chat-observer-"))), @@ -71,6 +76,8 @@ function makeHarness() { discordPosts: [] as Array<{ channelId: string; content: string }>, mirrorThreads: 0, mirrorReplies: [] as Array, + titles: [] as Array, + bridged: [] as Array, }; const state = { discordFails: false, mirrorFails: false, t3Fails: false, t3FailsOnce: false }; const projectId = ProjectId.make("project:scanner"); @@ -83,13 +90,14 @@ function makeHarness() { serverConfig: () => Effect.succeed({ settings: DEFAULT_SERVER_SETTINGS, newProjectsRoot: "/projects" }), shell: () => Effect.succeed({ threads: [] }), - startTurnWithWorktree: () => + startTurnWithWorktree: (input: { readonly titleSeed?: string }) => state.t3Fails || state.t3FailsOnce ? Effect.sync(() => { state.t3FailsOnce = false; }).pipe(Effect.andThen(Effect.fail(new Error("T3 down")))) : Effect.sync(() => { calls.t3Starts += 1; + calls.titles.push(input.titleSeed); return { threadId: ThreadId.make("thread:weekly"), messageId: "message:1" }; }), startTurn: () => @@ -127,9 +135,21 @@ function makeHarness() { const ingest = (text: string, withDiscord = true, t3Retries = 0) => Effect.gen(function* () { const runtime = yield* Effect.context(); - return yield* ingestTeamsGroupChat(config, rules, [], runtime, message(text), poster, { - t3RetrySchedule: Schedule.recurs(t3Retries), - }); + return yield* ingestTeamsGroupChat( + config, + chatRules, + [], + runtime, + { ...message(text), ...base }, + poster, + { + t3RetrySchedule: Schedule.recurs(t3Retries), + bridgeMirror: (turn) => + Effect.sync(() => { + calls.bridged.push(turn); + }), + }, + ); }).pipe( (effect) => (withDiscord ? Effect.provideService(effect, DiscordREST, rest) : effect), Effect.provideService(ThreadLinkStore, links), @@ -144,7 +164,12 @@ function makeHarness() { expect(all).toHaveLength(1); return all[0]!; }); - return { calls, state, ingest, links, weeklyLink }; + const ensureMirrorLink = (turn: TeamsMirrorTurn) => + ensureTeamsMirrorLink(turn).pipe( + Effect.provideService(ThreadLinkStore, links), + Effect.provideService(T3Session, session), + ); + return { calls, state, ingest, links, weeklyLink, ensureMirrorLink }; }); } @@ -248,3 +273,93 @@ describe("Teams group chat observer failure isolation", () => { }).pipe(Effect.scoped), ); }); + +describe("Teams group chat mirror delivery", () => { + it.effect("streams each weekly T3 turn into the Teams mirror thread", () => + Effect.gen(function* () { + const { calls, ingest, weeklyLink } = yield* makeHarness(); + yield* ingest("Der Scanner bucht nicht."); + yield* ingest("Immer noch nicht."); + const link = yield* weeklyLink; + expect(calls.bridged).toEqual([ + { + mirror: rules[0]!.mirror, + conversationId: "19:mirror@thread.tacv2;messageid=77", + sourceKey: link.sourceThreadId, + t3ThreadId: "thread:weekly", + messageId: "message:1", + }, + expect.objectContaining({ + conversationId: "19:mirror@thread.tacv2;messageid=77", + t3ThreadId: "thread:weekly", + messageId: "message:n", + }), + ]); + }).pipe(Effect.scoped), + ); + + it.effect("does not stream when the chat has no mirror thread", () => + Effect.gen(function* () { + const { calls, ingest } = yield* makeHarness([ + { titleIncludes: "MAKO", projectShortName: "scanner" }, + ]); + yield* ingest("Der Scanner bucht nicht."); + expect(calls.t3Starts).toBe(1); + expect(calls.mirrorThreads).toBe(0); + expect(calls.bridged).toEqual([]); + }).pipe(Effect.scoped), + ); + + it.effect( + "keeps one delivery link per mirror thread, whether a turn or a mention ensures it", + () => + Effect.gen(function* () { + const { calls, ingest, links, ensureMirrorLink } = yield* makeHarness(); + yield* ingest("Der Scanner bucht nicht."); + const turn = calls.bridged[0]!; + yield* ensureMirrorLink(turn); + yield* links.setInfoDiscordMessageId(turn.conversationId, "info-card", "fingerprint"); + // A later mention in the mirror thread ensures the same conversation and T3 thread. + yield* ensureMirrorLink(turn); + const all = yield* links.list(); + expect(all).toHaveLength(2); + const mirrorLink = yield* links.getByDiscordThreadId(turn.conversationId); + expect(mirrorLink?.t3ThreadId).toBe("thread:weekly"); + expect(mirrorLink?.infoDiscordMessageId).toBe("info-card"); + // The weekly key still resolves to the Discord thread's link. + const weekly = yield* links.getBySourceThread("teams", turn.sourceKey); + expect(weekly?.discordThreadId).toMatch(/^\d+$/u); + }).pipe(Effect.scoped), + ); +}); + +describe("Teams group chat names and channels", () => { + it.effect("names the T3 thread after the chat and week, not the passive prompt", () => + Effect.gen(function* () { + const { calls, ingest } = yield* makeHarness(); + yield* ingest("Der Scanner bucht nicht."); + expect(calls.titles[0]).toMatch(/^Teams: MAKO Scanner · week \d{4}-\d{2}-\d{2}$/u); + }).pipe(Effect.scoped), + ); + + it.effect("uses the rule's title and Discord channel when Teams sends no chat title", () => + Effect.gen(function* () { + const { calls, ingest, weeklyLink } = yield* makeHarness( + [ + { + conversationId: "19:chat@thread.v2", + projectShortName: "scanner", + title: "Easy Life Scanner", + discordChannelId: "1345512665602330664", + }, + ], + { title: undefined }, + ); + yield* ingest("Der Scanner bucht nicht."); + expect(calls.discordPosts[0]).toMatchObject({ channelId: "1345512665602330664" }); + expect(calls.discordPosts[0]?.content).toContain("**Easy Life Scanner**"); + expect(calls.titles[0]).toMatch(/^Teams: Easy Life Scanner · week /u); + expect((yield* weeklyLink).channelId).toBe("1345512665602330664"); + }).pipe(Effect.scoped), + ); +}); diff --git a/apps/discord-bot/src/features/TeamsGroupChatObserver.ts b/apps/discord-bot/src/features/TeamsGroupChatObserver.ts index 554a27f9ca7a0..c4f455cde6314 100644 --- a/apps/discord-bot/src/features/TeamsGroupChatObserver.ts +++ b/apps/discord-bot/src/features/TeamsGroupChatObserver.ts @@ -27,6 +27,7 @@ import { groupChatMirrorsFile, planTeamsGroupChat, groupChatThreadName, + groupChatT3ThreadTitle, readGroupChatMirror, rememberGroupChatMirror, teamsChannelThreadId, @@ -35,7 +36,7 @@ import { type GroupChatPlan, type GroupChatRule, } from "../teams/groupChats.ts"; -import { weeklyThreadKey } from "../teams/weeklyThreads.ts"; +import { teamsWeekBucket, weeklyThreadKey } from "../teams/weeklyThreads.ts"; import { formatOmegentLinkMarker } from "./linkMarker.ts"; import { startOrContinueT3Turn } from "./LinkedTurnRouter.ts"; @@ -130,6 +131,14 @@ function knownAlertThread(threadsFile: string, sourceKey: string, existing: Thre return readGroupChatMirror(threadsFile, sourceKey); } +/** Parent channel for a new weekly Discord thread: the chat's own, else the alerts channel. */ +function groupChatDiscordChannel( + config: DiscordBotConfig, + chat: Extract["chat"], +): string | undefined { + return chat.discordChannelId ?? config.alertsChannelId; +} + const ensureAlertThread = Effect.fn("ensureAlertThread")(function* ( runtime: Context.Context, config: DiscordBotConfig, @@ -147,7 +156,7 @@ const ensureAlertThread = Effect.fn("ensureAlertThread")(function* ( }); return null; } - const alertsChannelId = config.alertsChannelId; + const alertsChannelId = groupChatDiscordChannel(config, chat); if (alertsChannelId === undefined || alertsChannelId.length === 0) { yield* Effect.logError( "DISCORD_ALERTS_CHANNEL_ID is unset; the Teams group chat continues without Discord", @@ -221,14 +230,23 @@ const attachAlertThread = Effect.fn("attachAlertThread")(function* ( // Left as is, the next message retries the attach. if (posted === null) return; if (link.discordThreadId !== discordThreadId) { + const channelId = groupChatDiscordChannel(config, chat); yield* links.rekey(link.discordThreadId, { discordThreadId, - ...(config.alertsChannelId === undefined ? {} : { channelId: config.alertsChannelId }), + ...(channelId === undefined ? {} : { channelId }), }); } yield* links.setInfoDiscordMessageId(discordThreadId, posted); }); +export interface TeamsMirrorTurn { + readonly mirror: GroupChatMirror; + readonly conversationId: string; + readonly sourceKey: string; + readonly t3ThreadId: ThreadId; + readonly messageId: string; +} + export interface TeamsChannelPoster { openThread(input: { readonly mirror: GroupChatMirror; @@ -308,6 +326,44 @@ const copyToChannelThread = Effect.fn("copyToChannelThread")(function* ( return { created: savedId === null, conversationId: openedId }; }); +/** + * The weekly link is keyed by its Discord thread, so a Teams mirror thread gets its own delivery + * link. Bridge state (info card, stream tips, delivered answers) then stays per conversation. + */ +export const ensureTeamsMirrorLink = Effect.fn("ensureTeamsMirrorLink")(function* (input: { + readonly conversationId: string; + readonly sourceKey: string; + readonly t3ThreadId: ThreadId; +}) { + const links = yield* ThreadLinkStore; + const current = yield* links.getByDiscordThreadId(input.conversationId); + if (current !== null && current.t3ThreadId === input.t3ThreadId) return; + const weekly = yield* links.getBySourceThread("teams", input.sourceKey); + if (weekly === null || weekly.t3ThreadId !== input.t3ThreadId) return; + // An answer finished before this link existed was not meant for this thread; don't replay it. + const t3 = yield* T3Session; + const snapshot = yield* t3 + .fetchThreadDetail(input.t3ThreadId) + .pipe(Effect.orElseSucceed(() => null)); + const latest = snapshot?.thread.latestTurn; + yield* links.put({ + sourceKind: "teams", + sourceThreadId: `${input.sourceKey}#teams-mirror`, + discordThreadId: input.conversationId, + t3ThreadId: input.t3ThreadId, + projectId: weekly.projectId, + channelId: "", + guildId: "", + createdAt: DateTime.formatIso(yield* DateTime.now), + ...(latest?.state === "completed" + ? { + lastSeenTurnId: latest.turnId, + lastFinalizedAssistantId: latest.assistantMessageId, + } + : {}), + }); +}); + const runGroupChatCommand = Effect.fn("runGroupChatCommand")(function* ( runtime: Context.Context, discordThreadId: string, @@ -379,10 +435,13 @@ export const ingestTeamsGroupChat = Effect.fn("ingestTeamsGroupChat")(function* options?: { readonly builtinScanner?: boolean; readonly builtinMirror?: GroupChatMirror; + readonly builtinDiscordChannelId?: string; readonly hasImages?: boolean; readonly attachments?: ReadonlyArray; readonly attachmentNote?: string; readonly t3RetrySchedule?: Schedule.Schedule; + /** Streams the weekly T3 thread's output into its Teams mirror thread, as a mention would. */ + readonly bridgeMirror?: (input: TeamsMirrorTurn) => Effect.Effect; }, ) { const access = @@ -409,6 +468,9 @@ export const ingestTeamsGroupChat = Effect.fn("ingestTeamsGroupChat")(function* mentionedBot: activity.mentionedBot, ...(options?.builtinScanner === undefined ? {} : { builtinScanner: options.builtinScanner }), ...(options?.builtinMirror === undefined ? {} : { builtinMirror: options.builtinMirror }), + ...(options?.builtinDiscordChannelId === undefined + ? {} + : { builtinDiscordChannelId: options.builtinDiscordChannelId }), ...(activity.messageId === undefined ? {} : { messageId: activity.messageId }), ...(activity.author === undefined ? {} : { author: activity.author }), ...(options?.hasImages === true ? { hasImages: true } : {}), @@ -426,7 +488,8 @@ export const ingestTeamsGroupChat = Effect.fn("ingestTeamsGroupChat")(function* } // 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 now = DateTime.toDateUtc(yield* DateTime.now); + const sourceKey = weeklyThreadKey(plan.sourceKey, now); const links = yield* ThreadLinkStore; const existing = yield* links.getBySourceThread("teams", sourceKey); const mirrorsFile = groupChatMirrorsFile(config.dataDir); @@ -510,6 +573,7 @@ export const ingestTeamsGroupChat = Effect.fn("ingestTeamsGroupChat")(function* externalTenantId: existing?.guildId ?? "", projectShortName: plan.chat.projectShortName, prompt, + title: groupChatT3ThreadTitle(plan.chat.title, teamsWeekBucket(now)), flags: {}, stickyModelOnContinue: true, ...(options?.attachments !== undefined && options.attachments.length > 0 @@ -559,5 +623,22 @@ export const ingestTeamsGroupChat = Effect.fn("ingestTeamsGroupChat")(function* ), ); } + const bridgeMirror = options?.bridgeMirror; + if (bridgeMirror !== undefined && plan.chat.mirror !== null && channelThread.conversationId) { + yield* bridgeMirror({ + mirror: plan.chat.mirror, + conversationId: channelThread.conversationId, + sourceKey, + t3ThreadId, + messageId: turn.messageId, + }).pipe( + Effect.catchCause((cause) => + Effect.logError("Could not stream T3 output to the Teams channel thread", { + sourceKey, + cause: Cause.pretty(cause), + }), + ), + ); + } return { handled: true as const }; }); diff --git a/apps/discord-bot/src/teams-gateway-main.ts b/apps/discord-bot/src/teams-gateway-main.ts index fe7cddb8125a2..f0724cfc2c4a7 100644 --- a/apps/discord-bot/src/teams-gateway-main.ts +++ b/apps/discord-bot/src/teams-gateway-main.ts @@ -24,7 +24,10 @@ import { bridgeThreadToPlatform, runBridge } from "./features/ResponseBridge.ts" import { layer as bridgeHubLayer } from "./features/BridgeHub.ts"; import { BotResponseTransport } from "./features/BotResponseTransport.ts"; import { layer as warmCacheLayer } from "./store/ThreadWarmCacheStore.ts"; -import { makeTeamsResponseTransport } from "./teams/ResponseTransport.ts"; +import { + makeTeamsResponseTransport, + type TeamsResponseActivity, +} from "./teams/ResponseTransport.ts"; import { IdentityMapStore, layerFromOptionalPath as identityMapLayer } from "./identityMap.ts"; import { layerFromOptionalPath as aliasesLayer } from "./projectAliases.ts"; import { ThreadLinkStore, layer as linksLayer } from "./store/ThreadLinkStore.ts"; @@ -54,7 +57,12 @@ import { type GraphChatMessage, type GraphNotificationBatch, } from "./teams/graphNotifications.ts"; -import { ingestTeamsGroupChat, teamsChannelPoster } from "./features/TeamsGroupChatObserver.ts"; +import { + ensureTeamsMirrorLink, + ingestTeamsGroupChat, + teamsChannelPoster, + type TeamsMirrorTurn, +} from "./features/TeamsGroupChatObserver.ts"; import { mentionsTeamsRecipient, registerTeamsMessageEvents } from "./teams/messageEvents.ts"; import { TeamsGatewayDispatcher } from "./teams/gatewayDispatcher.ts"; import { @@ -242,6 +250,48 @@ const program = Effect.gen(function* () { throw new Error("Teams binding was revoked or changed"); return workspaces.get(lease.binding.workspace)!; }; + const transportFor = ( + lease: GatewayLease, + rootMessageId: string, + send: (wire: TeamsResponseActivity) => Promise<{ id?: string }>, + deleteMessage: (id: string) => Promise, + ) => + makeTeamsResponseTransport({ + config: active(lease).config, + clientId: initial.identity.entraClientId, + tenantId: lease.binding.tenantId, + clientSecret: readPrivateCredential(secretPath), + teamId: lease.binding.teamId, + channelId: lease.binding.channelId, + fileDestination: lease.binding.fileDestination, + includeProgressHistory: lease.binding.includeProgressHistory, + getChannelTopic: () => channelTopic(lease), + conversationId: lease.conversationId, + rootMessageId, + assertActive: () => { + active(lease); + }, + send, + deleteMessage, + }); + // Turn-less delivery (restored or group-chat mirror bridges) posts with the bot's own envelope. + const restoredTransport = (lease: GatewayLease, serviceUrl: string, rootMessageId: string) => { + const api = new ApiClient(serviceUrl, app.api.http); + const sendRestored = restoredTeamsSender({ + conversations: api.conversations, + conversationId: lease.conversationId, + botId: "28:" + initial.identity.entraClientId, + }); + return transportFor( + lease, + rootMessageId, + (wire) => { + active(lease); + return sendRestored(wire); + }, + (id) => api.conversations.deleteActivity(lease.conversationId, id), + ); + }; // A mention in a group-chat mirror thread continues that chat's weekly T3 thread. const channelSourceKey = (lease: GatewayLease, dataDir: string) => teamsChannelSourceKey({ @@ -314,24 +364,16 @@ const program = Effect.gen(function* () { stickyModelOnContinue: true, promptContext: { kind: "raw", value: "Authorized Teams request: Continue" }, }); - const transport = makeTeamsResponseTransport({ - config: workspace.config, - clientId: initial.identity.entraClientId, - tenantId: lease.binding.tenantId, - clientSecret: readPrivateCredential(secretPath), - teamId: lease.binding.teamId, - channelId: lease.binding.channelId, - fileDestination: lease.binding.fileDestination, - includeProgressHistory: lease.binding.includeProgressHistory, - getChannelTopic: () => channelTopic(lease), + const transport = transportFor( + lease, + lease.conversationId.split(";messageid=")[1] ?? activity.replyToId ?? activity.id, + (wire) => send(wire), + (id) => api.conversations.deleteActivity(lease.conversationId, id), + ); + yield* ensureTeamsMirrorLink({ conversationId: lease.conversationId, - rootMessageId: - lease.conversationId.split(";messageid=")[1] ?? activity.replyToId ?? activity.id, - assertActive: () => { - active(lease); - }, - send: (wire) => send(wire), - deleteMessage: (id) => api.conversations.deleteActivity(lease.conversationId, id), + sourceKey, + t3ThreadId: turn.threadId, }); yield* bridgeThreadToPlatform({ conversationId: lease.conversationId, @@ -506,9 +548,14 @@ const program = Effect.gen(function* () { ...(handled.builtinMirror === undefined ? {} : { builtinMirror: handled.builtinMirror }), + ...(handled.builtinDiscordChannelId === undefined + ? {} + : { builtinDiscordChannelId: handled.builtinDiscordChannelId }), ...(images.uploads.length > 0 || images.note.length > 0 ? { hasImages: true } : {}), ...(images.uploads.length > 0 ? { attachments: images.uploads } : {}), ...(images.note.length > 0 ? { attachmentNote: images.note } : {}), + bridgeMirror: (turn) => + Effect.tryPromise(() => bridgeGroupChatMirror(handled.workspaceId, api, turn)), }, ); }), @@ -520,6 +567,37 @@ const program = Effect.gen(function* () { }); }; + // Same delivery as after a mention in the mirror thread, without one: the gateway started this + // weekly T3 thread itself, so only its output is delivered; nothing new is authorized. + const bridgeGroupChatMirror = async ( + workspaceId: string, + api: Parameters[0], + turn: TeamsMirrorTurn, + ) => { + const lease = policy.mirrorLease(workspaceId, turn.mirror, turn.conversationId); + if (lease === null) { + log("warning", "No active channel binding for the Teams group chat mirror", { + workspaceId, + channelId: turn.mirror.channelId, + }); + return; + } + const workspace = active(lease); + const rootMessageId = turn.conversationId.split(";messageid=")[1]!; + references.remember(lease, api.serviceUrl, rootMessageId); + const transport = restoredTransport(lease, api.serviceUrl, rootMessageId); + await workspace.runtime.runPromise( + Effect.gen(function* () { + yield* ensureTeamsMirrorLink(turn); + yield* bridgeThreadToPlatform({ + conversationId: turn.conversationId, + threadId: turn.t3ThreadId, + sentUserMessageIds: [turn.messageId], + }).pipe(Effect.provideService(BotResponseTransport, transport)); + }), + ); + }; + // Graph work per chat runs in arrival order, so reads cannot overtake each other. const graphQueue = new KeyedSerialQueue(); const ingestGraphMessage = async (chatId: string, message: GraphChatMessage) => { @@ -733,24 +811,16 @@ const program = Effect.gen(function* () { ...(images.uploads.length > 0 ? { attachments: images.uploads } : {}), promptContext: { kind: "raw", value: enriched }, }); - const transport = makeTeamsResponseTransport({ - config: workspace.config, - clientId: initial.identity.entraClientId, - tenantId: lease.binding.tenantId, - clientSecret: readPrivateCredential(secretPath), - teamId: lease.binding.teamId, - channelId: lease.binding.channelId, - fileDestination: lease.binding.fileDestination, - includeProgressHistory: lease.binding.includeProgressHistory, - getChannelTopic: () => channelTopic(lease), + const transport = transportFor( + lease, + lease.conversationId.split(";messageid=")[1] ?? activity.replyToId ?? activity.id, + (wire) => send(wire), + (id) => api.conversations.deleteActivity(lease.conversationId, id), + ); + yield* ensureTeamsMirrorLink({ conversationId: lease.conversationId, - rootMessageId: - lease.conversationId.split(";messageid=")[1] ?? activity.replyToId ?? activity.id, - assertActive: () => { - active(lease); - }, - send: (wire) => send(wire), - deleteMessage: (id) => api.conversations.deleteActivity(lease.conversationId, id), + sourceKey, + t3ThreadId: turn.threadId, }); yield* bridgeThreadToPlatform({ conversationId: lease.conversationId, @@ -825,45 +895,12 @@ const program = Effect.gen(function* () { for (const reference of references.restore(initial, (lease) => policy.isActive(lease))) { const { lease } = reference; const workspace = active(lease); - const api = new ApiClient(reference.serviceUrl, app.api.http); - const sendRestored = restoredTeamsSender({ - conversations: api.conversations, - conversationId: lease.conversationId, - botId: "28:" + initial.identity.entraClientId, - }); - const transport = makeTeamsResponseTransport({ - config: workspace.config, - clientId: initial.identity.entraClientId, - tenantId: lease.binding.tenantId, - clientSecret: readPrivateCredential(secretPath), - teamId: lease.binding.teamId, - channelId: lease.binding.channelId, - fileDestination: lease.binding.fileDestination, - includeProgressHistory: lease.binding.includeProgressHistory, - getChannelTopic: () => channelTopic(lease), - conversationId: lease.conversationId, - rootMessageId: reference.rootMessageId, - assertActive: () => { - active(lease); - }, - send: (wire) => { - active(lease); - return sendRestored(wire); - }, - deleteMessage: (id) => api.conversations.deleteActivity(lease.conversationId, id), - }); + const transport = restoredTransport(lease, reference.serviceUrl, reference.rootMessageId); workspace.runtime.runFork( Effect.gen(function* () { const links = yield* ThreadLinkStore; - const sourceKey = - "native/" + - [ - lease.binding.tenantId, - lease.binding.teamId, - lease.binding.channelId, - lease.conversationId, - ].join("/"); - const link = yield* links.getBySourceThread("teams", sourceKey); + // Keyed by conversation: native channel threads and group-chat mirror threads alike. + const link = yield* links.getByDiscordThreadId(lease.conversationId); if (link === null) return; const session = yield* T3Session; // Startup connection runs in another fiber; rehydration must not subscribe before it is ready. diff --git a/apps/discord-bot/src/teams/ResponseTransport.test.ts b/apps/discord-bot/src/teams/ResponseTransport.test.ts index 46369e85bf57e..bbca37d9f9de2 100644 --- a/apps/discord-bot/src/teams/ResponseTransport.test.ts +++ b/apps/discord-bot/src/teams/ResponseTransport.test.ts @@ -25,6 +25,7 @@ import { type TeamsResponseActivity, } from "./ResponseTransport.ts"; import { restoredTeamsSender } from "./responseReferences.ts"; +import { ensureTeamsMirrorLink } from "../features/TeamsGroupChatObserver.ts"; const options = { clientId: "bot", @@ -166,6 +167,66 @@ describe("Teams response adapter", () => { expect(send.mock.calls[3]?.[0].text).toContain("/worktrees/c"); }), ); + it.effect("posts one thread-info card in a group-chat mirror thread across activations", () => + Effect.gen(function* () { + const config = yield* DiscordBotConfig.pipe( + Effect.provide( + ConfigProvider.layer( + ConfigProvider.fromEnvRecord({ T3_DISCORD_BOT_DATA_DIR: directory }), + ), + ), + ); + const links = yield* makeThreadLinkStore(directory); + const sourceKey = "native/tenant/group/19:chat@thread.v2/week-2026-11-23"; + const t3ThreadId = ThreadId.make("weekly-thread"); + // The weekly link belongs to the Discord thread; the mirror thread has none of its own yet. + yield* links.put({ + sourceKind: "teams", + sourceThreadId: sourceKey, + discordThreadId: "1400000000000000000", + t3ThreadId, + projectId: ProjectId.make("scanner"), + channelId: "900", + guildId: "", + infoDiscordMessageId: "discord-marker", + createdAt: "2026-11-23T10:00:00.000Z", + }); + const send = vi + .fn<(wire: TeamsResponseActivity) => Promise<{ id: string }>>() + .mockResolvedValue({ id: "info" }); + const session = { + fetchThreadDetail: () => Effect.succeed(null), + } as unknown as T3SessionService; + // A group-chat turn, then a mention in the mirror thread, each activate the bridge. + for (let activation = 0; activation < 2; activation += 1) { + yield* ensureTeamsMirrorLink({ + conversationId: options.conversationId, + sourceKey, + t3ThreadId, + }).pipe( + Effect.andThen( + makeTeamsResponseTransport({ ...options, config, send }).upsertThreadInfo({ + config, + conversationId: options.conversationId, + threadId: t3ThreadId, + modelSelection: { instanceId: "grok", model: "grok-4.7" }, + }), + ), + Effect.provideService(ThreadLinkStore, links), + Effect.provideService(ProjectAliasStore, makeProjectAliasStore([])), + Effect.provideService(T3Session, session), + ); + } + expect(send).toHaveBeenCalledTimes(1); + expect( + (yield* links.getByDiscordThreadId(options.conversationId))?.infoDiscordMessageId, + ).toBe("info"); + // The Discord marker id on the weekly link is untouched. + expect((yield* links.getBySourceThread("teams", sourceKey))?.infoDiscordMessageId).toBe( + "discord-marker", + ); + }), + ); it("sends restored edits with the same bot envelope as creates", async () => { const createActivity = vi.fn(async () => ({ id: "created" })); const updateActivity = vi.fn(async () => ({})); diff --git a/apps/discord-bot/src/teams/gatewayConfig.ts b/apps/discord-bot/src/teams/gatewayConfig.ts index ef6f04f460cd5..487b9468b287f 100644 --- a/apps/discord-bot/src/teams/gatewayConfig.ts +++ b/apps/discord-bot/src/teams/gatewayConfig.ts @@ -13,6 +13,8 @@ const GatewayGroupChatRule = Schema.Struct({ mirrorTenantId: Schema.optional(Schema.String), mirrorTeamId: Schema.optional(Schema.String), mirrorChannelId: Schema.optional(Schema.String), + title: Schema.optional(Schema.String), + discordChannelId: Schema.optional(Schema.String), passive: Schema.optional(Schema.Boolean), }); const Workspace = Schema.Struct({ @@ -31,6 +33,7 @@ const Workspace = Schema.Struct({ scannerMirrorTenantId: Schema.optional(Schema.String), scannerMirrorTeamId: Schema.optional(Schema.String), scannerMirrorChannelId: Schema.optional(Schema.String), + scannerDiscordChannelId: Schema.optional(Schema.String), groupChats: Schema.optional(Schema.Array(GatewayGroupChatRule)), }); const Binding = Schema.Struct({ diff --git a/apps/discord-bot/src/teams/gatewayPolicy.test.ts b/apps/discord-bot/src/teams/gatewayPolicy.test.ts index 8b1931cb6bd62..7541721dc2053 100644 --- a/apps/discord-bot/src/teams/gatewayPolicy.test.ts +++ b/apps/discord-bot/src/teams/gatewayPolicy.test.ts @@ -8,7 +8,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test" import { parseGatewayConfig, type TeamsGatewayConfig } from "./gatewayConfig.ts"; import { TeamsGatewayDispatcher, type MentionDecision } from "./gatewayDispatcher.ts"; import { TeamsResponseReferences } from "./responseReferences.ts"; -import { TeamsGatewayPolicy, safeTeamsServiceUrl, type GatewayActivity } from "./gatewayPolicy.ts"; +import { + GROUP_CHAT_MIRROR_ACTOR, + TeamsGatewayPolicy, + safeTeamsServiceUrl, + type GatewayActivity, +} from "./gatewayPolicy.ts"; const appId = "11111111-1111-4111-8111-111111111111"; const tenant = "22222222-2222-4222-8222-222222222222"; @@ -269,6 +274,38 @@ describe("shared Teams gateway", () => { references.remember(decision.lease, "https://attacker.invalid/", "root"), ).toThrow(); }); + it("gives a group-chat mirror thread a delivery lease that shares the mention's reference", () => { + const mirror = { tenantId: tenant, teamId: team, channelId: "channel-alpha" }; + const thread = "channel-alpha;messageid=77"; + const lease = policy.mirrorLease("alpha", mirror, thread); + expect(lease?.actorId).toBe(GROUP_CHAT_MIRROR_ACTOR); + expect(lease?.binding.id).toBe("alpha"); + expect(policy.mirrorLease("beta", mirror, thread)).toBeNull(); + expect(policy.mirrorLease("alpha", mirror, "channel-beta;messageid=77")).toBeNull(); + expect(policy.mirrorLease("alpha", mirror, "conversation-alpha")).toBeNull(); + + const mention = policy.accept(activity({ conversation: { id: thread, tenantId: tenant } })); + expect(mention.kind).toBe("mention"); + if (mention.kind !== "mention" || lease === null) return; + expect(mention.lease.key).toBe(lease.key); + const references = new TeamsResponseReferences(directory); + references.remember(lease, "https://smba.trafficmanager.net/emea/", "77"); + references.remember(mention.lease, "https://smba.trafficmanager.net/emea/", "77"); + expect( + new TeamsResponseReferences(directory).restore(config, (l) => policy.isActive(l)), + ).toHaveLength(1); + + // The delivery actor never authorizes intake, and the lease ends with its binding. + expect( + policy.accept(activity({ from: { id: "x", aadObjectId: GROUP_CHAT_MIRROR_ACTOR } })).kind, + ).toBe("reject"); + config = { + ...config, + bindings: config.bindings.map((binding) => ({ ...binding, enabled: false })), + }; + expect(policy.isActive(lease)).toBe(false); + expect(policy.mirrorLease("alpha", mirror, thread)).toBeNull(); + }); it("authorizes card invokes through the same envelope and actor policy without a mention", () => { const invoke = activity({ type: "invoke", entities: [] }); expect(policy.authorizeAction(invoke)?.actorId).toBe(actor); diff --git a/apps/discord-bot/src/teams/gatewayPolicy.ts b/apps/discord-bot/src/teams/gatewayPolicy.ts index e8a52af8ded30..18985002a533f 100644 --- a/apps/discord-bot/src/teams/gatewayPolicy.ts +++ b/apps/discord-bot/src/teams/gatewayPolicy.ts @@ -68,6 +68,7 @@ export type GroupChatIntake = readonly rules: ReadonlyArray; readonly builtinScanner: boolean; readonly builtinMirror?: GroupChatMirror; + readonly builtinDiscordChannelId?: string; }; const digest = (value: unknown) => @@ -75,6 +76,11 @@ const digest = (value: unknown) => const teamKey = (tenant: string, team: string) => digest([tenant, team]); const fingerprint = (config: TeamsGatewayConfig, binding: TeamsGatewayBinding) => digest([config.identity, binding, config.workspaces[binding.workspace]]); +// Same key for every actor in one conversation, so one response reference per conversation. +const leaseKey = (config: TeamsGatewayConfig, binding: TeamsGatewayBinding, conversation: string) => + digest([binding.workspace, binding.id, fingerprint(config, binding), conversation]); +/** Not an Entra object id (bindings only allow UUID actors), so no activity can carry it. */ +export const GROUP_CHAT_MIRROR_ACTOR = "system:group-chat-mirror"; const botId = (value: string | undefined) => value?.replace(/^28:/u, "").toLowerCase(); // Bot activities use a conversation ID in team.id; bindings use the Entra group ID. const matchesTeam = (binding: TeamsGatewayBinding, activity: GatewayActivity) => { @@ -215,14 +221,52 @@ export class TeamsGatewayPolicy { config.workspaces[current.workspace]?.enabled === true && !this.revoked.has(teamKey(current.tenantId, current.teamId)) && fingerprint(config, current) === lease.fingerprint && - this.identityAllowed(current.workspace, lease.actorId) && - current.allowedActorIds.some((id) => id.toLowerCase() === lease.actorId) + (lease.actorId === GROUP_CHAT_MIRROR_ACTOR || + (this.identityAllowed(current.workspace, lease.actorId) && + current.allowedActorIds.some((id) => id.toLowerCase() === lease.actorId))) ); } catch { return false; } } + /** + * Delivery-only lease for a group-chat mirror thread, so T3 output for the weekly thread the + * gateway started reaches it without a mention. It never authorizes intake or card actions: + * those always build their lease from the authenticated actor in `accept`. + */ + mirrorLease( + workspace: string, + mirror: GroupChatMirror, + conversationId: string, + ): GatewayLease | null { + let config: TeamsGatewayConfig; + try { + config = this.config(); + } catch { + return null; + } + if (!conversationId.startsWith(`${mirror.channelId};messageid=`)) return null; + const matches = config.bindings.filter( + (binding) => + binding.enabled && + binding.workspace === workspace && + binding.tenantId.toLowerCase() === mirror.tenantId.toLowerCase() && + binding.teamId.toLowerCase() === mirror.teamId.toLowerCase() && + binding.channelId === mirror.channelId, + ); + if (matches.length !== 1) return null; + const binding = matches[0]!; + const lease: GatewayLease = { + binding, + fingerprint: fingerprint(config, binding), + actorId: GROUP_CHAT_MIRROR_ACTOR, + conversationId, + key: leaseKey(config, binding, conversationId), + }; + return this.isActive(lease) ? lease : null; + } + /** Uninstall revokes delivery even when the installer is not an authorized work actor. */ revoke(activity: GatewayActivity): void { if (activity.channelId !== "msteams" || !safeTeamsServiceUrl(activity.serviceUrl)) return; @@ -357,6 +401,9 @@ export class TeamsGatewayPolicy { rules: target.rules, builtinScanner: target.scannerGroupChats, ...(target.builtinMirror === undefined ? {} : { builtinMirror: target.builtinMirror }), + ...(target.builtinDiscordChannelId === undefined + ? {} + : { builtinDiscordChannelId: target.builtinDiscordChannelId }), }; } @@ -407,12 +454,7 @@ export class TeamsGatewayPolicy { fingerprint: fingerprint(config, binding), actorId, conversationId: activity.conversation.id, - key: digest([ - binding.workspace, - binding.id, - fingerprint(config, binding), - activity.conversation.id, - ]), + key: leaseKey(config, binding, activity.conversation.id), }; if (!this.isActive(lease)) return reject("revoked-binding"); // Expired receipts cannot be replayed because their activity timestamp is now too old. diff --git a/apps/discord-bot/src/teams/groupChats.test.ts b/apps/discord-bot/src/teams/groupChats.test.ts index 51d1561106300..8266ce46dd1e6 100644 --- a/apps/discord-bot/src/teams/groupChats.test.ts +++ b/apps/discord-bot/src/teams/groupChats.test.ts @@ -11,6 +11,8 @@ import { groupChatMirrorsFile, groupChatSourceKey, groupChatSpeaksInTeams, + groupChatT3ThreadTitle, + groupChatWorkspaceTarget, readGroupChatMirror, rememberGroupChatMirror, SCANNER_GROUP_CHAT_MIRROR, @@ -444,3 +446,75 @@ describe("loadGroupChatRulesFromFileSync", () => { expect(loadGroupChatRulesFromFileSync(filePath)).toEqual([]); }); }); + +describe("group chat display names and Discord channels", () => { + const workspace = (groupChats: ReadonlyArray, extra = {}) => + groupChatWorkspaceTarget("alpha", { groupChats, ...extra }); + + it("parses a rule title and Discord channel, and rejects bad values", () => { + expect( + workspace([ + { + conversationId: "19:chat@thread.v2", + projectShortName: "macs-scanner", + title: " Easy Life Scanner ", + discordChannelId: "1345512665602330664", + }, + ]).rules, + ).toEqual([ + { + conversationId: "19:chat@thread.v2", + projectShortName: "macs-scanner", + title: "Easy Life Scanner", + discordChannelId: "1345512665602330664", + }, + ]); + const rule = { conversationId: "19:chat@thread.v2", projectShortName: "macs-scanner" }; + expect(() => workspace([{ ...rule, title: " " }])).toThrow(/title/u); + expect(() => workspace([{ ...rule, title: "x".repeat(101) }])).toThrow(/title/u); + expect(() => workspace([{ ...rule, discordChannelId: "#macs-scanner" }])).toThrow( + /discordChannelId/u, + ); + expect( + workspace([], { scannerGroupChats: true, scannerDiscordChannelId: "1345512665602330664" }) + .builtinDiscordChannelId, + ).toBe("1345512665602330664"); + expect(() => workspace([], { scannerDiscordChannelId: "1345512665602330664" })).toThrow( + /requires scannerGroupChats/u, + ); + }); + + it("prefers the rule title and falls back to the scanner channel default", () => { + const pinned = resolveGroupChat({ + title: "Teams group chat", + conversationId: "19:chat@thread.v2", + rules: [ + { + conversationId: "19:chat@thread.v2", + projectShortName: "macs-scanner", + title: "Easy Life Scanner", + }, + ], + }); + expect(pinned).toMatchObject({ title: "Easy Life Scanner", discordChannelId: null }); + const builtin = resolveGroupChat({ + title: "MAKO Scanner", + conversationId: "19:other@thread.v2", + rules: [], + builtinDiscordChannelId: "1345512665602330664", + }); + expect(builtin).toMatchObject({ + title: "MAKO Scanner", + discordChannelId: "1345512665602330664", + }); + }); + + it("keeps the week in a shortened T3 title", () => { + expect(groupChatT3ThreadTitle("MAKO Scanner", "week-2026-11-23")).toBe( + "Teams: MAKO Scanner · week 2026-11-23", + ); + const long = groupChatT3ThreadTitle("x".repeat(200), "week-2026-11-23"); + expect(long.length).toBeLessThanOrEqual(72); + expect(long.endsWith("… · week 2026-11-23")).toBe(true); + }); +}); diff --git a/apps/discord-bot/src/teams/groupChats.ts b/apps/discord-bot/src/teams/groupChats.ts index 4771f695e9ee0..8d4957231b17e 100644 --- a/apps/discord-bot/src/teams/groupChats.ts +++ b/apps/discord-bot/src/teams/groupChats.ts @@ -25,6 +25,10 @@ export interface GroupChatRule { readonly titleIncludes?: string | undefined; readonly projectShortName: string; readonly mirror?: GroupChatMirror | undefined; + /** Display name. Teams often omits chat titles, and Graph may not be allowed to read them. */ + readonly title?: string | undefined; + /** Discord channel for this chat's weekly threads, instead of the alerts channel. */ + readonly discordChannelId?: string | undefined; } interface ResolvedGroupChat { @@ -32,6 +36,7 @@ interface ResolvedGroupChat { readonly passive: true; readonly title: string; readonly mirror: GroupChatMirror | null; + readonly discordChannelId: string | null; } type GroupChatEvent = "message" | "join"; @@ -124,6 +129,17 @@ export function groupChatThreadName(title: string): string { return name.length <= 100 ? name : `${name.slice(0, 99).trimEnd()}…`; } +/** + * Explicit T3 title for the weekly thread. Without it the title is cut from the first prompt, + * which starts with the passive-chat rules, and the Discord thread mirrors that. + */ +export function groupChatT3ThreadTitle(title: string, weekBucket: string): string { + const week = ` · ${weekBucket.replace(/^week-/u, "week ")}`; + const name = groupChatThreadName(title); + const room = 72 - week.length; + return `${name.length <= room ? name : `${name.slice(0, room - 1).trimEnd()}…`}${week}`; +} + export function groupChatSpeaksInTeams(): false { return false; } @@ -157,6 +173,7 @@ export function resolveGroupChat(input: { /** Omitted means the native listener, which keeps the scanner names. */ readonly builtinScanner?: boolean; readonly builtinMirror?: GroupChatMirror; + readonly builtinDiscordChannelId?: string; }): ResolvedGroupChat | null { const title = input.title?.trim(); const displayTitle = title !== undefined && title.length > 0 ? title : undefined; @@ -165,8 +182,9 @@ export function resolveGroupChat(input: { return { projectShortName: rule.projectShortName, passive: true, - title: displayTitle ?? rule.titleIncludes ?? "Teams group chat", + title: rule.title ?? displayTitle ?? rule.titleIncludes ?? "Teams group chat", mirror: mirrorFor(rule.projectShortName, rule.mirror), + discordChannelId: rule.discordChannelId ?? null, }; } if ( @@ -179,6 +197,7 @@ export function resolveGroupChat(input: { passive: true, title: displayTitle, mirror: input.builtinMirror ?? SCANNER_GROUP_CHAT_MIRROR, + discordChannelId: input.builtinDiscordChannelId ?? null, }; } return null; @@ -189,6 +208,7 @@ export interface GroupChatWorkspaceTarget { readonly rules: ReadonlyArray; readonly scannerGroupChats: boolean; readonly builtinMirror?: GroupChatMirror; + readonly builtinDiscordChannelId?: string; } export function groupChatWorkspaceTarget( @@ -198,6 +218,7 @@ export function groupChatWorkspaceTarget( readonly scannerMirrorTenantId?: string | undefined; readonly scannerMirrorTeamId?: string | undefined; readonly scannerMirrorChannelId?: string | undefined; + readonly scannerDiscordChannelId?: string | undefined; readonly groupChats?: ReadonlyArray | undefined; }, ): GroupChatWorkspaceTarget { @@ -213,11 +234,19 @@ export function groupChatWorkspaceTarget( if (builtinMirror !== undefined && workspace.scannerGroupChats !== true) { throw new Error("scannerMirror requires scannerGroupChats"); } + const builtinDiscordChannelId = discordChannelIdField( + workspace.scannerDiscordChannelId, + "scannerDiscordChannelId", + ); + if (builtinDiscordChannelId !== undefined && workspace.scannerGroupChats !== true) { + throw new Error("scannerDiscordChannelId requires scannerGroupChats"); + } return { id, rules, scannerGroupChats: workspace.scannerGroupChats === true, ...(builtinMirror === undefined ? {} : { builtinMirror }), + ...(builtinDiscordChannelId === undefined ? {} : { builtinDiscordChannelId }), }; } @@ -472,6 +501,7 @@ export function planTeamsGroupChat(input: { readonly rules: ReadonlyArray; readonly builtinScanner?: boolean; readonly builtinMirror?: GroupChatMirror; + readonly builtinDiscordChannelId?: string; readonly event: GroupChatEvent; readonly text: string; readonly fromBot: boolean; @@ -497,6 +527,9 @@ export function planTeamsGroupChat(input: { rules: input.rules, ...(input.builtinScanner === undefined ? {} : { builtinScanner: input.builtinScanner }), ...(input.builtinMirror === undefined ? {} : { builtinMirror: input.builtinMirror }), + ...(input.builtinDiscordChannelId === undefined + ? {} + : { builtinDiscordChannelId: input.builtinDiscordChannelId }), }); if (chat === null) return { kind: "unmapped" }; const sourceKey = groupChatSourceKey(input.tenantId, input.conversationId); @@ -582,14 +615,33 @@ function parseGroupChatRule(value: unknown, index: number): GroupChatRule { ); } const mirror = parseGroupChatMirror(value, index); + const title = value.title === undefined ? undefined : optionalTrimmed(value.title); + if (value.title !== undefined && (title === undefined || title.length > 100)) { + throw new Error(`Teams group chat rule #${index + 1} title must be 1 to 100 characters.`); + } + const discordChannelId = discordChannelIdField( + value.discordChannelId, + `Teams group chat rule #${index + 1} discordChannelId`, + ); return { projectShortName, ...(conversationId === undefined ? {} : { conversationId }), ...(titleIncludes === undefined ? {} : { titleIncludes }), ...(mirror === undefined ? {} : { mirror }), + ...(title === undefined ? {} : { title }), + ...(discordChannelId === undefined ? {} : { discordChannelId }), }; } +function discordChannelIdField(value: unknown, label: string): string | undefined { + if (value === undefined) return undefined; + const id = optionalTrimmed(value); + if (id === undefined || !/^\d{17,20}$/u.test(id)) { + throw new Error(`${label} must be a Discord channel id.`); + } + return id; +} + const MIRROR_CHANNEL_ID = /^19:\S+@thread\.tacv2$/u; function optionalTrimmed(value: unknown): string | undefined { diff --git a/apps/discord-bot/src/teams/inboundImages.test.ts b/apps/discord-bot/src/teams/inboundImages.test.ts index 19066a92474b8..4600e90391700 100644 --- a/apps/discord-bot/src/teams/inboundImages.test.ts +++ b/apps/discord-bot/src/teams/inboundImages.test.ts @@ -176,6 +176,57 @@ describe("Teams turn images", () => { expect(result.note).not.toContain("please look into mako prod"); }); + it("does not read the mention in Teams' copy of the message body as attachment text", async () => { + const fetch = vi.fn( + async () => new Response("missing", { status: 404 }), + ); + for (const [plainText, content] of [ + ["do you receive?", '

Omegent do you receive?

'], + ["", '

Omegent

'], + ] as const) { + const result = await loadTeamsTurnImages( + request({ fetch, plainText, attachments: [{ contentType: "text/html", content }] }), + ); + expect(result.note).toBe(""); + expect(result.uploads).toEqual([]); + } + }); + + it("still resolves a quoted reply next to a mention", async () => { + const chat = "19:mako@thread.v2"; + const fetch = vi.fn(async (input) => { + const url = href(input); + if (url.endsWith(`/chats/${encodeURIComponent(chat)}/messages/333`)) { + return Response.json({ + id: "333", + messageType: "message", + createdDateTime: "2026-11-24T08:56:00Z", + from: { user: { displayName: "Jochen" } }, + body: { contentType: "html", content: "

The scanner crashes on login

" }, + }); + } + return new Response("missing", { status: 404 }); + }); + const result = await loadTeamsTurnImages( + request({ + fetch, + messageId: "m1", + location: { kind: "chat", conversationId: chat }, + referencedDetail: "text", + plainText: "look at this", + attachments: [ + { + contentType: "text/html", + content: `
Jochen

The scanner crashes…

Omegent look at this

`, + }, + ], + }), + ); + expect(result.note).toContain("The scanner crashes on login"); + expect(result.note).not.toContain("Quoted Teams attachment text"); + expect(result.note).not.toContain("Omegent"); + }); + it("reports a hosted-content denial and ignores a missing collection", async () => { const denied = vi.fn(async () => new Response("no", { status: 403 })); const deniedResult = await loadTeamsTurnImages(request({ fetch: denied })); diff --git a/apps/discord-bot/src/teams/inboundImages.ts b/apps/discord-bot/src/teams/inboundImages.ts index 26d132c3ff309..2d68a4acd4f88 100644 --- a/apps/discord-bot/src/teams/inboundImages.ts +++ b/apps/discord-bot/src/teams/inboundImages.ts @@ -187,9 +187,11 @@ function quotedAttachmentText( const type = mediaType(attachment.contentType); if (type !== "text/html" && type !== "text/plain") return null; if (typeof attachment.content !== "string") return null; + // Teams copies the message body into an HTML attachment. Its `` mentions are stripped from + // the activity text, so drop them here too or the bot's name reads as attachment text. const text = type === "text/html" - ? htmlToText(attachment.content) + ? htmlToText(attachment.content.replace(/]*>[\s\S]*?<\/at>/giu, " ")) : attachment.content.replace(/\s+/gu, " ").trim(); if (text.length === 0) return null; const plain = plainText.replace(/\s+/gu, " ").trim(); diff --git a/apps/discord-bot/src/teams/weeklyThreads.ts b/apps/discord-bot/src/teams/weeklyThreads.ts index 451dc06d23b0e..509b0592bc6da 100644 --- a/apps/discord-bot/src/teams/weeklyThreads.ts +++ b/apps/discord-bot/src/teams/weeklyThreads.ts @@ -33,3 +33,11 @@ export function teamsWeekBucket(at: Date, timeZone: string = TEAMS_THREAD_WEEK_T export function weeklyThreadKey(locationKey: string, at: Date): string { return `${locationKey}/${teamsWeekBucket(at)}`; } + +/** Weekly group-chat link key (`native//group//week-…`), as opposed to a channel. */ +export function isWeeklyGroupChatSourceKey(sourceThreadId: string | undefined): boolean { + return ( + sourceThreadId !== undefined && + /^native\/[^/]+\/group\/[^/]+\/week-\d{4}-\d{2}-\d{2}$/u.test(sourceThreadId) + ); +}