diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9e70792d6e..e431ec173e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -775,6 +775,7 @@ jobs: app/tests/question-answer-prompt-browser.test.tsx app/tests/queue-send-now-layout.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 app/tests/reload-keeps-answer-browser.test.tsx app/tests/renderer-crash.test.ts diff --git a/api/asyncapi.yaml b/api/asyncapi.yaml index 0e7cee399b..2a8ccd1bf1 100644 --- a/api/asyncapi.yaml +++ b/api/asyncapi.yaml @@ -2067,6 +2067,32 @@ components: type: string organization_id: type: string + name: + type: string + description: >- + A CUSTOM event's name. Any Bot may send these, built in or + connected, and an app ignores a name it doesn't know. OpenBot's + own: `openbot.reconnecting`, sent while the Bot waits to try a + model call again after its connection dropped (more than one may + come in a row, one per attempt); and `openbot.reconnected`, sent + when the call it tried again starts answering. The app shows + "Reconnecting…" on the turn's live line from the first until the + second, or until any later event of the run that is not CUSTOM, or + until the run ends. + examples: + - openbot.reconnecting + - openbot.reconnected + value: + description: >- + A CUSTOM event's value. For `openbot.reconnecting`, an object with + `attempt` (the attempt it waits to make, counted from 1), + `attempts` (the most it will make) and `retryInMs` (how long until + it tries). For `openbot.reconnected`, an empty object. + examples: + - attempt: 1 + attempts: 4 + retryInMs: 2000 + - {} metadata: type: object properties: diff --git a/app/src/components/channels/channel-chat.tsx b/app/src/components/channels/channel-chat.tsx index 085e4e8314..0ecef0ce6a 100644 --- a/app/src/components/channels/channel-chat.tsx +++ b/app/src/components/channels/channel-chat.tsx @@ -146,6 +146,7 @@ import { watchQuietRun, } from "@/lib/copilot/quiet-run"; import { realtimeTrouble } from "@/lib/copilot/realtime-trouble"; +import { useReconnecting } from "@/lib/copilot/reconnecting"; import { repairUnansweredToolCalls, unansweredToolCalls, @@ -824,6 +825,8 @@ export function ChannelChat({ offerItsOwnTools(agent, runtimeAgentId, queries); return observeApprovalAgent(agent); }, [agent, runtimeAgentId, queries]); + // The Bot waiting to try its model again, said on the turn's live line (`reconnecting.ts`). + const reconnecting = useReconnecting(agent); /** * First-message seed from the compose screen. It is taken once per mount and retained until the @@ -3668,6 +3671,7 @@ export function ChannelChat({ } stoppedDismissed={stoppedDismissal.dismissed} onDismissStopped={stoppedDismissal.dismiss} + reconnecting={reconnecting} /* * What the server says this conversation waits on: a Bot its Bot asked, a routine. * Hidden while this tab's own turn is going, which already shows itself and would diff --git a/app/src/components/channels/chat-transcript.tsx b/app/src/components/channels/chat-transcript.tsx index bda8947d42..b4230fc611 100644 --- a/app/src/components/channels/chat-transcript.tsx +++ b/app/src/components/channels/chat-transcript.tsx @@ -299,6 +299,12 @@ type ChatTranscriptProps = { * answer will appear. */ working?: React.ReactNode; + /** + * The Bot is waiting to try its model again after the connection dropped (`useReconnecting`). + * While `busy`, the turn's live line says "Reconnecting…" in place of "Thinking", under whatever + * the Bot said last. + */ + reconnecting?: boolean; }; /** One shared empty array, so a screen without a queue does not hand down a new one per render. */ @@ -440,8 +446,13 @@ export function RestoringTranscript() { * * It borrows the shimmer a running tool line uses, so "working on it" reads the same whether the * work is a tool call or a model that has not spoken yet. + * + * While the Bot waits to try its model again after the connection dropped, the same line says + * "Reconnecting…" (`reconnecting` on the transcript). Same line and same shimmer: the Bot is still + * on it, and the person needs nothing more than that. Only if the tries run out does the turn's + * notice say so. */ -function Thinking() { +function Thinking({ reconnecting = false }: { reconnecting?: boolean }) { return (

- Thinking + {reconnecting ? "Reconnecting…" : "Thinking"}

); } @@ -2620,6 +2631,7 @@ export function ChatTranscript({ stoppedDismissed = false, onDismissStopped, working, + reconnecting = false, }: ChatTranscriptProps) { const isDrawn = useDrawnTool(); // Which calls draw a component, so one asked for too early is left out. See `shared/tool-steps.ts`. @@ -2766,6 +2778,12 @@ export function ChatTranscript({ * the Thinking indicator. */ lastItem?.kind === "attachments"); + /* + * WAITING TO RECONNECT IS DRAWN WHEREVER THE TURN IS. The model's connection can drop after the + * Bot has already said something this turn, with its words the last thing on screen. Nothing else + * says it is still working then, so the live line comes back under them until the Bot carries on. + */ + const reconnectingNow = busy && reconnecting; const viewportRef = useRef(null); const newestUserMessageId = @@ -3320,8 +3338,8 @@ export function ChatTranscript({ reason={stopped} /> ) - ) : waitingOnTheModel ? ( - + ) : waitingOnTheModel || reconnectingNow ? ( + ) : null} {working} {queued.map((message) => ( diff --git a/app/src/components/channels/conversation-view.tsx b/app/src/components/channels/conversation-view.tsx index a1f491de75..5b909bd104 100644 --- a/app/src/components/channels/conversation-view.tsx +++ b/app/src/components/channels/conversation-view.tsx @@ -63,6 +63,7 @@ export function ConversationView({ stoppedDismissed, onDismissStopped, working, + reconnecting = false, stoppable, queueWhileBusy = false, restoring = false, @@ -143,6 +144,8 @@ export function ConversationView({ onDismissStopped?: () => void; /** Work the conversation waits on that is not this tab's run. Drawn at the end of the transcript. */ working?: ReactNode; + /** The Bot is waiting to reconnect to its model; see the transcript's `reconnecting`. */ + reconnecting?: boolean; /** * There is a run for Stop to abort, which is a narrower fact than `pending` and is the honest one * to draw a Stop button from. Defaults to `pending` for a caller with no gap between the two. @@ -653,6 +656,7 @@ export function ConversationView({ {...(stopped && stoppedDismissed ? { stoppedDismissed } : {})} {...(stopped && onDismissStopped ? { onDismissStopped } : {})} working={working} + reconnecting={reconnecting} /> {/* The composer's column, shared with a group conversation; see `ComposerColumn`. */} diff --git a/app/src/lib/copilot/reconnecting.ts b/app/src/lib/copilot/reconnecting.ts new file mode 100644 index 0000000000..e59940c400 --- /dev/null +++ b/app/src/lib/copilot/reconnecting.ts @@ -0,0 +1,72 @@ +import { type AbstractAgent, EventType } from "@copilotkit/react-core/v2"; +import { useEffect, useState } from "react"; + +/** + * Whether the Bot is waiting to try a dropped model call again, as its run says it is. + * + * A model connection that drops mid-turn is tried again by the Bot itself, with a wait between + * tries, and the turn carries on. While it waits, the run says so in plain AG-UI, so any Bot can, + * built in or connected (api/asyncapi.yaml, `AgUiEvent`): + * + * - `CUSTOM` named `openbot.reconnecting`, `{ attempt, attempts, retryInMs }`, once per wait; + * - `CUSTOM` named `openbot.reconnected`, `{}`, when the call it tried again starts answering. + * + * The wait also ends on anything else the run says: words, a tool call, reasoning, a step, its end. + * Each of those means the Bot is past the wait, whether or not `openbot.reconnected` came first. + * And it ends with the run, however the run ends, so a turn that stops never leaves it standing. + * + * Only the person's live line reads this (`ChatTranscript`'s `reconnecting`). If the Bot runs out + * of tries, the run ends with its error and the turn's usual notice says so, Carry on and all. + */ +export const RECONNECTING_EVENT = "openbot.reconnecting"; +export const RECONNECTED_EVENT = "openbot.reconnected"; + +/** A CUSTOM event's name, when it has one. */ +function customName(event: unknown): string | null { + if (!event || typeof event !== "object") return null; + const { type, name } = event as { type?: unknown; name?: unknown }; + if (type !== EventType.CUSTOM) return null; + return typeof name === "string" ? name : ""; +} + +/** + * Tells `setReconnecting` when one agent's run starts and stops waiting to reconnect. Returns the + * function that stops watching, which also says it is no longer waiting. + */ +export function watchReconnecting( + agent: Pick, + setReconnecting: (reconnecting: boolean) => void, +): () => void { + // Only a change is passed on: a reply streams many events a second, and each would set it again. + let waiting = false; + const set = (next: boolean) => { + if (next === waiting) return; + waiting = next; + setReconnecting(next); + }; + const subscription = agent.subscribe({ + onRunInitialized: () => set(false), + onEvent: ({ event }) => { + const name = customName(event); + if (name === null) set(false); + else if (name === RECONNECTING_EVENT) set(true); + else if (name === RECONNECTED_EVENT) set(false); + // Any other CUSTOM event is about something else, and changes nothing here. + }, + onRunFinalized: () => set(false), + onRunFailed: () => set(false), + }); + return () => { + subscription.unsubscribe(); + set(false); + }; +} + +/** Whether this agent's run is waiting to reconnect to its model now. See `watchReconnecting`. */ +export function useReconnecting( + agent: Pick, +): boolean { + const [reconnecting, setReconnecting] = useState(false); + useEffect(() => watchReconnecting(agent, setReconnecting), [agent]); + return reconnecting; +} diff --git a/app/tests/reconnecting-line-layout.fixture.tsx b/app/tests/reconnecting-line-layout.fixture.tsx new file mode 100644 index 0000000000..fdba44c3ac --- /dev/null +++ b/app/tests/reconnecting-line-layout.fixture.tsx @@ -0,0 +1,145 @@ +import type { Message } from "@ag-ui/core"; +import { + AbstractAgent, + type BaseEvent, + CopilotKitProvider, + EventType, + type RunAgentInput, +} from "@copilotkit/react-core/v2"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { useEffect, useState } from "react"; +import { createRoot } from "react-dom/client"; +import { Observable, ReplaySubject } from "rxjs"; +import { ConversationView } from "@/components/channels/conversation-view"; +import { TooltipProvider } from "@/components/ui/tooltip"; +import { useReconnecting } from "@/lib/copilot/reconnecting"; +import { setCurrentOrganization } from "@/lib/organizations/current"; + +/** + * A conversation whose Bot's model connection drops, as a page of its own for + * reconnecting-line-layout.test.tsx to bundle and load in a browser: the real conversation view and + * transcript, and a real AG-UI agent read by `useReconnecting`, as the conversation screen reads it. + * The test says what the run sends next with `window.__say(step)`. + * + * `?theme=dark` draws it in the dark theme. + */ +type Step = "dropped" | "back" | "words" | "more" | "finished"; +type Page = Window & { __say: (step: Step) => void }; +const page = window as unknown as Page; +setCurrentOrganization("default"); + +if (new URLSearchParams(location.search).get("theme") === "dark") { + document.documentElement.classList.add("dark"); +} + +class DroppingBot extends AbstractAgent { + private said = new ReplaySubject(); + private ids = { threadId: "thread-1", runId: "run-1" }; + constructor() { + super({ + agentId: "bot", + threadId: "thread-1", + initialMessages: [ + { + id: "asked", + role: "user", + content: "Summarize this quarter's numbers for the board.", + }, + ], + }); + } + run(input: RunAgentInput): Observable { + this.ids = { threadId: input.threadId, runId: input.runId }; + this.say({ type: EventType.RUN_STARTED, ...this.ids }); + return new Observable((subscriber) => { + const hearing = this.said.subscribe(subscriber); + return () => hearing.unsubscribe(); + }); + } + say(event: Record) { + this.said.next(event as unknown as BaseEvent); + } + step(step: Step) { + if (step === "dropped") + this.say({ + type: EventType.CUSTOM, + name: "openbot.reconnecting", + value: { attempt: 1, attempts: 4, retryInMs: 2000 }, + }); + if (step === "back") + this.say({ + type: EventType.CUSTOM, + name: "openbot.reconnected", + value: {}, + }); + if (step === "words" || step === "more") { + const messageId = `said-${step}`; + this.say({ + type: EventType.TEXT_MESSAGE_START, + messageId, + role: "assistant", + }); + this.say({ + type: EventType.TEXT_MESSAGE_CONTENT, + messageId, + delta: + step === "words" + ? "Revenue grew 12% on last quarter, led by the two new enterprise contracts." + : "Costs held flat.", + }); + this.say({ type: EventType.TEXT_MESSAGE_END, messageId }); + } + if (step === "finished") { + this.say({ type: EventType.RUN_FINISHED, ...this.ids }); + this.said.complete(); + } + } +} + +const bot = new DroppingBot(); +page.__say = (step) => bot.step(step); + +const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, +}); + +function Conversation() { + const reconnecting = useReconnecting(bot); + const [messages, setMessages] = useState(() => [...bot.messages]); + const [busy, setBusy] = useState(false); + useEffect(() => { + const subscription = bot.subscribe({ + onRunInitialized: () => setBusy(true), + onRunFinalized: () => setBusy(false), + onMessagesChanged: ({ messages: now }) => setMessages([...now]), + }); + void bot.runAgent().catch(() => undefined); + return () => subscription.unsubscribe(); + }, []); + return ( + {}} + pending={busy} + reconnecting={reconnecting} + stoppable={busy} + /> + ); +} + +const root = document.getElementById("root"); +if (root) { + createRoot(root).render( + + + +
+ +
+
+
+
, + ); +} diff --git a/app/tests/reconnecting-line-layout.test.tsx b/app/tests/reconnecting-line-layout.test.tsx new file mode 100644 index 0000000000..f3b7350370 --- /dev/null +++ b/app/tests/reconnecting-line-layout.test.tsx @@ -0,0 +1,322 @@ +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 { test } from "./renderer-crash"; + +/** + * "Reconnecting…" on a turn's live line, in a real browser. + * + * A Bot whose model connection drops tries again by itself, and its run says so + * (`openbot.reconnecting`, then `openbot.reconnected`). The live line says "Reconnecting…" while it + * waits: the line that said "Thinking", in the same place, size, colour and shimmer, and nothing + * else on the page changes. Mid-turn it comes back under what the Bot already said, and goes when + * the Bot carries on. reconnecting-line.test.tsx holds the behaviour; this is how it looks, in the + * app's stylesheet, in a wide window and a phone-width one. + * + * OPENBOT_APP_BROWSER=1 bun test app/tests/reconnecting-line-layout.test.tsx + * + * Chromium by default, as CI has it. OPENBOT_APP_ENGINES=chromium,webkit adds WebKit. With + * OPENBOT_APP_SHOTS= each step is saved as reconnecting----.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 ORIGIN = "http://openbot.test"; +const ASKED = "Summarize this quarter's numbers for the board."; +const SAID = + "Revenue grew 12% on last quarter, led by the two new enterprise contracts."; + +/** 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, "reconnecting-line-layout.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 script: string; + +beforeAll(async () => { + if (!asked) return; + 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(); +}); + +/** 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)]) }); +} + +/** The conversation, the Bot thinking about the person's message. */ +async function open( + engine: string, + theme: "light" | "dark", + window: { width: number; height: number }, +): Promise { + 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)); + const figtree = join(packageDir("@fontsource-variable/figtree"), "files"); + await page.route(`${ORIGIN}/**`, (route) => { + const path = new URL(route.request().url()).pathname; + if (path === "/conversation.js") + return route.fulfill({ contentType: "text/javascript", body: script }); + const font = join(figtree, path.split("/").pop() ?? ""); + if (path.startsWith("/files/") && existsSync(font)) + return route.fulfill({ path: font }); + // Nothing on the side reaches a server here. + if (path.startsWith("/api/")) return route.fulfill({ status: 404 }); + return route.fulfill({ + contentType: "text/html", + body: `
`, + }); + }); + await page.goto(`${ORIGIN}/?theme=${theme}`); + await page.getByText(ASKED).waitFor({ timeout: 15_000 }); + await page.getByText("Thinking", { exact: true }).waitFor(); + await style(page); + await page.evaluate(() => document.fonts.ready); + return page; +} + +type Step = "dropped" | "back" | "words" | "more" | "finished"; +const say = (page: Page, step: Step) => + page.evaluate( + (next) => + (window as unknown as { __say: (step: string) => void }).__say(next), + step, + ); + +async function shoot(page: Page, step: string, name: string) { + if (!shots) return; + mkdirSync(shots, { recursive: true }); + await page.screenshot({ + path: join(shots, `reconnecting-${step}-${name}.png`), + }); +} + +/** How the turn's live line is drawn, and how many there are. Only `count` when there is none. */ +type LiveLine = { + count: number; + text?: string | null; + left?: number; + top?: number; + height?: number; + size?: string; + color?: string; + weight?: string; + oneLine?: boolean; + sideways?: boolean; +}; + +function liveLine(page: Page): Promise { + return page.evaluate((): LiveLine => { + const lines = [ + ...document.querySelectorAll( + '[role="status"].tool-line-running', + ), + ]; + const line = lines[0]; + if (!line) return { count: 0 }; + const box = line.getBoundingClientRect(); + const look = getComputedStyle(line); + return { + count: lines.length, + text: line.textContent, + left: Math.round(box.left), + top: Math.round(box.top), + height: Math.round(box.height), + size: look.fontSize, + color: look.color, + weight: look.fontWeight, + oneLine: box.height < Number.parseFloat(look.lineHeight) * 1.5, + sideways: document.documentElement.scrollWidth > innerWidth, + }; + }); +} + +/** Where the Bot's words end, to see the live line sits under them. */ +const wordsBottom = (page: Page) => + page + .getByText(SAID) + .evaluate((element) => Math.round(element.getBoundingClientRect().bottom)); + +describe.skipIf(!asked)("Reconnecting… on the live line", () => { + for (const engine of engines) + for (const theme of ["light", "dark"] as const) + for (const window of [ + { width: 1000, height: 760 }, + { width: 390, height: 760 }, + ]) + test(`says Reconnecting… where it said Thinking, and goes when the Bot carries on, in ${engine}, ${theme}, ${window.width}px`, async () => { + const page = await open(engine, theme, window); + const name = `${engine}-${theme}-${window.width}`; + try { + const thinking = await liveLine(page); + expect(thinking).toMatchObject({ count: 1, text: "Thinking" }); + await shoot(page, "1-thinking", name); + + // The model's connection dropped: the same line, drawn the same, says so. + await say(page, "dropped"); + await page.getByText("Reconnecting…").waitFor(); + await style(page); + const waiting = await liveLine(page); + await shoot(page, "2-reconnecting", name); + expect(waiting).toEqual({ + ...thinking, + text: "Reconnecting…", + }); + expect(waiting).toMatchObject({ oneLine: true, sideways: false }); + + // Back: Thinking again, in the same place. + await say(page, "back"); + await page.getByText("Thinking", { exact: true }).waitFor(); + expect(await liveLine(page)).toEqual(thinking); + + // The Bot speaks; nothing else says it is working. + await say(page, "words"); + await page.getByText(SAID).waitFor(); + await style(page); + expect(await liveLine(page)).toEqual({ count: 0 }); + await shoot(page, "3-words", name); + + // Its next model call drops: the line comes back under its words. + await say(page, "dropped"); + await page.getByText("Reconnecting…").waitFor(); + await style(page); + const midTurn = await liveLine(page); + await shoot(page, "4-reconnecting-mid-turn", name); + expect(midTurn).toMatchObject({ + count: 1, + text: "Reconnecting…", + left: thinking.left, + size: thinking.size, + color: thinking.color, + weight: thinking.weight, + oneLine: true, + sideways: false, + }); + expect( + (midTurn as { top: number }).top >= (await wordsBottom(page)), + ).toBe(true); + + // It carries on: the line is gone, and the turn ends. + await say(page, "more"); + await page.getByText("Costs held flat.").waitFor(); + await page + .getByText("Reconnecting…") + .waitFor({ state: "detached" }); + await style(page); + expect(await liveLine(page)).toEqual({ count: 0 }); + // The new words finish fading in before they are shot. + await page.waitForFunction(() => + [ + ...document.querySelectorAll('[data-slot="message-arriving"]'), + ].every((row) => getComputedStyle(row).opacity === "1"), + ); + await shoot(page, "5-cleared", name); + await say(page, "finished"); + } finally { + await page.close(); + } + }, 90_000); +}); diff --git a/app/tests/reconnecting-line.test.tsx b/app/tests/reconnecting-line.test.tsx new file mode 100644 index 0000000000..773f9f229f --- /dev/null +++ b/app/tests/reconnecting-line.test.tsx @@ -0,0 +1,262 @@ +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; +import type { Message } from "@ag-ui/core"; +import { + AbstractAgent, + type BaseEvent, + CopilotKitProvider, + EventType, + type RunAgentInput, +} from "@copilotkit/react-core/v2"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { act, cleanup, render, waitFor } from "@testing-library/react"; +import { useEffect, useState } from "react"; +import { Observable, ReplaySubject } from "rxjs"; +import { ChatTranscript } from "@/components/channels/chat-transcript"; +import { forgetOpenedLines } from "@/components/channels/tool-line"; +import { useReconnecting } from "@/lib/copilot/reconnecting"; +import { queryClient } from "@/query-client"; +import { approvalInboxResponse } from "./approvals-api"; +import { settleReactWork } from "./settle-react-work"; + +/** + * While a Bot waits to try its model again, the turn's live line says "Reconnecting…". + * + * Reported in dogfooding: a Bot stopped mid-turn when its model connection dropped, and the person + * had to press Carry on. The Bot now tries again by itself, and its run says so in plain AG-UI + * (`CUSTOM` `openbot.reconnecting`, then `openbot.reconnected`), so any Bot can, built in or + * connected. These feed those events through a real AG-UI agent, the same subscriber the + * conversation screen uses, and the real transcript. + */ + +const originalFetch = globalThis.fetch; + +beforeAll(() => { + GlobalRegistrator.register({ url: "http://localhost/" }); + // The transcript asks whether OpenBot is waiting on the person; nothing is. + globalThis.fetch = Object.assign( + async (input: Parameters[0]) => { + const url = new URL( + typeof input === "string" + ? input + : input instanceof URL + ? input.href + : input.url, + "http://localhost", + ); + const approvals = approvalInboxResponse(url.pathname, { + enabled: false, + requests: [], + rules: [], + teamRules: [], + questions: [], + }); + if (approvals) return approvals; + return Response.json({ error: "not served" }, { status: 404 }); + }, + { preconnect: originalFetch.preconnect }, + ); +}); + +afterEach(() => { + cleanup(); + forgetOpenedLines(); + queryClient.clear(); +}); + +afterAll(async () => { + await settleReactWork(); + globalThis.fetch = originalFetch; + GlobalRegistrator.unregister(); +}); + +/** A Bot whose one run says what the test tells it to, when the test tells it to. */ +class DroppingBot extends AbstractAgent { + private said = new ReplaySubject(); + private ids = { threadId: "thread-1", runId: "run-1" }; + constructor() { + super({ + agentId: "bot", + threadId: "thread-1", + initialMessages: [ + { id: "u1", role: "user", content: "Summarize the quarter." }, + ], + }); + } + run(input: RunAgentInput): Observable { + this.ids = { threadId: input.threadId, runId: input.runId }; + return new Observable((subscriber) => { + const hearing = this.said.subscribe(subscriber); + return () => hearing.unsubscribe(); + }); + } + say(event: Record) { + this.said.next(event as unknown as BaseEvent); + } + started() { + this.say({ type: EventType.RUN_STARTED, ...this.ids }); + } + reconnecting(attempt: number) { + this.say({ + type: EventType.CUSTOM, + name: "openbot.reconnecting", + value: { attempt, attempts: 4, retryInMs: 2000 }, + }); + } + reconnected() { + this.say({ + type: EventType.CUSTOM, + name: "openbot.reconnected", + value: {}, + }); + } + words(id: string, text: string) { + this.say({ + type: EventType.TEXT_MESSAGE_START, + messageId: id, + role: "assistant", + }); + this.say({ + type: EventType.TEXT_MESSAGE_CONTENT, + messageId: id, + delta: text, + }); + } + wordsEnd(id: string) { + this.say({ type: EventType.TEXT_MESSAGE_END, messageId: id }); + } + finished() { + this.say({ type: EventType.RUN_FINISHED, ...this.ids }); + this.said.complete(); + } + failed(message: string) { + this.say({ type: EventType.RUN_ERROR, message }); + this.said.complete(); + } +} + +/** The conversation as the screen wires it: the agent's messages and run, and `useReconnecting`. */ +function Conversation({ agent }: { agent: DroppingBot }) { + const reconnecting = useReconnecting(agent); + const [messages, setMessages] = useState(() => [ + ...agent.messages, + ]); + const [busy, setBusy] = useState(false); + useEffect(() => { + const subscription = agent.subscribe({ + onRunInitialized: () => setBusy(true), + onRunFinalized: () => setBusy(false), + onMessagesChanged: ({ messages: now }) => setMessages([...now]), + }); + return () => subscription.unsubscribe(); + }, [agent]); + return ( + + ); +} + +function open(agent: DroppingBot) { + return render( + + + + + , + ); +} + +const SHIMMER = "tool-line-running"; + +/** The turn's live line, the one `role="status"` line that shimmers. */ +function liveLine(): HTMLElement | null { + return document.querySelector(`[role="status"].${SHIMMER}`); +} + +test("while the Bot waits to reconnect, the live line says Reconnecting…, then Thinking again once it is back", async () => { + const bot = new DroppingBot(); + const view = open(bot); + let running: Promise = Promise.resolve(); + await act(async () => { + running = bot.runAgent().catch(() => undefined); + bot.started(); + }); + await waitFor(() => expect(liveLine()?.textContent).toBe("Thinking")); + + // The model's connection dropped: the same line, same shimmer, same role, says so. + await act(async () => bot.reconnecting(1)); + await waitFor(() => expect(liveLine()?.textContent).toBe("Reconnecting…")); + // A second try is still the same quiet line, not a second one. + await act(async () => bot.reconnecting(2)); + expect(view.getAllByRole("status")).toHaveLength(1); + expect(liveLine()?.textContent).toBe("Reconnecting…"); + + // The retried call answers. + await act(async () => bot.reconnected()); + await waitFor(() => expect(liveLine()?.textContent).toBe("Thinking")); + expect(view.queryByText("Reconnecting…")).toBeNull(); + + await act(async () => { + bot.finished(); + await running; + }); + await waitFor(() => expect(liveLine()).toBeNull()); +}); + +test("mid-turn, under what the Bot already said, Reconnecting… shows and goes when the Bot speaks again or the run ends", async () => { + const bot = new DroppingBot(); + const view = open(bot); + let running: Promise = Promise.resolve(); + await act(async () => { + running = bot.runAgent().catch(() => undefined); + bot.started(); + bot.words("a1", "Revenue grew 12% this quarter."); + bot.wordsEnd("a1"); + }); + await view.findByText("Revenue grew 12% this quarter."); + // The Bot's words are the last thing on screen: nothing else says it is working. + expect(liveLine()).toBeNull(); + + // Its next model call dropped. + await act(async () => bot.reconnecting(1)); + await waitFor(() => expect(liveLine()?.textContent).toBe("Reconnecting…")); + + // No `openbot.reconnected`: the next words alone mean it is back. + await act(async () => bot.words("a2", "Costs held flat.")); + await view.findByText("Costs held flat."); + expect(view.queryByText("Reconnecting…")).toBeNull(); + + // Dropped again, and the run ends while it waits: nothing is left saying it. + await act(async () => { + bot.wordsEnd("a2"); + bot.reconnecting(1); + }); + await waitFor(() => expect(liveLine()?.textContent).toBe("Reconnecting…")); + await act(async () => { + bot.finished(); + await running; + }); + await waitFor(() => expect(view.queryByText("Reconnecting…")).toBeNull()); + expect(liveLine()).toBeNull(); +}); + +test("when the tries run out, the run's error ends Reconnecting…", async () => { + const bot = new DroppingBot(); + const view = open(bot); + let running: Promise = Promise.resolve(); + await act(async () => { + running = bot.runAgent().catch(() => undefined); + bot.started(); + bot.reconnecting(4); + }); + await waitFor(() => expect(liveLine()?.textContent).toBe("Reconnecting…")); + await act(async () => { + bot.failed("The connection to Anthropic dropped. Ask the Bot to carry on."); + await running; + }); + await waitFor(() => expect(view.queryByText("Reconnecting…")).toBeNull()); +});