From 4c03578e44da4614a71ef4aa50184c2fd36e3d73 Mon Sep 17 00:00:00 2001 From: T3 Code PR Stack <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:21:09 +0100 Subject: [PATCH 1/4] feat(teams): new channel posts join the week's thread; group chats roll over weekly A Teams channel reply chain keeps the T3 thread it started on. A new top-level post joins the thread the channel opened this week (Monday 00:00 Europe/Amsterdam) instead of opening one per post, and gets its own link row. Group chats, which have no reply chains, start a fresh thread each week. Co-Authored-By: Claude Opus 5.5 --- .../src/features/LinkedTurnRouter.ts | 37 +++++- .../LinkedTurnRouter.weeklyJoin.test.ts | 118 ++++++++++++++++++ .../src/features/TeamsGroupChatObserver.ts | 29 ++--- .../src/features/TeamsNativeApp.ts | 10 ++ apps/discord-bot/src/teams-gateway-main.ts | 11 ++ .../src/teams/weeklyThreads.test.ts | 98 +++++++++++++++ apps/discord-bot/src/teams/weeklyThreads.ts | 105 ++++++++++++++++ 7 files changed, 390 insertions(+), 18 deletions(-) create mode 100644 apps/discord-bot/src/features/LinkedTurnRouter.weeklyJoin.test.ts create mode 100644 apps/discord-bot/src/teams/weeklyThreads.test.ts create mode 100644 apps/discord-bot/src/teams/weeklyThreads.ts diff --git a/apps/discord-bot/src/features/LinkedTurnRouter.ts b/apps/discord-bot/src/features/LinkedTurnRouter.ts index 885e6f31fb535..2d20ddc2ba7ea 100644 --- a/apps/discord-bot/src/features/LinkedTurnRouter.ts +++ b/apps/discord-bot/src/features/LinkedTurnRouter.ts @@ -1,5 +1,5 @@ // @effect-diagnostics anyUnknownInErrorContext:off missingEffectContext:off globalDate:off globalErrorInEffectFailure:off outdatedApi:off -import type { ClientSourceHint, UploadChatAttachment } from "@t3tools/contracts"; +import type { ClientSourceHint, ThreadId, UploadChatAttachment } from "@t3tools/contracts"; import { DiscordREST } from "dfx"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -76,6 +76,11 @@ export interface TransportNeutralLinkedTurnInput { readonly stickyModelOnContinue?: boolean | undefined; readonly attachments?: ReadonlyArray | undefined; readonly promptContext?: LinkedTurnInput["promptContext"]; + /** + * When this source has no link yet, continue this T3 thread instead of opening one, and link + * the source to it. Ignored when the thread is gone or belongs to another project. + */ + readonly joinT3ThreadId?: string | undefined; } /** Preserve the requester on every dispatch; the server keeps the first thread origin. */ @@ -145,10 +150,26 @@ export const startOrContinueT3Turn = Effect.fn("startOrContinueT3Turn")(function const hasExplicitModelFlags = input.flags.provider !== undefined || input.flags.model !== undefined; const resolved = yield* resolveProjectFromShortName(input.projectShortName); - const existing = yield* links.getBySourceThread( + const linkedSource = yield* links.getBySourceThread( input.source.sourceKind, input.source.sourceThreadId, ); + const joinT3ThreadId = linkedSource === null ? input.joinT3ThreadId : undefined; + const joinable = + joinT3ThreadId === undefined + ? null + : yield* t3 + .fetchThreadDetail(joinT3ThreadId as ThreadId) + .pipe( + Effect.map((snapshot) => + snapshot !== null && snapshot.thread.projectId === resolved.project.id + ? (joinT3ThreadId as ThreadId) + : null, + ), + ); + const existing = + linkedSource ?? + (joinable === null ? null : { t3ThreadId: joinable, projectId: resolved.project.id }); if (existing !== null) { if (input.source.sourceKind === "teams" && existing.projectId !== resolved.project.id) { @@ -185,6 +206,18 @@ export const startOrContinueT3Turn = Effect.fn("startOrContinueT3Turn")(function ...(attachments.length > 0 ? { attachments } : {}), sourceHint, }); + if (linkedSource === null) { + yield* links.put({ + sourceKind: input.source.sourceKind, + sourceThreadId: input.source.sourceThreadId, + discordThreadId: input.externalConversationId, + t3ThreadId: existing.t3ThreadId, + projectId: resolved.project.id, + channelId: input.externalParentId, + guildId: input.externalTenantId, + createdAt: DateTime.formatIso(DateTime.nowUnsafe()), + }); + } return { threadId: existing.t3ThreadId, messageId, isNew: false } as const; } diff --git a/apps/discord-bot/src/features/LinkedTurnRouter.weeklyJoin.test.ts b/apps/discord-bot/src/features/LinkedTurnRouter.weeklyJoin.test.ts new file mode 100644 index 0000000000000..28ccdd7752662 --- /dev/null +++ b/apps/discord-bot/src/features/LinkedTurnRouter.weeklyJoin.test.ts @@ -0,0 +1,118 @@ +// @effect-diagnostics nodeBuiltinImport:off unsafeEffectTypeAssertion:off +import * as NodeFSP from "node:fs/promises"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import { + DEFAULT_SERVER_SETTINGS, + ProjectId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Effect from "effect/Effect"; +import { describe, expect } from "vite-plus/test"; +import { it } from "@effect/vitest"; +import { DiscordBotConfig } from "../config.ts"; +import { makeProjectAliasStore, ProjectAliasStore } from "../projectAliases.ts"; +import { makeThreadLinkStore, ThreadLinkStore } from "../store/ThreadLinkStore.ts"; +import { T3Session, type T3SessionService } from "../t3/T3Session.ts"; +import { startOrContinueT3Turn } from "./LinkedTurnRouter.ts"; + +describe("Teams weekly thread join", () => { + it.effect("links a new reply chain to the week's thread, and keeps old chains on theirs", () => + Effect.gen(function* () { + const directory = yield* Effect.acquireRelease( + Effect.promise(() => NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "teams-week-join-"))), + (path) => Effect.promise(() => NodeFSP.rm(path, { recursive: true, force: true })), + ); + const config = yield* DiscordBotConfig.pipe( + Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnvRecord({}))), + ); + const project = ProjectId.make("project:teams"); + const projects = new Map([ + ["thread:week", project], + ["thread:old-chain", project], + ["thread:other-project", ProjectId.make("project:other")], + ]); + const continued: Array = []; + let launches = 0; + const session = { + findProjectByWorkspaceRoot: () => + Effect.succeed({ + id: project, + workspaceRoot: "/workspace/omega", + defaultModelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok" }, + }), + resolveModelSelection: () => + Effect.succeed({ instanceId: ProviderInstanceId.make("grok"), model: "grok" }), + fetchThreadDetail: (threadId: string) => + Effect.succeed( + projects.has(threadId) ? { thread: { projectId: projects.get(threadId) } } : null, + ), + serverConfig: () => + Effect.succeed({ settings: DEFAULT_SERVER_SETTINGS, newProjectsRoot: "/projects" }), + shell: () => Effect.succeed({ threads: [] }), + startTurnWithWorktree: () => + Effect.sync(() => { + launches += 1; + return { threadId: ThreadId.make(`thread:new-${launches}`), messageId: "m:new" }; + }), + startTurn: (input: Parameters[0]) => + Effect.sync(() => { + continued.push(input.threadId); + return { messageId: `m:${continued.length}` }; + }), + } as unknown as T3SessionService; + + const links = yield* makeThreadLinkStore(directory); + const turn = (chain: string, joinT3ThreadId: string | undefined) => + startOrContinueT3Turn(config, { + source: { sourceKind: "teams", sourceThreadId: `native/t/team/ch/${chain}` }, + joinT3ThreadId, + externalConversationId: chain, + externalParentId: "team/ch", + externalTenantId: "t", + projectShortName: "omega", + prompt: "Investigate", + promptContext: { kind: "raw", value: "Investigate" }, + flags: {}, + stickyModelOnContinue: true, + }).pipe( + Effect.provideService( + ProjectAliasStore, + makeProjectAliasStore([{ shortName: "omega", workspaceRoot: "/workspace/omega" }]), + ), + Effect.provideService(ThreadLinkStore, links), + Effect.provideService(T3Session, session), + ); + + // A new top-level post joins the week's thread and gets its own link to it. + expect(yield* turn("chain-b", "thread:week")).toMatchObject({ + threadId: "thread:week", + isNew: false, + }); + expect( + (yield* links.getBySourceThread("teams", "native/t/team/ch/chain-b"))?.t3ThreadId, + ).toBe("thread:week"); + expect((yield* links.getByDiscordThreadId("chain-b"))?.t3ThreadId).toBe("thread:week"); + + // A reply chain that already has a thread stays on it, whatever the week's thread is. + yield* links.put({ + sourceKind: "teams", + sourceThreadId: "native/t/team/ch/chain-old", + discordThreadId: "chain-old", + t3ThreadId: ThreadId.make("thread:old-chain"), + projectId: project, + channelId: "team/ch", + guildId: "t", + createdAt: "2026-11-02T09:00:00.000Z", + }); + expect((yield* turn("chain-old", "thread:week")).threadId).toBe("thread:old-chain"); + + // A missing or foreign week thread falls back to opening a new one. + expect(yield* turn("chain-c", "thread:gone")).toMatchObject({ isNew: true }); + expect(yield* turn("chain-d", "thread:other-project")).toMatchObject({ isNew: true }); + expect(continued).toEqual(["thread:week", "thread:old-chain"]); + }).pipe(Effect.scoped), + ); +}); 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/features/TeamsNativeApp.ts b/apps/discord-bot/src/features/TeamsNativeApp.ts index 11c8d07f65726..8039fff9e46aa 100644 --- a/apps/discord-bot/src/features/TeamsNativeApp.ts +++ b/apps/discord-bot/src/features/TeamsNativeApp.ts @@ -33,6 +33,7 @@ import { BridgeHub } from "./BridgeHub.ts"; import { ThreadWarmCacheStore } from "../store/ThreadWarmCacheStore.ts"; import { BotResponseTransport } from "./BotResponseTransport.ts"; import { makeTeamsResponseTransport } from "../teams/ResponseTransport.ts"; +import { channelWeek, rememberChannelWeek } from "../teams/weeklyThreads.ts"; interface TeamsConversationCoordinates { readonly tenantId: string; @@ -488,8 +489,16 @@ export const runTeamsNativeApp = Effect.fn("runTeamsNativeApp")(function* ( return; } + const week = channelWeek({ + dataDir: config.dataDir, + tenantId: location.tenantId, + teamId: location.teamId, + channelId: location.channelId, + at: DateTime.toDateUtc(yield* DateTime.now), + }); const turn = yield* startOrContinueT3Turn(config, { source: { sourceKind: "teams", sourceThreadId: sourceKey }, + joinT3ThreadId: week?.joinT3ThreadId, sourceActor: { platformId: activity.from.aadObjectId ?? activity.from.id, displayName: access.person.name, @@ -504,6 +513,7 @@ export const runTeamsNativeApp = Effect.fn("runTeamsNativeApp")(function* ( stickyModelOnContinue: true, promptContext: { kind: "raw", value: prompt }, }); + yield* Effect.promise(() => rememberChannelWeek(week, turn)); const receivedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso)); const transport = makeTeamsResponseTransport({ diff --git a/apps/discord-bot/src/teams-gateway-main.ts b/apps/discord-bot/src/teams-gateway-main.ts index e718b59c1e967..c29c7d0d11b7a 100644 --- a/apps/discord-bot/src/teams-gateway-main.ts +++ b/apps/discord-bot/src/teams-gateway-main.ts @@ -11,6 +11,7 @@ import { BridgeHub } from "./features/BridgeHub.ts"; import { App } from "@microsoft/teams.apps"; import { NodeRuntime } from "@effect/platform-node"; import * as ConfigProvider from "effect/ConfigProvider"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as ManagedRuntime from "effect/ManagedRuntime"; @@ -30,6 +31,7 @@ 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 { channelWeek, rememberChannelWeek } from "./teams/weeklyThreads.ts"; import { readGatewayConfig, readPrivateCredential } from "./teams/gatewayConfig.ts"; import { ingestTeamsGroupChat, teamsChannelPoster } from "./features/TeamsGroupChatObserver.ts"; import { mentionsTeamsRecipient, registerTeamsMessageEvents } from "./teams/messageEvents.ts"; @@ -546,8 +548,16 @@ const program = Effect.gen(function* () { ] .filter((part) => part.trim().length > 0) .join("\n\n"); + const week = channelWeek({ + dataDir: workspace.config.dataDir, + tenantId: lease.binding.tenantId, + teamId: lease.binding.teamId, + channelId: lease.binding.channelId, + at: DateTime.toDateUtc(yield* DateTime.now), + }); const turn = yield* startOrContinueT3Turn(workspace.config, { source: { sourceKind: "teams", sourceThreadId: sourceKey }, + joinT3ThreadId: week?.joinT3ThreadId, sourceActor: { platformId: lease.actorId }, externalConversationId: lease.conversationId, externalParentId: lease.binding.teamId + "/" + lease.binding.channelId, @@ -560,6 +570,7 @@ const program = Effect.gen(function* () { ...(images.uploads.length > 0 ? { attachments: images.uploads } : {}), promptContext: { kind: "raw", value: enriched }, }); + yield* Effect.promise(() => rememberChannelWeek(week, turn)); const transport = makeTeamsResponseTransport({ config: workspace.config, clientId: initial.identity.entraClientId, 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..295727bef1498 --- /dev/null +++ b/apps/discord-bot/src/teams/weeklyThreads.test.ts @@ -0,0 +1,98 @@ +// @effect-diagnostics nodeBuiltinImport:off globalDate:off +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import { afterEach, describe, expect, it } from "vite-plus/test"; + +import { + channelWeek, + rememberChannelWeek, + 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 location 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", + ); + }); +}); + +describe("channelWeek", () => { + const dirs: Array = []; + const dataDir = () => { + const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "teams-weekly-")); + dirs.push(dir); + return dir; + }; + afterEach(() => { + for (const dir of dirs.splice(0)) NodeFS.rmSync(dir, { recursive: true, force: true }); + }); + const at = new Date("2026-11-24T09:00:00Z"); + const channel = { tenantId: "t", teamId: "team", channelId: "ch" }; + + it("does not apply outside channels", () => { + expect( + channelWeek({ + dataDir: dataDir(), + tenantId: "t", + teamId: undefined, + channelId: undefined, + at, + }), + ).toBeNull(); + }); + + it("lets later reply chains join the thread the first chain opened this week", async () => { + const dir = dataDir(); + const first = channelWeek({ dataDir: dir, ...channel, at }); + expect(first?.joinT3ThreadId).toBeUndefined(); + await rememberChannelWeek(first, { threadId: "thread-1", isNew: true }); + + expect(channelWeek({ dataDir: dir, ...channel, at })?.joinT3ThreadId).toBe("thread-1"); + // A later chain opening its own thread (e.g. the week's thread was gone) keeps the first one. + await rememberChannelWeek(channelWeek({ dataDir: dir, ...channel, at }), { + threadId: "thread-2", + isNew: true, + }); + expect(channelWeek({ dataDir: dir, ...channel, at })?.joinT3ThreadId).toBe("thread-1"); + }); + + it("starts fresh next week and keeps channels apart", async () => { + const dir = dataDir(); + await rememberChannelWeek(channelWeek({ dataDir: dir, ...channel, at }), { + threadId: "thread-1", + isNew: true, + }); + const nextWeek = new Date("2026-12-01T09:00:00Z"); + expect(channelWeek({ dataDir: dir, ...channel, at: nextWeek })?.joinT3ThreadId).toBeUndefined(); + expect( + channelWeek({ dataDir: dir, ...channel, channelId: "other", at })?.joinT3ThreadId, + ).toBeUndefined(); + }); + + it("ignores continued threads", async () => { + const dir = dataDir(); + const week = channelWeek({ dataDir: dir, ...channel, at }); + await rememberChannelWeek(week, { threadId: "old-chain-thread", isNew: false }); + expect(channelWeek({ dataDir: dir, ...channel, at })?.joinT3ThreadId).toBeUndefined(); + }); +}); diff --git a/apps/discord-bot/src/teams/weeklyThreads.ts b/apps/discord-bot/src/teams/weeklyThreads.ts new file mode 100644 index 0000000000000..76c5f03df064c --- /dev/null +++ b/apps/discord-bot/src/teams/weeklyThreads.ts @@ -0,0 +1,105 @@ +// @effect-diagnostics nodeBuiltinImport:off globalDate:off +import * as NodePath from "node:path"; + +import { readGroupChatMirror, rememberGroupChatMirror } from "./groupChats.ts"; + +/** + * A channel reply chain keeps its own T3 thread; a new top-level post joins the channel's thread + * for the week. Group chats roll over weekly. Weeks start Monday 00:00 in this time zone. + */ +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 location key. */ +export function weeklyThreadKey(locationKey: string, at: Date): string { + return `${locationKey}/${teamsWeekBucket(at)}`; +} + +/** Key of a Teams channel, shared by every reply chain posted in it. */ +export function teamsChannelLocationKey(input: { + readonly tenantId: string; + readonly teamId: string; + readonly channelId: string; +}): string { + return `native/${input.tenantId}/${input.teamId}/${input.channelId}`; +} + +export function weeklyThreadsFile(dataDir: string): string { + return NodePath.join(dataDir, "teams-weekly-threads.json"); +} + +/** The T3 thread opened for a channel week, if any. */ +export function readWeeklyThread(filePath: string, weekKey: string): string | null { + return readGroupChatMirror(filePath, weekKey); +} + +export function rememberWeeklyThread( + filePath: string, + weekKey: string, + t3ThreadId: string, +): Promise { + return rememberGroupChatMirror(filePath, weekKey, t3ThreadId); +} + +export interface ChannelWeek { + readonly file: string; + readonly weekKey: string; + /** This week's thread for the channel, for a reply chain that has no link yet. */ + readonly joinT3ThreadId: string | undefined; +} + +/** Weekly thread for a channel message; `null` outside channels (personal and group chats). */ +export function channelWeek(input: { + readonly dataDir: string; + readonly tenantId: string; + readonly teamId: string | undefined; + readonly channelId: string | undefined; + readonly at: Date; +}): ChannelWeek | null { + if (!input.teamId || !input.channelId) return null; + const file = weeklyThreadsFile(input.dataDir); + const weekKey = weeklyThreadKey( + teamsChannelLocationKey({ + tenantId: input.tenantId, + teamId: input.teamId, + channelId: input.channelId, + }), + input.at, + ); + return { file, weekKey, joinT3ThreadId: readWeeklyThread(file, weekKey) ?? undefined }; +} + +/** Records a thread a channel reply chain just opened as that channel's thread for the week. */ +export async function rememberChannelWeek( + week: ChannelWeek | null, + turn: { readonly threadId: string; readonly isNew: boolean }, +): Promise { + if (week === null || !turn.isNew || readWeeklyThread(week.file, week.weekKey) !== null) return; + await rememberWeeklyThread(week.file, week.weekKey, turn.threadId); +} From db53e2edcd2310ad892a44aed43412e1c6f48890 Mon Sep 17 00:00:00 2001 From: T3 Code PR Stack <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:21:09 +0100 Subject: [PATCH 2/4] fix(teams): answer only in the reply chain that asked Several reply chains can now share one T3 thread. Each chain's bridge renders only turns whose user message it sent; web UI turns go to the chain that last spoke. The owned ids persist on the link so this survives restarts. Discord bridges and older Teams links keep rendering every turn. Co-Authored-By: Claude Opus 5.5 --- .../ResponseBridge.teamsOwnership.test.ts | 93 ++++ .../src/features/ResponseBridge.ts | 459 ++++++++++++------ 2 files changed, 396 insertions(+), 156 deletions(-) create mode 100644 apps/discord-bot/src/features/ResponseBridge.teamsOwnership.test.ts diff --git a/apps/discord-bot/src/features/ResponseBridge.teamsOwnership.test.ts b/apps/discord-bot/src/features/ResponseBridge.teamsOwnership.test.ts new file mode 100644 index 0000000000000..0cbc4e8eceb50 --- /dev/null +++ b/apps/discord-bot/src/features/ResponseBridge.teamsOwnership.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { teamsBridgeOwnsTurn, userMessagesForTurn } from "./ResponseBridge.ts"; + +const teams = (id: string, turnId: string | null, request: string) => ({ + id, + role: "user", + turnId, + text: `Context\n\nAuthorized Teams request:\n${request}`, +}); +const web = (id: string, turnId: string | null, text: string) => ({ + id, + role: "user", + turnId, + text, +}); +const answer = (id: string, turnId: string | null) => ({ + id, + role: "assistant", + turnId, + text: `answer ${id}`, +}); + +// Chain A sent u1 (turn t1), chain B sent u2 (turn t2), web UI sent u3 (turn t3). +const messages = [ + teams("u1", "t1", "first"), + answer("a1", "t1"), + teams("u2", "t2", "second"), + answer("a2", "t2"), + web("u3", "t3", "from the browser"), + answer("a3", "t3"), +]; + +describe("userMessagesForTurn", () => { + it("prefers user messages tagged with the turn id", () => { + expect(userMessagesForTurn(messages, "t2").map((message) => message.id)).toEqual(["u2"]); + }); + + it("falls back to the latest user message before the turn's first answer", () => { + const untagged = [teams("u1", null, "first"), answer("a1", "t1"), teams("u2", null, "x")]; + expect(userMessagesForTurn(untagged, "t1").map((message) => message.id)).toEqual(["u1"]); + // No answer yet: the latest user message starts the turn. + expect(userMessagesForTurn(untagged, "t9").map((message) => message.id)).toEqual(["u2"]); + }); +}); + +describe("teamsBridgeOwnsTurn", () => { + const ownsFor = (owned: ReadonlyArray, turnId: string | null, list = messages) => + teamsBridgeOwnsTurn({ platform: "teams", turnId, messages: list, ownedUserMessageIds: owned }); + + it("owns a turn this chain sent", () => { + expect(ownsFor(["u1"], "t1")).toBe(true); + expect(ownsFor(["u2"], "t2")).toBe(true); + }); + + it("does not own another chain's turn", () => { + expect(ownsFor(["u1"], "t2")).toBe(false); + expect(ownsFor(["u2"], "t1")).toBe(false); + }); + + it("gives a web UI turn to the chain that most recently sent a Teams message", () => { + expect(ownsFor(["u2"], "t3")).toBe(true); + expect(ownsFor(["u1"], "t3")).toBe(false); + }); + + it("lets every chain render a web UI turn with no earlier Teams message", () => { + const list = [web("w1", "t1", "hi"), answer("a1", "t1")]; + expect(ownsFor(["other"], "t1", list)).toBe(true); + }); + + it("does not let a newly joined chain claim an earlier completed turn", () => { + // Chain B joins with only its first turn's message id; turn t1 belongs to chain A. + const list = [teams("u1", "t1", "first"), answer("a1", "t1"), teams("u2", "t2", "second")]; + expect(ownsFor(["u2"], "t1", list)).toBe(false); + expect(ownsFor(["u2"], "t2", list)).toBe(true); + }); + + it("renders every turn for a legacy bridge without remembered ids", () => { + expect(ownsFor([], "t1")).toBe(true); + expect(ownsFor([], "t2")).toBe(true); + }); + + it("always owns turns on Discord", () => { + expect( + teamsBridgeOwnsTurn({ + platform: "discord", + turnId: "t2", + messages, + ownedUserMessageIds: ["u1"], + }), + ).toBe(true); + }); +}); diff --git a/apps/discord-bot/src/features/ResponseBridge.ts b/apps/discord-bot/src/features/ResponseBridge.ts index d5316a23937fa..4d935916d27ea 100644 --- a/apps/discord-bot/src/features/ResponseBridge.ts +++ b/apps/discord-bot/src/features/ResponseBridge.ts @@ -1124,6 +1124,76 @@ export function classifyUserMessageIngress(text: string): UserMessageIngressSurf return "t3-client"; } +type TurnOwnershipMessage = { + readonly id: string; + readonly role: string; + readonly turnId: string | null; + readonly text: string; +}; + +/** + * User messages that started (or steered) `turnId`. User messages carry the run id + * as `turnId`; when none is tagged, fall back to the latest user message before the + * turn's first assistant message (or the latest user message when it has none yet). + */ +export function userMessagesForTurn( + messages: ReadonlyArray, + turnId: string | null, +): ReadonlyArray { + if (turnId !== null) { + const tagged = messages.filter( + (message) => message.role === "user" && message.turnId === turnId, + ); + if (tagged.length > 0) return tagged; + } + const firstAssistantIndex = + turnId === null + ? -1 + : messages.findIndex((message) => message.role === "assistant" && message.turnId === turnId); + const end = firstAssistantIndex >= 0 ? firstAssistantIndex : messages.length; + for (let index = end - 1; index >= 0; index -= 1) { + const message = messages[index]; + if (message?.role === "user") return [message]; + } + return []; +} + +/** + * Teams reply chains sharing a T3 thread render only turns whose user message they sent. + * Other turns (web UI, GitHub) go to the chain that last sent a Teams message before them, + * else to every chain. Legacy bridges without sent ids and Discord bridges own every turn. + */ +export function teamsBridgeOwnsTurn(input: { + readonly platform: "discord" | "teams"; + readonly turnId: string | null; + readonly messages: ReadonlyArray; + readonly ownedUserMessageIds: ReadonlySet | ReadonlyArray; +}): boolean { + if (input.platform !== "teams") return true; + const owned = + input.ownedUserMessageIds instanceof Set + ? input.ownedUserMessageIds + : new Set(input.ownedUserMessageIds); + if (owned.size === 0) return true; + const turnUsers = userMessagesForTurn(input.messages, input.turnId); + if (turnUsers.length === 0) return true; + if (turnUsers.some((message) => owned.has(message.id))) return true; + if (turnUsers.some((message) => classifyUserMessageIngress(message.text) === "teams")) { + return false; + } + const firstIndex = input.messages.findIndex((message) => message.id === turnUsers[0]!.id); + for (let index = firstIndex - 1; index >= 0; index -= 1) { + const message = input.messages[index]; + if (message?.role !== "user") continue; + if (owned.has(message.id)) return true; + if (classifyUserMessageIngress(message.text) === "teams") return false; + } + return true; +} + +/** Cap for the durable per-chain ownership memory persisted on Teams links. */ +const TEAMS_OWNED_USER_MESSAGE_ID_LIMIT = 64; + /** * User prompts this bot injected into T3 (Discord mention / bootstrap path). * Never mirror these back into Discord as "External User Input" — they originated here. @@ -2391,8 +2461,46 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( ), discardPersistedTips: freshWorkingTurn, }); - const seedLastFinalized = - persistedLink?.lastFinalizedAssistantId ?? warmCacheEntry?.lastFinalizedAssistantId ?? null; + // Every user message this chain sent (resolved or not). `sentDiscordUserMessageIds` + // is pruned once a message lands in T3, so Teams turn ownership keeps its own memory. + const ownedUserMessageIds = new Set([ + ...(persistedLink?.sentDiscordUserMessageIds ?? []), + ...(input.sentDiscordUserMessageIds ?? []), + ]); + /** Per-snapshot Teams turn ownership (Discord always owns). */ + const turnOwnershipFor = (thread: OrchestrationThread) => { + const cache = new Map(); + return (turnId: string | null): boolean => { + if (rest.platform !== "teams") return true; + const cached = cache.get(turnId); + if (cached !== undefined) return cached; + const owns = teamsBridgeOwnsTurn({ + platform: rest.platform, + turnId, + messages: thread.messages, + ownedUserMessageIds, + }); + cache.set(turnId, owns); + return owns; + }; + }; + // Teams persists the owned tail (not just unresolved ids) so ownership survives restarts. + const persistTeamsOwnedUserMessageIds = () => + links.setSentDiscordUserMessageIds( + input.discordChannelId, + [...ownedUserMessageIds].slice(-TEAMS_OWNED_USER_MESSAGE_ID_LIMIT), + ); + if (rest.platform === "teams" && (input.sentDiscordUserMessageIds ?? []).length > 0) { + yield* persistTeamsOwnedUserMessageIds().pipe(Effect.ignore); + } + // The warm cache is keyed by T3 thread, so on Teams it holds whichever reply chain + // finalized last. Once a chain renders only its own turns, another chain's cursor + // would hide this chain's unfinalized answers; keep it only for legacy all-turn links. + const warmCacheLastFinalizedSeed = + rest.platform === "teams" && ownedUserMessageIds.size > 0 + ? null + : (warmCacheEntry?.lastFinalizedAssistantId ?? null); + const seedLastFinalized = persistedLink?.lastFinalizedAssistantId ?? warmCacheLastFinalizedSeed; const stateRef = yield* Ref.make({ ...emptyState({ workingAckMessageId: freshWorkingTurn ? (input.workingAckMessageId ?? null) : null, @@ -2464,8 +2572,7 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( // Mutable watermark for trim + warm cache (updated on finalize). const deliveredMemoryTrim = { lastFinalizedAssistantId: (persistedLink?.lastFinalizedAssistantId ?? - warmCacheEntry?.lastFinalizedAssistantId ?? - null) as string | null, + warmCacheLastFinalizedSeed) as string | null, }; const projectThreadForDiscordMemory = (thread: OrchestrationThread): OrchestrationThread => trimOrchestrationThreadForDiscordMemory({ @@ -2562,7 +2669,17 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( Ref.update(stateRef, (current) => ({ ...current, sentDiscordUserMessageIds: uniqueMessageIds([...current.sentDiscordUserMessageIds, ...ids]), - })).pipe(Effect.asVoid); + })).pipe( + Effect.andThen( + rest.platform === "teams" + ? Effect.suspend(() => { + for (const id of ids) ownedUserMessageIds.add(id); + return persistTeamsOwnedUserMessageIds().pipe(Effect.ignore); + }) + : Effect.void, + ), + Effect.asVoid, + ); controlSlot.adoptWorkingAckMessageId = Effect.fn("adoptWorkingAckMessageId")((messageId) => Effect.gen(function* () { @@ -2805,7 +2922,9 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( ); const persistSentDiscordUserMessageIds = (ids: ReadonlyArray) => - links.setSentDiscordUserMessageIds(input.discordChannelId, uniqueMessageIds(ids)); + rest.platform === "teams" + ? persistTeamsOwnedUserMessageIds() + : links.setSentDiscordUserMessageIds(input.discordChannelId, uniqueMessageIds(ids)); const postExternalUserMessages = Effect.fn("ResponseBridge.postExternalUserMessages")(function* ( messages: ReadonlyArray, @@ -5307,12 +5426,24 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( const activeTurnId = thread.latestTurn?.turnId ?? null; const turnInProgressNow = isTurnInProgress(thread); + // Teams reply chains sharing this T3 thread render only their own turns. Skipping + // leaves this bridge's delivery state untouched for its next owned turn. + const ownsTurn = turnOwnershipFor(thread); + const ownsActiveTurn = ownsTurn(activeTurnId); + if (!ownsActiveTurn) { + yield* Effect.logDebug("Teams bridge skipping turn owned by another reply chain", { + discordChannelId: input.discordChannelId, + t3ThreadId: input.t3ThreadId, + turnId: activeTurnId, + }); + } // Interrupted session (Wake Required): convert open Working tips to a Continue notice // before catch-up finalize would treat partial stream as a finished answer. { const preWake = yield* Ref.get(stateRef); if ( + ownsActiveTurn && shouldConvertWorkingTipsToWakeUp({ sessionStatus: thread.session?.status ?? null, activeTurnId: thread.session?.activeTurnId ?? null, @@ -5349,15 +5480,21 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( prior.delivery.lastFinalizedAssistantId ?? durableLinkNow?.lastFinalizedAssistantId ?? persistedLink?.lastFinalizedAssistantId ?? - warmCacheEntry?.lastFinalizedAssistantId ?? - null; + warmCacheLastFinalizedSeed; const lastFinalizedTextForDelivery = prior.delivery.lastFinalizedText ?? null; - const threadMessagesForDelivery = thread.messages.map((message) => ({ + const allThreadMessagesForDelivery = thread.messages.map((message) => ({ id: message.id, role: message.role, turnId: message.turnId, text: message.text, })); + // Teams: other chains' answers are invisible to this bridge's catch-up and delivery. + const threadMessagesForDelivery = + rest.platform === "teams" + ? allThreadMessagesForDelivery.filter( + (message) => message.role !== "assistant" || ownsTurn(message.turnId), + ) + : allThreadMessagesForDelivery; const deliveryAssistants = assistantMessagesForDelivery({ messages: threadMessagesForDelivery, turnId: activeTurnId, @@ -5405,154 +5542,156 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( Effect.asVoid, ); } - const afterCatchUp = yield* Ref.get(stateRef); - const lastFinalizedAfterCatchUp = - afterCatchUp.delivery.lastFinalizedAssistantId ?? lastFinalizedForDelivery; - const lastFinalizedTextAfterCatchUp = - afterCatchUp.delivery.lastFinalizedText ?? lastFinalizedTextForDelivery; - const deliveryAssistantIds = new Set(deliveryAssistants.map((entry) => entry.id)); - const turnAssistants = thread.messages.filter( - (message) => message.role === "assistant" && deliveryAssistantIds.has(message.id), - ); - const images = turnAssistants.flatMap((message) => imageAttachmentsOf(message.attachments)); - const streaming = - turnInProgressNow || - (thread.latestTurn == null && - turnAssistants.some( - (message) => isAssistantStreaming(thread, message.id) || message.streaming === true, - )); - - const decision = decideAssistantDelivery({ - state: { - ...afterCatchUp.delivery, - // Keep durable finalize memory from the link store in sync. - lastFinalizedAssistantId: lastFinalizedAfterCatchUp, - lastFinalizedText: lastFinalizedTextAfterCatchUp, - }, - turnId: activeTurnId, - turnInProgress: turnInProgressNow, - assistants: deliveryAssistants.map((entry) => ({ - id: entry.id, - text: entry.text, - })), - messages: threadMessagesForDelivery, - streaming, - presentationFull: (input.presentationMode ?? "full") === "full", - // Idle catch-up (rehydrate *or* interactive recovery after a comment) often - // gets a single settled snapshot — do not stream the previous final under - // `_Working.._` + Stop waiting for a second settle tick that never arrives. - // Substantial answers also finalize immediately inside decideAssistantDelivery. - skipSettleGrace: !turnInProgressNow, - }); - - yield* Effect.logInfo("Discord delivery decision", { - t3ThreadId: input.t3ThreadId, - turnId: activeTurnId, - intent: decision.intent._tag, - reason: - decision.intent._tag === "noop" || decision.intent._tag === "hold" - ? decision.intent.reason - : null, - phase: decision.state.phase, - epoch: decision.state.epoch, - settleReady: decision.state.settleReady, - deliveryAssistants: deliveryAssistants.length, - streaming, - turnInProgress: turnInProgressNow, - }); + if (ownsActiveTurn) { + const afterCatchUp = yield* Ref.get(stateRef); + const lastFinalizedAfterCatchUp = + afterCatchUp.delivery.lastFinalizedAssistantId ?? lastFinalizedForDelivery; + const lastFinalizedTextAfterCatchUp = + afterCatchUp.delivery.lastFinalizedText ?? lastFinalizedTextForDelivery; + const deliveryAssistantIds = new Set(deliveryAssistants.map((entry) => entry.id)); + const turnAssistants = thread.messages.filter( + (message) => message.role === "assistant" && deliveryAssistantIds.has(message.id), + ); + const images = turnAssistants.flatMap((message) => imageAttachmentsOf(message.attachments)); + const streaming = + turnInProgressNow || + (thread.latestTurn == null && + turnAssistants.some( + (message) => isAssistantStreaming(thread, message.id) || message.streaming === true, + )); + + const decision = decideAssistantDelivery({ + state: { + ...afterCatchUp.delivery, + // Keep durable finalize memory from the link store in sync. + lastFinalizedAssistantId: lastFinalizedAfterCatchUp, + lastFinalizedText: lastFinalizedTextAfterCatchUp, + }, + turnId: activeTurnId, + turnInProgress: turnInProgressNow, + assistants: deliveryAssistants.map((entry) => ({ + id: entry.id, + text: entry.text, + })), + messages: threadMessagesForDelivery, + streaming, + presentationFull: (input.presentationMode ?? "full") === "full", + // Idle catch-up (rehydrate *or* interactive recovery after a comment) often + // gets a single settled snapshot — do not stream the previous final under + // `_Working.._` + Stop waiting for a second settle tick that never arrives. + // Substantial answers also finalize immediately inside decideAssistantDelivery. + skipSettleGrace: !turnInProgressNow, + }); - // Apply non-terminal state before I/O; finalize commits only after successful post - // so a failed finalize can retry without being stuck in phase=finalized. - if (decision.intent._tag !== "finalize") { - // Late multi-bubble reopen: epoch left finalized → streaming/awaiting with a - // new assistant after lastFinalized. Clear bridge finalizedTurnId so stream / - // re-finalize is not treated as a no-op duplicate of the short status final. - const reopenedAfterPrematureFinal = - prior.delivery.phase === "finalized" && - (decision.state.phase === "streaming" || decision.state.phase === "awaiting"); - yield* Ref.update(stateRef, (current) => ({ - ...current, - delivery: decision.state, - adoptedInitialSnapshot: true, - seededWorkingAckPending: decision.state.phase === "awaiting", - finalizedTurnId: - decision.state.phase === "awaiting" || reopenedAfterPrematureFinal - ? null - : current.finalizedTurnId, - })); - } else { - yield* Ref.update(stateRef, (current) => ({ - ...current, - adoptedInitialSnapshot: true, - })); - } + yield* Effect.logInfo("Discord delivery decision", { + t3ThreadId: input.t3ThreadId, + turnId: activeTurnId, + intent: decision.intent._tag, + reason: + decision.intent._tag === "noop" || decision.intent._tag === "hold" + ? decision.intent.reason + : null, + phase: decision.state.phase, + epoch: decision.state.epoch, + settleReady: decision.state.settleReady, + deliveryAssistants: deliveryAssistants.length, + streaming, + turnInProgress: turnInProgressNow, + }); - if (decision.intent._tag === "stream") { - yield* postUserMessagesBefore(decision.intent.assistantId); - yield* postOrEditAssistant({ - turnId: decision.intent.turnId, - t3MessageId: decision.intent.assistantId, - text: decision.intent.text, - streaming: true, - images, - worktreePath: thread.worktreePath, - }).pipe(Effect.tapCause(alertStreamFailure("live-stream")), Effect.asVoid); - } else if (decision.intent._tag === "finalize") { - yield* postUserMessagesBefore(decision.intent.assistantId); - yield* postOrEditAssistant({ - turnId: decision.intent.turnId, - t3MessageId: decision.intent.assistantId, - text: decision.intent.text, - streaming: false, - images, - worktreePath: thread.worktreePath, - }).pipe(Effect.tapCause(alertStreamFailure("finalize")), Effect.asVoid); - } else if ( - decision.intent._tag === "noop" && - decision.intent.reason === "settled-without-content" && - !prior.seededWorkingAckPending && - prior.delivery.phase !== "finalized" - ) { - // Prefer posting whatever we already streamed over wiping Working with silence. - const fallbackText = prior.lastAssistantText.trim(); - if (fallbackText !== "" && prior.t3AssistantMessageId !== null) { - yield* Effect.logInfo( - "Finalizing from last streamed body (settled without new content)", - { - t3ThreadId: input.t3ThreadId, - turnId: activeTurnId, - textLen: fallbackText.length, - }, - ); - yield* postUserMessagesBefore(prior.t3AssistantMessageId); - yield* postOrEditAssistant({ - turnId: activeTurnId, - t3MessageId: prior.t3AssistantMessageId, - text: fallbackText, - streaming: false, - images: [], - worktreePath: thread.worktreePath, - }).pipe(Effect.tapCause(alertStreamFailure("finalize-stream-fallback")), Effect.asVoid); + // Apply non-terminal state before I/O; finalize commits only after successful post + // so a failed finalize can retry without being stuck in phase=finalized. + if (decision.intent._tag !== "finalize") { + // Late multi-bubble reopen: epoch left finalized → streaming/awaiting with a + // new assistant after lastFinalized. Clear bridge finalizedTurnId so stream / + // re-finalize is not treated as a no-op duplicate of the short status final. + const reopenedAfterPrematureFinal = + prior.delivery.phase === "finalized" && + (decision.state.phase === "streaming" || decision.state.phase === "awaiting"); yield* Ref.update(stateRef, (current) => ({ ...current, - delivery: { - ...current.delivery, - phase: "finalized" as const, - streamText: "", - settleReady: false, - finalizedAssistantId: prior.t3AssistantMessageId, - lastFinalizedAssistantId: prior.t3AssistantMessageId, - lastFinalizedText: fallbackText, - }, - seededWorkingAckPending: false, - lastAssistantText: "", - finalizedTurnId: activeTurnId, + delivery: decision.state, + adoptedInitialSnapshot: true, + seededWorkingAckPending: decision.state.phase === "awaiting", + finalizedTurnId: + decision.state.phase === "awaiting" || reopenedAfterPrematureFinal + ? null + : current.finalizedTurnId, })); } else { - yield* clearInProgressMessages("settled-without-final-content").pipe( - Effect.catchCause(Effect.logError), - Effect.asVoid, - ); + yield* Ref.update(stateRef, (current) => ({ + ...current, + adoptedInitialSnapshot: true, + })); + } + + if (decision.intent._tag === "stream") { + yield* postUserMessagesBefore(decision.intent.assistantId); + yield* postOrEditAssistant({ + turnId: decision.intent.turnId, + t3MessageId: decision.intent.assistantId, + text: decision.intent.text, + streaming: true, + images, + worktreePath: thread.worktreePath, + }).pipe(Effect.tapCause(alertStreamFailure("live-stream")), Effect.asVoid); + } else if (decision.intent._tag === "finalize") { + yield* postUserMessagesBefore(decision.intent.assistantId); + yield* postOrEditAssistant({ + turnId: decision.intent.turnId, + t3MessageId: decision.intent.assistantId, + text: decision.intent.text, + streaming: false, + images, + worktreePath: thread.worktreePath, + }).pipe(Effect.tapCause(alertStreamFailure("finalize")), Effect.asVoid); + } else if ( + decision.intent._tag === "noop" && + decision.intent.reason === "settled-without-content" && + !prior.seededWorkingAckPending && + prior.delivery.phase !== "finalized" + ) { + // Prefer posting whatever we already streamed over wiping Working with silence. + const fallbackText = prior.lastAssistantText.trim(); + if (fallbackText !== "" && prior.t3AssistantMessageId !== null) { + yield* Effect.logInfo( + "Finalizing from last streamed body (settled without new content)", + { + t3ThreadId: input.t3ThreadId, + turnId: activeTurnId, + textLen: fallbackText.length, + }, + ); + yield* postUserMessagesBefore(prior.t3AssistantMessageId); + yield* postOrEditAssistant({ + turnId: activeTurnId, + t3MessageId: prior.t3AssistantMessageId, + text: fallbackText, + streaming: false, + images: [], + worktreePath: thread.worktreePath, + }).pipe(Effect.tapCause(alertStreamFailure("finalize-stream-fallback")), Effect.asVoid); + yield* Ref.update(stateRef, (current) => ({ + ...current, + delivery: { + ...current.delivery, + phase: "finalized" as const, + streamText: "", + settleReady: false, + finalizedAssistantId: prior.t3AssistantMessageId, + lastFinalizedAssistantId: prior.t3AssistantMessageId, + lastFinalizedText: fallbackText, + }, + seededWorkingAckPending: false, + lastAssistantText: "", + finalizedTurnId: activeTurnId, + })); + } else { + yield* clearInProgressMessages("settled-without-final-content").pipe( + Effect.catchCause(Effect.logError), + Effect.asVoid, + ); + } } } } else { @@ -5571,7 +5710,9 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( seededWorkingAckPending: state.seededWorkingAckPending, state: summarizeBridgeStateForLog(state), }); - if ( + if (!ownsActiveTurn) { + // Another reply chain's turn: keep this chain's Working tip as-is. + } else if ( turnRunningNoAssistant && !state.seededWorkingAckPending && shouldPublishAssistantUpdate({ @@ -5621,7 +5762,7 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( // Deliver them through the normal final-message path so Working is removed and the // durable delivery receipt prevents duplicate notifications after reconnecting. const failureActivity = - thread.latestTurn?.state === "error" + ownsActiveTurn && thread.latestTurn?.state === "error" ? thread.activities.findLast((activity) => { if (activity.turnId !== activeTurnId || activity.tone !== "error") return false; const payload = activity.payload; @@ -5699,7 +5840,9 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( // Tasks first: first-class Discord progress UI from turn.plan (not External User Input). // Keep updating mid-turn / rehydrate; owned via taskDiscordMessageId so it never freezes Working. - const tasks = presentTasks(thread.activities, thread.latestTurn?.turnId ?? null); + const tasks = ownsActiveTurn + ? presentTasks(thread.activities, thread.latestTurn?.turnId ?? null) + : null; if (tasks !== null && input.presentationMode !== "final-only") { const content = formatTasksForDiscord(tasks); const key = `${tasks.explanation ?? ""}:${tasks.tasks.map((task) => `${task.status}:${task.step}`).join("|")}`; @@ -5709,13 +5852,17 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( ); } - const pending = derivePendingInteractions(thread.activities); + const pending = derivePendingInteractions( + rest.platform === "teams" + ? thread.activities.filter((activity) => ownsTurn(activity.turnId)) + : thread.activities, + ); const approvals = pending.filter( (entry): entry is PendingApproval => entry.kind === "approval", ); yield* postApprovals(approvals).pipe(Effect.catchCause(Effect.logError), Effect.asVoid); - if (thread.session?.status === "error" && thread.session.lastError) { + if (ownsActiveTurn && thread.session?.status === "error" && thread.session.lastError) { yield* rest .createMessage(input.discordChannelId, { content: `**T3 error:** ${thread.session.lastError}`, From 715b799d5c43ab0f9e48cdaf2208c928aded1b3e Mon Sep 17 00:00:00 2001 From: T3 Code PR Stack <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:27:47 +0100 Subject: [PATCH 3/4] revert(teams): keep channel conversations as they were Scope this PR to watched group chats only. Channel reply chains, the linked turn router and the response bridge go back to fork/dev unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/features/LinkedTurnRouter.ts | 37 +- .../LinkedTurnRouter.weeklyJoin.test.ts | 118 ----- .../ResponseBridge.teamsOwnership.test.ts | 93 ---- .../src/features/ResponseBridge.ts | 459 ++++++------------ .../src/features/TeamsNativeApp.ts | 10 - apps/discord-bot/src/teams-gateway-main.ts | 11 - .../src/teams/weeklyThreads.test.ts | 78 +-- apps/discord-bot/src/teams/weeklyThreads.ts | 76 +-- 8 files changed, 165 insertions(+), 717 deletions(-) delete mode 100644 apps/discord-bot/src/features/LinkedTurnRouter.weeklyJoin.test.ts delete mode 100644 apps/discord-bot/src/features/ResponseBridge.teamsOwnership.test.ts diff --git a/apps/discord-bot/src/features/LinkedTurnRouter.ts b/apps/discord-bot/src/features/LinkedTurnRouter.ts index 2d20ddc2ba7ea..885e6f31fb535 100644 --- a/apps/discord-bot/src/features/LinkedTurnRouter.ts +++ b/apps/discord-bot/src/features/LinkedTurnRouter.ts @@ -1,5 +1,5 @@ // @effect-diagnostics anyUnknownInErrorContext:off missingEffectContext:off globalDate:off globalErrorInEffectFailure:off outdatedApi:off -import type { ClientSourceHint, ThreadId, UploadChatAttachment } from "@t3tools/contracts"; +import type { ClientSourceHint, UploadChatAttachment } from "@t3tools/contracts"; import { DiscordREST } from "dfx"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -76,11 +76,6 @@ export interface TransportNeutralLinkedTurnInput { readonly stickyModelOnContinue?: boolean | undefined; readonly attachments?: ReadonlyArray | undefined; readonly promptContext?: LinkedTurnInput["promptContext"]; - /** - * When this source has no link yet, continue this T3 thread instead of opening one, and link - * the source to it. Ignored when the thread is gone or belongs to another project. - */ - readonly joinT3ThreadId?: string | undefined; } /** Preserve the requester on every dispatch; the server keeps the first thread origin. */ @@ -150,26 +145,10 @@ export const startOrContinueT3Turn = Effect.fn("startOrContinueT3Turn")(function const hasExplicitModelFlags = input.flags.provider !== undefined || input.flags.model !== undefined; const resolved = yield* resolveProjectFromShortName(input.projectShortName); - const linkedSource = yield* links.getBySourceThread( + const existing = yield* links.getBySourceThread( input.source.sourceKind, input.source.sourceThreadId, ); - const joinT3ThreadId = linkedSource === null ? input.joinT3ThreadId : undefined; - const joinable = - joinT3ThreadId === undefined - ? null - : yield* t3 - .fetchThreadDetail(joinT3ThreadId as ThreadId) - .pipe( - Effect.map((snapshot) => - snapshot !== null && snapshot.thread.projectId === resolved.project.id - ? (joinT3ThreadId as ThreadId) - : null, - ), - ); - const existing = - linkedSource ?? - (joinable === null ? null : { t3ThreadId: joinable, projectId: resolved.project.id }); if (existing !== null) { if (input.source.sourceKind === "teams" && existing.projectId !== resolved.project.id) { @@ -206,18 +185,6 @@ export const startOrContinueT3Turn = Effect.fn("startOrContinueT3Turn")(function ...(attachments.length > 0 ? { attachments } : {}), sourceHint, }); - if (linkedSource === null) { - yield* links.put({ - sourceKind: input.source.sourceKind, - sourceThreadId: input.source.sourceThreadId, - discordThreadId: input.externalConversationId, - t3ThreadId: existing.t3ThreadId, - projectId: resolved.project.id, - channelId: input.externalParentId, - guildId: input.externalTenantId, - createdAt: DateTime.formatIso(DateTime.nowUnsafe()), - }); - } return { threadId: existing.t3ThreadId, messageId, isNew: false } as const; } diff --git a/apps/discord-bot/src/features/LinkedTurnRouter.weeklyJoin.test.ts b/apps/discord-bot/src/features/LinkedTurnRouter.weeklyJoin.test.ts deleted file mode 100644 index 28ccdd7752662..0000000000000 --- a/apps/discord-bot/src/features/LinkedTurnRouter.weeklyJoin.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off unsafeEffectTypeAssertion:off -import * as NodeFSP from "node:fs/promises"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; -import { - DEFAULT_SERVER_SETTINGS, - ProjectId, - ProviderInstanceId, - ThreadId, -} from "@t3tools/contracts"; -import * as ConfigProvider from "effect/ConfigProvider"; -import * as Effect from "effect/Effect"; -import { describe, expect } from "vite-plus/test"; -import { it } from "@effect/vitest"; -import { DiscordBotConfig } from "../config.ts"; -import { makeProjectAliasStore, ProjectAliasStore } from "../projectAliases.ts"; -import { makeThreadLinkStore, ThreadLinkStore } from "../store/ThreadLinkStore.ts"; -import { T3Session, type T3SessionService } from "../t3/T3Session.ts"; -import { startOrContinueT3Turn } from "./LinkedTurnRouter.ts"; - -describe("Teams weekly thread join", () => { - it.effect("links a new reply chain to the week's thread, and keeps old chains on theirs", () => - Effect.gen(function* () { - const directory = yield* Effect.acquireRelease( - Effect.promise(() => NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "teams-week-join-"))), - (path) => Effect.promise(() => NodeFSP.rm(path, { recursive: true, force: true })), - ); - const config = yield* DiscordBotConfig.pipe( - Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnvRecord({}))), - ); - const project = ProjectId.make("project:teams"); - const projects = new Map([ - ["thread:week", project], - ["thread:old-chain", project], - ["thread:other-project", ProjectId.make("project:other")], - ]); - const continued: Array = []; - let launches = 0; - const session = { - findProjectByWorkspaceRoot: () => - Effect.succeed({ - id: project, - workspaceRoot: "/workspace/omega", - defaultModelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok" }, - }), - resolveModelSelection: () => - Effect.succeed({ instanceId: ProviderInstanceId.make("grok"), model: "grok" }), - fetchThreadDetail: (threadId: string) => - Effect.succeed( - projects.has(threadId) ? { thread: { projectId: projects.get(threadId) } } : null, - ), - serverConfig: () => - Effect.succeed({ settings: DEFAULT_SERVER_SETTINGS, newProjectsRoot: "/projects" }), - shell: () => Effect.succeed({ threads: [] }), - startTurnWithWorktree: () => - Effect.sync(() => { - launches += 1; - return { threadId: ThreadId.make(`thread:new-${launches}`), messageId: "m:new" }; - }), - startTurn: (input: Parameters[0]) => - Effect.sync(() => { - continued.push(input.threadId); - return { messageId: `m:${continued.length}` }; - }), - } as unknown as T3SessionService; - - const links = yield* makeThreadLinkStore(directory); - const turn = (chain: string, joinT3ThreadId: string | undefined) => - startOrContinueT3Turn(config, { - source: { sourceKind: "teams", sourceThreadId: `native/t/team/ch/${chain}` }, - joinT3ThreadId, - externalConversationId: chain, - externalParentId: "team/ch", - externalTenantId: "t", - projectShortName: "omega", - prompt: "Investigate", - promptContext: { kind: "raw", value: "Investigate" }, - flags: {}, - stickyModelOnContinue: true, - }).pipe( - Effect.provideService( - ProjectAliasStore, - makeProjectAliasStore([{ shortName: "omega", workspaceRoot: "/workspace/omega" }]), - ), - Effect.provideService(ThreadLinkStore, links), - Effect.provideService(T3Session, session), - ); - - // A new top-level post joins the week's thread and gets its own link to it. - expect(yield* turn("chain-b", "thread:week")).toMatchObject({ - threadId: "thread:week", - isNew: false, - }); - expect( - (yield* links.getBySourceThread("teams", "native/t/team/ch/chain-b"))?.t3ThreadId, - ).toBe("thread:week"); - expect((yield* links.getByDiscordThreadId("chain-b"))?.t3ThreadId).toBe("thread:week"); - - // A reply chain that already has a thread stays on it, whatever the week's thread is. - yield* links.put({ - sourceKind: "teams", - sourceThreadId: "native/t/team/ch/chain-old", - discordThreadId: "chain-old", - t3ThreadId: ThreadId.make("thread:old-chain"), - projectId: project, - channelId: "team/ch", - guildId: "t", - createdAt: "2026-11-02T09:00:00.000Z", - }); - expect((yield* turn("chain-old", "thread:week")).threadId).toBe("thread:old-chain"); - - // A missing or foreign week thread falls back to opening a new one. - expect(yield* turn("chain-c", "thread:gone")).toMatchObject({ isNew: true }); - expect(yield* turn("chain-d", "thread:other-project")).toMatchObject({ isNew: true }); - expect(continued).toEqual(["thread:week", "thread:old-chain"]); - }).pipe(Effect.scoped), - ); -}); diff --git a/apps/discord-bot/src/features/ResponseBridge.teamsOwnership.test.ts b/apps/discord-bot/src/features/ResponseBridge.teamsOwnership.test.ts deleted file mode 100644 index 0cbc4e8eceb50..0000000000000 --- a/apps/discord-bot/src/features/ResponseBridge.teamsOwnership.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; - -import { teamsBridgeOwnsTurn, userMessagesForTurn } from "./ResponseBridge.ts"; - -const teams = (id: string, turnId: string | null, request: string) => ({ - id, - role: "user", - turnId, - text: `Context\n\nAuthorized Teams request:\n${request}`, -}); -const web = (id: string, turnId: string | null, text: string) => ({ - id, - role: "user", - turnId, - text, -}); -const answer = (id: string, turnId: string | null) => ({ - id, - role: "assistant", - turnId, - text: `answer ${id}`, -}); - -// Chain A sent u1 (turn t1), chain B sent u2 (turn t2), web UI sent u3 (turn t3). -const messages = [ - teams("u1", "t1", "first"), - answer("a1", "t1"), - teams("u2", "t2", "second"), - answer("a2", "t2"), - web("u3", "t3", "from the browser"), - answer("a3", "t3"), -]; - -describe("userMessagesForTurn", () => { - it("prefers user messages tagged with the turn id", () => { - expect(userMessagesForTurn(messages, "t2").map((message) => message.id)).toEqual(["u2"]); - }); - - it("falls back to the latest user message before the turn's first answer", () => { - const untagged = [teams("u1", null, "first"), answer("a1", "t1"), teams("u2", null, "x")]; - expect(userMessagesForTurn(untagged, "t1").map((message) => message.id)).toEqual(["u1"]); - // No answer yet: the latest user message starts the turn. - expect(userMessagesForTurn(untagged, "t9").map((message) => message.id)).toEqual(["u2"]); - }); -}); - -describe("teamsBridgeOwnsTurn", () => { - const ownsFor = (owned: ReadonlyArray, turnId: string | null, list = messages) => - teamsBridgeOwnsTurn({ platform: "teams", turnId, messages: list, ownedUserMessageIds: owned }); - - it("owns a turn this chain sent", () => { - expect(ownsFor(["u1"], "t1")).toBe(true); - expect(ownsFor(["u2"], "t2")).toBe(true); - }); - - it("does not own another chain's turn", () => { - expect(ownsFor(["u1"], "t2")).toBe(false); - expect(ownsFor(["u2"], "t1")).toBe(false); - }); - - it("gives a web UI turn to the chain that most recently sent a Teams message", () => { - expect(ownsFor(["u2"], "t3")).toBe(true); - expect(ownsFor(["u1"], "t3")).toBe(false); - }); - - it("lets every chain render a web UI turn with no earlier Teams message", () => { - const list = [web("w1", "t1", "hi"), answer("a1", "t1")]; - expect(ownsFor(["other"], "t1", list)).toBe(true); - }); - - it("does not let a newly joined chain claim an earlier completed turn", () => { - // Chain B joins with only its first turn's message id; turn t1 belongs to chain A. - const list = [teams("u1", "t1", "first"), answer("a1", "t1"), teams("u2", "t2", "second")]; - expect(ownsFor(["u2"], "t1", list)).toBe(false); - expect(ownsFor(["u2"], "t2", list)).toBe(true); - }); - - it("renders every turn for a legacy bridge without remembered ids", () => { - expect(ownsFor([], "t1")).toBe(true); - expect(ownsFor([], "t2")).toBe(true); - }); - - it("always owns turns on Discord", () => { - expect( - teamsBridgeOwnsTurn({ - platform: "discord", - turnId: "t2", - messages, - ownedUserMessageIds: ["u1"], - }), - ).toBe(true); - }); -}); diff --git a/apps/discord-bot/src/features/ResponseBridge.ts b/apps/discord-bot/src/features/ResponseBridge.ts index 4d935916d27ea..d5316a23937fa 100644 --- a/apps/discord-bot/src/features/ResponseBridge.ts +++ b/apps/discord-bot/src/features/ResponseBridge.ts @@ -1124,76 +1124,6 @@ export function classifyUserMessageIngress(text: string): UserMessageIngressSurf return "t3-client"; } -type TurnOwnershipMessage = { - readonly id: string; - readonly role: string; - readonly turnId: string | null; - readonly text: string; -}; - -/** - * User messages that started (or steered) `turnId`. User messages carry the run id - * as `turnId`; when none is tagged, fall back to the latest user message before the - * turn's first assistant message (or the latest user message when it has none yet). - */ -export function userMessagesForTurn( - messages: ReadonlyArray, - turnId: string | null, -): ReadonlyArray { - if (turnId !== null) { - const tagged = messages.filter( - (message) => message.role === "user" && message.turnId === turnId, - ); - if (tagged.length > 0) return tagged; - } - const firstAssistantIndex = - turnId === null - ? -1 - : messages.findIndex((message) => message.role === "assistant" && message.turnId === turnId); - const end = firstAssistantIndex >= 0 ? firstAssistantIndex : messages.length; - for (let index = end - 1; index >= 0; index -= 1) { - const message = messages[index]; - if (message?.role === "user") return [message]; - } - return []; -} - -/** - * Teams reply chains sharing a T3 thread render only turns whose user message they sent. - * Other turns (web UI, GitHub) go to the chain that last sent a Teams message before them, - * else to every chain. Legacy bridges without sent ids and Discord bridges own every turn. - */ -export function teamsBridgeOwnsTurn(input: { - readonly platform: "discord" | "teams"; - readonly turnId: string | null; - readonly messages: ReadonlyArray; - readonly ownedUserMessageIds: ReadonlySet | ReadonlyArray; -}): boolean { - if (input.platform !== "teams") return true; - const owned = - input.ownedUserMessageIds instanceof Set - ? input.ownedUserMessageIds - : new Set(input.ownedUserMessageIds); - if (owned.size === 0) return true; - const turnUsers = userMessagesForTurn(input.messages, input.turnId); - if (turnUsers.length === 0) return true; - if (turnUsers.some((message) => owned.has(message.id))) return true; - if (turnUsers.some((message) => classifyUserMessageIngress(message.text) === "teams")) { - return false; - } - const firstIndex = input.messages.findIndex((message) => message.id === turnUsers[0]!.id); - for (let index = firstIndex - 1; index >= 0; index -= 1) { - const message = input.messages[index]; - if (message?.role !== "user") continue; - if (owned.has(message.id)) return true; - if (classifyUserMessageIngress(message.text) === "teams") return false; - } - return true; -} - -/** Cap for the durable per-chain ownership memory persisted on Teams links. */ -const TEAMS_OWNED_USER_MESSAGE_ID_LIMIT = 64; - /** * User prompts this bot injected into T3 (Discord mention / bootstrap path). * Never mirror these back into Discord as "External User Input" — they originated here. @@ -2461,46 +2391,8 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( ), discardPersistedTips: freshWorkingTurn, }); - // Every user message this chain sent (resolved or not). `sentDiscordUserMessageIds` - // is pruned once a message lands in T3, so Teams turn ownership keeps its own memory. - const ownedUserMessageIds = new Set([ - ...(persistedLink?.sentDiscordUserMessageIds ?? []), - ...(input.sentDiscordUserMessageIds ?? []), - ]); - /** Per-snapshot Teams turn ownership (Discord always owns). */ - const turnOwnershipFor = (thread: OrchestrationThread) => { - const cache = new Map(); - return (turnId: string | null): boolean => { - if (rest.platform !== "teams") return true; - const cached = cache.get(turnId); - if (cached !== undefined) return cached; - const owns = teamsBridgeOwnsTurn({ - platform: rest.platform, - turnId, - messages: thread.messages, - ownedUserMessageIds, - }); - cache.set(turnId, owns); - return owns; - }; - }; - // Teams persists the owned tail (not just unresolved ids) so ownership survives restarts. - const persistTeamsOwnedUserMessageIds = () => - links.setSentDiscordUserMessageIds( - input.discordChannelId, - [...ownedUserMessageIds].slice(-TEAMS_OWNED_USER_MESSAGE_ID_LIMIT), - ); - if (rest.platform === "teams" && (input.sentDiscordUserMessageIds ?? []).length > 0) { - yield* persistTeamsOwnedUserMessageIds().pipe(Effect.ignore); - } - // The warm cache is keyed by T3 thread, so on Teams it holds whichever reply chain - // finalized last. Once a chain renders only its own turns, another chain's cursor - // would hide this chain's unfinalized answers; keep it only for legacy all-turn links. - const warmCacheLastFinalizedSeed = - rest.platform === "teams" && ownedUserMessageIds.size > 0 - ? null - : (warmCacheEntry?.lastFinalizedAssistantId ?? null); - const seedLastFinalized = persistedLink?.lastFinalizedAssistantId ?? warmCacheLastFinalizedSeed; + const seedLastFinalized = + persistedLink?.lastFinalizedAssistantId ?? warmCacheEntry?.lastFinalizedAssistantId ?? null; const stateRef = yield* Ref.make({ ...emptyState({ workingAckMessageId: freshWorkingTurn ? (input.workingAckMessageId ?? null) : null, @@ -2572,7 +2464,8 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( // Mutable watermark for trim + warm cache (updated on finalize). const deliveredMemoryTrim = { lastFinalizedAssistantId: (persistedLink?.lastFinalizedAssistantId ?? - warmCacheLastFinalizedSeed) as string | null, + warmCacheEntry?.lastFinalizedAssistantId ?? + null) as string | null, }; const projectThreadForDiscordMemory = (thread: OrchestrationThread): OrchestrationThread => trimOrchestrationThreadForDiscordMemory({ @@ -2669,17 +2562,7 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( Ref.update(stateRef, (current) => ({ ...current, sentDiscordUserMessageIds: uniqueMessageIds([...current.sentDiscordUserMessageIds, ...ids]), - })).pipe( - Effect.andThen( - rest.platform === "teams" - ? Effect.suspend(() => { - for (const id of ids) ownedUserMessageIds.add(id); - return persistTeamsOwnedUserMessageIds().pipe(Effect.ignore); - }) - : Effect.void, - ), - Effect.asVoid, - ); + })).pipe(Effect.asVoid); controlSlot.adoptWorkingAckMessageId = Effect.fn("adoptWorkingAckMessageId")((messageId) => Effect.gen(function* () { @@ -2922,9 +2805,7 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( ); const persistSentDiscordUserMessageIds = (ids: ReadonlyArray) => - rest.platform === "teams" - ? persistTeamsOwnedUserMessageIds() - : links.setSentDiscordUserMessageIds(input.discordChannelId, uniqueMessageIds(ids)); + links.setSentDiscordUserMessageIds(input.discordChannelId, uniqueMessageIds(ids)); const postExternalUserMessages = Effect.fn("ResponseBridge.postExternalUserMessages")(function* ( messages: ReadonlyArray, @@ -5426,24 +5307,12 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( const activeTurnId = thread.latestTurn?.turnId ?? null; const turnInProgressNow = isTurnInProgress(thread); - // Teams reply chains sharing this T3 thread render only their own turns. Skipping - // leaves this bridge's delivery state untouched for its next owned turn. - const ownsTurn = turnOwnershipFor(thread); - const ownsActiveTurn = ownsTurn(activeTurnId); - if (!ownsActiveTurn) { - yield* Effect.logDebug("Teams bridge skipping turn owned by another reply chain", { - discordChannelId: input.discordChannelId, - t3ThreadId: input.t3ThreadId, - turnId: activeTurnId, - }); - } // Interrupted session (Wake Required): convert open Working tips to a Continue notice // before catch-up finalize would treat partial stream as a finished answer. { const preWake = yield* Ref.get(stateRef); if ( - ownsActiveTurn && shouldConvertWorkingTipsToWakeUp({ sessionStatus: thread.session?.status ?? null, activeTurnId: thread.session?.activeTurnId ?? null, @@ -5480,21 +5349,15 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( prior.delivery.lastFinalizedAssistantId ?? durableLinkNow?.lastFinalizedAssistantId ?? persistedLink?.lastFinalizedAssistantId ?? - warmCacheLastFinalizedSeed; + warmCacheEntry?.lastFinalizedAssistantId ?? + null; const lastFinalizedTextForDelivery = prior.delivery.lastFinalizedText ?? null; - const allThreadMessagesForDelivery = thread.messages.map((message) => ({ + const threadMessagesForDelivery = thread.messages.map((message) => ({ id: message.id, role: message.role, turnId: message.turnId, text: message.text, })); - // Teams: other chains' answers are invisible to this bridge's catch-up and delivery. - const threadMessagesForDelivery = - rest.platform === "teams" - ? allThreadMessagesForDelivery.filter( - (message) => message.role !== "assistant" || ownsTurn(message.turnId), - ) - : allThreadMessagesForDelivery; const deliveryAssistants = assistantMessagesForDelivery({ messages: threadMessagesForDelivery, turnId: activeTurnId, @@ -5542,156 +5405,154 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( Effect.asVoid, ); } - if (ownsActiveTurn) { - const afterCatchUp = yield* Ref.get(stateRef); - const lastFinalizedAfterCatchUp = - afterCatchUp.delivery.lastFinalizedAssistantId ?? lastFinalizedForDelivery; - const lastFinalizedTextAfterCatchUp = - afterCatchUp.delivery.lastFinalizedText ?? lastFinalizedTextForDelivery; - const deliveryAssistantIds = new Set(deliveryAssistants.map((entry) => entry.id)); - const turnAssistants = thread.messages.filter( - (message) => message.role === "assistant" && deliveryAssistantIds.has(message.id), - ); - const images = turnAssistants.flatMap((message) => imageAttachmentsOf(message.attachments)); - const streaming = - turnInProgressNow || - (thread.latestTurn == null && - turnAssistants.some( - (message) => isAssistantStreaming(thread, message.id) || message.streaming === true, - )); - - const decision = decideAssistantDelivery({ - state: { - ...afterCatchUp.delivery, - // Keep durable finalize memory from the link store in sync. - lastFinalizedAssistantId: lastFinalizedAfterCatchUp, - lastFinalizedText: lastFinalizedTextAfterCatchUp, - }, - turnId: activeTurnId, - turnInProgress: turnInProgressNow, - assistants: deliveryAssistants.map((entry) => ({ - id: entry.id, - text: entry.text, - })), - messages: threadMessagesForDelivery, - streaming, - presentationFull: (input.presentationMode ?? "full") === "full", - // Idle catch-up (rehydrate *or* interactive recovery after a comment) often - // gets a single settled snapshot — do not stream the previous final under - // `_Working.._` + Stop waiting for a second settle tick that never arrives. - // Substantial answers also finalize immediately inside decideAssistantDelivery. - skipSettleGrace: !turnInProgressNow, - }); + const afterCatchUp = yield* Ref.get(stateRef); + const lastFinalizedAfterCatchUp = + afterCatchUp.delivery.lastFinalizedAssistantId ?? lastFinalizedForDelivery; + const lastFinalizedTextAfterCatchUp = + afterCatchUp.delivery.lastFinalizedText ?? lastFinalizedTextForDelivery; + const deliveryAssistantIds = new Set(deliveryAssistants.map((entry) => entry.id)); + const turnAssistants = thread.messages.filter( + (message) => message.role === "assistant" && deliveryAssistantIds.has(message.id), + ); + const images = turnAssistants.flatMap((message) => imageAttachmentsOf(message.attachments)); + const streaming = + turnInProgressNow || + (thread.latestTurn == null && + turnAssistants.some( + (message) => isAssistantStreaming(thread, message.id) || message.streaming === true, + )); + + const decision = decideAssistantDelivery({ + state: { + ...afterCatchUp.delivery, + // Keep durable finalize memory from the link store in sync. + lastFinalizedAssistantId: lastFinalizedAfterCatchUp, + lastFinalizedText: lastFinalizedTextAfterCatchUp, + }, + turnId: activeTurnId, + turnInProgress: turnInProgressNow, + assistants: deliveryAssistants.map((entry) => ({ + id: entry.id, + text: entry.text, + })), + messages: threadMessagesForDelivery, + streaming, + presentationFull: (input.presentationMode ?? "full") === "full", + // Idle catch-up (rehydrate *or* interactive recovery after a comment) often + // gets a single settled snapshot — do not stream the previous final under + // `_Working.._` + Stop waiting for a second settle tick that never arrives. + // Substantial answers also finalize immediately inside decideAssistantDelivery. + skipSettleGrace: !turnInProgressNow, + }); - yield* Effect.logInfo("Discord delivery decision", { - t3ThreadId: input.t3ThreadId, - turnId: activeTurnId, - intent: decision.intent._tag, - reason: - decision.intent._tag === "noop" || decision.intent._tag === "hold" - ? decision.intent.reason - : null, - phase: decision.state.phase, - epoch: decision.state.epoch, - settleReady: decision.state.settleReady, - deliveryAssistants: deliveryAssistants.length, - streaming, - turnInProgress: turnInProgressNow, - }); + yield* Effect.logInfo("Discord delivery decision", { + t3ThreadId: input.t3ThreadId, + turnId: activeTurnId, + intent: decision.intent._tag, + reason: + decision.intent._tag === "noop" || decision.intent._tag === "hold" + ? decision.intent.reason + : null, + phase: decision.state.phase, + epoch: decision.state.epoch, + settleReady: decision.state.settleReady, + deliveryAssistants: deliveryAssistants.length, + streaming, + turnInProgress: turnInProgressNow, + }); - // Apply non-terminal state before I/O; finalize commits only after successful post - // so a failed finalize can retry without being stuck in phase=finalized. - if (decision.intent._tag !== "finalize") { - // Late multi-bubble reopen: epoch left finalized → streaming/awaiting with a - // new assistant after lastFinalized. Clear bridge finalizedTurnId so stream / - // re-finalize is not treated as a no-op duplicate of the short status final. - const reopenedAfterPrematureFinal = - prior.delivery.phase === "finalized" && - (decision.state.phase === "streaming" || decision.state.phase === "awaiting"); - yield* Ref.update(stateRef, (current) => ({ - ...current, - delivery: decision.state, - adoptedInitialSnapshot: true, - seededWorkingAckPending: decision.state.phase === "awaiting", - finalizedTurnId: - decision.state.phase === "awaiting" || reopenedAfterPrematureFinal - ? null - : current.finalizedTurnId, - })); - } else { - yield* Ref.update(stateRef, (current) => ({ - ...current, - adoptedInitialSnapshot: true, - })); - } + // Apply non-terminal state before I/O; finalize commits only after successful post + // so a failed finalize can retry without being stuck in phase=finalized. + if (decision.intent._tag !== "finalize") { + // Late multi-bubble reopen: epoch left finalized → streaming/awaiting with a + // new assistant after lastFinalized. Clear bridge finalizedTurnId so stream / + // re-finalize is not treated as a no-op duplicate of the short status final. + const reopenedAfterPrematureFinal = + prior.delivery.phase === "finalized" && + (decision.state.phase === "streaming" || decision.state.phase === "awaiting"); + yield* Ref.update(stateRef, (current) => ({ + ...current, + delivery: decision.state, + adoptedInitialSnapshot: true, + seededWorkingAckPending: decision.state.phase === "awaiting", + finalizedTurnId: + decision.state.phase === "awaiting" || reopenedAfterPrematureFinal + ? null + : current.finalizedTurnId, + })); + } else { + yield* Ref.update(stateRef, (current) => ({ + ...current, + adoptedInitialSnapshot: true, + })); + } - if (decision.intent._tag === "stream") { - yield* postUserMessagesBefore(decision.intent.assistantId); - yield* postOrEditAssistant({ - turnId: decision.intent.turnId, - t3MessageId: decision.intent.assistantId, - text: decision.intent.text, - streaming: true, - images, - worktreePath: thread.worktreePath, - }).pipe(Effect.tapCause(alertStreamFailure("live-stream")), Effect.asVoid); - } else if (decision.intent._tag === "finalize") { - yield* postUserMessagesBefore(decision.intent.assistantId); + if (decision.intent._tag === "stream") { + yield* postUserMessagesBefore(decision.intent.assistantId); + yield* postOrEditAssistant({ + turnId: decision.intent.turnId, + t3MessageId: decision.intent.assistantId, + text: decision.intent.text, + streaming: true, + images, + worktreePath: thread.worktreePath, + }).pipe(Effect.tapCause(alertStreamFailure("live-stream")), Effect.asVoid); + } else if (decision.intent._tag === "finalize") { + yield* postUserMessagesBefore(decision.intent.assistantId); + yield* postOrEditAssistant({ + turnId: decision.intent.turnId, + t3MessageId: decision.intent.assistantId, + text: decision.intent.text, + streaming: false, + images, + worktreePath: thread.worktreePath, + }).pipe(Effect.tapCause(alertStreamFailure("finalize")), Effect.asVoid); + } else if ( + decision.intent._tag === "noop" && + decision.intent.reason === "settled-without-content" && + !prior.seededWorkingAckPending && + prior.delivery.phase !== "finalized" + ) { + // Prefer posting whatever we already streamed over wiping Working with silence. + const fallbackText = prior.lastAssistantText.trim(); + if (fallbackText !== "" && prior.t3AssistantMessageId !== null) { + yield* Effect.logInfo( + "Finalizing from last streamed body (settled without new content)", + { + t3ThreadId: input.t3ThreadId, + turnId: activeTurnId, + textLen: fallbackText.length, + }, + ); + yield* postUserMessagesBefore(prior.t3AssistantMessageId); yield* postOrEditAssistant({ - turnId: decision.intent.turnId, - t3MessageId: decision.intent.assistantId, - text: decision.intent.text, + turnId: activeTurnId, + t3MessageId: prior.t3AssistantMessageId, + text: fallbackText, streaming: false, - images, + images: [], worktreePath: thread.worktreePath, - }).pipe(Effect.tapCause(alertStreamFailure("finalize")), Effect.asVoid); - } else if ( - decision.intent._tag === "noop" && - decision.intent.reason === "settled-without-content" && - !prior.seededWorkingAckPending && - prior.delivery.phase !== "finalized" - ) { - // Prefer posting whatever we already streamed over wiping Working with silence. - const fallbackText = prior.lastAssistantText.trim(); - if (fallbackText !== "" && prior.t3AssistantMessageId !== null) { - yield* Effect.logInfo( - "Finalizing from last streamed body (settled without new content)", - { - t3ThreadId: input.t3ThreadId, - turnId: activeTurnId, - textLen: fallbackText.length, - }, - ); - yield* postUserMessagesBefore(prior.t3AssistantMessageId); - yield* postOrEditAssistant({ - turnId: activeTurnId, - t3MessageId: prior.t3AssistantMessageId, - text: fallbackText, - streaming: false, - images: [], - worktreePath: thread.worktreePath, - }).pipe(Effect.tapCause(alertStreamFailure("finalize-stream-fallback")), Effect.asVoid); - yield* Ref.update(stateRef, (current) => ({ - ...current, - delivery: { - ...current.delivery, - phase: "finalized" as const, - streamText: "", - settleReady: false, - finalizedAssistantId: prior.t3AssistantMessageId, - lastFinalizedAssistantId: prior.t3AssistantMessageId, - lastFinalizedText: fallbackText, - }, - seededWorkingAckPending: false, - lastAssistantText: "", - finalizedTurnId: activeTurnId, - })); - } else { - yield* clearInProgressMessages("settled-without-final-content").pipe( - Effect.catchCause(Effect.logError), - Effect.asVoid, - ); - } + }).pipe(Effect.tapCause(alertStreamFailure("finalize-stream-fallback")), Effect.asVoid); + yield* Ref.update(stateRef, (current) => ({ + ...current, + delivery: { + ...current.delivery, + phase: "finalized" as const, + streamText: "", + settleReady: false, + finalizedAssistantId: prior.t3AssistantMessageId, + lastFinalizedAssistantId: prior.t3AssistantMessageId, + lastFinalizedText: fallbackText, + }, + seededWorkingAckPending: false, + lastAssistantText: "", + finalizedTurnId: activeTurnId, + })); + } else { + yield* clearInProgressMessages("settled-without-final-content").pipe( + Effect.catchCause(Effect.logError), + Effect.asVoid, + ); } } } else { @@ -5710,9 +5571,7 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( seededWorkingAckPending: state.seededWorkingAckPending, state: summarizeBridgeStateForLog(state), }); - if (!ownsActiveTurn) { - // Another reply chain's turn: keep this chain's Working tip as-is. - } else if ( + if ( turnRunningNoAssistant && !state.seededWorkingAckPending && shouldPublishAssistantUpdate({ @@ -5762,7 +5621,7 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( // Deliver them through the normal final-message path so Working is removed and the // durable delivery receipt prevents duplicate notifications after reconnecting. const failureActivity = - ownsActiveTurn && thread.latestTurn?.state === "error" + thread.latestTurn?.state === "error" ? thread.activities.findLast((activity) => { if (activity.turnId !== activeTurnId || activity.tone !== "error") return false; const payload = activity.payload; @@ -5840,9 +5699,7 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( // Tasks first: first-class Discord progress UI from turn.plan (not External User Input). // Keep updating mid-turn / rehydrate; owned via taskDiscordMessageId so it never freezes Working. - const tasks = ownsActiveTurn - ? presentTasks(thread.activities, thread.latestTurn?.turnId ?? null) - : null; + const tasks = presentTasks(thread.activities, thread.latestTurn?.turnId ?? null); if (tasks !== null && input.presentationMode !== "final-only") { const content = formatTasksForDiscord(tasks); const key = `${tasks.explanation ?? ""}:${tasks.tasks.map((task) => `${task.status}:${task.step}`).join("|")}`; @@ -5852,17 +5709,13 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* ( ); } - const pending = derivePendingInteractions( - rest.platform === "teams" - ? thread.activities.filter((activity) => ownsTurn(activity.turnId)) - : thread.activities, - ); + const pending = derivePendingInteractions(thread.activities); const approvals = pending.filter( (entry): entry is PendingApproval => entry.kind === "approval", ); yield* postApprovals(approvals).pipe(Effect.catchCause(Effect.logError), Effect.asVoid); - if (ownsActiveTurn && thread.session?.status === "error" && thread.session.lastError) { + if (thread.session?.status === "error" && thread.session.lastError) { yield* rest .createMessage(input.discordChannelId, { content: `**T3 error:** ${thread.session.lastError}`, diff --git a/apps/discord-bot/src/features/TeamsNativeApp.ts b/apps/discord-bot/src/features/TeamsNativeApp.ts index 8039fff9e46aa..11c8d07f65726 100644 --- a/apps/discord-bot/src/features/TeamsNativeApp.ts +++ b/apps/discord-bot/src/features/TeamsNativeApp.ts @@ -33,7 +33,6 @@ import { BridgeHub } from "./BridgeHub.ts"; import { ThreadWarmCacheStore } from "../store/ThreadWarmCacheStore.ts"; import { BotResponseTransport } from "./BotResponseTransport.ts"; import { makeTeamsResponseTransport } from "../teams/ResponseTransport.ts"; -import { channelWeek, rememberChannelWeek } from "../teams/weeklyThreads.ts"; interface TeamsConversationCoordinates { readonly tenantId: string; @@ -489,16 +488,8 @@ export const runTeamsNativeApp = Effect.fn("runTeamsNativeApp")(function* ( return; } - const week = channelWeek({ - dataDir: config.dataDir, - tenantId: location.tenantId, - teamId: location.teamId, - channelId: location.channelId, - at: DateTime.toDateUtc(yield* DateTime.now), - }); const turn = yield* startOrContinueT3Turn(config, { source: { sourceKind: "teams", sourceThreadId: sourceKey }, - joinT3ThreadId: week?.joinT3ThreadId, sourceActor: { platformId: activity.from.aadObjectId ?? activity.from.id, displayName: access.person.name, @@ -513,7 +504,6 @@ export const runTeamsNativeApp = Effect.fn("runTeamsNativeApp")(function* ( stickyModelOnContinue: true, promptContext: { kind: "raw", value: prompt }, }); - yield* Effect.promise(() => rememberChannelWeek(week, turn)); const receivedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso)); const transport = makeTeamsResponseTransport({ diff --git a/apps/discord-bot/src/teams-gateway-main.ts b/apps/discord-bot/src/teams-gateway-main.ts index c29c7d0d11b7a..e718b59c1e967 100644 --- a/apps/discord-bot/src/teams-gateway-main.ts +++ b/apps/discord-bot/src/teams-gateway-main.ts @@ -11,7 +11,6 @@ import { BridgeHub } from "./features/BridgeHub.ts"; import { App } from "@microsoft/teams.apps"; import { NodeRuntime } from "@effect/platform-node"; import * as ConfigProvider from "effect/ConfigProvider"; -import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as ManagedRuntime from "effect/ManagedRuntime"; @@ -31,7 +30,6 @@ 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 { channelWeek, rememberChannelWeek } from "./teams/weeklyThreads.ts"; import { readGatewayConfig, readPrivateCredential } from "./teams/gatewayConfig.ts"; import { ingestTeamsGroupChat, teamsChannelPoster } from "./features/TeamsGroupChatObserver.ts"; import { mentionsTeamsRecipient, registerTeamsMessageEvents } from "./teams/messageEvents.ts"; @@ -548,16 +546,8 @@ const program = Effect.gen(function* () { ] .filter((part) => part.trim().length > 0) .join("\n\n"); - const week = channelWeek({ - dataDir: workspace.config.dataDir, - tenantId: lease.binding.tenantId, - teamId: lease.binding.teamId, - channelId: lease.binding.channelId, - at: DateTime.toDateUtc(yield* DateTime.now), - }); const turn = yield* startOrContinueT3Turn(workspace.config, { source: { sourceKind: "teams", sourceThreadId: sourceKey }, - joinT3ThreadId: week?.joinT3ThreadId, sourceActor: { platformId: lease.actorId }, externalConversationId: lease.conversationId, externalParentId: lease.binding.teamId + "/" + lease.binding.channelId, @@ -570,7 +560,6 @@ const program = Effect.gen(function* () { ...(images.uploads.length > 0 ? { attachments: images.uploads } : {}), promptContext: { kind: "raw", value: enriched }, }); - yield* Effect.promise(() => rememberChannelWeek(week, turn)); const transport = makeTeamsResponseTransport({ config: workspace.config, clientId: initial.identity.entraClientId, diff --git a/apps/discord-bot/src/teams/weeklyThreads.test.ts b/apps/discord-bot/src/teams/weeklyThreads.test.ts index 295727bef1498..a195e2c185207 100644 --- a/apps/discord-bot/src/teams/weeklyThreads.test.ts +++ b/apps/discord-bot/src/teams/weeklyThreads.test.ts @@ -1,16 +1,7 @@ -// @effect-diagnostics nodeBuiltinImport:off globalDate:off -import * as NodeFS from "node:fs"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; +// @effect-diagnostics globalDate:off +import { describe, expect, it } from "vite-plus/test"; -import { afterEach, describe, expect, it } from "vite-plus/test"; - -import { - channelWeek, - rememberChannelWeek, - teamsWeekBucket, - weeklyThreadKey, -} from "./weeklyThreads.ts"; +import { teamsWeekBucket, weeklyThreadKey } from "./weeklyThreads.ts"; describe("teamsWeekBucket", () => { it("names the Monday that starts the week", () => { @@ -29,70 +20,9 @@ describe("teamsWeekBucket", () => { expect(teamsWeekBucket(new Date("2027-01-01T09:00:00Z"))).toBe("week-2026-12-28"); }); - it("appends the bucket to a location key", () => { + 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", ); }); }); - -describe("channelWeek", () => { - const dirs: Array = []; - const dataDir = () => { - const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "teams-weekly-")); - dirs.push(dir); - return dir; - }; - afterEach(() => { - for (const dir of dirs.splice(0)) NodeFS.rmSync(dir, { recursive: true, force: true }); - }); - const at = new Date("2026-11-24T09:00:00Z"); - const channel = { tenantId: "t", teamId: "team", channelId: "ch" }; - - it("does not apply outside channels", () => { - expect( - channelWeek({ - dataDir: dataDir(), - tenantId: "t", - teamId: undefined, - channelId: undefined, - at, - }), - ).toBeNull(); - }); - - it("lets later reply chains join the thread the first chain opened this week", async () => { - const dir = dataDir(); - const first = channelWeek({ dataDir: dir, ...channel, at }); - expect(first?.joinT3ThreadId).toBeUndefined(); - await rememberChannelWeek(first, { threadId: "thread-1", isNew: true }); - - expect(channelWeek({ dataDir: dir, ...channel, at })?.joinT3ThreadId).toBe("thread-1"); - // A later chain opening its own thread (e.g. the week's thread was gone) keeps the first one. - await rememberChannelWeek(channelWeek({ dataDir: dir, ...channel, at }), { - threadId: "thread-2", - isNew: true, - }); - expect(channelWeek({ dataDir: dir, ...channel, at })?.joinT3ThreadId).toBe("thread-1"); - }); - - it("starts fresh next week and keeps channels apart", async () => { - const dir = dataDir(); - await rememberChannelWeek(channelWeek({ dataDir: dir, ...channel, at }), { - threadId: "thread-1", - isNew: true, - }); - const nextWeek = new Date("2026-12-01T09:00:00Z"); - expect(channelWeek({ dataDir: dir, ...channel, at: nextWeek })?.joinT3ThreadId).toBeUndefined(); - expect( - channelWeek({ dataDir: dir, ...channel, channelId: "other", at })?.joinT3ThreadId, - ).toBeUndefined(); - }); - - it("ignores continued threads", async () => { - const dir = dataDir(); - const week = channelWeek({ dataDir: dir, ...channel, at }); - await rememberChannelWeek(week, { threadId: "old-chain-thread", isNew: false }); - expect(channelWeek({ dataDir: dir, ...channel, at })?.joinT3ThreadId).toBeUndefined(); - }); -}); diff --git a/apps/discord-bot/src/teams/weeklyThreads.ts b/apps/discord-bot/src/teams/weeklyThreads.ts index 76c5f03df064c..451dc06d23b0e 100644 --- a/apps/discord-bot/src/teams/weeklyThreads.ts +++ b/apps/discord-bot/src/teams/weeklyThreads.ts @@ -1,12 +1,5 @@ -// @effect-diagnostics nodeBuiltinImport:off globalDate:off -import * as NodePath from "node:path"; - -import { readGroupChatMirror, rememberGroupChatMirror } from "./groupChats.ts"; - -/** - * A channel reply chain keeps its own T3 thread; a new top-level post joins the channel's thread - * for the week. Group chats roll over weekly. Weeks start Monday 00:00 in this time zone. - */ +// @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; @@ -36,70 +29,7 @@ export function teamsWeekBucket(at: Date, timeZone: string = TEAMS_THREAD_WEEK_T return `week-${monday.toISOString().slice(0, 10)}`; } -/** Appends the week bucket to a location key. */ +/** Appends the week bucket to a group chat's key. */ export function weeklyThreadKey(locationKey: string, at: Date): string { return `${locationKey}/${teamsWeekBucket(at)}`; } - -/** Key of a Teams channel, shared by every reply chain posted in it. */ -export function teamsChannelLocationKey(input: { - readonly tenantId: string; - readonly teamId: string; - readonly channelId: string; -}): string { - return `native/${input.tenantId}/${input.teamId}/${input.channelId}`; -} - -export function weeklyThreadsFile(dataDir: string): string { - return NodePath.join(dataDir, "teams-weekly-threads.json"); -} - -/** The T3 thread opened for a channel week, if any. */ -export function readWeeklyThread(filePath: string, weekKey: string): string | null { - return readGroupChatMirror(filePath, weekKey); -} - -export function rememberWeeklyThread( - filePath: string, - weekKey: string, - t3ThreadId: string, -): Promise { - return rememberGroupChatMirror(filePath, weekKey, t3ThreadId); -} - -export interface ChannelWeek { - readonly file: string; - readonly weekKey: string; - /** This week's thread for the channel, for a reply chain that has no link yet. */ - readonly joinT3ThreadId: string | undefined; -} - -/** Weekly thread for a channel message; `null` outside channels (personal and group chats). */ -export function channelWeek(input: { - readonly dataDir: string; - readonly tenantId: string; - readonly teamId: string | undefined; - readonly channelId: string | undefined; - readonly at: Date; -}): ChannelWeek | null { - if (!input.teamId || !input.channelId) return null; - const file = weeklyThreadsFile(input.dataDir); - const weekKey = weeklyThreadKey( - teamsChannelLocationKey({ - tenantId: input.tenantId, - teamId: input.teamId, - channelId: input.channelId, - }), - input.at, - ); - return { file, weekKey, joinT3ThreadId: readWeeklyThread(file, weekKey) ?? undefined }; -} - -/** Records a thread a channel reply chain just opened as that channel's thread for the week. */ -export async function rememberChannelWeek( - week: ChannelWeek | null, - turn: { readonly threadId: string; readonly isNew: boolean }, -): Promise { - if (week === null || !turn.isNew || readWeeklyThread(week.file, week.weekKey) !== null) return; - await rememberWeeklyThread(week.file, week.weekKey, turn.threadId); -} From 2c7b4da1d0bc6c827d26f7c6b79b0a0f4f57d3ff Mon Sep 17 00:00:00 2001 From: T3 Code PR Stack <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:55:46 +0100 Subject: [PATCH 4/4] fix(teams): look up missing group chat titles and log chats that aren't watched Watched group chats are matched by title, but Teams often leaves conversation.name off group chat activities, so those messages were dropped without a trace. The gateway now reads the chat topic from Graph when the title is missing (cached per chat), and logs each unwatched chat once with its title, where the title came from, and the Graph outcome. Co-Authored-By: Claude Opus 5.5 --- apps/discord-bot/src/teams-gateway-main.ts | 47 ++++++++++- .../src/teams/groupChatTitles.test.ts | 81 +++++++++++++++++++ apps/discord-bot/src/teams/groupChatTitles.ts | 80 ++++++++++++++++++ 3 files changed, 205 insertions(+), 3 deletions(-) create mode 100644 apps/discord-bot/src/teams/groupChatTitles.test.ts create mode 100644 apps/discord-bot/src/teams/groupChatTitles.ts 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; + }; +}