diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 418bd1083e..005cca9faa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -518,7 +518,7 @@ jobs: --volume "$(command -v bun):/usr/local/bin/bun:ro" \ --env OPENBOT_APP_BROWSER=1 --env OPENBOT_APP_ENGINES=chromium,webkit \ "$PLAYWRIGHT_IMAGE" \ - bun test --parallel="$TEST_WORKERS" --timeout="$TEST_TIMEOUT_MS" app/tests/chunk-recovery.test.tsx app/tests/composer-dictation-language.test.tsx app/tests/sidebar-zoom-drag.test.tsx app/tests/service-terms.test.tsx app/tests/move-to-cloud-settings.test.tsx app/tests/moved-elsewhere.test.tsx app/tests/home-no-answer.test.tsx app/tests/section-strip-routines.test.tsx app/tests/organization-members-remove.test.tsx app/tests/settings-tool-cards-admin-layout.test.tsx app/tests/settings-tool-cards-personal.test.tsx app/tests/add-custom-mcp-card-layout.test.tsx app/tests/settings-tool-cards-core.test.tsx app/tests/one-press-connect-layout.test.tsx app/tests/sign-in-reconnect-layout.test.tsx app/tests/admin-notion-one-press-layout.test.tsx app/tests/team-connections-directory-layout.test.tsx app/tests/conversation-switch.test.tsx app/tests/conversation-kept-browser.test.tsx app/tests/conversation-resume.test.tsx app/tests/conversation-return-running.test.tsx app/tests/member-rows-long-names.test.tsx app/tests/people-lists.test.tsx app/tests/organization-moving.test.tsx app/tests/organization-removed.test.tsx app/tests/organization-held-reload.test.tsx app/tests/organization-unavailable-pages.test.tsx app/tests/organization-held-actions.test.tsx app/tests/organization-unavailable-admin-pages.test.tsx app/tests/organization-held-recovery.test.tsx app/tests/bot-screen-sharp.test.tsx app/tests/bots-panel-start-conversation.test.tsx app/tests/table-export-browser.test.tsx app/tests/organization-unavailable-chat.test.tsx app/tests/too-many-follow-ups.test.tsx app/tests/moved-apps-reconnect.test.tsx app/tests/composer-keeps-draft-browser.test.tsx app/tests/conversation-reply-toolbar-layout.test.tsx app/tests/roster-working.test.tsx app/tests/delete-account-layout.test.tsx app/tests/composer-touch-return.test.tsx app/tests/bot-long-instructions-layout.test.tsx app/tests/web-push-browser.test.tsx app/tests/computer-panel-phone-layout.test.tsx app/tests/computer-starting-browser.test.tsx app/tests/browse-apps-pages.test.tsx app/tests/hand-back-row-layout.test.tsx app/tests/first-message-thinking.test.tsx app/tests/group-conversation-gutter.test.tsx app/tests/new-conversation-picked-model.test.tsx app/tests/renderer-crash.test.ts app/tests/home-holds-still.test.tsx app/tests/app-frame-skeleton-still.test.tsx app/tests/step-rows-layout.test.tsx app/tests/sign-in-returns-there.test.tsx app/tests/sign-in-with-apple-layout.test.tsx app/tests/stopped-command-layout.test.tsx + bun test --parallel="$TEST_WORKERS" --timeout="$TEST_TIMEOUT_MS" app/tests/chunk-recovery.test.tsx app/tests/composer-dictation-language.test.tsx app/tests/sidebar-zoom-drag.test.tsx app/tests/service-terms.test.tsx app/tests/move-to-cloud-settings.test.tsx app/tests/moved-elsewhere.test.tsx app/tests/home-no-answer.test.tsx app/tests/section-strip-routines.test.tsx app/tests/organization-members-remove.test.tsx app/tests/settings-tool-cards-admin-layout.test.tsx app/tests/settings-tool-cards-personal.test.tsx app/tests/add-custom-mcp-card-layout.test.tsx app/tests/settings-tool-cards-core.test.tsx app/tests/one-press-connect-layout.test.tsx app/tests/sign-in-reconnect-layout.test.tsx app/tests/admin-notion-one-press-layout.test.tsx app/tests/team-connections-directory-layout.test.tsx app/tests/conversation-switch.test.tsx app/tests/conversation-kept-browser.test.tsx app/tests/conversation-resume.test.tsx app/tests/conversation-return-running.test.tsx app/tests/reload-keeps-answer-browser.test.tsx app/tests/member-rows-long-names.test.tsx app/tests/people-lists.test.tsx app/tests/organization-moving.test.tsx app/tests/organization-removed.test.tsx app/tests/organization-held-reload.test.tsx app/tests/organization-unavailable-pages.test.tsx app/tests/organization-held-actions.test.tsx app/tests/organization-unavailable-admin-pages.test.tsx app/tests/organization-held-recovery.test.tsx app/tests/bot-screen-sharp.test.tsx app/tests/bots-panel-start-conversation.test.tsx app/tests/table-export-browser.test.tsx app/tests/organization-unavailable-chat.test.tsx app/tests/too-many-follow-ups.test.tsx app/tests/moved-apps-reconnect.test.tsx app/tests/composer-keeps-draft-browser.test.tsx app/tests/conversation-reply-toolbar-layout.test.tsx app/tests/roster-working.test.tsx app/tests/delete-account-layout.test.tsx app/tests/composer-touch-return.test.tsx app/tests/bot-long-instructions-layout.test.tsx app/tests/web-push-browser.test.tsx app/tests/computer-panel-phone-layout.test.tsx app/tests/computer-starting-browser.test.tsx app/tests/browse-apps-pages.test.tsx app/tests/hand-back-row-layout.test.tsx app/tests/first-message-thinking.test.tsx app/tests/group-conversation-gutter.test.tsx app/tests/new-conversation-picked-model.test.tsx app/tests/renderer-crash.test.ts app/tests/home-holds-still.test.tsx app/tests/app-frame-skeleton-still.test.tsx app/tests/step-rows-layout.test.tsx app/tests/sign-in-returns-there.test.tsx app/tests/sign-in-with-apple-layout.test.tsx app/tests/stopped-command-layout.test.tsx # Connect your AI's sign-in code, copied with one press and read back from WebKit's clipboard. # Only that test: the rest of the file runs in Chromium in the job above. - run: | diff --git a/app/src/components/channels/channel-chat.tsx b/app/src/components/channels/channel-chat.tsx index b83b445361..def36f307b 100644 --- a/app/src/components/channels/channel-chat.tsx +++ b/app/src/components/channels/channel-chat.tsx @@ -200,6 +200,17 @@ import { newId } from "../../lib/new-id"; */ const JOIN_DEADLINE_MS = 1500; +/** One join's gate (`joinSettled`): open once that join has replayed the thread, or given up. */ +type JoinedGate = { promise: Promise; open: () => void }; + +function joinedGate(): JoinedGate { + let open: () => void = () => {}; + const promise = new Promise((resolve) => { + open = resolve; + }); + return { promise, open }; +} + /** * How long the runtime is given to say whether a turn the roster reports can still be heard, before * the join is ended. Shorter than a quiet run's ask: the conversation shows nothing while it waits. @@ -808,15 +819,30 @@ export function ChannelChat({ /** * Opened once the join has replayed the thread, or given up, and before history is read. Every * read of the store waits for it; see `pull` below. + * + * ONE GATE PER JOIN, AND THE WAIT IS FOR THE NEWEST. The join below can run more than once as + * the conversation opens: in development React runs it twice on mount (StrictMode, main.tsx), and + * the conversation's agent is kept and ready at once (`useKeptAgent`), so both runs join the + * thread; the agent changing, or OpenBot answering again (`joins`), runs it again too. The first + * join, given up for the second, is over at once, and a gate it opened let a read through before + * the second had replayed the thread. FOUND BY THE STOCK AG-UI APPROVAL JOURNEY, reloaded a moment + * after the Bot answered: the sidebar's list arrived and its read merged the whole stored history + * onto the agent; the second join's replay then rebuilt the agent from the thread's first run and + * was cut at its deadline before the second, which held the answer; and the opening's own read had + * been taken over by the list's, so nothing read the store again. The answer was on screen for half + * a second, then gone until the conversation was opened again. Each join now has a gate of its own, + * and `joinSettled` waits until the newest join's gate is open. */ - const openJoined = useRef<() => void>(() => {}); - const joinedGate = useRef | null>(null); - if (joinedGate.current === null) { - joinedGate.current = new Promise((resolve) => { - openJoined.current = resolve; - }); - } - const joinedPromise = joinedGate.current; + const joined = useRef(null); + if (joined.current === null) joined.current = joinedGate(); + const joinSettled = useCallback(async () => { + for (;;) { + const gate = joined.current; + if (!gate) return; + await gate.promise; + if (joined.current === gate) return; + } + }, []); /** Promise gate so messages typed before runtime readiness wait instead of being discarded. */ const openReadyGate = useRef<() => void>(() => {}); @@ -961,7 +987,7 @@ export function ChannelChat({ // Just made here: nothing to join or read, and the first message is not held for it (`fresh`). // Asked again when OpenBot answers again (`joins`), it is joined as any conversation is. if (fresh && joins === 0) { - openJoined.current(); + joined.current?.open(); openJoinGate.current(); return; } @@ -976,7 +1002,7 @@ export function ChannelChat({ */ if (liveJoin(agent)) { setRestoring(false); - openJoined.current(); + joined.current?.open(); openJoinGate.current(); void joinsEnded(agent).then(() => { if (current) setJoins((count) => count + 1); @@ -986,6 +1012,12 @@ export function ChannelChat({ }; } const version = ++historyReadVersion.current; + // This join's own gate: reads wait for this join, not one an earlier run of this effect made + // (`joinSettled`). Whoever waits on the earlier gate is let through once this one opens. + const previousGate = joined.current; + const gate = joinedGate(); + joined.current = gate; + if (previousGate) void gate.promise.then(previousGate.open); // Before the connect: it is handed the subscribers the agent has when it starts. const lastRun = followLastRun(agent); /* @@ -1121,7 +1153,7 @@ export function ChannelChat({ joinOver = true; // The stored copy stays up until the history below is on the agent: see `earlyHistory`. if (current) setReplaying(false); - openJoined.current(); + gate.open(); } /* * The turn the join was kept for had ended without a word reaching here: say so, unless the @@ -1424,7 +1456,7 @@ export function ChannelChat({ * reload. The roster can announce a Bot's turn at any moment, the moment the conversation * opens included, so every read waits for the join to be over. */ - await joinedPromise; + await joinSettled(); // Nor while a run of a turn going on in a chat that closed is joined: see `rejoining`. await rejoining.current; if (!isCurrent()) return; @@ -1569,7 +1601,7 @@ export function ChannelChat({ channel.id, channel.threadId, joinGatePromise, - joinedPromise, + joinSettled, runtimeAgentId, historyShare, ]); @@ -1587,7 +1619,7 @@ export function ChannelChat({ const off = onRunStartedAway(channel.id, () => { const previous = rejoining.current; rejoining.current = (async () => { - await joinedPromise; + await joinSettled(); await previous; const target = agentRef.current; if (!current || turnsRef.current > 0 || target.isRunning) return; @@ -1602,7 +1634,7 @@ export function ChannelChat({ current = false; off(); }; - }, [channel.id, copilotkit, joinedPromise]); + }, [channel.id, copilotkit, joinSettled]); // Tool calls from this conversation act on this coworker's own computer. useActiveBot(runtimeAgentId); @@ -1856,7 +1888,7 @@ export function ChannelChat({ let current = true; void (async () => { // After the conversation has joined its thread: a run going then streams in through that join. - await joinedPromise; + await joinSettled(); while (current && carriedByServerRef.current) { const target = agentRef.current; // This tab's own turn follows the server's runs itself (`deliver`), and a join is a run. @@ -1883,7 +1915,7 @@ export function ChannelChat({ return () => { current = false; }; - }, [carriedByServer, isReady, channel.id, copilotkit, joinedPromise]); + }, [carriedByServer, isReady, channel.id, copilotkit, joinSettled]); /** * Tell the roster what was just said. Failures here must not block the conversation. diff --git a/app/tests/reload-keeps-answer-browser.test.tsx b/app/tests/reload-keeps-answer-browser.test.tsx new file mode 100644 index 0000000000..5411243f2d --- /dev/null +++ b/app/tests/reload-keeps-answer-browser.test.tsx @@ -0,0 +1,382 @@ +import { afterAll, beforeAll, describe, expect } from "bun:test"; +import { mkdirSync } from "node:fs"; +import { join } from "node:path"; +import type { Browser, BrowserType, Page } from "playwright-core"; +import { getGetBotResponseMock } from "@/lib/api/generated/bots/bots.msw"; +import { personBody } from "./accounts-api"; +import { approvalInboxResponse } from "./approvals-api"; +import { botGrantsBody } from "./bot-grants-api"; +import { test } from "./renderer-crash"; + +/** + * A conversation reloaded a moment after its Bot answered an approved change keeps the answer, in a + * real browser. The same race as reload-keeps-answer.test.tsx, found by the stock AG-UI approval + * journey: the page joins its thread twice as it opens (StrictMode, in development), the sidebar's + * list arrives and reads the store before the second join has replayed anything, and that join's + * replay is cut at its deadline after the thread's first run. The answer was on screen for half a + * second, then gone. + * + * OPENBOT_APP_BROWSER=1 bun test app/tests/reload-keeps-answer-browser.test.tsx + * + * Chromium by default, as CI has it. OPENBOT_APP_ENGINES=chromium,webkit adds WebKit. With + * OPENBOT_APP_SHOTS= the page is saved as reload-keeps-answer--.png. + */ +const asked = process.env.OPENBOT_APP_BROWSER === "1"; +const shots = process.env.OPENBOT_APP_SHOTS; +const engines = (process.env.OPENBOT_APP_ENGINES ?? "chromium") + .split(",") + .map((engine) => engine.trim()) + .filter((engine) => engine === "chromium" || engine === "webkit") as ( + | "chromium" + | "webkit" +)[]; + +const ORGANIZATION = "/api/v2/organizations/default"; +const THREAD = "seed-thread"; +const TOPIC = `thread:${THREAD}`; +const ASKED = + "Place an order at the Fernhill Seed Shop for 2 packets of Moonglow tomato, then tell me the order number."; +const ORDER_NUMBER = "FS-61907"; +const ANSWER = `I placed the order for 2 packets of Moonglow tomato. The order number is ${ORDER_NUMBER}.`; +const TOOL = "mcp__fernhill-seed-shop__place_seed_order"; +const ARGS = JSON.stringify({ variety: "Moonglow tomato", packets: 2 }); + +const user = { id: "asked", role: "user", content: ASKED }; +const step = { + id: "step", + role: "assistant", + content: "", + toolCalls: [ + { + id: "call-1", + type: "function", + function: { name: TOOL, arguments: ARGS }, + }, + ], +}; +const granted = { + id: "granted-tools:seed-bot", + role: "system", + content: "You can use these apps for the person you are working with.", +}; +const result = { + id: "approval:request-1", + role: "tool", + toolCallId: "call-1", + content: "Ran: the app made this change. Do not make it again.", +}; +const answer = { id: "answer", role: "assistant", content: ANSWER }; + +function event(run: string, seq: number, fields: Record) { + return { + ...fields, + threadId: THREAD, + thread_id: THREAD, + runId: run, + run_id: run, + metadata: { cpki_event_id: `${run}-${seq}`, cpki_event_seq: seq }, + }; +} +/** The run that asked for the change and stopped for approval. */ +const FIRST_RUN = [ + event("run-1", 1, { + type: "RUN_STARTED", + input: { threadId: THREAD, runId: "run-1", messages: [user] }, + }), + event("run-1", 2, { + type: "TOOL_CALL_START", + toolCallId: "call-1", + toolCallName: TOOL, + parentMessageId: "step", + }), + event("run-1", 3, { + type: "TOOL_CALL_ARGS", + toolCallId: "call-1", + delta: ARGS, + }), + event("run-1", 4, { type: "TOOL_CALL_END", toolCallId: "call-1" }), + event("run-1", 5, { + type: "MESSAGES_SNAPSHOT", + messages: [granted, user, step], + }), + event("run-1", 6, { type: "RUN_FINISHED" }), +]; +/** The run after Allow once: the change made, and the answer. */ +const SECOND_RUN = [ + event("run-2", 1, { + type: "RUN_STARTED", + input: { threadId: THREAD, runId: "run-2", messages: [granted, result] }, + }), + event("run-2", 2, { + type: "TEXT_MESSAGE_START", + messageId: "answer", + role: "assistant", + }), + event("run-2", 3, { + type: "TEXT_MESSAGE_CONTENT", + messageId: "answer", + delta: ANSWER, + }), + event("run-2", 4, { type: "TEXT_MESSAGE_END", messageId: "answer" }), + event("run-2", 5, { + type: "MESSAGES_SNAPSHOT", + messages: [granted, user, step, result, answer], + }), + event("run-2", 6, { type: "RUN_FINISHED" }), +]; + +const BOT = { + ...getGetBotResponseMock().bot, + id: "seed-bot", + name: "Fernhill Scout", + mine: true, + canManage: true, + systemOwned: false, + visibility: "private" as const, + hidden: false, + builtIn: false, + endpoint: null, + framework: "LangChain", +}; + +let port = 0; +let server: ReturnType | undefined; +const sleep = (milliseconds: number) => + new Promise((resolve) => setTimeout(resolve, milliseconds)); + +function answerApi(path: string): Response | undefined { + const json = (body: unknown, status = 200) => Response.json(body, { status }); + if (path === "/api/copilotkit/info") + return json({ + version: "fixture", + agents: { "seed-bot": { description: "Fixture", capabilities: {} } }, + mode: "intelligence", + intelligence: { wsUrl: `ws://127.0.0.1:${port}/client` }, + telemetryDisabled: true, + }); + if (/\/agent\/seed-bot\/connect$/.test(path)) + return json({ + threadId: THREAD, + runId: null, + joinToken: "join-token", + realtime: { clientUrl: `ws://127.0.0.1:${port}/client`, topic: TOPIC }, + }); + if (/\/conversations\/[^/]+\/join-tokens$/.test(path)) + return json( + { + joinToken: "join-token", + expiresAt: new Date(Date.now() + 30_000).toISOString(), + threadId: THREAD, + runId: null, + realtime: { clientUrl: `ws://127.0.0.1:${port}/client`, topic: TOPIC }, + }, + 201, + ); + if (path === `${ORGANIZATION}/bots`) + return json({ bots: [BOT], nextCursor: null }); + if (/\/bots\/[^/]+\/grants$/.test(path)) return json(botGrantsBody()); + if (/\/bots\/[^/]+\/components$/.test(path)) + return json({ components: [], nextCursor: null }); + if (/\/bots\/[^/]+$/.test(path)) return json({ bot: BOT }); + if (path === `${ORGANIZATION}/people/me/capabilities`) + return json({ capabilities: {}, enforced: false }); + if (path === `${ORGANIZATION}/people/me`) + return json({ + person: personBody({ + id: "dana", + name: "Dana Reyes", + email: "dana.reyes@northwind.example", + role: "admin", + }), + openbotVersion: "v1.2.4", + }); + if (path === `${ORGANIZATION}/deployment`) + return json({ + generativeUi: true, + selfHostBanner: false, + localEvaluation: false, + edition: "team", + authProviders: [], + ssoConfigured: false, + ssoRequired: false, + }); + const approvals = approvalInboxResponse(path, { + enabled: true, + requests: [], + rules: [], + teamRules: [], + questions: [], + }); + if (approvals) return approvals; + if (/\/conversations\/[^/]+\/(activity|signal-busy|mark-read)$/.test(path)) + return new Response(null, { status: 204 }); + if (/\/conversations\/[^/]+\/voice-sessions$/.test(path)) + return json({ sessions: [], nextCursor: null }); + if (/\/threads\/[^/]+\/messages$/.test(path)) + return json({ messages: [user, step, granted, result, answer] }); + return undefined; +} + +/** + * What the gateway sends a join of the thread: the first run a moment later, and the second only + * after the join's deadline, as a replay running slow does. + */ +async function replay(send: (name: string, payload: unknown) => void) { + await sleep(400); + for (const one of FIRST_RUN) send("ag_ui_event", one); + await sleep(2_500); + for (const one of SECOND_RUN) send("ag_ui_event", one); + send("replay_complete", { latestEventId: "run-2-6" }); + send("stream_idle", { latestEventId: "run-2-6" }); +} + +/** The fixture, bundled for the browser in development, where StrictMode runs effects twice. */ +async function bundle(): Promise { + const built = await Bun.build({ + entrypoints: [join(import.meta.dir, "reload-keeps-answer.fixture.tsx")], + target: "browser", + define: { "process.env.NODE_ENV": JSON.stringify("development") }, + plugins: [ + { + name: "no-marks", + setup(build) { + build.onResolve({ filter: /^@\/lib\/marks$/ }, () => ({ + path: "marks", + namespace: "no-marks", + })); + build.onLoad({ filter: /.*/, namespace: "no-marks" }, () => ({ + contents: "export const markFor = () => null;", + loader: "js", + })); + }, + }, + ], + }); + if (!built.success) throw new AggregateError(built.logs, "bundle failed"); + const script = built.outputs.find((output) => output.kind === "entry-point"); + if (!script) throw new Error("bundle has no entry point"); + return script.text(); +} + +let script = ""; +const browsers = new Map(); + +function reply(url: URL): Response { + if (url.pathname === "/conversation.js") + return new Response(script, { + headers: { "content-type": "text/javascript" }, + }); + if (url.pathname.startsWith("/api/")) + return ( + answerApi(url.pathname) ?? + Response.json({ detail: "Not found." }, { status: 404 }) + ); + return new Response( + `
`, + { headers: { "content-type": "text/html" } }, + ); +} + +beforeAll(async () => { + if (!asked) return; + server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch(request, bun) { + if (request.headers.get("upgrade") === "websocket") + return bun.upgrade(request, { data: {} }) + ? undefined + : new Response("upgrade failed", { status: 400 }); + return reply(new URL(request.url)); + }, + websocket: { + message(socket, message) { + const [joinRef, ref, topic, name] = JSON.parse(String(message)) as [ + string | null, + string | null, + string, + string, + unknown, + ]; + socket.send( + JSON.stringify([ + joinRef, + ref, + topic, + "phx_reply", + { status: "ok", response: {} }, + ]), + ); + if (name !== "phx_join" || topic !== TOPIC) return; + void replay((event, payload) => { + if (socket.readyState === 1) + socket.send(JSON.stringify([joinRef, null, topic, event, payload])); + }); + }, + }, + }); + port = server.port ?? 0; + script = await bundle(); + const playwright = await import("playwright-core"); + for (const engine of engines) { + const type: BrowserType = playwright[engine]; + browsers.set( + engine, + // The CI job installs full Chromium without the headless shell. + await type.launch(engine === "chromium" ? { channel: "chromium" } : {}), + ); + } +}, 120_000); + +afterAll(async () => { + for (const browser of browsers.values()) await browser.close(); + server?.stop(true); +}); + +/** The conversation's words as drawn. */ +async function words(page: Page): Promise { + return (await page.locator("main").innerText()).replace(/\s+/g, " "); +} + +async function shoot(page: Page, load: string, engine: string) { + if (!shots) return; + mkdirSync(shots, { recursive: true }); + await page.screenshot({ + path: join(shots, `reload-keeps-answer-${load}-${engine}.png`), + }); +} + +describe.skipIf(!asked)( + "a conversation reloaded a moment after its Bot answered", + () => { + for (const engine of engines) + test(`keeps the answer, in ${engine}`, async () => { + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const page = await browser.newPage({ + viewport: { width: 1280, height: 800 }, + reducedMotion: "reduce", + }); + page.on("pageerror", (error) => console.error(error)); + try { + for (const load of ["opened", "reloaded"]) { + if (load === "opened") await page.goto(`http://127.0.0.1:${port}/`); + else await page.reload(); + // Past the join's deadline and the reads after it, the answer is there, and stays. + await page + .getByText(ORDER_NUMBER) + .first() + .waitFor({ timeout: 15_000 }); + await sleep(5_000); + await shoot(page, load, engine); + const shown = await words(page); + console.log(`[${engine}, ${load}] ${shown.slice(0, 240)}`); + expect(shown).toContain(ORDER_NUMBER); + expect(shown).toContain(ASKED); + } + } finally { + await page.close(); + } + }, 90_000); + }, +); diff --git a/app/tests/reload-keeps-answer.fixture.tsx b/app/tests/reload-keeps-answer.fixture.tsx new file mode 100644 index 0000000000..7278120c69 --- /dev/null +++ b/app/tests/reload-keeps-answer.fixture.tsx @@ -0,0 +1,93 @@ +import { CopilotKitProvider } from "@copilotkit/react-core/v2"; +import { type InfiniteData, QueryClientProvider } from "@tanstack/react-query"; +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { ChannelChat } from "@/components/channels/channel-chat"; +import { TooltipProvider } from "@/components/ui/tooltip"; +import { + type AuthenticatedUser, + currentUserQueryOptions, +} from "@/lib/auth/queries"; +import { + type AgentChannel, + type ChannelPage, + channelKeys, +} from "@/lib/channels/queries"; +import { ActiveBotProvider } from "@/lib/copilot/active-bot"; +import { setCurrentOrganization } from "@/lib/organizations/current"; +import { queryClient } from "@/query-client"; + +/** + * One conversation, opened as a page reloaded a moment after its Bot answered, for + * reload-keeps-answer-browser.test.tsx to bundle and load in a browser. Drawn as the app is + * (main.tsx), under StrictMode, so in development each effect runs twice as it mounts. The sidebar's + * list of conversations arrives a moment after the conversation is drawn, as after a reload, with + * the Bot's answer as this conversation's last line. What the server and the gateway answer comes + * from the test. + */ +setCurrentOrganization("default"); + +const CONVERSATION: AgentChannel = { + id: "seed-order", + name: "Fernhill Scout", + agentIds: ["seed-bot"], + threadId: "seed-thread", + active: true, + lastMessageAt: "2026-12-01T05:46:50.000Z", +}; + +const DANA: AuthenticatedUser = { + id: "dana", + email: "dana.reyes@northwind.example", + name: "Dana Reyes", + role: "admin", + onboarding: null, + openbotVersion: "v1.2.4", + providers: [], +}; +queryClient.setQueryData(currentUserQueryOptions().queryKey, DANA); +queryClient.setQueryDefaults(channelKeys.list(), { staleTime: Infinity }); + +const ANSWER_LINE = + "I placed the order for 2 packets of Moonglow tomato. The order number is FS-61907."; + +// The sidebar's list, a moment after the conversation is drawn. +setTimeout(() => { + queryClient.setQueryData>(channelKeys.list(), { + pages: [ + { + channels: [ + { + ...CONVERSATION, + summary: "Seed order", + lastMessage: ANSWER_LINE, + lastMessageAgentId: "seed-bot", + createdAt: "2026-12-01T05:45:00.000Z", + pinned: false, + lastReadAt: null, + }, + ], + nextCursor: null, + }, + ], + pageParams: [""], + }); +}, 150); + +const root = document.getElementById("root"); +if (root) + createRoot(root).render( + + + + + +
+ +
+
+
+
+
+
, + ); diff --git a/app/tests/reload-keeps-answer.test.tsx b/app/tests/reload-keeps-answer.test.tsx new file mode 100644 index 0000000000..8b68ef03be --- /dev/null +++ b/app/tests/reload-keeps-answer.test.tsx @@ -0,0 +1,358 @@ +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; +import { CopilotKitProvider } from "@copilotkit/react-core/v2"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { type InfiniteData, QueryClientProvider } from "@tanstack/react-query"; +import { act, cleanup, render, waitFor } from "@testing-library/react"; +import { StrictMode } from "react"; +import { ChannelChat } from "@/components/channels/channel-chat"; +import { + type AgentChannel, + type ChannelPage, + type ChannelSummary, + channelKeys, +} from "@/lib/channels/queries"; +import { forgetAgents } from "@/lib/copilot/kept-agents"; +import { queryClient } from "@/query-client"; +import { MY_CAPABILITIES_PATH } from "./admin-settings-api"; +import { approvalInboxResponse } from "./approvals-api"; +import { botGrantsPath, botGrantsResponse } from "./bot-grants-api"; +import { answerBotsList, botPath } from "./bots-api"; +import { botComponentsPath, botComponentsResponse } from "./components-api"; + +/* + * A CONVERSATION RELOADED A MOMENT AFTER ITS BOT ANSWERED KEEPS THE ANSWER. + * + * Found by the stock AG-UI approval journey (backend e2e, `stock-agui-langgraph-langchain`), about two + * runs in seven: a person allowed a Bot's change, the Bot answered with the order number, and the page + * was reloaded at once. The answer showed for half a second and was gone, leaving the person's message + * and the approved step, until the conversation was opened again. + * + * What happened, read from the page's own log in that journey: the conversation joined its thread + * twice as it opened, as the app is drawn under StrictMode (main.tsx) and in development React runs + * each effect twice on mount, and its agent is kept and ready at once (`useKeptAgent`). The first + * join, given up for the second, was over at once and opened the gate every read of the store waits + * on. The sidebar's list then arrived, its line for this conversation the Bot's answer, and its read + * merged the whole stored history onto the agent before the second join had replayed anything. That + * join's replay then rebuilt the agent from the thread's first run (the person's message and the step + * waiting for approval) and was cut at its deadline before the second run, which carried the answer. + * And the opening's own read after it had been taken over by the list's, so nothing read the store + * again. + * + * The real provider, ChannelChat, its history reader and the AG-UI reducer, joining through a + * stand-in for the Intelligence gateway's realtime protocol, as channel-join-replay does. The thread + * is the journey's in shape: a first run that asks for the change and stops for approval, and a + * second, after Allow once, that runs it and answers. + */ + +type ChannelCache = InfiniteData; +type Frame = [string | null, string | null, string, string, unknown]; +const NativeResponse = globalThis.Response; +const NativeWebSocket = globalThis.WebSocket; +const BOT = "reload-bot"; +const THREAD = "reload-thread"; +const channel: AgentChannel = { + id: "reload-channel", + name: "Seed order", + agentIds: [BOT], + threadId: THREAD, + active: true, + lastMessageAt: "2026-12-01T05:46:40.000Z", +}; +const TOPIC = `thread:${THREAD}`; + +const ASKED = + "Place an order at the Fernhill Seed Shop for 2 packets of Moonglow tomato, then tell me the order number."; +const ANSWER = + "I placed the order for 2 packets of Moonglow tomato. The order number is FS-61907."; +const TOOL = "mcp__fernhill-seed-shop__place_seed_order"; +const ARGS = JSON.stringify({ variety: "Moonglow tomato", packets: 2 }); +const RAN = "Ran: the app made this change. Do not make it again."; + +const user = { id: "asked", role: "user", content: ASKED }; +const step = { + id: "step", + role: "assistant", + content: "", + toolCalls: [ + { + id: "call-1", + type: "function", + function: { name: TOOL, arguments: ARGS }, + }, + ], +}; +const granted = { + id: `granted-tools:${BOT}`, + role: "system", + content: "You can use these apps for the person you are working with.", +}; +const result = { + id: "approval:request-1", + role: "tool", + toolCallId: "call-1", + content: RAN, +}; +const answer = { id: "answer", role: "assistant", content: ANSWER }; + +function event(run: string, seq: number, fields: Record) { + return { + ...fields, + threadId: THREAD, + thread_id: THREAD, + runId: run, + run_id: run, + metadata: { cpki_event_id: `${run}-${seq}`, cpki_event_seq: seq }, + }; +} + +/** The first run: the change asked for, and the run stopped for the person's approval. */ +const FIRST_RUN = [ + event("run-1", 1, { + type: "RUN_STARTED", + input: { threadId: THREAD, runId: "run-1", messages: [user] }, + }), + event("run-1", 2, { + type: "TOOL_CALL_START", + toolCallId: "call-1", + toolCallName: TOOL, + parentMessageId: "step", + }), + event("run-1", 3, { + type: "TOOL_CALL_ARGS", + toolCallId: "call-1", + delta: ARGS, + }), + event("run-1", 4, { type: "TOOL_CALL_END", toolCallId: "call-1" }), + event("run-1", 5, { + type: "MESSAGES_SNAPSHOT", + messages: [granted, user, step], + }), + event("run-1", 6, { type: "RUN_FINISHED" }), +]; +/** The second run, after Allow once: the change made, and the Bot's answer. */ +const SECOND_RUN = [ + event("run-2", 1, { + type: "RUN_STARTED", + input: { threadId: THREAD, runId: "run-2", messages: [granted, result] }, + }), + event("run-2", 2, { + type: "TEXT_MESSAGE_START", + messageId: "answer", + role: "assistant", + }), + event("run-2", 3, { + type: "TEXT_MESSAGE_CONTENT", + messageId: "answer", + delta: ANSWER, + }), + event("run-2", 4, { type: "TEXT_MESSAGE_END", messageId: "answer" }), + event("run-2", 5, { + type: "MESSAGES_SNAPSHOT", + messages: [granted, user, step, result, answer], + }), + event("run-2", 6, { type: "RUN_FINISHED" }), +]; +/** The thread as the store holds it once the Bot has answered. */ +const STORED = [user, step, granted, result, answer]; + +/** What the gateway does on the browser's nth join of the thread. */ +let script: ( + send: (event: string, payload: unknown) => void, + join: number, +) => Promise = async () => {}; +let joins = 0; +let gateway: ReturnType; +let originalFetch: typeof fetch; + +beforeAll(() => { + gateway = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch(request, server) { + return server.upgrade(request, { data: undefined }) + ? undefined + : new NativeResponse("upgrade failed", { status: 400 }); + }, + websocket: { + message(socket, message) { + const [joinRef, ref, topic, name] = JSON.parse( + String(message), + ) as Frame; + const send = (event: string, payload: unknown) => { + if (socket.readyState === 1) + socket.send(JSON.stringify([joinRef, null, TOPIC, event, payload])); + }; + socket.send( + JSON.stringify([ + joinRef, + ref, + topic, + "phx_reply", + { status: "ok", response: {} }, + ]), + ); + if (name === "phx_join" && topic === TOPIC) { + joins += 1; + void script(send, joins); + } + }, + }, + }); + GlobalRegistrator.register({ url: "http://localhost/" }); + globalThis.WebSocket = NativeWebSocket; + originalFetch = globalThis.fetch; + globalThis.fetch = Object.assign( + async (input: Parameters[0], init?: RequestInit) => { + const url = new URL( + typeof input === "string" + ? input + : input instanceof URL + ? input.href + : input.url, + "http://localhost", + ); + const bots = answerBotsList(url, init, { visible: [] }); + if (bots) return bots; + if (url.pathname === botGrantsPath(BOT)) return botGrantsResponse(); + if (url.pathname === botPath(BOT)) + return NativeResponse.json({ + bot: { id: BOT, visibility: "public", canManage: true }, + }); + if (url.pathname === botComponentsPath(BOT)) + return botComponentsResponse(); + if (url.pathname === MY_CAPABILITIES_PATH) + return NativeResponse.json({ capabilities: {}, enforced: false }); + const approvals = approvalInboxResponse(url.pathname, { + enabled: true, + requests: [], + rules: [], + teamRules: [], + questions: [], + }); + if (approvals) return approvals; + if (url.pathname.endsWith("/info")) + return NativeResponse.json({ + version: "fixture", + agents: { [BOT]: { description: "Fixture", capabilities: {} } }, + mode: "intelligence", + intelligence: { wsUrl: `ws://127.0.0.1:${gateway.port}/client` }, + telemetryDisabled: true, + }); + if (/\/conversations\/[^/]+\/join-tokens$/.test(url.pathname)) + return NativeResponse.json( + { + joinToken: "join-token", + expiresAt: new Date(Date.now() + 30_000).toISOString(), + threadId: THREAD, + runId: null, + realtime: { + clientUrl: `ws://127.0.0.1:${gateway.port}/client`, + topic: TOPIC, + }, + }, + { status: 201 }, + ); + if (url.pathname.endsWith(`/agent/${BOT}/connect`)) + return NativeResponse.json({ + threadId: THREAD, + runId: null, + joinToken: "join-token", + realtime: { + clientUrl: `ws://127.0.0.1:${gateway.port}/client`, + topic: TOPIC, + }, + }); + if ( + /^\/api\/v2\/organizations\/default\/conversations\/[^/]+\/(activity|signal-busy|mark-read)$/.test( + url.pathname, + ) + ) + return new NativeResponse(null, { status: 204 }); + if ( + /^\/api\/v2\/organizations\/default\/conversations\/[^/]+\/voice-sessions$/.test( + url.pathname, + ) + ) + return NativeResponse.json({ sessions: [], nextCursor: null }); + if (/\/threads\/[^/]+\/messages$/.test(url.pathname)) + return NativeResponse.json({ messages: STORED }); + throw new Error(`Unexpected fixture request: ${url.pathname}`); + }, + { + preconnect() { + throw new Error("Unexpected fixture preconnect"); + }, + }, + ); +}); +afterEach(() => { + cleanup(); + forgetAgents(); + queryClient.clear(); + joins = 0; +}); +afterAll(() => { + globalThis.fetch = originalFetch; + GlobalRegistrator.unregister(); + gateway.stop(true); +}); + +const sleep = (milliseconds: number) => + act(() => new Promise((resolve) => setTimeout(resolve, milliseconds))); + +/** The roster, holding this conversation, with the Bot's answer as its latest line once `answered`. */ +function roster(at: string, text: string) { + const summary: ChannelSummary = { + ...channel, + summary: null, + lastMessage: text, + lastMessageAgentId: BOT, + lastMessageAt: at, + createdAt: "2026-12-01T05:45:00.000Z", + pinned: false, + lastReadAt: null, + }; + queryClient.setQueryData(channelKeys.list(), { + pages: [{ channels: [summary], nextCursor: null }], + pageParams: [""], + }); +} + +test("a conversation reloaded a moment after its Bot answered an approved change keeps the answer", async () => { + script = async (send) => { + // The join: the first run a moment later, and the second only after the join's deadline, as a + // replay running slow does. + await new Promise((resolve) => setTimeout(resolve, 400)); + for (const replayed of FIRST_RUN) send("ag_ui_event", replayed); + await new Promise((resolve) => setTimeout(resolve, 2_500)); + for (const replayed of SECOND_RUN) send("ag_ui_event", replayed); + send("replay_complete", { latestEventId: "run-2-6" }); + send("stream_idle", { latestEventId: "run-2-6" }); + }; + // As the app is drawn (main.tsx): in development React runs each effect twice as it mounts, so + // the conversation joins its thread twice as it opens, the first join given up for the second. + const view = render( + + + + + + + , + ); + // The sidebar's list of conversations arrives while the conversation's join is on its way, its + // line for this one the Bot's answer, which reads the store. + await sleep(150); + await act(async () => roster("2026-12-01T05:46:50.000Z", ANSWER)); + + // Past the second join's deadline, and the reads after it: the answer is on screen, and stays. + await sleep(4_000); + await waitFor( + () => expect(view.container.textContent ?? "").toContain("FS-61907"), + { + timeout: 4_000, + }, + ); + await sleep(2_000); + expect(view.container.textContent ?? "").toContain("FS-61907"); +}, 30_000);