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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions apps/discord-bot/src/features/LinkedTurnRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ export interface TransportNeutralLinkedTurnInput {
readonly stickyModelOnContinue?: boolean | undefined;
readonly attachments?: ReadonlyArray<UploadChatAttachment> | undefined;
readonly promptContext?: LinkedTurnInput["promptContext"];
/** T3 title for a new thread; otherwise it is cut from the prompt. */
readonly title?: string | undefined;
}

/** Preserve the requester on every dispatch; the server keeps the first thread origin. */
Expand Down Expand Up @@ -214,6 +216,7 @@ export const startOrContinueT3Turn = Effect.fn("startOrContinueT3Turn")(function
const { threadId, messageId } = yield* t3.startTurnWithWorktree({
project: resolved.project,
prompt: enrichedPrompt,
...(input.title === undefined ? {} : { titleSeed: input.title }),
modelSelection,
interactionMode: input.flags.plan ? "plan" : "default",
...launchWorkspaceFields(workspace),
Expand Down
31 changes: 31 additions & 0 deletions apps/discord-bot/src/features/ResponseBridge.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { MessageId, TurnId, type VcsStatusResult } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { isWeeklyGroupChatSourceKey } from "../teams/weeklyThreads.ts";

import {
activeStreamTipIdsForDelivery,
Expand Down Expand Up @@ -1576,6 +1577,36 @@ describe("rewriteInlinePathCodeSpansForDiscord", () => {
});

describe("externalUserMessagesToEcho", () => {
it("leaves gateway observations out of a weekly Teams group-chat log, and only there", () => {
const user = (id: string, text: string, channel: "teams" | "web") => ({
id: MessageId.make(id),
role: "user" as const,
text,
turnId: null,
streaming: false,
createdAt: "2026-11-27T00:00:00.000Z",
updatedAt: "2026-11-27T00:00:00.000Z",
source: { channel },
});
const messages = [
user("observed", "This Teams group chat is passive. Do not send a message…", "teams"),
user("web", "check the scanner logs too", "web"),
];
const echoed = (teamsGroupChatLog: boolean) =>
externalUserMessagesToEcho({
messages,
observedInitialUserSnapshot: true,
seenUserMessageIds: [],
sentDiscordUserMessageIds: [],
teamsGroupChatLog,
}).map((message) => message.id);
const weekly = "native/tenant/group/19:chat@thread.v2/week-2026-11-23";
expect(isWeeklyGroupChatSourceKey(weekly)).toBe(true);
expect(isWeeklyGroupChatSourceKey("native/tenant/team/19:c@thread.tacv2/conv")).toBe(false);
expect(echoed(true)).toEqual(["web"]);
expect(echoed(false)).toEqual(["observed", "web"]);
});

it("includes unseen user messages from other clients", () => {
const messages = externalUserMessagesToEcho({
messages: [
Expand Down
7 changes: 7 additions & 0 deletions apps/discord-bot/src/features/ResponseBridge.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";
import { type IntegrationThreadView as OrchestrationThread } from "@t3tools/shared/integrationThreadView";
import { isWeeklyGroupChatSourceKey } from "../teams/weeklyThreads.ts";
// @effect-diagnostics anyUnknownInErrorContext:off missingEffectContext:off globalFetchInEffect:off unknownInEffectCatch:off nodeBuiltinImport:off
import * as NodeCrypto from "node:crypto";
import * as NodeFSP from "node:fs/promises";
Expand Down Expand Up @@ -1275,13 +1276,16 @@ export function externalUserMessagesToEcho(input: {
readonly observedInitialUserSnapshot: boolean;
readonly seenUserMessageIds: ReadonlyArray<string>;
readonly sentDiscordUserMessageIds: ReadonlyArray<string>;
/** Weekly Teams group-chat log: the gateway already posted each observation as a clean line. */
readonly teamsGroupChatLog?: boolean;
}): ReadonlyArray<OrchestrationThread["messages"][number]> {
if (!input.observedInitialUserSnapshot) return [];
const seen = new Set(input.seenUserMessageIds);
const sentByDiscord = new Set(input.sentDiscordUserMessageIds);
return input.messages.filter(
(message) =>
message.role === "user" &&
!(input.teamsGroupChatLog === true && message.source?.channel === "teams") &&
shouldEchoUserMessageToDiscord({
text: message.text,
messageId: message.id,
Expand Down Expand Up @@ -5262,6 +5266,9 @@ export const runBridge = Effect.fn("ResponseBridge.runBridge")(function* (
observedInitialUserSnapshot: priorState.observedInitialUserSnapshot,
seenUserMessageIds: priorState.seenUserMessageIds,
sentDiscordUserMessageIds: priorState.sentDiscordUserMessageIds,
teamsGroupChatLog:
persistedLink?.sourceKind === "teams" &&
isWeeklyGroupChatSourceKey(persistedLink.sourceThreadId),
});
const pendingEchoIds = new Set<string>(unseenExternalUserMessages.map((message) => message.id));
const unresolvedSentDiscordUserMessageIds = priorState.sentDiscordUserMessageIds.filter(
Expand Down
127 changes: 121 additions & 6 deletions apps/discord-bot/src/features/TeamsGroupChatObserver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@ import { T3Session, type T3SessionService } from "../t3/T3Session.ts";
import type { GroupChatRule } from "../teams/groupChats.ts";
import { parseOmegentLinkMarker } from "./linkMarker.ts";
import {
ensureTeamsMirrorLink,
groupChatPlaceholderThreadId,
ingestTeamsGroupChat,
type TeamsChannelPoster,
type TeamsMirrorTurn,
} from "./TeamsGroupChatObserver.ts";

const rules: ReadonlyArray<GroupChatRule> = [
Expand All @@ -48,7 +50,10 @@ const message = (text: string) => ({
mentionedBot: false,
});

function makeHarness() {
function makeHarness(
chatRules: ReadonlyArray<GroupChatRule> = rules,
base: { readonly title?: string | undefined } = {},
) {
return Effect.gen(function* () {
const directory = yield* Effect.acquireRelease(
Effect.promise(() => NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "group-chat-observer-"))),
Expand All @@ -71,6 +76,8 @@ function makeHarness() {
discordPosts: [] as Array<{ channelId: string; content: string }>,
mirrorThreads: 0,
mirrorReplies: [] as Array<string>,
titles: [] as Array<string | undefined>,
bridged: [] as Array<TeamsMirrorTurn>,
};
const state = { discordFails: false, mirrorFails: false, t3Fails: false, t3FailsOnce: false };
const projectId = ProjectId.make("project:scanner");
Expand All @@ -83,13 +90,14 @@ function makeHarness() {
serverConfig: () =>
Effect.succeed({ settings: DEFAULT_SERVER_SETTINGS, newProjectsRoot: "/projects" }),
shell: () => Effect.succeed({ threads: [] }),
startTurnWithWorktree: () =>
startTurnWithWorktree: (input: { readonly titleSeed?: string }) =>
state.t3Fails || state.t3FailsOnce
? Effect.sync(() => {
state.t3FailsOnce = false;
}).pipe(Effect.andThen(Effect.fail(new Error("T3 down"))))
: Effect.sync(() => {
calls.t3Starts += 1;
calls.titles.push(input.titleSeed);
return { threadId: ThreadId.make("thread:weekly"), messageId: "message:1" };
}),
startTurn: () =>
Expand Down Expand Up @@ -127,9 +135,21 @@ function makeHarness() {
const ingest = (text: string, withDiscord = true, t3Retries = 0) =>
Effect.gen(function* () {
const runtime = yield* Effect.context<never>();
return yield* ingestTeamsGroupChat(config, rules, [], runtime, message(text), poster, {
t3RetrySchedule: Schedule.recurs(t3Retries),
});
return yield* ingestTeamsGroupChat(
config,
chatRules,
[],
runtime,
{ ...message(text), ...base },
poster,
{
t3RetrySchedule: Schedule.recurs(t3Retries),
bridgeMirror: (turn) =>
Effect.sync(() => {
calls.bridged.push(turn);
}),
},
);
}).pipe(
(effect) => (withDiscord ? Effect.provideService(effect, DiscordREST, rest) : effect),
Effect.provideService(ThreadLinkStore, links),
Expand All @@ -144,7 +164,12 @@ function makeHarness() {
expect(all).toHaveLength(1);
return all[0]!;
});
return { calls, state, ingest, links, weeklyLink };
const ensureMirrorLink = (turn: TeamsMirrorTurn) =>
ensureTeamsMirrorLink(turn).pipe(
Effect.provideService(ThreadLinkStore, links),
Effect.provideService(T3Session, session),
);
return { calls, state, ingest, links, weeklyLink, ensureMirrorLink };
});
}

Expand Down Expand Up @@ -248,3 +273,93 @@ describe("Teams group chat observer failure isolation", () => {
}).pipe(Effect.scoped),
);
});

describe("Teams group chat mirror delivery", () => {
it.effect("streams each weekly T3 turn into the Teams mirror thread", () =>
Effect.gen(function* () {
const { calls, ingest, weeklyLink } = yield* makeHarness();
yield* ingest("Der Scanner bucht nicht.");
yield* ingest("Immer noch nicht.");
const link = yield* weeklyLink;
expect(calls.bridged).toEqual([
{
mirror: rules[0]!.mirror,
conversationId: "19:mirror@thread.tacv2;messageid=77",
sourceKey: link.sourceThreadId,
t3ThreadId: "thread:weekly",
messageId: "message:1",
},
expect.objectContaining({
conversationId: "19:mirror@thread.tacv2;messageid=77",
t3ThreadId: "thread:weekly",
messageId: "message:n",
}),
]);
}).pipe(Effect.scoped),
);

it.effect("does not stream when the chat has no mirror thread", () =>
Effect.gen(function* () {
const { calls, ingest } = yield* makeHarness([
{ titleIncludes: "MAKO", projectShortName: "scanner" },
]);
yield* ingest("Der Scanner bucht nicht.");
expect(calls.t3Starts).toBe(1);
expect(calls.mirrorThreads).toBe(0);
expect(calls.bridged).toEqual([]);
}).pipe(Effect.scoped),
);

it.effect(
"keeps one delivery link per mirror thread, whether a turn or a mention ensures it",
() =>
Effect.gen(function* () {
const { calls, ingest, links, ensureMirrorLink } = yield* makeHarness();
yield* ingest("Der Scanner bucht nicht.");
const turn = calls.bridged[0]!;
yield* ensureMirrorLink(turn);
yield* links.setInfoDiscordMessageId(turn.conversationId, "info-card", "fingerprint");
// A later mention in the mirror thread ensures the same conversation and T3 thread.
yield* ensureMirrorLink(turn);
const all = yield* links.list();
expect(all).toHaveLength(2);
const mirrorLink = yield* links.getByDiscordThreadId(turn.conversationId);
expect(mirrorLink?.t3ThreadId).toBe("thread:weekly");
expect(mirrorLink?.infoDiscordMessageId).toBe("info-card");
// The weekly key still resolves to the Discord thread's link.
const weekly = yield* links.getBySourceThread("teams", turn.sourceKey);
expect(weekly?.discordThreadId).toMatch(/^\d+$/u);
}).pipe(Effect.scoped),
);
});

describe("Teams group chat names and channels", () => {
it.effect("names the T3 thread after the chat and week, not the passive prompt", () =>
Effect.gen(function* () {
const { calls, ingest } = yield* makeHarness();
yield* ingest("Der Scanner bucht nicht.");
expect(calls.titles[0]).toMatch(/^Teams: MAKO Scanner · week \d{4}-\d{2}-\d{2}$/u);
}).pipe(Effect.scoped),
);

it.effect("uses the rule's title and Discord channel when Teams sends no chat title", () =>
Effect.gen(function* () {
const { calls, ingest, weeklyLink } = yield* makeHarness(
[
{
conversationId: "19:chat@thread.v2",
projectShortName: "scanner",
title: "Easy Life Scanner",
discordChannelId: "1345512665602330664",
},
],
{ title: undefined },
);
yield* ingest("Der Scanner bucht nicht.");
expect(calls.discordPosts[0]).toMatchObject({ channelId: "1345512665602330664" });
expect(calls.discordPosts[0]?.content).toContain("**Easy Life Scanner**");
expect(calls.titles[0]).toMatch(/^Teams: Easy Life Scanner · week /u);
expect((yield* weeklyLink).channelId).toBe("1345512665602330664");
}).pipe(Effect.scoped),
);
});
Loading
Loading