diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3452be1743..c2f5be03a3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -858,6 +858,8 @@ jobs: app/tests/plan-notices-layout.test.tsx app/tests/question-answer-prompt-browser.test.tsx app/tests/queue-send-now-layout.test.tsx + app/tests/queued-send-busy-browser.test.tsx + app/tests/queued-send-locked-browser.test.tsx app/tests/reached-as-the-person-browser.test.tsx app/tests/reconnecting-line-layout.test.tsx app/tests/rejoin-fresh-token-browser.test.tsx diff --git a/app/src/components/channels/channel-chat.tsx b/app/src/components/channels/channel-chat.tsx index 96bce59f3b..1d64c54bde 100644 --- a/app/src/components/channels/channel-chat.tsx +++ b/app/src/components/channels/channel-chat.tsx @@ -175,6 +175,7 @@ import { stoppedReason, TURN_CUT_OFF, TURN_INTERRUPTED, + threadBusy, } from "@/lib/copilot/stopped-turn"; import { HISTORY_READ_CEILING_MS, @@ -1955,6 +1956,27 @@ export function ChannelChat({ * does, and the box is left empty: handed back with Send ready, it only asked to be refused again. */ const turnRefused = useRef(false); + /** + * THE TURN'S FIRST RUN WAS REFUSED BECAUSE THE CONVERSATION STILL HAD A RUN GOING (`threadBusy`). + * + * Nothing ran, so nothing is said and nothing is kept: `deliver` takes the message off the screen + * and throws `StillWorkingError`, and the message waits as queued, faded, with Remove, until the + * conversation is free, then goes by itself. This is how Claude Code, GitHub Copilot's SDK, Codex + * and Open WebUI treat a message sent while a turn is still going. + * + * FOUND ON OPENBOT CLOUD, 2026-12-05. Send now stopped a turn and sent the queued message the + * moment the turn ended here, while a run on the server, carrying the stopped turn on, held the + * conversation for six seconds. The person read "Thread is locked" under their message, the + * message stayed on screen as if sent, and a second copy waited as queued; removing that copy left + * the first looking sent. + */ + const lockRefused = useRef(false); + /** + * Ask the server whether a run is still going before the next turn is sent: after a Stop, and + * after a run was refused because one was. A run still going is waited for with the message + * queued, and the message is never drawn as sent in between. + */ + const askFreeFirst = useRef(false); /** * The run going now already said why it failed, in its RUN_ERROR. The runtime's client then fails * the run as well (`onRunFailed`, carrying the same words), which for a turn still counted here @@ -2451,6 +2473,7 @@ export function ChannelChat({ setRunError(null); turnFailure.current = null; turnRefused.current = false; + lockRefused.current = false; stoppedHere.current = false; // A Stop from here on is this turn's: it ends any run of the server's the turn follows. const stops = stopEpoch.current; @@ -2894,6 +2917,20 @@ export function ChannelChat({ watching.unsubscribe(); setRunsInFlight((count) => count - 1); } + /* + * REFUSED BECAUSE A RUN WAS STILL GOING: nothing ran, so the message was never part of the + * conversation. It comes off the screen, and the throw parks it as queued to go again by itself + * once the conversation is free (`conversation-view.tsx`). See `lockRefused`. + */ + if (lockRefused.current) { + lockRefused.current = false; + awaitingReply.current = false; + askFreeFirst.current = true; + target.setMessages( + target.messages.filter((message) => existingMessageIds.has(message.id)), + ); + throw new StillWorkingError(); + } if (!started && turnFailure.current === null && awaitingReply.current) { awaitingReply.current = false; // It never left this browser, so it is not part of the conversation: the words go back in the box. @@ -2958,6 +2995,20 @@ export function ChannelChat({ .join("\n\n"); }; + /** + * Whether the conversation is free for the next message: at once, unless a Stop or a refused run + * left a run that may still be going on the server, when the server is asked (`askFreeFirst`). + * A server that can't be asked counts as free, so a message is never held for want of an answer. + */ + const freeToSend = (): boolean | Promise => { + if (!askFreeFirst.current) return true; + return askRunGoing(channel.id).then((going) => { + if (going.liveness === "live") return false; + askFreeFirst.current = false; + return true; + }); + }; + /** * Send a user turn through the channel, including activity reporting and history repair. * @@ -2989,6 +3040,22 @@ export function ChannelChat({ // Its own kind, so a drained queue tries again once the Bot is free (`StillWorkingError`). throw new StillWorkingError(); } + /* + * AFTER A STOP, OR A RUN REFUSED BECAUSE ONE WAS GOING, THE SERVER IS ASKED FIRST. A stopped run + * can go on for a while on the server before it lets go of the conversation, and a message sent + * into that is refused. Asked first, the message waits as queued and is never drawn as sent in + * between. A server that can't be asked is no reason to hold it: it goes. + */ + if (askFreeFirst.current) { + if (!(await freeToSend())) throw new StillWorkingError(); + if ( + turnsRef.current > 0 || + agentRef.current.isRunning || + turnsGoingAway(channel.id) > 0 || + carriedByServerRef.current + ) + throw new StillWorkingError(); + } const turn = {}; turnTokens.current.add(turn); @@ -3105,6 +3172,11 @@ export function ChannelChat({ // Seen failing here is read, though the roster never hears of it (mark-read.ts). runEndedIn(channel.id); runErrorSaid.current = true; + // Refused because a run was still going: the turn's message waits and goes again (`lockRefused`). + if (threadBusy(event) && awaitingReply.current) { + lockRefused.current = true; + return; + } fail( stoppedReason(event?.message), true, @@ -3115,6 +3187,14 @@ export function ChannelChat({ ); }, onRunFailed: ({ error }) => { + // The turn's first run refused because a run was still going: said nowhere (`lockRefused`). + if ( + threadBusy(error) && + (awaitingReply.current || lockRefused.current) + ) { + lockRefused.current = true; + return; + } /* * Not the Bot failing: the run's stream reached this browser out of shape, in any run of a * turn going here. The turn reads it back from the thread once its runs are over (`deliver`). @@ -3302,6 +3382,8 @@ export function ChannelChat({ awaitingReply.current = false; stoppedHere.current = true; stopEpoch.current++; + // The stopped run may hold the conversation on the server for a moment yet (`askFreeFirst`). + askFreeFirst.current = true; copilotkit.stopAgent({ agent }); /* * A TURN THE SERVER IS CARRYING ON IS STOPPED WHEREVER IT IS. Between one run and the next no run @@ -3312,11 +3394,27 @@ export function ChannelChat({ const carried = channel.work?.find( (entry) => isTurnWork(entry) && entry.key !== stoppedCarried, ); - if (!carried || !agent.threadId) return; - setStoppedCarried(carried.key); const routed = (agent as { runtimeAgentId?: string }).runtimeAgentId ?? agent.agentId; - if (!routed) return; + if (!routed || !agent.threadId) return; + /* + * AND A RUN GOING HERE IS STOPPED ON THE SERVER'S ROUTE TOO, not only on the socket. The server + * takes a person's turn to carry the moment its run answers a step itself, and a Stop that reached + * only the run let the server carry the turn on in a run of its own. FOUND ON OPENBOT CLOUD, + * 2026-12-05: the Bot went on to answer the message the person had just stopped, and that run + * held the conversation while their next message was refused. The route takes the turn off the + * server's queue. Nothing is said when it answers badly here: the run itself was stopped above. + * + * Only where the Stop above went over the socket: through the backend's event store, CopilotKit's + * agent hands its runs to an Intelligence agent of its own (`delegate`, `@copilotkit/core` 1.88) + * and stops it with `stop_run` alone. Over the plain event stream its Stop is this route already. + */ + if (!carried) { + if ((agent as { delegate?: unknown }).delegate) + void stopCarriedTurn(routed, agent.threadId).catch(() => undefined); + return; + } + setStoppedCarried(carried.key); // The runtime's refusal is written for a program ("Thread access denied"): a person reads theirs. stopCarriedTurn(routed, agent.threadId).catch(() => { setStoppedCarried((stopped) => @@ -3475,6 +3573,8 @@ export function ChannelChat({ } agents={toAgentOptions(agentProfiles, channel.agentIds)} channelId={channel.id} + // What waits as queued goes once the conversation is free (`askFreeFirst`). + freeToSend={freeToSend} // An unsent reply stays with this conversation when somebody looks at another one. draftKey={`conversation:${channel.id}`} composerOpening={composerOpenings} diff --git a/app/src/components/channels/conversation-view.tsx b/app/src/components/channels/conversation-view.tsx index d4b653bb83..bdb85c262c 100644 --- a/app/src/components/channels/conversation-view.tsx +++ b/app/src/components/channels/conversation-view.tsx @@ -39,6 +39,8 @@ import { newId } from "../../lib/new-id"; /** How soon a drain the Bot was still too busy for goes again. Nothing is sent while it waits. */ export const STILL_WORKING_RETRY_MS = 500; +/** The longest a waiting message goes between tries, however long the Bot stays busy. */ +export const STILL_WORKING_RETRY_MAX_MS = 4_000; export function ConversationView({ messages, @@ -66,6 +68,7 @@ export function ConversationView({ reconnecting = false, stoppable, queueWhileBusy = false, + freeToSend, restoring = false, readOnly = false, kept = false, @@ -165,6 +168,13 @@ export function ConversationView({ * moving it onto this composer or asking for it upstream, and neither is a queue. */ queueWhileBusy?: boolean; + /** + * Whether the conversation is free for the next message, asked before what is queued goes: + * `true` or `false` when the answer is known here, a promise when the server has to be asked + * (after a Stop, while the stopped run may still be going there). Answered `false`, the queue + * stays as it is, on screen with Remove, and is tried again shortly. Without it, it goes. + */ + freeToSend?: () => boolean | Promise; /** History has been asked for and has not arrived. Drawn as placeholder rows; see `ChatTranscript`. */ restoring?: boolean; /** @@ -373,6 +383,27 @@ export function ConversationView({ * server, so it is not held back: it goes again on this tick, until the Bot is free. */ const [busyRetry, setBusyRetry] = useState(0); + /** + * How many tries in a row the Bot was too busy for. Each one waits twice as long as the last, up + * to `STILL_WORKING_RETRY_MAX_MS`: a try may ask the server whether a run is still going, and a + * run the server is still letting go of can take a while. Back to none once a send goes. + */ + const busyTries = useRef(0); + /** + * Not before this, the next try: the turn that was refused ending must not send again at once, + * which went round as fast as the server answered. `busyRetry` brings the drain back then. + */ + const tryNotBefore = useRef(0); + const tryAgainSoon = useCallback(() => { + const wait = Math.min( + STILL_WORKING_RETRY_MS * 2 ** busyTries.current, + STILL_WORKING_RETRY_MAX_MS, + ); + busyTries.current += 1; + // A few milliseconds short, so the timer that brings the drain back is never turned away. + tryNotBefore.current = Date.now() + wait - 10; + setTimeout(() => setBusyRetry((tick) => tick + 1), wait); + }, []); const restoreFailedRun = useCallback( (messages: readonly QueuedMessage[], error?: unknown) => { if (messages.length === 0) { @@ -383,19 +414,24 @@ export function ConversationView({ // true by the moment the queue is non-empty again rather than one statement later. heldBack.current = !stillWorking; apply({ messages, type: "restore" }); - if (stillWorking) - setTimeout( - () => setBusyRetry((tick) => tick + 1), - STILL_WORKING_RETRY_MS, - ); + if (stillWorking) tryAgainSoon(); }, - [apply], + [apply, tryAgainSoon], ); + /** Read through a ref, so a caller's inline function does not re-run the drain effect. */ + const freeToSendRef = useRef(freeToSend); + freeToSendRef.current = freeToSend; + /** A drain asking `freeToSend` and not answered yet: one ask at a time. */ + const askingFree = useRef(false); + /** `inFlight` and `disabled` as of now, for a drain that goes once the server has answered. */ + const nowIdle = useRef(true); + nowIdle.current = !(pending || running) && !disabled; const start = async (draft: ComposerDraft) => { setRunning(true); try { await onSubmit(draft); + busyTries.current = 0; } finally { setRunning(false); } @@ -410,16 +446,49 @@ export function ConversationView({ */ const submit = useCallback( (draft: ComposerDraft, whileBusy: boolean) => { + const id = newId(); const next = apply({ busy: whileBusy, draft, - id: newId(), + id, type: "submit", }); if (!next.run) { return undefined; } - const started = startRef.current(next.run); + const run = next.run; + const started = startRef.current(run); + /* + * A SEND THE BOT WAS STILL TOO BUSY FOR IS PARKED, NOT HANDED BACK. Nothing was sent: the Bot + * still had the turn here, or the server still had a run going. The words wait as queued, + * with Remove, and go by themselves once the Bot is free. Handed back to the box, they waited + * for the person to send them again, which no other assistant asks of anybody. + * + * With the queue they joined, in the order they were typed. The live draft carries what of + * its files the join kept. + */ + const live: QueuedMessage = { + attachments: draft.attachments.filter((attachment) => + run.attachments.includes(attachment), + ), + commandIds: [...draft.commandIds], + id, + text: draft.text, + }; + const parkWhenBusy = started.catch((error: unknown) => { + if (!(error instanceof StillWorkingError)) throw error; + restoreFailedRun( + [ + ...next.restoreIfRunFails, + ...(live.text.trim() || + live.commandIds.length > 0 || + live.attachments.length > 0 + ? [live] + : []), + ], + error, + ); + }); /* * A SEND THAT TOOK THE QUEUE WITH IT AND THEN FAILED LEAVES THE PARKED HALF HELD BY NOBODY, * which is the same shape the drain effect below answers, and with the same line. @@ -434,18 +503,20 @@ export function ConversationView({ * on the transition that emptied it. Restoring the composer's own as well would queue a * second copy of the words that are back in somebody's box. * - * `started` IS WHAT GOES BACK TO THE COMPOSER, not the promise this `catch` derives from it. - * The composer needs the rejection to restore the words, so the failure must still be its to - * handle; the derived promise exists only to hang the restore off, is settled by the `catch` - * itself, and is deliberately dropped. + * `parkWhenBusy` IS WHAT GOES BACK TO THE COMPOSER. It rejects as `started` does for every + * failure but a busy one, so the composer still restores the words of a send that failed; a + * busy one is parked above and resolves, so the box stays clear. The promise below exists + * only to hang the restore off, is settled by its own `catch`, and is deliberately dropped. */ if (next.restoreIfRunFails.length > 0) { const carried = next.restoreIfRunFails; void started.catch((error: unknown) => { + // Parked whole with the live draft, above. + if (error instanceof StillWorkingError) return; restoreFailedRun(carried, error); }); } - return started; + return parkWhenBusy; }, [apply, restoreFailedRun], ); @@ -616,7 +687,37 @@ export function ConversationView({ heldBack.current = false; return; } - if (disabled || heldBack.current || queuedRef.current.length === 0) { + if ( + disabled || + heldBack.current || + askingFree.current || + queuedRef.current.length === 0 || + Date.now() < tryNotBefore.current + ) { + return; + } + /* + * ASKED BEFORE IT GOES, AND WHILE IT IS ASKED THE QUEUE STAYS ON SCREEN. A drain the server + * then refused would take the messages out of the queue, draw them as sent for as long as the + * refusal took, and put them back. Asked first, they stay where they are, with Remove, until the + * conversation is free. + */ + const free = freeToSendRef.current?.() ?? true; + if (free === false) { + tryAgainSoon(); + return; + } + if (free !== true) { + askingFree.current = true; + void free + .catch(() => true) + .then((answer) => { + askingFree.current = false; + if (answer) { + // Asked and free: the next look goes without asking (`freeToSend` answers `true`). + if (nowIdle.current) setBusyRetry((tick) => tick + 1); + } else tryAgainSoon(); + }); return; } const next = apply({ type: "settle" }); @@ -658,7 +759,7 @@ export function ConversationView({ */ restoreFailedRun(carried, error); }); - }, [apply, disabled, inFlight, restoreFailedRun, busyRetry]); + }, [apply, disabled, inFlight, restoreFailedRun, tryAgainSoon, busyRetry]); return (
diff --git a/app/src/lib/copilot/stopped-turn.ts b/app/src/lib/copilot/stopped-turn.ts index 726b6ef62d..d433b6bd79 100644 --- a/app/src/lib/copilot/stopped-turn.ts +++ b/app/src/lib/copilot/stopped-turn.ts @@ -42,6 +42,7 @@ export function stoppedReason(reported: unknown): string { ? reported : ""; notePlanRefusal(reported, said); + if (threadBusy(reported)) return THREAD_BUSY; const busy = tooManyRuns(reported); if (busy) return busy.message; const refused = refusalForPerson(said); @@ -62,9 +63,57 @@ export function stoppedReason(reported: unknown): string { console.warn("A Bot's connection was cut part way through a turn.", said); return CONNECTION_CUT_OFF; } + /* + * AN ID IS NEVER SAID TO A PERSON. Words from upstream that name a thread, a run or a request by + * its id were written for whoever debugs it ("Thread is locked", found on OpenBot + * Cloud). They go to the console, and the person reads a sentence in plain words. + */ + if (NAMES_AN_ID.test(said)) { + console.warn("A turn ended in words written for debugging.", said); + return STOPPED_UNNAMED; + } return said.trim() || "The Bot stopped without saying why."; } +/** A UUID anywhere in the words: something named by its id, which is no person's to read. */ +const NAMES_AN_ID = + /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i; + +/** Said in place of upstream words that named something by its id. */ +export const STOPPED_UNNAMED = + "Something went wrong and the Bot stopped. Try again, or ask an admin if it keeps happening."; + +/** + * Whether a run was refused because the conversation still had a run going: nothing ran, and the + * same message sent once that run lets go is taken. + * + * Two shapes, one fact. Through the backend's event store, CopilotKit's client turns the runtime's + * 409 into `AgentThreadLockedError`, "Thread is locked" (`@copilotkit/core` 1.88). Over the + * runtime's own event stream, the run ends in a RUN_ERROR with code `THREAD_ALREADY_RUNNING`, + * "Thread already running". Built-in Bots and connected AG-UI Bots reach both the same way. + */ +export function threadBusy(reported: unknown): boolean { + if (!reported) return false; + if (typeof reported === "object") { + const { code, name, message } = reported as Record; + if (code === "THREAD_ALREADY_RUNNING" || name === "AgentThreadLockedError") + return true; + return typeof message === "string" && THREAD_BUSY_WORDS.test(message); + } + return typeof reported === "string" && THREAD_BUSY_WORDS.test(reported); +} + +const THREAD_BUSY_WORDS = + /^Thread (?:\S+ )?is locked$|^Thread already running$/; + +/** + * Said where a run the conversation was still busy for can't be sent again from here: a later run + * of a turn, or a page that only watches. The first run of a turn is not said at all; its message + * waits as queued and goes once the conversation is free (`channel-chat.tsx`). + */ +export const THREAD_BUSY = + "The Bot was still finishing its last turn, so this step didn't start. Ask it to carry on."; + /** * A fetch's own words for a connection that was cut part way: Bun's ("ECONNRESET: The socket * connection was closed unexpectedly. For more information, pass `verbose: true` in the second diff --git a/app/tests/no-fixed-settle-waits.test.ts b/app/tests/no-fixed-settle-waits.test.ts index 00abb9e9e6..a16cee4a30 100644 --- a/app/tests/no-fixed-settle-waits.test.ts +++ b/app/tests/no-fixed-settle-waits.test.ts @@ -99,6 +99,14 @@ const ALLOWED: Record = { most: 2, why: "lets a typeahead's search, which waits for typing to stop, be asked and answered", }, + "queued-send-busy-browser.test.tsx": { + most: 4, + why: "lets a held conversation refuse a queued message, then proves it goes once, and that one removed never goes", + }, + "queued-send-locked-browser.test.tsx": { + most: 3, + why: "polls the fake server for the Stop, lets the held lock refuse a send, then proves the message goes once", + }, "roster-working.test.tsx": { most: 3, why: "polls the fake server for a read, and proves a row's Working is not settled back", diff --git a/app/tests/queued-send-busy-browser.test.tsx b/app/tests/queued-send-busy-browser.test.tsx new file mode 100644 index 0000000000..7264f00a08 --- /dev/null +++ b/app/tests/queued-send-busy-browser.test.tsx @@ -0,0 +1,631 @@ +import { afterAll, beforeAll, describe, expect } from "bun:test"; +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import type { Server } from "bun"; +import type { Browser, BrowserType, Page } from "playwright-core"; +import { compile } from "tailwindcss"; +import { getGetBotResponseMock } from "@/lib/api/generated/bots/bots.msw"; +import type { ApprovalQueueData, ApprovalSettingsData } from "@/lib/approvals"; +import { personBody } from "./accounts-api"; +import { approvalInboxResponse } from "./approvals-api"; +import { botGrantsBody } from "./bot-grants-api"; +import { still } from "./page-still"; +import { test } from "./renderer-crash"; + +/** + * A message sent while the conversation still has a run going waits, then goes by itself, and one + * taken back while it waits never goes and is never drawn as sent. In a real browser. + * + * FOUND ON OPENBOT CLOUD, 2026-12-05. A person queued a message while the Bot worked and pressed + * Send now. The turn stopped here at once, but the stopped run went on holding the conversation on + * the server for a moment, and the message was sent into that and refused. The conversation said + * "Thread is locked" under the message, kept the message on screen as sent, and showed a + * second copy waiting as queued. Removing that copy left the first looking sent, and nothing ran + * until the person typed it again. + * + * The leaders' way (Claude Code, GitHub Copilot's SDK, Codex, Open WebUI): a message sent while a + * turn is going waits as queued, drawn as not started, and goes once the turn is over without + * another press; taking it back means it is never sent. + * + * The real conversation in the app's frame (carried-turn.fixture.tsx) against a real HTTP server on + * this machine, which answers as the runtime does: while a run holds the thread, a run asked for is + * refused with the runtime's own RUN_ERROR (`THREAD_ALREADY_RUNNING`), and a join token names the + * run still going. A stopped run lets go of the thread a moment after the browser stops it. + * + * OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/queued-send-busy-browser.test.tsx + * + * With OPENBOT_APP_SHOTS= each step is saved as queued-busy-----.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 APP = join(import.meta.dir, ".."); +const ORGANIZATION = "/api/v2/organizations/default"; +const BOT_ID = "general-assistant"; +const CONVERSATION = "launch-conversation"; +const THREAD = "launch-thread"; +const BOT_PATH = `${ORGANIZATION}/bots/${BOT_ID}`; + +const ASKED = "Draft the launch plan for the spring release."; +const WORKING = "Working through the launch plan"; +const FOLLOW = "Use the March numbers instead."; +const ANSWERED = "Done. The plan now uses the March numbers."; + +const BOT = { + ...getGetBotResponseMock().bot, + id: BOT_ID, + name: "General Assistant", + mine: true, + canManage: true, + systemOwned: false, + visibility: "private" as const, +}; + +type Scene = { + /** Every run the server took, in order. */ + runs: { messages: { role: string; content?: unknown }[] }[]; + /** The person's words of every run refused because the thread was held. */ + refused: unknown[]; + /** The run a join token names: still going on the server. */ + going: string | null; + /** The thread is held by a run: a run asked for now is refused. */ + locked: boolean; + /** After a stop: how long the run is still going, and how long the thread stays held. */ + goingAfterStopMs: number; + lockedAfterStopMs: number; + /** Whether the stopped run has started letting go. */ + stopping: boolean; + /** Ends the long run's stream, as a Stop does. */ + endHeld?: (() => void) | undefined; + stored: unknown[]; +}; +let scene: Scene; + +function freshScene(goingAfterStopMs: number, lockedAfterStopMs: number) { + return { + runs: [], + refused: [], + going: null, + locked: false, + goingAfterStopMs, + lockedAfterStopMs, + stopping: false, + stored: [], + } satisfies Scene as Scene; +} + +/** The stopped run lets go: first it ends, then the thread is free. */ +function letGo() { + if (scene.stopping || !scene.locked) return; + scene.stopping = true; + const own = scene; + setTimeout(() => { + own.going = null; + }, own.goingAfterStopMs); + setTimeout(() => { + own.locked = false; + }, own.lockedAfterStopMs); +} + +const json = (body: unknown, status = 200) => + Response.json(body, { + status, + headers: { "cache-control": "private, no-store" }, + }); +const sse = (events: unknown[]) => + new Response( + events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""), + { headers: { "content-type": "text/event-stream" } }, + ); +const encoder = new TextEncoder(); + +function run( + input: { + threadId: string; + runId: string; + messages: { id: string; role: string; content?: unknown }[]; + }, + signal: AbortSignal, +): Response { + const person = input.messages.filter((message) => message.role === "user"); + const last = person.at(-1)?.content; + // What the runtime answers a run while another holds the thread (`sse-response.ts`). + if (scene.locked) { + scene.refused.push(last); + return sse([ + { + type: "RUN_ERROR", + message: "Thread already running", + code: "THREAD_ALREADY_RUNNING", + }, + ]); + } + scene.runs.push(input); + if (last === ASKED) { + // A long turn: it streams until the browser stops it, and holds the thread until it lets go. + scene.going = input.runId; + scene.locked = true; + // What the thread keeps of it: the message, and the reply as far as it got. + scene.stored = [ + ...person, + { id: "working", role: "assistant", content: WORKING }, + ]; + let ticking: ReturnType | undefined; + const body = new ReadableStream({ + start(controller) { + const send = (event: unknown) => + controller.enqueue( + encoder.encode(`data: ${JSON.stringify(event)}\n\n`), + ); + send({ + type: "RUN_STARTED", + threadId: input.threadId, + runId: input.runId, + }); + send({ + type: "TEXT_MESSAGE_START", + messageId: "working", + role: "assistant", + }); + send({ + type: "TEXT_MESSAGE_CONTENT", + messageId: "working", + delta: WORKING, + }); + ticking = setInterval(() => { + try { + send({ + type: "TEXT_MESSAGE_CONTENT", + messageId: "working", + delta: ".", + }); + } catch { + clearInterval(ticking); + } + }, 250); + const end = () => { + clearInterval(ticking); + letGo(); + try { + controller.close(); + } catch { + // Already closed. + } + }; + signal.addEventListener("abort", end); + // Stopped as the runtime stops a run: it ends cancelled, and its stream closes. + scene.endHeld = () => { + try { + send({ type: "TEXT_MESSAGE_END", messageId: "working" }); + send({ + type: "RUN_FINISHED", + threadId: input.threadId, + runId: input.runId, + outcome: { type: "cancelled" }, + }); + } catch { + // Already closed. + } + end(); + }; + }, + cancel() { + clearInterval(ticking); + letGo(); + }, + }); + return new Response(body, { + headers: { "content-type": "text/event-stream" }, + }); + } + const messageId = `reply-${input.runId}`; + scene.stored = [ + ...scene.stored, + ...person.slice(-1), + { id: messageId, role: "assistant", content: ANSWERED }, + ]; + return sse([ + { type: "RUN_STARTED", threadId: input.threadId, runId: input.runId }, + { type: "TEXT_MESSAGE_START", messageId, role: "assistant" }, + { type: "TEXT_MESSAGE_CONTENT", messageId, delta: ANSWERED }, + { type: "TEXT_MESSAGE_END", messageId }, + { type: "RUN_FINISHED", threadId: input.threadId, runId: input.runId }, + ]); +} + +const inbox = () => + ({ + enabled: true, + requests: [], + rules: [], + teamRules: [], + questions: [], + }) as unknown as ApprovalQueueData & Partial; + +/** What the server answers at the API's and the runtime's addresses. */ +async function answer(request: Request): Promise { + const path = new URL(request.url).pathname; + const approvals = approvalInboxResponse(path, inbox()); + if (approvals) return approvals; + if (path === "/api/copilotkit/info") + return json({ + version: "fixture", + agents: { [BOT_ID]: { description: "Fixture", capabilities: {} } }, + mode: "sse", + telemetryDisabled: true, + }); + if (path.endsWith("/connect")) return sse([]); + if (path.endsWith("/run")) return run(await request.json(), request.signal); + if (/\/agent\/[^/]+\/stop\//.test(path)) { + const end = scene.endHeld; + scene.endHeld = undefined; + end?.(); + letGo(); + return json({ stopped: Boolean(end) }); + } + if (path.startsWith(`${ORGANIZATION}/people/me/approval-modes/`)) + return json({ asksEveryStep: false }); + if (path === BOT_PATH) return json({ bot: BOT }); + if (path === `${ORGANIZATION}/bots`) + return json({ bots: [BOT], nextCursor: null }); + if (path === `${BOT_PATH}/grants`) return json(botGrantsBody()); + if (path === `${BOT_PATH}/components`) + return json({ components: [], nextCursor: null }); + if (path === `${ORGANIZATION}/people/me/capabilities`) + return json({ capabilities: {}, enforced: false }); + if (path === `${ORGANIZATION}/people/me`) + return json({ + person: personBody({ + id: "sam", + name: "Sam Rivera", + email: "sam.rivera@northwind.example", + role: "member", + }), + openbotVersion: "v1.2.0", + }); + if (path === `${ORGANIZATION}/deployment`) + return json({ + generativeUi: true, + selfHostBanner: false, + localEvaluation: false, + edition: "team", + authProviders: [], + ssoConfigured: false, + ssoRequired: false, + }); + if (/\/conversations\/[^/]+\/(activity|signal-busy)$/.test(path)) + return new Response(null, { status: 204 }); + if (/\/conversations\/[^/]+\/voice-sessions$/.test(path)) + return json({ sessions: [], nextCursor: null }); + if (/\/conversations\/[^/]+\/refused-turns$/.test(path)) + return json({ refusedTurns: [], nextCursor: null }); + if (path === `${ORGANIZATION}/conversations/${CONVERSATION}/join-tokens`) + return json( + { + joinToken: "jt", + expiresAt: "2026-12-05T21:20:30.000Z", + threadId: THREAD, + runId: scene.going, + realtime: { clientUrl: "ws://127.0.0.1/client", topic: "thread" }, + }, + 201, + ); + const ran = path.match( + new RegExp(`^${ORGANIZATION}/conversations/[^/]+/runs/([^/]+)$`), + ); + if (ran) + return json({ + run: { + id: decodeURIComponent(ran[1] ?? ""), + outcome: "succeeded", + endedAt: "2026-12-05T21:01:00.000Z", + }, + }); + if (/\/threads\/[^/]+\/messages$/.test(path)) + return json({ messages: scene.stored }); + return undefined; +} + +/** The fixture bundled for the browser. `@/lib/marks` is Vite's `import.meta.glob`, so no marks. */ +async function bundle(): Promise { + const built = await Bun.build({ + entrypoints: [join(import.meta.dir, "carried-turn.fixture.tsx")], + target: "browser", + define: { "process.env.NODE_ENV": JSON.stringify("production") }, + 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(); +} + +/** The directory of an installed package, from the app or the repository root. */ +function packageDir(name: string): string { + const dir = [ + join(APP, "node_modules", name), + join(APP, "..", "node_modules", name), + ].find(existsSync); + if (!dir) throw new Error(`no package ${name}`); + return dir; +} + +/** Where `@import "[/]"` lands, by the package's `style` export as Vite reads it. */ +function packageStylesheet(id: string): string { + const parts = id.split("/"); + const name = id.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]; + const dir = packageDir(name); + const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + const subpath = `.${id.slice(name.length)}`; + const entry = pkg.exports?.[subpath]; + const file = + typeof entry === "string" + ? entry + : (entry?.style ?? entry?.default ?? pkg.main ?? "index.css"); + return join(dir, file); +} + +/** The app's stylesheet, built by Tailwind for these classes, as the app's build does. */ +async function stylesheet(classes: string[]): Promise { + const tailwind = dirname(Bun.resolveSync("tailwindcss/package.json", APP)); + const entry = join(APP, "src", "styles.css"); + const compiler = await compile(readFileSync(entry, "utf8"), { + base: dirname(entry), + loadStylesheet: async (id, base) => { + const path = + id === "tailwindcss" + ? join(tailwind, "index.css") + : id.startsWith(".") + ? join(base, id) + : packageStylesheet(id); + return { path, base: dirname(path), content: readFileSync(path, "utf8") }; + }, + }); + return compiler.build(classes); +} + +const browsers = new Map(); +let server: Server | undefined; +let origin = ""; + +beforeAll(async () => { + if (!asked) return; + const script = await bundle(); + const figtree = join(packageDir("@fontsource-variable/figtree"), "files"); + server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + idleTimeout: 0, + async fetch(request) { + const path = new URL(request.url).pathname; + if (path === "/conversation.js") + return new Response(script, { + headers: { "content-type": "text/javascript" }, + }); + if (path === "/fixture/live") return json({ work: [], approvals: 0 }); + const font = join(figtree, path.split("/").pop() ?? ""); + if (path.startsWith("/files/") && existsSync(font)) + return new Response(Bun.file(font)); + if (path.startsWith("/api/")) + return (await answer(request)) ?? json({ detail: "Not found." }, 404); + const theme = new URL(request.url).searchParams.get("theme") ?? "light"; + return new Response( + `
`, + { headers: { "content-type": "text/html" } }, + ); + }, + }); + origin = `http://127.0.0.1:${server.port}`; + 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(); + await server?.stop(true); +}); + +/** Styled for everything now on the page. */ +async function style(page: Page) { + const classes = await page.evaluate(() => + [...document.querySelectorAll("[class]")].flatMap((element) => [ + ...element.classList, + ]), + ); + await page.addStyleTag({ content: await stylesheet([...new Set(classes)]) }); +} + +async function shoot(page: Page, name: string) { + await style(page); + await still(page); + if (!shots) return; + mkdirSync(shots, { recursive: true }); + await page.screenshot({ path: join(shots, `${name}.png`) }); +} + +/** Nothing drawn wider than the window. */ +async function fits(page: Page) { + expect( + await page.evaluate( + () => document.documentElement.scrollWidth > innerWidth, + ), + ).toBe(false); +} + +/** Upstream's words for a held thread, or an id, anywhere on the page. */ +async function rawWords(page: Page) { + const text = (await page.locator("body").textContent()) ?? ""; + return { + locked: /is locked|already running/i.test(text), + id: /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i.test( + text, + ), + }; +} + +const windows = [ + { width: 1280, height: 800 }, + { width: 390, height: 844 }, +]; + +describe.skipIf(!asked)("A message sent while a run is still going", () => { + for (const engine of engines) + for (const theme of ["light", "dark"] as const) + for (const window of windows) { + const open = async (name: string) => { + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const page = await browser.newPage({ + viewport: window, + colorScheme: theme, + reducedMotion: "reduce", + }); + page.on("pageerror", (error) => console.error(error)); + await page.goto( + `${origin}/channel/${CONVERSATION}?quietMs=5000&theme=${theme}`, + ); + const box = page.getByRole("textbox", { name: "Message" }); + await box.click(); + await box.fill(ASKED); + await page.getByRole("button", { name: "Send message" }).click(); + await page.getByText(WORKING).first().waitFor({ timeout: 15_000 }); + // Typed while the Bot works: it waits as queued. + await box.click(); + await box.fill(FOLLOW); + await page.getByRole("button", { name: "Queue message" }).click(); + await page + .getByRole("button", { name: `Remove queued message: ${FOLLOW}` }) + .waitFor({ timeout: 5_000 }); + return { + page, + name: (step: string) => + `queued-busy-${name}-${step}-${engine}-${theme}-${window.width}`, + }; + }; + + test(`Send now into a run still letting go waits, with no error, and goes once by itself, in ${engine}, ${theme}, ${window.width}px`, async () => { + // The stopped run ends 0.3s after the stop, and holds the thread till 2.5s: what is sent + // in between is refused, as the runtime refuses it. + scene = freshScene(300, 2_500); + const { page, name } = await open("send-now"); + try { + await shoot(page, name("1-queued")); + await page + .getByRole("button", { + name: `Send queued message now: ${FOLLOW}`, + }) + .click(); + // The turn stops here at once; the run on the server is still letting go. + await page + .getByRole("button", { name: `Remove queued message: ${FOLLOW}` }) + .waitFor({ timeout: 5_000 }); + await shoot(page, name("2-waiting")); + expect(await rawWords(page)).toEqual({ locked: false, id: false }); + expect(await page.getByTestId("transcript-stopped").count()).toBe( + 0, + ); + await fits(page); + + // Past the first refusal: still nothing said about it. + await page.waitForTimeout(1_500); + await shoot(page, name("3-refused")); + expect(await rawWords(page)).toEqual({ locked: false, id: false }); + expect(await page.getByTestId("transcript-stopped").count()).toBe( + 0, + ); + + // Once the thread is free, it goes by itself, once. + await page.getByText(ANSWERED).waitFor({ timeout: 20_000 }); + await page + .getByRole("button", { name: `Remove queued message: ${FOLLOW}` }) + .waitFor({ state: "detached", timeout: 5_000 }); + await page.waitForTimeout(1_000); + await shoot(page, name("4-answered")); + // It was refused at least once while the thread was held, and never said so. + expect(scene.refused.length).toBeGreaterThan(0); + expect(new Set(scene.refused)).toEqual(new Set([FOLLOW])); + expect(scene.runs).toHaveLength(2); + expect(scene.runs[1]?.messages.at(-1)).toMatchObject({ + role: "user", + content: FOLLOW, + }); + // Drawn once, as the turn it is, and nothing about the refusal said anywhere. + expect(await page.getByText(FOLLOW, { exact: true }).count()).toBe( + 1, + ); + expect(await rawWords(page)).toEqual({ locked: false, id: false }); + expect(await page.getByTestId("transcript-stopped").count()).toBe( + 0, + ); + await fits(page); + } finally { + await page.close(); + } + }, 90_000); + + test(`Remove on a message waiting for a run to let go means it never goes and never shows as sent, in ${engine}, ${theme}, ${window.width}px`, async () => { + // A run that takes a while to let go after its stop. + scene = freshScene(3_000, 3_500); + const { page, name } = await open("remove"); + try { + await page + .getByRole("button", { + name: `Send queued message now: ${FOLLOW}`, + }) + .click(); + const waiting = page.getByRole("button", { + name: `Remove queued message: ${FOLLOW}`, + }); + await waiting.waitFor({ timeout: 5_000 }); + await page.waitForTimeout(500); + await waiting.waitFor({ timeout: 5_000 }); + await waiting.click(); + await waiting.waitFor({ state: "detached", timeout: 5_000 }); + // Past the run letting go, and a few more tries' worth. + await page.waitForTimeout(6_000); + await shoot(page, name("1-removed")); + expect(scene.runs).toHaveLength(1); + expect( + scene.runs.map((taken) => taken.messages.at(-1)?.content), + ).toEqual([ASKED]); + // Not drawn as sent anywhere, and nothing about a refusal said. + expect(await page.getByText(FOLLOW).count()).toBe(0); + expect(await rawWords(page)).toEqual({ locked: false, id: false }); + expect(await page.getByTestId("transcript-stopped").count()).toBe( + 0, + ); + await fits(page); + } finally { + await page.close(); + } + }, 90_000); + } +}); diff --git a/app/tests/queued-send-locked-browser.test.tsx b/app/tests/queued-send-locked-browser.test.tsx new file mode 100644 index 0000000000..e0c6271138 --- /dev/null +++ b/app/tests/queued-send-locked-browser.test.tsx @@ -0,0 +1,603 @@ +import { afterAll, beforeAll, describe, expect } from "bun:test"; +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import type { Browser, BrowserType, Page } from "playwright-core"; +import { compile } from "tailwindcss"; +import { getGetBotResponseMock } from "@/lib/api/generated/bots/bots.msw"; +import { personBody } from "./accounts-api"; +import { botGrantsBody } from "./bot-grants-api"; +import { still } from "./page-still"; +import { test } from "./renderer-crash"; + +/** + * Send now into a conversation the backend still holds, through the backend's event store, in a + * real browser: the path OpenBot Cloud runs. + * + * FOUND ON OPENBOT CLOUD, 2026-12-05. A person pressed Send now on a queued message. The Stop went + * to the run over the conversation's socket only, so the server carried the stopped turn on in a + * run of its own, which held the conversation's lock. The queued message was sent at once, the + * runtime refused it 409 ("Thread lock denied"), and CopilotKit's client turned that into "Thread + * is locked", which the conversation showed under the message, word for word. The message + * stayed on screen as sent, a second copy waited as queued, and nothing ran until it was typed + * again. + * + * Here: the real conversation in the app's frame (run-ended-unheard.fixture.tsx) with the app's + * runtime client in Intelligence mode, against a server on this machine that answers as the + * runtime and the thread's gateway do. A Stop comes as `stop_run` on the socket; the run ends + * cancelled, and the thread stays locked a moment after it, as the carried run held it. A run asked + * for while it is locked is answered 409 "Thread lock denied", as the runtime answers it. + * + * OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/queued-send-locked-browser.test.tsx + * + * With OPENBOT_APP_SHOTS= each step is saved as queued-locked---.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 APP = join(import.meta.dir, ".."); +const ORGANIZATION = "/api/v2/organizations/default"; +const BOT_ID = "general-assistant"; +const CONVERSATION = "launch-conversation"; +const THREAD = "launch-thread"; +const BOT_PATH = `${ORGANIZATION}/bots/${BOT_ID}`; + +const ASKED = "Draft the launch plan for the spring release."; +const WORKING = "Working through the launch plan"; +const FOLLOW = "Use the March numbers instead."; +const ANSWERED = "Done. The plan now uses the March numbers."; + +const BOT = { + ...getGetBotResponseMock().bot, + id: BOT_ID, + name: "General Assistant", + mine: true, + canManage: true, + systemOwned: false, + visibility: "private" as const, +}; + +type Send = (name: string, payload: unknown) => void; +type Frame = [string | null, string | null, string, string, unknown]; + +/** One run on the thread: its events so far, and whether it is over. */ +type Run = { id: string; events: unknown[]; over: boolean }; + +type Scene = { + /** Every run the runtime took, by the person's last words in it. */ + runs: { runId: string; last: unknown }[]; + /** How many runs were refused 409 because the thread was locked. */ + refused: number; + /** Stops: `stop_run` on the socket, and the runtime's Stop route. */ + stopRuns: number; + stopRoutes: number; + /** The run the page's channel follows, and who is joined to it. */ + current: Run | null; + listeners: Set; + /** A run still going on the server, as a join token names it. */ + going: string | null; + /** The thread's lock is held: a run asked for now is refused. */ + locked: boolean; + stored: unknown[]; + tokens: Set; +}; +let scene: Scene; +const freshScene = (): Scene => ({ + runs: [], + refused: 0, + stopRuns: 0, + stopRoutes: 0, + current: null, + listeners: new Set(), + going: null, + locked: false, + stored: [], + tokens: new Set(), +}); + +let origin = ""; +let minted = 0; +let seq = 0; + +/** A fresh join token, as the runtime hands one out on every run, connect and join-token ask. */ +const credentials = () => { + minted += 1; + const joinToken = `join-token-${minted}`; + scene.tokens.add(joinToken); + return { + threadId: THREAD, + runId: scene.current?.id ?? null, + joinToken, + realtime: { + clientUrl: `${origin.replace("http", "ws")}/client`, + topic: `thread:${THREAD}`, + }, + }; +}; + +/** Put an event on the run, numbered as the gateway numbers them, and send it to whoever listens. */ +function emit(run: Run, fields: Record) { + seq += 1; + const event = { + ...fields, + threadId: THREAD, + runId: run.id, + run_id: run.id, + metadata: { cpki_event_id: `event-${seq}`, cpki_event_seq: seq }, + }; + run.events.push(event); + if (scene.current === run) + for (const send of scene.listeners) send("ag_ui_event", event); +} + +function idle(run: Run) { + for (const send of scene.listeners) + send("stream_idle", { latestEventId: `event-${seq}` }); + if (scene.current === run) scene.listeners.clear(); +} + +/** A run asked for: the person's long one is held until stopped; the next one answers at once. */ +function start(input: { + runId: string; + messages: { id: string; role: string; content?: unknown }[]; +}) { + const person = input.messages.filter((message) => message.role === "user"); + const last = person.at(-1)?.content; + scene.runs.push({ runId: input.runId, last }); + const run: Run = { id: input.runId, events: [], over: false }; + scene.current = run; + scene.going = run.id; + scene.locked = true; + if (last === ASKED) { + scene.stored = [ + ...person, + { id: "working", role: "assistant", content: WORKING }, + ]; + setTimeout(() => { + emit(run, { type: "RUN_STARTED" }); + emit(run, { + type: "TEXT_MESSAGE_START", + messageId: "working", + role: "assistant", + }); + emit(run, { + type: "TEXT_MESSAGE_CONTENT", + messageId: "working", + delta: WORKING, + }); + }, 150); + return; + } + const messageId = `reply-${run.id}`; + scene.stored = [ + ...scene.stored, + ...person.slice(-1), + { id: messageId, role: "assistant", content: ANSWERED }, + ]; + setTimeout(() => { + emit(run, { type: "RUN_STARTED" }); + emit(run, { type: "TEXT_MESSAGE_START", messageId, role: "assistant" }); + emit(run, { + type: "TEXT_MESSAGE_CONTENT", + messageId, + delta: ANSWERED, + }); + emit(run, { type: "TEXT_MESSAGE_END", messageId }); + emit(run, { type: "RUN_FINISHED" }); + run.over = true; + scene.going = null; + scene.locked = false; + idle(run); + }, 150); +} + +/** + * A Stop, as the runtime carries it out: the run ends cancelled. The thread stays held a moment + * after, as the run the server carried the stopped turn on in held it on OpenBot Cloud: going for + * 0.3 s, and locked for 2.5 s. + */ +function stopped() { + const run = scene.current; + if (!run || run.over) return; + emit(run, { type: "TEXT_MESSAGE_END", messageId: "working" }); + emit(run, { type: "RUN_FINISHED", outcome: { type: "cancelled" } }); + run.over = true; + idle(run); + const own = scene; + own.going = "carried-on"; + setTimeout(() => { + own.going = null; + }, 300); + setTimeout(() => { + own.locked = false; + }, 2_500); +} + +function joined(send: Send, params: Record) { + const run = scene.current; + const mode = params.stream_mode === "run" ? "run" : "connect"; + if (!run) { + send("replay_complete", { latestEventId: null }); + send("stream_idle", { latestEventId: null }); + return; + } + for (const event of run.events) send("ag_ui_event", event); + if (mode === "connect") + send("replay_complete", { latestEventId: `event-${seq}` }); + if (run.over) { + send("stream_idle", { latestEventId: `event-${seq}` }); + return; + } + scene.listeners.add(send); +} + +const json = (body: unknown, status = 200) => + Response.json(body, { + status, + headers: { "cache-control": "private, no-store" }, + }); + +/** What the server answers at the API's and the runtime's addresses. */ +async function answer(request: Request): Promise { + const path = new URL(request.url).pathname; + if (path === "/api/copilotkit/info") + return json({ + version: "fixture", + agents: { [BOT_ID]: { description: "Fixture", capabilities: {} } }, + mode: "intelligence", + intelligence: { wsUrl: `${origin.replace("http", "ws")}/client` }, + telemetryDisabled: true, + }); + if (path.endsWith("/connect")) { + if (!scene.current) return new Response(null, { status: 204 }); + return json(credentials()); + } + if (path.endsWith("/run")) { + // What the runtime answers a run while the thread's lock is held (`handlers/intelligence/run`). + if (scene.locked) { + scene.refused += 1; + return json({ error: "Thread lock denied" }, 409); + } + start(await request.json()); + return json(credentials()); + } + if (/\/agent\/[^/]+\/stop\//.test(path)) { + scene.stopRoutes += 1; + return json({ stopped: false, message: "No active run." }); + } + if (path === BOT_PATH) return json({ bot: BOT }); + if (path === `${ORGANIZATION}/bots`) + return json({ bots: [BOT], nextCursor: null }); + if (path === `${BOT_PATH}/grants`) return json(botGrantsBody()); + if (path === `${BOT_PATH}/components`) + return json({ components: [], nextCursor: null }); + if (path.startsWith(`${ORGANIZATION}/people/me/approval-modes/`)) + return json({ asksEveryStep: false }); + if (path === `${ORGANIZATION}/people/me/capabilities`) + return json({ capabilities: {}, enforced: false }); + if (path === `${ORGANIZATION}/people/me`) + return json({ + person: personBody({ + id: "sam", + name: "Sam Rivera", + email: "sam.rivera@northwind.example", + role: "member", + }), + openbotVersion: "v1.2.11", + }); + if (path === `${ORGANIZATION}/deployment`) + return json({ + generativeUi: true, + selfHostBanner: false, + localEvaluation: false, + edition: "team", + authProviders: [], + ssoConfigured: false, + ssoRequired: false, + }); + if (/\/conversations\/[^/]+\/(activity|signal-busy)$/.test(path)) + return new Response(null, { status: 204 }); + if (/\/conversations\/[^/]+\/voice-sessions$/.test(path)) + return json({ sessions: [], nextCursor: null }); + if (/\/conversations\/[^/]+\/refused-turns$/.test(path)) + return json({ refusedTurns: [], nextCursor: null }); + if (path === `${ORGANIZATION}/conversations/${CONVERSATION}/join-tokens`) + return json( + { + ...credentials(), + expiresAt: new Date(Date.now() + 30_000).toISOString(), + runId: scene.going, + }, + 201, + ); + const ran = path.match( + new RegExp(`^${ORGANIZATION}/conversations/${CONVERSATION}/runs/([^/]+)$`), + ); + if (ran) + return json({ + run: { + id: decodeURIComponent(ran[1] ?? ""), + outcome: "succeeded", + endedAt: new Date().toISOString(), + }, + }); + if (/\/threads\/[^/]+\/messages$/.test(path)) + return json({ messages: scene.stored }); + return undefined; +} + +/** The fixture bundled for the browser. `@/lib/marks` is Vite's `import.meta.glob`, so no marks. */ +async function bundle(): Promise { + const built = await Bun.build({ + entrypoints: [join(import.meta.dir, "run-ended-unheard.fixture.tsx")], + target: "browser", + define: { "process.env.NODE_ENV": JSON.stringify("production") }, + 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(); +} + +/** The directory of an installed package, from the app or the repository root. */ +function packageDir(name: string): string { + const dir = [ + join(APP, "node_modules", name), + join(APP, "..", "node_modules", name), + ].find(existsSync); + if (!dir) throw new Error(`no package ${name}`); + return dir; +} + +/** Where `@import "[/]"` lands, by the package's `style` export as Vite reads it. */ +function packageStylesheet(id: string): string { + const parts = id.split("/"); + const name = id.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]; + const dir = packageDir(name); + const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + const subpath = `.${id.slice(name.length)}`; + const entry = pkg.exports?.[subpath]; + const file = + typeof entry === "string" + ? entry + : (entry?.style ?? entry?.default ?? pkg.main ?? "index.css"); + return join(dir, file); +} + +/** The app's stylesheet, built by Tailwind for these classes, as the app's build does. */ +async function stylesheet(classes: string[]): Promise { + const tailwind = dirname(Bun.resolveSync("tailwindcss/package.json", APP)); + const entry = join(APP, "src", "styles.css"); + const compiler = await compile(readFileSync(entry, "utf8"), { + base: dirname(entry), + loadStylesheet: async (id, base) => { + const path = + id === "tailwindcss" + ? join(tailwind, "index.css") + : id.startsWith(".") + ? join(base, id) + : packageStylesheet(id); + return { path, base: dirname(path), content: readFileSync(path, "utf8") }; + }, + }); + return compiler.build(classes); +} + +const browsers = new Map(); +let server: ReturnType | undefined; + +beforeAll(async () => { + if (!asked) return; + const script = await bundle(); + const figtree = join(packageDir("@fontsource-variable/figtree"), "files"); + // The server and the thread's gateway in one: the page, the API, the runtime, and Phoenix's JSON. + server = Bun.serve<{ open: boolean }>({ + hostname: "127.0.0.1", + port: 0, + idleTimeout: 0, + async fetch(request, bun) { + const url = new URL(request.url); + if (request.headers.get("upgrade") === "websocket") { + const token = url.searchParams.get("join_token") ?? ""; + // A join token opens one socket, once, as the gateway takes it. + if (!scene.tokens.delete(token)) + return new Response("forbidden", { status: 403 }); + return bun.upgrade(request, { data: { open: true } }) + ? undefined + : new Response("upgrade failed", { status: 400 }); + } + const path = url.pathname; + if (path === "/conversation.js") + return new Response(script, { + headers: { "content-type": "text/javascript" }, + }); + const font = join(figtree, path.split("/").pop() ?? ""); + if (path.startsWith("/files/") && existsSync(font)) + return new Response(Bun.file(font)); + if (path.startsWith("/api/")) + return (await answer(request)) ?? json({ detail: "Not found." }, 404); + return new Response( + `
`, + { headers: { "content-type": "text/html" } }, + ); + }, + websocket: { + close(socket) { + socket.data.open = false; + }, + message(socket, message) { + const [joinRef, ref, topic, name, payload] = JSON.parse( + String(message), + ) as Frame; + socket.send( + JSON.stringify([ + joinRef, + ref, + topic, + "phx_reply", + { status: "ok", response: {} }, + ]), + ); + // The browser's Stop, on the thread's channel (`stop_run` in @copilotkit/core). + if (name === "stop_run") { + scene.stopRuns += 1; + stopped(); + return; + } + if (name !== "phx_join") return; + const send: Send = (event, body) => { + if (socket.data.open && socket.readyState === 1) + socket.send(JSON.stringify([joinRef, null, topic, event, body])); + }; + joined(send, (payload ?? {}) as Record); + }, + }, + }); + origin = `http://127.0.0.1:${server.port}`; + 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(); + await server?.stop(true); +}); + +/** Styled for everything now on the page. */ +async function style(page: Page) { + const classes = await page.evaluate(() => + [...document.querySelectorAll("[class]")].flatMap((element) => [ + ...element.classList, + ]), + ); + await page.addStyleTag({ content: await stylesheet([...new Set(classes)]) }); +} + +async function shoot(page: Page, name: string) { + await style(page); + await still(page); + if (!shots) return; + mkdirSync(shots, { recursive: true }); + await page.screenshot({ path: join(shots, `${name}.png`) }); +} + +/** Upstream's words for a held thread, or an id, anywhere on the page. */ +async function rawWords(page: Page) { + const text = (await page.locator("body").textContent()) ?? ""; + return { + locked: /is locked|lock denied|already running/i.test(text), + id: /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i.test( + text, + ), + }; +} + +const windows = [ + { width: 1280, height: 800 }, + { width: 390, height: 844 }, +]; + +describe.skipIf(!asked)( + "Send now into a conversation the backend still holds", + () => { + for (const engine of engines) + for (const window of windows) + test(`the Stop reaches the server's route, the message waits with no error and goes once, in ${engine}, ${window.width}px`, async () => { + scene = freshScene(); + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const page = await browser.newPage({ + viewport: window, + reducedMotion: "reduce", + }); + page.on("pageerror", (error) => console.error(error)); + const name = (step: string) => + `queued-locked-${step}-${engine}-${window.width}`; + try { + await page.goto(`${origin}/channel/${CONVERSATION}?quietMs=5000`); + const box = page.getByRole("textbox", { name: "Message" }); + await box.click(); + await box.fill(ASKED); + await page.getByRole("button", { name: "Send message" }).click(); + await page.getByText(WORKING).first().waitFor({ timeout: 15_000 }); + await box.click(); + await box.fill(FOLLOW); + await page.getByRole("button", { name: "Queue message" }).click(); + await page + .getByRole("button", { + name: `Send queued message now: ${FOLLOW}`, + }) + .click(); + + // The Stop goes to the run on the socket. + const until = Date.now() + 5_000; + while (scene.stopRuns === 0 && Date.now() < until) + await page.waitForTimeout(50); + expect(scene.stopRuns).toBe(1); + + // Waiting, with nothing said about why. + await page.waitForTimeout(1_500); + await shoot(page, name("1-waiting")); + // And to the server's route, which takes the turn off the server's queue, so the server + // does not carry the stopped turn on. + expect(scene.stopRoutes).toBe(1); + expect(await rawWords(page)).toEqual({ locked: false, id: false }); + expect(await page.getByTestId("transcript-stopped").count()).toBe( + 0, + ); + + // Once the thread is free, it goes by itself, once. + await page.getByText(ANSWERED).waitFor({ timeout: 20_000 }); + await page + .getByRole("button", { name: `Remove queued message: ${FOLLOW}` }) + .waitFor({ state: "detached", timeout: 5_000 }); + await page.waitForTimeout(1_000); + await shoot(page, name("2-answered")); + expect(scene.refused).toBeGreaterThan(0); + expect(scene.runs.map((run) => run.last)).toEqual([ASKED, FOLLOW]); + expect(await page.getByText(FOLLOW, { exact: true }).count()).toBe( + 1, + ); + expect(await rawWords(page)).toEqual({ locked: false, id: false }); + expect(await page.getByTestId("transcript-stopped").count()).toBe( + 0, + ); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth > innerWidth, + ), + ).toBe(false); + } finally { + await page.close(); + } + }, 90_000); + }, +); diff --git a/app/tests/stopped-turn.test.ts b/app/tests/stopped-turn.test.ts index 0fed6dc4d2..618cc8bf3b 100644 --- a/app/tests/stopped-turn.test.ts +++ b/app/tests/stopped-turn.test.ts @@ -1,5 +1,7 @@ import { describe, expect, test } from "bun:test"; +import { AgentThreadLockedError } from "@copilotkit/react-core/v2"; import { + asksToCarryOn, BOT_CANNOT_RUN, BOT_CANNOT_RUN_MESSAGE_NOT_SENT, CONNECT_NOT_OPENED, @@ -7,10 +9,13 @@ import { failedRunReason, laterRunFailure, RUN_NOT_STARTED, + STOPPED_UNNAMED, stoppedReason, + THREAD_BUSY, TURN_CUT_OFF, TURN_INTERRUPTED, TURN_REFUSED, + threadBusy, } from "../src/lib/copilot/stopped-turn"; /** @@ -120,6 +125,68 @@ describe("a later run of a turn that fails", () => { }); }); +/* + * FOUND ON OPENBOT CLOUD, 2026-12-05: a turn sent while the stopped run before it still held the + * conversation ended "Thread 0b7e2c1a-4f3d-4e8a-9c21-6d5f8a3b2e10 is locked", word for word, under + * the person's message. + */ +describe("a run refused because the conversation still had a run going", () => { + test("is known in both shapes the client reports it, and in no other", () => { + // Through the backend's event store: CopilotKit's client, on the runtime's 409. + expect( + threadBusy( + new AgentThreadLockedError("0b7e2c1a-4f3d-4e8a-9c21-6d5f8a3b2e10"), + ), + ).toBe(true); + expect(threadBusy(new AgentThreadLockedError())).toBe(true); + // Over the runtime's own event stream: its RUN_ERROR, and that RUN_ERROR's words. + expect( + threadBusy({ + type: "RUN_ERROR", + message: "Thread already running", + code: "THREAD_ALREADY_RUNNING", + }), + ).toBe(true); + expect(threadBusy("Thread already running")).toBe(true); + for (const other of [ + new Error("The endpoint refused the connection"), + "Thread access denied", + "REST run request failed: Failed to fetch", + undefined, + ]) + expect([other, threadBusy(other)]).toEqual([other, false]); + }); + + test("is said in plain words with a way on, never with the conversation's id", () => { + const said = stoppedReason( + new AgentThreadLockedError("0b7e2c1a-4f3d-4e8a-9c21-6d5f8a3b2e10"), + ); + expect(said).toBe(THREAD_BUSY); + expect(said).not.toContain("0b7e2c1a"); + expect(asksToCarryOn(said)).toBe(true); + expect(stoppedReason("Thread already running")).toBe(THREAD_BUSY); + // A later run of a turn refused the same way. + expect( + laterRunFailure( + new AgentThreadLockedError("0b7e2c1a-4f3d-4e8a-9c21-6d5f8a3b2e10"), + ), + ).toBe(THREAD_BUSY); + }); +}); + +describe("words from upstream that name something by its id", () => { + test("are never said to a person", () => { + for (const raw of [ + "Run 0f9c2e7a-41b3-4c1d-9a8e-2b6f1d3c4e5a not found", + "Thread 0b7e2c1a-4f3d-4e8a-9c21-6d5f8a3b2e10 has no runner", + ]) + expect([raw, stoppedReason(new Error(raw))]).toEqual([ + raw, + STOPPED_UNNAMED, + ]); + }); +}); + describe("the reason a turn ended", () => { test("passes on what ended the turn, in its own words", () => { expect(