Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Chat: a bot's reply appears as it streams (#5480)

Milind Soni6c95a78a1154
diff --git a/NOTICE b/NOTICE
index 28bd4af58a..6667b96457 100644
--- a/NOTICE
+++ b/NOTICE
@@ -12,6 +12,14 @@ authentication, and runtime temporary-folder behavior from T3 Code, Copyright
Selected-text citation matching adapts T3 Code's assistant citation selection,
Copyright 2026 T3 Tools Inc., used under the MIT License.
+Streaming reply rendering (src/state/live-reply.ts), its Markdown block
+splitting (src/lib/markdown-stream-blocks.ts), the transcript's follow and
+per-visit scroll restore (src/lib/transcript-follow.ts), and the server's
+per-message ids for streamed reply text (server/harness/text-items.ts) adapt
+T3 Code's chat timeline, provider text-delta coalescing and ACP assistant
+segments, Copyright 2026 T3 Tools Inc., used under the MIT License
+(third_party/t3-code/LICENSE).
+
The egress gate for the bots' browser (server/browser/egress/) adapts T3 Code's
public-only SOCKS5 proxy for HTML previews and the Linux listener-ownership
scan of its preview port scanner, Copyright 2026 T3 Tools Inc., used under the
diff --git a/docs/verification/chat-ui.md b/docs/verification/chat-ui.md
index 8d91d7054e..f1425f41e2 100644
--- a/docs/verification/chat-ui.md
+++ b/docs/verification/chat-ui.md
@@ -259,6 +259,43 @@ fake Codex app-server, and `FAKE_CODEX_COMMAND`, `FAKE_CODEX_COMMAND_OUTPUT`
script its command. A bot moved to the `codex` instance then shows `last
output just now` and the command's last two lines in the card.
+## A reply as it streams
+
+The bot's words appear as they arrive, keyed by the id the server streams each
+message under, and the saved message takes the streamed bubble's place in the
+same frame. One command streams every scripted case through the real renderer,
+once per engine, and checks each frame:
+
+```sh
+node --experimental-strip-types scripts/verify-live-reply.ts \
+ --engines claude,codex,acp,cline,copilot --out .omb-scratch/verify-evidence/live-reply
+```
+
+Each engine gets its own fixture (`ui launch --engine codex|acp|cline|copilot`);
+its fake plays the case named by a marker in the prompt from
+`FAKE_STREAM_SCRIPT` at `FAKE_STREAM_CADENCE` (the cases are
+`server/testing/live-reply-cases.ts`: short and long replies, Markdown, code
+fences, math, emoji and right-to-left text, links and images, text and tools
+interleaved, two messages in a row, a blank message, thinking, Stop, a steer,
+an error, a reconnect, a chat switch, and a room with two bots). Expected: a
+`pass` for every case in the printed table, which is also written to
+`results.md` with each case's screenshot and evidence. Steering is checked
+where the fake steers (Claude).
+
+`--engines opencode` with `OMB_VERIFY_OPENCODE_CLI` set to an OpenCode the
+recipe downloaded and checked against `server/drivers/acp/opencode-release.ts`
+runs real prompts on a free model OpenCode offers with no sign-in, in the
+fixture's temporary home.
+
+The engine-level checks, which need no browser, are
+`server/drivers/acp/live-reply-matrix.test.ts` (every ACP engine),
+`server/drivers/claude-live-reply.test.ts`, and the case runs in
+`server/drivers/codex.test.ts`, `server/drivers/pi.test.ts` and
+`server/drivers/openai-chat-tools.test.ts` (each OpenAI-compatible provider).
+The client's checks are `src/state/live-reply.test.ts`,
+`src/components/ChatView.live-reply.test.ts` and
+`src/components/ChatMarkdown.streaming.test.ts`.
+
The before-and-after screenshots were removed because they showed real example
data; run the `scripts/control-omb.ts ui launch` command above to see the
working line and the Now card.
diff --git a/scripts/control-omb.test.ts b/scripts/control-omb.test.ts
index 175ada2e66..91e6bc161e 100644
--- a/scripts/control-omb.test.ts
+++ b/scripts/control-omb.test.ts
@@ -25,6 +25,12 @@ describe("the fixture's fake engine knobs", () => {
expect(env).toMatchObject({ FAKE_CLAUDE_TEXT_ROUTES: "/tmp/routes.json", FAKE_CODEX_TEXT_ROUTES: "/tmp/codex-routes.json", FAKE_CODEX_TEXT_LOG: "/tmp/codex.jsonl" });
for (const key of ["FAKE_CODEX_MODE", "FAKE_CODEX_DUMP", "SOME_SECRET"]) expect(env, key).not.toHaveProperty(key);
});
+
+ it("lets every fake's scripted stream cross, for a reply that arrives in pieces", () => {
+ const env = childEnv({ FAKE_STREAM_SCRIPT: "/tmp/script.json", FAKE_STREAM_CADENCE: "3:90", FAKE_ACP_DUMP: "/tmp/acp.json" });
+ expect(env).toMatchObject({ FAKE_STREAM_SCRIPT: "/tmp/script.json", FAKE_STREAM_CADENCE: "3:90" });
+ expect(env).not.toHaveProperty("FAKE_ACP_DUMP");
+ });
});
describe("the fixture's Netlify stand-in", () => {
diff --git a/scripts/control-omb.ts b/scripts/control-omb.ts
index 229691faa2..61a88b1f5a 100644
--- a/scripts/control-omb.ts
+++ b/scripts/control-omb.ts
@@ -35,7 +35,7 @@ export interface ControlOmbDependencies {
}
export const HELP_UI = `renderer (needs a ui launch handle; every verb takes --ui HANDLE, never discovery):
- node --experimental-strip-types scripts/control-omb.ts ui launch [--entry threads] [--tool-calls JSON] [--mode happy] [--engine codex]
+ node --experimental-strip-types scripts/control-omb.ts ui launch [--entry threads] [--tool-calls JSON] [--mode happy] [--engine codex|acp|cline|copilot|opencode]
ui snapshot --ui HANDLE [--interactive]
ui click --ui HANDLE (--ref @eN | --name NAME)
ui type --ui HANDLE (--ref @eN | --name NAME) --text TEXT
@@ -168,7 +168,7 @@ export function verificationServerEnvironment(parentEnv: NodeJS.ProcessEnv, data
// The fake engines' knobs are the one thing a caller may script into the child.
for (const [key, value] of Object.entries(parentEnv)) {
// FAKE_CLAUDE_DUMP stays the launcher's: assertions read fixtureDumpPath.
- if ((key.startsWith("FAKE_CLAUDE_") || key.startsWith("FAKE_CODEX_TEXT_") || key.startsWith("FAKE_CODEX_COMMAND") || key === "FAKE_ACP_HANG_ON") && key !== "FAKE_CLAUDE_DUMP" && value) childEnv[key] = value;
+ if ((key.startsWith("FAKE_CLAUDE_") || key.startsWith("FAKE_CODEX_TEXT_") || key.startsWith("FAKE_CODEX_COMMAND") || key.startsWith("FAKE_STREAM_") || key === "FAKE_ACP_HANG_ON") && key !== "FAKE_CLAUDE_DUMP" && value) childEnv[key] = value;
}
// Enables POST /api/testing/org-library; the route does not exist without it.
if (parentEnv.OMB_TEST_ORG_LIBRARY_KEY) childEnv.OMB_TEST_ORG_LIBRARY_KEY = parentEnv.OMB_TEST_ORG_LIBRARY_KEY;
@@ -285,7 +285,7 @@ export async function launchVerificationServer(
enterprise?: { dir: string; licenseKey: string },
room?: { scripted: boolean },
/** Optional repository-owned fake providers for multi-engine setup checks. */
- extraProviders: Array<"codex" | "cline" | "copilot" | "customAcp"> = [],
+ extraProviders: Array<"codex" | "cline" | "copilot" | "customAcp" | "opencode"> = [],
/** Programmatic tests only: an owned loopback Boat provider, never a live account. */
boatFixtureApi?: string,
/** Programmatic web UI qualification against the fixture's static server. */
@@ -343,6 +343,10 @@ export async function launchVerificationServer(
environment: { FAKE_ACP_MODELS: "auto,claude-haiku-4.5,gpt-5.6-luna", FAKE_ACP_REJECT_STDIO_MCP: "1",
FAKE_ACP_DUMP: join(dataDir, "copilot-launch.json") },
} } : {}),
+ // A real OpenCode the recipe downloaded and verified itself; it runs in this fixture's temporary home.
+ ...(extraProviders.includes("opencode") && parentEnv.OMB_VERIFY_OPENCODE_CLI ? { opencode: {
+ driver: "opencodeGo", displayName: "Verification OpenCode", config: { cli: parentEnv.OMB_VERIFY_OPENCODE_CLI },
+ } } : {}),
...(extraProviders.includes("customAcp") ? { myAgent: {
driver: "customAcp", displayName: "Verification custom ACP",
config: { cli: fileURLToPath(new URL("../server/testing/fake-acp-cli.ts", import.meta.url)) },
diff --git a/scripts/testing/control-omb-ui.ts b/scripts/testing/control-omb-ui.ts
index a7632e3fab..2e7f924c2b 100644
--- a/scripts/testing/control-omb-ui.ts
+++ b/scripts/testing/control-omb-ui.ts
@@ -425,8 +425,9 @@ export async function launchUi(
fixtureOptions: { boatFixtureApi?: string } = {},
): Promise<void> {
const values = parse("ui launch", args, { entry: { type: "string" }, "tool-calls": { type: "string" }, mode: { type: "string" }, engine: { type: "string" } });
- if (values.engine !== undefined && values.engine !== "codex") {
- throw new ControlOmbError(`unknown --engine ${JSON.stringify(values.engine)}`, "the fake Claude CLI always runs; --engine codex adds the fake Codex app-server beside it");
+ const extraEngines: Record<string, "codex" | "customAcp" | "cline" | "copilot" | "opencode"> = { codex: "codex", acp: "customAcp", cline: "cline", copilot: "copilot", opencode: "opencode" };
+ if (values.engine !== undefined && !Object.hasOwn(extraEngines, String(values.engine))) {
+ throw new ControlOmbError(`unknown --engine ${JSON.stringify(values.engine)}`, "the fake Claude CLI always runs; --engine codex adds the fake Codex app-server beside it, --engine acp, cline or copilot a fake ACP agent, --engine opencode the OpenCode at OMB_VERIFY_OPENCODE_CLI");
}
const entryName = typeof values.entry === "string" ? values.entry : "threads";
if (!Object.hasOwn(ENTRIES, entryName)) {
@@ -464,7 +465,7 @@ export async function launchUi(
const { binary, chrome } = await ensureUiBrowser(parentEnv, note);
checkpoint();
fixture = await launchVerificationServer({ ...parentEnv, ...fakeEnv }, startup.signal, undefined,
- { binaryPath: binary, executablePath: chrome ?? "" }, undefined, undefined, values.engine === "codex" ? ["codex"] : [], fixtureOptions.boatFixtureApi);
+ { binaryPath: binary, executablePath: chrome ?? "" }, undefined, undefined, values.engine === undefined ? [] : [extraEngines[String(values.engine)]!], fixtureOptions.boatFixtureApi);
checkpoint();
const api = fixtureApi(fixture.info.url);
await api("PATCH", "/api/config", { language: "en" });
diff --git a/scripts/verify-live-reply.ts b/scripts/verify-live-reply.ts
new file mode 100644
index 0000000000..43e9eaaced
--- /dev/null
+++ b/scripts/verify-live-reply.ts
@@ -0,0 +1,299 @@
+#!/usr/bin/env -S node --experimental-strip-types
+// Streams every scripted reply case through the real renderer in an isolated fixture, once per engine, and checks each
+// frame: no message's words twice, none glued to another message, none vanishing once shown, no thinking shown as reply
+// text, no streamed row left once the turn ends, the transcript's words equal to the saved messages, and no console
+// errors. Prints a pass/fail table and writes it, with each case's evidence, to --out.
+//
+// node --experimental-strip-types scripts/verify-live-reply.ts [--engines claude,codex,acp,cline,copilot]
+// [--cases short,long,...] [--skip-room] [--out DIR] [--cadence 4:30]
+//
+// Needs the pinned test browser (OMB_AGENT_BROWSER_PATH / AGENT_BROWSER_EXECUTABLE_PATH, as control-omb ui launch).
+import { spawn, type ChildProcess } from "node:child_process";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { parseArgs } from "node:util";
+
+import { caseTokens, LIVE_REPLY_CASES, liveReplyScripts, type LiveReplyCase } from "../server/testing/live-reply-cases.ts";
+import { runControlOmbUi } from "./testing/control-omb-ui.ts";
+
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
+/** The instance each engine's fixture adds, and the model Pepper is moved to. */
+const ENGINES: Record<string, { flag?: string; instanceId: string; model: string }> = {
+ claude: { instanceId: "claude", model: "claude-sonnet-5" },
+ codex: { flag: "codex", instanceId: "codex", model: "gpt-fake-default" },
+ acp: { flag: "acp", instanceId: "myAgent", model: "fixture-fast" },
+ cline: { flag: "cline", instanceId: "cline", model: "cline-default" },
+ copilot: { flag: "copilot", instanceId: "githubCopilot", model: "claude-haiku-4.5" },
+ // A real OpenCode at OMB_VERIFY_OPENCODE_CLI, on a free model it offers with no key: real prompts, not scripts.
+ opencode: { flag: "opencode", instanceId: "opencode", model: "" },
+};
+/** Prompts for a real engine: each asks for its own token, so the checks can find the reply's words. */
+const REAL_CASES: Array<LiveReplyCase & { prompt: string; tokens: string[] }> = [
+ { name: "real-short", marker: "", steps: [], prompt: "Reply with one short sentence that begins with the word R1M1.", tokens: ["R1M1"] },
+ { name: "real-markdown", marker: "", steps: [], prompt: "Begin your reply with the word R2M1, then give a markdown heading, a bulleted list of three fruits and a two-row table of their colours.", tokens: ["R2M1"] },
+ { name: "real-code", marker: "", steps: [], prompt: "Begin your reply with the word R3M1, then show a three-line Python code block that prints hello, then one closing sentence.", tokens: ["R3M1"] },
+ { name: "real-long", marker: "", steps: [], prompt: "Begin your reply with the word R4M1, then write four short paragraphs about why tea is popular. Do not use any tools.", tokens: ["R4M1"] },
+];
+const STEERS = new Set(["claude"]);
+
+interface Handle { ui: string; url: string; botId: string }
+interface Verdict { engine: string; name: string; ok: boolean; problems: string[] }
+
+const { values } = parseArgs({ options: {
+ engines: { type: "string", default: Object.keys(ENGINES).join(",") },
+ cases: { type: "string" },
+ "skip-room": { type: "boolean", default: false },
+ out: { type: "string" },
+ cadence: { type: "string", default: "4:30" },
+} });
+const out = values.out ?? mkdtempSync(join(tmpdir(), "omb-live-reply-verify-"));
+mkdirSync(out, { recursive: true });
+const scripts = join(out, "scripts.json");
+writeFileSync(scripts, JSON.stringify(liveReplyScripts()));
+const wanted = values.cases?.split(",") ?? null;
+const cases = LIVE_REPLY_CASES.filter((entry) => !wanted || wanted.includes(entry.name));
+
+/** How often a token appears: `T2M1` is not counted inside `T2M1z` (a row's time can follow a token directly). */
+const occurrences = (text: string, token: string) => (text.match(new RegExp(`${token}(?!z)`, "g")) ?? []).length;
+const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+const ui = (handle: Handle, ...args: string[]) => runControlOmbUi([args[0]!, "--ui", handle.ui, ...args.slice(1)]) as Promise<any>;
+const evaluate = async (handle: Handle, js: string): Promise<any> => {
+ const result = await ui(handle, "eval", "--js", js);
+ return result.result ?? result.data?.result;
+};
+const api = async (handle: Handle, method: string, path: string, body?: unknown): Promise<any> => {
+ const response = await fetch(`${handle.url}${path}`, { method, headers: { "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+ const result = await response.json();
+ if (!response.ok) throw new Error(`${method} ${path}: ${JSON.stringify(result)}`);
+ return result;
+};
+
+/** Starts a fixture and resolves with its handle once it has printed it. */
+function launch(engine: string): Promise<{ child: ChildProcess; handle: Handle }> {
+ const flag = ENGINES[engine]!.flag;
+ const child = spawn(process.execPath, ["--experimental-strip-types", join(ROOT, "scripts", "control-omb.ts"), "ui", "launch", ...(flag ? ["--engine", flag] : [])], {
+ cwd: ROOT, env: { ...process.env, FAKE_STREAM_SCRIPT: scripts, FAKE_STREAM_CADENCE: values.cadence }, stdio: ["ignore", "pipe", "pipe"],
+ });
+ return new Promise((resolve, reject) => {
+ let text = "";
+ child.stdout!.on("data", (chunk) => {
+ text += chunk;
+ const start = text.indexOf("{");
+ const end = text.lastIndexOf("}");
+ if (start < 0 || end < start) return;
+ try {
+ const parsed = JSON.parse(text.slice(start, end + 1));
+ resolve({ child, handle: { ui: parsed.ui, url: parsed.url, botId: parsed.botId } });
+ } catch {}
+ });
+ child.once("exit", (code) => reject(new Error(`ui launch exited ${code}: ${text.slice(-500)}`)));
+ });
+}
+
+async function stop(child: ChildProcess): Promise<void> {
+ if (child.exitCode !== null) return;
+ child.kill("SIGINT");
+ await new Promise((resolve) => child.once("exit", resolve));
+}
+
+/** Samples every animation frame: which tokens the open chat shows and how often, which ones each streamed row holds. */
+const SAMPLER = (tokens: string[], chat: string) => `(() => {
+ const tokens = ${JSON.stringify(tokens)};
+ const frames = [];
+ window.__liveReply = frames;
+ const count = (text, token) => (text.match(new RegExp(token + '(?!z)', 'g')) || []).length;
+ const sample = () => {
+ const log = document.querySelector('[role="log"]');
+ const label = log ? log.getAttribute('aria-label') || '' : '';
+ // The person's own lines are left out: a steer quotes a token the reply then says.
+ const bot = log ? log.cloneNode(true) : null;
+ bot?.querySelectorAll('[data-message-row].items-end').forEach((row) => row.remove());
+ const text = bot ? bot.textContent : '';
+ const rows = [...document.querySelectorAll('[data-mid^="live:"]')].map((row) => tokens.filter((token) => count(row.textContent, token) > 0));
+ frames.push({ chat: label.includes(${JSON.stringify(chat)}), counts: tokens.map((token) => count(text, token)), rows, think: /THINK\\d/.test(text) });
+ };
+ // A headless page with nothing moving may draw no frames; the checks take one more sample of the page as it is.
+ window.__liveReplySample = sample;
+ const tick = () => {
+ sample();
+ if (frames.length < 30000) requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ return 'sampling';
+})()`;
+
+const CONSOLE_ERRORS = async (handle: Handle): Promise<number> => {
+ const result = await ui(handle, "console");
+ const entries = Object.values(result).find((value) => Array.isArray(value)) as Array<Record<string, unknown>> | undefined
+ ?? Object.values(result.data ?? {}).find((value) => Array.isArray(value)) as Array<Record<string, unknown>> | undefined ?? [];
+ return entries.filter((entry) => (entry.type ?? entry.level) === "error").length;
+};
+
+async function runCase(handle: Handle, engine: string, entry: LiveReplyCase & { prompt?: string; tokens?: string[] }, context: { threadId: string; otherBotRow: string; botRow: string; composer: string; chat: string }): Promise<Verdict> {
+ const tokens = entry.tokens ?? caseTokens(entry);
+ const problems: string[] = [];
+ if (entry.action === "steer" && !STEERS.has(engine)) return { engine, name: entry.name, ok: true, problems: ["skipped: this engine does not steer in its fake"] };
+ const errorsBefore = await CONSOLE_ERRORS(handle);
+ const savedBefore = new Set(((await api(handle, "GET", `/api/threads/${context.threadId}/messages`)).messages as Array<{ id: string }>).map((message) => message.id));
+ await evaluate(handle, SAMPLER([...tokens, ...(entry.action === "steer" ? ["T13STEER"] : [])], context.chat));
+ await ui(handle, "type", "--name", context.composer, "--text", entry.prompt ?? `Please answer ${entry.marker}`);
+ await ui(handle, "press", "--keys", "Enter");
+ if (entry.action) {
+ await pause(2_500);
+ if (entry.action === "stop") await evaluate(handle, `(() => { const b = [...document.querySelectorAll('button')].find((x) => x.textContent.trim() === 'Stop' || /^Stop\b/.test(x.getAttribute('aria-label') || '')); b?.click(); return Boolean(b); })()`);
+ if (entry.action === "steer") {
+ await ui(handle, "type", "--name", context.composer, "--text", "also mention T13STEER");
+ await ui(handle, "press", "--keys", "Enter");
+ }
+ if (entry.action === "reconnect") await evaluate(handle, "window.dispatchEvent(new Event('omb:retry-live-events')); 'retried'");
+ if (entry.action === "switch") {
+ await evaluate(handle, `document.querySelector(${JSON.stringify(context.otherBotRow)})?.click(); 'away'`);
+ await pause(1_500);
+ await evaluate(handle, `document.querySelector(${JSON.stringify(context.botRow)})?.click(); 'back'`);
+ }
+ }
+ const settled = await ui(handle, "wait-settle", "--timeout", "120").catch((error: unknown) => ({ ok: false, error: String(error) }));
+ if (settled?.ok === false) problems.push(`did not settle: ${JSON.stringify(settled).slice(0, 200)}`);
+ await pause(600);
+ const frames: Array<{ chat: boolean; counts: number[]; rows: string[][]; think: boolean }> = (await evaluate(handle, "(window.__liveReplySample(), JSON.stringify(window.__liveReply))").then((raw: string) => JSON.parse(raw)));
+ const all = [...tokens, ...(entry.action === "steer" ? ["T13STEER"] : [])];
+ const saved = ((await api(handle, "GET", `/api/threads/${context.threadId}/messages`)).messages as Array<{ id: string; role: string; kind: string; text?: string }>)
+ .filter((message) => !savedBefore.has(message.id) && message.role === "bot" && message.kind === "text");
+ const savedText = saved.map((message) => message.text ?? "").join("\n");
+ const inChat = frames.filter((frame) => frame.chat);
+ // A token said again in a message saved again (an automatic retry) is not a double.
+ const allowed = all.map((token) => Math.max(1, saved.filter((message) => occurrences(message.text ?? "", token) > 0).length));
+ const doubled = inChat.filter((frame) => frame.counts.some((count, index) => count > allowed[index]!)).length;
+ if (doubled) problems.push(`${doubled} frames show a message's words twice`);
+ // Glued: one streamed row holding words the server saved as two messages.
+ const owner = (token: string) => saved.findIndex((message) => occurrences(message.text ?? "", token) > 0);
+ const glued = inChat.filter((frame) => frame.rows.some((row) => new Set(row.map(owner).filter((index) => index >= 0)).size > 1)).length;
+ if (glued) problems.push(`${glued} frames glue two saved messages in one streamed row`);
+ if (inChat.some((frame) => frame.think)) problems.push("thinking shown as reply text");
+ all.forEach((token, index) => {
+ const kept = occurrences(savedText, token) > 0;
+ const first = inChat.findIndex((frame) => frame.counts[index]! > 0);
+ if (first < 0) {
+ if (kept) problems.push(`${token} saved but never shown`);
+ return;
+ }
+ const gone = inChat.slice(first).filter((frame) => frame.counts[index] === 0).length;
+ if (gone && kept) problems.push(`${token} vanished in ${gone} frames`);
+ });
+ const last = inChat.at(-1);
+ if (!last) problems.push("no frame of the chat was sampled");
+ else {
+ if (last.rows.length) problems.push(`${last.rows.length} streamed rows left after the turn`);
+ all.forEach((token, index) => {
+ const want = occurrences(savedText, token);
+ if (last.counts[index] !== want) problems.push(`${token}: the transcript shows ${last.counts[index]}, the saved messages ${want}`);
+ });
+ }
+ if (!entry.action && !["error"].includes(entry.name)) for (const token of tokens) if (!occurrences(savedText, token) > 0) problems.push(`${token} not saved`);
+ const errors = (await CONSOLE_ERRORS(handle)) - errorsBefore;
+ if (errors > 0) problems.push(`${errors} console errors`);
+ const streamedFrames = inChat.filter((frame) => frame.rows.length > 0).length;
+ writeFileSync(join(out, `${engine}-${entry.name}.json`), JSON.stringify({ problems, frames: frames.length, streamedFrames, lastFrame: inChat.at(-1), tokens: all, saved }, null, 2));
+ await ui(handle, "screenshot", "--out", join(out, `${engine}-${entry.name}.png`)).catch(() => {});
+ return { engine, name: entry.name, ok: problems.length === 0, problems };
+}
+
+async function runRoom(handle: Handle, engine: string): Promise<Verdict> {
+ const problems: string[] = [];
+ const spec = ENGINES[engine]!;
+ const basil = (await api(handle, "POST", "/api/bots", { name: "Basil", modelSelection: { instanceId: spec.instanceId, model: spec.model } })).bot;
+ const room = (await api(handle, "POST", "/api/groups", { memberIds: [handle.botId, basil.id], name: "Launch room",
+ setup: { bulletin: "", defaultResponder: { kind: "member", botId: handle.botId } } })).group;
+ const row = `[data-sidebar-group-row="${room.id}"]`;
+ for (let tries = 0; tries < 40 && !(await evaluate(handle, `Boolean(document.querySelector('${row}'))`)); tries++) await pause(250);
+ await evaluate(handle, `document.querySelector('${row}')?.click(); 'opened'`);
+ for (let tries = 0; tries < 40 && !(await evaluate(handle, `Boolean(document.querySelector('textarea[aria-label="Message Launch room"]'))`)); tries++) await pause(250);
+ const entry = LIVE_REPLY_CASES.find((candidate) => candidate.name === "two-messages")!;
+ const tokens = caseTokens(entry);
+ await evaluate(handle, SAMPLER(tokens, "Launch room"));
+ const errorsBefore = await CONSOLE_ERRORS(handle);
+ for (const name of ["Pepper", "Basil"]) {
+ await ui(handle, "type", "--name", "Message Launch room", "--text", `@${name} please answer ${entry.marker}`);
+ await ui(handle, "press", "--keys", "Enter");
+ await ui(handle, "wait-settle", "--timeout", "120").catch((error: unknown) => problems.push(`did not settle: ${String(error).slice(0, 120)}`));
+ }
+ await pause(600);
+ const frames: Array<{ chat: boolean; counts: number[]; rows: string[][] }> = JSON.parse(await evaluate(handle, "(window.__liveReplySample(), JSON.stringify(window.__liveReply))"));
+ const saved = ((await api(handle, "GET", `/api/threads/${room.threadId}/messages`)).messages as Array<{ role: string; kind: string; text?: string; from?: { name: string } }>)
+ .filter((message) => message.role === "bot" && message.kind === "text" && tokens.some((token) => occurrences(message.text ?? "", token) > 0));
+ const speakers = new Set(saved.map((message) => message.from?.name));
+ if (speakers.size < 2) problems.push(`only ${[...speakers].join(", ") || "nobody"} replied`);
+ const inChat = frames.filter((frame) => frame.chat);
+ const most = tokens.map((_, index) => Math.max(...inChat.map((frame) => frame.counts[index]!)));
+ tokens.forEach((token, index) => {
+ const want = saved.filter((message) => occurrences(message.text ?? "", token) > 0).length;
+ if (most[index]! > want) problems.push(`${token} shown ${most[index]} times, saved ${want}`);
+ });
+ const owner = (token: string) => saved.findIndex((message) => occurrences(message.text ?? "", token) > 0);
+ if (inChat.some((frame) => frame.rows.some((row) => new Set(row.map(owner).filter((index) => index >= 0)).size > 1))) problems.push("two saved messages glued in one streamed row");
+ if (inChat.at(-1)?.rows.length) problems.push("streamed rows left after the turns");
+ const errors = (await CONSOLE_ERRORS(handle)) - errorsBefore;
+ if (errors > 0) problems.push(`${errors} console errors`);
+ await ui(handle, "screenshot", "--out", join(out, `${engine}-room.png`)).catch(() => {});
+ return { engine, name: "room, two bots", ok: problems.length === 0, problems };
+}
+
+const verdicts: Verdict[] = [];
+for (const engine of values.engines!.split(",")) {
+ const spec = ENGINES[engine];
+ if (!spec) throw new Error(`unknown engine ${engine}`);
+ const { child, handle } = await launch(engine);
+ try {
+ let model = spec.model;
+ if (engine === "opencode") {
+ const instances = (await api(handle, "GET", "/api/instances")).instances as Array<{ instanceId: string; models?: { options?: Array<{ id: string }> } }>;
+ const offered = instances.find((instance) => instance.instanceId === spec.instanceId)?.models?.options?.map((option) => option.id) ?? [];
+ model = offered.find((id) => /(^|[-_/])free$/i.test(id)) ?? "";
+ process.stderr.write(`opencode offers ${offered.length} models; free: ${model || "none"}\n`);
+ if (!model) {
+ verdicts.push({ engine, name: "real OpenCode", ok: true, problems: ["skipped: no free model offered without a sign-in"] });
+ continue;
+ }
+ }
+ await api(handle, "PATCH", `/api/bots/${handle.botId}`, { modelSelection: { instanceId: spec.instanceId, model } });
+ const bots = (await api(handle, "GET", "/api/bots")).bots as Array<{ id: string; name: string; threadId: string }>;
+ const pepper = bots.find((bot) => bot.id === handle.botId)!;
+ const other = bots.find((bot) => bot.id !== handle.botId)!;
+ await evaluate(handle, "localStorage.setItem('omb-advanced-mode', 'true'); location.reload(); 'reloaded'");
+ await pause(4_000);
+ await ui(handle, "flag", "--set", "features.showToolCalls=true");
+ const before = await CONSOLE_ERRORS(handle);
+ await evaluate(handle, "console.error('verify-live-reply console probe'); 'probed'");
+ if ((await CONSOLE_ERRORS(handle)) !== before + 1) throw new Error("the console check cannot see console errors");
+ const context = { threadId: pepper.threadId, chat: "Pepper", composer: "Message Pepper",
+ botRow: `[data-sidebar-bot-row="${pepper.id}"]`, otherBotRow: `[data-sidebar-bot-row="${other.id}"]` };
+ for (const entry of engine === "opencode" ? REAL_CASES : cases) {
+ const verdict = await runCase(handle, engine, entry, context).catch((error: unknown) => ({ engine, name: entry.name, ok: false, problems: [String(error).slice(0, 300)] }));
+ verdicts.push(verdict);
+ process.stderr.write(`${verdict.ok ? "pass" : "FAIL"} ${engine} ${entry.name} ${verdict.problems.join("; ")}\n`);
+ }
+ if (!values["skip-room"] && engine !== "opencode") {
+ const verdict = await runRoom(handle, engine).catch((error: unknown) => ({ engine, name: "room, two bots", ok: false, problems: [String(error).slice(0, 300)] }));
+ verdicts.push(verdict);
+ process.stderr.write(`${verdict.ok ? "pass" : "FAIL"} ${engine} room ${verdict.problems.join("; ")}\n`);
+ }
+ } finally {
+ await stop(child);
+ }
+}
+
+const names = [...new Set(verdicts.map((verdict) => verdict.name))];
+const engines = [...new Set(verdicts.map((verdict) => verdict.engine))];
+const table = [
+ `| Case | ${engines.join(" | ")} |`,
+ `| --- | ${engines.map(() => "---").join(" | ")} |`,
+ ...names.map((name) => `| ${name} | ${engines.map((engine) => {
+ const verdict = verdicts.find((candidate) => candidate.engine === engine && candidate.name === name);
+ return !verdict ? "" : verdict.ok ? (verdict.problems[0]?.startsWith("skipped") ? "skip" : "pass") : `FAIL: ${verdict.problems.join("; ").replaceAll("|", "/")}`;
+ }).join(" | ")} |`),
+].join("\n");
+writeFileSync(join(out, "results.md"), `${table}\n`);
+process.stdout.write(`${table}\n\nevidence: ${out}\n`);
+process.exitCode = verdicts.every((verdict) => verdict.ok) ? 0 : 1;
diff --git a/server/drivers/acp/acp.test.ts b/server/drivers/acp/acp.test.ts
index ac3da3d4b5..3419723475 100644
--- a/server/drivers/acp/acp.test.ts
+++ b/server/drivers/acp/acp.test.ts
@@ -10,6 +10,7 @@ import { BUILT_IN_DATA_SYSTEM_PROMPT } from "../../data/instructions.ts";
import type { ProviderInstance } from "../../contracts.ts";
import { TurnNotStartedError } from "../../contracts.ts";
import { recordEvents, type EventRecorder } from "../../testing/events.ts";
+import { publishedMessages } from "../../harness/text-items.testkit.ts";
import { promptSplitFingerprints, writePromptSplitReceipt } from "../prompt-split.ts";
import { classifyError } from "../retry.ts";
import { createAcpDriver, skipSubscriptionAuthForLocalInject, type AcpSupport } from "./core.ts";
@@ -1001,6 +1002,11 @@ describe("ACP turns (fake CLI)", () => {
.filter((e) => e.type === "item.completed" && (e as { itemType?: string }).itemType === "assistant_text")
.map((e) => (e as { text: string }).text);
expect(texts).toEqual(["before one", "before two", "after"]);
+ expect(publishedMessages(recorder.events), "each message's words and its completion share one id of their own").toEqual([
+ { itemId: expect.any(String), streamed: "before one", completed: "before one" },
+ { itemId: expect.any(String), streamed: "before two", completed: "before two" },
+ { itemId: expect.any(String), streamed: "after", completed: "after" },
+ ]);
});
it("normalizes a structured ACP image block without treating it as text", async () => {
diff --git a/server/drivers/acp/hermes-steer.test.ts b/server/drivers/acp/hermes-steer.test.ts
index a6a22842b8..d87e9ba78c 100644
--- a/server/drivers/acp/hermes-steer.test.ts
+++ b/server/drivers/acp/hermes-steer.test.ts
@@ -9,6 +9,7 @@ import { ensureDirs } from "../../config.ts";
import type { AnyProviderDriver, ProviderInstance } from "../../contracts.ts";
import { removeTempDir } from "../../testing/cleanup.ts";
import { recordEvents, type EventRecorder } from "../../testing/events.ts";
+import { publishedMessages } from "../../harness/text-items.testkit.ts";
import { AntigravityDriver } from "../antigravity.ts";
import { ClineAgentDriver } from "./cline.ts";
import { CommandCodeAgentDriver } from "./command-code.ts";
@@ -109,6 +110,10 @@ describe("Hermes steering", () => {
expect(replyOf(turnId)).toEqual(["working. done; steered: Use pytest, not unittest.\nAnd keep it short."]);
const shown = recorder!.events.filter((event) => event.turnId === turnId && event.type === "content.delta").map((event) => event.type === "content.delta" ? event.delta : "");
expect(shown.join("")).not.toContain("Steer queued");
+ expect(publishedMessages(recorder!.events.filter((event) => event.turnId === turnId)).map(({ streamed, completed }) => ({ streamed, completed })),
+ "a steered turn is still one message under one id, with Hermes's own line left out").toEqual([
+ { streamed: "working. done; steered: Use pytest, not unittest.\nAnd keep it short.", completed: "working. done; steered: Use pytest, not unittest.\nAnd keep it short." },
+ ]);
});
it("refuses a steer once the turn has ended, without sending it", async () => {
diff --git a/server/drivers/acp/live-reply-matrix.test.ts b/server/drivers/acp/live-reply-matrix.test.ts
new file mode 100644
index 0000000000..ecc68b2b23
--- /dev/null
+++ b/server/drivers/acp/live-reply-matrix.test.ts
@@ -0,0 +1,81 @@
+// Every ACP engine's adapter against the scripted ACP peer, for each streamed reply case: the words and completion of
+// each message share one id, and nothing is doubled, lost, glued to another message or shown from thinking.
+import { mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import { ensureDirs } from "../../config.ts";
+import type { ProviderDriver, RuntimeEvent } from "../../contracts.ts";
+import { replyProblems } from "../../harness/text-items.testkit.ts";
+import { removeTempDir } from "../../testing/cleanup.ts";
+import { recordEvents } from "../../testing/events.ts";
+import { caseTokens, LIVE_REPLY_CASES, liveReplyScripts } from "../../testing/live-reply-cases.ts";
+import type { AcpConfig } from "./core.ts";
+import { ClineAgentDriver } from "./cline.ts";
+import { CommandCodeAgentDriver } from "./command-code.ts";
+import { CopilotAgentDriver } from "./copilot.ts";
+import { CursorAgentDriver } from "./cursor.ts";
+import { CustomAcpDriver } from "./custom.ts";
+import { DeepSeekAgentDriver } from "./deepseek.ts";
+import { DroidAgentDriver } from "./droid.ts";
+import { GeminiAgentDriver } from "./gemini.ts";
+import { GrokAgentDriver } from "./grok.ts";
+import { HermesAgentDriver } from "./hermes.ts";
+import { KimiAgentDriver } from "./kimi.ts";
+import { KiroAgentDriver } from "./kiro.ts";
+import { createOpenCodeDriver } from "./opencode-go.ts";
+import { QwenAgentDriver } from "./qwen.ts";
+
+const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "../../testing/fake-acp-cli.ts");
+const OpenCodeDriver = createOpenCodeDriver(async () => ({
+ default: "opencode/fixture-model",
+ options: [{ id: "opencode/fixture-model", label: "Fixture model" }],
+}));
+const ENGINES: ProviderDriver<AcpConfig>[] = [
+ OpenCodeDriver, HermesAgentDriver, GeminiAgentDriver, KimiAgentDriver, QwenAgentDriver, GrokAgentDriver, DeepSeekAgentDriver,
+ DroidAgentDriver, CommandCodeAgentDriver, KiroAgentDriver, CursorAgentDriver, ClineAgentDriver, CopilotAgentDriver, CustomAcpDriver,
+] as ProviderDriver<AcpConfig>[];
+const CASES = LIVE_REPLY_CASES.filter((entry) => entry.action === undefined || entry.action === "stop");
+
+let scratch: string;
+let scripts: string;
+beforeAll(() => {
+ ensureDirs();
+ scratch = mkdtempSync(join(tmpdir(), "omb-live-reply-acp-"));
+ scripts = join(scratch, "scripts.json");
+ writeFileSync(scripts, JSON.stringify(liveReplyScripts()));
+});
+afterAll(async () => { await removeTempDir(scratch); });
+
+describe.each(ENGINES.map((driver) => ({ driver, kind: driver.driverKind })))("$kind streams each reply message under its own id", ({ driver }) => {
+ it.each(CASES.map((entry) => ({ entry, name: entry.name })))("$name", async ({ entry }) => {
+ const home = mkdtempSync(join(scratch, `${driver.driverKind}-`));
+ const instance = await driver.create({
+ instanceId: `live-reply-${driver.driverKind}`,
+ displayName: "Live reply fixture",
+ enabled: true,
+ environment: {
+ HOME: home, USERPROFILE: home, HERMES_HOME: join(home, ".hermes"), CLINE_DATA_DIR: join(home, "cline"), CLINE_PROVIDER: "openai-compatible", CLINE_MODEL: "fixture-model", CLINE_API_KEY: "fixture-only", KIMI_CODE_HOME: join(home, ".kimi"),
+ OPENMAUSBOT_PROBE_LOCAL_INJECT: "0", OPENCODE_API_KEY: "fixture-only", DEEPSEEK_API_KEY: "fixture-only", KIRO_API_KEY: "fixture-only", FAKE_ACP_AUTOPILOT: "1",
+ FAKE_STREAM_SCRIPT: scripts, FAKE_STREAM_CADENCE: entry.action === "stop" ? "6:5" : "7:0",
+ },
+ config: { cli: FAKE_CLI, fullAuto: true },
+ });
+ const recorder = recordEvents(instance.adapter);
+ try {
+ const { turnId } = await instance.adapter.sendTurn({ threadId: `live-${entry.name}`, text: `Please answer ${entry.marker}`, cwd: home, approvalMode: "full" });
+ if (entry.action === "stop") {
+ await recorder.until((event) => event.type === "content.delta" && event.turnId === turnId);
+ await instance.adapter.interruptTurn(`live-${entry.name}`);
+ }
+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId, 30_000);
+ const events = recorder.events.filter((event): event is RuntimeEvent => event.turnId === turnId);
+ expect(replyProblems(events, caseTokens(entry), { stopped: entry.action === "stop" })).toEqual([]);
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ }
+ }, 60_000);
+});
diff --git a/server/drivers/claude-live-reply.test.ts b/server/drivers/claude-live-reply.test.ts
new file mode 100644
index 0000000000..45afe717ea
--- /dev/null
+++ b/server/drivers/claude-live-reply.test.ts
@@ -0,0 +1,55 @@
+// The Claude adapter against the fake CLI for each streamed reply case: each message's words and completion share one
+// id, and nothing is doubled, lost, glued to another message or shown from thinking.
+import { chmodSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import { ensureDirs } from "../config.ts";
+import { replyProblems } from "../harness/text-items.testkit.ts";
+import { removeTempDir } from "../testing/cleanup.ts";
+import { recordEvents } from "../testing/events.ts";
+import { caseTokens, LIVE_REPLY_CASES, liveReplyScripts } from "../testing/live-reply-cases.ts";
+import { ClaudeDriver } from "./claude.ts";
+
+const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-claude-cli.ts");
+const CASES = LIVE_REPLY_CASES.filter((entry) => entry.action === undefined || entry.action === "stop");
+
+let scratch: string;
+let scripts: string;
+beforeAll(() => {
+ ensureDirs();
+ chmodSync(FAKE_CLI, 0o755);
+ scratch = mkdtempSync(join(tmpdir(), "omb-claude-live-reply-"));
+ scripts = join(scratch, "scripts.json");
+ writeFileSync(scripts, JSON.stringify(liveReplyScripts()));
+});
+afterAll(async () => { await removeTempDir(scratch); });
+
+describe("Claude streams each reply message under its own id", () => {
+ it.each(CASES.map((entry) => ({ entry, name: entry.name })))("$name", async ({ entry }) => {
+ const instance = await ClaudeDriver.create({
+ instanceId: "claude-live-reply",
+ displayName: "Claude live reply",
+ environment: { FAKE_STREAM_SCRIPT: scripts, FAKE_STREAM_CADENCE: entry.action === "stop" ? "6:5" : "7:0" },
+ enabled: true,
+ config: { cli: FAKE_CLI, permissionMode: "acceptEdits" },
+ });
+ const recorder = recordEvents(instance.adapter);
+ try {
+ const threadId = `claude-live-${entry.name}`;
+ const { turnId } = await instance.adapter.sendTurn({ threadId, text: `Please answer ${entry.marker}`, approvalMode: "full" });
+ if (entry.action === "stop") {
+ await recorder.until((event) => event.type === "content.delta" && event.turnId === turnId, 30_000);
+ await instance.adapter.interruptTurn(threadId);
+ }
+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId, 30_000);
+ const events = recorder.events.filter((event) => event.turnId === turnId);
+ expect(replyProblems(events, caseTokens(entry), { stopped: entry.action === "stop" })).toEqual([]);
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ }
+ }, 60_000);
+});
diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.ts
index 6a70692b23..f37d5230cf 100644
--- a/server/drivers/codex.test.ts
+++ b/server/drivers/codex.test.ts
@@ -14,6 +14,8 @@ import { DATA_DIR, NATIVE_DIR } from "../config.ts";
import { flushNativeLog } from "./native.ts";
import { ChatGptPlanAuthController } from "./chatgpt-plan-auth.ts";
import { recordEvents, type EventRecorder } from "../testing/events.ts";
+import { publishedMessages, replyProblems } from "../harness/text-items.testkit.ts";
+import { caseTokens, LIVE_REPLY_CASES, liveReplyScripts } from "../testing/live-reply-cases.ts";
import { CodexDriver, codexNativeIncomingLogMessage, codexUpdateCommand } from "./codex.ts";
import { codexCliOverrides } from "./codex-process.ts";
import { parseToml } from "../toml-lite.ts";
@@ -2079,6 +2081,53 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
expect((settled[0] as any).text).toBe("done from fake codex");
});
+ it("keeps each streamed message under Codex's own item id, scoped to its turn", async () => {
+ const scripts = join(scratch, "scripts.json");
+ writeFileSync(scripts, JSON.stringify({ "#ids": [{ say: "First message." }, { tool: "ls" }, { say: "Second, after the command." }, { say: "Third." }] }));
+ process.env.FAKE_STREAM_SCRIPT = scripts;
+ process.env.FAKE_STREAM_CADENCE = "4:0";
+ try {
+ await create();
+ await instance.adapter.sendTurn({ threadId: "t-items", text: "hi #ids" });
+ await recorder.until((e) => e.type === "turn.completed");
+ } finally {
+ delete process.env.FAKE_STREAM_SCRIPT;
+ delete process.env.FAKE_STREAM_CADENCE;
+ }
+ const deltas = recorder.events.filter((e: any) => e.type === "content.delta" && e.streamKind === "assistant_text");
+ expect(new Set(deltas.map((e) => e.itemId))).toEqual(new Set(["m1", "m3", "m4"]));
+ const messages = publishedMessages(recorder.events);
+ expect(messages.map(({ streamed, completed }) => ({ streamed, completed }))).toEqual([
+ { streamed: "First message.", completed: "First message." },
+ { streamed: "Second, after the command.", completed: "Second, after the command." },
+ { streamed: "Third.", completed: "Third." },
+ ]);
+ const turnId = recorder.events.find((e) => e.type === "turn.started")?.turnId;
+ expect(messages.map((message) => message.itemId)).toEqual([`${turnId}:m1`, `${turnId}:m3`, `${turnId}:m4`]);
+ });
+
+ it.each(LIVE_REPLY_CASES.filter((entry) => entry.action === undefined || entry.action === "stop").map((entry) => ({ entry, name: entry.name })))(
+ "streams the $name reply with one id per message and nothing doubled, lost or glued", async ({ entry }) => {
+ const scripts = join(scratch, "scripts.json");
+ writeFileSync(scripts, JSON.stringify(liveReplyScripts()));
+ process.env.FAKE_STREAM_SCRIPT = scripts;
+ process.env.FAKE_STREAM_CADENCE = entry.action === "stop" ? "6:5" : "7:0";
+ try {
+ await create();
+ const { turnId } = await instance.adapter.sendTurn({ threadId: `t-${entry.name}`, text: `Please answer ${entry.marker}` });
+ if (entry.action === "stop") {
+ await recorder.until((e) => e.type === "content.delta" && e.turnId === turnId);
+ await instance.adapter.interruptTurn(`t-${entry.name}`);
+ }
+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === turnId, 30_000);
+ const events = recorder.events.filter((e) => e.turnId === turnId);
+ expect(replyProblems(events, caseTokens(entry), { stopped: entry.action === "stop" })).toEqual([]);
+ } finally {
+ delete process.env.FAKE_STREAM_SCRIPT;
+ delete process.env.FAKE_STREAM_CADENCE;
+ }
+ }, 60_000);
+
it("reports an apply_patch as it streams, for the chat's status line", async () => {
process.env.FAKE_CODEX_PATCH_BYTES = "6144";
try {
diff --git a/server/drivers/codex.ts b/server/drivers/codex.ts
index 0aafa92b01..e07da37d92 100644
--- a/server/drivers/codex.ts
+++ b/server/drivers/codex.ts
@@ -52,7 +52,7 @@ import { commandSummary, toolDetailPreview } from "../tool-summary.ts";
import { codexDeveloperInstructions, syncCodexInstructions } from "./codex-instructions.ts";
import { volatileContextNote, withContextNote } from "./prompt-split.ts";
import type { ApprovalMode } from "../../shared/approval-mode.ts";
-import { CodexDeviceAuthController } from "./codex-device-auth.ts";
+import { CodexDeviceAuthController } from "./codex-device-auth.ts"; import { messageItem } from "../harness/text-items.ts";
import { codexAccountEmail, codexHome } from "./codex-identity.ts";
import { linkSharedCodexHome } from "./codex-shared-home.ts";
import { containsControlCharacter, mcpAppApprovalForm, mcpAppApprovalText, mcpElicitationDeclined, plainRecord } from "./codex-app-approval.ts";
@@ -1069,7 +1069,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
const delta = typeof p.delta === "string" ? p.delta : "";
if (delta) {
state.sawStreamDelta = true;
- emit({ ...base(threadId, turnId), type: "content.delta", streamKind: "assistant_text", delta });
+ emit({ ...base(threadId, turnId), ...messageItem({ id: p.itemId }), type: "content.delta", streamKind: "assistant_text", delta });
}
break;
}
@@ -1113,10 +1113,10 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
if (item.text?.trim()) {
state.lastText = item.text;
if (!state.sawStreamDelta) {
- emit({ ...base(threadId, turnId), type: "content.delta", streamKind: "assistant_text", delta: item.text });
+ emit({ ...base(threadId, turnId), ...messageItem(item), type: "content.delta", streamKind: "assistant_text", delta: item.text });
}
state.sawStreamDelta = false;
- emit({ ...base(threadId, turnId), type: "item.completed", itemType: "assistant_text", text: item.text });
+ emit({ ...base(threadId, turnId), ...messageItem(item), type: "item.completed", itemType: "assistant_text", text: item.text });
}
openAsyncQuestion(item, asks, steerActiveTurn, (event) => emit({ ...base(threadId, turnId), ...event }));
} else if (item.type === "imageGeneration" && item.status !== "failed") {
diff --git a/server/drivers/openai-chat-tools.test.ts b/server/drivers/openai-chat-tools.test.ts
index 7486f79768..cb4d61fda7 100644
--- a/server/drivers/openai-chat-tools.test.ts
+++ b/server/drivers/openai-chat-tools.test.ts
@@ -9,7 +9,10 @@ import { afterEach, describe, expect, it } from "vitest";
import { ensureDirs, NATIVE_DIR } from "../config.ts";
import { BUILT_IN_DATA_SYSTEM_PROMPT } from "../data/instructions.ts";
-import type { ProviderInstance, SendTurnInput } from "../contracts.ts";
+import type { ProviderDriver, ProviderInstance, SendTurnInput } from "../contracts.ts";
+import { replyProblems } from "../harness/text-items.testkit.ts";
+import { caseTokens, LIVE_REPLY_CASES } from "../testing/live-reply-cases.ts";
+import type { StreamStep } from "../testing/stream-script.ts";
import { removeTempDir } from "../testing/cleanup.ts";
import { recordEvents } from "../testing/events.ts";
import { catalogServer, CUA_DRIVER_WINDOWS_TOOLS, syntheticToolNames } from "../testing/cua-driver-tools.ts";
@@ -17,6 +20,11 @@ import { startFakeHttpMcp } from "../testing/fake-http-mcp-server.ts";
import { whopLikeCatalog } from "../testing/whop-like-catalog.ts";
import { toolBudgetOf } from "../tool-budgets.ts";
import { GrokDriver } from "./grok.ts";
+import { GreenferenceDriver } from "./greenference.ts";
+import { GroqDriver } from "./groq.ts";
+import { MetaDriver } from "./meta.ts";
+import { MistralDriver } from "./mistral.ts";
+import { ModelgoDriver } from "./modelgo.ts";
import { CerebrasDriver } from "./cerebras.ts";
import { MinimaxDriver } from "./minimax.ts";
import { OpenAICompatDriver } from "./openai-compat.ts";
@@ -34,7 +42,15 @@ interface ChatRequest {
}
type Script = (body: ChatRequest, response: ServerResponse, round: number) => void;
-type Provider = "openai-compat" | "grok" | "minimax" | "cerebras";
+type Provider = "openai-compat" | "grok" | "minimax" | "cerebras" | keyof typeof KEYED_DRIVERS;
+/** OpenAI-compatible providers configured by a URL and their own key variable. */
+const KEYED_DRIVERS = {
+ greenference: [GreenferenceDriver, "GREENFERENCE_API_KEY"],
+ groq: [GroqDriver, "GROQ_API_KEY"],
+ meta: [MetaDriver, "META_API_KEY"],
+ mistral: [MistralDriver, "MISTRAL_API_KEY"],
+ modelgo: [ModelgoDriver, "MODELGO_API_KEY"],
+} as const;
const API_KEY_CANARY = "fixture-credential-cda00ee8d8384f54";
function deferred<T = void>() {
@@ -122,7 +138,10 @@ async function fixture(script: Script, provider: Provider = "openai-compat", api
const helper = join(directory, "mcp.mjs");
writeFileSync(helper, MCP_SCRIPT);
const common = { instanceId: randomUUID(), displayName: "Tool contract fixture", enabled: true };
- const instance: ProviderInstance = provider === "minimax"
+ const keyed = provider in KEYED_DRIVERS ? KEYED_DRIVERS[provider as keyof typeof KEYED_DRIVERS] : null;
+ const instance: ProviderInstance = keyed
+ ? await (keyed[0] as ProviderDriver<unknown>).create({ ...common, config: keyed[0].decodeConfig({ url: `${origin}/v1` }), environment: { [keyed[1]]: apiKey } })
+ : provider === "minimax"
? await MinimaxDriver.create({ ...common, config: { url: `${origin}/v1` }, environment: { MINIMAX_API_KEY: apiKey } })
: provider === "cerebras"
? await CerebrasDriver.create({ ...common, config: CerebrasDriver.decodeConfig({ url: `${origin}/v1` }), environment: { CEREBRAS_API_KEY: apiKey } })
@@ -161,6 +180,46 @@ async function fixture(script: Script, provider: Provider = "openai-compat", api
};
}
+describe("streamed reply messages from an OpenAI-compatible API", () => {
+ /** A case's steps as the API's rounds: words and reasoning streamed in pieces, each tool ending its round. */
+ const rounds = (steps: StreamStep[]) => {
+ const out: Array<{ chunks: unknown[]; fail?: string }> = [{ chunks: [] }];
+ let calls = 0;
+ for (const step of steps) {
+ const round = out.at(-1)!;
+ if ("fail" in step) round.fail = step.fail;
+ else if ("tool" in step) {
+ round.chunks.push(chunk({ tool_calls: [toolCall("audit_write", JSON.stringify({ name: `step-${++calls}`, value: step.tool }), `call-${calls}`)] }, "tool_calls"));
+ out.push({ chunks: [] });
+ } else {
+ const text = "say" in step ? step.say : step.think;
+ for (let at = 0; at < text.length; at += 7) round.chunks.push(chunk("say" in step ? { content: text.slice(at, at + 7) } : { reasoning_content: text.slice(at, at + 7) }));
+ }
+ }
+ return out;
+ };
+
+ const PROVIDERS: Provider[] = ["openai-compat", "grok", "minimax", "cerebras", "greenference", "groq", "meta", "mistral", "modelgo"];
+ it.each(PROVIDERS.flatMap((provider) => LIVE_REPLY_CASES.filter((entry) => entry.action === undefined).map((entry) => ({ provider, entry, name: entry.name }))))(
+ "$provider streams the $name reply with one id per message and nothing doubled, lost or glued", async ({ provider, entry }) => {
+ const script = rounds(entry.steps);
+ const f = await fixture((_body, response, round) => {
+ const step = script[round - 1];
+ if (!step) return answer(response, "ok");
+ if (step.fail) {
+ sse(response, step.chunks, false);
+ response.destroy();
+ return;
+ }
+ sse(response, round === script.length ? [...step.chunks, chunk({}, "stop")] : step.chunks);
+ }, provider);
+ const { turnId } = await f.start({ approvalMode: "full", text: `Please answer ${entry.marker}` });
+ await f.recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId, 30_000);
+ const events = f.recorder.events.filter((event) => event.turnId === turnId);
+ expect(replyProblems(events, caseTokens(entry))).toEqual([]);
+ }, 60_000);
+});
+
describe("bounded action announcement recovery", () => {
const later = `${"The terminal output is absent; the launch receipt only confirms the process. ".repeat(7)}\n\nLet me execute the commands to create the file and read it back.`;
diff --git a/server/drivers/pi.test.ts b/server/drivers/pi.test.ts
index c71004ec85..40215bbd4d 100644
--- a/server/drivers/pi.test.ts
+++ b/server/drivers/pi.test.ts
@@ -8,6 +8,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ensureDirs, NATIVE_DIR } from "../config.ts";
import type { ProviderInstance, RuntimeEvent } from "../contracts.ts";
import { recordEvents, type EventRecorder } from "../testing/events.ts";
+import { publishedMessages, replyProblems } from "../harness/text-items.testkit.ts";
+import { caseTokens, LIVE_REPLY_CASES, liveReplyScripts } from "../testing/live-reply-cases.ts";
import { removeTempDir } from "../testing/cleanup.ts";
import { encodeInjectId, localHost } from "./local-inject.ts";
import { buildMcpServers } from "./pi-mcp-servers.ts";
@@ -944,7 +946,29 @@ describe("PiDriver turns (fake CLI)", () => {
.filter((e) => e.type === "item.completed" && (e as { itemType: string }).itemType === "assistant_text")
.map((e) => (e as { text: string }).text);
expect(texts).toEqual(["before one", "before two", "after"]);
- });
+ expect(publishedMessages(recorder.events).map(({ streamed, completed }) => ({ streamed, completed }))).toEqual([
+ { streamed: "before one", completed: "before one" },
+ { streamed: "before two", completed: "before two" },
+ { streamed: "after", completed: "after" },
+ ]);
+ expect(new Set(publishedMessages(recorder.events).map((message) => message.itemId)).size).toBe(3);
+ });
+
+ it.each(LIVE_REPLY_CASES.filter((entry) => entry.action === undefined || entry.action === "stop").map((entry) => ({ entry, name: entry.name })))(
+ "streams the $name reply with one id per message and nothing doubled, lost or glued", async ({ entry }) => {
+ const scripts = join(mkdtempSync(join(tmpdir(), "omb-pi-live-")), "scripts.json");
+ writeFileSync(scripts, JSON.stringify(liveReplyScripts()));
+ await create(undefined, { FAKE_STREAM_SCRIPT: scripts, FAKE_STREAM_CADENCE: entry.action === "stop" ? "6:5" : "7:0" });
+ const threadId = `t-live-${entry.name}`;
+ const { turnId } = await instance.adapter.sendTurn({ threadId, text: `Please answer ${entry.marker}`, model: "ollama-cloud/glm-5.2" });
+ if (entry.action === "stop") {
+ await recorder.until((e) => e.type === "content.delta" && e.turnId === turnId);
+ await instance.adapter.interruptTurn(threadId);
+ }
+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === turnId, 30_000);
+ const events = recorder.events.filter((e) => e.turnId === turnId);
+ expect(replyProblems(events, caseTokens(entry), { stopped: entry.action === "stop" })).toEqual([]);
+ }, 60_000);
it("brokers a permission ask through request.opened → respondToRequest", async () => {
await create("permission");
diff --git a/server/harness/bus.test.ts b/server/harness/bus.test.ts
index a302dd102c..420c7c9058 100644
--- a/server/harness/bus.test.ts
+++ b/server/harness/bus.test.ts
@@ -441,6 +441,28 @@ describe("EventBus streamed text", () => {
expect(summary(logged("thread-1"))).toEqual(expected);
});
+ it("keys each message's text by its own id, merged per message and kept on its completion", async () => {
+ const bus = new EventBus();
+ const seen: RuntimeEvent[] = [];
+ bus.subscribe((event) => seen.push(event));
+
+ bus.publish(delta("\n", { eventId: "w" }));
+ bus.publish(delta("Let me ", { eventId: "a1" }));
+ bus.publish(delta("check.", { eventId: "a2" }));
+ bus.publish(testEvent({ eventId: "a", type: "item.completed", itemType: "assistant_text", text: "Let me check.", turnId: "turn-1" }));
+ bus.publish(testEvent({ eventId: "tool", type: "item.started", itemType: "tool", title: "Read", turnId: "turn-1" }));
+ bus.publish(delta("Done.", { eventId: "b1" }));
+ bus.publish(testEvent({ eventId: "b", type: "item.completed", itemType: "assistant_text", text: "Done.", turnId: "turn-1" }));
+
+ const text = seen.filter((event) => event.type === "content.delta" || (event.type === "item.completed" && event.itemType === "assistant_text"));
+ expect(text.map((event) => event.type === "content.delta" ? event.delta : event.type)).toEqual(["Let me check.", "item.completed", "Done.", "item.completed"]);
+ expect(text[0]!.itemId).toBeTruthy();
+ expect(text[1]!.itemId, "a message's completion carries its words' id").toBe(text[0]!.itemId);
+ expect(text[2]!.itemId).not.toBe(text[0]!.itemId);
+ expect(text[3]!.itemId).toBe(text[2]!.itemId);
+ await bus.flush();
+ });
+
it("never merges across threads, stream kinds, turns or synthetic text", async () => {
const bus = new EventBus();
const seen: RuntimeEvent[] = [];
diff --git a/server/harness/bus.ts b/server/harness/bus.ts
index ed155afc92..e7b6dac3fc 100644
--- a/server/harness/bus.ts
+++ b/server/harness/bus.ts
@@ -10,6 +10,7 @@ import { capThreadLog, currentThreadLogCap } from "../thread-log-rotation.ts";
import { newId, type ProviderAdapter, type ProviderInstance, type RuntimeEvent, type RuntimeEventListener } from "../contracts.ts";
import { LiveSteps } from "./live-steps.ts";
import { ProgressGate } from "./progress-gate.ts";
+import { TextItems } from "./text-items.ts";
const INCOMPLETE_LOG_MESSAGE =
"Canonical event history is incomplete: OpenMausBot could not write one or more events to disk. Live updates will continue.";
@@ -72,6 +73,7 @@ export class EventBus {
});
private readonly gate?: (event: RuntimeEvent) => boolean;
+ private readonly textItems = new TextItems();
/** `gate` sees each adapter event first; true means it took the event and publishes what it chooses. */
constructor(appendLog: EventLogAppend = defaultAppend, gate?: (event: RuntimeEvent) => boolean) {
@@ -96,7 +98,10 @@ export class EventBus {
}
}
- publish(raw: RuntimeEvent) {
+ publish(unstamped: RuntimeEvent) {
+ // Reply text is keyed by its message from here on: the delta merge below and every listener see the same id.
+ const raw = this.textItems.stamp(unstamped);
+ if (!raw) return;
if (raw.type === "turn.progress") {
this.progress.offer(this.steps.progress(raw));
return;
diff --git a/server/harness/public-reply.test.ts b/server/harness/public-reply.test.ts
new file mode 100644
index 0000000000..9bbbb91f5e
--- /dev/null
+++ b/server/harness/public-reply.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+
+import type { RuntimeEvent } from "../contracts.ts";
+import { redactSecretsInText } from "../redact.ts";
+import { publicReplyEvent, savedReplyText } from "./public-reply.ts";
+
+const words = (delta: string): RuntimeEvent =>
+ ({ eventId: "e1", provider: "fake", threadId: "t", createdAt: "", turnId: "turn-1", itemId: "turn-1:m1", type: "content.delta", streamKind: "assistant_text", delta }) as RuntimeEvent;
+
+describe("a reply as it goes out", () => {
+ it("carries a finished reply's text as its saved message holds it, and the bus's own copy is untouched", () => {
+ const text = "Done. <openmaus-goal>{\"status\":\"done\"}</openmaus-goal> Key sk-ant-api03-abcdefghijklmnopqrstuvwxyz";
+ const completed = { ...words(""), type: "item.completed", itemType: "assistant_text", text } as RuntimeEvent;
+ const sent = publicReplyEvent(completed);
+ expect(sent.type === "item.completed" && sent.itemType === "assistant_text" && sent.text).toBe(redactSecretsInText("Done. Key sk-ant-api03-abcdefghijklmnopqrstuvwxyz"));
+ expect(savedReplyText("plain words")).toBe("plain words");
+ expect(completed.type === "item.completed" && completed.itemType === "assistant_text" && completed.text).toBe(text);
+ });
+
+ it("names a room reply's speaker on its words, and nothing on a direct chat's or on thinking", () => {
+ const said = words("Hi ");
+ expect(publicReplyEvent(said, "b2")).toMatchObject({ botId: "b2", delta: "Hi " });
+ expect(publicReplyEvent(said)).toBe(said);
+ const thinking = { ...said, streamKind: "reasoning_text" } as RuntimeEvent;
+ expect(publicReplyEvent(thinking, "b2")).toBe(thinking);
+ });
+});
diff --git a/server/harness/public-reply.ts b/server/harness/public-reply.ts
new file mode 100644
index 0000000000..06160e33b9
--- /dev/null
+++ b/server/harness/public-reply.ts
@@ -0,0 +1,17 @@
+// A reply's runtime events as every client receives them: a finished reply's text as its saved message holds it (the
+// goal envelope out, credentials and held secrets masked), so the streamed bubble is swapped for the same words; and a
+// room reply's words naming the member who speaks them. Streamed words themselves go out as the engine writes them.
+import type { RuntimeEvent } from "../contracts.ts";
+import { redactSecretsInText } from "../redact.ts";
+import { visibleCoordinatorText } from "../group-goal-run.ts";
+
+/** A finished reply as its saved message holds it. */
+export function savedReplyText(text: string): string {
+ return redactSecretsInText(text.includes("openmaus-goal>") ? visibleCoordinatorText(text) : text);
+}
+
+export function publicReplyEvent(event: RuntimeEvent, speakerId?: string): RuntimeEvent {
+ if (event.type === "item.completed" && event.itemType === "assistant_text") return { ...event, text: savedReplyText(event.text) };
+ if (event.type === "content.delta" && event.streamKind === "assistant_text" && speakerId) return { ...event, botId: speakerId };
+ return event;
+}
diff --git a/server/harness/text-items.test.ts b/server/harness/text-items.test.ts
new file mode 100644
index 0000000000..e17c250ff0
--- /dev/null
+++ b/server/harness/text-items.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it } from "vitest";
+
+import type { RuntimeEvent } from "../contracts.ts";
+import { TextItems } from "./text-items.ts";
+import { publishedMessages } from "./text-items.testkit.ts";
+
+let seq = 0;
+const event = (fields: Partial<RuntimeEvent>, turnId = "turn-1"): RuntimeEvent =>
+ ({ eventId: `e${++seq}`, provider: "fake", threadId: "t", createdAt: "", turnId, ...fields }) as RuntimeEvent;
+const words = (delta: string, extra: Partial<RuntimeEvent> = {}, turnId?: string) =>
+ event({ type: "content.delta", streamKind: "assistant_text", delta, ...extra } as Partial<RuntimeEvent>, turnId);
+const done = (text: string, extra: Partial<RuntimeEvent> = {}, turnId?: string) =>
+ event({ type: "item.completed", itemType: "assistant_text", text, ...extra } as Partial<RuntimeEvent>, turnId);
+const tool = (itemId: string) => [
+ event({ type: "item.started", itemType: "tool", itemId, title: "ls" } as Partial<RuntimeEvent>),
+ event({ type: "item.completed", itemType: "tool", itemId, ok: true } as Partial<RuntimeEvent>),
+];
+
+describe("reply text ids", () => {
+ it("gives an engine that names no message one id per message: text, tool, text, tool, text", () => {
+ const messages = publishedMessages([
+ event({ type: "turn.started" }),
+ words("Looking "), words("first."), done("Looking first."),
+ ...tool("c1"),
+ words("Found "), words("three."), done("Found three."),
+ ...tool("c2"),
+ words("All "), words("done."), done("All done."),
+ event({ type: "turn.completed", ok: true } as Partial<RuntimeEvent>),
+ ]);
+ expect(messages.map(({ streamed, completed }) => ({ streamed, completed }))).toEqual([
+ { streamed: "Looking first.", completed: "Looking first." },
+ { streamed: "Found three.", completed: "Found three." },
+ { streamed: "All done.", completed: "All done." },
+ ]);
+ expect(new Set(messages.map((message) => message.itemId)).size).toBe(3);
+ });
+
+ it("starts a new message after one completes, with no tool between", () => {
+ const messages = publishedMessages([words("One. "), done("One."), words("Two."), done("Two.")]);
+ expect(messages.map((message) => message.completed)).toEqual(["One.", "Two."]);
+ expect(messages[0]!.itemId).not.toBe(messages[1]!.itemId);
+ });
+
+ it("closes a message a tool interrupts, so the words after it are a message of their own", () => {
+ const messages = publishedMessages([words("Half a thought "), ...tool("c1"), words("Then this."), done("Then this.")]);
+ expect(messages).toEqual([
+ { itemId: expect.any(String), streamed: "Half a thought " },
+ { itemId: expect.any(String), streamed: "Then this.", completed: "Then this." },
+ ]);
+ expect(messages[0]!.itemId).not.toBe(messages[1]!.itemId);
+ });
+
+ it("drops whitespace before a message's first word, and keeps it inside one", () => {
+ const items = new TextItems();
+ expect(items.stamp(words("\n\n"))).toBeNull();
+ const first = items.stamp(words("Para one."))!;
+ const gap = items.stamp(words("\n\n"))!;
+ expect(gap.itemId).toBe(first.itemId);
+ });
+
+ it("gives a completion with no streamed words an id too", () => {
+ expect(publishedMessages([done("Only at the end.")])).toEqual([{ itemId: expect.any(String), streamed: "", completed: "Only at the end." }]);
+ });
+
+ it("keeps an engine's own message ids, scoped to the turn so a reused id is a new message", () => {
+ const messages = publishedMessages([
+ words("Turn one.", { itemId: "m1" }), done("Turn one.", { itemId: "m1" }),
+ words("Turn two.", { itemId: "m1" }, "turn-2"), done("Turn two.", { itemId: "m1" }, "turn-2"),
+ ]);
+ expect(messages.map((message) => message.itemId)).toEqual(["turn-1:m1", "turn-2:m1"]);
+ });
+
+ it("starts a new message when the turn changes, and forgets an open one at the turn's end", () => {
+ const items = new TextItems();
+ const a = items.stamp(words("Stopped mid "))!;
+ items.stamp(event({ type: "turn.completed", ok: false } as Partial<RuntimeEvent>));
+ const b = items.stamp(words("Fresh ", {}, "turn-2"))!;
+ expect(b.itemId).not.toBe(a.itemId);
+ const c = items.stamp(words("in another turn ", {}, "turn-3"))!;
+ expect(c.itemId).not.toBe(b.itemId);
+ });
+
+ it("stamps an already stamped event the same way again", () => {
+ const items = new TextItems();
+ const once = items.stamp(words("Hello ", { itemId: "m1" }))!;
+ expect(new TextItems().stamp(once)!.itemId).toBe(once.itemId);
+ const minted = new TextItems().stamp(words("Hi "))!;
+ expect(new TextItems().stamp(minted)!.itemId).toBe(minted.itemId);
+ });
+
+ it("keeps threads apart", () => {
+ const items = new TextItems();
+ const a = items.stamp(words("A "))!;
+ const b = items.stamp({ ...words("B "), threadId: "u" })!;
+ expect(a.itemId).not.toBe(b.itemId);
+ expect(items.stamp(words("more A "))!.itemId).toBe(a.itemId);
+ });
+
+ it("leaves reasoning and every other event as it was", () => {
+ const items = new TextItems();
+ const thinking = event({ type: "content.delta", streamKind: "reasoning_text", delta: "hmm" } as Partial<RuntimeEvent>);
+ expect(items.stamp(thinking)).toBe(thinking);
+ const usage = event({ type: "thread.token-usage.updated", input: 1, output: 1 } as Partial<RuntimeEvent>);
+ expect(items.stamp(usage)).toBe(usage);
+ });
+});
diff --git a/server/harness/text-items.testkit.ts b/server/harness/text-items.testkit.ts
new file mode 100644
index 0000000000..cc2d0ca163
--- /dev/null
+++ b/server/harness/text-items.testkit.ts
@@ -0,0 +1,53 @@
+import type { RuntimeEvent } from "../contracts.ts";
+import { TextItems } from "./text-items.ts";
+
+/** A turn's reply messages as the bus publishes them: each message's id, the words streamed under it, and its
+ * completed text; throws when a delta or a completion carries no id. */
+export function publishedMessages(events: readonly RuntimeEvent[]): Array<{ itemId: string; streamed: string; completed?: string }> {
+ const items = new TextItems();
+ const messages = new Map<string, { itemId: string; streamed: string; completed?: string }>();
+ for (const raw of events) {
+ const event = items.stamp(raw);
+ if (!event) continue;
+ const text = event.type === "content.delta" && event.streamKind === "assistant_text" ? event.delta
+ : event.type === "item.completed" && event.itemType === "assistant_text" ? event.text : undefined;
+ if (text === undefined) continue;
+ if (!event.itemId) throw new Error(`${event.type} carries no item id`);
+ const message = messages.get(event.itemId) ?? { itemId: event.itemId, streamed: "" };
+ if (event.type === "content.delta") message.streamed += text;
+ else message.completed = text;
+ messages.set(event.itemId, message);
+ }
+ return [...messages.values()];
+}
+
+/** What is wrong with a turn's published reply text for a scripted case: words without an id, a message's words
+ * differing from its completion, a message's tokens doubled or lost, two messages under one id, or thinking shown as
+ * reply text. Empty when the turn is right. `stopped`: the turn ended early, so later tokens may be missing. */
+export function replyProblems(events: readonly RuntimeEvent[], tokens: readonly string[], options: { stopped?: boolean } = {}): string[] {
+ const problems: string[] = [];
+ let messages: ReturnType<typeof publishedMessages>;
+ try {
+ messages = publishedMessages(events);
+ } catch (error) {
+ return [String(error)];
+ }
+ const ids = messages.map((message) => message.itemId);
+ if (new Set(ids).size !== ids.length) problems.push("two messages share an id");
+ for (const message of messages) {
+ if (message.completed !== undefined && message.streamed && message.streamed.trim() !== message.completed.trim()) {
+ problems.push(`${message.itemId}: streamed ${JSON.stringify(message.streamed.slice(0, 60))} but completed ${JSON.stringify(message.completed.slice(0, 60))}`);
+ }
+ if (/THINK\d/.test(message.streamed + (message.completed ?? ""))) problems.push(`${message.itemId}: thinking shown as reply text`);
+ }
+ const shown = messages.map((message) => message.completed ?? message.streamed).join("\n");
+ const occurrences = (text: string, token: string) => (text.match(new RegExp(`${token}(?!z)`, "g")) ?? []).length;
+ for (const token of tokens) {
+ const count = occurrences(shown, token);
+ if (count > 1) problems.push(`${token} said ${count} times`);
+ const owners = messages.filter((message) => occurrences(message.completed ?? message.streamed, token) > 0).length;
+ if (count === 0 && !options.stopped) problems.push(`${token} lost`);
+ if (owners > 1) problems.push(`${token} in ${owners} messages`);
+ }
+ return problems;
+}
diff --git a/server/harness/text-items.ts b/server/harness/text-items.ts
new file mode 100644
index 0000000000..0f6a16f850
--- /dev/null
+++ b/server/harness/text-items.ts
@@ -0,0 +1,66 @@
+// Gives every piece of a bot's reply text the id of the message it belongs to, so a client keys streamed words by
+// message and never has to guess where one message ends and the next begins.
+import { newId, type RuntimeEvent } from "../contracts.ts";
+
+type Active = { turnId: string | undefined; itemId: string };
+
+const MINTED = "text-";
+
+/** The engine's own id for a message, for an event that should carry it. */
+export function messageItem(item: { id?: unknown }): { itemId?: string } {
+ return typeof item.id === "string" && item.id ? { itemId: item.id } : {};
+}
+
+const isTurnBoundary = (event: RuntimeEvent) =>
+ event.type === "turn.started" || event.type === "turn.completed" || event.type === "cap.exhausted" ||
+ event.type === "session.exited" || (event.type === "runtime.error" && event.terminal === true);
+
+/**
+ * One instance per event bus. An engine's own message id is kept, scoped to its turn (engines reuse ids such as "m1"
+ * from turn to turn); an engine that names no message gets one minted at its first visible word, closed when a tool
+ * starts, the message completes, or the turn ends.
+ */
+export class TextItems {
+ private readonly active = new Map<string, Active>();
+
+ /** The event as it should be published, or null for a delta that carries nothing yet (whitespace before any word). */
+ stamp(event: RuntimeEvent): RuntimeEvent | null {
+ const { threadId } = event;
+ if (isTurnBoundary(event)) {
+ this.active.delete(threadId);
+ return event;
+ }
+ if (event.type === "item.started" && event.itemType === "tool") {
+ this.active.delete(threadId);
+ return event;
+ }
+ if (event.type === "content.delta" && event.streamKind === "assistant_text") {
+ const itemId = this.open(event, event.delta.trim() === "");
+ return itemId ? { ...event, itemId } : null;
+ }
+ if (event.type === "item.completed" && event.itemType === "assistant_text") {
+ const itemId = this.open(event, false)!;
+ this.active.delete(threadId);
+ return { ...event, itemId };
+ }
+ return event;
+ }
+
+ private open(event: RuntimeEvent, whitespace: boolean): string | undefined {
+ const { threadId, turnId } = event;
+ const current = this.active.get(threadId);
+ const sameTurn = current && current.turnId === turnId;
+ if (event.itemId) {
+ const scope = `${turnId ?? "turn"}:`;
+ const itemId = event.itemId.startsWith(scope) || event.itemId.startsWith(MINTED) ? event.itemId : `${scope}${event.itemId}`;
+ this.active.set(threadId, { turnId, itemId });
+ return itemId;
+ }
+ if (current && sameTurn) return current.itemId;
+ // Whitespace before a message's first word opens nothing: a tool may follow, and then there was no message.
+ if (whitespace) return undefined;
+ const itemId = `${MINTED}${newId()}`;
+ this.active.set(threadId, { turnId, itemId });
+ return itemId;
+ }
+}
diff --git a/server/index.ts b/server/index.ts
index d6e7392972..af018f59bd 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -268,7 +268,7 @@ import {
sendFingerprint,
SendSequencer,
} from "./send-idempotency.ts";
-import { EventBus } from "./harness/bus.ts";
+import { EventBus } from "./harness/bus.ts"; import { publicReplyEvent } from "./harness/public-reply.ts";
import { ENGINE_LIST_REUSE_MS, engineMemory, enginesByUse, ProviderRegistry } from "./harness/registry.ts"; import { afterFirstEngineRead, holdUntilFirstEngineRead } from "./first-engine-read.ts"; import { HANDOFF_BROWSER_NOTE, HANDOFF_BROWSER_ONLY, handoffSurface, StoppedHandoffs, stoppedHandoffResult } from "./host/handoff-browser.ts";
import { ManagedDesktopProviders } from "./managed-desktop.ts";
import { mainThread, wasOldestThread } from "./main-thread.ts";
@@ -6344,14 +6344,14 @@ bus.subscribe((event: RuntimeEvent) => {
eventId: `${event.eventId}-goal-text`,
type: "item.completed",
itemType: "assistant_text",
- text: coordinatorVisibleText,
+ text: redactSecretsInText(coordinatorVisibleText),
};
broadcast({ kind: "runtime", event: publicAssistantEvent });
}
const privateImageEvent = event.type === "item.completed" && event.itemType === "assistant_image";
if (!privateImageEvent) {
// Exact executable input is internal; the bus's persistence redactor does not scrub the live event.
- const publicEvent = event.type === "request.opened" ? { ...event, command: undefined, commandLine: undefined, reads: undefined } : event;
+ const publicEvent = event.type === "request.opened" ? { ...event, command: undefined, commandLine: undefined, reads: undefined } : publicReplyEvent(event, groupSpeakers.get(event.threadId)?.botId);
broadcast({ kind: "runtime", event: publicEvent });
}
const routineRun = privateImageEvent ? null : (routines?.handleRuntimeEvent(event) ?? null);
@@ -6387,7 +6387,7 @@ bus.subscribe((event: RuntimeEvent) => {
pushStoppedTurn(turnId);
return;
}
- pushMessage({ role: "bot", kind: "text", text: spoken.text, turnId });
+ pushMessage({ role: "bot", kind: "text", text: spoken.text, turnId, ...(event.type === "item.completed" && event.itemId ? { itemId: event.itemId } : {}) });
lastReply.set(event.threadId, spoken.text);
};
const landParkedFiles = () => {
diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.ts
index 52b06e22e0..d3a987a555 100755
--- a/server/testing/fake-acp-cli.ts
+++ b/server/testing/fake-acp-cli.ts
@@ -6,6 +6,7 @@
// (FAKE_ACP_REJECT_LIVE_LOAD_DSH=1: with dsh 0.2's -32602 "session is already active" instead of -32000)
// FAKE_ACP_CACHED_LIVE_LOAD a live session/load is acknowledged but keeps the old MCP credentials, like Qwen
// FAKE_ACP_TEXT_REPLY answer every session/prompt with only this text
+// FAKE_STREAM_SCRIPT, FAKE_STREAM_CADENCE a scripted reply chosen by a marker in the prompt (stream-script.ts)
// FAKE_ACP_MODE happy (default) | image | empty-reply | reasoning-only | exit-early | fail-after-text | crash-in-prompt
// | abort-in-prompt (a sign-in link, then a TCMalloc CHECK line on stderr, then exit 134 as bubblewrap reports SIGABRT) | hang
// | hang-initialize | unkeyed-tool | finished-tools (tool_call frames that arrive already completed or failed, one updated again)
@@ -84,6 +85,49 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlink
const mode = process.env.FAKE_ACP_MODE ?? "happy";
+// The scripted replies every fake plays (FAKE_STREAM_SCRIPT, FAKE_STREAM_CADENCE); inlined, since tests copy this fake
+// out of the repo.
+type StreamStep = { say?: string; think?: string; tool?: string; fail?: string };
+type StreamScript = { steps: StreamStep[]; chars: number; ms: number };
+function streamScript(prompt: string): StreamScript | null {
+ if (!process.env.FAKE_STREAM_SCRIPT) return null;
+ let scripts: Record<string, StreamStep[]>;
+ try { scripts = JSON.parse(readFileSync(process.env.FAKE_STREAM_SCRIPT, "utf8")); } catch { return null; }
+ // A prompt can carry earlier requests as context: the newest marker in it is the request.
+ const marker = Object.keys(scripts).filter((key) => prompt.includes(key)).sort((a, b) => prompt.lastIndexOf(b) - prompt.lastIndexOf(a) || b.length - a.length)[0];
+ if (!marker) return null;
+ const [chars = 4, ms = 40] = (process.env.FAKE_STREAM_CADENCE ?? "4:40").split(":").map(Number);
+ return { steps: scripts[marker]!, chars: Math.max(1, chars), ms: Math.max(0, ms) };
+}
+function playStreamScript(script: StreamScript, play: { chunk(step: StreamStep, piece: string): void; end(step: StreamStep): void; done(failure?: string): void; cancelled(): boolean }): void {
+ const queue = script.steps.slice();
+ const next = (): void => {
+ if (play.cancelled()) return;
+ const step = queue.shift();
+ if (!step) return play.done();
+ if (step.fail !== undefined) return play.done(step.fail);
+ if (step.tool !== undefined) {
+ play.end(step);
+ setTimeout(next, script.ms);
+ return;
+ }
+ const text = step.say ?? step.think ?? "";
+ let at = 0;
+ const send = (): void => {
+ if (play.cancelled()) return;
+ if (at < text.length) {
+ play.chunk(step, text.slice(at, at += script.chars));
+ setTimeout(send, script.ms);
+ return;
+ }
+ play.end(step);
+ setTimeout(next, script.ms);
+ };
+ send();
+ };
+ next();
+}
+
// Follow the spawning server down; on Windows ppid does not change after parent exit.
{
const spawner = process.ppid;
@@ -443,6 +487,7 @@ let pendingAskQuestionId: number | null = null;
let onAskQuestionAnswered: (() => void) | null = null;
let hangingPromptId: unknown = null;
+let streamingPromptId: unknown = null;
let hangKeepAlive: ReturnType<typeof setInterval> | null = null;
type McpEntry = { command: string; args?: string[]; env?: Array<{ name: string; value: string }> };
@@ -1076,6 +1121,28 @@ function handle(msg: any) {
: { stopReason: "end_turn", _meta: { inputTokens: 10, outputTokens: 5 } },
);
};
+ const script = streamScript((Array.isArray(msg.params?.prompt) ? msg.params.prompt : []).map((block: any) => block?.text ?? "").join(""));
+ if (script) {
+ streamingPromptId = msg.id;
+ const update = (u: Record<string, unknown>) => out({ jsonrpc: "2.0", method: "session/update", params: { update: u } });
+ let tools = 0;
+ playStreamScript(script, {
+ cancelled: () => streamingPromptId !== msg.id,
+ chunk: (step, piece) => update({ sessionUpdate: step.think !== undefined ? "agent_thought_chunk" : "agent_message_chunk", content: { text: piece } }),
+ end: (step) => {
+ if (step.tool === undefined) return;
+ const id = `script-tool-${++tools}`;
+ update({ sessionUpdate: "tool_call", toolCallId: id, title: step.tool, rawInput: { command: step.tool } });
+ update({ sessionUpdate: "tool_call_update", toolCallId: id, status: "completed" });
+ },
+ done: (failure) => {
+ streamingPromptId = null;
+ if (failure) out({ jsonrpc: "2.0", id: msg.id, error: { code: -32000, message: failure } });
+ else complete();
+ },
+ });
+ return;
+ }
if (mode === "quiet-then-answer") {
const lines: string[] = process.env.FAKE_ACP_QWEN_LOG ? JSON.parse(process.env.FAKE_ACP_QWEN_LOG) : [];
let logTimer: ReturnType<typeof setInterval> | null = null;
@@ -1537,6 +1604,10 @@ function handle(msg: any) {
break;
}
case "session/cancel":
+ if (streamingPromptId !== null) {
+ result(streamingPromptId, { stopReason: "cancelled", _meta: {} });
+ streamingPromptId = null;
+ }
if (hangingPromptId !== null && process.env.FAKE_ACP_IGNORE_CANCEL !== "1") {
result(hangingPromptId, { stopReason: process.env.FAKE_ACP_CANCEL_STOP_REASON ?? "cancelled", _meta: {} });
if (hangKeepAlive) clearInterval(hangKeepAlive);
diff --git a/server/testing/fake-claude-cli.ts b/server/testing/fake-claude-cli.ts
index 1d4f1ae6f3..8197e9b0cd 100755
--- a/server/testing/fake-claude-cli.ts
+++ b/server/testing/fake-claude-cli.ts
@@ -41,6 +41,7 @@
// (default 30000) as 2.1.306 does; hold "busy" | "idle" | "network" also keeps a stand-in child process that burns CPU,
// sleeps, or holds a loopback TCP connection, as the call's command would
// FAKE_CLAUDE_TOOL_CALLS_FILE path of the same JSON, read again each turn (a warm process's turns differ); missing: none
+// FAKE_STREAM_SCRIPT, FAKE_STREAM_CADENCE a scripted reply chosen by a marker in the prompt (stream-script.ts)
// FAKE_CLAUDE_STREAM_CADENCE "chars:ms" (happy mode): stream each scripted reply as
// text_delta chunks of `chars` chars every `ms` ms before its assistant message
// FAKE_CLAUDE_USES_CLOUD_COMPUTER 1: first take one screenshot through the `computer` MCP server
@@ -96,6 +97,7 @@ import { appendFileSync, closeSync, existsSync, mkdirSync, readFileSync, renameS
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { runRoomHandoffAgent } from "./room-handoff-agent.ts";
+import { playStreamScript, streamScript } from "./stream-script.ts";
const mode = process.env.FAKE_CLAUDE_MODE ?? "happy";
const streamCadence = (() => {
@@ -1129,6 +1131,35 @@ const playTurn = (prompt: JsonValue, late = false) => {
finishIfDone();
};
+ const script = streamScript(promptText(prompt));
+ if (script) {
+ const streamEvent = (event: unknown) => out({ type: "stream_event", event, parent_tool_use_id: null, session_id: sessionId });
+ playStreamScript(script, {
+ cancelled: () => false,
+ chunk: (step, piece) => streamEvent({ type: "content_block_delta", index: 0,
+ delta: "think" in step ? { type: "thinking_delta", thinking: piece } : { type: "text_delta", text: piece } }),
+ end: (step) => {
+ if ("say" in step) out({ type: "assistant", message: { content: [{ type: "text", text: step.say }], usage } });
+ if (!("tool" in step)) return;
+ const id = `tu-${process.pid}-${++toolUseCount}`;
+ out({ type: "assistant", message: { content: [{ type: "tool_use", id, name: "Bash", input: { command: step.tool } }], usage } });
+ out({ type: "user", message: { content: [{ type: "tool_result", tool_use_id: id, is_error: false, content: "ok" }] } });
+ },
+ done: (failure) => {
+ if (failure) {
+ out({ type: "assistant", message: { model: "<synthetic>", stop_reason: "stop_sequence", content: [{ type: "text", text: failure }] }, error: "unknown", is_api_error_message: true });
+ out({ type: "result", subtype: "success", is_error: true, stop_reason: "stop_sequence", terminal_reason: "api_error", result: failure });
+ turnRunning = false;
+ finishIfDone();
+ return;
+ }
+ if (steered.length) out({ type: "assistant", message: { content: [{ type: "text", text: `Noted: ${steered.join(" | ")}` }], usage } });
+ finish();
+ },
+ });
+ return;
+ }
+
if (mode === "slow-write") {
const total = Number(process.env.FAKE_CLAUDE_WRITE_BYTES) || 16_384;
const stepMs = Number(process.env.FAKE_CLAUDE_WRITE_STEP_MS) || 100;
diff --git a/server/testing/fake-codex-app-server.ts b/server/testing/fake-codex-app-server.ts
index 68539e1d00..b43964b4f9 100755
--- a/server/testing/fake-codex-app-server.ts
+++ b/server/testing/fake-codex-app-server.ts
@@ -23,6 +23,7 @@
// FAKE_CODEX_COMMAND the happy turn's one call, this command (default: "ls -la" and a web search);
// FAKE_CODEX_COMMAND_OUTPUT JSON chunks it prints as item/commandExecution/outputDelta notifications, one every
// FAKE_CODEX_COMMAND_OUTPUT_MS (default all at once); FAKE_CODEX_COMMAND_GATE the turn finishes once this file exists
+// FAKE_STREAM_SCRIPT, FAKE_STREAM_CADENCE a scripted reply chosen by a marker in the prompt (as stream-script.ts)
// FAKE_CODEX_PATCH_BYTES each turn first writes web/index.html by apply_patch, streamed as two
// item/fileChange/patchUpdated notifications (codex-cli 0.160.1's schema) of half and all this many bytes
// FAKE_CODEX_IGNORE_FEATURES "1": config/read reports no `-c features.*` override
@@ -421,6 +422,54 @@ const finishTurn = () => {
}
};
+// The scripted replies every fake plays (FAKE_STREAM_SCRIPT, FAKE_STREAM_CADENCE); inlined, since tests copy this fake
+// out of the repo.
+let streamTurn = 0;
+const streamScriptFor = (prompt: string): { steps: Array<Record<string, string>>; chars: number; ms: number } | null => {
+ if (!process.env.FAKE_STREAM_SCRIPT) return null;
+ let scripts: Record<string, Array<Record<string, string>>>;
+ try { scripts = JSON.parse(readFileSync(process.env.FAKE_STREAM_SCRIPT, "utf8")); } catch { return null; }
+ // A prompt can carry earlier requests as context: the newest marker in it is the request.
+ const marker = Object.keys(scripts).filter((key) => prompt.includes(key)).sort((a, b) => prompt.lastIndexOf(b) - prompt.lastIndexOf(a) || b.length - a.length)[0];
+ if (!marker) return null;
+ const [chars = 4, ms = 40] = (process.env.FAKE_STREAM_CADENCE ?? "4:40").split(":").map(Number);
+ return { steps: scripts[marker]!, chars: Math.max(1, chars), ms: Math.max(0, ms) };
+};
+const playStreamScript = (script: NonNullable<ReturnType<typeof streamScriptFor>>) => {
+ const turn = ++streamTurn;
+ const live = () => turn === streamTurn;
+ const queue = script.steps.slice();
+ let index = 0;
+ const next = () => {
+ if (!live()) return;
+ const step = queue.shift();
+ if (!step) return void notify("turn/completed", { turn: { status: "completed" } });
+ index += 1;
+ if (step.fail !== undefined) return void notify("turn/completed", { turn: { status: "failed", error: { message: step.fail } } });
+ if (step.tool !== undefined) {
+ notify("item/started", { item: { id: `c${index}`, type: "commandExecution", command: step.tool } });
+ notify("item/completed", { item: { id: `c${index}`, type: "commandExecution", status: "completed", aggregatedOutput: "ok", exitCode: 0 } });
+ return void setTimeout(next, script.ms);
+ }
+ const text = step.say ?? step.think ?? "";
+ const id = `m${index}`;
+ if (step.say !== undefined) notify("item/started", { item: { id, type: "agentMessage", text: "" } });
+ let at = 0;
+ const send = () => {
+ if (!live()) return;
+ if (at < text.length) {
+ const delta = text.slice(at, at += script.chars);
+ notify(step.say !== undefined ? "item/agentMessage/delta" : "item/reasoning/textDelta", { itemId: id, delta });
+ return void setTimeout(send, script.ms);
+ }
+ if (step.say !== undefined) notify("item/completed", { item: { id, type: "agentMessage", text } });
+ setTimeout(next, script.ms);
+ };
+ send();
+ };
+ next();
+};
+
const playRoomPlanTurn = (msg: any, planPath: string) => {
const ack = () => out({ jsonrpc: "2.0", id: msg.id, result: { turn: { id: nativeTurnId } } });
const early = process.env.FAKE_CODEX_COMPLETE_BEFORE_ACK === "1";
@@ -634,6 +683,7 @@ process.stdin.on("data", (chunk) => {
}
case "turn/interrupt":
dump();
+ streamTurn += 1;
if (process.env.FAKE_CODEX_INTERRUPT_SILENT) break;
out({ jsonrpc: "2.0", id: msg.id, result: {} });
notify("turn/completed", { turn: { status: "interrupted" } });
@@ -868,6 +918,11 @@ process.stdin.on("data", (chunk) => {
}
if (mode === "early-turn-events") finishTurn();
out({ jsonrpc: "2.0", id: msg.id, result: { turn: { id: nativeTurnId } } });
+ const script = streamScriptFor((msg.params?.input ?? []).filter((item: any) => item?.type === "text").map((item: any) => item.text).join("\n"));
+ if (script) {
+ playStreamScript(script);
+ break;
+ }
if (mode === "early-turn-events") break;
if (process.env.FAKE_CODEX_ECHO_INPUT === "1") {
const prompt = { type: "userMessage", id: "u1", content: msg.params?.input ?? [] };
diff --git a/server/testing/fake-pi-cli.ts b/server/testing/fake-pi-cli.ts
index 43c09ca754..16fbe5f3c8 100755
--- a/server/testing/fake-pi-cli.ts
+++ b/server/testing/fake-pi-cli.ts
@@ -1,5 +1,6 @@
#!/usr/bin/env node
// Fake of the pi coding agent's `--mode rpc --no-session` stdio surface for pi.ts tests. Env knobs:
+// FAKE_STREAM_SCRIPT, FAKE_STREAM_CADENCE a scripted reply chosen by a marker in the prompt (stream-script.ts)
// FAKE_PI_MODE happy (default) | tooluse | priced | priced-stop | permission | interleave | question-select | question-input
// | turn-error | no-models | exit-early | compaction | compaction-recovery
// | compaction-recovery-upstream | prompt-reject | omp-chunk
@@ -10,6 +11,7 @@
// FAKE_PI_STEER_OUT_OF_ORDER hold the first steer until a second arrives, then refuse the first and accept the second
import { appendFileSync, readFileSync } from "node:fs";
+import { playStreamScript, streamScript, type StreamScript } from "./stream-script.ts";
const mode = process.env.FAKE_PI_MODE ?? "happy";
const modelPairs = (process.env.FAKE_PI_MODELS ?? "ollama-cloud/glm-5.2,openai/gpt-4o")
@@ -97,6 +99,32 @@ const streamTurn = () => {
send({ type: "agent_end" });
};
+let scriptRun = 0;
+const streamScriptTurn = (script: StreamScript) => {
+ const run = ++scriptRun;
+ let tools = 0;
+ const usage = { input: 0, output: 0 };
+ send({ type: "agent_start" });
+ send({ type: "turn_start" });
+ playStreamScript(script, {
+ cancelled: () => run !== scriptRun,
+ chunk: (step, piece) => send({ type: "message_update", usage, assistantMessageEvent: "think" in step
+ ? { type: "thinking_delta", contentIndex: 0, delta: piece } : { type: "text_delta", contentIndex: 0, delta: piece } }),
+ end: (step) => {
+ if (!("tool" in step)) return;
+ const id = `script_call_${++tools}`;
+ send({ type: "tool_execution_start", toolCallId: id, toolName: "bash", args: { command: step.tool } });
+ send({ type: "tool_execution_end", toolCallId: id, toolName: "bash", isError: false, result: { content: [{ type: "text", text: "ok" }] } });
+ send({ type: "turn_end", message: { stopReason: "toolUse", usage }, usage });
+ send({ type: "turn_start" });
+ },
+ done: (failure) => {
+ send({ type: "turn_end", message: failure ? { stopReason: "error", errorMessage: failure, usage } : { stopReason: "end_turn", usage: { input: 12, output: 3 } }, usage });
+ send({ type: "agent_end" });
+ },
+ });
+};
+
// Un-negotiated, the v1 transport replaces each chunked frame with the `rpc_frame_error` stub.
const streamChunkedTurn = () => {
for (const frame of [
@@ -381,7 +409,8 @@ function handle(cmd: any) {
} catch {}
}
send({ type: "response", command: "prompt", success: true });
- if (mode === "tooluse") streamToolTurn();
+ if (streamScript(String(cmd.message ?? ""))) streamScriptTurn(streamScript(String(cmd.message ?? ""))!);
+ else if (mode === "tooluse") streamToolTurn();
else if (mode === "priced") streamPricedTurn();
else if (mode === "priced-stop") startPricedToolTurn();
else if (mode === "permission") streamPermissionTurn();
@@ -431,6 +460,7 @@ function handle(cmd: any) {
else if (cmd.id === "ask-select" || cmd.id === "ask-input") finishPermissionTurn();
return;
case "abort":
+ scriptRun += 1;
send({ type: "turn_end", message: { stopReason: "cancelled", usage: { input: 0, output: 0 } }, usage: { input: 0, output: 0 } });
return;
default:
diff --git a/server/testing/fakes-self-contained.test.ts b/server/testing/fakes-self-contained.test.ts
index 1bb6e7af0a..d368b87294 100644
--- a/server/testing/fakes-self-contained.test.ts
+++ b/server/testing/fakes-self-contained.test.ts
@@ -8,7 +8,7 @@ import { describe, expect, it } from "vitest";
const HERE = dirname(fileURLToPath(import.meta.url));
/** Fakes a test copies out of the repo: nothing relative may be imported, not even a sibling. */
-const COPIED_OUT = new Set(["fake-codex-app-server.ts"]);
+const COPIED_OUT = new Set(["fake-codex-app-server.ts", "fake-acp-cli.ts"]);
/** Value imports only: `import type` is erased before the file runs. */
const importSpecifiers = (source: string): string[] =>
diff --git a/server/testing/live-reply-cases.ts b/server/testing/live-reply-cases.ts
new file mode 100644
index 0000000000..b5b45cbfa5
--- /dev/null
+++ b/server/testing/live-reply-cases.ts
@@ -0,0 +1,59 @@
+// The replies a streamed chat is checked with, one per case, each chosen by its marker in the prompt
+// (server/testing/stream-script.ts). Every message carries a token of its own (`T<case>M<n>`) so a check can find
+// each message's words in a transcript (a message's last words carry `T<case>M<n>z`), and thinking carries `THINK`
+// tokens that must never show as reply text. No token appears twice in a case.
+import type { StreamStep } from "./stream-script.ts";
+
+export interface LiveReplyCase {
+ name: string;
+ marker: string;
+ steps: StreamStep[];
+ /** What the fixture does while the reply streams. */
+ action?: "stop" | "steer" | "reconnect" | "switch";
+}
+
+const LONG = Array.from({ length: 5 }, (_, n) =>
+ `Paragraph ${n + 1} of the long reply walks through one more step of the plan, with enough words that it wraps across several lines in the chat and keeps streaming for a while before the next one starts.`).join("\n\n");
+
+export const LIVE_REPLY_CASES: LiveReplyCase[] = [
+ { name: "short", marker: "#case-short", steps: [{ say: "Hi there, T1M1 here." }] },
+ { name: "long", marker: "#case-long", steps: [{ say: `T2M1 opens. ${LONG}\n\nT2M1z closes.` }] },
+ { name: "markdown", marker: "#case-markdown", steps: [{ say:
+ "# Plan T3M1\n\nIntro paragraph.\n\n## Steps\n\n- first item\n- second item\n - nested item\n\n1. one\n2. two\n\n| Day | Task |\n| --- | --- |\n| Mon | Gym |\n| Tue | Review |\n\n### Done\n\nThat is T3M1z in full." }] },
+ { name: "code", marker: "#case-code", steps: [{ say:
+ "T4M1 starts the code.\n\n```ts\nconst week = [\"Mon\", \"Tue\"];\nfor (const day of week) {\n console.log(day);\n}\n```\n\nThen two in a row:\n\n```sh\nls -la\n```\n```py\nprint(\"hi\")\n```\n\nT4M1z ends." }] },
+ { name: "math", marker: "#case-math", steps: [{ say: "T5M1 inline math $a^2 + b^2 = c^2$ and display:\n\n$$\n\\int_0^1 x^2\\,dx = \\frac{1}{3}\n$$\n\nT5M1z done." }] },
+ { name: "intl", marker: "#case-intl", steps: [{ say: "T6M1 emoji 🎉🚀👍, 中文测试 日本語のテキスト 한국어, and right to left: مرحبا بالعالم שלום עולם. T6M1z end." }] },
+ { name: "link-image", marker: "#case-link", steps: [{ say: "T7M1 see [the docs](https://example.com/docs) and the picture ![a cat](https://example.com/cat.png). T7M1z end." }] },
+ { name: "text-tool-text", marker: "#case-tools", steps: [
+ { say: "T8M1 looking at the folder first." }, { tool: "ls -la" },
+ { say: "T8M2 found three files, reading one." }, { tool: "cat notes.txt" },
+ { say: "T8M3 all done, nothing else needed." },
+ ] },
+ { name: "two-messages", marker: "#case-pair", steps: [{ say: "T9M1 is the first message." }, { say: "T9M2 is the second message." }] },
+ { name: "whitespace", marker: "#case-blank", steps: [{ say: " \n\n " }, { tool: "ls" }, { say: "T10M1 after a blank message." }] },
+ { name: "thinking", marker: "#case-think", steps: [
+ { think: "THINK11A weighing the options quietly." }, { say: "T11M1 the answer is yes." },
+ { think: "THINK11B checking once more." }, { tool: "ls" }, { say: "T11M2 confirmed." },
+ ] },
+ { name: "stop", marker: "#case-stop", action: "stop", steps: [{ say: `T12M1 starts a reply that will be stopped. ${LONG}` }] },
+ { name: "steer", marker: "#case-steer", action: "steer", steps: [{ say: `T13M1 starts a reply that will be steered. ${LONG}` }] },
+ { name: "error", marker: "#case-error", steps: [{ say: "T14M1 got this far." }, { tool: "ls" }, { fail: "API Error: 529 Overloaded. This is a server-side issue, usually temporary." }] },
+ { name: "reconnect", marker: "#case-reconnect", action: "reconnect", steps: [{ say: `T15M1 keeps going across a reconnect. ${LONG}` }, { tool: "ls" }, { say: "T15M2 after it." }] },
+ { name: "switch", marker: "#case-switch", action: "switch", steps: [{ say: `T16M1 keeps going while you look away. ${LONG}` }, { tool: "ls" }, { say: "T16M2 when you are back." }] },
+];
+
+/** The scripts file the fakes read: marker to steps. */
+export function liveReplyScripts(cases: readonly LiveReplyCase[] = LIVE_REPLY_CASES): Record<string, StreamStep[]> {
+ return Object.fromEntries(cases.map((entry) => [entry.marker, entry.steps]));
+}
+
+/** The message tokens a case's words carry, in order. */
+export function caseTokens(entry: LiveReplyCase): string[] {
+ const tokens: string[] = [];
+ for (const step of entry.steps) {
+ if (!("say" in step)) continue;
+ for (const match of step.say.matchAll(/\bT\d+M\d+z?\b/g)) if (!tokens.includes(match[0])) tokens.push(match[0]);
+ }
+ return tokens;
+}
diff --git a/server/testing/stream-script.ts b/server/testing/stream-script.ts
new file mode 100644
index 0000000000..64068bf8c8
--- /dev/null
+++ b/server/testing/stream-script.ts
@@ -0,0 +1,72 @@
+// A scripted reply for the provider fakes, chosen by a marker in the prompt: words, thinking, a tool call, or a failure,
+// streamed a few characters at a time so a chat can be watched while it grows.
+// FAKE_STREAM_SCRIPT JSON file: { "<marker in the prompt>": StreamStep[] }
+// FAKE_STREAM_CADENCE "chars:ms" (default 4:40)
+import { readFileSync } from "node:fs";
+
+export type StreamStep =
+ | { say: string }
+ | { think: string }
+ | { tool: string }
+ | { fail: string };
+
+export interface StreamScript {
+ steps: StreamStep[];
+ chars: number;
+ ms: number;
+}
+
+export function streamScript(prompt: string): StreamScript | null {
+ const path = process.env.FAKE_STREAM_SCRIPT;
+ if (!path) return null;
+ let scripts: Record<string, StreamStep[]>;
+ try {
+ scripts = JSON.parse(readFileSync(path, "utf8"));
+ } catch {
+ return null;
+ }
+ // A prompt can carry earlier requests as context: the newest marker in it is the request.
+ const marker = Object.keys(scripts).filter((key) => prompt.includes(key)).sort((a, b) => prompt.lastIndexOf(b) - prompt.lastIndexOf(a) || b.length - a.length)[0];
+ if (!marker) return null;
+ const [chars = 4, ms = 40] = (process.env.FAKE_STREAM_CADENCE ?? "4:40").split(":").map(Number);
+ return { steps: scripts[marker]!, chars: Math.max(1, chars), ms: Math.max(0, ms) };
+}
+
+export function streamChunks(text: string, chars: number): string[] {
+ const out: string[] = [];
+ for (let at = 0; at < text.length; at += chars) out.push(text.slice(at, at + chars));
+ return out;
+}
+
+/** Plays `steps` in order, one chunk every `ms`, until `cancelled()`; `done` runs once at the end unless cancelled. */
+export function playStreamScript(script: StreamScript, play: {
+ chunk(step: StreamStep, piece: string): void;
+ end(step: StreamStep): void;
+ done(failure?: string): void;
+ cancelled(): boolean;
+}): void {
+ const queue = script.steps.slice();
+ const next = () => {
+ if (play.cancelled()) return;
+ const step = queue.shift();
+ if (!step) return play.done();
+ if ("fail" in step) return play.done(step.fail);
+ if ("tool" in step) {
+ play.end(step);
+ return void setTimeout(next, script.ms);
+ }
+ const pieces = streamChunks("say" in step ? step.say : step.think, script.chars);
+ const send = () => {
+ if (play.cancelled()) return;
+ const piece = pieces.shift();
+ if (piece !== undefined) {
+ play.chunk(step, piece);
+ return void setTimeout(send, script.ms);
+ }
+ play.end(step);
+ setTimeout(next, script.ms);
+ };
+ send();
+ };
+ next();
+}
diff --git a/shared/runtime-events.ts b/shared/runtime-events.ts
index 3e860dcbe4..9c6e1bf2e5 100644
--- a/shared/runtime-events.ts
+++ b/shared/runtime-events.ts
@@ -125,7 +125,7 @@ export type RuntimeEvent = RuntimeEventBase &
* store and never forwarded to renderer SSE. `fromTool`: a tool's result
* returned the image to the engine; the bot did not make or send it. */
| { type: "item.completed"; itemType: "assistant_image"; data: string; alt?: string; fromTool?: true }
- | { type: "content.delta"; streamKind: "assistant_text" | "reasoning_text"; delta: string }
+ | { type: "content.delta"; streamKind: "assistant_text" | "reasoning_text"; delta: string; /** A room reply as it goes out: the member speaking. */ botId?: string }
| {
type: "request.opened";
requestType: "permission" | "question";
diff --git a/shared/wire.ts b/shared/wire.ts
index 768b134c48..290d8576c9 100644
--- a/shared/wire.ts
+++ b/shared/wire.ts
@@ -535,7 +535,7 @@ export interface WireMessage extends ServerTextLine, HelperIntroField, SetupCard
* one. Absent reads as the profile name. */
sender?: ResolvedSender;
/** Provider turn that produced this message. */
- turnId?: string; /** A stopped row where several people use the server: who pressed Stop. */ stoppedBy?: ResolvedSender;
+ turnId?: string; /** A stopped row where several people use the server: who pressed Stop. */ stoppedBy?: ResolvedSender; /** A bot reply: the `itemId` its words streamed under, so a client swaps the streamed text for this message. */ itemId?: string;
/** Server-proven originating user message, including supported harness
* continuations. Absent means external clients must not infer ownership. */
requestMessageId?: string;
diff --git a/src/components/ChatMarkdown.streaming.test.ts b/src/components/ChatMarkdown.streaming.test.ts
new file mode 100644
index 0000000000..299668ef16
--- /dev/null
+++ b/src/components/ChatMarkdown.streaming.test.ts
@@ -0,0 +1,105 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { setLocale } from "../lib/i18n";
+import { StreamingReplyContext } from "@/state/live-reply";
+
+const parsed = vi.hoisted(() => [] as string[]);
+vi.mock("react-markdown", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("react-markdown")>();
+ return {
+ ...actual,
+ default: (options: Parameters<typeof actual.default>[0]) => {
+ parsed.push(String(options.children));
+ return actual.default(options);
+ },
+ };
+});
+vi.mock("@/lib/interface-mode", async (importOriginal) => ({
+ ...await importOriginal<typeof import("@/lib/interface-mode")>(),
+ useAdvancedMode: () => true,
+ readAdvancedMode: () => true,
+}));
+
+const { ChatMarkdown, clearChatMarkdownCache } = await import("./ChatMarkdown");
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("a reply's Markdown while it streams", () => {
+ let host: HTMLDivElement;
+ let root: Root;
+ const draw = (text: string, streaming: boolean) =>
+ act(() => root.render(createElement(StreamingReplyContext, { value: streaming }, createElement(ChatMarkdown, { text }))));
+ const markup = () => host.innerHTML;
+
+ beforeEach(() => {
+ setLocale("en");
+ clearChatMarkdownCache();
+ parsed.length = 0;
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+ });
+ afterEach(() => {
+ act(() => root.unmount());
+ host.remove();
+ });
+
+ it("parses each finished block once and only the last block again as text arrives", () => {
+ const head = "# Plan\n\nFirst paragraph with **bold**.\n\n";
+ draw(`${head}Second`, true);
+ expect(parsed).toEqual(["# Plan\n\n", "First paragraph with **bold**.\n\n", "Second"]);
+ parsed.length = 0;
+ draw(`${head}Second paragraph`, true);
+ expect(parsed, "the finished blocks were drawn from the cache").toEqual(["Second paragraph"]);
+ parsed.length = 0;
+ draw(`${head}Second paragraph grows`, true);
+ expect(parsed).toEqual(["Second paragraph grows"]);
+ });
+
+ it("draws the same page as the finished reply, so the saved message replaces it without a change", () => {
+ for (const text of [
+ "# Title\n\nA paragraph with `code` and a [link](https://example.com).\n\n- one\n- two\n\n> quoted\n\nThe end.",
+ "Prices: $5 and $10.\n\n| a | b |\n| - | - |\n| 1 | 2 |\n\nAfter the table.",
+ "Intro\n\n```js\nconst a = 1;\n```\n\nOutro",
+ ]) {
+ draw(text, true);
+ const streamed = markup();
+ draw(text, false);
+ expect(streamed, text).toBe(markup());
+ }
+ });
+
+ it("falls back to one parse of the whole text when its syntax ties blocks together", () => {
+ const text = "A claim.[^1]\n\nMore.\n\n[^1]: The source.";
+ draw(text, true);
+ expect(parsed).toEqual([text]);
+ const streamed = markup();
+ draw(text, false);
+ expect(streamed).toBe(markup());
+ });
+
+ it("shows an open code fence as plain code with no actions, and offers them once it closes", () => {
+ draw("Here:\n\n```ts\nconst a = 1;\nconst b", true);
+ expect(parsed, "an open fence is not parsed").toEqual(["Here:\n\n"]);
+ const block = host.querySelector(".chat-code-block")!;
+ expect(block.textContent).toContain("const a = 1;\nconst b");
+ const actions = block.querySelector(".chat-code-actions")!;
+ expect(actions.classList.contains("invisible")).toBe(true);
+ expect(actions.hasAttribute("inert")).toBe(true);
+
+ draw("Here:\n\n```ts\nconst a = 1;\nconst b = 2;\n```\n\nDone", true);
+ const closed = host.querySelector(".chat-code-actions")!;
+ expect(closed.classList.contains("invisible")).toBe(false);
+ expect(closed.hasAttribute("inert")).toBe(false);
+ });
+
+ it("keeps a fence's actions hidden while it is open inside a parsed block", () => {
+ draw("Text right above\n```py\nprint(1)", true);
+ const actions = host.querySelector(".chat-code-actions")!;
+ expect(actions.hasAttribute("inert")).toBe(true);
+ draw("Text right above\n```py\nprint(1)\n```", true);
+ expect(host.querySelector(".chat-code-actions")!.hasAttribute("inert")).toBe(false);
+ });
+});
diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsx
index 5933853ca4..79b0fb5958 100644
--- a/src/components/ChatMarkdown.tsx
+++ b/src/components/ChatMarkdown.tsx
@@ -1,5 +1,5 @@
// Security: model output never reaches the DOM as raw HTML (no rehype-raw); Shiki's output is generator-escaped.
-import { createContext, memo, use, useContext, useEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from "react";
+import { createContext, Fragment, memo, use, useContext, useEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from "react";
import Markdown, { defaultUrlTransform, type Components, type ExtraProps, type Options as MarkdownOptions } from "react-markdown";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
@@ -11,6 +11,8 @@ import { cn } from "@/lib/cn";
import { useAdvancedMode } from "@/lib/interface-mode";
import { remarkMentions, sameMentionPerson, type MentionPeer, type MentionPerson } from "@/lib/mentions";
import { createMarkdownRenderCache } from "@/lib/markdown-render-cache";
+import { closedFence, openFence, splitMarkdownBlocks } from "@/lib/markdown-stream-blocks";
+import { StreamingReplyContext } from "@/state/live-reply";
import { parseFenceInfo } from "../lib/code-block";
import { markdownImageName, markdownImageOpenUrl } from "../lib/markdown-image";
@@ -520,16 +522,19 @@ export function normalizeMathDelimiters(text: string, imageOffsets?: Map<number,
const normalizedCache = new Map<string, Pick<MessageScope, "imageOffsets"> & { source: string }>();
const NORMALIZED_CACHE_MAX = TRANSCRIPT_WINDOW_SIZE * 2;
+function normalizeMarkdown(text: string) {
+ const imageOffsets = text.includes(MARKDOWN_IMAGE) ? new Map<number, number>() : undefined;
+ return { source: normalizeMathDelimiters(imageOffsets ? text : repairMarkdownTables(text), imageOffsets), imageOffsets };
+}
+
function normalizeMessageMarkdown(text: string) {
const cached = normalizedCache.get(text);
if (cached) return cached;
- const imageOffsets = text.includes(MARKDOWN_IMAGE) ? new Map<number, number>() : undefined;
- const source = normalizeMathDelimiters(imageOffsets ? text : repairMarkdownTables(text), imageOffsets);
+ const normalized = normalizeMarkdown(text);
if (normalizedCache.size >= NORMALIZED_CACHE_MAX) {
const first = normalizedCache.keys().next().value;
if (first !== undefined) normalizedCache.delete(first);
}
- const normalized = { source, imageOffsets };
normalizedCache.set(text, normalized);
return normalized;
}
@@ -592,18 +597,23 @@ export type DeliveredFiles = Readonly<Record<string, string>>;
const fileName = (path: string) => path.split(/[\\/]/).at(-1) ?? path;
const MessageScopeContext = createContext<MessageScope>({ threads: [] });
+/** The source of the block still being written, whose last fence may be open; null for finished text. */
+const StreamSourceContext = createContext<string | null>(null);
function MarkdownCode({ node, children }: BlockProps) {
+ const streamSource = use(StreamSourceContext);
+ const position = (node as { position?: { start: { offset?: number }; end: { offset?: number } } } | undefined)?.position;
+ const open = streamSource !== null && !closedFence(streamSource, position?.start.offset, position?.end.offset);
const child: any = Array.isArray(children) ? children[0] : children;
const className: string = child?.props?.className ?? "";
const { lang, wrap } = parseFenceInfo(/language-([^\s]+)/.exec(className)?.[1] ?? "", (node as { children?: { data?: { meta?: unknown } }[] })?.children?.[0]?.data?.meta);
const flat = (n: any): string =>
typeof n === "string" ? n : Array.isArray(n) ? n.map(flat).join("") : (n?.props?.children ? flat(n.props.children) : "");
const code = flat(child?.props?.children).replace(/\n$/, "");
- if (lang.trim().toLowerCase() === "mermaid") {
+ if (lang.trim().toLowerCase() === "mermaid" && !open) {
return <MermaidDiagram code={code} />;
}
- return <CodeBlock code={code} lang={lang} initialWrap={wrap} />;
+ return <CodeBlock code={code} lang={lang} initialWrap={wrap} open={open} />;
}
function MarkdownImage(props: ComponentProps<"img"> & ExtraProps) {
@@ -774,6 +784,30 @@ export function clearChatMarkdownCache(): void {
markdownCache.clear();
}
+interface MarkdownPart {
+ text: string;
+ source: string;
+ imageOffsets?: Map<number, number>;
+ /** Finished text, whose drawing is kept for the next render. */
+ finished: boolean;
+ /** A code fence still being written, drawn without parsing. */
+ fence?: { lang: string; wrap: boolean; code: string };
+}
+
+/** A finished message is one part. A streaming one is its blocks: the finished ones are parsed once and kept, and only
+ * the last is parsed again as text arrives. */
+function markdownParts(text: string, streaming: boolean): MarkdownPart[] {
+ if (!streaming) return [{ text, ...normalizeMessageMarkdown(text), finished: true }];
+ const blocks = splitMarkdownBlocks(text) ?? [text];
+ return blocks.map((block, index): MarkdownPart => {
+ if (index < blocks.length - 1) return { text: block, ...normalizeMessageMarkdown(block), finished: true };
+ const fence = openFence(block);
+ if (!fence) return { text: block, ...normalizeMarkdown(block), finished: false };
+ const [info = "", ...meta] = fence.info.split(/\s+/);
+ return { text: block, source: block, finished: false, fence: { ...parseFenceInfo(info, meta.join(" ")), code: fence.code } };
+ });
+}
+
function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS, everyone = false, mentionPerson, delivered, originals }: {
text: string; message?: MessageAttachmentContext;
mentionPeers?: readonly MentionPeer[]; everyone?: boolean; mentionPerson?: MentionPerson;
@@ -782,8 +816,9 @@ function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS,
}) {
// use() may be called conditionally: only a message that can hold a thread link subscribes to the thread list.
const { threads, currentBotId } = MAY_LINK_THREAD.test(text) ? use(ThreadRefsContext) : NO_THREAD_REFS;
- const { source, imageOffsets } = normalizeMessageMarkdown(text);
- const needsMath = normalizedSourceHasMath(source);
+ const streaming = use(StreamingReplyContext);
+ const parts = useMemo(() => markdownParts(text, streaming), [text, streaming]);
+ const needsMath = parts.some((part) => !part.fence && normalizedSourceHasMath(part.source));
const [katexReady, setKatexReady] = useState(() => katexPlugin !== null);
useEffect(() => {
if (!needsMath) return;
@@ -801,18 +836,30 @@ function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS,
};
}, [needsMath]);
const mathPlugin = needsMath && katexReady ? katexPlugin : null;
- const mentions = source.includes("@"), linksThreads = threads.length > 0;
- const variant = `${mathPlugin ? "math" : ""}\u0003${mentions ? `${peerSignature(mentionPeers)}\u0001${everyone ? 1 : 0}\u0001${mentionPerson?.profileName ?? ""}` : ""}\u0003${linksThreads ? `${threadListId(threads)}\u0001${currentBotId ?? ""}` : ""}`;
- // Markdown is a plain function of its options (no hooks), so its elements can be kept and drawn again.
- const markdown = markdownCache.render(text, variant, () => {
- const remarkPlugins = [...BASE_REMARK_PLUGINS];
- if (mentions) remarkPlugins.push([remarkMentions, { peers: mentionPeers, everyone, person: mentionPerson }]);
- if (linksThreads) remarkPlugins.push(remarkThreadRefs(threads, currentBotId));
- return Markdown({ children: source, remarkPlugins, rehypePlugins: rehypePluginsFor(mathPlugin), urlTransform: chatUrlTransform, components: MARKDOWN_COMPONENTS });
- });
+ const linksThreads = threads.length > 0;
+ const draw = ({ text: partText, source, finished }: MarkdownPart) => {
+ const mentions = source.includes("@");
+ const variant = `${mathPlugin ? "math" : ""}\u0003${mentions ? `${peerSignature(mentionPeers)}\u0001${everyone ? 1 : 0}\u0001${mentionPerson?.profileName ?? ""}` : ""}\u0003${linksThreads ? `${threadListId(threads)}\u0001${currentBotId ?? ""}` : ""}`;
+ // Markdown is a plain function of its options (no hooks), so its elements can be kept and drawn again.
+ const render = () => {
+ const remarkPlugins = [...BASE_REMARK_PLUGINS];
+ if (mentions) remarkPlugins.push([remarkMentions, { peers: mentionPeers, everyone, person: mentionPerson }]);
+ if (linksThreads) remarkPlugins.push(remarkThreadRefs(threads, currentBotId));
+ return Markdown({ children: source, remarkPlugins, rehypePlugins: rehypePluginsFor(mathPlugin), urlTransform: chatUrlTransform, components: MARKDOWN_COMPONENTS });
+ };
+ // Streamed text grows each render; keeping its drawing would only fill the cache with prefixes.
+ return finished ? markdownCache.render(partText, variant, render) : <StreamSourceContext value={source}>{render()}</StreamSourceContext>;
+ };
+ // A message still streaming has no saved files to fetch yet.
+ const scope = { message: streaming ? undefined : message, imageOffsets: streaming ? undefined : parts[0]?.imageOffsets, threads, currentBotId, delivered, originals };
return (
- <MessageScopeContext.Provider value={{ message, imageOffsets, threads, currentBotId, delivered, originals }}>
- <div className="chat-md min-w-0 [&>*+*]:mt-2">{markdown}</div>
+ <MessageScopeContext.Provider value={scope}>
+ <div className="chat-md min-w-0 [&>*+*]:mt-2">
+ {parts.map((part, index) => (
+ // The whole text's tree puts a line break between its top-level blocks; the parts keep it.
+ <Fragment key={index}>{index > 0 && "\n"}{part.fence ? <CodeBlock code={part.fence.code} lang={part.fence.lang} initialWrap={part.fence.wrap} open /> : draw(part)}</Fragment>
+ ))}
+ </div>
</MessageScopeContext.Provider>
);
}
diff --git a/src/components/ChatView.follow.test.ts b/src/components/ChatView.follow.test.ts
index e9357f32c7..c15aea0058 100644
--- a/src/components/ChatView.follow.test.ts
+++ b/src/components/ChatView.follow.test.ts
@@ -12,6 +12,7 @@ const fixture = vi.hoisted(() => {
vi.mock("react", async (original) => ({
...await original<typeof import("react")>(),
useEffect: (effect: EffectCallback, deps?: DependencyList) => { fixture.effects.push({ effect, deps }); },
+ useLayoutEffect: (effect: EffectCallback, deps?: DependencyList) => { fixture.effects.push({ effect, deps }); },
useRef: (initial: unknown) => (fixture.refs[fixture.ref++] ??= { current: initial }),
}));
vi.mock("@/state/store", async (importOriginal) => {
diff --git a/src/components/ChatView.live-reply.test.ts b/src/components/ChatView.live-reply.test.ts
new file mode 100644
index 0000000000..8455a6a1cb
--- /dev/null
+++ b/src/components/ChatView.live-reply.test.ts
@@ -0,0 +1,211 @@
+// @vitest-environment happy-dom
+import { act, createElement, type ComponentProps } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { Bot, InstanceInfo, Message } from "@/state/store";
+import type { RuntimeEvent } from "../../shared/runtime-events";
+import type { ApprovalModeSelector } from "./ApprovalModeSelector";
+import type { ModelPicker } from "./ModelPicker";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const dispatch = vi.hoisted(() => vi.fn());
+vi.mock("@/state/store", async (importOriginal) => {
+ const original = await importOriginal<typeof import("@/state/store")>();
+ return { ...original, useStore: () => ({
+ state: { ...original.initialState, config: null, instances: [{ instanceId: "test", driverKind: "claudeAgent", displayName: "Test" } as InstanceInfo] },
+ dispatch,
+ }) };
+});
+vi.mock("./DesktopCapabilities", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./DesktopCapabilities")>(),
+ useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: true, platform: "other" }, localComputer: { available: false, reasonCode: "x", message: "" } }, ready: true }),
+}));
+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
+vi.mock("@/lib/thread-preferences", async (importOriginal) => ({
+ ...await importOriginal<typeof import("@/lib/thread-preferences")>(),
+ useShowThreads: () => true,
+}));
+const mode = vi.hoisted(() => ({ advanced: true }));
+vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => mode.advanced, setAdvancedMode: vi.fn() }));
+vi.mock("./SidebarPopoverMenu", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./SidebarPopoverMenu")>(),
+ SidebarPopoverMenu: (props: { renderTrigger: (state: { open: boolean }) => unknown }) => props.renderTrigger({ open: false }),
+}));
+vi.mock("@/lib/cloud-guest", () => ({ useCanWriteIn: () => null, useReactor: () => "user" }));
+vi.mock("./CitationUI", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./CitationUI")>(),
+ CitationSelectionToolbar: () => createElement("span"),
+}));
+vi.mock("./ModelPicker", () => ({ ModelPicker: (_props: ComponentProps<typeof ModelPicker>) => createElement("span") }));
+vi.mock("./ApprovalModeSelector", () => ({ ApprovalModeSelector: (_props: ComponentProps<typeof ApprovalModeSelector>) => createElement("span") }));
+
+const { ChatView } = await import("./ChatView");
+const { noteLiveReplyEvent, noteLiveReplyMessage, resetLiveReplies } = await import("@/state/live-reply");
+const { resetTurnLive } = await import("@/state/turn-status");
+
+const THREAD = "selected";
+const started = Date.UTC(2026, 10, 11, 12, 0, 0);
+const bot = (messages: Message[], busy = true): Bot => ({
+ id: "bot", threadId: THREAD, name: "Pepper", title: "", description: "", color: "green",
+ notifications: true, unread: false, busy, activity: busy ? "working" : "idle", turnStartedAt: busy ? started : undefined, messages,
+ modelSelection: { instanceId: "test", model: "m" },
+});
+const ask: Message = { id: "ask", role: "user", kind: "text", at: started, text: "Plan my week" };
+
+let seq = 0;
+const frame = (event: Partial<RuntimeEvent>) => ({
+ eventId: `e${++seq}`, provider: "claudeAgent", threadId: THREAD, createdAt: new Date().toISOString(), turnId: "t1", ...event,
+} as RuntimeEvent);
+const engine = (event: Partial<RuntimeEvent>) => act(() => noteLiveReplyEvent(frame(event)));
+const sayIn = (delta: string, itemId: string) => engine({ type: "content.delta", streamKind: "assistant_text", delta, itemId } as Partial<RuntimeEvent>);
+const say = (delta: string) => engine({ type: "content.delta", streamKind: "assistant_text", delta } as Partial<RuntimeEvent>);
+
+let host: HTMLDivElement;
+let root: Root;
+const render = (shown: Bot) => act(() => root.render(createElement(ChatView, { bot: shown })));
+const log = () => host.querySelector('[role="log"]')!;
+const liveRows = () => [...log().querySelectorAll('[data-mid^="live:"]')];
+const rowOf = (id: string) => log().querySelector(`[data-mid="${id}"]`);
+const occurrences = (text: string) => (log().textContent ?? "").split(text).length - 1;
+/** A row's markup with the ids that name it taken out: what the eye sees. */
+const looks = (row: Element) => row.outerHTML.replace(/live:[^"]+|data-mid="[^"]+"|data-citation-source="[^"]+"/g, "");
+
+beforeEach(() => {
+ vi.useFakeTimers({ now: started + 5_000 });
+ resetTurnLive();
+ resetLiveReplies();
+ vi.stubGlobal("fetch", vi.fn(async () => new Response("{}", { status: 200, headers: { "content-type": "application/json" } })));
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(() => {
+ mode.advanced = true;
+ act(() => root.unmount());
+ host.remove();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+});
+
+describe.each([["Advanced", true], ["Simple", false]])("a streaming reply in %s mode", (_name, advanced) => {
+ it("grows in place and is replaced by the saved message in the same frame, never shown twice", () => {
+ mode.advanced = advanced;
+ engine({ type: "turn.started" });
+ render(bot([ask]));
+ expect(liveRows()).toHaveLength(0);
+
+ say("Monday: gym. ");
+ expect(liveRows()).toHaveLength(1);
+ expect(liveRows()[0]!.textContent).toContain("Monday: gym.");
+ say("Tuesday: **review** the bud");
+ expect(liveRows()).toHaveLength(1);
+ expect(liveRows()[0]!.querySelector("strong")?.textContent, "drawn as Markdown while it streams").toBe("review");
+ expect(liveRows()[0]!.textContent, "a word still being written waits").not.toContain("bud");
+ say("get.");
+ const text = "Monday: gym. Tuesday: **review** the budget.";
+ engine({ type: "item.completed", itemType: "assistant_text", text } as Partial<RuntimeEvent>);
+ expect(liveRows()[0]!.textContent).toContain("the budget.");
+ expect(liveRows()[0]!.querySelector('[data-testid="message-actions"]')?.hasAttribute("inert"), "no actions on words still arriving").toBe(true);
+ const live = looks(liveRows()[0]!);
+
+ const saved: Message = { id: "m-saved", role: "bot", kind: "text", at: started + 5_000, text, turnId: "t1", parentId: "ask" };
+ act(() => noteLiveReplyMessage(THREAD, saved));
+ expect(liveRows(), "the frame is in but the transcript has not drawn it: the streamed bubble stays").toHaveLength(1);
+ expect(occurrences("the budget.")).toBe(1);
+
+ render(bot([ask, saved]));
+ expect(liveRows()).toHaveLength(0);
+ expect(rowOf("m-saved")).not.toBeNull();
+ expect(occurrences("the budget."), "one reply, not two").toBe(1);
+ expect(looks(rowOf("m-saved")!).replace(/ inert=""/g, ""), "the saved bubble looks like the streamed one").toBe(live.replace(/ inert=""/g, ""));
+ expect(rowOf("m-saved")!.querySelector(".turn-answer"), "it does not play in again").toBeNull();
+ });
+});
+
+describe("a streaming reply's end", () => {
+ it("is gone when the turn fails or stops before the reply was saved", () => {
+ engine({ type: "turn.started" });
+ render(bot([ask]));
+ say("Half an answer ");
+ expect(liveRows()).toHaveLength(1);
+ engine({ type: "turn.completed", ok: false } as Partial<RuntimeEvent>);
+ expect(liveRows()).toHaveLength(0);
+ });
+
+ it("belongs to its own conversation: another one opened shows none of it", () => {
+ engine({ type: "turn.started" });
+ render(bot([ask]));
+ say("Private words ");
+ render({ ...bot([], false), threadId: "other" });
+ expect(liveRows()).toHaveLength(0);
+ expect(occurrences("Private words")).toBe(0);
+ render(bot([ask]));
+ expect(liveRows()[0]!.textContent, "coming back shows it again, still growing").toContain("Private words");
+ });
+});
+
+describe("a turn of several messages, each streamed under its own id", () => {
+ it("streams each message after the last, swaps each for its saved one, and leaves nothing behind", () => {
+ engine({ type: "turn.started" });
+ render(bot([ask]));
+ sayIn("Checking your calendar ", "x1");
+ sayIn("first. ", "x1");
+ engine({ type: "item.completed", itemType: "assistant_text", text: "Checking your calendar first.", itemId: "x1" } as Partial<RuntimeEvent>);
+ const first = { id: "m1", role: "bot", kind: "text", at: started + 5_000, text: "Checking your calendar first.", turnId: "t1", parentId: "ask", itemId: "x1" } as Message;
+ act(() => noteLiveReplyMessage(THREAD, first));
+ engine({ type: "item.started", itemType: "tool", itemId: "c1", title: "ls -la" } as Partial<RuntimeEvent>);
+ const step: Message = { id: "s1", role: "bot", kind: "activity", at: started + 5_000, tool: { name: "ls -la", itemId: "c1" }, turnId: "t1", parentId: "m1" };
+ sayIn("Monday is ", "x2");
+ expect(occurrences("Checking your calendar first."), "the first message stays drawn until the transcript has it").toBe(1);
+ render(bot([ask, first, step]));
+ expect(occurrences("Checking your calendar first.")).toBe(1);
+ expect(liveRows()).toHaveLength(1);
+ expect(liveRows()[0]!.textContent, "the second message stands alone").not.toContain("Checking");
+ sayIn("free. ", "x2");
+ engine({ type: "item.completed", itemType: "assistant_text", text: "Monday is free.", itemId: "x2" } as Partial<RuntimeEvent>);
+ const second = { id: "m2", role: "bot", kind: "text", at: started + 5_000, text: "Monday is free.", turnId: "t1", parentId: "s1", itemId: "x2" } as Message;
+ act(() => noteLiveReplyMessage(THREAD, second));
+ engine({ type: "turn.completed", ok: true } as Partial<RuntimeEvent>);
+ expect(occurrences("Monday is free.")).toBe(1);
+ render(bot([ask, first, step, second], false));
+ expect(liveRows()).toHaveLength(0);
+ expect(occurrences("Checking your calendar first.")).toBe(1);
+ expect(occurrences("Monday is free.")).toBe(1);
+ const order = [...log().querySelectorAll("[data-mid]")].map((row) => row.getAttribute("data-mid"));
+ expect(order.indexOf("m1")).toBeLessThan(order.indexOf("m2"));
+ });
+
+ it("swaps a streamed message for the saved one with its id even if the message frame was missed", () => {
+ engine({ type: "turn.started" });
+ render(bot([ask]));
+ sayIn("Reloaded mid reply. ", "y1");
+ engine({ type: "item.completed", itemType: "assistant_text", text: "Reloaded mid reply.", itemId: "y1" } as Partial<RuntimeEvent>);
+ expect(liveRows()).toHaveLength(1);
+ render(bot([ask, { id: "m5", role: "bot", kind: "text", at: started + 5_000, text: "Reloaded mid reply.", turnId: "t1", parentId: "ask", itemId: "y1" } as Message]));
+ expect(liveRows()).toHaveLength(0);
+ expect(occurrences("Reloaded mid reply.")).toBe(1);
+ });
+});
+
+
+describe("a conversation that streamed while nobody had it open", () => {
+ it("opens with none of its old replies drawn again after the newest message", () => {
+ const rows: Message[] = [];
+ for (let turn = 1; turn <= 30; turn++) {
+ const turnId = `bg${turn}`, itemId = `${turnId}:x`, text = `Background reply ${turn}.`;
+ engine({ type: "turn.started", turnId });
+ engine({ type: "content.delta", streamKind: "assistant_text", delta: "Background reply ", turnId, itemId } as Partial<RuntimeEvent>);
+ engine({ type: "item.completed", itemType: "assistant_text", text, turnId, itemId } as Partial<RuntimeEvent>);
+ const saved = { id: `r${turn}`, role: "bot", kind: "text", at: started + turn, text, turnId, itemId } as Message;
+ act(() => noteLiveReplyMessage(THREAD, saved));
+ engine({ type: "turn.completed", ok: true, turnId } as Partial<RuntimeEvent>);
+ rows.push({ id: `q${turn}`, role: "user", kind: "text", at: started + turn, text: `Question ${turn}` }, saved);
+ }
+ for (let n = 0; n < 200; n++) rows.push({ id: `n${n}`, role: n % 2 ? "bot" : "user", kind: "text", at: started + 100 + n, text: `Later ${n}` } as Message);
+ render(bot(rows, false));
+ expect(rowOf("r30"), "the window holds only the newest rows").toBeNull();
+ expect(liveRows()).toHaveLength(0);
+ expect(occurrences("Background reply")).toBe(0);
+ });
+});
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index 653308d849..6faefa3c47 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -57,7 +57,7 @@ import { normalizeState, stateForBot } from "@/lib/mascot";
import { peerLine, peerRequest, type PeerLine } from "@/lib/peer-message";
import { showWorkingDots } from "@/lib/turn-tail";
import { lastNonReceipt } from "@/lib/receipts";
-import { useTurnLive } from "@/state/turn-status"; import { useTurnNow } from "./NowCard"; import { useThreadRoutineRun } from "@/state/older-routine-runs";
+import { useTurnLive } from "@/state/turn-status"; import { isLiveReply, StreamingReplyContext, streamedReply, useHasLiveReply, useLiveTranscript } from "@/state/live-reply"; import { useTurnNow } from "./NowCard"; import { useThreadRoutineRun } from "@/state/older-routine-runs";
import { ChatMarkdown } from "./ChatMarkdown";
import { LiveToolsContext, useLiveToolIds } from "@/hooks/use-live-tool-ids";
import { VoiceNoteBubble, type VoiceNoteAttachment } from "./VoiceNoteBubble";
@@ -362,11 +362,11 @@ const Bubble = memo(function Bubble({
const attached = useMemo(() => splitMessageAttachments(message.attachments), [message.attachments]);
const generatedPaths = attached.images;
const linkedFiles = useMemo(
- () => user ? [] : [...attached.files, ...collectMessageFiles(text, [...attached.images, ...attached.files.map((file) => file.path)])],
+ () => user || isLiveReply(message) ? [] : [...attached.files, ...collectMessageFiles(text, [...attached.images, ...attached.files.map((file) => file.path)])],
[user, text, attached],
);
const group = useMemo(
- () => !user && text.trim() ? replyAttachmentGroup(text, message.attachments) : null,
+ () => !user && !isLiveReply(message) && text.trim() ? replyAttachmentGroup(text, message.attachments) : null,
[user, text, message.attachments],
);
const voiceNotes = useMemo(
@@ -374,7 +374,7 @@ const Bubble = memo(function Bubble({
[message.attachments],
);
const join: BubbleJoin = { above: joinAbove, below: joinBelow };
- const reply = useReplySegments(conversational && !user && !peer && !viewRaw && !replyTarget && message.kind === "text", text, message.at, openedAt);
+ const reply = useReplySegments(conversational && !user && !peer && !viewRaw && !replyTarget && message.kind === "text", text, message.at, openedAt, message.id);
const split = reply.segments.length > 1;
// Simple mode draws each table of a reply as its own card between the reply's prose bubbles.
const blocks = useMemo(() => simple && !user && !peer && !viewRaw && !split && text ? splitReplyBlocks(text) : null, [simple, user, peer, viewRaw, split, text]);
@@ -445,7 +445,7 @@ const Bubble = memo(function Bubble({
className={cn(
tabled ? "w-full" : "w-fit",
simple ? !tabled && SIMPLE_BUBBLE_MAX : "max-w-[min(var(--chat-bubble-max),var(--chat-bubble-pct))] rounded-2xl text-[15px] leading-relaxed",
- emerging && "turn-answer",
+ emerging && !streamedReply(message.id) && "turn-answer",
user && webhookView
? cn("overflow-hidden border border-accent/25 bg-card text-ink", simple ? cn("rounded-[18px]", SIMPLE_BUBBLE_TEXT) : "shadow-[0_10px_30px_rgba(0,0,0,0.18)]")
: attachmentsOnly || split || tabled
@@ -629,7 +629,7 @@ const ActivityChip = memo(function ActivityChip({ message, place = "auto" }: { m
const RoomHandoffChip = ({ message, comm, bots, dispatch }: { message: Message; comm: NonNullable<Message["comm"]>; bots: readonly Bot[]; dispatch: Dispatch<Action> }) => { const store = useStoreRef(); return <HandoffChip message={message} bots={bots} title={t("chat.openConversationWith", { name: comm.withName })} onClick={() => openRoomThread(dispatch, comm, store.state().groups)} />; };
const MessagesList = memo(function MessagesList({
- messages,
+ messages: saved,
transcript,
lookups,
place,
@@ -668,6 +668,7 @@ const MessagesList = memo(function MessagesList({
onReply: (message: Message) => void;
}) {
const { botId, threadId, botName, botColor, bots, hasMore, focus, showToolCalls, locale, simple = false } = useChatRows(), busy = use(ChatBusyContext);
+ const messages = useLiveTranscript(threadId, saved, transcript);
// A finished turn keeps the bot's progress lines and folds only its tool steps under "Worked for", in both modes.
const items = useMemo(() => groupTranscript(messages), [messages, locale]);
const newestMessageId = messages.at(-1)?.id;
@@ -789,7 +790,7 @@ const MessagesList = memo(function MessagesList({
{newDay && <DaySeparator at={m.at} today={today} simple={simple} />}
{divider}
{m.automation && <AutomationCaption message={m} line={m.automation} botId={botId} />}{m.inbox && <InboxCaption message={m} />}
- {row}{m.inbox?.answers && <InboxAnswers message={m} />}{m.inbox && <InboxCardSlot threadId={threadId} messageId={m.id} />}{m.setupOffer && <SetupOffer botId={botId} threadId={threadId} message={m} transcript={transcript} />}{m.savedSteps && <SavedStepsChip botId={botId} message={m} />}
+ {isLiveReply(m) ? <StreamingReplyContext value>{row}</StreamingReplyContext> : row}{m.inbox?.answers && <InboxAnswers message={m} />}{m.inbox && <InboxCardSlot threadId={threadId} messageId={m.id} />}{m.setupOffer && <SetupOffer botId={botId} threadId={threadId} message={m} transcript={transcript} />}{m.savedSteps && <SavedStepsChip botId={botId} message={m} />}
</div>
);
})}
@@ -856,7 +857,7 @@ export const ChatView = memo(function ChatView({ bot: profile }: { bot: Bot }) {
transcriptRef,
topSentinelRef,
transcriptKey,
- following,
+ following, showJumpToLatest,
windowedMessages,
hiddenCount,
laterCount,
@@ -959,7 +960,7 @@ export const ChatView = memo(function ChatView({ bot: profile }: { bot: Bot }) {
const teammatesWorking = !advanced && !bot.busy && Boolean(bot.waitingForTeammates);
const presenceVisible = waiting || popping !== null || teammatesWorking, sharedRun = useSharedRun(bot, advanced);
const lastShownRow = windowedMessages.findLast((message) => !quietRow(message, showToolCalls));
- const presenceUnderBubble = Boolean(lastShownRow && isBotTextRow(lastShownRow, bot.id));
+ const presenceUnderBubble = useHasLiveReply(bot.threadId) || Boolean(lastShownRow && isBotTextRow(lastShownRow, bot.id));
const announcement = useMemo((): TranscriptSnapshot => {
const approval = pendingApprovals(messages)[0];
return {
@@ -1143,7 +1144,6 @@ export const ChatView = memo(function ChatView({ bot: profile }: { bot: Bot }) {
}
/>
-
</GlassBar>
<div
@@ -1258,7 +1258,7 @@ export const ChatView = memo(function ChatView({ bot: profile }: { bot: Bot }) {
/>
</div>
)}
- {!following && (
+ {showJumpToLatest && (
<div className="relative">
<JumpToLatestButton onClick={jumpToLatest} className="pointer-events-auto bottom-2" />
</div>
diff --git a/src/components/CodeBlock.tsx b/src/components/CodeBlock.tsx
index bd1e74f696..aa88ae7405 100644
--- a/src/components/CodeBlock.tsx
+++ b/src/components/CodeBlock.tsx
@@ -167,6 +167,8 @@ export interface CodeBlockProps {
code: string;
lang: string;
initialWrap?: boolean;
+ /** The fence is still being written: no colouring and no actions until it closes. */
+ open?: boolean;
}
const PLATE_BUTTON = "inline-flex size-7 touch:size-11 items-center justify-center rounded-full text-ink-secondary transition-colors hover:bg-ink/[0.06] hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60";
@@ -196,13 +198,13 @@ export function CodePlate({ copied, onCopy, copyLabel, items }: {
);
}
-export function CodeBlock({ code, lang, initialWrap = false }: CodeBlockProps) {
+export function CodeBlock({ code, lang, initialWrap = false, open = false }: CodeBlockProps) {
const simple = !useAdvancedMode();
const frame = useRef<HTMLDivElement>(null);
// A long chat can hold dozens of blocks: coloured ones are thousands of spans to style and lay out on every switch,
// so a block is coloured only once it comes near the screen.
const near = useNearScreen(frame);
- const highlightable = code.length <= HIGHLIGHT_MAX_CHARS;
+ const highlightable = !open && code.length <= HIGHLIGHT_MAX_CHARS;
const [html, setHtml] = useState<string | null>(() => highlightable && near ? highlightCache.get(highlightKey(lang, code)) ?? null : null);
// React compares dangerouslySetInnerHTML by identity: a fresh object each render rebuilds the highlighted DOM.
const markup = useMemo(() => (html ? { __html: html } : null), [html]);
@@ -255,11 +257,11 @@ export function CodeBlock({ code, lang, initialWrap = false }: CodeBlockProps) {
if (simple) {
return (
<div ref={frame} dir="ltr" className="chat-code-block group/code relative my-2.5 overflow-hidden rounded-xl bg-ink/[0.04]">
- <CodePlate copied={copied} onCopy={copy} copyLabel={t("code.copyTitle")} items={[
+ {!open && <CodePlate copied={copied} onCopy={copy} copyLabel={t("code.copyTitle")} items={[
{ key: "wrap", label: t("code.wrapLines"), icon: <WrapText size={14} aria-hidden="true" />, active: wrapLines, onSelect: () => setWrapLines((wrap) => !wrap) },
{ key: "save", label: t("code.saveAsFile"), icon: <Download size={14} aria-hidden="true" />, onSelect: download },
{ key: "about", label: t("code.caption", { language: displayLanguage, lines: formatLineCount(lineCount) }), disabled: true, separatorBefore: true, onSelect: () => {} },
- ]} />
+ ]} />}
{body("leading-5 [&_pre]:px-3 [&_pre]:py-2", "text-ink-secondary")}
</div>
);
@@ -278,7 +280,7 @@ export function CodeBlock({ code, lang, initialWrap = false }: CodeBlockProps) {
</span>
)}
</div>
- <div className="chat-code-actions flex shrink-0 items-center gap-1 whitespace-nowrap">
+ <div className={cn("chat-code-actions flex shrink-0 items-center gap-1 whitespace-nowrap", open && "invisible")} inert={open || undefined}>
<button
type="button"
onClick={() => setWrapLines((w) => !w)}
diff --git a/src/components/ConversationalReply.tsx b/src/components/ConversationalReply.tsx
index d169a2b83d..51d8f5fafa 100644
--- a/src/components/ConversationalReply.tsx
+++ b/src/components/ConversationalReply.tsx
@@ -3,15 +3,17 @@ import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
import { splitConversationalReply } from "../../shared/reply-style";
import { joinedCorners, SIMPLE_BOT_BUBBLE, type BubbleJoin } from "./chat-bubble";
+import { streamedReply } from "@/state/live-reply";
export { isConversational } from "../../shared/reply-style";
/** A reply that arrives while its thread is open plays its parts in; parts already shown never replay. */
-export function useReplySegments(show: boolean, text: string, at: number, openedAt: number): { segments: string[]; firstNew: number } {
+export function useReplySegments(show: boolean, text: string, at: number, openedAt: number, messageId: string): { segments: string[]; firstNew: number } {
const segments = useMemo(() => (show ? splitConversationalReply(text) : []), [show, text]);
- const [fresh] = useState(() => at >= openedAt);
+ const streamed = streamedReply(messageId);
+ const [fresh] = useState(() => at >= openedAt && !streamed);
const shown = useRef(fresh ? 0 : segments.length);
- const firstNew = shown.current;
+ const firstNew = streamed ? Number.POSITIVE_INFINITY : shown.current;
useEffect(() => {
shown.current = Math.max(shown.current, segments.length);
}, [segments.length]);
diff --git a/src/components/GroupView.live-reply.test.ts b/src/components/GroupView.live-reply.test.ts
new file mode 100644
index 0000000000..08beb5384d
--- /dev/null
+++ b/src/components/GroupView.live-reply.test.ts
@@ -0,0 +1,68 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { Bot, Group, Message } from "@/state/store";
+import type { RuntimeEvent } from "../../shared/runtime-events";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const bots = vi.hoisted(() => [] as Bot[]);
+vi.mock("@/state/store", async (importOriginal) => {
+ const original = await importOriginal<typeof import("@/state/store")>();
+ return { ...original, useStore: () => ({ state: { ...original.initialState, bots }, dispatch: vi.fn() }) };
+});
+vi.mock("./DesktopCapabilities", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./DesktopCapabilities")>(),
+ useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: true, platform: "other" }, localComputer: { available: false } }, ready: true }),
+}));
+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
+
+const { GroupView } = await import("./GroupView");
+const { noteLiveReplyEvent, resetLiveReplies } = await import("@/state/live-reply");
+
+const member = (id: string, name: string, color: string) =>
+ ({ id, name, color, busy: false, messages: [], notifications: true, unread: false, title: "", description: "", modelSelection: { instanceId: "test", model: "default" } }) as unknown as Bot;
+bots.push(member("ada", "Ada", "blue"), member("ben", "Ben", "green"));
+const at = Date.UTC(2026, 10, 11, 12);
+const ask: Message = { id: "u", role: "user", kind: "text", at, text: "Plan the launch" };
+const room = (busyBotId: string | undefined): Group => ({
+ id: "room", threadId: "room-thread", name: "Planning", memberIds: ["ada", "ben"], defaultResponder: { kind: "member", botId: "ada" },
+ bulletin: "", unread: false, createdAt: 1, messages: [ask], busyBotId, working: Boolean(busyBotId), turnStartedAt: at,
+} as unknown as Group);
+
+let seq = 0;
+const stream = (delta: string, botId?: string) => act(() => noteLiveReplyEvent({
+ eventId: `d${++seq}`, provider: "claudeAgent", threadId: "room-thread", createdAt: new Date(at).toISOString(), turnId: "t1", itemId: "x",
+ type: "content.delta", streamKind: "assistant_text", delta, ...(botId ? { botId } : {}),
+} as RuntimeEvent));
+
+let host: HTMLDivElement;
+let root: Root;
+const render = (group: Group) => act(() => root.render(createElement(GroupView, { group })));
+const liveRow = () => host.querySelector('[data-mid^="live:"]');
+
+beforeEach(() => {
+ resetLiveReplies();
+ vi.stubGlobal("fetch", vi.fn(async () => new Response("{}", { status: 200, headers: { "content-type": "application/json" } })));
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ host.remove();
+ vi.unstubAllGlobals();
+});
+
+describe("a room reply as it streams", () => {
+ it("names the member the server says is speaking, whoever the room shows as busy", () => {
+ render(room(undefined));
+ stream("Drafting the outline now ", "ada");
+ expect(liveRow()?.textContent).toContain("Drafting the outline now");
+ expect(liveRow()?.textContent, "no one busy yet: still Ada's words").toContain("Ada");
+ render(room("ben"));
+ expect(liveRow()?.textContent, "the room already shows the next speaker").toContain("Ada");
+ expect(liveRow()?.textContent).not.toContain("Ben");
+ });
+});
diff --git a/src/components/GroupView.tsx b/src/components/GroupView.tsx
index b42635c50f..3f3a797a02 100644
--- a/src/components/GroupView.tsx
+++ b/src/components/GroupView.tsx
@@ -77,7 +77,7 @@ import { roomNeedsSetup } from "@/lib/room-setup";
import { useComposerDockPad } from "@/lib/composer-dock";
import { GlassBar, GlassScrollFrame } from "./GlassScrollFrame";
import { awaitedMemberId, showWorkingDots } from "@/lib/turn-tail";
-import { turnNowPhrases } from "@/lib/live-activity"; import { useTurnLive } from "@/state/turn-status";
+import { turnNowPhrases } from "@/lib/live-activity"; import { useTurnLive } from "@/state/turn-status"; import { isLiveReply, StreamingReplyContext, streamedReply, useLiveTranscript } from "@/state/live-reply";
import { splitTranscriptAttachments } from "@/lib/composer-attachments";
import { useTranscriptViewport } from "@/hooks/use-transcript-viewport";
import { useUnreadDivider } from "@/hooks/use-unread-divider";
@@ -183,7 +183,7 @@ function RoomTextMessage({
onToggleRaw: () => setViewRaw((raw) => !raw),
pin,
});
- const replyGroup = useMemo(() => !user && botText.trim() ? replyAttachmentGroup(botText, m.attachments) : null, [user, botText, m.attachments]);
+ const replyGroup = useMemo(() => !user && !isLiveReply(m) && botText.trim() ? replyAttachmentGroup(botText, m.attachments) : null, [user, m, botText]);
const blocks = useMemo(() => simple && !user && !viewRaw && botText.trim() ? splitReplyBlocks(botText) : null, [simple, user, viewRaw, botText]);
const tabled = Boolean(blocks?.some((block) => block.kind === "table"));
const botActions = !user && (
@@ -210,7 +210,7 @@ function RoomTextMessage({
className={cn(
tabled ? "w-full" : "w-fit",
simple ? cn(!tabled && SIMPLE_BUBBLE_MAX, SIMPLE_BUBBLE_TEXT) : "max-w-[min(var(--chat-bubble-max),var(--chat-bubble-pct))] rounded-2xl text-[15px] leading-relaxed",
- !user && emerging && "turn-answer",
+ !user && emerging && !streamedReply(m.id) && "turn-answer",
tabled || (!user && !m.text?.trim() && !m.replyToId && m.attachments?.length)
? "text-ink"
: !simple && !user && isFormattedReply(m.text ?? "")
@@ -307,7 +307,7 @@ export const Transcript = memo(function Transcript({
group,
members,
locale,
- messages,
+ messages: saved,
transcript,
emergingId,
unreadDividerId = null,
@@ -328,7 +328,7 @@ export const Transcript = memo(function Transcript({
const showThreads = useShowThreads();
const showToolCalls = showToolCallsEnabled(state.config);
const canReact = useCanReact(group.threadId);
- const memberOf = (id?: string) => members.find((b) => b.id === id);
+ const memberOf = (id?: string) => members.find((b) => b.id === id); const messages = useLiveTranscript(group.threadId, saved, transcript, members, roomThreadSpeakerId(group, group.threadId));
const folds = useMemo(() => roomTurnFolds(messages), [messages, locale]);
const items = useMemo(() => groupActivityRuns(messages.filter(message =>
!folds.hiddenIds.has(message.id) &&
@@ -513,7 +513,7 @@ export const Transcript = memo(function Transcript({
))}
</TurnNarrationRun>
)}
- {row}
+ {isLiveReply(m) ? <StreamingReplyContext value>{row}</StreamingReplyContext> : row}
</div>
);
})}
@@ -977,7 +977,7 @@ export function GroupView({ group }: { group: Group }) {
transcriptRef,
topSentinelRef,
transcriptKey,
- following,
+ following, showJumpToLatest,
windowedMessages,
hiddenCount,
laterCount,
@@ -1193,7 +1193,7 @@ export function GroupView({ group }: { group: Group }) {
<TranscriptAnnouncer threadKey={transcriptKey} snapshot={announcement} />
- {!following && (
+ {showJumpToLatest && (
<JumpToLatestButton onClick={jumpToLatest} style={{ bottom: composerDock.height }} />
)}
diff --git a/src/components/MessageActions.tsx b/src/components/MessageActions.tsx
index 0ceb20b10c..7d4740218b 100644
--- a/src/components/MessageActions.tsx
+++ b/src/components/MessageActions.tsx
@@ -5,6 +5,7 @@ import { cn } from "@/lib/cn";
import { useCopyFeedback } from "@/lib/copy-text";
import { t } from "@/lib/i18n";
import { MENU_ITEM, MENU_SHEET } from "./menu-recipe";
+import { StreamingReplyContext } from "@/state/live-reply";
export const ACTION_ICON = { size: 17, strokeWidth: 1.5 } as const;
@@ -67,7 +68,8 @@ export function MessageActions({
const [menuAbove, setMenuAbove] = useState(false);
const [menuFlipped, setMenuFlipped] = useState(false);
const mirrored = side === "user";
- const shown = forceOpen || menuOpen || hovered || keyboardFocus || tapped;
+ const streaming = use(StreamingReplyContext);
+ const shown = !streaming && (forceOpen || menuOpen || hovered || keyboardFocus || tapped);
useEffect(() => {
const row = rootRef.current?.closest<HTMLElement>(`[${MESSAGE_ROW}]`) ?? rootRef.current;
@@ -173,6 +175,7 @@ export function MessageActions({
className,
)}
data-testid="message-actions"
+ inert={streaming || undefined}
data-shown={shown ? "true" : undefined}
onKeyDown={(event) => {
if (menuOpen || forceOpen || !popoverClosesOnKey(event.nativeEvent) || !keyboardFocus) return;
diff --git a/src/hooks/use-transcript-viewport.test.ts b/src/hooks/use-transcript-viewport.test.ts
index ba65f984b8..196e9afb5b 100644
--- a/src/hooks/use-transcript-viewport.test.ts
+++ b/src/hooks/use-transcript-viewport.test.ts
@@ -83,6 +83,9 @@ vi.mock("@/state/store", () => ({ useStore: () => store }));
vi.mock("@/lib/focus-message", () => ({ useFocusMessage: () => {} }));
import { useTranscriptViewport } from "./use-transcript-viewport";
+import { forgetTranscriptPositions } from "@/lib/transcript-follow";
+import { noteLiveReplyEvent, resetLiveReplies } from "@/state/live-reply";
+import type { RuntimeEvent } from "../../shared/runtime-events";
type Row = { id: string; role?: "user" | "bot" };
const rows = (count: number, from = 0): Row[] => Array.from({ length: count }, (_, index) => ({ id: `m${from + index}` }));
@@ -105,13 +108,25 @@ class Scroller {
this.calls.push(options);
this.scrollTop = Math.max(0, Math.min(options.top ?? this.scrollTop, this.bottom));
}
+ getBoundingClientRect() {
+ return { top: 0, bottom: this.clientHeight, height: this.clientHeight };
+ }
}
+/** The mounted rows, each ROW tall, laid out from the scroller's top. */
+const transcriptOf = (shown: readonly Row[]) => ({
+ querySelectorAll: () => shown.map((row, index) => {
+ const top = index * ROW - scroller.scrollTop;
+ return { dataset: { mid: row.id }, getBoundingClientRect: () => ({ top, bottom: top + ROW, height: ROW }) };
+ }),
+});
+
type Props = Parameters<typeof useTranscriptViewport<Row>>[0];
let scroller: Scroller;
let frames: FrameRequestCallback[];
let keyListeners: Set<(event: Partial<KeyboardEvent>) => void>;
let observers: number;
+let resized: (() => void)[];
let dispatched: unknown[];
function mount(initial: Partial<Props> = {}) {
@@ -123,7 +138,7 @@ function mount(initial: Partial<Props> = {}) {
// React's commit before layout effects; a browser clamps scrollTop when content gets shorter.
const commit = () => {
result.scrollRef.current = scroller as unknown as HTMLDivElement;
- result.transcriptRef.current = {} as HTMLDivElement;
+ result.transcriptRef.current = transcriptOf(result.windowedMessages) as unknown as HTMLDivElement;
scroller.rows = result.windowedMessages.length;
scroller.scrollTop = Math.min(scroller.scrollTop, scroller.bottom);
};
@@ -155,7 +170,10 @@ beforeEach(() => {
frames = [];
keyListeners = new Set();
observers = 0;
+ resized = [];
dispatched = [];
+ forgetTranscriptPositions();
+ resetLiveReplies();
store.state.focusMessage = null;
store.state.loadingOlder = {};
store.dispatch = (action) => dispatched.push(action);
@@ -165,8 +183,9 @@ beforeEach(() => {
});
vi.stubGlobal("requestAnimationFrame", (frame: FrameRequestCallback) => frames.push(frame));
vi.stubGlobal("ResizeObserver", class {
- constructor() {
+ constructor(callback: () => void) {
observers++;
+ resized.push(callback);
}
observe() {}
disconnect() {}
@@ -572,3 +591,98 @@ describe("transcript viewport", () => {
expect(dispatched).toEqual([{ type: "loadOlderMessages", threadId: "thread" }]);
});
});
+
+describe("following a reply and coming back to a conversation", () => {
+ const readUpTo = (view: ReturnType<typeof mount>, scrollTop: number) => {
+ view.act(() => view.current.scrollHandlers.onWheel({ deltaY: -40 } as never));
+ view.act(() => {
+ scroller.scrollTop = scrollTop;
+ view.current.scrollHandlers.onScroll();
+ });
+ };
+
+ it("opens a conversation where the reader left it, and another one at its end", () => {
+ const view = mount({ messages: rows(300) });
+ readUpTo(view, 1_000);
+ expect(view.current.following).toBe(false);
+ const reading = view.current.windowedMessages[1_000 / ROW]!.id;
+
+ view.rerender({ threadId: "other", messages: rows(50, 5_000) });
+ expect(view.current.following, "a conversation never read opens at its end").toBe(true);
+ expect(scroller.scrollTop).toBe(scroller.bottom);
+
+ scroller.calls = [];
+ view.rerender({ threadId: "thread", messages: rows(300) });
+ expect(view.current.following).toBe(false);
+ expect(view.current.windowedMessages.map((row) => row.id)).toContain(reading);
+ expect(view.current.windowedMessages[scroller.scrollTop / ROW]!.id, "the same row is at the top, before any paint").toBe(reading);
+ expect(scroller.calls, "no trip to the end on the way").toEqual([]);
+ expect(view.current.showJumpToLatest).toBe(false);
+ });
+
+ it("opens at the end a conversation the reader left following, even after it grew", () => {
+ const view = mount({ messages: rows(40) });
+ view.rerender({ threadId: "other", messages: rows(40, 5_000) });
+ readUpTo(view, 200);
+ view.rerender({ threadId: "thread", messages: rows(60) });
+ expect(view.current.following).toBe(true);
+ expect(scroller.scrollTop).toBe(scroller.bottom);
+ });
+
+ it("follows the end again when the person sends a message, wherever they were reading", () => {
+ const view = mount({ messages: rows(60) });
+ readUpTo(view, 300);
+ expect(view.current.following).toBe(false);
+ view.rerender({ messages: [...rows(60), { id: "optimistic-1", role: "user" }] });
+ expect(view.current.following).toBe(true);
+ expect(scroller.scrollTop).toBe(scroller.bottom);
+ });
+
+ it("does not follow a message someone else sent while the reader is up the page", () => {
+ const view = mount({ messages: rows(60) });
+ readUpTo(view, 300);
+ view.rerender({ messages: [...rows(60), { id: "from-a-teammate", role: "user" }] });
+ expect(view.current.following).toBe(false);
+ expect(scroller.scrollTop).toBe(300);
+ });
+
+ it("glides after a growing reply while following, lands at once otherwise, and never pulls a reader down", () => {
+ const view = mount({ messages: rows(20) });
+ const grow = () => {
+ scroller.extra += 30;
+ for (const callback of resized) callback();
+ };
+ grow();
+ expect(scroller.calls.at(-1)).toEqual({ top: scroller.scrollHeight });
+
+ noteLiveReplyEvent({ eventId: "d1", provider: "claudeAgent", threadId: "thread", createdAt: "", turnId: "t", type: "content.delta", streamKind: "assistant_text", delta: "Streaming words " } as RuntimeEvent);
+ grow();
+ expect(scroller.calls.at(-1)).toEqual({ top: scroller.scrollHeight, behavior: "smooth" });
+
+ readUpTo(view, 100);
+ const calls = scroller.calls.length;
+ grow();
+ grow();
+ expect(scroller.calls.length - calls, "the reader scrolled up: growth leaves them where they are").toBe(0);
+ expect(scroller.scrollTop).toBe(100);
+ });
+
+ it("offers Jump to latest only a moment after the reader leaves the end, and hides it at once on return", () => {
+ vi.useFakeTimers();
+ try {
+ const view = mount({ messages: rows(60) });
+ readUpTo(view, 300);
+ expect(view.current.showJumpToLatest, "not on the first frame away").toBe(false);
+ view.act(() => void vi.advanceTimersByTime(150));
+ expect(view.current.showJumpToLatest).toBe(true);
+ view.act(() => {
+ scroller.scrollTop = scroller.bottom;
+ view.current.scrollHandlers.onScroll();
+ });
+ expect(view.current.following).toBe(true);
+ expect(view.current.showJumpToLatest).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/src/hooks/use-transcript-viewport.ts b/src/hooks/use-transcript-viewport.ts
index dd6b1bb6ee..8096bf8ce1 100644
--- a/src/hooks/use-transcript-viewport.ts
+++ b/src/hooks/use-transcript-viewport.ts
@@ -10,7 +10,7 @@ import {
type TouchEvent,
type WheelEvent,
} from "react";
-import { BOTTOM_FOLLOW_THRESHOLD, shouldResumeBottomFollow, useBottomFollowResize } from "@/lib/bottom-follow";
+import { BOTTOM_FOLLOW_THRESHOLD, followBottomGrowth, useBottomFollowResize } from "@/lib/bottom-follow";
import { useFocusMessage } from "@/lib/focus-message";
import {
TRANSCRIPT_WINDOW_SIZE,
@@ -21,12 +21,43 @@ import {
tailWindowStart,
} from "@/lib/transcript-window";
import { reducedMotion } from "@/lib/onboarding";
+import {
+ JUMP_TO_LATEST_DELAY_MS,
+ initialTranscriptFollow,
+ readTranscriptPosition,
+ rememberTranscriptPosition,
+ rowScrollTop,
+ settleScroll,
+ topRow,
+ transitionTranscriptFollow,
+ wantsJumpToLatest,
+ type TranscriptFollow,
+ type TranscriptFollowEvent,
+} from "@/lib/transcript-follow";
+import { hasLiveReply } from "@/state/live-reply";
import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
export const AUTO_EXPAND_TOP_THRESHOLD = 250;
const WIDGETS_WITH_OWN_ARROW_KEYS = '[role="menu"], [role="menubar"], [role="listbox"], [role="tree"], [role="grid"], [role="tablist"], [role="radiogroup"], [role="slider"], select, [contenteditable="true"]';
+const atEndOf = (el: HTMLElement | null) => !el || el.scrollHeight - el.scrollTop - el.clientHeight < BOTTOM_FOLLOW_THRESHOLD;
+
+interface TranscriptVisit {
+ key: string;
+ follow: TranscriptFollow;
+ /** The row to put back at the top, and the window start that draws it; absent when the visit opens at the end. */
+ restore?: { rowId: string; offsetWithinRow: number; start: number };
+}
+
+function openVisit(key: string, messages: readonly { id: string }[]): TranscriptVisit {
+ const remembered = readTranscriptPosition(key);
+ const rowIndex = remembered && !remembered.atEnd && remembered.rowId ? messages.findIndex((message) => message.id === remembered.rowId) : -1;
+ if (!remembered || rowIndex < 0) return { key, follow: initialTranscriptFollow(true) };
+ const start = Math.min(rowIndex, Math.max(0, Math.min(remembered.windowStart ?? rowIndex, tailWindowStart(messages.length))));
+ return { key, follow: initialTranscriptFollow(false), restore: { rowId: remembered.rowId!, offsetWithinRow: remembered.offsetWithinRow ?? 0, start } };
+}
+
export function useTranscriptViewport<T extends { id: string; role?: string }>({
ownerId,
threadId,
@@ -48,28 +79,29 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
const scrollRef = useRef<HTMLDivElement>(null);
const transcriptRef = useRef<HTMLDivElement>(null);
const topSentinelRef = useRef<HTMLDivElement>(null);
-
- // Follow breaks only on an upward user gesture: content growth flickers "at bottom" false for a frame.
- const [follow, setFollow] = useState(true);
- const followRef = useRef(true);
- const previousScrollTop = useRef(0);
const touchY = useRef(0);
const transcriptKey = `${ownerId}:${threadId}`;
const tailStart = tailWindowStart(messages.length);
- const [transcriptWindow, setTranscriptWindow] = useState<{
- key: string;
- start: number;
- end: number | null;
- }>(() => ({
- key: transcriptKey,
- start: tailStart,
- end: null,
- }));
+ // One visit per conversation: switching back opens where the reader left it, or at the end if they were there.
+ const [visit, setVisit] = useState(() => openVisit(transcriptKey, messages));
+ const [transcriptWindow, setTranscriptWindow] = useState<{ key: string; start: number; end: number | null }>(
+ () => ({ key: transcriptKey, start: visit.restore?.start ?? tailStart, end: null }),
+ );
+ const followNow = useRef<{ key: string; follow: TranscriptFollow }>({ key: visit.key, follow: visit.follow });
+ const followRef = useRef(visit.follow.mode === "following");
const switched = transcriptWindow.key !== transcriptKey;
+ const current = visit.key === transcriptKey ? visit : openVisit(transcriptKey, messages);
+ if (current !== visit) setVisit(current);
+ if (followNow.current.key !== transcriptKey) {
+ followNow.current = { key: transcriptKey, follow: current.follow };
+ followRef.current = current.follow.mode === "following";
+ }
+ const follow = followNow.current.follow;
+ const following = follow.mode === "following";
const nextStart = switched
- ? tailStart
- : follow && transcriptWindow.end === null
+ ? current.restore?.start ?? tailStart
+ : following && transcriptWindow.end === null
? followWindowStart(messages, transcriptWindow.start)
: transcriptWindow.start;
if (switched || nextStart !== transcriptWindow.start) {
@@ -85,34 +117,101 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
() => resolveTranscriptWindow(messages, transcriptWindow.start, TRANSCRIPT_WINDOW_SIZE, transcriptWindow.end),
[messages, transcriptWindow.start, transcriptWindow.end],
);
+ const windowRef = useRef(transcriptWindow);
+ windowRef.current = transcriptWindow;
+
+ const [, setFollowShown] = useState(follow);
+ const navigationCount = useRef(0);
+ // A reply streaming in is followed smoothly; anything else (a switch, history loading, a sent message) lands at once.
+ const smoothFollow = useCallback(() => hasLiveReply(threadId) && !reducedMotion(), [threadId]);
+ const followEvent = useCallback((event: TranscriptFollowEvent) => {
+ const before = followNow.current.follow;
+ const after = transitionTranscriptFollow(before, event);
+ if (event.type === "navigated") navigationCount.current += 1;
+ if (after === before) return;
+ followNow.current = { key: followNow.current.key, follow: after };
+ followRef.current = after.mode === "following";
+ const el = scrollRef.current;
+ if (el && before.mode === "following" && after.mode === "released" && smoothFollow()) {
+ // A smooth follow scroll keeps running after the reader takes over; an instant scroll to where it is halts it.
+ el.scrollTo({ top: el.scrollTop });
+ }
+ if (after.mode === "following") rememberTranscriptPosition(followNow.current.key, { atEnd: true });
+ setFollowShown(after);
+ }, [smoothFollow]);
+ const setBottomFollow = useCallback((next: boolean) => followEvent({ type: next ? "followEnd" : "navigated" }), [followEvent]);
+
+ const nearEnd = () => atEndOf(scrollRef.current);
+ const noteEnd = useCallback(() => {
+ if (scrollRef.current) followEvent({ type: atEndOf(scrollRef.current) ? "reachedEnd" : "leftEnd" });
+ }, [followEvent]);
+
+ const recordFrame = useRef(false);
+ const recordPosition = () => {
+ if (recordFrame.current) return;
+ recordFrame.current = true;
+ requestAnimationFrame(() => {
+ recordFrame.current = false;
+ const el = scrollRef.current, list = transcriptRef.current, key = followNow.current.key;
+ if (!el || !list || key !== windowRef.current.key) return;
+ if (followRef.current || nearEnd()) return rememberTranscriptPosition(key, { atEnd: true });
+ const top = topRow(el, list);
+ if (top) rememberTranscriptPosition(key, { atEnd: false, ...top, windowStart: windowRef.current.start, windowEnd: windowRef.current.end });
+ });
+ };
+
+ // Content growing under a released reader can only take the end away from them; their own scroll brings it back.
+ const noteLeftEnd = useCallback(() => {
+ if (!atEndOf(scrollRef.current)) followEvent({ type: "leftEnd" });
+ }, [followEvent]);
+ const onTranscriptResize = useCallback(() => {
+ const el = scrollRef.current;
+ if (el && !followBottomGrowth(el, followRef.current, smoothFollow())) noteLeftEnd();
+ }, [noteLeftEnd, smoothFollow]);
+ useBottomFollowResize(scrollRef, transcriptRef, transcriptShown ? transcriptKey : null, onTranscriptResize);
- const setBottomFollow = useCallback((next: boolean) => {
- followRef.current = next;
- setFollow(next);
- }, []);
- useBottomFollowResize(scrollRef, transcriptRef, followRef, transcriptShown ? transcriptKey : null);
+ // The person sent a message: whatever they were reading, the conversation follows its end again.
+ const newestId = messages.at(-1)?.id;
+ const sentLast = Boolean(newestId?.startsWith("optimistic-"));
+ useLayoutEffect(() => {
+ if (sentLast) setBottomFollow(true);
+ }, [newestId, sentLast, setBottomFollow]);
- useEffect(() => setBottomFollow(true), [transcriptKey, setBottomFollow]);
+ // A remembered row is put back before the first paint and held while late layout settles; any move of the reader's
+ // own stops that.
+ useLayoutEffect(() => {
+ const el = scrollRef.current, list = transcriptRef.current, restore = current.restore;
+ if (!el || !list || !restore) return;
+ const navigations = navigationCount.current;
+ const target = () => rowScrollTop(el, list, restore.rowId, restore.offsetWithinRow);
+ const first = target();
+ if (first === undefined) return;
+ el.scrollTop = first;
+ settleScroll(el, target, () => navigationCount.current !== navigations || followNow.current.key !== current.key);
+ }, [current]);
const appliedFocus = useRef<number | null>(null);
- useEffect(() => {
+ // Before the follow scroll below: a search jump into the conversation just opened wins over its end.
+ useLayoutEffect(() => {
const focus = focusMessage;
if (!focus || focus.consumed || focus.threadId !== threadId || appliedFocus.current === focus.nonce) return;
const targetIndex = messages.findIndex((message) => message.id === focus.messageId);
if (targetIndex < 0) return;
appliedFocus.current = focus.nonce;
const range = focusWindowRange(messages.length, targetIndex);
- setBottomFollow(false);
+ followEvent({ type: "navigated" });
+ followEvent({ type: "leftEnd" });
setTranscriptWindow({ key: transcriptKey, start: range.start, end: range.end });
- }, [threadId, messages, setBottomFollow, focusMessage, transcriptKey]);
+ }, [threadId, messages, followEvent, focusMessage, transcriptKey]);
useFocusMessage(threadId, messages.length > 0);
- // `follow` is omitted on purpose: re-arming only arms future content and never scrolls.
- useEffect(() => {
+ // Before paint, so a conversation opens at its end with no frame elsewhere. `follow` is omitted on purpose: re-arming
+ // only arms future content and never scrolls.
+ useLayoutEffect(() => {
const el = scrollRef.current;
- if (!el || !followRef.current) return;
+ if (!el) return;
+ if (!followRef.current) return noteLeftEnd();
el.scrollTo({ top: el.scrollHeight });
- previousScrollTop.current = el.scrollTop;
// eslint-disable-next-line react-hooks/exhaustive-deps -- pinOn is the caller's dependency list
}, [transcriptKey, messages.length, ...pinOn]);
@@ -138,7 +237,6 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
return;
}
el.scrollTop += el.scrollHeight - captured.height;
- previousScrollTop.current = el.scrollTop;
expandingRef.current = false;
}, [transcriptWindow.start, oldestId, transcriptKey]);
@@ -212,10 +310,6 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
};
// Rows that draw nothing (hidden tool steps) can leave a window too short to scroll while earlier ones exist.
const canScrollUp = () => canScroll() || hiddenCount > 0 || Boolean(hasMore);
- const atEnd = () => {
- const el = scrollRef.current;
- return !el || el.scrollHeight - el.scrollTop - el.clientHeight < BOTTOM_FOLLOW_THRESHOLD;
- };
const jumpToLatest = () => {
setBottomFollow(true);
setTranscriptWindow({ key: transcriptKey, start: tailStart, end: null });
@@ -237,7 +331,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
if (el && el.scrollTop <= AUTO_EXPAND_TOP_THRESHOLD) {
triggerAutoEarlier();
}
- } else if (atEnd()) {
+ } else if (nearEnd()) {
setBottomFollow(true);
}
},
@@ -252,35 +346,35 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
if (el && el.scrollTop <= AUTO_EXPAND_TOP_THRESHOLD) {
triggerAutoEarlier();
}
- } else if (atEnd()) {
+ } else if (nearEnd()) {
setBottomFollow(true);
}
},
onScroll: () => {
const el = scrollRef.current;
if (!el) return;
- const scrollTop = el.scrollTop;
- const resume = shouldResumeBottomFollow({
- following: followRef.current,
- previousScrollTop: previousScrollTop.current,
- scrollTop,
- distanceFromBottom: el.scrollHeight - scrollTop - el.clientHeight,
- });
- previousScrollTop.current = scrollTop;
- if (resume) {
- setBottomFollow(true);
- } else if (!followRef.current && scrollTop <= AUTO_EXPAND_TOP_THRESHOLD) {
- triggerAutoEarlier();
- }
+ noteEnd();
+ recordPosition();
+ if (!followRef.current && el.scrollTop <= AUTO_EXPAND_TOP_THRESHOLD) triggerAutoEarlier();
},
};
+ const wantsJump = wantsJumpToLatest(follow);
+ const [jumpShown, setJumpShown] = useState(false);
+ useEffect(() => {
+ if (!wantsJump) return setJumpShown(false);
+ const timer = setTimeout(() => setJumpShown(true), JUMP_TO_LATEST_DELAY_MS);
+ return () => clearTimeout(timer);
+ }, [wantsJump, transcriptKey]);
+
return {
scrollRef,
transcriptRef,
topSentinelRef,
transcriptKey,
- following: follow,
+ following,
+ /** The reader left the end a moment ago and has not come back: offer the way down. */
+ showJumpToLatest: wantsJump && jumpShown,
windowedMessages,
hiddenCount,
laterCount,
diff --git a/src/lib/bottom-follow.test.ts b/src/lib/bottom-follow.test.ts
index c9707f107d..f68f9a14ec 100644
--- a/src/lib/bottom-follow.test.ts
+++ b/src/lib/bottom-follow.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { BOTTOM_FOLLOW_THRESHOLD, followBottomGrowth, shouldResumeBottomFollow } from "./bottom-follow";
+import { followBottomGrowth } from "./bottom-follow";
describe("followBottomGrowth", () => {
it("scrolls resized content to its new bottom while following", () => {
@@ -14,71 +14,25 @@ describe("followBottomGrowth", () => {
expect(calls).toEqual([{ top: 1_240 }]);
});
- it("preserves scrollback when bottom-follow is detached", () => {
+ it("glides to the bottom while a reply streams in", () => {
const calls: ScrollToOptions[] = [];
const scroller = {
scrollHeight: 1_240,
scrollTo: (options: ScrollToOptions) => calls.push(options),
};
- expect(followBottomGrowth(scroller, false)).toBe(false);
- expect(calls).toEqual([]);
- });
-});
-
-describe("shouldResumeBottomFollow", () => {
- it("does not re-pin a small upward scroll inside the near-bottom zone", () => {
- expect(
- shouldResumeBottomFollow({
- following: false,
- previousScrollTop: 1_000,
- scrollTop: 992,
- distanceFromBottom: 8,
- }),
- ).toBe(false);
- });
-
- it("re-pins after scrolling downward to the end", () => {
- expect(
- shouldResumeBottomFollow({
- following: false,
- previousScrollTop: 992,
- scrollTop: 1_000,
- distanceFromBottom: 0,
- }),
- ).toBe(true);
- });
-
- it("stays detached while downward movement remains away from the end", () => {
- expect(
- shouldResumeBottomFollow({
- following: false,
- previousScrollTop: 500,
- scrollTop: 600,
- distanceFromBottom: BOTTOM_FOLLOW_THRESHOLD,
- }),
- ).toBe(false);
+ expect(followBottomGrowth(scroller, true, true)).toBe(true);
+ expect(calls).toEqual([{ top: 1_240, behavior: "smooth" }]);
});
- it("does not re-pin in the old 48px magnet zone", () => {
- expect(
- shouldResumeBottomFollow({
- following: false,
- previousScrollTop: 952,
- scrollTop: 960,
- distanceFromBottom: 40,
- }),
- ).toBe(false);
- });
+ it("preserves scrollback when bottom-follow is detached", () => {
+ const calls: ScrollToOptions[] = [];
+ const scroller = {
+ scrollHeight: 1_240,
+ scrollTo: (options: ScrollToOptions) => calls.push(options),
+ };
- it("does nothing when bottom-follow is already active", () => {
- expect(
- shouldResumeBottomFollow({
- following: true,
- previousScrollTop: 992,
- scrollTop: 1_000,
- distanceFromBottom: 0,
- }),
- ).toBe(false);
+ expect(followBottomGrowth(scroller, false)).toBe(false);
+ expect(calls).toEqual([]);
});
});
diff --git a/src/lib/bottom-follow.ts b/src/lib/bottom-follow.ts
index a17251bac4..3749d186d6 100644
--- a/src/lib/bottom-follow.ts
+++ b/src/lib/bottom-follow.ts
@@ -2,46 +2,31 @@ import { useLayoutEffect, type RefObject } from "react";
export const BOTTOM_FOLLOW_THRESHOLD = 4;
-export function shouldResumeBottomFollow({
- following,
- previousScrollTop,
- scrollTop,
- distanceFromBottom,
-}: {
- following: boolean;
- previousScrollTop: number;
- scrollTop: number;
- distanceFromBottom: number;
-}): boolean {
- return !following && scrollTop > previousScrollTop && distanceFromBottom < BOTTOM_FOLLOW_THRESHOLD;
-}
-
interface BottomFollowScroller {
scrollHeight: number;
scrollTo(options?: ScrollToOptions): void;
}
-export function followBottomGrowth(scroller: BottomFollowScroller, following: boolean): boolean {
+export function followBottomGrowth(scroller: BottomFollowScroller, following: boolean, smooth = false): boolean {
if (!following) return false;
- scroller.scrollTo({ top: scroller.scrollHeight });
+ scroller.scrollTo(smooth ? { top: scroller.scrollHeight, behavior: "smooth" } : { top: scroller.scrollHeight });
return true;
}
+/** Calls `onResize` whenever the transcript's content changes size: a reply growing inside its last row included. */
export function useBottomFollowResize(
scrollRef: RefObject<HTMLElement | null>,
transcriptRef: RefObject<HTMLElement | null>,
- followingRef: RefObject<boolean>,
observeKey: string | null,
+ onResize: () => void,
): void {
useLayoutEffect(() => {
const scroller = scrollRef.current;
const transcript = transcriptRef.current;
if (!scroller || !transcript || observeKey === null) return;
- const observer = new ResizeObserver(() => {
- followBottomGrowth(scroller, followingRef.current);
- });
+ const observer = new ResizeObserver(onResize);
observer.observe(transcript);
return () => observer.disconnect();
- }, [followingRef, observeKey, scrollRef, transcriptRef]);
+ }, [observeKey, onResize, scrollRef, transcriptRef]);
}
diff --git a/src/lib/live-events.ts b/src/lib/live-events.ts
index cd53a75652..f0e9ff0595 100644
--- a/src/lib/live-events.ts
+++ b/src/lib/live-events.ts
@@ -3,6 +3,7 @@ import type { ServerFrame } from "../../shared/wire";
import { cloudAsleep, markCloudAsleep, onCloudPower, sleepingFrame } from "./cloud-power";
import { recordBotTextMessage, recordRuntimeEvent } from "./voice-latency-probe";
import { noteTurnEvent } from "@/state/turn-status";
+import { forgetLiveReplies, noteLiveReplyEvent, noteLiveReplyMessage } from "@/state/live-reply";
export const LIVE_EVENTS_PATH = "/api/events";
export const LIVE_EVENTS_STALE_MS = 40_000;
@@ -101,6 +102,7 @@ export function publishLiveFrame(frame: ServerFrame): void {
}
export function publishMissedFrames(): void {
+ forgetLiveReplies();
for (const listener of liveFrameListeners) listener.onMissedFrames?.();
}
@@ -140,8 +142,10 @@ function tapLiveFrame(frame: ServerFrame): void {
if (frame.kind === "runtime") {
// The chat's status line reads every live runtime frame; none of them is stored.
noteTurnEvent(frame.event);
+ noteLiveReplyEvent(frame.event);
recordRuntimeEvent(frame.event);
} else if (frame.kind === "message" && frame.message?.role === "bot" && frame.message?.kind === "text") {
+ noteLiveReplyMessage(frame.threadId, frame.message);
recordBotTextMessage(frame.message, frame.threadId);
}
}
diff --git a/src/lib/markdown-stream-blocks.test.ts b/src/lib/markdown-stream-blocks.test.ts
new file mode 100644
index 0000000000..e19e1af5bc
--- /dev/null
+++ b/src/lib/markdown-stream-blocks.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from "vitest";
+
+import { closedFence, openFence, splitMarkdownBlocks } from "./markdown-stream-blocks";
+
+describe("splitting streamed Markdown into blocks", () => {
+ it("cuts at blank lines that close every block, and the pieces join back to the text", () => {
+ // A list marker after a blank line may still belong to what is above it, so it never starts a block.
+ const text = "# Plan\n\nFirst paragraph\nstill first.\n\n- one\n- two\n\nLast";
+ const blocks = splitMarkdownBlocks(text)!;
+ expect(blocks).toEqual(["# Plan\n\n", "First paragraph\nstill first.\n\n- one\n- two\n\n", "Last"]);
+ expect(blocks.join("")).toBe(text);
+ });
+
+ it("keeps a loose list and indented content in one block", () => {
+ const text = "- one\n\n- two\n\n more of two\n\nAfter";
+ expect(splitMarkdownBlocks(text)).toEqual(["- one\n\n- two\n\n more of two\n\n", "After"]);
+ });
+
+ it("never cuts inside a code fence, closed or still open", () => {
+ const closed = "Intro\n\n```js\nconst a = 1;\n\nconst b = 2;\n```\n\nOutro";
+ expect(splitMarkdownBlocks(closed)).toEqual(["Intro\n\n", "```js\nconst a = 1;\n\nconst b = 2;\n```\n\n", "Outro"]);
+ const open = "Intro\n\n~~~\nline\n\nmore";
+ expect(splitMarkdownBlocks(open)).toEqual(["Intro\n\n", "~~~\nline\n\nmore"]);
+ });
+
+ it("stops at an indented fence's edge, leaving the rest to the last block", () => {
+ const text = "- item\n\n ```\n code\n\nloose";
+ const blocks = splitMarkdownBlocks(text)!;
+ expect(blocks.join("")).toBe(text);
+ expect(blocks.at(-1)).toContain("code");
+ });
+
+ it("falls back to the whole text when syntax ties blocks together", () => {
+ for (const text of [
+ "See [the docs][1].\n\n[1]: https://example.com",
+ "A claim.[^1]\n\n[^1]: The source.",
+ "<details>\n\nhidden\n\n</details>",
+ "$$\nx^2\n\n$$",
+ "\\[\na\n\\]",
+ "::: note\n\nbody\n:::",
+ "Line\r\n\r\nother",
+ ]) expect(splitMarkdownBlocks(text), text).toBeNull();
+ });
+});
+
+describe("a fence still being written", () => {
+ it("is read without parsing while it has no closing line", () => {
+ expect(openFence("```ts wrap\nconst a = 1;\nconst b")).toEqual({ info: "ts wrap", code: "const a = 1;\nconst b" });
+ expect(openFence("```")).toEqual({ info: "", code: "" });
+ expect(openFence("~~~~\nx\n~~~\n")).toEqual({ info: "", code: "x\n~~~" });
+ });
+
+ it("is not one once it closes, or when the block is not a fence", () => {
+ expect(openFence("```js\ncode\n```\n")).toBeNull();
+ expect(openFence("~~~\ncode\n~~~~")).toBeNull();
+ expect(openFence("Prose with ``` in it")).toBeNull();
+ expect(openFence("``` inline ` tick")).toBeNull();
+ });
+
+ it("tells a closed fence from an open one by its last line", () => {
+ const closed = "```js\ncode\n```";
+ expect(closedFence(closed, 0, closed.length)).toBe(true);
+ const open = "```js\ncode\nmore";
+ expect(closedFence(open, 0, open.length)).toBe(false);
+ expect(closedFence("```", 0, 3)).toBe(false);
+ expect(closedFence("````\na\n```", 0, 10), "a shorter closer does not close").toBe(false);
+ expect(closedFence(" indented code", 0, 17), "indented code has no fence").toBe(true);
+ expect(closedFence("anything", undefined, undefined)).toBe(true);
+ });
+});
diff --git a/src/lib/markdown-stream-blocks.ts b/src/lib/markdown-stream-blocks.ts
new file mode 100644
index 0000000000..870c4b06e6
--- /dev/null
+++ b/src/lib/markdown-stream-blocks.ts
@@ -0,0 +1,63 @@
+// Definitions, footnotes, raw HTML, container directives and display math can tie blocks together.
+const DOCUMENT_WIDE_SYNTAX = /^ {0,3}(?:\[[^\]\n]+\]:|<[A-Za-z!?/]|:::|\$\$|\\\[)|\[\^/m;
+const FENCE_OPENER = /^ {0,3}(`{3,}|~{3,})/;
+// After a blank line these still continue the previous block: a list item or indented content.
+const CONTINUATION = /^(?:[ \t]|(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$))/;
+
+/**
+ * Cuts Markdown at blank lines that close every open block, so each piece renders exactly as it would inside the whole
+ * text. Null when the text uses syntax that spans blocks.
+ */
+export function splitMarkdownBlocks(text: string): string[] | null {
+ if (text.includes("\r") || DOCUMENT_WIDE_SYNTAX.test(text)) return null;
+ const blocks: string[] = [];
+ let blockStart = 0;
+ let lineStart = 0;
+ let fence: string | null = null;
+ let fenceIndent = 0;
+ let afterBlankLine = false;
+ for (const line of text.split("\n")) {
+ const opener = FENCE_OPENER.exec(line)?.[1];
+ if (fence !== null) {
+ // A line left of an indented fence may end the list item holding it, which is not tracked.
+ if (/\S/.test(line.slice(0, fenceIndent))) break;
+ if (opener && opener[0] === fence[0] && opener.length >= fence.length && line.trim() === opener) fence = null;
+ } else if (line.trim() === "") {
+ afterBlankLine = true;
+ } else {
+ if (afterBlankLine && lineStart > blockStart && !CONTINUATION.test(line)) {
+ blocks.push(text.slice(blockStart, lineStart));
+ blockStart = lineStart;
+ }
+ afterBlankLine = false;
+ fence = opener ?? null;
+ if (opener) fenceIndent = line.indexOf(opener);
+ }
+ lineStart += line.length + 1;
+ }
+ blocks.push(text.slice(blockStart));
+ return blocks;
+}
+
+/** A block that is one code fence still being written, from its first column: its info string and code so far. */
+export function openFence(block: string): { info: string; code: string } | null {
+ const newline = block.indexOf("\n");
+ const first = newline < 0 ? block : block.slice(0, newline);
+ const opener = /^(`{3,}|~{3,})(.*)$/.exec(first);
+ if (!opener || (opener[1]![0] === "`" && opener[2]!.includes("`"))) return null;
+ const code = newline < 0 ? "" : block.slice(newline + 1);
+ const closing = new RegExp(`^ {0,3}${opener[1]![0] === "`" ? "`" : "~"}{${opener[1]!.length},}[ \\t]*$`, "m");
+ if (closing.test(code)) return null;
+ return { info: opener[2]!.trim(), code: code.replace(/\n$/, "") };
+}
+
+/** Whether the fenced code at `start..end` of `source` has its closing fence. */
+export function closedFence(source: string, start: number | undefined, end: number | undefined): boolean {
+ if (start === undefined || end === undefined) return true;
+ const value = source.slice(start, end);
+ const opener = FENCE_OPENER.exec(value)?.[1];
+ if (!opener) return true;
+ if (!value.includes("\n")) return false;
+ const lastLine = value.slice(value.lastIndexOf("\n") + 1);
+ return new RegExp(`^ {0,3}${opener[0] === "`" ? "`" : "~"}{${opener.length},}[ \\t]*$`).test(lastLine);
+}
diff --git a/src/lib/stop-turn.ts b/src/lib/stop-turn.ts
index b080350a3e..ba2425e7ef 100644
--- a/src/lib/stop-turn.ts
+++ b/src/lib/stop-turn.ts
@@ -7,6 +7,7 @@ import { useSyncExternalStore } from "react";
import type { RuntimeEvent } from "../../shared/runtime-events";
import { isCancelledTranscriptRow } from "../../shared/client-cancel";
import type { Message } from "@/state/store";
+import { stopLiveReply } from "@/state/live-reply";
export const STOP_REPEAT_MS = 1_000;
@@ -66,6 +67,7 @@ export function sendStop(api: Api, action: StopAction, showError: (error: unknow
const last = lastStops.get(key);
if (last !== undefined && now - last < STOP_REPEAT_MS) return;
lastStops.set(key, now);
+ if (action.threadId) stopLiveReply(action.threadId);
const turnId = action.threadId ? liveTurns.get(action.threadId) : undefined;
api(`/api/bots/${action.botId}/interrupt`, {
method: "POST",
diff --git a/src/lib/transcript-follow.test.ts b/src/lib/transcript-follow.test.ts
new file mode 100644
index 0000000000..b4da3242de
--- /dev/null
+++ b/src/lib/transcript-follow.test.ts
@@ -0,0 +1,59 @@
+import { afterEach, describe, expect, it } from "vitest";
+
+import {
+ FOLLOWING,
+ forgetTranscriptPositions,
+ initialTranscriptFollow,
+ readTranscriptPosition,
+ rememberTranscriptPosition,
+ transitionTranscriptFollow,
+ wantsJumpToLatest,
+ type TranscriptFollow,
+ type TranscriptFollowEvent,
+} from "./transcript-follow";
+
+const run = (from: TranscriptFollow, ...events: TranscriptFollowEvent["type"][]) =>
+ events.reduce((state, type) => transitionTranscriptFollow(state, { type } as TranscriptFollowEvent), from);
+
+afterEach(() => forgetTranscriptPositions());
+
+describe("following a transcript's end", () => {
+ it("opens following, or released when the reader left the conversation away from its end", () => {
+ expect(initialTranscriptFollow(true)).toBe(FOLLOWING);
+ expect(initialTranscriptFollow(false)).toEqual({ mode: "released", atEnd: false });
+ });
+
+ it("lets go when the reader navigates, and comes back only after leaving the end and returning", () => {
+ const released = run(FOLLOWING, "navigated");
+ expect(released).toEqual({ mode: "released", atEnd: true });
+ expect(run(released, "reachedEnd"), "a scroll key at the end cannot re-arm").toBe(released);
+ expect(run(released, "leftEnd")).toEqual({ mode: "released", atEnd: false });
+ expect(run(released, "leftEnd", "reachedEnd")).toBe(FOLLOWING);
+ });
+
+ it("ignores the end band flickering while it follows a growing reply", () => {
+ expect(run(FOLLOWING, "leftEnd", "reachedEnd", "leftEnd")).toBe(FOLLOWING);
+ });
+
+ it("follows again whenever the person asks for the end: a sent message or the latest button", () => {
+ expect(run(FOLLOWING, "navigated", "leftEnd", "followEnd")).toBe(FOLLOWING);
+ });
+
+ it("offers the way down only once the reader is released away from the end", () => {
+ expect(wantsJumpToLatest(FOLLOWING)).toBe(false);
+ expect(wantsJumpToLatest(run(FOLLOWING, "navigated"))).toBe(false);
+ expect(wantsJumpToLatest(run(FOLLOWING, "navigated", "leftEnd"))).toBe(true);
+ });
+});
+
+describe("remembered positions", () => {
+ it("keeps each conversation's own, the newest hundred", () => {
+ rememberTranscriptPosition("a", { atEnd: false, rowId: "m3", offsetWithinRow: 12 });
+ rememberTranscriptPosition("b", { atEnd: true });
+ expect(readTranscriptPosition("a")).toEqual({ atEnd: false, rowId: "m3", offsetWithinRow: 12 });
+ expect(readTranscriptPosition("b")).toEqual({ atEnd: true });
+ for (let index = 0; index < 100; index++) rememberTranscriptPosition(`k${index}`, { atEnd: true });
+ expect(readTranscriptPosition("a")).toBeUndefined();
+ expect(readTranscriptPosition("k99")).toEqual({ atEnd: true });
+ });
+});
diff --git a/src/lib/transcript-follow.ts b/src/lib/transcript-follow.ts
new file mode 100644
index 0000000000..86af12b066
--- /dev/null
+++ b/src/lib/transcript-follow.ts
@@ -0,0 +1,128 @@
+/**
+ * Whether the transcript keeps its live end in view. `atEnd` only matters once released: while following, the
+ * transcript is at its end by definition.
+ */
+export type TranscriptFollow =
+ | { readonly mode: "following" }
+ | { readonly mode: "released"; readonly atEnd: boolean };
+
+export type TranscriptFollowEvent =
+ /** The person moved the transcript away from where it follows: a scroll up, a scroll key, a scrollbar grab. */
+ | { readonly type: "navigated" }
+ /** The person asked for the end: they sent a message, pressed "latest", or pulled down at the end. */
+ | { readonly type: "followEnd" }
+ | { readonly type: "reachedEnd" }
+ | { readonly type: "leftEnd" };
+
+export const FOLLOWING: TranscriptFollow = { mode: "following" };
+
+export function initialTranscriptFollow(followEnd: boolean): TranscriptFollow {
+ return followEnd ? FOLLOWING : { mode: "released", atEnd: false };
+}
+
+export function transitionTranscriptFollow(state: TranscriptFollow, event: TranscriptFollowEvent): TranscriptFollow {
+ switch (event.type) {
+ case "navigated":
+ return state.mode === "released" ? state : { mode: "released", atEnd: true };
+ case "followEnd":
+ return FOLLOWING;
+ case "reachedEnd":
+ // A scroll key pressed at the end stays released until the transcript has left the end and come back.
+ return state.mode === "released" && !state.atEnd ? FOLLOWING : state;
+ case "leftEnd":
+ // While following, every streamed chunk leaves the end band for a frame before the follow scroll catches up.
+ return state.mode === "released" && state.atEnd ? { mode: "released", atEnd: false } : state;
+ }
+}
+
+/** The "latest" button shows once the reader has left the end; it waits a moment so a switch or a settle never flashes it. */
+export const JUMP_TO_LATEST_DELAY_MS = 150;
+
+export function wantsJumpToLatest(state: TranscriptFollow): boolean {
+ return state.mode === "released" && !state.atEnd;
+}
+
+/** Where the reader left a conversation: the row at the top of the view and how far it was scrolled past, or the end. */
+export interface RememberedTranscriptPosition {
+ readonly atEnd: boolean;
+ readonly rowId?: string;
+ readonly offsetWithinRow?: number;
+ readonly windowStart?: number;
+ readonly windowEnd?: number | null;
+}
+
+const MAX_REMEMBERED = 100;
+const remembered = new Map<string, RememberedTranscriptPosition>();
+
+export function readTranscriptPosition(key: string): RememberedTranscriptPosition | undefined {
+ return remembered.get(key);
+}
+
+export function rememberTranscriptPosition(key: string, position: RememberedTranscriptPosition): void {
+ remembered.delete(key);
+ remembered.set(key, position);
+ if (remembered.size > MAX_REMEMBERED) remembered.delete(remembered.keys().next().value!);
+}
+
+/** Tests only. */
+export function forgetTranscriptPositions(): void {
+ remembered.clear();
+}
+
+/** A row's box: transcript rows are `display: contents`, so their own box is empty and their content's is used. */
+function rowBox(row: Element): { top: number; bottom: number } {
+ const own = row.getBoundingClientRect();
+ if (own.height > 0 || typeof document === "undefined" || typeof document.createRange !== "function") return own;
+ const range = document.createRange();
+ range.selectNodeContents(row);
+ return range.getBoundingClientRect();
+}
+
+const ROW_SELECTOR = "[data-mid]";
+
+/** The first saved row at the top of the view, and how far above the view's top its own top lies. */
+export function topRow(scroller: HTMLElement, transcript: HTMLElement): { rowId: string; offsetWithinRow: number } | null {
+ if (typeof transcript.querySelectorAll !== "function") return null;
+ const top = scroller.getBoundingClientRect().top;
+ for (const row of Array.from(transcript.querySelectorAll<HTMLElement>(ROW_SELECTOR))) {
+ const rowId = row.dataset.mid;
+ if (!rowId || rowId.startsWith("live:")) continue;
+ const box = rowBox(row);
+ if (box.bottom > top) return { rowId, offsetWithinRow: top - box.top };
+ }
+ return null;
+}
+
+/** The scrollTop that puts `rowId` back where `topRow` found it, or undefined when the row is not drawn. */
+export function rowScrollTop(scroller: HTMLElement, transcript: HTMLElement, rowId: string, offsetWithinRow: number): number | undefined {
+ if (typeof transcript.querySelectorAll !== "function") return undefined;
+ const row = Array.from(transcript.querySelectorAll<HTMLElement>(ROW_SELECTOR)).find((candidate) => candidate.dataset.mid === rowId);
+ if (!row) return undefined;
+ const target = scroller.scrollTop + rowBox(row).top - scroller.getBoundingClientRect().top + offsetWithinRow;
+ return Math.max(0, Math.min(target, scroller.scrollHeight - scroller.clientHeight));
+}
+
+// A streaming reply moves the end every frame, so the target may never hold still: past this many frames, follow's own
+// growth handling takes over.
+const SETTLE_MAX_FRAMES = 60;
+
+/**
+ * Layout after a switch is not final in the first frame (code colouring, images, fonts), so a restored position is
+ * corrected against the DOM until it holds for two frames, the frame budget runs out, or the caller cancels.
+ */
+export function settleScroll(scroller: HTMLElement, target: () => number | undefined, cancelled: () => boolean): void {
+ let stableFrames = 0;
+ let frames = 0;
+ const reconcile = () => {
+ if (cancelled()) return;
+ const offset = target();
+ frames += 1;
+ if (offset === undefined || frames > SETTLE_MAX_FRAMES) return;
+ if (Math.abs(scroller.scrollTop - offset) > 1) {
+ stableFrames = 0;
+ scroller.scrollTop = offset;
+ } else if (++stableFrames >= 2) return;
+ requestAnimationFrame(reconcile);
+ };
+ requestAnimationFrame(reconcile);
+}
diff --git a/src/state/live-reply.test.ts b/src/state/live-reply.test.ts
new file mode 100644
index 0000000000..f00b8de6ee
--- /dev/null
+++ b/src/state/live-reply.test.ts
@@ -0,0 +1,322 @@
+import { afterEach, describe, expect, it } from "vitest";
+
+import type { RuntimeEvent } from "../../shared/runtime-events";
+import {
+ forgetLiveReplies,
+ hasLiveReply,
+ liveReplies,
+ liveReplyRows,
+ liveReplyText,
+ noteLiveReplyEvent,
+ noteLiveReplyMessage,
+ resetLiveReplies,
+ roomLiveSpeaker,
+ settleLiveReplies,
+ stopLiveReply,
+ streamedReply,
+ withLiveRows,
+} from "./live-reply";
+import type { Message } from "@/state/store";
+
+let seq = 0;
+const frame = (event: Partial<RuntimeEvent>, threadId = "t"): RuntimeEvent =>
+ ({ eventId: `e${++seq}`, provider: "claudeAgent", threadId, createdAt: "2026-11-11T12:00:00.000Z", turnId: "turn-1", ...event } as RuntimeEvent);
+const note = (event: Partial<RuntimeEvent>, threadId = "t") => {
+ const sent = frame(event, threadId);
+ noteLiveReplyEvent(sent);
+ return sent;
+};
+const delta = (text: string, threadId = "t", extra: Partial<RuntimeEvent> = {}) =>
+ note({ type: "content.delta", streamKind: "assistant_text", delta: text, ...extra } as Partial<RuntimeEvent>, threadId);
+const complete = (text: string, threadId = "t") =>
+ note({ type: "item.completed", itemType: "assistant_text", text } as Partial<RuntimeEvent>, threadId);
+const shown = (threadId = "t", transcript: { id: string }[] = []) =>
+ liveReplyRows(liveReplies(threadId), transcript).rows.map((row) => row.text);
+
+afterEach(() => resetLiveReplies());
+
+// Frames with no item id are what a server older than item ids sends (a Cloud not yet updated).
+describe("a reply as it streams from an older server", () => {
+ it("grows with each delta of the bot's words, and leaves reasoning out", () => {
+ note({ type: "turn.started" });
+ delta("Here is ");
+ note({ type: "content.delta", streamKind: "reasoning_text", delta: "thinking hard" } as Partial<RuntimeEvent>);
+ delta("the plan for ");
+ expect(shown()).toEqual(["Here is the plan for "]);
+ delta("today.");
+ expect(liveReplies("t")).toHaveLength(1);
+ expect(liveReplies("t")[0]!.text).toBe("Here is the plan for today.");
+ expect(shown(), "the unfinished last word waits").toEqual(["Here is the plan for "]);
+ });
+
+ it("keeps each thread's reply its own", () => {
+ delta("one ", "a");
+ delta("two ", "b");
+ expect(shown("a")).toEqual(["one "]);
+ expect(shown("b")).toEqual(["two "]);
+ expect(shown("c")).toEqual([]);
+ });
+
+ it("stays drawn after the engine finishes until the transcript holds its saved message, then gives way", () => {
+ delta("All done ");
+ complete("All done here.");
+ expect(shown(), "finished: the whole text").toEqual(["All done here."]);
+ noteLiveReplyMessage("t", { id: "m1", role: "bot", kind: "text", turnId: "turn-1" });
+ expect(liveReplies("t")[0]!.savedAs).toBe("m1");
+ expect(shown("t", []), "the frame arrived but the transcript has not drawn it yet").toEqual(["All done here."]);
+ const { rows, settled } = liveReplyRows(liveReplies("t"), [{ id: "m1" }]);
+ expect(rows, "never both at once").toEqual([]);
+ settleLiveReplies("t", settled);
+ expect(liveReplies("t")).toEqual([]);
+ expect(streamedReply("m1"), "the saved bubble does not play in again").toBe(true);
+ expect(streamedReply("m2")).toBe(false);
+ });
+
+ it("holds a finished item while the next one streams, each swapped by its own message", () => {
+ delta("First part. ");
+ complete("First part.");
+ noteLiveReplyMessage("t", { id: "m1", role: "bot", kind: "text", turnId: "turn-1" });
+ note({ type: "item.started", itemType: "tool", itemId: "x", title: "Bash" } as Partial<RuntimeEvent>);
+ delta("Second part ");
+ expect(shown()).toEqual(["First part.", "Second part "]);
+ expect(shown("t", [{ id: "m1" }])).toEqual(["Second part "]);
+ });
+
+ it("ignores a frame it has already seen, so a resumed stream never doubles the text", () => {
+ const first = delta("Hello ");
+ const second = delta("there ");
+ noteLiveReplyEvent(first);
+ noteLiveReplyEvent(second);
+ expect(liveReplies("t")[0]!.text).toBe("Hello there ");
+ const done = complete("Hello there");
+ noteLiveReplyMessage("t", { id: "m1", role: "bot", kind: "text", turnId: "turn-1" });
+ noteLiveReplyEvent(done);
+ noteLiveReplyMessage("t", { id: "m1", role: "bot", kind: "text", turnId: "turn-1" });
+ expect(liveReplies("t")).toHaveLength(1);
+ expect(liveReplies("t")[0]!.savedAs).toBe("m1");
+ });
+
+ it("drops a reply that never got saved when the turn ends, fails or is stopped", () => {
+ delta("Partial answer ");
+ note({ type: "turn.completed", ok: false } as Partial<RuntimeEvent>);
+ expect(liveReplies("t")).toEqual([]);
+
+ delta("Another try ");
+ note({ type: "runtime.error", message: "boom", terminal: true } as Partial<RuntimeEvent>);
+ expect(liveReplies("t")).toEqual([]);
+
+ delta("A third ");
+ note({ type: "runtime.error", message: "a warning" } as Partial<RuntimeEvent>);
+ expect(shown(), "a passing warning is no end").toEqual(["A third "]);
+
+ stopLiveReply("t");
+ expect(shown(), "what streamed before Stop stays, as an engine may keep it").toEqual(["A third "]);
+ delta("late words ");
+ expect(shown(), "the rest of a stopped item is not drawn").toEqual(["A third "]);
+ note({ type: "turn.completed", ok: false } as Partial<RuntimeEvent>);
+ expect(liveReplies("t"), "not kept: the turn's end removes it").toEqual([]);
+ note({ type: "turn.started" });
+ delta("Fresh ");
+ expect(shown()).toEqual(["Fresh "]);
+ });
+
+ it("keeps a saved item through the turn's end until the transcript draws it", () => {
+ delta("Answer ");
+ complete("Answer");
+ noteLiveReplyMessage("t", { id: "m1", role: "bot", kind: "text", turnId: "turn-1" });
+ note({ type: "turn.completed", ok: true } as Partial<RuntimeEvent>);
+ expect(shown()).toEqual(["Answer"]);
+ });
+
+ it("drops a finished item the server never saved (a hidden or stopped reply) at the turn's end", () => {
+ delta("Request was aborted ");
+ complete("The request was aborted.");
+ note({ type: "turn.completed", ok: false } as Partial<RuntimeEvent>);
+ expect(liveReplies("t")).toEqual([]);
+ });
+
+ it("after a gap in the stream, draws nothing until the next item starts clean", () => {
+ delta("Before the gap ");
+ forgetLiveReplies();
+ expect(liveReplies("t")).toEqual([]);
+ delta("tail of the item ");
+ delta("other thread ", "u");
+ expect(shown()).toEqual([]);
+ expect(shown("u")).toEqual([]);
+ complete("Before the gap tail of the item");
+ delta("Next item ");
+ expect(shown()).toEqual(["Next item "]);
+ });
+
+ it("masks a secret the way the saved message will, and never shows a half-typed one", () => {
+ delta("Your key is sk-ant-api03-");
+ expect(shown()).toEqual(["Your key is "]);
+ delta("abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJ done.");
+ expect(shown()[0]).not.toContain("abcdefghijklmnopqrstuvwxyz");
+ expect(liveReplyText({ text: "plain words", done: false })).toBe("plain ");
+ });
+
+ it("draws nothing for a client abort sentence", () => {
+ delta("The request was cancelled by the client.");
+ complete("The request was cancelled by the client.");
+ expect(shown()).toEqual([]);
+ expect(hasLiveReply("t")).toBe(false);
+ });
+
+ it("names a room's speaker on the live row, as the saved message will", () => {
+ delta("Room words ", "room");
+ const from = { botId: "b1", name: "Pepper", color: "green" as const };
+ const [row] = liveReplyRows(liveReplies("room"), [], roomLiveSpeaker([{ id: "b1", ...from, color: "green" }], "b1")).rows;
+ expect(row).toMatchObject({ role: "bot", kind: "text", from, turnId: "turn-1" });
+ expect(row!.id.startsWith("live:")).toBe(true);
+ });
+
+ it("names the member the server says is speaking, whoever the room shows as busy", () => {
+ const members = [{ id: "b1", name: "Pepper", color: "green" as const }, { id: "b2", name: "Basil", color: "blue" as const }];
+ delta("Pepper speaks ", "room", { botId: "b1", itemId: "p" } as Partial<RuntimeEvent>);
+ note({ type: "item.completed", itemType: "assistant_text", text: "Pepper speaks.", itemId: "p" } as Partial<RuntimeEvent>, "room");
+ delta("Basil answers ", "room", { botId: "b2", itemId: "q" } as Partial<RuntimeEvent>);
+ for (const busy of ["b2", null, undefined]) {
+ const rows = liveReplyRows(liveReplies("room"), [], roomLiveSpeaker(members, busy)).rows;
+ expect(rows.map((row) => row.from?.name), `room busy with ${busy}`).toEqual(["Pepper", "Basil"]);
+ }
+ delta("Older server ", "u");
+ expect(liveReplyRows(liveReplies("u"), [], roomLiveSpeaker(members, "b2")).rows[0]!.from?.name, "an older server names no one: the busy member").toBe("Basil");
+ expect(liveReplyRows(liveReplies("u"), [], roomLiveSpeaker(members, null)).rows[0]!.from).toBeUndefined();
+ });
+});
+
+describe("a reply keyed by the id the server streams it under", () => {
+ const said = (text: string, itemId: string) => delta(text, "t", { itemId } as Partial<RuntimeEvent>);
+ const finished = (text: string, itemId: string) =>
+ note({ type: "item.completed", itemType: "assistant_text", text, itemId } as Partial<RuntimeEvent>);
+ const saved = (id: string, itemId: string) => noteLiveReplyMessage("t", { id, role: "bot", kind: "text", turnId: "turn-1", itemId });
+ const tool = (itemId: string) => {
+ note({ type: "item.started", itemType: "tool", itemId, title: "ls -la" } as Partial<RuntimeEvent>);
+ note({ type: "item.completed", itemType: "tool", itemId, ok: true } as Partial<RuntimeEvent>);
+ };
+ const rows = (transcript: { id: string; itemId?: string }[] = []) => liveReplyRows(liveReplies("t"), transcript).rows.map((row) => row.text);
+
+ it("keeps text, tool, text, tool, text as three messages: never glued, doubled, lost or left behind", () => {
+ note({ type: "turn.started" });
+ said("Checking the ", "a");
+ said("folder first. ", "a");
+ expect(rows()).toEqual(["Checking the folder first. "]);
+ finished("Checking the folder first.", "a");
+ saved("m1", "a");
+ tool("c1");
+ said("Found three ", "b");
+ expect(rows(), "the first is saved but not drawn yet").toEqual(["Checking the folder first.", "Found three "]);
+ expect(rows([{ id: "m1", itemId: "a" }]), "drawn: only the new message streams").toEqual(["Found three "]);
+ said("files. ", "b");
+ finished("Found three files.", "b");
+ saved("m2", "b");
+ tool("c2");
+ said("Done.", "c");
+ finished("Done.", "c");
+ saved("m3", "c");
+ note({ type: "turn.completed", ok: true } as Partial<RuntimeEvent>);
+ const transcript = [{ id: "m1", itemId: "a" }, { id: "m2", itemId: "b" }, { id: "m3", itemId: "c" }];
+ const drawn = liveReplyRows(liveReplies("t"), transcript);
+ expect(drawn.rows).toEqual([]);
+ settleLiveReplies("t", drawn.settled);
+ expect(liveReplies("t"), "nothing stale once the saved messages land").toEqual([]);
+ });
+
+ it("swaps by id even when the message frame never reached the store, as after a reload", () => {
+ said("Answer ", "a");
+ finished("Answer.", "a");
+ expect(rows([{ id: "m9", itemId: "a" }])).toEqual([]);
+ expect(rows([{ id: "m9", itemId: "other" }])).toEqual(["Answer."]);
+ });
+
+ it("keeps two messages in a row apart when no tool runs between them", () => {
+ said("First thought. ", "a");
+ finished("First thought.", "a");
+ said("Second thought ", "b");
+ expect(rows()).toEqual(["First thought.", "Second thought "]);
+ });
+
+ it("drops a message the server closed without finishing when its next one starts", () => {
+ said("Half a ", "a");
+ tool("c1");
+ said("Result ", "b");
+ expect(rows()).toEqual(["Result "]);
+ });
+
+ it("ignores a frame it has already seen, and a word for a message that already finished", () => {
+ const first = said("Hello ", "a");
+ noteLiveReplyEvent(first);
+ finished("Hello there.", "a");
+ said("late ", "a");
+ expect(rows()).toEqual(["Hello there."]);
+ });
+
+ it("does not take an older server's message for a message that streamed under an id", () => {
+ said("Keyed ", "a");
+ finished("Keyed.", "a");
+ noteLiveReplyMessage("t", { id: "old", role: "bot", kind: "text", turnId: "turn-1" });
+ expect(liveReplies("t")[0]!.savedAs).toBeUndefined();
+ saved("m1", "a");
+ expect(liveReplies("t")[0]!.savedAs).toBe("m1");
+ expect(streamedReply("m1")).toBe(true);
+ });
+
+ it("drops a finished message the server never saved when the turn ends", () => {
+ said("<SYSTEM_NOTE>internal ", "a");
+ finished("<SYSTEM_NOTE>internal</SYSTEM_NOTE>", "a");
+ note({ type: "turn.completed", ok: true } as Partial<RuntimeEvent>);
+ expect(liveReplies("t")).toEqual([]);
+ });
+});
+
+describe("a thread nobody has on screen", () => {
+ const reply = (id: string, turnId: string, text: string): Message =>
+ ({ id, role: "bot", kind: "text", at: 0, text, turnId, itemId: `${turnId}:x` }) as Message;
+
+ it("keeps nothing stale across 30 turns, and opening it with a small window draws none of them again", () => {
+ const transcript: Message[] = [];
+ for (let turn = 1; turn <= 30; turn++) {
+ const turnId = `turn-${turn}`, itemId = `${turnId}:x`, text = `Reply number ${turn}.`;
+ note({ type: "turn.started", turnId }, "bg");
+ delta("Reply number ", "bg", { turnId, itemId } as Partial<RuntimeEvent>);
+ note({ type: "item.completed", itemType: "assistant_text", text, turnId, itemId } as Partial<RuntimeEvent>, "bg");
+ const saved = reply(`m${turn}`, turnId, text);
+ noteLiveReplyMessage("bg", saved);
+ note({ type: "turn.completed", ok: true, turnId } as Partial<RuntimeEvent>, "bg");
+ transcript.push({ id: `ask${turn}`, role: "user", kind: "text", at: 0, text: "again" } as Message, saved);
+ }
+ expect(liveReplies("bg").length, "only the last turn's saved item waits for its transcript").toBeLessThanOrEqual(1);
+ const windowed = transcript.slice(-1);
+ const opened = withLiveRows(liveReplies("bg"), windowed, transcript);
+ expect(opened.rows, "nothing drawn after the newest message").toEqual(windowed);
+ settleLiveReplies("bg", opened.settled);
+ expect(liveReplies("bg")).toEqual([]);
+ });
+
+ it("matches a saved item against the whole transcript, not the rows a window shows", () => {
+ delta("Old answer ", "t", { itemId: "a" } as Partial<RuntimeEvent>);
+ note({ type: "item.completed", itemType: "assistant_text", text: "Old answer.", itemId: "a" } as Partial<RuntimeEvent>);
+ noteLiveReplyMessage("t", { id: "m1", role: "bot", kind: "text", turnId: "turn-1", itemId: "a" });
+ const transcript = [reply("m1", "turn-1", "Old answer."), { id: "later", role: "user", kind: "text", at: 0, text: "next" } as Message];
+ const { rows, settled } = withLiveRows(liveReplies("t"), transcript.slice(1), transcript);
+ expect(rows.map((row) => row.id)).toEqual(["later"]);
+ expect(settled).toHaveLength(1);
+ });
+
+ it("draws a streaming reply only under the newest message, never under a window scrolled back or opened at an old one", () => {
+ const transcript = [reply("m1", "turn-0", "Old."), { id: "ask", role: "user", kind: "text", at: 0, text: "Now?" } as Message];
+ delta("Streaming now ");
+ expect(withLiveRows(liveReplies("t"), transcript.slice(0, 1), transcript).rows.map((row) => row.id)).toEqual(["m1"]);
+ expect(withLiveRows(liveReplies("t"), transcript, transcript).rows.map((row) => row.text)).toEqual(["Old.", "Now?", "Streaming now "]);
+ });
+
+ it("holds a bounded number of items per thread whatever arrives", () => {
+ for (let n = 0; n < 100; n++) {
+ delta(`Item ${n} `, "t", { itemId: `i${n}` } as Partial<RuntimeEvent>);
+ note({ type: "item.completed", itemType: "assistant_text", text: `Item ${n}.`, itemId: `i${n}` } as Partial<RuntimeEvent>);
+ }
+ expect(liveReplies("t").length).toBeLessThanOrEqual(32);
+ expect(liveReplies("t").at(-1)!.text).toBe("Item 99.");
+ });
+});
diff --git a/src/state/live-reply.ts b/src/state/live-reply.ts
new file mode 100644
index 0000000000..50d7943e86
--- /dev/null
+++ b/src/state/live-reply.ts
@@ -0,0 +1,284 @@
+// A bot's reply as it streams: each thread's assistant text deltas, keyed by the message id the server streams them
+// under and held outside the app reducer, so a delta re-renders only the transcript that shows that thread. A streamed
+// item stays drawn until the transcript holds the message saved under the same id, so the saved bubble replaces it in
+// the same commit.
+import { createContext, useEffect, useMemo, useSyncExternalStore } from "react";
+
+import type { RuntimeEvent } from "../../shared/runtime-events";
+import { isClientCancellation } from "../../shared/client-cancel";
+import { redactSecretsInText } from "../../shared/redact";
+import type { Message } from "@/state/store";
+
+export interface LiveReplyItem {
+ key: string;
+ /** The message id the server streamed it under; absent from a server older than item ids. */
+ itemId?: string;
+ turnId?: string;
+ /** A room reply: the member whose words these are. */
+ botId?: string;
+ text: string;
+ at: number;
+ /** The engine finished the item; its saved message is on its way. */
+ done: boolean;
+ /** The message the server saved the item as. */
+ savedAs?: string;
+}
+
+interface ThreadReplies {
+ items: readonly LiveReplyItem[];
+ /** Deltas were missed (a stream gap or a Stop): later ones of the same item would draw a reply without its start. */
+ skipping: boolean;
+}
+
+/** True around a reply still streaming in: its actions wait for it to finish. */
+export const StreamingReplyContext = createContext(false);
+
+const LIVE_ID = "live:";
+const MAX_THREADS = 200;
+const MAX_SEEN_EVENTS = 4096;
+const MAX_STREAMED = 500;
+/** A backstop: a thread nobody has on screen settles nothing, and a turn's start already drops the turns before it. */
+const MAX_ITEMS = 32;
+const EMPTY: readonly LiveReplyItem[] = [];
+const threads = new Map<string, ThreadReplies>();
+const listeners = new Map<string, Set<() => void>>();
+const seenEvents = new Set<string>();
+const streamed = new Set<string>();
+/** Set when the stream restarted without the frames it missed; a thread then draws deltas only after its next item or
+ * turn boundary, since any item open across the gap lost its start. */
+let gapped = false;
+const boundarySinceGap = new Set<string>();
+
+function put(threadId: string, next: ThreadReplies): void {
+ const current = threads.get(threadId);
+ if (current && current.items === next.items && current.skipping === next.skipping) return;
+ if (next.items.length > MAX_ITEMS) next = { ...next, items: next.items.slice(-MAX_ITEMS) };
+ threads.delete(threadId);
+ if (next.items.length || next.skipping) threads.set(threadId, next);
+ if (threads.size > MAX_THREADS) threads.delete(threads.keys().next().value!);
+ if ((current?.items ?? EMPTY) === next.items) return;
+ for (const listener of Array.from(listeners.get(threadId) ?? [])) listener();
+}
+
+function firstSeen(eventId: string): boolean {
+ if (seenEvents.has(eventId)) return false;
+ seenEvents.add(eventId);
+ if (seenEvents.size > MAX_SEEN_EVENTS) seenEvents.delete(seenEvents.values().next().value!);
+ return true;
+}
+
+const isSaved = (item: LiveReplyItem) => item.savedAs !== undefined;
+const sameTurn = (item: LiveReplyItem, turnId: string | undefined) => !turnId || !item.turnId || item.turnId === turnId;
+const kept = (items: readonly LiveReplyItem[], keep: (item: LiveReplyItem) => boolean) => {
+ const next = items.filter(keep);
+ return next.length === items.length ? items : next;
+};
+const isTurnEnd = (event: RuntimeEvent) =>
+ event.type === "turn.completed" || event.type === "cap.exhausted" || event.type === "session.exited" ||
+ (event.type === "runtime.error" && event.terminal === true);
+
+/** One live runtime frame. A frame seen before (a resumed stream replaying it) changes nothing. */
+export function noteLiveReplyEvent(event: RuntimeEvent): void {
+ const { threadId } = event;
+ const current = threads.get(threadId) ?? { items: EMPTY, skipping: false };
+ const { items } = current;
+ if (event.type === "content.delta") {
+ if (event.streamKind !== "assistant_text" || !event.delta || !firstSeen(event.eventId) || current.skipping) return;
+ if (gapped && !boundarySinceGap.has(threadId)) return;
+ const at = event.itemId ? items.findIndex((item) => item.itemId === event.itemId) : legacyOpen(items, event.turnId);
+ const growing = items[at];
+ if (growing) {
+ if (!growing.done) put(threadId, { ...current, items: items.map((item, index) => index === at ? { ...item, text: item.text + event.delta, ...(event.botId ? { botId: event.botId } : {}) } : item) });
+ return;
+ }
+ // The server opens a message only once the one before it is over: an earlier one still open never completes.
+ const fresh: LiveReplyItem = { key: event.itemId ?? event.eventId, ...(event.itemId ? { itemId: event.itemId } : {}),
+ ...(event.turnId ? { turnId: event.turnId } : {}), ...(event.botId ? { botId: event.botId } : {}), text: event.delta, at: Date.now(), done: false };
+ put(threadId, { ...current, items: [...kept(items, (item) => item.done), fresh] });
+ } else if (event.type === "item.completed" && event.itemType === "assistant_text") {
+ if (!firstSeen(event.eventId)) return;
+ if (gapped) boundarySinceGap.add(threadId);
+ const at = event.itemId ? items.findIndex((item) => item.itemId === event.itemId) : legacyOpen(items, event.turnId);
+ const next = at >= 0 && !items[at]!.done ? items.map((item, index) => index === at ? { ...item, text: event.text, done: true } : item) : items;
+ put(threadId, { items: next, skipping: false });
+ } else if (event.type === "item.started" && event.itemType === "tool") {
+ if (gapped) boundarySinceGap.add(threadId);
+ } else if (event.type === "turn.started") {
+ if (gapped) boundarySinceGap.add(threadId);
+ // The turns before this one are over: their saved messages are in the thread's transcript by now, drawn or not.
+ put(threadId, { items: kept(items, (item) => isSaved(item) && event.turnId !== undefined && item.turnId === event.turnId), skipping: false });
+ } else if (isTurnEnd(event)) {
+ if (gapped) boundarySinceGap.add(threadId);
+ put(threadId, { items: kept(items, isSaved), skipping: false });
+ }
+}
+
+/** A server older than item ids sends none: its words build the last open item of the turn until one completes. */
+function legacyOpen(items: readonly LiveReplyItem[], turnId: string | undefined): number {
+ const last = items.length - 1;
+ const open = items[last];
+ return open && !open.itemId && !open.done && sameTurn(open, turnId) ? last : -1;
+}
+
+/** A message frame: the reply saved from the item that streamed under its `itemId` (or, from an older server, the
+ * first finished item of its turn) is now that message. */
+export function noteLiveReplyMessage(threadId: string, message: (Pick<Message, "id" | "role" | "kind" | "turnId"> & { itemId?: string }) | undefined): void {
+ if (!message || message.role !== "bot" || message.kind !== "text") return;
+ const current = threads.get(threadId);
+ if (!current || current.items.some((item) => item.savedAs === message.id)) return;
+ const index = message.itemId
+ ? current.items.findIndex((item) => item.itemId === message.itemId)
+ : current.items.findIndex((item) => !item.itemId && item.done && item.savedAs === undefined && sameTurn(item, message.turnId));
+ if (index < 0) return;
+ streamed.add(message.id);
+ if (streamed.size > MAX_STREAMED) streamed.delete(streamed.values().next().value!);
+ const items = current.items.map((item, at) => at === index ? { ...item, savedAs: message.id } : item);
+ put(threadId, { ...current, items });
+}
+
+/** The person pressed Stop: what streamed so far stays as it is and grows no more. An engine that keeps the words a
+ * Stop cut short completes the item and its saved message takes its place; otherwise the turn's end removes it. */
+export function stopLiveReply(threadId: string): void {
+ put(threadId, { items: threads.get(threadId)?.items ?? EMPTY, skipping: true });
+}
+
+/** The live stream restarted without the frames it missed: no thread's open item can be completed from here. */
+export function forgetLiveReplies(): void {
+ gapped = true;
+ boundarySinceGap.clear();
+ for (const [threadId, current] of Array.from(threads)) {
+ put(threadId, { ...current, items: kept(current.items, isSaved) });
+ }
+}
+
+/** Drops the items the transcript now draws as saved messages. */
+export function settleLiveReplies(threadId: string, keys: readonly string[]): void {
+ const current = threads.get(threadId);
+ if (!current || !keys.length) return;
+ put(threadId, { ...current, items: kept(current.items, (item) => !keys.includes(item.key)) });
+}
+
+export function liveReplies(threadId: string | null | undefined): readonly LiveReplyItem[] {
+ return (threadId && threads.get(threadId)?.items) || EMPTY;
+}
+
+/** Whether the thread draws a streamed reply, or one waiting for its saved message to take its place. */
+export function hasLiveReply(threadId: string | null | undefined): boolean {
+ return liveReplies(threadId).some((item) => liveReplyText(item).trim() !== "");
+}
+
+/** A saved message that replaced a streamed bubble: it is already on screen, so it does not play in. */
+export function streamedReply(messageId: string): boolean {
+ return messageId.startsWith(LIVE_ID) || streamed.has(messageId);
+}
+
+export function isLiveReply(message: Pick<Message, "id">): boolean {
+ return message.id.startsWith(LIVE_ID);
+}
+
+/** What a streaming item shows. The last word waits for the space after it, so a secret is masked whole or not shown. */
+export function liveReplyText(item: Pick<LiveReplyItem, "text" | "done">): string {
+ const end = item.done ? item.text.length : Math.max(item.text.lastIndexOf(" "), item.text.lastIndexOf("\n")) + 1;
+ const text = item.text.slice(0, end);
+ return isClientCancellation(text) ? "" : redactSecretsInText(text);
+}
+
+function subscribe(threadId: string | null | undefined, listener: () => void): () => void {
+ if (!threadId) return () => {};
+ let set = listeners.get(threadId);
+ if (!set) listeners.set(threadId, (set = new Set()));
+ set.add(listener);
+ return () => {
+ set.delete(listener);
+ if (set.size === 0) listeners.delete(threadId);
+ };
+}
+
+export function useLiveReplies(threadId: string | null | undefined): readonly LiveReplyItem[] {
+ return useSyncExternalStore(
+ (listener) => subscribe(threadId, listener),
+ () => liveReplies(threadId),
+ () => EMPTY,
+ );
+}
+
+export function useHasLiveReply(threadId: string | null | undefined): boolean {
+ return useSyncExternalStore(
+ (listener) => subscribe(threadId, listener),
+ () => hasLiveReply(threadId),
+ () => false,
+ );
+}
+
+const rowCache = new WeakMap<LiveReplyItem, { text: string; message: Message }>();
+const sameSpeaker = (a: Message["from"], b: Message["from"]) =>
+ a === b || (a !== undefined && b !== undefined && a.botId === b.botId && a.name === b.name && a.color === b.color);
+
+/** Who a room's live row names: the member the server says speaks it, else (a server that does not say) `speakingNow`. */
+export type LiveSpeaker = (botId: string | undefined) => Message["from"] | undefined;
+type RoomMember = { id: string; name: string; color: NonNullable<Message["from"]>["color"] };
+
+/** The speaker resolver for a room's members; one per members list and current speaker, so rows keep their identity. */
+export function roomLiveSpeaker(members: readonly RoomMember[], speakingNow?: string | null): LiveSpeaker {
+ return (botId) => {
+ const member = members.find((bot) => bot.id === (botId ?? speakingNow));
+ return member ? { botId: member.id, name: member.name, color: member.color } : undefined;
+ };
+}
+
+/** The transcript rows the live items draw, after `transcript`'s own: an item whose saved message `transcript` holds
+ * draws nothing, so the two never show together. */
+export function liveReplyRows(items: readonly LiveReplyItem[], transcript: readonly (Pick<Message, "id"> & { itemId?: string })[], speaker?: LiveSpeaker): { rows: Message[]; settled: string[] } {
+ const rows: Message[] = [];
+ const settled: string[] = [];
+ const ids = new Set<string>(), itemIds = new Set<string>();
+ for (const message of transcript) {
+ ids.add(message.id);
+ if (message.itemId !== undefined) itemIds.add(message.itemId);
+ }
+ for (const item of items) {
+ if ((item.itemId !== undefined && itemIds.has(item.itemId)) || (item.savedAs !== undefined && ids.has(item.savedAs))) {
+ settled.push(item.key);
+ continue;
+ }
+ const text = liveReplyText(item);
+ if (!text.trim()) continue;
+ const from = speaker?.(item.botId);
+ let row = rowCache.get(item);
+ if (!row || row.text !== text || !sameSpeaker(row.message.from, from)) {
+ row = { text, message: { id: `${LIVE_ID}${item.key}`, role: "bot", kind: "text", text, at: item.at, ...(item.turnId ? { turnId: item.turnId } : {}), ...(from ? { from } : {}) } as Message };
+ rowCache.set(item, row);
+ }
+ rows.push(row.message);
+ }
+ return { rows, settled };
+}
+
+/** The rows a transcript window draws: `windowed` (a slice of the whole `transcript`), then the live items. An item is
+ * matched against the whole transcript, so one saved outside the window is not drawn again; and live rows follow the
+ * newest message, so a window that stops short of it (scrolled back, or opened at a found or pinned message) draws none. */
+export function withLiveRows(items: readonly LiveReplyItem[], windowed: Message[], transcript: readonly Message[], speaker?: LiveSpeaker): { rows: Message[]; settled: string[] } {
+ if (!items.length) return { rows: windowed, settled: [] };
+ const drawn = liveReplyRows(items, transcript, speaker);
+ const atEnd = windowed.at(-1)?.id === transcript.at(-1)?.id;
+ return { rows: atEnd && drawn.rows.length ? [...windowed, ...drawn.rows] : windowed, settled: drawn.settled };
+}
+
+/** The `windowed` rows of `transcript` with the thread's streaming reply after them; in a room, each live row names its
+ * speaker from `members`. */
+export function useLiveTranscript(threadId: string, windowed: Message[], transcript: readonly Message[], members?: readonly RoomMember[], speakingNow?: string | null): Message[] {
+ const items = useLiveReplies(threadId);
+ const speaker = useMemo(() => members && roomLiveSpeaker(members, speakingNow), [members, speakingNow]);
+ const live = useMemo(() => withLiveRows(items, windowed, transcript, speaker), [items, windowed, transcript, speaker]);
+ useEffect(() => settleLiveReplies(threadId, live.settled), [threadId, live.settled]);
+ return live.rows;
+}
+
+/** Tests only. */
+export function resetLiveReplies(): void {
+ threads.clear();
+ seenEvents.clear();
+ streamed.clear();
+ gapped = false;
+ boundarySinceGap.clear();
+}