Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(ok): render Codex runtime warnings as agent notices (PRD-8394) (#3959)
serafin-garciac54a1458ea7f
diff --git a/.changeset/prd-8394-acp-agent-warning-rendering.md b/.changeset/prd-8394-acp-agent-warning-rendering.mdnew file mode 100644index 000000000..a625c48ac--- /dev/null+++ b/.changeset/prd-8394-acp-agent-warning-rendering.md@@ -0,0 +1,11 @@+---+"@inkeep/open-knowledge": patch+---++Runtime warnings from Codex now read as status instead of as part of the agent's answer. When Codex reports something mid-turn, such as skill descriptions being shortened to fit its context budget or invalid entries being ignored in `config.toml`, that text used to arrive in the transcript as ordinary assistant prose, so it looked like something the agent had said.++Those warnings now get their own inline card at the point in the conversation where they arrived, carrying a "Warning" label, a warning glyph, and a border that stays visible under high contrast and forced colors, so the severity never depends on seeing the amber tint. The wording is the agent runtime's own, left as it was sent, and the answer that follows stays separate.++The card is passive. There is no toast, no banner, no dismiss control, and nothing to retry. It lives in the transcript, so reopening a thread started on this version shows the warning again in its original place. Threads recorded before this version can still show an older warning as ordinary prose, because their transcripts were stored that way. A screen reader hears the opening line of each newly arrived warning once, in the order the warnings arrived, with the full text left on the card, while reopening a past thread stays silent and keyboard focus never moves.++Only the exact warning format of Codex added from the agent registry is treated this way. Everything else renders exactly as it did before, including a reply that happens to begin with the word "Warning", a Codex you configured yourself, and warnings from other agents.diff --git a/packages/app/package.json b/packages/app/package.jsonindex 84e2987d2..8ef0b10fc 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -7,7 +7,8 @@"scripts": {"predev": "turbo run build --filter=@inkeep/open-knowledge-core --filter=@inkeep/open-knowledge-server && sh scripts/i18n-compile-unless-skipped.sh && node scripts/copy-excalidraw-assets.mjs","dev": "vite",- "build": "pnpm run i18n:compile && node scripts/copy-excalidraw-assets.mjs && tsc --noEmit && vite build",+ "build": "pnpm run i18n:compile && node scripts/copy-excalidraw-assets.mjs && tsc --noEmit && vite build && pnpm run check:no-dev-harness",+ "check:no-dev-harness": "node scripts/check-dev-harness-absent.mjs","typecheck": "tsc --noEmit","i18n": "lingui extract --clean && pnpm run i18n:compile","i18n:extract": "lingui extract --clean",diff --git a/packages/app/scripts/check-dev-harness-absent.mjs b/packages/app/scripts/check-dev-harness-absent.mjsnew file mode 100644index 000000000..98a028860--- /dev/null+++ b/packages/app/scripts/check-dev-harness-absent.mjs@@ -0,0 +1,113 @@+#!/usr/bin/env node+/**+ * Production-artifact gate for the DEV-only ACP thread-injection harness.+ *+ * The harness is kept out of shipped code by two independent+ * `import.meta.env.DEV` guards, either of which is enough for the bundler to+ * fold the publish away. That gating lives in source, so it can regress+ * without a single suite going red: every unit, DOM, integration and browser+ * tier runs against source or a dev server, never against an emitted chunk.+ * This reads the emitted `dist/`, which is the bundle a user actually runs —+ * the CLI copies it to `cli/dist/public` and the desktop package ships that as+ * the renderer its packaged window loads. It is the only automatic check that+ * still discriminates once both guards are gone; the sentinel list in+ * `tests/perf/lib/bundle-check.ts` covers the same string but no tier collects+ * it, so it only discriminates when someone runs it by hand.+ *+ * Non-zero on a hit, on a missing build, and on a walk that found nothing to+ * read — an absence check that inspected no bytes is not a pass.+ */++import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { argv, exit, stderr, stdout } from 'node:process';+import { fileURLToPath } from 'node:url';++/**+ * The global the harness publishes itself on. A property name survives+ * minification verbatim, so it is the one part of the module guaranteed to+ * appear in an emitted chunk if any of it leaks. A DOM test pins that the+ * harness still uses this exact name, so a rename cannot leave this scanning+ * for a string nothing writes any more.+ */+export const DEV_HARNESS_SENTINEL = '__acpThreadHarness';++/** Extensions Vite emits code or markup into. Fonts and images cannot carry it. */+const SCANNED_EXTENSIONS = ['.js', '.mjs', '.cjs', '.css', '.html', '.map'];++const APP_ROOT = join(fileURLToPath(import.meta.url), '..', '..');++function parseDistArg() {+ const flag = argv.indexOf('--dist');+ return flag === -1 ? join(APP_ROOT, 'dist') : argv[flag + 1];+}++function listScannableFiles(dir) {+ const found = [];+ const walk = (current) => {+ for (const entry of readdirSync(current, { withFileTypes: true })) {+ const path = join(current, entry.name);+ if (entry.isDirectory()) walk(path);+ else if (SCANNED_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) found.push(path);+ }+ };+ walk(dir);+ return found;+}++function main() {+ const distDir = parseDistArg();+ if (distDir === undefined) {+ stderr.write('check-dev-harness-absent: --dist needs a directory\n');+ return 1;+ }++ let dist;+ try {+ dist = statSync(distDir);+ } catch {+ stderr.write(+ `check-dev-harness-absent: no build at ${distDir}\n` ++ ' This gate reads the emitted artifact, so it cannot run before `pnpm run build`.\n',+ );+ return 1;+ }+ if (!dist.isDirectory()) {+ stderr.write(`check-dev-harness-absent: ${distDir} is not a directory\n`);+ return 1;+ }++ const files = listScannableFiles(distDir);+ if (files.length === 0) {+ stderr.write(+ `check-dev-harness-absent: nothing to scan under ${distDir}\n` ++ ` Expected emitted ${SCANNED_EXTENSIONS.join('/')} assets. A build that emits none, or a\n` ++ ' layout this walk no longer understands, would otherwise report a clean pass.\n',+ );+ return 1;+ }++ const hits = files.filter((path) => readFileSync(path, 'utf8').includes(DEV_HARNESS_SENTINEL));+ if (hits.length > 0) {+ stderr.write(+ `check-dev-harness-absent: '${DEV_HARNESS_SENTINEL}' reached the production build\n` ++ `${hits.map((path) => ` ${path}\n`).join('')}` ++ ' Two `import.meta.env.DEV` guards keep it out, and folding either one is enough\n' ++ ' on its own: the branch around the installer call in\n' ++ ' src/components/acp/AgentThreadClientBinder.tsx, and the early return opening\n' ++ ' installAcpThreadHarness in src/lib/acp/dev-thread-harness.ts. Reaching an\n' ++ ' emitted chunk means neither folded, so check both rather than just the import.\n',+ );+ return 1;+ }++ stdout.write(+ `check-dev-harness-absent: '${DEV_HARNESS_SENTINEL}' absent from ${files.length} assets\n`,+ );+ return 0;+}++// Importers want the sentinel alone; only a direct invocation is the gate.+if (argv[1] !== undefined && resolve(argv[1]) === fileURLToPath(import.meta.url)) {+ exit(main());+}diff --git a/packages/app/src/components/acp/AgentNoticeAnnouncer.tsx b/packages/app/src/components/acp/AgentNoticeAnnouncer.tsxnew file mode 100644index 000000000..833077cdc--- /dev/null+++ b/packages/app/src/components/acp/AgentNoticeAnnouncer.tsx@@ -0,0 +1,104 @@+import { useLingui } from '@lingui/react/macro';+import { type ReactNode, useEffect, useRef } from 'react';+import { createLiveRegionQueue, type LiveRegionQueue } from './live-region-queue';++/**+ * Long enough that a screen reader observes each announcement separately,+ * short enough that a pair of warnings from one turn still reads as prompt.+ * Chosen for observable separation rather than measured against how long a+ * warning takes to speak, which needs a real screen reader to settle.+ */+const ANNOUNCE_SPACING_MS = 150;++/**+ * Speaks runtime warnings that arrive while the reader is here, and stays+ * silent about the ones that were already history when the thread opened.+ *+ * A warning card is passive by design — it draws itself and waits — which+ * leaves a reader who cannot see the transcript with no cue that anything+ * appeared. This region is that cue, and only that: it never moves focus and+ * the card it describes stays exactly where it is.+ *+ * The replay boundary is the whole difficulty, and it is settled per notice+ * rather than per render. A thread's transcript arrives after the view is+ * already mounted, in one or more batches out of the server's retained log, so+ * "the model gained a notice" cannot by itself mean "a warning just happened"+ * — opening a month-old thread would recite every warning it ever produced.+ * Comparing each notice's own seq against the subscription's replay bound is+ * exact where counting is not: a batch that carries the tail of the retained+ * log AND a warning that landed after it is indistinguishable by count, and+ * the live half of it would be lost.+ *+ * Scoped to the thread the reader is looking at. A background thread's panel+ * is `display: none`, which takes its region out of the accessibility tree, so+ * a warning arriving there is drawn but not spoken and is found on the card+ * when the reader switches to it. Announcing it on reveal was rejected for the+ * same reason replay is silent: by then it is history, and speaking history is+ * the failure mode this region is built to avoid.+ */+export function AgentNoticeAnnouncer({+ notices,+ agentName,+ replayThroughSeq,+}: {+ /** Every agent notice in the transcript, in source order, with its seq. */+ notices: readonly { readonly seq: number; readonly text: string }[];+ agentName: string;+ /** Upper bound of the replayed window — at or below it is history. */+ replayThroughSeq: number;+}): ReactNode {+ const { t } = useLingui();+ const regionRef = useRef<HTMLDivElement | null>(null);+ const queueRef = useRef<LiveRegionQueue | null>(null);+ const spokenThroughRef = useRef(Number.NEGATIVE_INFINITY);++ // Declared before the announcing effect so the queue exists by the time that+ // one first runs — effects fire in declaration order.+ useEffect(() => {+ const queue = createLiveRegionQueue({+ region: () => regionRef.current,+ spacingMs: ANNOUNCE_SPACING_MS,+ });+ queueRef.current = queue;+ return () => {+ queue.dispose();+ queueRef.current = null;+ };+ }, []);++ useEffect(() => {+ const floor = Math.max(replayThroughSeq, spokenThroughRef.current);+ const arrived = notices.filter((item) => item.seq > floor);+ if (arrived.length === 0) return;+ spokenThroughRef.current = arrived[arrived.length - 1]?.seq ?? floor;+ queueRef.current?.announce(+ arrived.map((item) => {+ const headline = noticeHeadline(item.text);+ return t`${agentName} reported: ${headline}`;+ }),+ );+ }, [notices, agentName, replayThroughSeq, t]);++ // Mounted empty from the first render and filled later: a region that+ // appears already holding its text is commonly missed, and one added and+ // populated in the same cycle is missed outright.+ return (+ <div+ ref={regionRef}+ role="status"+ aria-live="polite"+ aria-atomic="true"+ className="sr-only"+ data-testid="agent-thread-warning-announcer"+ />+ );+}++/**+ * The warning's own opening line. The rest of a multi-paragraph config warning+ * stays on screen instead of being read into the polite queue, and what is+ * spoken is the agent's wording rather than a paraphrase of it.+ */+function noticeHeadline(text: string): string {+ return (text.split('\n', 1)[0] ?? '').trim();+}diff --git a/packages/app/src/components/acp/AgentThreadClientBinder.tsx b/packages/app/src/components/acp/AgentThreadClientBinder.tsxindex 0945eb204..e412f830a 100644--- a/packages/app/src/components/acp/AgentThreadClientBinder.tsx+++ b/packages/app/src/components/acp/AgentThreadClientBinder.tsx@@ -12,6 +12,25 @@ import { useEffect } from 'react';import { getAgentThreadClient, threadUrlFromCollabUrl } from '@/lib/acp/thread-client';import { useCollabUrl } from '@/lib/use-collab-url';+/**+ * Fetch the development-only thread-injection harness installer.+ *+ * Deliberately a module-scope function rather than inline in the effect below:+ * React Compiler cannot lower an `import()` expression inside a component and+ * fails the build outright, while a plain function is left alone. Keeping the+ * only caller inside an `import.meta.env.DEV` branch is what lets the bundler+ * drop this function, the dynamic import, and the harness chunk together.+ *+ * Resolves to the installer rather than calling it, so a caller that has since+ * unmounted can decline without ever having published a harness.+ */+async function loadDevThreadHarnessInstaller(): Promise<+ typeof import('@/lib/acp/dev-thread-harness').installAcpThreadHarness+> {+ const mod = await import('@/lib/acp/dev-thread-harness');+ return mod.installAcpThreadHarness;+}+export function AgentThreadClientBinder(): null {const { collabUrl } = useCollabUrl();@@ -21,5 +40,33 @@ export function AgentThreadClientBinder(): null {getAgentThreadClient().setUrl(threadUrlFromCollabUrl(collabUrl));}, [collabUrl]);+ useEffect(() => {+ if (!import.meta.env.DEV) return;+ let uninstall: (() => void) | null = null;+ let unmounted = false;+ loadDevThreadHarnessInstaller()+ .then((install) => {+ // Declining after unmount is what makes this safe under StrictMode's+ // remount: installing and then withdrawing would clobber the harness the+ // second mount had already published in the meantime.+ if (unmounted) return;+ uninstall = install(getAgentThreadClient());+ })+ .catch((err: unknown) => {+ // A stale chunk after a dev-server restart rejects here. Unhandled, the+ // only symptom downstream is a browser test waiting out its timeout on+ // a global that never appears, with the real cause in a rejection+ // nothing is listening for.+ console.warn(+ '[acp] dev thread harness unavailable; window.__acpThreadHarness will not be published',+ err,+ );+ });+ return () => {+ unmounted = true;+ uninstall?.();+ };+ }, []);+return null;}diff --git a/packages/app/src/components/acp/ThreadView.composed.dom.test.tsx b/packages/app/src/components/acp/ThreadView.composed.dom.test.tsxnew file mode 100644index 000000000..c38d979e6--- /dev/null+++ b/packages/app/src/components/acp/ThreadView.composed.dom.test.tsx@@ -0,0 +1,564 @@+/**+ * The classifier-to-renderer join, exercised end to end.+ *+ * Every other ThreadView suite doubles `@/lib/acp/thread-client` and hands the+ * view a hand-authored render model, so a classifier that never fires or a+ * render arm that is never reached passes green in all of them. Here the only+ * double on the data path is the browser's own `WebSocket`: raw server frames+ * enter through the real client's socket handler, the real incremental fold+ * builds the model, and the real ThreadView draws it.+ *+ * Fixtures carry the producer's exact bytes and are shared with the core+ * predicate, the server boundary guard, and the fold, so the four cannot drift.+ */++import type {+ SessionUpdate,+ ThreadEvent,+ ThreadInfo,+ ThreadServerFrame,+} from '@inkeep/open-knowledge-core/acp/thread-protocol';+import { act, cleanup, render as rtlRender, screen, waitFor, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { TooltipProvider } from '@/components/ui/tooltip';+import fixture from '../../../../../test-support/fixtures/codex-legacy-warning-envelopes.json' with {+ type: 'json',+};+import { MockComposerMentionInput } from './composer-mention-input.test-helper';++/**+ * Environment doubles, not seam doubles: the editor context and workspace hook+ * need providers this suite has no reason to stand up, and the composer's real+ * field is a ProseMirror contentEditable jsdom cannot host. None of them sits+ * between a server frame and a transcript row. `AgentMarkdown` is deliberately+ * NOT doubled here — the notice card is supposed to reach the same renderer a+ * reply does, and a double would hide it if it stopped.+ */+vi.doMock('@/editor/DocumentContext', () => ({+ useDocumentContext: () => ({ systemProvider: null }),+}));+vi.doMock('@/lib/use-workspace', () => ({ useWorkspace: () => null }));+vi.doMock('@/editor/ComposerMentionInput', () => ({+ ComposerMentionInput: MockComposerMentionInput,+}));++const { ThreadView } = await import('./ThreadView');+const { getAgentThreadClient } = await import('@/lib/acp/thread-client');++const render = (ui: Parameters<typeof rtlRender>[0]) => rtlRender(ui, { wrapper: TooltipProvider });++const CODEX = fixture.agents.codexRegistry;+const SOCKET_URL = 'ws://localhost:5173/collab/thread';++type AgentIdentity = typeof fixture.agents.codexRegistry;+/**+ * The fixture records a near miss's identity as a KEY into `agents`. Two of+ * them are near misses only because of who sent them, so subscribing under a+ * raw key would reject them for being malformed and prove nothing about the+ * identity gate.+ */+const agentNamed = (name: string | undefined): AgentIdentity =>+ name === undefined ? CODEX : (fixture.agents as Record<string, AgentIdentity>)[name];++/**+ * The transport, and only the transport. The client owns everything above it —+ * frame parsing, the event log, dedupe, the fold — so this stands in for the+ * browser primitive alone: construct, open, deliver a payload, record what was+ * sent back.+ */+class FakeSocket {+ static readonly CONNECTING = 0;+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ static readonly CLOSED = 3;+ static last: FakeSocket | null = null;++ readyState: number = FakeSocket.CONNECTING;+ onopen: (() => void) | null = null;+ onmessage: ((event: { data: string }) => void) | null = null;+ onclose: (() => void) | null = null;+ onerror: (() => void) | null = null;+ readonly sent: string[] = [];++ constructor(readonly url: string) {+ FakeSocket.last = this;+ }++ send(data: string): void {+ this.sent.push(data);+ }++ close(): void {+ this.readyState = FakeSocket.CLOSED;+ this.onclose?.();+ }++ openFromServer(): void {+ this.readyState = FakeSocket.OPEN;+ this.onopen?.();+ }++ deliver(frame: ThreadServerFrame): void {+ this.onmessage?.({ data: JSON.stringify(frame) });+ }+}++const realWebSocket = globalThis.WebSocket;+let socket: FakeSocket;+/**+ * The client is a module singleton whose store outlives every test in this+ * file, and it dedupes by seq — so a scenario that reused a thread id would+ * have its frames silently dropped as stale and then assert against whatever+ * the previous scenario left on screen. Every subscription takes a fresh id.+ */+let threadId: string;+let threadCounter = 0;++beforeEach(() => {+ vi.stubGlobal('WebSocket', FakeSocket);+ FakeSocket.last = null;+ act(() => {+ getAgentThreadClient().setUrl(SOCKET_URL);+ });+ if (FakeSocket.last === null) throw new Error('the client did not open a socket');+ socket = FakeSocket.last;+ act(() => {+ socket.openFromServer();+ });+});++afterEach(() => {+ cleanup();+ // Drops the socket and its reconnect timer before the next test opens one;+ // without it the singleton keeps a live backoff timer per test.+ act(() => {+ getAgentThreadClient().setUrl(null);+ });+ vi.stubGlobal('WebSocket', realWebSocket);+ vi.useRealTimers();+});++/** Subscribe a brand-new thread and hand back the info the view renders. */+function openThread(overrides?: Omit<Partial<ThreadInfo>, 'threadId'>): ThreadInfo {+ threadCounter += 1;+ threadId = `composed-${threadCounter}`;+ const info: ThreadInfo = {+ agent: CODEX,+ title: 'Composed thread',+ status: 'ready',+ createdAt: 1,+ lastActivityAt: 2,+ lastSeq: -1,+ archived: false,+ ...overrides,+ threadId,+ };+ act(() => {+ socket.deliver({ op: 'subscribed', threadId, fromSeq: 0, info });+ });+ return info;+}++/** One event frame, the shape a mid-turn single send uses. */+function pushEvent(event: ThreadEvent, seq: number): void {+ act(() => {+ socket.deliver({ op: 'event', threadId, seq, event });+ });+}++/** A batch frame — both live coalescing and history replay use this shape. */+function pushEvents(events: readonly ThreadEvent[], fromSeq: number): void {+ act(() => {+ socket.deliver({ op: 'events', threadId, fromSeq, events: [...events] });+ });+}++/**+ * Fixture updates are untyped wire JSON on purpose: several negatives are+ * shapes the SDK's types forbid, and those are exactly the ones that have to+ * reach the fold unclassified rather than be filtered out by a cast here.+ */+const asUpdate = (value: unknown): SessionUpdate => value as SessionUpdate;++let eventTs = 0;+function su(update: unknown): ThreadEvent {+ eventTs += 1;+ return { kind: 'session_update', update: asUpdate(structuredClone(update)), ts: eventTs };+}++function chunk(text: string, messageId?: string): ThreadEvent {+ return su({+ sessionUpdate: 'agent_message_chunk',+ ...(messageId === undefined ? {} : { messageId }),+ content: { type: 'text', text },+ });+}++/** Row-level testids only: nested controls would pollute the ordering. */+const ROW_TESTIDS = [+ 'agent-thread-agent-notice',+ 'agent-thread-agent-message',+ 'agent-thread-user-message',+ 'agent-thread-thought',+ 'agent-thread-notice',+ 'agent-thread-tool-call',+] as const;++/** What the reader ends up with: each transcript row's kind and visible text, in order. */+function transcriptRows(): [string, string][] {+ const transcript = screen.getByTestId('agent-thread-transcript');+ const selector = ROW_TESTIDS.map((id) => `[data-testid="${id}"]`).join(',');+ return [...transcript.querySelectorAll<HTMLElement>(selector)].map((row) => [+ row.dataset.testid ?? '',+ row.textContent ?? '',+ ]);+}++const noticeCards = (): HTMLElement[] => screen.queryAllByTestId('agent-thread-agent-notice');++describe('composed transcript: a Codex warning becomes a warning card', () => {+ test.each(+ fixture.candidates.map((candidate) => [candidate.name, candidate] as const),+ )('candidate %s arrives over the socket and draws one runtime-warning row', (_name, candidate) => {+ render(<ThreadView info={openThread()} />);++ pushEvent(su(candidate.update), 0);++ const cards = noticeCards();+ expect(cards).toHaveLength(1);+ const card = cards[0];+ expect(card).toBe(screen.getByRole('note'));+ // The label and the glyph are the two cues that survive when the amber+ // fill does not — a reader on forced colors, or one skimming.+ expect(card.textContent).toContain('Warning');+ expect(card.querySelector('svg')?.getAttribute('aria-hidden')).toBe('true');+ // The producer's own words, through the same markdown path a reply takes.+ const body = candidate.update.content.text.trim();+ expect(card.textContent).toContain(body.split('\n')[0]);+ expect(screen.queryByTestId('agent-thread-agent-message')).toBeNull();+ });++ test('a config warning keeps its detail paragraphs inside the one card', () => {+ const detailed = fixture.candidates.find((c) => c.name === 'config-warning-with-details');+ if (detailed === undefined) throw new Error('fixture lost its detailed config warning');+ render(<ThreadView info={openThread()} />);++ pushEvent(su(detailed.update), 0);++ expect(noticeCards()).toHaveLength(1);+ const card = noticeCards()[0];+ expect(card.textContent).toContain('Ignored 2 invalid entries in config.toml.');+ // The detail paragraph the summary line alone would lose. Markdown turns+ // it into a list and eats the backticks, so the assertion is on the words.+ const bullets = within(card).getAllByRole('listitem');+ expect(bullets.map((bullet) => bullet.textContent)).toEqual([+ 'model_reasoning_effort: expected one of low, medium, high',+ 'sandbox_mode: unknown value full-access',+ ]);+ });++ test('a warning body renders producer markdown, so its links and fences are real controls', () => {+ // The card's own chrome contributes no control, but the body goes through+ // the same renderer as a reply, and the producer interpolates an arbitrary+ // runtime message into it. A warning that points at a docs URL or quotes a+ // config block therefore brings whatever that text brings anywhere else in+ // the transcript. That is the decided behaviour rather than an oversight,+ // and pinning it here means a later tightening of the card's contract is a+ // deliberate change instead of a rediscovery.+ render(<ThreadView info={openThread()} />);++ pushEvent(+ chunk('Warning: see https://example.com/docs for the fix.\n\n```toml\nmode = 1\n```\n\n'),+ 0,+ );++ const card = noticeCards()[0];+ expect(card).toBe(screen.getByRole('note'));+ expect(within(card).getByRole('link').getAttribute('href')).toBe('https://example.com/docs');+ expect(within(card).getAllByRole('button').length).toBeGreaterThan(0);+ });++ test('a warning between adjacent no-ID chrome leaves both neighbours as prose', () => {+ render(<ThreadView info={openThread()} />);++ pushEvents(+ [+ su(fixture.neighbors.contextCompacted.update),+ su(fixture.candidates[0].update),+ su(fixture.neighbors.turnError.update),+ ],+ 0,+ );++ expect(transcriptRows().map(([id]) => id)).toEqual([+ 'agent-thread-agent-message',+ 'agent-thread-agent-notice',+ 'agent-thread-agent-message',+ ]);+ expect(screen.getByTestId('agent-thread-transcript').textContent).toContain(+ 'stream disconnected before completion',+ );+ });+});++describe('composed transcript: near misses stay ordinary prose', () => {+ const SENTINEL = 'The refactor is safe.';++ test.each(+ fixture.negatives.map((negative) => [negative.name, negative] as const),+ )('near miss %s draws no warning card', (_name, negative) => {+ const agent = agentNamed((negative as { agent?: string }).agent);+ render(<ThreadView info={openThread({ agent })} />);++ // The sentinel carries an id, so it never merges with the near miss and+ // its presence proves the transcript actually drew something.+ pushEvents([su(negative.update), chunk(SENTINEL, 'sentinel')], 0);++ expect(noticeCards()).toHaveLength(0);+ expect(screen.queryAllByRole('note')).toHaveLength(0);+ const transcript = screen.getByTestId('agent-thread-transcript');+ expect(transcript.textContent).toContain(SENTINEL);+ const body = (negative.update as { content?: { type?: string; text?: string } }).content;+ if (body?.type === 'text' && body.text !== undefined && body.text.trim() !== '') {+ expect(transcript.textContent).toContain(body.text.trim());+ }+ });++ test('an ordinary answer carrying an item id stays a reply bubble', () => {+ render(<ThreadView info={openThread()} />);++ pushEvent(su(fixture.ordinaryAnswer.update), 0);++ expect(noticeCards()).toHaveLength(0);+ expect(screen.getByTestId('agent-thread-agent-message').textContent).toContain(+ 'The skills are all still loaded.',+ );+ });++ test('a historical event that already merged chrome with a warning is one prose bubble', () => {+ // What the log holds for a thread recorded before the boundary guard: the+ // producer's two events coalesced into one. It no longer starts with the+ // prefix, so it fails closed — and is never carved apart at the blank line.+ const merged =+ fixture.neighbors.contextCompacted.update.content.text ++ fixture.candidates[0].update.content.text;+ render(<ThreadView info={openThread()} />);++ pushEvents([chunk(merged)], 0);++ expect(noticeCards()).toHaveLength(0);+ expect(transcriptRows().map(([id]) => id)).toEqual(['agent-thread-agent-message']);+ const bubble = screen.getByTestId('agent-thread-agent-message');+ expect(bubble.textContent).toContain("Context compacted to fit the model's context window.");+ expect(bubble.textContent).toContain('Warning: Skill descriptions were shortened');+ });+});++describe('composed transcript: delivery shape does not change what is drawn', () => {+ /** Prose, a warning, more prose, a second warning, then a settled answer. */+ function sourceEvents(): ThreadEvent[] {+ return [+ { kind: 'user_message', content: 'check the skills', ts: 1 },+ su(fixture.neighbors.contextCompacted.update),+ su(fixture.candidates[0].update),+ chunk('Looking into it.', 'm1'),+ su(fixture.candidates[2].update),+ chunk('All set.', 'm2'),+ ];+ }++ /**+ * `lastSeq` is the wire's own replay upper bound: a live thread has already+ * folded everything the server retains, a reopened one has not. Both use the+ * same `events` frame, so this is the only thing that distinguishes history+ * from a live burst — and neither may change what the transcript draws.+ */+ function drawnWith(+ deliver: (events: ThreadEvent[]) => void,+ retainedThrough = -1,+ ): [string, string][] {+ render(<ThreadView info={openThread({ lastSeq: retainedThrough })} />);+ deliver(sourceEvents());+ const rows = transcriptRows();+ cleanup();+ return rows;+ }++ test('live, one-shot, batched, and replayed delivery draw the same transcript', () => {+ const live = drawnWith((events) => {+ events.forEach((event, index) => {+ pushEvent(event, index);+ });+ });+ const oneShot = drawnWith((events) => pushEvents(events, 0));+ const batched = drawnWith((events) => {+ pushEvents(events.slice(0, 2), 0);+ pushEvents(events.slice(2, 4), 2);+ pushEvents(events.slice(4), 4);+ });+ // A reopened thread: the whole log is already retained, and history walks+ // back to the client in chunks behind the subscription.+ const replayed = drawnWith((events) => {+ pushEvents(events.slice(0, 3), 0);+ pushEvents(events.slice(3), 3);+ }, sourceEvents().length - 1);++ // Pinned outright, not only compared: four empty transcripts are equal to+ // each other and would say nothing about boundaries.+ expect(live.map(([id]) => id)).toEqual([+ 'agent-thread-user-message',+ 'agent-thread-agent-message',+ 'agent-thread-agent-notice',+ 'agent-thread-agent-message',+ 'agent-thread-agent-notice',+ 'agent-thread-agent-message',+ ]);+ expect(oneShot).toEqual(live);+ expect(batched).toEqual(live);+ expect(replayed).toEqual(live);+ });++ test('a warning arriving live and the same event replayed from history agree', () => {+ const arrived = drawnWith((events) => pushEvent(events[2], 0));+ const fromHistory = drawnWith((events) => pushEvents([events[2]], 0), 0);++ expect(arrived.map(([id]) => id)).toEqual(['agent-thread-agent-notice']);+ expect(fromHistory).toEqual(arrived);+ });++ test('a replayed warning draws its card but announces nothing, unlike a live one', async () => {+ const announcer = () => screen.getByTestId('agent-thread-warning-announcer');++ render(<ThreadView info={openThread({ lastSeq: 0 })} />);+ pushEvents([sourceEvents()[2]], 0);+ expect(noticeCards()).toHaveLength(1);+ expect(announcer().textContent).toBe('');+ cleanup();++ render(<ThreadView info={openThread({ lastSeq: -1 })} />);+ pushEvent(sourceEvents()[2], 0);+ expect(noticeCards()).toHaveLength(1);+ await waitFor(() => expect(announcer().textContent).toContain('Codex reported:'));+ });+});++describe('composed transcript: existing rows keep their behaviour', () => {+ test('a startup failure still offers Retry, and the warning card carries none of it', async () => {+ render(<ThreadView info={openThread({ status: 'error' })} />);++ pushEvents(+ [+ su(fixture.candidates[0].update),+ {+ kind: 'status',+ status: 'error',+ ts: 2,+ failure: { reason: 'connect', agentMessage: 'initialize failed' },+ },+ ],+ 0,+ );++ const failure = screen.getByTestId('agent-thread-notice');+ const retry = screen.getByTestId('agent-thread-retry');+ expect(failure.contains(retry)).toBe(true);+ expect(noticeCards()[0].contains(retry)).toBe(false);+ expect(within(noticeCards()[0]).queryAllByRole('button')).toHaveLength(0);++ await act(async () => {+ await userEvent.click(retry);+ });++ // The click reached the real client, which put a retry on the wire.+ expect(socket.sent.map((frame) => JSON.parse(frame).op)).toContain('retry');+ });++ test('a failed prompt still offers Edit and resend, and it seeds the composer', async () => {+ render(<ThreadView info={openThread({ status: 'ready' })} />);++ pushEvents(+ [+ { kind: 'user_message', content: 'summarise the skills', ts: 1 },+ su(fixture.candidates[0].update),+ {+ kind: 'status',+ status: 'error',+ ts: 3,+ failure: { reason: 'prompt', agentMessage: 'the turn failed' },+ },+ ],+ 0,+ );++ const restore = screen.getByTestId('agent-thread-restore');+ expect(restore.textContent).toContain('Edit and resend');++ await act(async () => {+ await userEvent.click(restore);+ });++ expect(screen.getByTestId<HTMLTextAreaElement>('agent-thread-composer').value).toBe(+ 'summarise the skills',+ );+ });++ test('replies, thoughts, and tool calls draw as they always did alongside a warning', () => {+ render(<ThreadView info={openThread()} />);++ pushEvents(+ [+ { kind: 'user_message', content: 'run the tests', ts: 1 },+ su({+ sessionUpdate: 'agent_thought_chunk',+ content: { type: 'text', text: 'Checking the suite.' },+ }),+ su({+ sessionUpdate: 'tool_call',+ toolCallId: 'call-1',+ title: 'Run tests',+ kind: 'execute',+ status: 'completed',+ }),+ su(fixture.candidates[0].update),+ chunk('Everything passes.', 'm1'),+ ],+ 0,+ );++ expect(transcriptRows().map(([id]) => id)).toEqual([+ 'agent-thread-user-message',+ 'agent-thread-thought',+ 'agent-thread-tool-call',+ 'agent-thread-agent-notice',+ 'agent-thread-agent-message',+ ]);+ expect(screen.getByTestId('agent-thread-tool-call').textContent).toContain('Run tests');+ expect(screen.getByTestId('agent-thread-agent-message').textContent).toContain(+ 'Everything passes.',+ );+ });++ test('a warning mid-turn does not end the turn', () => {+ render(<ThreadView info={openThread({ status: 'running' })} />);++ pushEvents(+ [+ { kind: 'user_message', content: 'check the skills', ts: 1 },+ { kind: 'turn_started', ts: 2 },+ su(fixture.candidates[0].update),+ ],+ 0,+ );++ // The warning is chrome the agent emitted while still working; treating it+ // as the end of the turn would drop the indicator mid-answer.+ expect(noticeCards()).toHaveLength(1);+ expect(screen.getByTestId('agent-thread-working')).not.toBeNull();++ pushEvent({ kind: 'turn_ended', stopReason: 'end_turn', ts: 4 }, 3);++ expect(screen.queryByTestId('agent-thread-working')).toBeNull();+ expect(noticeCards()).toHaveLength(1);+ });+});diff --git a/packages/app/src/components/acp/ThreadView.crash-recovery.dom.test.tsx b/packages/app/src/components/acp/ThreadView.crash-recovery.dom.test.tsxnew file mode 100644index 000000000..84aec2412--- /dev/null+++ b/packages/app/src/components/acp/ThreadView.crash-recovery.dom.test.tsx@@ -0,0 +1,452 @@+/**+ * Reopening a thread the server died on, all the way from disk to the reader.+ *+ * A crash leaves the persisted metadata behind its own event log — the meta is+ * rewritten on info changes, not per appended event — so the durable log can+ * end far past the `lastSeq` on disk. That skew only matters once, and only+ * here: the polite announcer treats "delivery caught up to the retained log"+ * as the end of history, so a replay that runs past a stale bound starts+ * reciting a dead thread's warnings as if they had just happened.+ *+ * Nothing below hands the client a replay bound. The real manager rehydrates+ * the real files, the real socket announces the window, and the real client,+ * fold, renderer, and announcer do the rest, because a synthetic `subscribed`+ * frame with an accurate bound is precisely the mistake under test.+ */++import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { SessionUpdate, ThreadEvent } from '@inkeep/open-knowledge-core/acp/thread-protocol';+import type { AgentSessionManager } from '@inkeep/open-knowledge-server';+import {+ AcpPermissionStore,+ AcpRegistry,+ AcpThreadManager,+ attachAcpThreadSocket,+ getLogger,+} from '@inkeep/open-knowledge-server';+import { act, cleanup, render as rtlRender, screen } from '@testing-library/react';+import type { ReactNode } from 'react';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { TooltipProvider } from '@/components/ui/tooltip';+import fixture from '../../../../../test-support/fixtures/codex-legacy-warning-envelopes.json' with {+ type: 'json',+};+import { MockComposerMentionInput } from './composer-mention-input.test-helper';++/**+ * Environment doubles, not seam doubles: the editor context and workspace hook+ * need providers this suite has no reason to stand up, and the composer's real+ * field is a ProseMirror contentEditable jsdom cannot host. None of them sits+ * between a server frame and a transcript row.+ */+vi.doMock('@/editor/DocumentContext', () => ({+ useDocumentContext: () => ({ systemProvider: null }),+}));+vi.doMock('@/lib/use-workspace', () => ({ useWorkspace: () => null }));+vi.doMock('@/editor/ComposerMentionInput', () => ({+ ComposerMentionInput: MockComposerMentionInput,+}));++const { ThreadView } = await import('./ThreadView');+const { getAgentThreadClient, useAgentThread } = await import('@/lib/acp/thread-client');++const log = getLogger('acp-crash-recovery-test');+const AGENT_ID = 'codex-acp';+const AGENT_NAME = 'Codex';+const SOCKET_URL = 'ws://localhost:5173/collab/thread';+/** Replay walks the log back in 512-event frames; anything longer takes several. */+const REPLAY_CHUNK = 512;++const HISTORIC_WARNING_A = fixture.candidates[0].update.content.text;+const HISTORIC_WARNING_B = fixture.candidates[2].update.content.text;+const LIVE_WARNING = fixture.candidates[1].update.content.text;++// ── the durable transcript a crash left behind ────────────────────────────++const su = (update: unknown, ts: number): ThreadEvent => ({+ kind: 'session_update',+ update: update as SessionUpdate,+ ts,+});++const agentChunk = (text: string, ts: number): ThreadEvent =>+ su({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } }, ts);++const thoughtChunk = (ts: number): ThreadEvent =>+ su({ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: '.' } }, ts);++/**+ * One warning early enough to land in the first replay frame and one late+ * enough to land in a later one — the whole point of the fixture. Padding is+ * thought chunks so the transcript stays two warning cards plus a single+ * folded thought, however long the log is.+ */+function crashedTranscript(): ThreadEvent[] {+ const events: ThreadEvent[] = [{ kind: 'user_message', content: 'check the skills', ts: 1 }];+ events.push(agentChunk(HISTORIC_WARNING_A, 2));+ while (events.length < REPLAY_CHUNK) events.push(thoughtChunk(events.length + 1));+ events.push(agentChunk(HISTORIC_WARNING_B, events.length + 1));+ return events;+}++const CRASHED_EVENTS = crashedTranscript();+/** The seq the meta would have named had the server survived to write it. */+const DURABLE_LAST_SEQ = CRASHED_EVENTS.length - 1;+/**+ * What the meta actually holds: an early seq, from the last info change before+ * the crash. Small enough that delivery passes it inside the first frame.+ */+const STALE_LAST_SEQ = 1;++function writeCrashedThread(localDir: string, threadId: string): void {+ const threadsDir = join(localDir, 'threads');+ mkdirSync(threadsDir, { recursive: true });+ writeFileSync(+ join(threadsDir, `${threadId}.ndjson`),+ `${CRASHED_EVENTS.map((event) => JSON.stringify(event)).join('\n')}\n`,+ );+ writeFileSync(+ join(threadsDir, `${threadId}.meta.json`),+ JSON.stringify({+ version: 1,+ info: {+ threadId,+ agent: { id: AGENT_ID, name: AGENT_NAME, source: 'registry' },+ title: 'Crashed thread',+ status: 'running',+ createdAt: 1,+ lastActivityAt: 2,+ modes: null,+ configOptions: null,+ lastSeq: STALE_LAST_SEQ,+ },+ sessionId: 'sess-fixed',+ cwd: localDir,+ agentRef: { source: 'registry', id: AGENT_ID },+ }),+ );+}++// ── a resumable registry agent, reachable without a network ───────────────++/**+ * Registry source is not cosmetic: it is half of the identity both the+ * retention guard and the fold consult, and only a manifest can carry it. The+ * agent is reached the way a registry agent is — an `npx` shim on the+ * manifest's own overlay PATH — and answers `session/resume` so the crashed+ * thread can come back to life.+ */+function writeResumableRegistryAgent(binDir: string, warningText: string): void {+ const agentPath = join(binDir, 'agent.mjs');+ writeFileSync(+ agentPath,+ `+const write = (m) => process.stdout.write(JSON.stringify(m) + '\\n');+const WARNING = ${JSON.stringify(warningText)};+let buffer = '';+process.stdin.setEncoding('utf8');+process.stdin.on('data', (chunk) => {+ buffer += chunk;+ let idx = buffer.indexOf('\\n');+ while (idx !== -1) {+ const line = buffer.slice(0, idx);+ buffer = buffer.slice(idx + 1);+ idx = buffer.indexOf('\\n');+ if (line.trim() === '') continue;+ const msg = JSON.parse(line);+ const reply = (result) => write({ jsonrpc: '2.0', id: msg.id, result });+ if (msg.method === 'initialize') {+ reply({+ protocolVersion: 1,+ agentCapabilities: { sessionCapabilities: { resume: {} } },+ });+ } else if (msg.method === 'session/resume') {+ reply({});+ } else if (msg.method === 'session/prompt') {+ write({+ jsonrpc: '2.0',+ method: 'session/update',+ params: {+ sessionId: 'sess-fixed',+ update: {+ sessionUpdate: 'agent_message_chunk',+ content: { type: 'text', text: WARNING },+ },+ },+ });+ reply({ stopReason: 'end_turn' });+ } else if (msg.id !== undefined) {+ reply({});+ }+ }+});+`,+ );+ writeFileSync(join(binDir, 'npx'), `#!/bin/sh\nexec "${process.execPath}" "${agentPath}"\n`, {+ mode: 0o755,+ });+ // The launch path probes `node --version` for npx compatibility before it+ // spawns anything, and the overlay PATH is the only place it can look.+ writeFileSync(+ join(binDir, 'node'),+ `#!/bin/sh\nif [ "$1" = "--version" ]; then echo v${process.versions.node}; exit 0; fi\nexec "${process.execPath}" "$@"\n`,+ { mode: 0o755 },+ );+}++const fakeSessionManager = {+ getSession: async () => {+ throw new Error('fixture agents never use client fs');+ },+ closeAllForAgent: async () => {},+} as unknown as AgentSessionManager;++function makeManager(contentDir: string, localDir: string, binDir: string): AcpThreadManager {+ const manifest = {+ id: AGENT_ID,+ name: AGENT_NAME,+ version: '1.6.2',+ distribution: { npx: { package: `@fake/${AGENT_ID}`, env: { PATH: binDir } } },+ };+ return new AcpThreadManager({+ contentDir,+ localDir,+ globalDir: null,+ registry: new AcpRegistry({+ localDir,+ log,+ fetchImpl: (async () =>+ new Response(JSON.stringify({ agents: [manifest] }), {+ status: 200,+ })) as unknown as typeof fetch,+ }),+ permissions: new AcpPermissionStore(localDir, log),+ sessionManager: fakeSessionManager,+ isExcludedPath: () => false,+ isIgnoredPath: () => false,+ log,+ // Hermetic: every launch merges the login shell's PATH, and a test must+ // not spawn the developer's shell.+ resolveLoginShellPath: async () => null,+ });+}++// ── the socket, bridged in-process ────────────────────────────────────────++let manager: AcpThreadManager | null = null;+/** Every `events` frame the server put on the wire, in order. */+let replayFrameSizes: number[] = [];++/**+ * The browser primitive, and only it. Constructing one attaches the real+ * server-side handler to the other end, so every frame the client parses was+ * produced by `attachAcpThreadSocket` against a real thread record.+ */+class BridgedSocket {+ static readonly CONNECTING = 0;+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ static readonly CLOSED = 3;++ readyState: number = BridgedSocket.CONNECTING;+ onopen: (() => void) | null = null;+ onmessage: ((event: { data: string }) => void) | null = null;+ onclose: (() => void) | null = null;+ onerror: (() => void) | null = null;++ private readonly serverListeners = new Map<string, Array<(...args: unknown[]) => void>>();++ constructor(readonly url: string) {+ if (manager === null) throw new Error('no thread manager bound to the socket');+ attachAcpThreadSocket(+ {+ send: (data: string) => {+ const frame = JSON.parse(data) as { op: string; events?: unknown[] };+ if (frame.op === 'events') replayFrameSizes.push(frame.events?.length ?? 0);+ this.onmessage?.({ data });+ },+ close: () => this.close(),+ on: (event: string, listener: (...args: unknown[]) => void) => {+ const list = this.serverListeners.get(event) ?? [];+ list.push(listener);+ this.serverListeners.set(event, list);+ },+ },+ manager,+ log,+ );+ this.readyState = BridgedSocket.OPEN;+ queueMicrotask(() => this.onopen?.());+ }++ send(data: string): void {+ for (const listener of this.serverListeners.get('message') ?? []) listener(data);+ }++ close(): void {+ if (this.readyState === BridgedSocket.CLOSED) return;+ this.readyState = BridgedSocket.CLOSED;+ for (const listener of this.serverListeners.get('close') ?? []) listener();+ this.onclose?.();+ }+}++// ── harness ───────────────────────────────────────────────────────────────++const realWebSocket = globalThis.WebSocket;+let dirs: string[] = [];+let threadCounter = 0;++function tmp(): string {+ const dir = mkdtempSync(join(tmpdir(), 'acp-crash-recovery-'));+ dirs.push(dir);+ return dir;+}++async function until(predicate: () => boolean, label: string, ms = 15_000): Promise<void> {+ const deadline = Date.now() + ms;+ while (!predicate()) {+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${label}`);+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+}++const render = (ui: ReactNode) => rtlRender(ui, { wrapper: TooltipProvider });++/** Mirrors how the host feeds the view: info comes from the store, live. */+function ThreadHost({ threadId }: { threadId: string }): ReactNode {+ const state = useAgentThread(threadId);+ return state === null ? null : <ThreadView info={state.info} />;+}++const client = () => getAgentThreadClient();+const noticeCards = (): HTMLElement[] => screen.queryAllByTestId('agent-thread-agent-notice');+const announcer = (): HTMLElement => screen.getByTestId('agent-thread-warning-announcer');+const noticeCount = (threadId: string): number =>+ (client().getThreadModel(threadId)?.items ?? []).filter((item) => item.kind === 'agent_notice')+ .length;++/**+ * A settled region cannot tell a queued announcement from an overwritten one —+ * both leave the same final string — so the mutations are what get recorded.+ */+function recordAnnouncements(region: HTMLElement): () => string[] {+ const spoken: string[] = [];+ const observer = new MutationObserver((records) => {+ for (const record of records) {+ for (const node of record.addedNodes) {+ const text = node.textContent ?? '';+ if (text !== '') spoken.push(text);+ }+ }+ });+ observer.observe(region, { childList: true });+ return () => {+ observer.takeRecords().forEach((record) => {+ for (const node of record.addedNodes) {+ const text = node.textContent ?? '';+ if (text !== '') spoken.push(text);+ }+ });+ return [...spoken];+ };+}++/**+ * Boot a server over a crash-recovered thread, connect the real client to it,+ * and mount the view before any history has been asked for — the order that+ * puts the announcer on screen while the replay is still to come.+ */+async function openCrashedThread(): Promise<{ threadId: string; spoken: () => string[] }> {+ threadCounter += 1;+ const threadId = `crashed-${threadCounter}`;+ const localDir = tmp();+ const binDir = tmp();+ writeCrashedThread(localDir, threadId);+ writeResumableRegistryAgent(binDir, LIVE_WARNING);+ manager = makeManager(tmp(), localDir, binDir);+ await manager.init();++ await act(async () => {+ client().setUrl(SOCKET_URL);+ await until(() => client().getThread(threadId) !== null, 'the thread roster');+ });+ render(<ThreadHost threadId={threadId} />);+ return { threadId, spoken: recordAnnouncements(announcer()) };+}++beforeEach(() => {+ replayFrameSizes = [];+ vi.stubGlobal('WebSocket', BridgedSocket);+});++afterEach(async () => {+ cleanup();+ act(() => {+ client().setUrl(null);+ });+ vi.stubGlobal('WebSocket', realWebSocket);+ await manager?.destroy();+ manager = null;+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true });+ dirs = [];+});++describe.skipIf(process.platform === 'win32')('crash-recovered transcript', () => {+ test('replays every historical warning across several frames without announcing any', async () => {+ const { threadId, spoken } = await openCrashedThread();++ await act(async () => {+ client().openArchivedThread(threadId);+ await until(+ () => (client().getThread(threadId)?.lastSeq ?? -1) === DURABLE_LAST_SEQ,+ 'the durable log to finish replaying',+ );+ });++ // Anti-vacuity: one frame carrying everything could not tell an accurate+ // replay bound from a stale one, so the whole scenario would prove nothing.+ expect(replayFrameSizes.length).toBeGreaterThan(1);+ expect(replayFrameSizes.reduce((a, b) => a + b, 0)).toBe(CRASHED_EVENTS.length);++ const cards = noticeCards();+ expect(cards).toHaveLength(2);+ expect(cards[0].textContent).toContain(HISTORIC_WARNING_A.trim().split('\n')[0]);+ expect(cards[1].textContent).toContain(HISTORIC_WARNING_B.trim().split('\n')[0]);+ expect(announcer().textContent).toBe('');+ expect(spoken()).toEqual([]);+ }, 30_000);++ test('speaks the first warning that arrives after that replay, once', async () => {+ const { threadId, spoken } = await openCrashedThread();+ const composer = () => screen.getByTestId('agent-thread-composer');++ await act(async () => {+ client().openArchivedThread(threadId);+ await until(+ () => (client().getThread(threadId)?.lastSeq ?? -1) === DURABLE_LAST_SEQ,+ 'the durable log to finish replaying',+ );+ });+ composer().focus();+ const focused = document.activeElement;++ await act(async () => {+ await client().resumeThread(threadId, 'go');+ await until(() => noticeCount(threadId) === 3, 'the resumed agent to warn');+ });++ expect(noticeCards()).toHaveLength(3);+ // The region is cleared a beat before its message lands, so the utterance+ // is not on screen the instant the card is.+ await act(async () => {+ await until(() => spoken().length > 0, 'the live warning to be announced');+ });+ // Only the warning that actually just happened, and only one utterance of+ // it — the two the reader scrolled past stay on the cards.+ expect(spoken()).toEqual([`${AGENT_NAME} reported: ${LIVE_WARNING.trim().split('\n')[0]}`]);+ expect(document.activeElement).toBe(focused);+ }, 30_000);+});diff --git a/packages/app/src/components/acp/ThreadView.dom.test.tsx b/packages/app/src/components/acp/ThreadView.dom.test.tsxindex 724630e68..739cdab3b 100644--- a/packages/app/src/components/acp/ThreadView.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.dom.test.tsx@@ -14,6 +14,7 @@ import {fireEvent,render as rtlRender,screen,+ waitFor,within,} from '@testing-library/react';import userEvent from '@testing-library/user-event';@@ -33,6 +34,18 @@ import { MockComposerMentionInput } from './composer-mention-input.test-helper';const render = (ui: Parameters<typeof rtlRender>[0]) => rtlRender(ui, { wrapper: TooltipProvider });let model: ThreadRenderModel | null = null;+/**+ * The subscribed thread's store entry. `lastSeq` is how far the client has+ * folded the server's log and `replayThroughSeq` is the upper bound of the+ * replay the subscription announced, so a transcript still coming out of+ * history is one whose `lastSeq` has not reached that bound yet.+ */+let threadState = {+ info: undefined,+ events: [] as unknown[],+ lastSeq: 5,+ replayThroughSeq: 5,+};const respondPermission = vi.fn((_threadId: string, _requestId: string, _outcome: unknown) => {});const setConfigOption = vi.fn((_threadId: string, _configId: string, _value: string | boolean) => {},@@ -83,7 +96,7 @@ vi.doMock('@/lib/acp/thread-client', () => ({this.code = code;}},- useAgentThread: () => ({ info: undefined, events: [], lastSeq: 5 }),+ useAgentThread: () => threadState,useAgentThreadModel: () => model,}));@@ -204,6 +217,7 @@ afterEach(() => {authenticateThread.mockClear();authenticateResult = Promise.resolve();model = null;+ threadState = { info: undefined, events: [], lastSeq: 5, replayThroughSeq: 5 };});describe('ThreadView agent settings', () => {@@ -2708,6 +2722,317 @@ describe('ThreadView failure notices', () => {});});+/**+ * Runtime status the agent reported, drawn as chrome rather than speech.+ *+ * The defect this row exists to fix is misattribution: an operational warning+ * that reads as the agent's answer gets acted on as if the agent had said it.+ * So the assertions here are about what separates the two — a label, a glyph,+ * a box — and about what the row must NOT offer, since passive guidance with a+ * Retry button invites an action that does nothing.+ */+describe('ThreadView agent notices', () => {+ const WARNING_TEXT = 'Warning: Skill "foo" was not loaded because its manifest is invalid.\n\n';++ function agentNotice(text = WARNING_TEXT): Extract<RenderedItem, { kind: 'agent_notice' }> {+ return { kind: 'agent_notice', source: 'codex_legacy', severity: 'warning', text, seq: 0 };+ }++ test('reads as a runtime warning, not as the agent speaking', () => {+ model = makeModel({ turnActive: false, items: [agentNotice()] });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);++ const card = screen.getByRole('note');+ expect(card).toBe(screen.getByTestId('agent-thread-agent-notice'));+ // Three cues, because any one of them can be unavailable: the label for a+ // reader who cannot see the box, the glyph for one skimming, and the+ // border for forced-colors mode, where the amber fill is discarded.+ expect(card.textContent).toContain('Warning');+ expect(card.className).toContain('border');+ expect(card.className).toContain('amber');+ const glyph = card.querySelector('svg');+ expect(glyph?.getAttribute('aria-hidden')).toBe('true');+ // Not an assistant bubble — that is the whole point of the row.+ expect(screen.queryByTestId('agent-thread-agent-message')).toBeNull();+ });++ test('shows the producer text verbatim through the same renderer as a reply', () => {+ model = makeModel({ turnActive: false, items: [agentNotice()] });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);++ const rendered = within(screen.getByTestId('agent-thread-agent-notice')).getByTestId(+ 'rendered-markdown',+ );+ expect(rendered.textContent).toBe(WARNING_TEXT);+ });++ test('offers nothing to act on and opens no toast', () => {+ model = makeModel({ turnActive: false, items: [agentNotice()] });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);++ const card = screen.getByTestId('agent-thread-agent-notice');+ expect(within(card).queryAllByRole('button')).toHaveLength(0);+ expect(within(card).queryAllByRole('link')).toHaveLength(0);+ expect(screen.queryByTestId('agent-thread-retry')).toBeNull();+ expect(screen.queryByTestId('agent-thread-restore')).toBeNull();+ expect(toastError).not.toHaveBeenCalled();+ });++ test('sits in source order between the turns it interrupted', () => {+ model = makeModel({+ turnActive: false,+ items: [+ { kind: 'message', role: 'user', text: 'ship it', messageId: 'u1' },+ agentNotice(),+ { kind: 'message', role: 'agent', text: 'Done.', messageId: 'a1' },+ ],+ });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);++ const card = screen.getByTestId('agent-thread-agent-notice');+ const answer = screen.getByTestId('agent-thread-agent-message');+ expect(screen.getByTestId('agent-thread-user-message').compareDocumentPosition(card)).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ expect(card.compareDocumentPosition(answer)).toBe(Node.DOCUMENT_POSITION_FOLLOWING);+ // The answer keeps its own bubble: warning chrome never absorbs it.+ expect(within(answer).getByTestId('rendered-markdown').textContent).toBe('Done.');+ });++ test('two warnings in one turn stay two rows', () => {+ model = makeModel({+ turnActive: false,+ items: [agentNotice('Warning: first\n\n'), agentNotice('Warning: second\n\n')],+ });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);++ const cards = screen.getAllByTestId('agent-thread-agent-notice');+ expect(cards.map((card) => within(card).getByTestId('rendered-markdown').textContent)).toEqual([+ 'Warning: first\n\n',+ 'Warning: second\n\n',+ ]);+ });++ test('leaves an adjacent failure notice its own actions', async () => {+ model = makeModel({+ turnActive: false,+ items: [+ agentNotice(),+ {+ kind: 'notice',+ text: '',+ tone: 'error',+ attempts: 1,+ failure: { reason: 'connect', agentMessage: 'initialize failed' },+ },+ ],+ });+ render(<ThreadView info={makeInfo({ status: 'error' })} />);++ const failure = screen.getByTestId('agent-thread-notice');+ expect(failure.textContent).toContain("Claude couldn't start");+ // Retry belongs to the failure card, and the warning card sits outside it.+ const retry = screen.getByTestId('agent-thread-retry');+ expect(failure.contains(retry)).toBe(true);+ expect(screen.getByTestId('agent-thread-agent-notice').contains(retry)).toBe(false);++ await userEvent.click(retry);+ expect(retryThread).toHaveBeenCalledWith('thread-1');+ });+});++/**+ * Arrival announcements for runtime warnings.+ *+ * A warning card is silent by construction — it draws itself and offers+ * nothing to act on — so a reader who cannot see the transcript gets no cue+ * that one appeared. The polite region is that cue. The two failure modes it+ * has to avoid are opposite: saying nothing when a warning lands mid-turn, and+ * reciting a month of history to anyone who reopens an old thread.+ */+describe('ThreadView warning announcements', () => {+ const CODEX = { id: 'codex-acp', name: 'Codex', source: 'registry' as const };+ const FIRST = 'Warning: skill "alpha" was skipped\n\nIts manifest is invalid.\n\n';+ const SECOND = 'Warning: skill "beta" was skipped\n\n';++ function notice(text: string, seq: number): Extract<RenderedItem, { kind: 'agent_notice' }> {+ return { kind: 'agent_notice', source: 'codex_legacy', severity: 'warning', text, seq };+ }++ function announcer(): HTMLElement {+ return screen.getByTestId('agent-thread-warning-announcer');+ }++ /** A thread whose retained log has been fully folded — nothing left to replay. */+ function settled(seq: number) {+ threadState = { info: undefined, events: [], lastSeq: seq, replayThroughSeq: seq };+ return makeInfo({ status: 'ready', agent: CODEX, lastSeq: seq });+ }++ test('mounts the region empty, before any warning exists', () => {+ model = makeModel({ turnActive: false, items: [] });+ render(<ThreadView info={settled(5)} />);++ const region = announcer();+ expect(region.getAttribute('role')).toBe('status');+ expect(region.getAttribute('aria-live')).toBe('polite');+ expect(region.getAttribute('aria-atomic')).toBe('true');+ expect(region.className).toContain('sr-only');+ expect(region.textContent).toBe('');+ });++ test('announces a warning that arrives during the session', async () => {+ model = makeModel({ turnActive: true, items: [] });+ const { rerender } = render(<ThreadView info={settled(5)} />);++ threadState = { info: undefined, events: [], lastSeq: 6, replayThroughSeq: 5 };+ model = makeModel({ turnActive: true, items: [notice(FIRST, 6)] });+ rerender(<ThreadView info={settled(5)} />);++ // The agent's own opening line, framed by app copy that says who reported+ // it — the detail paragraph stays on the card rather than in the queue.+ await waitFor(() =>+ expect(announcer().textContent).toBe('Codex reported: Warning: skill "alpha" was skipped'),+ );+ });++ test('serializes two warnings from one turn in source order', async () => {+ model = makeModel({ turnActive: true, items: [] });+ const { rerender } = render(<ThreadView info={settled(5)} />);++ threadState = { info: undefined, events: [], lastSeq: 7, replayThroughSeq: 5 };+ model = makeModel({ turnActive: true, items: [notice(FIRST, 6), notice(SECOND, 7)] });+ rerender(<ThreadView info={settled(5)} />);++ await waitFor(() =>+ expect(announcer().textContent).toBe('Codex reported: Warning: skill "alpha" was skipped'),+ );+ // The second one waits its turn instead of replacing the first before it+ // has been read out.+ await waitFor(+ () =>+ expect(announcer().textContent).toBe('Codex reported: Warning: skill "beta" was skipped'),+ { timeout: 2000 },+ );+ });++ test('draws a replayed transcript without announcing any of it', () => {+ // Mounted before the retained log has been folded — what arrives next is+ // history, not news.+ threadState = { info: undefined, events: [], lastSeq: -1, replayThroughSeq: 4 };+ model = makeModel({ turnActive: false, items: [] });+ const info = makeInfo({ status: 'ready', agent: CODEX, lastSeq: 4 });+ const { rerender } = render(<ThreadView info={info} />);++ threadState = { info: undefined, events: [], lastSeq: 4, replayThroughSeq: 4 };+ model = makeModel({ turnActive: false, items: [notice(FIRST, 2), notice(SECOND, 4)] });+ rerender(<ThreadView info={info} />);++ expect(screen.getAllByTestId('agent-thread-agent-notice')).toHaveLength(2);+ expect(announcer().textContent).toBe('');+ });++ test('speaks the first warning that lands after a replayed transcript settles', async () => {+ threadState = { info: undefined, events: [], lastSeq: -1, replayThroughSeq: 4 };+ model = makeModel({ turnActive: false, items: [] });+ const info = makeInfo({ status: 'ready', agent: CODEX, lastSeq: 4 });+ const { rerender } = render(<ThreadView info={info} />);++ threadState = { info: undefined, events: [], lastSeq: 4, replayThroughSeq: 4 };+ model = makeModel({ turnActive: false, items: [notice(FIRST, 3)] });+ rerender(<ThreadView info={info} />);+ expect(announcer().textContent).toBe('');++ threadState = { info: undefined, events: [], lastSeq: 5, replayThroughSeq: 4 };+ model = makeModel({ turnActive: true, items: [notice(FIRST, 3), notice(SECOND, 5)] });+ rerender(<ThreadView info={info} />);++ await waitFor(() =>+ expect(announcer().textContent).toBe('Codex reported: Warning: skill "beta" was skipped'),+ );+ });++ test('speaks a warning that lands in the batch that closes the replay window', async () => {+ // The server advances `info.lastSeq` the moment it appends while event+ // batches coalesce on a timer, so delivery and that field cross back and+ // forth all session. The subscription's own bound is what separates+ // history from news, and the warning above it has to be spoken even when+ // the batch carrying it is also the one that catches delivery up.+ threadState = { info: undefined, events: [], lastSeq: -1, replayThroughSeq: 4 };+ model = makeModel({ turnActive: false, items: [] });+ const { rerender } = render(+ <ThreadView info={makeInfo({ status: 'ready', agent: CODEX, lastSeq: 4 })} />,+ );++ // The retained log lands, but an info snapshot has already raced past it.+ threadState = { info: undefined, events: [], lastSeq: 4, replayThroughSeq: 4 };+ model = makeModel({ turnActive: false, items: [notice(FIRST, 2)] });+ rerender(<ThreadView info={makeInfo({ status: 'ready', agent: CODEX, lastSeq: 8 })} />);+ expect(announcer().textContent).toBe('');++ // The live batch that catches delivery up carries the warning with it.+ threadState = { info: undefined, events: [], lastSeq: 8, replayThroughSeq: 4 };+ model = makeModel({ turnActive: true, items: [notice(FIRST, 2), notice(SECOND, 8)] });+ rerender(<ThreadView info={makeInfo({ status: 'ready', agent: CODEX, lastSeq: 8 })} />);++ await waitFor(() =>+ expect(announcer().textContent).toBe('Codex reported: Warning: skill "beta" was skipped'),+ );+ });++ test('stays silent when a reconnect replays a warning it already delivered', async () => {+ const info = makeInfo({ status: 'ready', agent: CODEX, lastSeq: 6 });+ threadState = { info: undefined, events: [], lastSeq: 6, replayThroughSeq: 5 };+ model = makeModel({ turnActive: true, items: [notice(FIRST, 6)] });+ const { rerender } = render(<ThreadView info={info} />);+ await waitFor(() =>+ expect(announcer().textContent).toBe('Codex reported: Warning: skill "alpha" was skipped'),+ );++ // Content alone cannot tell a second announcement from the first: they+ // are the same string. Count the writes instead.+ const spoken: string[] = [];+ const observer = new MutationObserver((records) => {+ for (const record of records) {+ for (const node of Array.from(record.addedNodes)) {+ const text = node.textContent ?? '';+ if (text !== '') spoken.push(text);+ }+ }+ });+ observer.observe(announcer(), { childList: true });++ // The socket drops and resubscribes. The server re-announces its retained+ // log, which now covers the warning already spoken — a bound that moves+ // with the log is what keeps the reader from hearing it a second time.+ threadState = { info: undefined, events: [], lastSeq: -1, replayThroughSeq: 6 };+ model = makeModel({ turnActive: false, items: [] });+ rerender(<ThreadView info={info} />);+ threadState = { info: undefined, events: [], lastSeq: 6, replayThroughSeq: 6 };+ model = makeModel({ turnActive: false, items: [notice(FIRST, 6)] });+ rerender(<ThreadView info={info} />);++ await new Promise((resolve) => setTimeout(resolve, 400));+ observer.disconnect();+ expect(spoken).toEqual([]);+ });++ test('leaves the active element alone when a warning arrives', async () => {+ model = makeModel({ turnActive: true, items: [] });+ const { rerender } = render(<ThreadView info={settled(5)} />);+ const composer = screen.getByTestId('agent-thread-composer');+ composer.focus();+ expect(document.activeElement).toBe(composer);++ threadState = { info: undefined, events: [], lastSeq: 6, replayThroughSeq: 5 };+ model = makeModel({ turnActive: true, items: [notice(FIRST, 6)] });+ rerender(<ThreadView info={settled(5)} />);++ await waitFor(() => expect(announcer().textContent).not.toBe(''));+ expect(document.activeElement).toBe(composer);+ });+});+/*** Sent messages render as markdown, like the agent's replies.*diff --git a/packages/app/src/components/acp/ThreadView.tsx b/packages/app/src/components/acp/ThreadView.tsxindex 0950eb76b..abad0e8b7 100644--- a/packages/app/src/components/acp/ThreadView.tsx+++ b/packages/app/src/components/acp/ThreadView.tsx@@ -46,6 +46,7 @@ import {SquarePen,Terminal as TerminalIcon,Trash2,+ TriangleAlert,Wrench,X,Zap,@@ -150,6 +151,7 @@ import { dispatchExternalLinkClick } from '@/lib/external-link';import { useWorkspace } from '@/lib/use-workspace';import { cn } from '@/lib/utils';import { AgentMarkdown } from './AgentMarkdown';+import { AgentNoticeAnnouncer } from './AgentNoticeAnnouncer';import { buildDocPathResolver, setDocPathResolver } from './doc-path-links';import { DocPathResolverReadyContext } from './doc-path-links-context';import {@@ -1042,6 +1044,14 @@ export function ThreadView({// those.const visibleEntries = foldedEntries.filter((_, index) => !revertedPositions.has(index));const visibleItems = visibleEntries.map((entry) => entry.item);+ // Read off the unfiltered fold: a warning is never superseded and never+ // reverted, so what the announcer sees is what the agent actually sent.+ const agentNotices =+ model === null+ ? []+ : model.items.flatMap((item) =>+ item.kind === 'agent_notice' ? [{ seq: item.seq, text: item.text }] : [],+ );let retryNoticeIndex = -1;if (canRetry) {for (let index = visibleItems.length - 1; index >= 0; index -= 1) {@@ -1182,6 +1192,13 @@ export function ThreadView({><DocPathResolverReadyContext value={resolverReady}><ThreadHeader info={info} followFile={followFile} onToggleFollow={toggleFollow} />+ {/* Outside every transcript branch so it is mounted before the first+ warning can arrive, whichever branch is on screen. */}+ <AgentNoticeAnnouncer+ notices={agentNotices}+ agentName={agentDisplayName(info.agent.name)}+ replayThroughSeq={state?.replayThroughSeq ?? Number.POSITIVE_INFINITY}+ />{model !== null && model.plan.length > 0 ? (<PlanChecklistplan={model.plan}@@ -2177,9 +2194,53 @@ function ThreadItem({onRestore={onRestore}/>);+ case 'agent_notice':+ return <AgentNoticeCard item={item} />;}}+/**+ * Runtime status the agent reported mid-turn, drawn as chrome so it cannot be+ * read as part of the answer.+ *+ * Severity is carried three ways — the written label, the glyph and the box's+ * own border — because color alone is unavailable to a reader who cannot see+ * it and is replaced outright by system colors under forced-colors mode. The+ * border survives both, which is why the box is the load-bearing cue and the+ * amber fill is only reinforcement.+ *+ * Passive by construction: `role="note"` rather than `alert`, and the card+ * itself offers no dismissal and no action, so a replayed transcript re-draws+ * it without interrupting and without offering the reader a control that would+ * do nothing. Arrival announcement is the thread-level live region's job, not+ * this row's.+ *+ * The agent's own words go through the same renderer as its replies and are+ * neither translated nor trimmed — only the surrounding label is app copy.+ */+function AgentNoticeCard({+ item,+}: {+ item: Extract<RenderedItem, { kind: 'agent_notice' }>;+}): ReactNode {+ const { t } = useLingui();+ return (+ <div+ role="note"+ className="rounded-md border border-amber-500/40 bg-amber-500/5 px-2 py-1.5 text-xs"+ data-testid="agent-thread-agent-notice"+ >+ <p className="flex items-center gap-1.5 font-medium text-amber-700 dark:text-amber-400">+ <TriangleAlert aria-hidden="true" className="size-3.5 shrink-0" />+ {t`Warning`}+ </p>+ <div className="mt-1 wrap-break-word text-foreground">+ <AgentMarkdown text={item.text} />+ </div>+ </div>+ );+}+/*** A thinking run, collapsed to one line. Collapsed even while streaming — the* tool-call card's comment records why expand-while-running fails here (thediff --git a/packages/app/src/components/acp/live-region-queue.dom.test.ts b/packages/app/src/components/acp/live-region-queue.dom.test.tsnew file mode 100644index 000000000..32b5d4208--- /dev/null+++ b/packages/app/src/components/acp/live-region-queue.dom.test.ts@@ -0,0 +1,153 @@+/**+ * The announcement mechanism on its own, without React: what reaches the live+ * region and in which order. The failure this guards against is silent — a+ * region whose text ends up correct while a screen reader heard one message+ * instead of three — so the assertions watch the region as it changes rather+ * than the settled text.+ */++import { afterEach, describe, expect, test, vi } from 'vitest';+import { CLEAR_TO_WRITE_MS, createLiveRegionQueue } from './live-region-queue';++const SPACING_MS = 150;++/**+ * Records the region's mutation history rather than its settled text. A+ * mutation observer is the closest stand-in available for how a screen reader+ * watches a live region: it sees each change as it happens, not the value left+ * behind at the end.+ *+ * A clear shows up as a removal with nothing added; a write shows up as the+ * inserted text.+ */+function watchRegion(): { region: HTMLElement; steps: string[] } {+ const region = document.createElement('div');+ document.body.append(region);+ const steps: string[] = [];+ const observer = new MutationObserver((records) => {+ for (const record of records) {+ if (record.addedNodes.length === 0) {+ steps.push('<cleared>');+ continue;+ }+ for (const node of record.addedNodes) steps.push(node.textContent ?? '');+ }+ });+ observer.observe(region, { childList: true, characterData: true, subtree: true });+ return { region, steps };+}++afterEach(() => {+ vi.useRealTimers();+ document.body.replaceChildren();+});++describe('live region queue', () => {+ test('announces a single message', () => {+ vi.useFakeTimers();+ const { region } = watchRegion();+ const queue = createLiveRegionQueue({ region: () => region, spacingMs: SPACING_MS });++ queue.announce(['first warning']);+ vi.advanceTimersByTime(CLEAR_TO_WRITE_MS);++ expect(region.textContent).toBe('first warning');+ queue.dispose();+ });++ test('spaces a burst so a later message cannot overwrite an unheard one', () => {+ vi.useFakeTimers();+ const { region } = watchRegion();+ const queue = createLiveRegionQueue({ region: () => region, spacingMs: SPACING_MS });++ queue.announce(['first warning', 'second warning', 'third warning']);++ vi.advanceTimersByTime(CLEAR_TO_WRITE_MS);+ expect(region.textContent).toBe('first warning');+ vi.advanceTimersByTime(SPACING_MS + CLEAR_TO_WRITE_MS);+ expect(region.textContent).toBe('second warning');+ vi.advanceTimersByTime(SPACING_MS + CLEAR_TO_WRITE_MS);+ expect(region.textContent).toBe('third warning');+ queue.dispose();+ });++ test('empties the region in its own task before repeating an identical message', () => {+ vi.useFakeTimers();+ const { region } = watchRegion();+ const queue = createLiveRegionQueue({ region: () => region, spacingMs: SPACING_MS });++ queue.announce(['the agent reported a warning', 'the agent reported a warning']);+ vi.advanceTimersByTime(CLEAR_TO_WRITE_MS);+ expect(region.textContent).toBe('the agent reported a warning');++ // The clear has to be observable on its own. A browser folds every DOM+ // change made in one task into a single accessibility-tree update, so a+ // clear and a write landing together leave the region's content+ // unchanged — which is the silent no-op the clear exists to avoid.+ vi.advanceTimersByTime(SPACING_MS);+ expect(region.textContent).toBe('');++ vi.advanceTimersByTime(CLEAR_TO_WRITE_MS);+ expect(region.textContent).toBe('the agent reported a warning');+ queue.dispose();+ });++ test('reaches the region as write, clear, write for a repeated message', async () => {+ const { region, steps } = watchRegion();+ const queue = createLiveRegionQueue({ region: () => region, spacingMs: 0 });++ queue.announce(['the agent reported a warning', 'the agent reported a warning']);+ // Real timers: the drain has to actually run, and a mutation observer+ // delivers on the microtask queue rather than on a timer.+ await new Promise((resolve) => setTimeout(resolve, CLEAR_TO_WRITE_MS * 4));++ expect(steps).toEqual([+ 'the agent reported a warning',+ '<cleared>',+ 'the agent reported a warning',+ ]);+ queue.dispose();+ });++ test('holds the spacing across separate arrivals, not just within one burst', () => {+ vi.useFakeTimers();+ const { region } = watchRegion();+ const queue = createLiveRegionQueue({ region: () => region, spacingMs: SPACING_MS });++ queue.announce(['first warning']);+ vi.advanceTimersByTime(CLEAR_TO_WRITE_MS);+ queue.announce(['second warning']);++ // Half a spacing interval later the first message is still standing.+ vi.advanceTimersByTime(SPACING_MS / 2);+ expect(region.textContent).toBe('first warning');+ vi.advanceTimersByTime(SPACING_MS / 2 + CLEAR_TO_WRITE_MS);+ expect(region.textContent).toBe('second warning');+ queue.dispose();+ });++ test('announces nothing for an empty batch', () => {+ vi.useFakeTimers();+ const { region } = watchRegion();+ const queue = createLiveRegionQueue({ region: () => region, spacingMs: SPACING_MS });++ queue.announce([]);+ vi.advanceTimersByTime(SPACING_MS * 4);++ expect(region.textContent).toBe('');+ queue.dispose();+ });++ test('drops queued messages once disposed', () => {+ vi.useFakeTimers();+ const { region } = watchRegion();+ const queue = createLiveRegionQueue({ region: () => region, spacingMs: SPACING_MS });++ queue.announce(['first warning', 'second warning']);+ vi.advanceTimersByTime(CLEAR_TO_WRITE_MS);+ queue.dispose();+ vi.advanceTimersByTime(SPACING_MS * 4);++ expect(region.textContent).toBe('first warning');+ });+});diff --git a/packages/app/src/components/acp/live-region-queue.ts b/packages/app/src/components/acp/live-region-queue.tsnew file mode 100644index 000000000..58a9d4035--- /dev/null+++ b/packages/app/src/components/acp/live-region-queue.ts@@ -0,0 +1,87 @@+/**+ * Serializing writer for one polite live region.+ *+ * Two properties assistive technology needs that a plain `textContent = message`+ * assignment does not provide:+ *+ * - **Consecutive messages are spaced.** A second write in the same tick+ * replaces the first before a screen reader has observed it, so a burst of+ * arrivals is heard as a single announcement, or as only the last one.+ * - **An identical message announces again.** Screen readers speak observed+ * content *changes*, so re-assigning the same string is a silent no-op. MDN's+ * live-region guidance is to clear the region before injecting the new+ * content, and the clear has to land in its own task: a clear and a write+ * inside one task collapse into a single accessibility-tree update whose net+ * content is unchanged, which is the very no-op being worked around.+ *+ * Writes are imperative rather than React state because React batches, and a+ * batched pair of state updates collapses to the final string, which is exactly+ * the overwrite this queue exists to prevent.+ *+ * `SelectionAnnouncer` in the editor writes its own region the same way, minus+ * the queue — it announces one debounced selection rather than a burst, so it+ * has nothing to serialize.+ *+ * The alternative shape is an additions-based region — `aria-relevant`+ * `additions`, `aria-atomic` false — that appends one child per message and+ * gets both properties from the append itself, with no timer and no+ * serialization state. `sonner`, already a dependency here, announces toasts+ * that way. It is not adopted for this region because a transcript is+ * long-lived and unbounded, so the region would accrete one child per warning+ * for as long as the thread stays open.+ */+export interface LiveRegionQueue {+ /** Queue messages for announcement, spoken in the order given. */+ announce(messages: readonly string[]): void;+ /** Drop anything still queued and cancel the pending drain. */+ dispose(): void;+}++/**+ * How long the region stays empty before its next message lands. Only has to+ * outlast the browser's own accessibility-tree update so the empty state is+ * observed on its own; it is not a reading pause.+ */+export const CLEAR_TO_WRITE_MS = 50;++export function createLiveRegionQueue(options: {+ /** Resolved per write, since the region's ref is empty until after mount. */+ region: () => HTMLElement | null;+ spacingMs: number;+}): LiveRegionQueue {+ const pending: string[] = [];+ let timer: ReturnType<typeof setTimeout> | null = null;++ const drain = (): void => {+ const next = pending.shift();+ if (next === undefined) {+ timer = null;+ return;+ }+ const cleared = options.region();+ if (cleared !== null) cleared.textContent = '';+ timer = setTimeout(() => {+ const region = options.region();+ if (region !== null) region.textContent = next;+ // Keep the slot held even with nothing else queued: an arrival landing a+ // few milliseconds from now must still wait out the spacing rather than+ // overwrite what was just written.+ timer = setTimeout(drain, options.spacingMs);+ }, CLEAR_TO_WRITE_MS);+ };++ return {+ announce(messages: readonly string[]): void {+ if (messages.length === 0) return;+ pending.push(...messages);+ if (timer === null) drain();+ },+ dispose(): void {+ pending.length = 0;+ if (timer !== null) {+ clearTimeout(timer);+ timer = null;+ }+ },+ };+}diff --git a/packages/app/src/components/acp/transcript-item-id.test.ts b/packages/app/src/components/acp/transcript-item-id.test.tsindex 73682df6f..1c2920be8 100644--- a/packages/app/src/components/acp/transcript-item-id.test.ts+++ b/packages/app/src/components/acp/transcript-item-id.test.ts@@ -8,6 +8,14 @@ const msg = (messageId: string, role: 'user' | 'agent' | 'thought' = 'agent'): Rconst tool = (toolCallId: string): RenderedItem =>({ kind: 'tool_call', toolCallId }) as RenderedItem;const notice = (): RenderedItem => ({ kind: 'notice', text: '', tone: 'info' }) as RenderedItem;+const agentNotice = (text = 'Warning: something\n\n'): RenderedItem =>+ ({+ kind: 'agent_notice',+ source: 'codex_legacy',+ severity: 'warning',+ text,+ seq: 0,+ }) as RenderedItem;describe('transcriptItemId', () => {it('is unique across sibling messages that share the default messageId', () => {@@ -32,4 +40,20 @@ describe('transcriptItemId', () => {it('is stable for a coalesced message re-rendered at the same index', () => {expect(transcriptItemId(msg('default'), 3)).toBe(transcriptItemId(msg('default'), 3));});++ it('distinguishes two identical runtime warnings and a failure notice at the same positions', () => {+ // Same text twice: nothing about the payload separates them, so the row+ // identity has to come from position alone.+ const items: RenderedItem[] = [agentNotice(), agentNotice(), notice()];+ expect(new Set(items.map(transcriptItemId)).size).toBe(items.length);+ });++ it('leaves the ids of preceding rows untouched whether or not a warning follows', () => {+ const head: RenderedItem[] = [msg('default', 'user'), tool('call-1')];+ const withWarning = [...head, agentNotice(), msg('default', 'agent')];+ const withoutWarning = [...head, msg('default', 'agent')];+ expect(withWarning.slice(0, head.length).map(transcriptItemId)).toEqual(+ withoutWarning.slice(0, head.length).map(transcriptItemId),+ );+ });});diff --git a/packages/app/src/components/acp/transcript-item-id.ts b/packages/app/src/components/acp/transcript-item-id.tsindex 61b973405..90948b784 100644--- a/packages/app/src/components/acp/transcript-item-id.ts+++ b/packages/app/src/components/acp/transcript-item-id.ts@@ -24,5 +24,9 @@ export function transcriptItemId(item: RenderedItem, index: number): string {return `pi-bridge:${item.prompt?.requestId ?? index}`;case 'notice':return `notice:${index}`;+ case 'agent_notice':+ // Runtime status carries no producer identity of its own, and two+ // identical warnings in one turn are two rows.+ return `agent-notice:${index}`;}}diff --git a/packages/app/src/env.d.ts b/packages/app/src/env.d.tsindex 66b226dea..6a0eb9b8e 100644--- a/packages/app/src/env.d.ts+++ b/packages/app/src/env.d.ts@@ -39,6 +39,7 @@ declare namespace globalThis {import type { Editor } from '@tiptap/core';import type { GraphNodeVisualState } from '@/components/graph-view-utils';import type { ProviderPool } from '@/editor/provider-pool';+ import type { AcpThreadHarness } from '@/lib/acp/dev-thread-harness';var __graphHarness:| {@@ -62,6 +63,13 @@ declare namespace globalThis {isSimulationSettled: () => boolean;}| undefined;+ /**+ * DEV-only: injects synthetic ACP thread frames at the socket boundary so a+ * browser test can drive the real client, fold, and transcript renderer+ * without an agent process. Tree-shaken from production bundles by the+ * `import.meta.env.DEV` guard in `AgentThreadClientBinder.tsx`.+ */+ var __acpThreadHarness: AcpThreadHarness | undefined;var __providerPool: ProviderPool | undefined;var __activeProvider: HocuspocusProvider | null;/**diff --git a/packages/app/src/lib/acp/dev-thread-harness.dom.test.tsx b/packages/app/src/lib/acp/dev-thread-harness.dom.test.tsxnew file mode 100644index 000000000..30ec09d72--- /dev/null+++ b/packages/app/src/lib/acp/dev-thread-harness.dom.test.tsx@@ -0,0 +1,234 @@+/**+ * The injection harness is only worth anything if the frames it hands the+ * client travel the same road a real socket message does, so these tests+ * assert against what came out the far end — the store, the folded render+ * model, and finally the mounted transcript — rather than against the frames+ * that went in.+ *+ * The last describe block is the one no cheaper test can replace: it renders+ * the real `ThreadView` over the real module-scope client, so a harness that+ * stopped reaching the fold, or a fold whose output the renderer ignored,+ * fails here and nowhere else.+ */++import type {+ SessionUpdate,+ ThreadAgentInfo,+ ThreadInfo,+} from '@inkeep/open-knowledge-core/acp/thread-protocol';+import { cleanup, render, screen } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { MockComposerMentionInput } from '@/components/acp/composer-mention-input.test-helper';+import { TooltipProvider } from '@/components/ui/tooltip';+import { DEV_HARNESS_SENTINEL } from '../../../scripts/check-dev-harness-absent.mjs';+import { type AcpThreadHarness, installAcpThreadHarness } from './dev-thread-harness';+import { AgentThreadClient } from './thread-client';+import type { RenderedItem } from './thread-event-model';++// Only the surfaces jsdom genuinely cannot host are doubled: the editor's+// Y.Doc context, the workspace lookup, the ProseMirror-backed composer, and+// toasts. The thread client, the fold, the markdown renderer, and the+// transcript are the shipping modules — doubling any of them would hide the+// break this file exists to catch.+vi.doMock('@/editor/DocumentContext', () => ({+ useDocumentContext: () => ({ systemProvider: null }),+}));+vi.doMock('@/lib/use-workspace', () => ({ useWorkspace: () => null }));+vi.doMock('sonner', () => ({+ toast: { error: vi.fn(), success: vi.fn(), info: vi.fn() },+}));+vi.doMock('@/editor/ComposerMentionInput', () => ({+ ComposerMentionInput: MockComposerMentionInput,+}));++const { ThreadView } = await import('@/components/acp/ThreadView');+const { getAgentThreadClient } = await import('./thread-client');++const CODEX: ThreadAgentInfo = { id: 'codex-acp', name: 'Codex', source: 'registry' };+const CLAUDE: ThreadAgentInfo = { id: 'claude-acp', name: 'Claude Agent', source: 'registry' };++function chunk(text: string): SessionUpdate {+ return {+ sessionUpdate: 'agent_message_chunk',+ content: { type: 'text', text },+ } as SessionUpdate;+}++function isMessage(item: RenderedItem): item is Extract<RenderedItem, { kind: 'message' }> {+ return item.kind === 'message';+}++/** Every message body the fold produced, in transcript order. */+function messageTexts(client: AgentThreadClient, threadId: string): string[] {+ return (client.getThreadModel(threadId)?.items ?? []).filter(isMessage).map((item) => item.text);+}++function takeHarness(): AcpThreadHarness {+ const installed = window.__acpThreadHarness;+ if (installed === undefined) throw new Error('harness did not install');+ return installed;+}++describe('injected frames reach the store through the socket path', () => {+ let client: AgentThreadClient;+ let harness: AcpThreadHarness;+ let uninstall: () => void;++ beforeEach(() => {+ client = new AgentThreadClient();+ uninstall = installAcpThreadHarness(client);+ harness = takeHarness();+ });++ afterEach(() => {+ uninstall();+ });++ test('an opened thread carries the agent identity it was given', () => {+ const threadId = harness.openThread({ agent: CODEX, title: 'Codex session' });++ const info = client.getThread(threadId)?.info;+ expect(info?.agent).toEqual(CODEX);+ expect(info?.title).toBe('Codex session');+ });++ test('two threads can run different agents at once', () => {+ const codexThread = harness.openThread({ agent: CODEX });+ const claudeThread = harness.openThread({ agent: CLAUDE });++ expect(client.getThread(codexThread)?.info.agent.id).toBe('codex-acp');+ expect(client.getThread(claudeThread)?.info.agent.id).toBe('claude-acp');+ });++ test('live updates fold into transcript messages in arrival order', () => {+ const threadId = harness.openThread({ agent: CODEX });++ harness.pushUpdates(threadId, [chunk('first '), chunk('second')]);++ expect(messageTexts(client, threadId)).toEqual(['first second']);+ });++ test('a replayed transcript folds identically to the same updates arriving live', () => {+ const updates = [chunk('alpha'), chunk('beta')];+ const liveThread = harness.openThread({ agent: CODEX });+ harness.pushUpdates(liveThread, updates);++ const replayedThread = harness.replayThread({ agent: CODEX }, updates);++ expect(messageTexts(client, replayedThread)).toEqual(messageTexts(client, liveThread));+ });++ test('a live update after a replay continues the same transcript', () => {+ const threadId = harness.replayThread({ agent: CODEX }, [chunk('history')]);++ harness.pushUpdates(threadId, [chunk(' and more')]);++ expect(messageTexts(client, threadId)).toEqual(['history and more']);+ });++ test('a replay announces the retained log it is about to deliver', () => {+ const updates = [chunk('alpha'), chunk('beta'), chunk('gamma')];++ const threadId = harness.replayThread({ agent: CODEX }, updates);++ // The transcript reaching the announced bound is how a consumer knows the+ // replay is done and anything further is new. A live thread announces an+ // empty log, so its very first update is already past the bound.+ const state = client.getThread(threadId);+ expect(state?.info.lastSeq).toBe(updates.length - 1);+ expect(state?.lastSeq).toBe(updates.length - 1);+ expect(client.getThread(harness.openThread({ agent: CODEX }))?.info.lastSeq).toBe(-1);+ });++ test('a raw frame is dispatched verbatim', () => {+ const threadId = harness.openThread({ agent: CODEX });++ harness.frame({+ op: 'event',+ threadId,+ seq: 0,+ event: { kind: 'title_changed', title: 'Renamed by frame', ts: 1 },+ });++ expect(client.getThread(threadId)?.info.title).toBe('Renamed by frame');+ });++ test('reset drops injected threads and leaves server-owned ones alone', () => {+ const serverThread: ThreadInfo = {+ threadId: 'from-server',+ agent: CLAUDE,+ title: 'Real thread',+ status: 'ready',+ createdAt: 1,+ lastActivityAt: 1,+ lastSeq: -1,+ };+ harness.frame({ op: 'info', info: serverThread });+ const injected = harness.openThread({ agent: CODEX });++ harness.reset();++ expect(client.getThread(injected)).toBeNull();+ expect(client.getThread('from-server')?.info.title).toBe('Real thread');+ });++ test('uninstalling withdraws the harness from the window', () => {+ uninstall();++ expect(window.__acpThreadHarness).toBeUndefined();+ });++ test('publishes itself on the exact global the production-artifact gate scans for', () => {+ // That gate greps emitted chunks for a bare string, which stays green+ // forever once the name it looks for stops being the name anything+ // writes. This is the only place the two can be held together.+ expect(Reflect.get(window, DEV_HARNESS_SENTINEL)).toBe(harness);+ });+});++describe('injected frames reach the mounted transcript', () => {+ let harness: AcpThreadHarness;+ let uninstall: () => void;++ beforeEach(() => {+ uninstall = installAcpThreadHarness(getAgentThreadClient());+ harness = takeHarness();+ });++ afterEach(() => {+ harness.reset();+ uninstall();+ cleanup();+ });++ test('an injected agent message paints in the transcript', async () => {+ const threadId = harness.openThread({ agent: CODEX, title: 'Injected' });+ harness.pushUpdates(threadId, [chunk('Injected answer body.')]);+ const info = getAgentThreadClient().getThread(threadId)?.info;+ if (info === undefined) throw new Error('thread missing from the client');++ render(+ <TooltipProvider>+ <ThreadView info={info} active />+ </TooltipProvider>,+ );++ expect(await screen.findByText('Injected answer body.')).toBeTruthy();+ });++ test('a replayed transcript paints the same body as a live arrival', async () => {+ const threadId = harness.replayThread({ agent: CODEX, title: 'Replayed' }, [+ chunk('Replayed answer body.'),+ ]);+ const info = getAgentThreadClient().getThread(threadId)?.info;+ if (info === undefined) throw new Error('thread missing from the client');++ render(+ <TooltipProvider>+ <ThreadView info={info} active />+ </TooltipProvider>,+ );++ expect(await screen.findByText('Replayed answer body.')).toBeTruthy();+ });+});diff --git a/packages/app/src/lib/acp/dev-thread-harness.ts b/packages/app/src/lib/acp/dev-thread-harness.tsnew file mode 100644index 000000000..33d08ad8e--- /dev/null+++ b/packages/app/src/lib/acp/dev-thread-harness.ts@@ -0,0 +1,176 @@+/**+ * Development-only injection seam for the ACP thread transport.+ *+ * A real agent thread needs a spawned agent process, a negotiated session, and+ * a producer that happens to emit the shape under test. None of that is+ * reachable from a browser test, which is why the interesting rendering and+ * accessibility behaviour of the transcript has only ever been exercised+ * against hand-authored render models. Those bypass the client and the fold+ * entirely, so a classifier that never fires or a render arm that is never+ * reached still passes.+ *+ * This harness closes that gap by entering at the socket boundary instead:+ * frames are handed to {@link AgentThreadClient.receiveServerFrame} as raw+ * JSON, exactly as `onmessage` delivers them. Everything downstream — frame+ * dispatch, the event log, the incremental fold, the renderer, the browser's+ * own cascade — is the production path, unmodified and unaware that the bytes+ * were synthesized.+ *+ * Nothing here reaches a production bundle: the module is imported only from+ * inside an `import.meta.env.DEV` branch, which Vite resolves to a constant+ * false and Rollup then eliminates along with the dynamic import.+ */++import type {+ SessionUpdate,+ ThreadAgentInfo,+ ThreadEvent,+ ThreadInfo,+ ThreadServerFrame,+ ThreadStatus,+} from '@inkeep/open-knowledge-core/acp/thread-protocol';+import type { AgentThreadClient } from './thread-client';++/** How a synthetic thread should present before any transcript arrives. */+interface DevThreadOptions {+ /**+ * Which agent the thread is running. Required, and deliberately so: the+ * transcript's interpretation of a payload can depend on which producer sent+ * it, so a default here would let a test assert a classification it never+ * actually asked for.+ */+ readonly agent: ThreadAgentInfo;+ /** Defaults to a fresh unique id. */+ readonly threadId?: string;+ readonly title?: string;+ readonly status?: ThreadStatus;+}++export interface AcpThreadHarness {+ /**+ * Put an empty synthetic thread on screen and return its id. The transcript+ * that follows arrives live, through {@link AcpThreadHarness.pushUpdates}.+ */+ openThread(options: DevThreadOptions): string;+ /**+ * Live arrival: one `event` frame per update, in order, as a streaming turn+ * delivers them.+ */+ pushUpdates(threadId: string, updates: readonly SessionUpdate[]): void;+ /**+ * History replay: subscribe a thread and hydrate its whole transcript from+ * the retained log in one batch, as opening an existing thread does. Takes+ * the same updates {@link AcpThreadHarness.pushUpdates} accepts so the two+ * lifecycles can be compared on identical input.+ */+ replayThread(options: DevThreadOptions, updates: readonly SessionUpdate[]): string;+ /**+ * Deliver one frame verbatim, for shapes the convenience methods above do+ * not cover.+ */+ frame(frame: ThreadServerFrame): void;+ /**+ * Drop every thread this harness opened, leaving any the server owns alone.+ */+ reset(): void;+}++let syntheticCounter = 0;++function makeThreadInfo(options: DevThreadOptions, threadId: string, lastSeq: number): ThreadInfo {+ const now = Date.now();+ return {+ threadId,+ agent: options.agent,+ title: options.title ?? 'Injected thread',+ status: options.status ?? 'ready',+ createdAt: now,+ lastActivityAt: now,+ modes: null,+ configOptions: null,+ lastSeq,+ archived: false,+ };+}++function toEvent(update: SessionUpdate): ThreadEvent {+ return { kind: 'session_update', update, ts: Date.now() };+}++/**+ * Publish the harness on `window.__acpThreadHarness` and return its uninstaller.+ * A no-op outside development, so the caller needs no gate of its own beyond+ * the one that keeps this module out of the bundle.+ */+export function installAcpThreadHarness(client: AgentThreadClient): () => void {+ if (!import.meta.env.DEV) return () => {};++ const owned = new Set<string>();++ const deliver = (frame: ThreadServerFrame): void => {+ client.receiveServerFrame(JSON.stringify(frame));+ };++ // `lastSeq` is the retained log's upper bound, which the server announces+ // before it replays anything. A consumer that has to tell history from live+ // arrival watches for the transcript to reach it, so a replay that claimed an+ // empty log would read as a burst of brand-new activity.+ const subscribe = (options: DevThreadOptions, lastSeq: number): string => {+ syntheticCounter += 1;+ const threadId = options.threadId ?? `injected-${syntheticCounter}`;+ owned.add(threadId);+ deliver({+ op: 'subscribed',+ threadId,+ fromSeq: 0,+ info: makeThreadInfo(options, threadId, lastSeq),+ });+ return threadId;+ };++ const harness: AcpThreadHarness = {+ openThread: (options) => subscribe(options, -1),++ pushUpdates(threadId, updates) {+ for (const update of updates) {+ // Read the seq back from the store rather than counting locally: the+ // client drops any event whose seq it already holds, so a private+ // counter that drifted would silently swallow updates.+ const seq = (client.getThread(threadId)?.lastSeq ?? -1) + 1;+ deliver({ op: 'event', threadId, seq, event: toEvent(update) });+ }+ },++ replayThread(options, updates) {+ const threadId = subscribe(options, updates.length - 1);+ if (updates.length > 0) {+ deliver({+ op: 'events',+ threadId,+ fromSeq: 0,+ events: updates.map(toEvent),+ });+ }+ return threadId;+ },++ frame: deliver,++ reset() {+ if (owned.size === 0) return;+ // A `threads` frame is the server's authoritative roster, and the client+ // drops whatever it omits. Re-listing the threads this harness does not+ // own is what keeps the reset from evicting real ones alongside them.+ const survivors = client.getThreads().filter((info) => !owned.has(info.threadId));+ owned.clear();+ deliver({ op: 'threads', threads: survivors });+ },+ };++ window.__acpThreadHarness = harness;+ return () => {+ if (window.__acpThreadHarness === harness) {+ delete window.__acpThreadHarness;+ }+ };+}diff --git a/packages/app/src/lib/acp/thread-client.test.ts b/packages/app/src/lib/acp/thread-client.test.tsindex 350ee1a7d..0da9a175b 100644--- a/packages/app/src/lib/acp/thread-client.test.ts+++ b/packages/app/src/lib/acp/thread-client.test.ts@@ -5,6 +5,9 @@ import type {ThreadServerFrame,} from '@inkeep/open-knowledge-core/acp/thread-protocol';import { describe, expect, test } from 'vitest';+import fixture from '../../../../../test-support/fixtures/codex-legacy-warning-envelopes.json' with {+ type: 'json',+};import { AgentThreadClient, ThreadChannelUnavailableError } from './thread-client';/**@@ -484,3 +487,152 @@ describe('unread affordance (PRD-8021)', () => {expect(notifications).toBe(5);});});++describe('raw frame ingestion', () => {+ const info: ThreadInfo = {+ threadId: 'raw-1',+ agent: { id: 'codex-acp', name: 'Codex', source: 'registry' },+ title: 'Raw',+ status: 'ready',+ createdAt: 1,+ lastActivityAt: 1,+ lastSeq: -1,+ };++ test('a JSON payload lands in the store the same as a parsed frame would', () => {+ const client = new AgentThreadClient();++ client.receiveServerFrame(JSON.stringify({ op: 'info', info }));++ expect(client.getThread('raw-1')?.info.title).toBe('Raw');+ });++ test('an unparseable payload is dropped instead of thrown', () => {+ const client = new AgentThreadClient();+ client.receiveServerFrame(JSON.stringify({ op: 'info', info }));++ // A peer in another process owns these bytes; one malformed frame must+ // not take the channel — or the transcript already on screen — with it.+ expect(() => client.receiveServerFrame('{ not json')).not.toThrow();+ expect(client.getThread('raw-1')?.info.title).toBe('Raw');+ });+});++/**+ * The fold reads the producer's identity off the subscribed thread, so a+ * classification that works in a unit fold still shows nothing on screen if+ * the client never hands that identity over. These drive the socket boundary+ * — raw JSON into `receiveServerFrame`, exactly as `onmessage` delivers it —+ * and read the model the view would render.+ */+describe('render-model agent identity', () => {+ const WARNING_TEXT = fixture.candidates[0].update.content.text;++ const infoFor = (agent: {+ id: string;+ name: string;+ source: 'registry' | 'custom';+ }): ThreadInfo =>+ ({+ threadId: 'ident-1',+ agent,+ title: 'Identity',+ status: 'ready',+ createdAt: 1,+ lastActivityAt: 1,+ lastSeq: -1,+ }) satisfies ThreadInfo;++ const warningEvent = (ts: number): ThreadEvent => ({+ kind: 'session_update',+ update: structuredClone(fixture.candidates[0].update) as never,+ ts,+ });++ function subscribed(agent: Parameters<typeof infoFor>[0]): AgentThreadClient {+ const client = new AgentThreadClient();+ client.receiveServerFrame(+ JSON.stringify({ op: 'subscribed', threadId: 'ident-1', fromSeq: 0, info: infoFor(agent) }),+ );+ return client;+ }++ test('a warning on a registry Codex thread reaches the view as runtime status', () => {+ const client = subscribed(fixture.agents.codexRegistry);++ client.receiveServerFrame(+ JSON.stringify({ op: 'event', threadId: 'ident-1', seq: 0, event: warningEvent(1) }),+ );++ expect(client.getThreadModel('ident-1')?.items).toEqual([+ {+ kind: 'agent_notice',+ source: 'codex_legacy',+ severity: 'warning',+ text: WARNING_TEXT,+ seq: 0,+ },+ ]);+ });++ test('the same bytes on another registry agent reach the view as prose', () => {+ const client = subscribed(fixture.agents.claudeRegistry);++ client.receiveServerFrame(+ JSON.stringify({ op: 'event', threadId: 'ident-1', seq: 0, event: warningEvent(1) }),+ );++ const items = client.getThreadModel('ident-1')?.items ?? [];+ expect(items.map((item) => item.kind)).toEqual(['message']);+ expect(items[0]).toMatchObject({ role: 'agent', text: WARNING_TEXT });+ });++ test('a replay that opens above seq 0 still stamps every notice with its wire seq', () => {+ // A thread whose in-memory window has trimmed past the durable log's reach+ // replays from the trim point, so the first batch a client sees can open+ // above seq 0. Position in the store's array is what the fold reads the+ // seq off, so a batch that lands without its predecessors must not shift+ // every later event below its true seq — the announcer compares that+ // number against the replay bound, and understating it is silent.+ const client = subscribed(fixture.agents.codexRegistry);++ client.receiveServerFrame(+ JSON.stringify({+ op: 'events',+ threadId: 'ident-1',+ fromSeq: 4,+ events: [warningEvent(1), warningEvent(2)],+ }),+ );++ const notices = (client.getThreadModel('ident-1')?.items ?? []).filter(+ (item) => item.kind === 'agent_notice',+ );+ expect(notices.map((item) => (item as { seq: number }).seq)).toEqual([4, 5]);+ // The invariant the fold reads seqs off, stated directly.+ const stored = client.getThread('ident-1');+ expect(stored?.lastSeq).toBe(5);+ expect(stored?.events.length).toBe((stored?.lastSeq ?? -1) + 1);+ });++ test('a batched replay and a live arrival of the same events agree', () => {+ const events = [warningEvent(1), warningEvent(2)];++ const live = subscribed(fixture.agents.codexRegistry);+ events.forEach((event, index) => {+ live.receiveServerFrame(+ JSON.stringify({ op: 'event', threadId: 'ident-1', seq: index, event }),+ );+ });++ const replayed = subscribed(fixture.agents.codexRegistry);+ replayed.receiveServerFrame(+ JSON.stringify({ op: 'events', threadId: 'ident-1', fromSeq: 0, events }),+ );++ expect(replayed.getThreadModel('ident-1')?.items).toEqual(+ live.getThreadModel('ident-1')?.items,+ );+ expect(replayed.getThreadModel('ident-1')?.items).toHaveLength(2);+ });+});diff --git a/packages/app/src/lib/acp/thread-client.ts b/packages/app/src/lib/acp/thread-client.tsindex cb6dda8fe..0f65cfa67 100644--- a/packages/app/src/lib/acp/thread-client.ts+++ b/packages/app/src/lib/acp/thread-client.ts@@ -37,6 +37,19 @@ export interface ThreadState {/** Copy-on-write: a new array reference per appended event. */readonly events: readonly ThreadEvent[];readonly lastSeq: number;+ /**+ * Upper bound of the replay the server is about to deliver, taken from the+ * `subscribed` frame and held still afterwards.+ *+ * `info.lastSeq` cannot serve here even though it carries the same number at+ * subscribe time: the server advances it the moment it appends while event+ * batches coalesce on a timer, so it races ahead of the transcript for the+ * rest of the session. Anything at or below this bound was already history+ * when the subscription opened; anything above it arrived while the reader+ * was watching. Infinity until the server says otherwise, so an unbounded+ * window is treated as all-history rather than all-new.+ */+ readonly replayThroughSeq: number;}export type ThreadConnectionStatus = 'idle' | 'connecting' | 'open' | 'closed';@@ -53,6 +66,17 @@ interface PendingQueueEdit {timer: ReturnType<typeof setTimeout>;}+/**+ * Placeholder for a seq the server never delivered. Renders nothing (the fold+ * has no arm for this kind) and exists only to keep an event's position in the+ * transcript array equal to its seq.+ */+const SEQ_GAP_EVENT: ThreadEvent = Object.freeze({+ kind: 'agent_stderr',+ line: '[missing log entry]',+ ts: 0,+});+const RECONNECT_MIN_MS = 500;const RECONNECT_MAX_MS = 15_000;const CREATE_TIMEOUT_MS = 30_000;@@ -238,7 +262,7 @@ export class AgentThreadClient {if (state === undefined) return null;let builder = this.modelBuilders.get(threadId);if (builder === undefined) {- builder = new ThreadRenderModelBuilder();+ builder = new ThreadRenderModelBuilder(state.info.agent);this.modelBuilders.set(threadId, builder);}return builder.sync(state.events);@@ -420,7 +444,12 @@ export class AgentThreadClient {this.send({ op: 'unsubscribe', threadId });this.openedArchived.delete(threadId);this.modelBuilders.delete(threadId);- this.threads.set(threadId, { info: state.info, events: [], lastSeq: -1 });+ this.threads.set(threadId, {+ info: state.info,+ events: [],+ lastSeq: -1,+ replayThroughSeq: Number.POSITIVE_INFINITY,+ });this.bump();return;}@@ -590,13 +619,7 @@ export class AgentThreadClient {ws.onmessage = (event) => {if (this.ws !== ws) return;if (typeof event.data !== 'string') return;- let frame: ThreadServerFrame;- try {- frame = JSON.parse(event.data) as ThreadServerFrame;- } catch {- return;- }- this.handleFrame(frame);+ this.receiveServerFrame(event.data);};ws.onclose = () => {if (this.ws !== ws) return;@@ -677,6 +700,27 @@ export class AgentThreadClient {}}+ /**+ * The transport's whole inbound surface: one raw socket payload in, one+ * store mutation out. Malformed JSON is dropped rather than thrown, because+ * the peer is a separate process whose bytes this client does not control+ * and one bad frame must not take the channel down with it.+ *+ * Named and reachable so a caller can hand the client a frame without a+ * socket. Development tooling uses that to drive the real store, fold, and+ * renderer over synthesized transcripts; the socket remains the only caller+ * that ships.+ */+ receiveServerFrame(data: string): void {+ let frame: ThreadServerFrame;+ try {+ frame = JSON.parse(data) as ThreadServerFrame;+ } catch {+ return;+ }+ this.handleFrame(frame);+ }+private handleFrame(frame: ThreadServerFrame): void {switch (frame.op) {case 'created': {@@ -748,6 +792,11 @@ export class AgentThreadClient {}case 'subscribed': {this.upsertInfo(frame.info);+ const state = this.threads.get(frame.threadId);+ if (state !== undefined) {+ this.threads.set(frame.threadId, { ...state, replayThroughSeq: frame.info.lastSeq });+ this.bump();+ }return;}case 'queue_edited': {@@ -829,6 +878,21 @@ export class AgentThreadClient {* Append consecutive events starting at `fromSeq`, skipping any the store* already has (replay/flush overlap) — one array copy and one listener* notification per batch, however many events arrived.+ *+ * Position in `events` is the event's seq, and consumers read it that way,+ * so a batch that opens above the tail is padded rather than closed up. A+ * replay whose durable log cannot supply the low range starts above seq 0,+ * and closing the hole would shift every later event below its true seq —+ * the same reason the persistence reader substitutes a placeholder for a+ * line it cannot parse instead of dropping it.+ *+ * The pad is as long as the hole, which reads as unbounded but is not: the+ * server replays contiguously from the seq it names, so a hole only opens+ * where the durable log has fewer lines than the thread has events, and its+ * size is that thread's own history at the moment persistence broke.+ * Refusing the batch instead would bound it, at the cost of freezing the+ * transcript for good — a reconnect resubscribes from the same tail, so a+ * server that still cannot supply the low range never gets past it.*/private appendEvents(threadId: string, fromSeq: number, events: readonly ThreadEvent[]): void {const state = this.threads.get(threadId);@@ -836,14 +900,27 @@ export class AgentThreadClient {const skip = Math.max(state.lastSeq + 1 - fromSeq, 0);if (skip >= events.length) return;const fresh = skip === 0 ? events : events.slice(skip);+ const missing = Math.max(fromSeq - (state.lastSeq + 1), 0);+ if (missing > 0) {+ console.warn('[agent-threads] replay opened above the transcript tail', {+ threadId,+ fromSeq,+ have: state.lastSeq,+ });+ }let info = state.info;for (const event of fresh) {info = applyEventToInfo(info, event);}this.threads.set(threadId, {info,- events: [...state.events, ...fresh],+ events: [+ ...state.events,+ ...(missing > 0 ? (Array(missing).fill(SEQ_GAP_EVENT) as ThreadEvent[]) : []),+ ...fresh,+ ],lastSeq: fromSeq + events.length - 1,+ replayThroughSeq: state.replayThroughSeq,});this.bump();}@@ -851,7 +928,12 @@ export class AgentThreadClient {private upsertInfo(info: ThreadInfo): void {const existing = this.threads.get(info.threadId);if (existing === undefined) {- this.threads.set(info.threadId, { info, events: [], lastSeq: -1 });+ this.threads.set(info.threadId, {+ info,+ events: [],+ lastSeq: -1,+ replayThroughSeq: Number.POSITIVE_INFINITY,+ });// Seed the unread floor at first observation so a renderer reload// doesn't unread every idle `ready` tab — the pulse means "advanced// WHILE you were elsewhere in this window", not "you just reloaded".@@ -864,7 +946,12 @@ export class AgentThreadClient {// history open replays fresh from disk.this.openedArchived.delete(info.threadId);this.modelBuilders.delete(info.threadId);- this.threads.set(info.threadId, { info, events: [], lastSeq: -1 });+ this.threads.set(info.threadId, {+ info,+ events: [],+ lastSeq: -1,+ replayThroughSeq: Number.POSITIVE_INFINITY,+ });} else {this.threads.set(info.threadId, { ...existing, info });}diff --git a/packages/app/src/lib/acp/thread-event-model.codex-notice.test.ts b/packages/app/src/lib/acp/thread-event-model.codex-notice.test.tsnew file mode 100644index 000000000..fae4e5304--- /dev/null+++ b/packages/app/src/lib/acp/thread-event-model.codex-notice.test.ts@@ -0,0 +1,334 @@+/**+ * The fold's half of the legacy Codex warning contract: a complete producer+ * envelope becomes runtime-status chrome, and everything else keeps its bytes+ * and its ordinary bubble.+ *+ * Fixtures carry the producer's exact emission rather than hand-typed+ * approximations, and the same file backs the core predicate's tests and the+ * server's boundary guard, so the three cannot drift apart.+ */++import type { SessionUpdate, ThreadEvent } from '@inkeep/open-knowledge-core/acp/thread-protocol';+import * as fc from 'fast-check';+import { afterEach, describe, expect, test, vi } from 'vitest';+import fixture from '../../../../../test-support/fixtures/codex-legacy-warning-envelopes.json' with {+ type: 'json',+};+import { transcriptItemId } from '../../components/acp/transcript-item-id';+import {+ buildThreadRenderModel,+ type RenderedItem,+ ThreadRenderModelBuilder,+} from './thread-event-model';++const CODEX = fixture.agents.codexRegistry;+const CLAUDE = fixture.agents.claudeRegistry;++type AgentIdentity = typeof fixture.agents.codexRegistry;+const agentNamed = (name: string | undefined): AgentIdentity =>+ name === undefined ? CODEX : (fixture.agents as Record<string, AgentIdentity>)[name];++/**+ * Fixture updates are untyped wire JSON on purpose: several negatives are+ * shapes the SDK's types forbid, which is exactly what has to reach the fold+ * unclassified rather than be excluded by a cast at the test boundary.+ */+const asUpdate = (value: unknown): SessionUpdate => value as SessionUpdate;++let ts = 0;+function su(update: unknown): ThreadEvent {+ ts += 1;+ return { kind: 'session_update', update: asUpdate(structuredClone(update)), ts };+}++function chunk(text: string, messageId?: string): ThreadEvent {+ return su({+ sessionUpdate: 'agent_message_chunk',+ ...(messageId === undefined ? {} : { messageId }),+ content: { type: 'text', text },+ });+}++type AgentNotice = Extract<RenderedItem, { kind: 'agent_notice' }>;+type Message = Extract<RenderedItem, { kind: 'message' }>;++const notices = (items: readonly RenderedItem[]): AgentNotice[] =>+ items.filter((item): item is AgentNotice => item.kind === 'agent_notice');++const agentMessages = (items: readonly RenderedItem[]): Message[] =>+ items.filter((item): item is Message => item.kind === 'message' && item.role === 'agent');++/**+ * Every message bubble regardless of role — a near miss on a thought or user+ * chunk still has to keep its bytes, and it keeps them on its own role's path.+ */+const messageText = (items: readonly RenderedItem[]): string =>+ items+ .filter((item): item is Message => item.kind === 'message')+ .map((item) => item.text)+ .join('');++/** Every agent-authored byte the fold emitted, notice and prose alike, in order. */+const agentText = (items: readonly RenderedItem[]): string =>+ items+ .filter(+ (item): item is AgentNotice | Message =>+ item.kind === 'agent_notice' || (item.kind === 'message' && item.role === 'agent'),+ )+ .map((item) => item.text)+ .join('');++describe('legacy Codex warning classification', () => {+ test('the observed warning envelope becomes one runtime-status row, not agent prose', () => {+ const event = su(fixture.candidates[0].update);++ const model = buildThreadRenderModel([event], CODEX);++ expect(model.items).toHaveLength(1);+ expect(model.items[0]).toEqual({+ kind: 'agent_notice',+ source: 'codex_legacy',+ severity: 'warning',+ text: fixture.candidates[0].update.content.text,+ seq: 0,+ });+ });++ test('the same bytes from another agent stay an ordinary message', () => {+ const event = su(fixture.candidates[0].update);++ const model = buildThreadRenderModel([event], CLAUDE);++ expect(notices(model.items)).toHaveLength(0);+ expect(agentMessages(model.items)).toEqual([+ expect.objectContaining({ role: 'agent', text: fixture.candidates[0].update.content.text }),+ ]);+ });++ test('a thread with no configured agent classifies nothing', () => {+ const model = buildThreadRenderModel([su(fixture.candidates[0].update)], null);++ expect(notices(model.items)).toHaveLength(0);+ expect(agentMessages(model.items)).toHaveLength(1);+ });++ test.each(+ fixture.candidates.map((c) => [c.name, c] as const),+ )('candidate %s folds to a single verbatim notice', (_name, candidate) => {+ const model = buildThreadRenderModel([su(candidate.update)], CODEX);++ expect(notices(model.items)).toEqual([+ {+ kind: 'agent_notice',+ source: 'codex_legacy',+ severity: 'warning',+ text: candidate.update.content.text,+ seq: 0,+ },+ ]);+ });++ test('a config warning keeps its internal blank lines in one row', () => {+ const detailed = fixture.candidates.find((c) => c.name === 'config-warning-with-details');+ if (detailed === undefined) throw new Error('fixture lost its detailed config warning');+ expect(detailed.update.content.text).toContain('\n\n-');++ const model = buildThreadRenderModel([su(detailed.update)], CODEX);++ expect(model.items).toHaveLength(1);+ expect(notices(model.items)[0].text).toBe(detailed.update.content.text);+ });++ test('an event mixing chrome with prose is classified whole, never split at the blank line', () => {+ const mixed = fixture.atomicity.multiParagraphWarning;++ const model = buildThreadRenderModel([su(mixed.update)], CODEX);++ expect(model.items).toHaveLength(1);+ expect(notices(model.items)[0].text).toBe(mixed.update.content.text);+ });++ test.each(+ fixture.negatives.map((n) => [n.name, n] as const),+ )('near miss %s keeps its bytes on the ordinary path', (_name, negative) => {+ // The fixture records the identity a near miss belongs to as a KEY into+ // `agents`, not an inline object — a couple of them are near misses only+ // because of who sent them, so folding under a raw key would reject them+ // for being malformed and prove nothing about the identity gate.+ const agent = agentNamed((negative as { agent?: string }).agent);++ const model = buildThreadRenderModel([su(negative.update)], agent);++ expect(notices(model.items)).toHaveLength(0);+ const content = (negative.update as { content?: { type?: string; text?: string } }).content;+ if (content?.type === 'text' && typeof content.text === 'string') {+ expect(messageText(model.items)).toBe(content.text);+ }+ });++ test('an ordinary answer carrying an item id stays prose', () => {+ const model = buildThreadRenderModel([su(fixture.ordinaryAnswer.update)], CODEX);++ expect(notices(model.items)).toHaveLength(0);+ expect(agentMessages(model.items)[0].text).toBe(fixture.ordinaryAnswer.update.content.text);+ });++ test('two warnings in one turn are two chronological rows', () => {+ const first = fixture.candidates[0].update.content.text;+ const second = fixture.candidates[2].update.content.text;++ const model = buildThreadRenderModel(+ [su(fixture.candidates[0].update), su(fixture.candidates[2].update)],+ CODEX,+ );++ expect(notices(model.items).map((n) => n.text)).toEqual([first, second]);+ });++ test('a warning between no-ID neighbours stays its own row without loss or reordering', () => {+ const before = fixture.neighbors.contextCompacted.update.content.text;+ const warning = fixture.candidates[0].update.content.text;+ const after = fixture.neighbors.turnError.update.content.text;++ const model = buildThreadRenderModel(+ [+ su(fixture.neighbors.contextCompacted.update),+ su(fixture.candidates[0].update),+ su(fixture.neighbors.turnError.update),+ ],+ CODEX,+ );++ expect(model.items.map((item) => item.kind)).toEqual(['message', 'agent_notice', 'message']);+ expect(agentText(model.items)).toBe(before + warning + after);+ });++ test('a warning does not glue the prose around it into one bubble', () => {+ const model = buildThreadRenderModel(+ [chunk('Reading the file'), su(fixture.candidates[0].update), chunk(' and it is fine.')],+ CODEX,+ );++ expect(agentMessages(model.items).map((m) => m.text)).toEqual([+ 'Reading the file',+ ' and it is fine.',+ ]);+ });++ test('notice rows get unique ids and leave the rows before them alone', () => {+ const prose = [chunk('Reading the file')];+ const withWarnings = [+ ...prose,+ su(fixture.candidates[0].update),+ su(fixture.candidates[2].update),+ ];++ const proseIds = buildThreadRenderModel(prose, CODEX).items.map(transcriptItemId);+ const allIds = buildThreadRenderModel(withWarnings, CODEX).items.map(transcriptItemId);++ expect(allIds).toHaveLength(3);+ expect(new Set(allIds).size).toBe(3);+ expect(allIds.slice(0, proseIds.length)).toEqual(proseIds);+ });+});++describe('legacy Codex warning fold properties', () => {+ const candidateTexts = fixture.candidates.map((c) => c.update.content.text);+ const proseTexts = [+ fixture.neighbors.contextCompacted.update.content.text,+ fixture.neighbors.turnError.update.content.text,+ 'Warning: no terminator here',+ 'warning: lowercase\n\n',+ 'plain answer text',+ ];++ /** One agent text event: a candidate, a near miss, or prose carrying an id. */+ const eventArb = fc.oneof(+ fc.constantFrom(...candidateTexts).map((text) => ({ text, candidate: true })),+ fc.constantFrom(...proseTexts).map((text) => ({ text, candidate: false })),+ fc+ .tuple(fc.constantFrom(...candidateTexts, ...proseTexts), fc.string({ minLength: 1 }))+ .map(([text, id]) => ({ text, candidate: false, messageId: id })),+ );++ test('agent bytes are conserved across notices and messages', () => {+ fc.assert(+ fc.property(fc.array(eventArb, { maxLength: 25 }), (specs) => {+ const events = specs.map((spec) => chunk(spec.text, spec.messageId));++ const model = buildThreadRenderModel(events, CODEX);++ expect(agentText(model.items)).toBe(specs.map((spec) => spec.text).join(''));+ expect(notices(model.items)).toHaveLength(specs.filter((s) => s.candidate).length);+ }),+ { numRuns: 200 },+ );+ });++ test('a notice never carries a fragment of a larger event', () => {+ fc.assert(+ fc.property(fc.array(eventArb, { maxLength: 25 }), (specs) => {+ const model = buildThreadRenderModel(+ specs.map((spec) => chunk(spec.text, spec.messageId)),+ CODEX,+ );++ for (const notice of notices(model.items)) {+ expect(candidateTexts).toContain(notice.text);+ }+ }),+ { numRuns: 200 },+ );+ });++ test('incremental delivery matches one-shot delivery', () => {+ fc.assert(+ fc.property(+ fc.array(eventArb, { maxLength: 25 }),+ fc.array(fc.integer({ min: 1, max: 5 }), { minLength: 1, maxLength: 25 }),+ (specs, steps) => {+ const events = specs.map((spec) => chunk(spec.text, spec.messageId));+ const expected = buildThreadRenderModel(events, CODEX);++ const builder = new ThreadRenderModelBuilder(CODEX);+ let applied = 0;+ let model = builder.sync([]);+ let step = 0;+ while (applied < events.length) {+ applied = Math.min(applied + steps[step % steps.length], events.length);+ step += 1;+ model = builder.sync(events.slice(0, applied));+ }+ expect(model.items).toEqual(expected.items);+ },+ ),+ { numRuns: 200 },+ );+ });+});++describe('legacy Codex warning classification observability', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ test('classifying emits nothing to the console or the network', () => {+ const spies = (['log', 'info', 'warn', 'error', 'debug'] as const).map((level) =>+ vi.spyOn(console, level).mockImplementation(() => {}),+ );+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('no network'));++ buildThreadRenderModel(+ [+ su(fixture.candidates[0].update),+ su(fixture.candidates[1].update),+ su(fixture.negatives[0].update),+ su(fixture.ordinaryAnswer.update),+ ],+ CODEX,+ );++ for (const spy of spies) expect(spy).not.toHaveBeenCalled();+ expect(fetchSpy).not.toHaveBeenCalled();+ });+});diff --git a/packages/app/src/lib/acp/thread-event-model.incremental.test.ts b/packages/app/src/lib/acp/thread-event-model.incremental.test.tsindex 53c9f72c1..2b00e6f2f 100644--- a/packages/app/src/lib/acp/thread-event-model.incremental.test.ts+++ b/packages/app/src/lib/acp/thread-event-model.incremental.test.ts@@ -120,9 +120,9 @@ describe('incremental fold equivalence', () => {for (let seed = 1; seed <= 20; seed++) {const rng = makeRng(seed * 7919);const events = generateEvents(rng, 120);- const expected = buildThreadRenderModel(events);+ const expected = buildThreadRenderModel(events, null);- const builder = new ThreadRenderModelBuilder();+ const builder = new ThreadRenderModelBuilder(null);let applied = 0;let model = builder.sync([]);while (applied < events.length) {@@ -136,14 +136,14 @@ describe('incremental fold equivalence', () => {test('snapshot is referentially stable when no new events arrive', () => {const events = generateEvents(makeRng(42), 50);- const builder = new ThreadRenderModelBuilder();+ const builder = new ThreadRenderModelBuilder(null);const first = builder.sync(events);expect(builder.sync(events)).toBe(first);expect(builder.sync(events)).toBe(first);});test('untouched rows keep object identity across snapshots (copy-on-write)', () => {- const builder = new ThreadRenderModelBuilder();+ const builder = new ThreadRenderModelBuilder(null);const base: ThreadEvent[] = [{ kind: 'user_message', content: 'hi', ts: 1 },{@@ -179,9 +179,9 @@ describe('incremental fold equivalence', () => {test('a shorter log than previously seen resets the builder', () => {const events = generateEvents(makeRng(7), 40);- const builder = new ThreadRenderModelBuilder();+ const builder = new ThreadRenderModelBuilder(null);builder.sync(events);const shorter = events.slice(0, 5);- expect(builder.sync(shorter)).toEqual(buildThreadRenderModel(shorter));+ expect(builder.sync(shorter)).toEqual(buildThreadRenderModel(shorter, null));});});diff --git a/packages/app/src/lib/acp/thread-event-model.test.ts b/packages/app/src/lib/acp/thread-event-model.test.tsindex d81eb381e..8d666c135 100644--- a/packages/app/src/lib/acp/thread-event-model.test.ts+++ b/packages/app/src/lib/acp/thread-event-model.test.ts@@ -34,7 +34,7 @@ describe('buildThreadRenderModel', () => {} as never,}),];- const model = buildThreadRenderModel(events);+ const model = buildThreadRenderModel(events, null);const messages = model.items.filter((i) => i.kind === 'message');expect(messages).toHaveLength(2); // user + one coalesced agent messageexpect(messages[1]).toMatchObject({ role: 'agent', text: 'Hello world' });@@ -81,7 +81,7 @@ describe('buildThreadRenderModel', () => {}),chunk(8, 'All finished.'),];- const model = buildThreadRenderModel(events);+ const model = buildThreadRenderModel(events, null);// Chronological: user, text, tool, text, tool, text — chunks coalesce only// while their message is still the tail, never across a tool call.expect(model.items.map((i) => (i.kind === 'message' ? `${i.kind}:${i.text}` : i.kind))).toEqual(@@ -120,7 +120,7 @@ describe('buildThreadRenderModel', () => {} as never,}),];- const model = buildThreadRenderModel(events);+ const model = buildThreadRenderModel(events, null);const call = model.items.find((i) => i.kind === 'tool_call');expect(call).toMatchObject({ toolCallId: 'c1', status: 'completed', toolKind: 'edit' });if (call?.kind !== 'tool_call') throw new Error('unreachable');@@ -138,7 +138,7 @@ describe('buildThreadRenderModel', () => {}),ev({ kind: 'permission_resolved', requestId: 'p1', optionId: 'allow', auto: false, ts: 2 }),];- const model = buildThreadRenderModel(events);+ const model = buildThreadRenderModel(events, null);const perm = model.items.find((i) => i.kind === 'permission');if (perm?.kind !== 'permission') throw new Error('unreachable');expect(perm.resolved).toEqual({ optionId: 'allow', auto: false });@@ -171,7 +171,7 @@ describe('buildThreadRenderModel', () => {[request, call, resolve],[call, request, resolve],] satisfies ThreadEvent[][]) {- const model = buildThreadRenderModel(events);+ const model = buildThreadRenderModel(events, null);const perm = model.items.find((i) => i.kind === 'permission');if (perm?.kind !== 'permission') throw new Error('unreachable');expect(perm.toolCallId).toBe('c1');@@ -190,7 +190,7 @@ describe('buildThreadRenderModel', () => {ts: 1,}),];- const perm = buildThreadRenderModel(events).items.find((i) => i.kind === 'permission');+ const perm = buildThreadRenderModel(events, null).items.find((i) => i.kind === 'permission');if (perm?.kind !== 'permission') throw new Error('unreachable');expect(perm.mergedIntoToolCall).toBe(false);});@@ -209,7 +209,7 @@ describe('buildThreadRenderModel', () => {} as never,}),];- const model = buildThreadRenderModel(events);+ const model = buildThreadRenderModel(events, null);expect(model.plan).toHaveLength(2);expect(model.plan[0]).toMatchObject({ content: 'Step 1', status: 'completed' });});@@ -219,7 +219,7 @@ describe('buildThreadRenderModel', () => {ev({ kind: 'status', status: 'error', detail: 'boom', ts: 1 }),ev({ kind: 'status', status: 'auth_required', detail: 'sign in', ts: 2 }),];- const model = buildThreadRenderModel(events);+ const model = buildThreadRenderModel(events, null);const notices = model.items.filter((i) => i.kind === 'notice');// A transcript recorded before the server classified failures carries only// the headline string — it still renders, with nothing structured to show.@@ -245,7 +245,7 @@ describe('buildThreadRenderModel', () => {ev({ kind: 'status', status: 'error', detail: 'connect failed', failure, ts: 2 }),ev({ kind: 'status', status: 'error', detail: 'connect failed', failure, ts: 3 }),];- const notices = buildThreadRenderModel(events).items.filter((i) => i.kind === 'notice');+ const notices = buildThreadRenderModel(events, null).items.filter((i) => i.kind === 'notice');expect(notices).toHaveLength(1);expect(notices[0]).toMatchObject({ attempts: 3, failure });});@@ -258,11 +258,14 @@ describe('buildThreadRenderModel', () => {// would filter the merged card out entirely — the live failure would// render nowhere, with no Retry button.const failure = { reason: 'connect' as const, agentMessage: 'boom' };- const model = buildThreadRenderModel([- ev({ kind: 'status', status: 'error', detail: 'boom', failure, ts: 1 }),- ev({ kind: 'status', status: 'ready', ts: 2 }),- ev({ kind: 'status', status: 'error', detail: 'boom', failure, ts: 3 }),- ]);+ const model = buildThreadRenderModel(+ [+ ev({ kind: 'status', status: 'error', detail: 'boom', failure, ts: 1 }),+ ev({ kind: 'status', status: 'ready', ts: 2 }),+ ev({ kind: 'status', status: 'error', detail: 'boom', failure, ts: 3 }),+ ],+ null,+ );const notices = model.items.filter((i) => i.kind === 'notice');expect(notices).toHaveLength(2);expect(notices[0]?.kind === 'notice' && notices[0].superseded).toBe(true);@@ -280,7 +283,7 @@ describe('buildThreadRenderModel', () => {ev({ kind: 'status', status: 'error', detail: 'x', failure: first, ts: 1 }),ev({ kind: 'status', status: 'error', detail: 'x', failure: second, ts: 2 }),];- const notices = buildThreadRenderModel(events).items.filter((i) => i.kind === 'notice');+ const notices = buildThreadRenderModel(events, null).items.filter((i) => i.kind === 'notice');expect(notices).toHaveLength(2);expect(notices.every((n) => n.kind === 'notice' && n.attempts === 1)).toBe(true);});@@ -292,9 +295,10 @@ describe('buildThreadRenderModel', () => {machineDetail: '{"detail":"x"}',authMethods: [{ id: 'test_login', name: 'Test Login', description: 'Sign in via test' }],};- const model = buildThreadRenderModel([- ev({ kind: 'status', status: 'auth_required', detail: 'sign in required', failure, ts: 1 }),- ]);+ const model = buildThreadRenderModel(+ [ev({ kind: 'status', status: 'auth_required', detail: 'sign in required', failure, ts: 1 })],+ null,+ );const notice = model.items.find((i) => i.kind === 'notice');if (notice?.kind !== 'notice') throw new Error('unreachable');expect(notice.tone).toBe('info');@@ -302,14 +306,17 @@ describe('buildThreadRenderModel', () => {});test('a failure with no detail string still produces a notice', () => {- const model = buildThreadRenderModel([- ev({- kind: 'status',- status: 'error',- failure: { reason: 'session-setup', agentMessage: 'no session for you' },- ts: 1,- }),- ]);+ const model = buildThreadRenderModel(+ [+ ev({+ kind: 'status',+ status: 'error',+ failure: { reason: 'session-setup', agentMessage: 'no session for you' },+ ts: 1,+ }),+ ],+ null,+ );const notice = model.items.find((i) => i.kind === 'notice');if (notice?.kind !== 'notice') throw new Error('unreachable');expect(notice.text).toBe('');@@ -327,7 +334,7 @@ describe('buildThreadRenderModel', () => {ev({ kind: 'status', status: 'running', ts: 3 }),ev({ kind: 'status', status: 'exited', detail: 'agent exited (SIGTERM)', ts: 4 }),];- expect(buildThreadRenderModel(events).turnActive).toBe(false);+ expect(buildThreadRenderModel(events, null).turnActive).toBe(false);});test('a resume after an exit re-arms the turn', () => {@@ -338,7 +345,7 @@ describe('buildThreadRenderModel', () => {ev({ kind: 'turn_started', ts: 3 }),ev({ kind: 'status', status: 'running', ts: 4 }),];- expect(buildThreadRenderModel(events).turnActive).toBe(true);+ expect(buildThreadRenderModel(events, null).turnActive).toBe(true);});const consentRequest = (): ThreadEvent =>@@ -356,7 +363,7 @@ describe('buildThreadRenderModel', () => {});test('renders a pending runtime-consent card from the request event', () => {- const model = buildThreadRenderModel([consentRequest()]);+ const model = buildThreadRenderModel([consentRequest()], null);const card = model.items.find((i) => i.kind === 'runtime_consent');if (card?.kind !== 'runtime_consent') throw new Error('unreachable');expect(card).toMatchObject({@@ -370,7 +377,7 @@ describe('buildThreadRenderModel', () => {});test('a request with no reason reads as missing — what pre-field events were', () => {- const model = buildThreadRenderModel([consentRequest()]);+ const model = buildThreadRenderModel([consentRequest()], null);const card = model.items.find((i) => i.kind === 'runtime_consent');if (card?.kind !== 'runtime_consent') throw new Error('unreachable');// The card picks its sentence off this; defaulting the other way would tell@@ -379,9 +386,10 @@ describe('buildThreadRenderModel', () => {});test('a broken-interpreter request carries that through to the card', () => {- const model = buildThreadRenderModel([- { ...consentRequest(), reason: 'broken' } as ThreadEvent,- ]);+ const model = buildThreadRenderModel(+ [{ ...consentRequest(), reason: 'broken' } as ThreadEvent],+ null,+ );const card = model.items.find((i) => i.kind === 'runtime_consent');if (card?.kind !== 'runtime_consent') throw new Error('unreachable');expect(card.reason).toBe('broken');@@ -391,28 +399,32 @@ describe('buildThreadRenderModel', () => {// card must not fall back to either interpreter sentence — both describe// something the user installed.test('a damaged-runtime request carries that through to the card', () => {- const model = buildThreadRenderModel([- { ...consentRequest(), reason: 'damaged' } as ThreadEvent,- ]);+ const model = buildThreadRenderModel(+ [{ ...consentRequest(), reason: 'damaged' } as ThreadEvent],+ null,+ );const card = model.items.find((i) => i.kind === 'runtime_consent');if (card?.kind !== 'runtime_consent') throw new Error('unreachable');expect(card.reason).toBe('damaged');});test('grant → progress → spawning drives the card through running to done', () => {- const model = buildThreadRenderModel([- consentRequest(),- ev({ kind: 'runtime_consent_resolved', requestId: 'r1', decision: 'granted', ts: 2 }),- ev({- kind: 'runtime_install_progress',- runtime: 'node',- phase: 'downloading',- receivedBytes: 20,- totalBytes: 40,- ts: 3,- }),- ev({ kind: 'status', status: 'spawning', ts: 4 }),- ]);+ const model = buildThreadRenderModel(+ [+ consentRequest(),+ ev({ kind: 'runtime_consent_resolved', requestId: 'r1', decision: 'granted', ts: 2 }),+ ev({+ kind: 'runtime_install_progress',+ runtime: 'node',+ phase: 'downloading',+ receivedBytes: 20,+ totalBytes: 40,+ ts: 3,+ }),+ ev({ kind: 'status', status: 'spawning', ts: 4 }),+ ],+ null,+ );const card = model.items.find((i) => i.kind === 'runtime_consent');if (card?.kind !== 'runtime_consent') throw new Error('unreachable');// Progress captured, and the follow-on spawning status marks it done.@@ -422,10 +434,13 @@ describe('buildThreadRenderModel', () => {});test('a decline resolves the card without an install lifecycle', () => {- const model = buildThreadRenderModel([- consentRequest(),- ev({ kind: 'runtime_consent_resolved', requestId: 'r1', decision: 'declined', ts: 2 }),- ]);+ const model = buildThreadRenderModel(+ [+ consentRequest(),+ ev({ kind: 'runtime_consent_resolved', requestId: 'r1', decision: 'declined', ts: 2 }),+ ],+ null,+ );const card = model.items.find((i) => i.kind === 'runtime_consent');if (card?.kind !== 'runtime_consent') throw new Error('unreachable');expect(card.resolved).toBe('declined');@@ -433,11 +448,14 @@ describe('buildThreadRenderModel', () => {});test('a failed launch after a grant marks the install failed', () => {- const model = buildThreadRenderModel([- consentRequest(),- ev({ kind: 'runtime_consent_resolved', requestId: 'r1', decision: 'granted', ts: 2 }),- ev({ kind: 'status', status: 'error', detail: 'checksum mismatch', ts: 3 }),- ]);+ const model = buildThreadRenderModel(+ [+ consentRequest(),+ ev({ kind: 'runtime_consent_resolved', requestId: 'r1', decision: 'granted', ts: 2 }),+ ev({ kind: 'status', status: 'error', detail: 'checksum mismatch', ts: 3 }),+ ],+ null,+ );const card = model.items.find((i) => i.kind === 'runtime_consent');if (card?.kind !== 'runtime_consent') throw new Error('unreachable');expect(card.install).toBe('failed');@@ -458,7 +476,7 @@ describe('buildThreadRenderModel', () => {});const piCard = (events: ThreadEvent[]): Extract<RenderedItem, { kind: 'pi_bridge' }> => {- const card = buildThreadRenderModel(events).items.find((i) => i.kind === 'pi_bridge');+ const card = buildThreadRenderModel(events, null).items.find((i) => i.kind === 'pi_bridge');if (card?.kind !== 'pi_bridge') throw new Error('no pi_bridge card');return card;};@@ -529,14 +547,17 @@ describe('buildThreadRenderModel', () => {// A status with nothing to fold onto — the foreign-file case, where nobody// was asked anything — still has to reach the transcript as its own row.test('a prompt-less status stands alone as a limitation row', () => {- const model = buildThreadRenderModel([- ev({- kind: 'pi_bridge_status',- state: 'foreign-file',- bridgePath: '/proj/.pi/extensions/open-knowledge.ts',- ts: 1,- }),- ]);+ const model = buildThreadRenderModel(+ [+ ev({+ kind: 'pi_bridge_status',+ state: 'foreign-file',+ bridgePath: '/proj/.pi/extensions/open-knowledge.ts',+ ts: 1,+ }),+ ],+ null,+ );const rows = model.items.filter((i) => i.kind === 'pi_bridge');expect(rows).toHaveLength(1);expect(rows[0]).toMatchObject({@@ -549,16 +570,19 @@ describe('buildThreadRenderModel', () => {// Same defense as the resolved-permission path: an answer whose question// fell off the retained log must not retarget some other row.test('an outcome for an unknown requestId becomes its own row', () => {- const model = buildThreadRenderModel([- piBridgeRequest(),- ev({- kind: 'pi_bridge_status',- requestId: 'gone',- state: 'ready',- bridgePath: '/other',- ts: 2,- }),- ]);+ const model = buildThreadRenderModel(+ [+ piBridgeRequest(),+ ev({+ kind: 'pi_bridge_status',+ requestId: 'gone',+ state: 'ready',+ bridgePath: '/other',+ ts: 2,+ }),+ ],+ null,+ );const rows = model.items.filter((i) => i.kind === 'pi_bridge');expect(rows).toHaveLength(2);expect(rows[0]).toMatchObject({ prompt: { requestId: 'p1' }, outcome: null });@@ -569,11 +593,14 @@ describe('buildThreadRenderModel', () => {// NEWER server replays on this client without losing the events it does// understand. `as never` is the only way past the union.test('an event kind this client has never heard of is skipped, not fatal', () => {- const model = buildThreadRenderModel([- ev({ kind: 'user_message', content: 'hi', ts: 1 }),- { kind: 'pi_bridge_teleported', ts: 2 } as never,- piBridgeRequest(),- ]);+ const model = buildThreadRenderModel(+ [+ ev({ kind: 'user_message', content: 'hi', ts: 1 }),+ { kind: 'pi_bridge_teleported', ts: 2 } as never,+ piBridgeRequest(),+ ],+ null,+ );expect(model.items.map((i) => i.kind)).toEqual(['message', 'pi_bridge']);});});@@ -583,12 +610,15 @@ describe('terminal folding', () => {ev({ kind: 'terminal_created', terminalId: id, command: 'npm', args: ['test'], ts });test('folds created → output chunks → exit into one terminal record', () => {- const model = buildThreadRenderModel([- created('t1'),- ev({ kind: 'terminal_output', terminalId: 't1', chunk: 'compiling…\n', ts: 2 }),- ev({ kind: 'terminal_output', terminalId: 't1', chunk: 'ok 12 tests\n', ts: 3 }),- ev({ kind: 'terminal_exit', terminalId: 't1', exitCode: 0, signal: null, ts: 4 }),- ]);+ const model = buildThreadRenderModel(+ [+ created('t1'),+ ev({ kind: 'terminal_output', terminalId: 't1', chunk: 'compiling…\n', ts: 2 }),+ ev({ kind: 'terminal_output', terminalId: 't1', chunk: 'ok 12 tests\n', ts: 3 }),+ ev({ kind: 'terminal_exit', terminalId: 't1', exitCode: 0, signal: null, ts: 4 }),+ ],+ null,+ );expect(model.terminals.t1).toMatchObject({command: 'npm',args: ['test'],@@ -599,11 +629,14 @@ describe('terminal folding', () => {});test('a running terminal has a null exit; output for unknown ids is dropped', () => {- const model = buildThreadRenderModel([- created('t1'),- ev({ kind: 'terminal_output', terminalId: 't1', chunk: 'partial', ts: 2 }),- ev({ kind: 'terminal_output', terminalId: 'ghost', chunk: 'nope', ts: 3 }),- ]);+ const model = buildThreadRenderModel(+ [+ created('t1'),+ ev({ kind: 'terminal_output', terminalId: 't1', chunk: 'partial', ts: 2 }),+ ev({ kind: 'terminal_output', terminalId: 'ghost', chunk: 'nope', ts: 3 }),+ ],+ null,+ );expect(model.terminals.t1?.exit).toBeNull();expect(model.terminals.t1?.output).toBe('partial');expect(model.terminals.ghost).toBeUndefined();@@ -620,7 +653,7 @@ describe('terminal folding', () => {});}events.push({ kind: 'terminal_output', terminalId: 't1', chunk: 'TAIL', ts: 99 });- const model = buildThreadRenderModel(events);+ const model = buildThreadRenderModel(events, null);const terminal = model.terminals.t1;if (terminal === undefined) throw new Error('unreachable');expect(terminal.output.length).toBeLessThanOrEqual(64_000);@@ -629,34 +662,43 @@ describe('terminal folding', () => {});test('signal exits carry the signal through', () => {- const model = buildThreadRenderModel([- created('t1'),- ev({ kind: 'terminal_exit', terminalId: 't1', exitCode: null, signal: 'SIGTERM', ts: 2 }),- ]);+ const model = buildThreadRenderModel(+ [+ created('t1'),+ ev({ kind: 'terminal_exit', terminalId: 't1', exitCode: null, signal: 'SIGTERM', ts: 2 }),+ ],+ null,+ );expect(model.terminals.t1?.exit).toEqual({ exitCode: null, signal: 'SIGTERM' });});});describe('token usage', () => {test('folds a spec usage_update (top-level used/size)', () => {- const model = buildThreadRenderModel([- ev({- kind: 'session_update',- ts: 1,- update: { sessionUpdate: 'usage_update', used: 12_345, size: 200_000 } as never,- }),- ]);+ const model = buildThreadRenderModel(+ [+ ev({+ kind: 'session_update',+ ts: 1,+ update: { sessionUpdate: 'usage_update', used: 12_345, size: 200_000 } as never,+ }),+ ],+ null,+ );expect(model.tokenUsage).toEqual({ used: 12_345, size: 200_000 });});test('still accepts the nested `usage` key shape from pre-spec adapters', () => {- const model = buildThreadRenderModel([- ev({- kind: 'session_update',- ts: 1,- update: { sessionUpdate: 'something_else', usage: { used: 7, size: 100 } } as never,- }),- ]);+ const model = buildThreadRenderModel(+ [+ ev({+ kind: 'session_update',+ ts: 1,+ update: { sessionUpdate: 'something_else', usage: { used: 7, size: 100 } } as never,+ }),+ ],+ null,+ );expect(model.tokenUsage).toEqual({ used: 7, size: 100 });});@@ -667,7 +709,7 @@ describe('token usage', () => {ts,update: { sessionUpdate: 'usage_update', used, size: 200_000 } as never,});- const model = buildThreadRenderModel([usage(10, 1), usage(50, 2)]);+ const model = buildThreadRenderModel([usage(10, 1), usage(50, 2)], null);expect(model.tokenUsage?.used).toBe(50);});});@@ -756,11 +798,14 @@ describe('startup failures a later ready retires', () => {// A thread that eventually started should not open on a stack of amber// cards about the sign-in the user already completed.test('a launch that eventually worked retires the failures it took to get there', () => {- const model = buildThreadRenderModel([- statusEvent('auth_required', 'auth-required'),- statusEvent('auth_required', 'auth-required'),- statusEvent('ready'),- ]);+ const model = buildThreadRenderModel(+ [+ statusEvent('auth_required', 'auth-required'),+ statusEvent('auth_required', 'auth-required'),+ statusEvent('ready'),+ ],+ null,+ );expect(model.items.filter((i) => i.kind === 'notice' && i.superseded !== true)).toHaveLength(0);// Two identical `auth_required` events coalesce into ONE notice with@@ -777,14 +822,17 @@ describe('startup failures a later ready retires', () => {// A prompt failure happened inside a live session, so a later `ready` says// nothing about it — the user still needs to see it.test('a prompt failure survives a later ready', () => {- const model = buildThreadRenderModel([statusEvent('error', 'prompt'), statusEvent('ready')]);+ const model = buildThreadRenderModel(+ [statusEvent('error', 'prompt'), statusEvent('ready')],+ null,+ );expect(model.items.filter((i) => i.kind === 'notice' && i.superseded !== true)).toHaveLength(1);});// Still parked: nothing has been answered yet, so nothing is retired.test('failures stand while the thread has not started', () => {- const model = buildThreadRenderModel([statusEvent('auth_required', 'auth-required')]);+ const model = buildThreadRenderModel([statusEvent('auth_required', 'auth-required')], null);expect(model.items.filter((i) => i.kind === 'notice' && i.superseded !== true)).toHaveLength(1);});diff --git a/packages/app/src/lib/acp/thread-event-model.ts b/packages/app/src/lib/acp/thread-event-model.tsindex 47cffa369..c6b508ef0 100644--- a/packages/app/src/lib/acp/thread-event-model.ts+++ b/packages/app/src/lib/acp/thread-event-model.ts@@ -21,6 +21,10 @@* were folded in — a historical transcript row, which the next fold corrects.*/+import {+ type CodexLegacyAgentIdentity,+ isCodexLegacyWarningUpdate,+} from '@inkeep/open-knowledge-core/acp/codex-legacy-notice';import type {PermissionOption,PiBridgeThreadState,@@ -118,6 +122,36 @@ interface RenderedNotice {attempts: number;}+/**+ * Operational status the agent's runtime reported mid-turn — how the session+ * is configured or behaving — as opposed to the answer the agent authored.+ *+ * Deliberately NOT a variant of `RenderedNotice`, which models a thread+ * failure: that shape carries retry, supersession and attempt state, and none+ * of it is answerable on passive guidance. Keeping them apart is what makes a+ * Retry button on this row unrepresentable rather than merely unrendered.+ *+ * `source` and `severity` are single-member unions on purpose. The protocol's+ * own typed notice is not deliverable by any released ACP SDK yet, so its arm+ * gets discriminated in beside this one when it becomes reachable, rather than+ * leaving fields nothing can populate today.+ */+interface RenderedAgentNotice {+ kind: 'agent_notice';+ source: 'codex_legacy';+ severity: 'warning';+ /** The producer's event text, byte for byte. Never rewritten or translated. */+ text: string;+ /**+ * Seq of the retained event this was minted from. Carried because arrival+ * behaviour depends on which side of the replay window an event fell on, and+ * that question is only answerable per event: counting notices cannot+ * separate the tail of a replayed log from a live arrival that landed in the+ * same batch.+ */+ seq: number;+}+/*** Live state of one ACP terminal (a command OK ran for the agent), folded* from `terminal_*` events. Rendered inside the tool call that embeds the@@ -212,6 +246,7 @@ export type RenderedItem =| RenderedToolCall| RenderedPermission| RenderedNotice+ | RenderedAgentNotice| RenderedRuntimeConsent| RenderedPiBridge;@@ -260,6 +295,15 @@ function isSupersededByReady(failure: ThreadFailureDetail | null): boolean {}export class ThreadRenderModelBuilder {+ /**+ * Which agent is answering. Required rather than optional because one+ * producer's payloads are read differently from every other's, and a+ * defaulted identity would silently fold a thread as "not that producer" —+ * the failure would be an absent notice, which looks exactly like a healthy+ * transcript. Callers with no identity to offer pass null explicitly.+ */+ constructor(private readonly agent: CodexLegacyAgentIdentity | null) {}+private items: RenderedItem[] = [];private plan: PlanEntry[] = [];private turnActive = false;@@ -298,7 +342,11 @@ export class ThreadRenderModelBuilder {sync(events: readonly ThreadEvent[]): ThreadRenderModel {if (events.length < this.appliedCount) this.reset();for (let i = this.appliedCount; i < events.length; i++) {- this.applyEvent(events[i]);+ // The array index IS the event's seq. The store keeps that true on the+ // way in — it dedupes an overlapping batch and pads a batch that opens+ // above the tail — so a caller assembling events by hand owes the same+ // alignment.+ this.applyEvent(events[i], i);}this.appliedCount = events.length;if (this.dirty) {@@ -333,7 +381,7 @@ export class ThreadRenderModelBuilder {this.dirty = true;}- private applyEvent(event: ThreadEvent): void {+ private applyEvent(event: ThreadEvent, seq: number): void {this.dirty = true;switch (event.kind) {case 'user_message': {@@ -595,7 +643,7 @@ export class ThreadRenderModelBuilder {break;}case 'session_update':- this.applyUpdate(event.update);+ this.applyUpdate(event.update, seq);break;default:break;@@ -635,11 +683,27 @@ export class ThreadRenderModelBuilder {this.items.push({ kind: 'message', role, text, messageId });}- private applyUpdate(update: SessionUpdate): void {+ private applyUpdate(update: SessionUpdate, seq: number): void {switch (update.sessionUpdate) {case 'agent_message_chunk': {const text = textFromContent(update.content);- if (text !== null) this.pushMessageChunk('agent', messageId(update), text);+ if (text === null) break;+ // Decided per retained event, before coalescing: once two events have+ // been glued into one bubble the producer's own boundary is gone, and+ // recovering it would mean guessing where the warning ended inside a+ // larger body. All-or-nothing on the whole event, so a near miss keeps+ // its bytes and follows the ordinary path untouched.+ if (isCodexLegacyWarningUpdate(update, this.agent)) {+ this.items.push({+ kind: 'agent_notice',+ source: 'codex_legacy',+ severity: 'warning',+ text,+ seq,+ });+ break;+ }+ this.pushMessageChunk('agent', messageId(update), text);break;}case 'agent_thought_chunk': {@@ -730,8 +794,11 @@ export class ThreadRenderModelBuilder {}/** One-shot fold — the non-incremental entry point for tests and tooling. */-export function buildThreadRenderModel(events: readonly ThreadEvent[]): ThreadRenderModel {- return new ThreadRenderModelBuilder().sync(events);+export function buildThreadRenderModel(+ events: readonly ThreadEvent[],+ agent: CodexLegacyAgentIdentity | null,+): ThreadRenderModel {+ return new ThreadRenderModelBuilder(agent).sync(events);}/**diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.jsonindex 3a1f60cf1..cecca0bec 100644--- a/packages/app/src/locales/ar/messages.json+++ b/packages/app/src/locales/ar/messages.json@@ -3542,6 +3542,7 @@}]],+ "d6qW27": [["agentName"], " أبلغ: ", ["headline"]],"dD7NPy": ["المخطط"],"dDpCOp": ["نجحت إعادة التسمية لكن الشريط الجانبي قد يكون قديمًا — حدّث لإعادة المزامنة"],"dEgA5A": ["إلغاء"],diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.poindex 84f72a0b9..acc013cb5 100644--- a/packages/app/src/locales/ar/messages.po+++ b/packages/app/src/locales/ar/messages.po@@ -482,6 +482,10 @@ msgstr "تعذّر تشغيل {agentName}."msgid "{agentName} doesn't accept image attachments."msgstr "{agentName} لا يقبل مرفقات الصور."+#: src/components/acp/AgentNoticeAnnouncer.tsx+msgid "{agentName} reported: {headline}"+msgstr "{agentName} أبلغ: {headline}"+#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr "{ahead} أمام"@@ -14594,6 +14598,7 @@ msgstr "في انتظار التفويض"msgid "Waiting for your approval"msgstr "في انتظار موافقتك"+#: src/components/acp/ThreadView.tsx#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/ThemePreviewCanvas.tsxmsgid "Warning"diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.jsonindex 088750221..8a472f9dc 100644--- a/packages/app/src/locales/bn/messages.json+++ b/packages/app/src/locales/bn/messages.json@@ -3017,6 +3017,7 @@"d2uTPx": ["সার্ভার ত্রুটি (HTTP ", ["status"], ")"],"d3dX3w": ["\"", ["word"], "\" খুঁজুন"],"d5rK4X": [["chars", "plural", { "one": ["অক্ষর"], "other": ["অক্ষর"] }]],+ "d6qW27": [["agentName"], " জানিয়েছে: ", ["headline"]],"dD7NPy": ["রূপরেখা"],"dDpCOp": ["নাম বদলানো সফল হয়েছে কিন্তু সাইডবার পুরোনো হতে পারে — আবার সিঙ্ক করতে সতেজ করুন"],"dEgA5A": ["বাতিল করুন"],diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.poindex dac2bba8a..ec7e0875d 100644--- a/packages/app/src/locales/bn/messages.po+++ b/packages/app/src/locales/bn/messages.po@@ -482,6 +482,10 @@ msgstr "{agentName} শুরু হতে পারেনি।"msgid "{agentName} doesn't accept image attachments."msgstr "{agentName} ছবি সংযুক্তি গ্রহণ করে না।"+#: src/components/acp/AgentNoticeAnnouncer.tsx+msgid "{agentName} reported: {headline}"+msgstr "{agentName} জানিয়েছে: {headline}"+#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr "{ahead} এগিয়ে"@@ -14590,6 +14594,7 @@ msgstr "অনুমোদনের অপেক্ষা"msgid "Waiting for your approval"msgstr "আপনার অনুমোদনের অপেক্ষা"+#: src/components/acp/ThreadView.tsx#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/ThemePreviewCanvas.tsxmsgid "Warning"diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 6235cab0f..b85c13873 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -3086,6 +3086,7 @@"d2uTPx": ["Server error (HTTP ", ["status"], ")"],"d3dX3w": ["Look Up \"", ["word"], "\""],"d5rK4X": [["chars", "plural", { "one": ["char"], "other": ["chars"] }]],+ "d6qW27": [["agentName"], " reported: ", ["headline"]],"dD7NPy": ["Outline"],"dDpCOp": ["Rename succeeded but the sidebar may be out of date — refresh to resync"],"dEgA5A": ["Cancel"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 5039f3a56..a8ab09257 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -482,6 +482,10 @@ msgstr "{agentName} couldn't start."msgid "{agentName} doesn't accept image attachments."msgstr "{agentName} doesn't accept image attachments."+#: src/components/acp/AgentNoticeAnnouncer.tsx+msgid "{agentName} reported: {headline}"+msgstr "{agentName} reported: {headline}"+#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr "{ahead} ahead"@@ -14594,6 +14598,7 @@ msgstr "Waiting for authorization"msgid "Waiting for your approval"msgstr "Waiting for your approval"+#: src/components/acp/ThreadView.tsx#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/ThemePreviewCanvas.tsxmsgid "Warning"diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.jsonindex a74408bc2..54dc1065e 100644--- a/packages/app/src/locales/es/messages.json+++ b/packages/app/src/locales/es/messages.json@@ -3597,6 +3597,7 @@"d5rK4X": [["chars", "plural", { "one": ["carácter"], "many": ["caracteres"], "other": ["caracteres"] }]],+ "d6qW27": [["agentName"], " informa: ", ["headline"]],"dD7NPy": ["Esquema"],"dDpCOp": ["Se renombró correctamente, pero puede que la barra lateral esté desactualizada; actualízala para resincronizar"diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.poindex 41eeb0ca1..2e5725df4 100644--- a/packages/app/src/locales/es/messages.po+++ b/packages/app/src/locales/es/messages.po@@ -482,6 +482,10 @@ msgstr "{agentName} no pudo iniciarse."msgid "{agentName} doesn't accept image attachments."msgstr "{agentName} no acepta adjuntos de imagen."+#: src/components/acp/AgentNoticeAnnouncer.tsx+msgid "{agentName} reported: {headline}"+msgstr "{agentName} informa: {headline}"+#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr "{ahead} por delante"@@ -14594,6 +14598,7 @@ msgstr "Esperando la autorización"msgid "Waiting for your approval"msgstr "Esperando tu aprobación"+#: src/components/acp/ThreadView.tsx#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/ThemePreviewCanvas.tsxmsgid "Warning"diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.jsonindex e4b9d212d..841161c3f 100644--- a/packages/app/src/locales/fr/messages.json+++ b/packages/app/src/locales/fr/messages.json@@ -3629,6 +3629,7 @@"d2uTPx": ["Erreur serveur (HTTP ", ["status"], ")"],"d3dX3w": ["Rechercher « ", ["word"], " »"],"d5rK4X": [["chars", "plural", { "one": ["car."], "many": ["car."], "other": ["car."] }]],+ "d6qW27": [["agentName"], " signale : ", ["headline"]],"dD7NPy": ["Plan"],"dDpCOp": ["Renommage réussi, mais la barre latérale n'est peut-être pas à jour — actualisez pour resynchroniser"diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.poindex 2e64da1ce..0374337d8 100644--- a/packages/app/src/locales/fr/messages.po+++ b/packages/app/src/locales/fr/messages.po@@ -482,6 +482,10 @@ msgstr "{agentName} n’a pas pu démarrer."msgid "{agentName} doesn't accept image attachments."msgstr "{agentName} n'accepte pas les pièces jointes d'image."+#: src/components/acp/AgentNoticeAnnouncer.tsx+msgid "{agentName} reported: {headline}"+msgstr "{agentName} signale : {headline}"+#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr "{ahead} en avance"@@ -14594,6 +14598,7 @@ msgstr "En attente d'autorisation"msgid "Waiting for your approval"msgstr "En attente de votre approbation"+#: src/components/acp/ThreadView.tsx#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/ThemePreviewCanvas.tsxmsgid "Warning"diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.jsonindex 8f931d6c6..b8e309072 100644--- a/packages/app/src/locales/hi/messages.json+++ b/packages/app/src/locales/hi/messages.json@@ -3001,6 +3001,7 @@"d2uTPx": ["सर्वर त्रुटि (HTTP ", ["status"], ")"],"d3dX3w": ["\"", ["word"], "\" देखें"],"d5rK4X": [["chars", "plural", { "one": ["अक्षर"], "other": ["अक्षर"] }]],+ "d6qW27": [["agentName"], " ने बताया: ", ["headline"]],"dD7NPy": ["रूपरेखा"],"dDpCOp": ["नाम बदल गया पर साइडबार पुराना हो सकता है — फिर से सिंक करने के लिए ताज़ा करें"],"dEgA5A": ["रद्द करें"],diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.poindex a7d9d7983..f23fa558f 100644--- a/packages/app/src/locales/hi/messages.po+++ b/packages/app/src/locales/hi/messages.po@@ -482,6 +482,10 @@ msgstr "{agentName} शुरू नहीं हो सका।"msgid "{agentName} doesn't accept image attachments."msgstr "{agentName} छवि अनुलग्नक स्वीकार नहीं करता।"+#: src/components/acp/AgentNoticeAnnouncer.tsx+msgid "{agentName} reported: {headline}"+msgstr "{agentName} ने बताया: {headline}"+#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr "{ahead} आगे"@@ -14590,6 +14594,7 @@ msgstr "प्राधिकरण की प्रतीक्षा"msgid "Waiting for your approval"msgstr "आपकी स्वीकृति की प्रतीक्षा"+#: src/components/acp/ThreadView.tsx#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/ThemePreviewCanvas.tsxmsgid "Warning"diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.jsonindex ece90e542..0c806e2b6 100644--- a/packages/app/src/locales/id/messages.json+++ b/packages/app/src/locales/id/messages.json@@ -3109,6 +3109,7 @@"d2uTPx": ["Galat server (HTTP ", ["status"], ")"],"d3dX3w": ["Cari \"", ["word"], "\""],"d5rK4X": [["chars", "plural", { "other": ["karakter"] }]],+ "d6qW27": [["agentName"], " melaporkan: ", ["headline"]],"dD7NPy": ["Kerangka"],"dDpCOp": ["Penggantian nama berhasil tetapi bilah sisi mungkin tidak mutakhir — segarkan untuk menyinkronkan ulang"diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.poindex 71c9f8358..21a799fd2 100644--- a/packages/app/src/locales/id/messages.po+++ b/packages/app/src/locales/id/messages.po@@ -482,6 +482,10 @@ msgstr "{agentName} tidak dapat dijalankan."msgid "{agentName} doesn't accept image attachments."msgstr "{agentName} tidak menerima lampiran gambar."+#: src/components/acp/AgentNoticeAnnouncer.tsx+msgid "{agentName} reported: {headline}"+msgstr "{agentName} melaporkan: {headline}"+#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr "{ahead} di depan"@@ -14590,6 +14594,7 @@ msgstr "Menunggu otorisasi"msgid "Waiting for your approval"msgstr "Menunggu persetujuan Anda"+#: src/components/acp/ThreadView.tsx#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/ThemePreviewCanvas.tsxmsgid "Warning"diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.jsonindex 51b4dc2c5..a60cee6d6 100644--- a/packages/app/src/locales/ko/messages.json+++ b/packages/app/src/locales/ko/messages.json@@ -2983,6 +2983,7 @@"d2uTPx": ["서버 오류 (HTTP ", ["status"], ")"],"d3dX3w": ["“", ["word"], "” 찾아보기"],"d5rK4X": [["chars", "plural", { "other": ["#", "자"] }]],+ "d6qW27": [["agentName"], " 보고: ", ["headline"]],"dD7NPy": ["개요"],"dDpCOp": ["이름 변경은 성공했지만 사이드바가 최신 상태가 아닐 수 있습니다. 다시 동기화하려면 새로 고침하세요."diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.poindex 2005e91b3..9cb0cbe72 100644--- a/packages/app/src/locales/ko/messages.po+++ b/packages/app/src/locales/ko/messages.po@@ -482,6 +482,10 @@ msgstr "{agentName} 시작 실패."msgid "{agentName} doesn't accept image attachments."msgstr "{agentName}: 이미지 첨부 미지원"+#: src/components/acp/AgentNoticeAnnouncer.tsx+msgid "{agentName} reported: {headline}"+msgstr "{agentName} 보고: {headline}"+#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr "{ahead}개 앞서 있음"@@ -14594,6 +14598,7 @@ msgstr "인증 대기 중"msgid "Waiting for your approval"msgstr "승인 대기 중"+#: src/components/acp/ThreadView.tsx#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/ThemePreviewCanvas.tsxmsgid "Warning"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 03459173f..2b029df46 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -3086,6 +3086,7 @@"d2uTPx": ["Śēŕvēŕ ēŕŕōŕ (ĤŢŢƤ ", ["status"], ")"],"d3dX3w": ["Ĺōōķ Ũƥ \"", ["word"], "\""],"d5rK4X": [["chars", "plural", { "one": ["ćĥàŕ"], "other": ["ćĥàŕś"] }]],+ "d6qW27": [["agentName"], " ŕēƥōŕţēď: ", ["headline"]],"dD7NPy": ["Ōũţĺĩńē"],"dDpCOp": ["Ŕēńàḿē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],"dEgA5A": ["Ćàńćēĺ"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 5a2ffa703..d16f3dd62 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -482,6 +482,10 @@ msgstr ""msgid "{agentName} doesn't accept image attachments."msgstr ""+#: src/components/acp/AgentNoticeAnnouncer.tsx+msgid "{agentName} reported: {headline}"+msgstr ""+#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr ""@@ -14590,6 +14594,7 @@ msgstr ""msgid "Waiting for your approval"msgstr ""+#: src/components/acp/ThreadView.tsx#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/ThemePreviewCanvas.tsxmsgid "Warning"diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.jsonindex 4d788ace0..6d260bd0a 100644--- a/packages/app/src/locales/pt-BR/messages.json+++ b/packages/app/src/locales/pt-BR/messages.json@@ -3515,6 +3515,7 @@"d5rK4X": [["chars", "plural", { "one": ["caractere"], "many": ["caracteres"], "other": ["caracteres"] }]],+ "d6qW27": [["agentName"], " informou: ", ["headline"]],"dD7NPy": ["Estrutura"],"dDpCOp": ["A renomeação deu certo, mas a barra lateral pode estar desatualizada — atualize para ressincronizar"diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.poindex 27c9b2068..919935a5a 100644--- a/packages/app/src/locales/pt-BR/messages.po+++ b/packages/app/src/locales/pt-BR/messages.po@@ -482,6 +482,10 @@ msgstr "{agentName} não conseguiu iniciar."msgid "{agentName} doesn't accept image attachments."msgstr "{agentName} não aceita anexos de imagem."+#: src/components/acp/AgentNoticeAnnouncer.tsx+msgid "{agentName} reported: {headline}"+msgstr "{agentName} informou: {headline}"+#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr "{ahead} à frente"@@ -14590,6 +14594,7 @@ msgstr "Aguardando a autorização"msgid "Waiting for your approval"msgstr "Aguardando sua aprovação"+#: src/components/acp/ThreadView.tsx#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/ThemePreviewCanvas.tsxmsgid "Warning"diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.jsonindex 556dcf247..b34c5a91e 100644--- a/packages/app/src/locales/ur/messages.json+++ b/packages/app/src/locales/ur/messages.json@@ -3169,6 +3169,7 @@"d2uTPx": ["سرور کی خرابی (HTTP ", ["status"], ")"],"d3dX3w": ["\"", ["word"], "\" تلاش کریں"],"d5rK4X": [["chars", "plural", { "one": ["حرف"], "other": ["حروف"] }]],+ "d6qW27": [["agentName"], " نے اطلاع دی: ", ["headline"]],"dD7NPy": ["خاکہ"],"dDpCOp": ["نام بدل گیا مگر سائیڈ بار پرانا ہو سکتا ہے — دوبارہ مطابقت کے لیے تازہ کریں"],"dEgA5A": ["منسوخ کریں"],diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.poindex 080843fed..8e28fc0ba 100644--- a/packages/app/src/locales/ur/messages.po+++ b/packages/app/src/locales/ur/messages.po@@ -482,6 +482,10 @@ msgstr "{agentName} شروع نہ ہو سکا۔"msgid "{agentName} doesn't accept image attachments."msgstr "{agentName} تصویری منسلکات قبول نہیں کرتا۔"+#: src/components/acp/AgentNoticeAnnouncer.tsx+msgid "{agentName} reported: {headline}"+msgstr "{agentName} نے اطلاع دی: {headline}"+#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr "{ahead} آگے"@@ -14594,6 +14598,7 @@ msgstr "اجازت کا انتظار ہے"msgid "Waiting for your approval"msgstr "آپ کی منظوری کا انتظار ہے"+#: src/components/acp/ThreadView.tsx#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/ThemePreviewCanvas.tsxmsgid "Warning"diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.jsonindex 2f56276d4..aa141e566 100644--- a/packages/app/src/locales/zh-Hans/messages.json+++ b/packages/app/src/locales/zh-Hans/messages.json@@ -2727,6 +2727,7 @@"d2uTPx": ["服务器错误(HTTP ", ["status"], ")"],"d3dX3w": ["查询“", ["word"], "”"],"d5rK4X": [["chars", "plural", { "other": ["字符"] }]],+ "d6qW27": [["agentName"], " 报告:", ["headline"]],"dD7NPy": ["大纲"],"dDpCOp": ["重命名成功,但侧边栏可能不是最新的——请刷新以重新同步"],"dEgA5A": ["取消"],diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.poindex 263ee8c4e..334b370c3 100644--- a/packages/app/src/locales/zh-Hans/messages.po+++ b/packages/app/src/locales/zh-Hans/messages.po@@ -482,6 +482,10 @@ msgstr "{agentName} 无法启动。"msgid "{agentName} doesn't accept image attachments."msgstr "{agentName} 不接受图像附件。"+#: src/components/acp/AgentNoticeAnnouncer.tsx+msgid "{agentName} reported: {headline}"+msgstr "{agentName} 报告:{headline}"+#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr "领先 {ahead} 个"@@ -14594,6 +14598,7 @@ msgstr "正在等待授权"msgid "Waiting for your approval"msgstr "正在等待你的批准"+#: src/components/acp/ThreadView.tsx#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/ThemePreviewCanvas.tsxmsgid "Warning"diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.jsonindex acf8211ac..4cd6bc361 100644--- a/packages/app/src/locales/zh-Hant/messages.json+++ b/packages/app/src/locales/zh-Hant/messages.json@@ -2753,6 +2753,7 @@"d2uTPx": ["伺服器錯誤(HTTP ", ["status"], ")"],"d3dX3w": ["查詢「", ["word"], "」"],"d5rK4X": [["chars", "plural", { "other": ["字元"] }]],+ "d6qW27": [["agentName"], " 回報:", ["headline"]],"dD7NPy": ["大綱"],"dDpCOp": ["重新命名成功,但側邊欄可能不是最新的——請重新整理以重新同步"],"dEgA5A": ["取消"],diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.poindex 611273003..83279f3fe 100644--- a/packages/app/src/locales/zh-Hant/messages.po+++ b/packages/app/src/locales/zh-Hant/messages.po@@ -482,6 +482,10 @@ msgstr "{agentName} 無法啟動。"msgid "{agentName} doesn't accept image attachments."msgstr "{agentName} 不接受圖片附件。"+#: src/components/acp/AgentNoticeAnnouncer.tsx+msgid "{agentName} reported: {headline}"+msgstr "{agentName} 回報:{headline}"+#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr "領先 {ahead} 個"@@ -14594,6 +14598,7 @@ msgstr "正在等待授權"msgid "Waiting for your approval"msgstr "正在等你核准"+#: src/components/acp/ThreadView.tsx#: src/components/settings/ContentRulesSection.tsx#: src/components/settings/ThemePreviewCanvas.tsxmsgid "Warning"diff --git a/packages/app/tests/a11y/acp-agent-notice.e2e.ts b/packages/app/tests/a11y/acp-agent-notice.e2e.tsnew file mode 100644index 000000000..92cfbe7d3--- /dev/null+++ b/packages/app/tests/a11y/acp-agent-notice.e2e.ts@@ -0,0 +1,487 @@+/**+ * Real-engine accessibility coverage for the ACP agent-warning card.+ *+ * jsdom can already prove the card's role, label, glyph and class list, and+ * the DOM tier does. What it cannot prove is anything the cascade decides:+ * it has no forced-colors substitution, no wrapping, and returns zero for+ * every box measurement, so a card that vanished into the background under+ * high contrast, spilled off a narrow viewport, or clipped its text at 400%+ * zoom would still pass there. Those failure classes need a browser.+ *+ * The transcript reaches the screen through the development-only injection+ * seam on `window`, so the client, the fold, the renderer and the browser are+ * all the production path — only the bytes are synthesized, and they are the+ * producer's own, read from the committed fixture the unit and server tiers+ * share.+ */++import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import AxeBuilder from '@axe-core/playwright';+import type { Locator, Page } from '@playwright/test';+import { expect, test } from '../stress/_helpers';++interface EnvelopeFixture {+ agents: Record<string, { source: string; id: string; name: string }>;+ candidates: { name: string; update: Record<string, unknown> }[];+ neighbors: Record<string, { update: Record<string, unknown> }>;+ ordinaryAnswer: { update: Record<string, unknown> };+}++const FIXTURE: EnvelopeFixture = JSON.parse(+ readFileSync(+ join(+ fileURLToPath(import.meta.url),+ '..',+ '..',+ '..',+ '..',+ '..',+ 'test-support',+ 'fixtures',+ 'codex-legacy-warning-envelopes.json',+ ),+ 'utf-8',+ ),+);++const CODEX = FIXTURE.agents.codexRegistry;++function candidate(name: string): Record<string, unknown> {+ const found = FIXTURE.candidates.find((entry) => entry.name === name);+ if (found === undefined) throw new Error(`fixture candidate "${name}" is missing`);+ return found.update;+}++/** The long single-paragraph warning — the one that has to wrap when space is short. */+const LONG_WARNING = candidate('warning-skills-budget');+/** The multi-paragraph config warning — the one whose details must not be clipped. */+const DETAILED_WARNING = candidate('config-warning-with-details');+const ORDINARY_ANSWER = FIXTURE.ordinaryAnswer.update;++const NOTICE = '[data-testid="agent-thread-agent-notice"]';+const ANNOUNCER = '[data-testid="agent-thread-warning-announcer"]';+const THREAD_ROOT = '[data-agent-thread-root]';++/**+ * Record every announcement the polite region receives, in write order.+ *+ * Reading the region's settled text cannot distinguish two announcements that+ * queued from two that overwrote each other — both leave the same final+ * string. The writer clears before each write, so the added text nodes are the+ * sequence, and that is also the closest available stand-in for how a screen+ * reader watches a live region.+ *+ * Installed after load rather than through `addInitScript`, which would run+ * against a document that has no element to observe yet.+ */+async function recordAnnouncements(page: Page): Promise<void> {+ await page.evaluate((announcerSelector) => {+ const log: string[] = [];+ Object.assign(globalThis, { acpAnnouncementLog: log });+ new MutationObserver((records) => {+ for (const record of records) {+ const target = record.target as HTMLElement;+ const region = target.closest?.(announcerSelector) ?? null;+ if (region === null) continue;+ for (const node of Array.from(record.addedNodes)) {+ const text = node.textContent ?? '';+ if (text !== '') log.push(text);+ }+ }+ }).observe(document.documentElement, { subtree: true, childList: true });+ }, ANNOUNCER);+}++function readAnnouncements(page: Page): Promise<string[]> {+ return page.evaluate(+ () => (globalThis as unknown as { acpAnnouncementLog?: string[] }).acpAnnouncementLog ?? [],+ );+}++/**+ * Resolve once the real thread socket has delivered its authoritative roster.+ *+ * The client asks the server to list its threads the moment the socket opens,+ * and the answer replaces the whole thread map — anything the server does not+ * name is dropped, which is exactly how the harness withdraws its own threads.+ * Injecting before that answer lands therefore races it, and loses. Observing+ * the frame on the wire is what makes the wait deterministic; there is no+ * rendered difference between "roster not yet received" and "roster received+ * and empty".+ *+ * Must be called before navigation, since the socket opens during load.+ */+function threadRosterDelivered(page: Page): Promise<void> {+ return new Promise((resolve, reject) => {+ const timer = setTimeout(+ () => reject(new Error('thread socket never delivered its roster')),+ 30_000,+ );+ page.on('websocket', (socket) => {+ if (!socket.url().includes('/collab/thread')) return;+ socket.on('framereceived', (frame) => {+ if (typeof frame.payload !== 'string') return;+ if (!frame.payload.includes('"op":"threads"')) return;+ clearTimeout(timer);+ resolve();+ });+ });+ });+}++/** Load the app shell and wait until synthetic threads can survive on it. */+async function openApp(page: Page): Promise<void> {+ const roster = threadRosterDelivered(page);+ await page.goto('/');+ await page.waitForFunction(() => Boolean(window.__acpThreadHarness), null, { timeout: 30_000 });+ await roster;+}++type Delivery = 'live' | 'replay';++interface MountedThread {+ threadId: string;+ card: Locator;+}++/**+ * Put a transcript on screen and return the thread plus its warning-card locator.+ *+ * `live` subscribes an empty thread, lets it paint, and only then streams the+ * updates in — the order a real turn arrives in, and the order the announcer's+ * replay latch is defined against. `replay` hydrates the whole transcript out+ * of the retained log in one batch, the way reopening an existing thread does.+ * The cards the two produce must be identical.+ */+async function mountThread(+ page: Page,+ updates: readonly Record<string, unknown>[],+ delivery: Delivery = 'live',+): Promise<MountedThread> {+ const threadId = await page.evaluate(+ ({ agent, payload, mode }) => {+ const harness = window.__acpThreadHarness;+ if (harness === undefined) throw new Error('ACP thread harness is not installed');+ const options = { agent, title: 'Accessibility thread' } as Parameters<+ typeof harness.openThread+ >[0];+ const sessionUpdates = payload as Parameters<typeof harness.pushUpdates>[1];+ return mode === 'replay'+ ? harness.replayThread(options, sessionUpdates)+ : harness.openThread(options);+ },+ { agent: CODEX, payload: updates, mode: delivery },+ );++ await expect(page.locator(THREAD_ROOT).first()).toBeVisible({ timeout: 30_000 });+ await expect(page.locator(ANNOUNCER).first()).toBeAttached({ timeout: 15_000 });+ if (delivery === 'live') await pushUpdates(page, threadId, updates);++ return { threadId, card: page.locator(NOTICE).first() };+}++/** Stream further updates into an already-mounted thread, as a live turn does. */+async function pushUpdates(+ page: Page,+ threadId: string,+ updates: readonly Record<string, unknown>[],+): Promise<void> {+ await page.evaluate(+ ({ id, payload }) => {+ const harness = window.__acpThreadHarness;+ if (harness === undefined) throw new Error('ACP thread harness is not installed');+ harness.pushUpdates(id, payload as Parameters<typeof harness.pushUpdates>[1]);+ },+ { id: threadId, payload: updates },+ );+}++/** Computed box + paint facts, read in one round trip so they describe one layout. */+function readCardMetrics(card: Locator) {+ return card.evaluate((el) => {+ const style = window.getComputedStyle(el);+ const rect = el.getBoundingClientRect();+ return {+ borderTopColor: style.borderTopColor,+ borderTopStyle: style.borderTopStyle,+ borderTopWidth: Number.parseFloat(style.borderTopWidth),+ backgroundColor: style.backgroundColor,+ color: style.color,+ fontSize: Number.parseFloat(style.fontSize),+ scrollWidth: el.scrollWidth,+ clientWidth: el.clientWidth,+ scrollHeight: el.scrollHeight,+ clientHeight: el.clientHeight,+ width: rect.width,+ height: rect.height,+ right: rect.right,+ forcedColors: window.matchMedia('(forced-colors: active)').matches,+ };+ });+}++/**+ * Type + box facts for the card's label and its body, which are what "legible+ * and untruncated" comes down to once the layout is magnified.+ */+function readTypography(card: Locator) {+ return card.evaluate((el) => {+ const measure = (part: HTMLElement | null) => {+ if (part === null) throw new Error('warning card is missing a text part');+ const style = window.getComputedStyle(part);+ return {+ fontSize: Number.parseFloat(style.fontSize),+ textOverflow: style.textOverflow,+ webkitLineClamp: style.webkitLineClamp,+ scrollWidth: part.scrollWidth,+ clientWidth: part.clientWidth,+ scrollHeight: part.scrollHeight,+ clientHeight: part.clientHeight,+ };+ };+ return {+ devicePixelRatio: window.devicePixelRatio,+ label: measure(el.querySelector('p')),+ body: measure(el.lastElementChild as HTMLElement | null),+ };+ });+}++// ── Forced colors ───────────────────────────────────────────────────────────++test('warning boundary survives forced-colors substitution', async ({ page }) => {+ await page.emulateMedia({ forcedColors: 'active' });+ await openApp(page);+ const { card } = await mountThread(page, [LONG_WARNING]);+ await expect(card).toBeVisible({ timeout: 15_000 });++ const metrics = await readCardMetrics(card);+ // Guard the oracle first: if the emulation never reached the page, every+ // assertion below would pass against ordinary rendering and prove nothing.+ expect(metrics.forcedColors).toBe(true);++ expect(metrics.borderTopStyle).not.toBe('none');+ expect(metrics.borderTopWidth).toBeGreaterThan(0);+ expect(metrics.borderTopColor).not.toBe('transparent');+ expect(metrics.borderTopColor).not.toBe('rgba(0, 0, 0, 0)');+ // The system palette replaces the amber fill outright, so the box is only a+ // box if its edge still contrasts with what it encloses.+ expect(metrics.borderTopColor).not.toBe(metrics.backgroundColor);++ // Severity must survive in words as well, since neither the tint nor the+ // glyph carries it here.+ await expect(card).toContainText('Warning');+ await expect(card).toContainText('skills context budget');+});++// ── 320 px reflow ───────────────────────────────────────────────────────────++/**+ * A window narrow enough that the thread panel itself lands under 320 CSS px.+ *+ * The panel group apportions the agents panel out of the layout it first+ * measured, and a window that opens at 320 leaves it nothing, so these two+ * blocks open at a workable width and narrow the window afterwards — which is+ * also the shape of the real gesture, since a reader shrinks or zooms a window+ * that already has a thread in it.+ */+const NARROWABLE = { width: 500, height: 800 } as const;++test.describe('narrow window', () => {+ test.use({ viewport: NARROWABLE });++ test('warning card reflows at a 320 px viewport without clipping or side-scroll', async ({+ page,+ }) => {+ await openApp(page);+ const { card } = await mountThread(page, [DETAILED_WARNING]);+ await expect(card).toBeVisible({ timeout: 15_000 });++ await page.setViewportSize({ width: 320, height: 640 });+ await page.waitForFunction(() => document.documentElement.clientWidth === 320, null, {+ timeout: 10_000,+ });++ const metrics = await readCardMetrics(card);+ // The card has to be measured at the width the requirement is about; a+ // panel that had collapsed instead would report a sliver and fail the+ // clipping checks below rather than passing them vacuously.+ expect(metrics.width).toBeGreaterThan(0);+ expect(metrics.width).toBeLessThanOrEqual(320);+ // Sub-pixel layout rounds either way, so allow a pixel before calling it overflow.+ expect(metrics.scrollWidth).toBeLessThanOrEqual(metrics.clientWidth + 1);+ expect(metrics.scrollHeight).toBeLessThanOrEqual(metrics.clientHeight + 1);+ expect(metrics.right).toBeLessThanOrEqual(320);++ const overflow = await page.evaluate(() => {+ const transcript = document.querySelector(+ '[data-testid="agent-thread-transcript"]',+ ) as HTMLElement;+ return {+ transcriptScrollWidth: transcript.scrollWidth,+ transcriptClientWidth: transcript.clientWidth,+ documentScrollWidth: document.documentElement.scrollWidth,+ documentClientWidth: document.documentElement.clientWidth,+ };+ });+ expect(overflow.transcriptScrollWidth).toBeLessThanOrEqual(overflow.transcriptClientWidth + 1);+ // Reflow means one direction of scrolling, so the warning must not push the+ // page itself sideways either.+ expect(overflow.documentScrollWidth).toBeLessThanOrEqual(overflow.documentClientWidth + 1);++ // Every detail line of the config warning is still rendered, not truncated+ // away to fit.+ await expect(card).toContainText('model_reasoning_effort');+ await expect(card).toContainText('sandbox_mode');+ });+});++// ── 400% zoom ───────────────────────────────────────────────────────────────++test.describe('400% browser zoom', () => {+ // Browser zoom scales a CSS pixel and shrinks the layout viewport by the same+ // factor, so 400% on a 1280x1024 display is a 320x256 layout viewport painted+ // at four device pixels per CSS pixel. Both halves matter: the ratio is what+ // magnifies the type, the viewport is what forces the reflow.+ test.use({ viewport: NARROWABLE, deviceScaleFactor: 4 });++ test('warning text stays legible and untruncated at 400% zoom', async ({ page }) => {+ await openApp(page);+ const { card } = await mountThread(page, [DETAILED_WARNING]);+ await expect(card).toBeVisible({ timeout: 15_000 });+ const unzoomed = await readCardMetrics(card);++ await page.setViewportSize({ width: 320, height: 256 });+ await page.waitForFunction(() => document.documentElement.clientWidth === 320, null, {+ timeout: 10_000,+ });++ const zoomed = await readTypography(card);+ // Guard the oracle: without the magnification this is just another narrow+ // viewport, and every legibility assertion below would be about nothing.+ expect(zoomed.devicePixelRatio).toBe(4);++ // Nothing shrank the type to make the content fit.+ expect(zoomed.label.fontSize).toBeGreaterThanOrEqual(unzoomed.fontSize);+ expect(zoomed.body.fontSize).toBeGreaterThanOrEqual(unzoomed.fontSize);+ // Nor hid the overflow: no ellipsis, no line clamp, no cropped box.+ for (const part of [zoomed.label, zoomed.body]) {+ expect(part.textOverflow).not.toBe('ellipsis');+ expect(part.webkitLineClamp).toBe('none');+ expect(part.scrollHeight).toBeLessThanOrEqual(part.clientHeight + 1);+ expect(part.scrollWidth).toBeLessThanOrEqual(part.clientWidth + 1);+ }++ await expect(card).toContainText('Warning');+ await expect(card).toContainText('Ignored 2 invalid entries');+ await expect(card).toContainText('model_reasoning_effort');+ await expect(card).toContainText('sandbox_mode');+ });+});++// ── axe ─────────────────────────────────────────────────────────────────────++test('a transcript carrying a warning card has no serious or critical violations', async ({+ page,+}) => {+ await openApp(page);+ await mountThread(page, [LONG_WARNING, ORDINARY_ANSWER, DETAILED_WARNING]);+ await expect(page.locator(NOTICE)).toHaveCount(2, { timeout: 15_000 });++ const results = await new AxeBuilder({ page })+ .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])+ .include(THREAD_ROOT)+ .analyze();+ const blocking = results.violations.filter(+ (violation) => violation.impact === 'serious' || violation.impact === 'critical',+ );+ expect(blocking.map((violation) => `${violation.id}: ${violation.help}`)).toEqual([]);+});++// ── Focus stability ─────────────────────────────────────────────────────────++test('an arriving warning moves no focus and adds no tab stop', async ({ page }) => {+ await openApp(page);+ const { threadId } = await mountThread(page, [ORDINARY_ANSWER]);++ const composer = page.locator('[data-testid="agent-thread-composer"]').first();+ await composer.focus();+ await expect(composer).toBeFocused();+ const focusBefore = await activeElementDescriptor(page);++ await pushUpdates(page, threadId, [LONG_WARNING]);+ await expect(page.locator(NOTICE)).toHaveCount(1, { timeout: 15_000 });++ await expect(composer).toBeFocused();+ expect(await activeElementDescriptor(page)).toBe(focusBefore);++ // The card's own chrome is inert — a label, a glyph and a box, no control —+ // so a warning body of plain prose adds no tab stop and the order a keyboard+ // user walks is the order they walked before it appeared. The body itself+ // renders through the same markdown path as any agent message, so a producer+ // that put a link or a fenced block in a warning would contribute whatever+ // that text contributes anywhere else in the transcript.+ const stops = await page+ .locator(NOTICE)+ .first()+ .evaluate(+ (el) =>+ el.querySelectorAll(+ 'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"]), [contenteditable="true"]',+ ).length,+ );+ expect(stops).toBe(0);+});++// ── Announcement order and replay silence ───────────────────────────────────++test('two live warnings announce in source order', async ({ page }) => {+ await openApp(page);+ await recordAnnouncements(page);+ await mountThread(page, [LONG_WARNING, ORDINARY_ANSWER, DETAILED_WARNING]);+ await expect(page.locator(NOTICE)).toHaveCount(2, { timeout: 15_000 });++ await expect.poll(() => readAnnouncements(page), { timeout: 15_000 }).toHaveLength(2);+ const announcements = await readAnnouncements(page);+ expect(announcements[0]).toContain('Warning: Skill descriptions were shortened');+ expect(announcements[1]).toContain('Config warning: Ignored 2 invalid entries');+ // The details paragraph belongs on the card, not in the reader's ear.+ expect(announcements[1]).not.toContain('model_reasoning_effort');+});++test('a replayed transcript renders its warnings without announcing them', async ({ page }) => {+ await openApp(page);+ await recordAnnouncements(page);+ const { threadId } = await mountThread(+ page,+ [LONG_WARNING, ORDINARY_ANSWER, DETAILED_WARNING],+ 'replay',+ );+ await expect(page.locator(NOTICE)).toHaveCount(2, { timeout: 15_000 });++ const region = page.locator(ANNOUNCER).first();+ await expect(region).toHaveAttribute('aria-live', 'polite');+ await expect(region).toBeEmpty();++ // A silent region proves nothing on its own — a broken announcer is silent+ // too. Sending one warning live into the same thread forces the positive+ // case: exactly one announcement, and it is the live arrival rather than+ // history catching up.+ await pushUpdates(page, threadId, [LONG_WARNING]);+ await expect(page.locator(NOTICE)).toHaveCount(3, { timeout: 15_000 });+ await expect.poll(() => readAnnouncements(page), { timeout: 15_000 }).toHaveLength(1);+ expect((await readAnnouncements(page))[0]).toContain(+ 'Warning: Skill descriptions were shortened',+ );+});++/** Enough of the focused element to tell "unchanged" from "moved elsewhere". */+function activeElementDescriptor(page: Page): Promise<string> {+ return page.evaluate(() => {+ const el = document.activeElement;+ if (el === null) return 'none';+ return `${el.tagName}#${el.id}[${el.getAttribute('data-testid') ?? ''}]`;+ });+}diff --git a/packages/app/tests/integration/dev-gate-allowlist.ts b/packages/app/tests/integration/dev-gate-allowlist.tsindex d06591bd1..ad99d8caa 100644--- a/packages/app/tests/integration/dev-gate-allowlist.ts+++ b/packages/app/tests/integration/dev-gate-allowlist.ts@@ -18,4 +18,5 @@ export const DEV_GATED_WINDOW_WRITERS: ReadonlyArray<string> = ['packages/app/src/components/SystemDocSubscriber.tsx','packages/app/src/editor/DocumentContext.tsx','packages/app/src/editor/TiptapEditor.tsx',+ 'packages/app/src/lib/acp/dev-thread-harness.ts',];diff --git a/packages/app/tests/integration/e2e-stop-rules.test.ts b/packages/app/tests/integration/e2e-stop-rules.test.tsindex c3efbb9dd..59e6ececc 100644--- a/packages/app/tests/integration/e2e-stop-rules.test.ts+++ b/packages/app/tests/integration/e2e-stop-rules.test.ts@@ -27,6 +27,8 @@* 10. Selection halo transition uses bare `ease-out` instead of* `var(--ease-out-strong)` — consistency with the repo's custom* easing token+ * 11. Static value imports of the DEV ACP thread harness, which would+ * defeat the dynamic-import gate that keeps it out of production*/import { readdirSync, readFileSync } from 'node:fs';@@ -140,6 +142,23 @@ function findSpawnIsolationViolations(return violations;}+/**+ * Core predicate of the DEV-harness import STOP rule, extracted so the rule+ * carries a planted-positive self-test (an absence-checker without one is a+ * vacuous no-op waiting to happen).+ *+ * The harness reaches production only if something pulls it into the module+ * graph eagerly. Its one sanctioned reference is the dynamic `import()` inside+ * `AgentThreadClientBinder.tsx`'s `import.meta.env.DEV` branch, which Vite+ * folds away; a static import would survive that gate. Type-only imports are+ * erased before bundling, so they are left alone.+ */+function isStaticDevHarnessImport(line: string): boolean {+ return /^\s*(?:import|export)\s+(?!type\b)[^;]*from\s+['"][^'"]*dev-thread-harness['"]/.test(+ line,+ );+}+function collectMatches(files: FileLines[],predicate: (line: string, lineIdx: number, file: FileLines) => boolean,@@ -279,6 +298,17 @@ describe('E2E STOP rule — zero allowlist', () => {}});+ test('no static value import of the DEV ACP thread harness', () => {+ const violations = collectMatches(listAppSrcTsFiles(), (line) =>+ isStaticDevHarnessImport(line),+ );+ if (violations.length > 0) {+ throw new Error(+ `Static import of dev-thread-harness in app source — it must be reached only through the DEV-gated dynamic import:\n${violations.join('\n')}`,+ );+ }+ });+test('no editor.mount( / editor.unmount( in V2 cache surfaces (precedent §25(a), SPEC US-001 Phase 1.0)', () => {// TipTap's `Editor.mount(container)` / `Editor.unmount()` API is BLOCKED// by `@tiptap/[email protected]` (probe — closure-captured@@ -508,6 +538,34 @@ describe('E2E STOP rule — zero allowlist', () => {expect(findSpawnIsolationViolations(multiSpawn).length).toBe(0);});+ /**+ * Planted-positive + adjacent-negative self-test for the DEV-harness import+ * rule, so the absence check above cannot rot into a no-op.+ *+ */+ test('dev-harness import rule fires on a static import and not on the sanctioned shapes', () => {+ expect(+ isStaticDevHarnessImport("import { installAcpThreadHarness } from './dev-thread-harness';"),+ ).toBe(true);+ expect(+ isStaticDevHarnessImport(+ "import { installAcpThreadHarness } from '@/lib/acp/dev-thread-harness';",+ ),+ ).toBe(true);+ expect(isStaticDevHarnessImport("export * from './dev-thread-harness';")).toBe(true);++ // Type-only: erased before bundling, so it cannot carry the module in.+ expect(+ isStaticDevHarnessImport("import type { AcpThreadHarness } from './dev-thread-harness';"),+ ).toBe(false);+ // The sanctioned reference — a dynamic import Vite folds away with its gate.+ expect(+ isStaticDevHarnessImport(" void import('@/lib/acp/dev-thread-harness').then(fn);"),+ ).toBe(false);+ // A neighbouring module whose name merely shares a prefix.+ expect(isStaticDevHarnessImport("import { x } from './thread-client';")).toBe(false);+ });+test('window.__activeEditor is published only by DocumentContext.tsx (regression — PR #168 merge collision)', () => {// `DocumentContext.tsx` owns `window.__activeEditor` via// `Object.defineProperty(window, '__activeEditor', { get: ... })` —diff --git a/packages/app/tests/meta/dev-harness-artifact-gate.test.ts b/packages/app/tests/meta/dev-harness-artifact-gate.test.tsnew file mode 100644index 000000000..35c9b3ec1--- /dev/null+++ b/packages/app/tests/meta/dev-harness-artifact-gate.test.ts@@ -0,0 +1,121 @@+/**+ * Production-artifact gate meta-guard.+ *+ * `scripts/check-dev-harness-absent.mjs` is the only check that runs against+ * an emitted chunk instead of source, so no other suite can tell whether it+ * still discriminates — a scanner that lost its walk, or that was pointed at a+ * tree it cannot read, reports the same clean pass as a genuinely clean build.+ * Its verdict is an exit code, so that is what these drive: a planted leak+ * must fail it and the same tree without the leak must not, and the degenerate+ * inputs that could fake a pass must fail it too.+ *+ * The wiring case is the other half. The gate is only load-bearing because it+ * runs at the moment the artifact is produced, so a build that stopped+ * invoking it would leave every case below green and ship the leak anyway.+ */++import { spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import { DEV_HARNESS_SENTINEL } from '../../scripts/check-dev-harness-absent.mjs';++const APP_ROOT = join(import.meta.dirname, '..', '..');+const GATE = join(APP_ROOT, 'scripts', 'check-dev-harness-absent.mjs');++const dirs: string[] = [];++function tmp(): string {+ const dir = mkdtempSync(join(tmpdir(), 'dev-harness-gate-'));+ dirs.push(dir);+ return dir;+}++/** Run the gate exactly as a build does, and report what a shell would see. */+function runGate(distDir: string): { status: number | null; stderr: string } {+ const result = spawnSync(process.execPath, [GATE, '--dist', distDir], { encoding: 'utf8' });+ return { status: result.status, stderr: result.stderr };+}++/** A build shaped like Vite's: hashed chunks under `assets/`, plus the entry HTML. */+function writeBuild(contents: Record<string, string>): string {+ const dist = tmp();+ mkdirSync(join(dist, 'assets'), { recursive: true });+ writeFileSync(join(dist, 'index.html'), '<!doctype html><body></body>');+ for (const [name, body] of Object.entries(contents)) {+ writeFileSync(join(dist, 'assets', name), body);+ }+ return dist;+}++afterEach(() => {+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true });+ dirs.length = 0;+});++describe('the emitted-artifact scanner', () => {+ test('fails on a chunk carrying the harness global, and names it', () => {+ const dist = writeBuild({+ 'index-a1b2c3.js': 'const a=1;export{a};',+ 'AgentThreadClientBinder-d4e5f6.js': `window.${DEV_HARNESS_SENTINEL}=h;`,+ });++ const { status, stderr } = runGate(dist);++ expect(status).toBe(1);+ expect(stderr).toContain('AgentThreadClientBinder-d4e5f6.js');+ // The clean sibling is not blamed alongside it.+ expect(stderr).not.toContain('index-a1b2c3.js');+ });++ test('passes the same build once the leak is gone', () => {+ const dist = writeBuild({+ 'index-a1b2c3.js': 'const a=1;export{a};',+ 'AgentThreadClientBinder-d4e5f6.js': 'const b=2;export{b};',+ });++ expect(runGate(dist).status).toBe(0);+ });++ test('fails when there is no build to read', () => {+ const { status, stderr } = runGate(join(tmp(), 'never-built'));++ expect(status).toBe(1);+ expect(stderr).toContain('no build at');+ });++ test('fails when the walk turns up nothing to read', () => {+ // A build whose layout this walk no longer understands looks exactly like+ // a clean one unless finding zero assets is itself a failure.+ const dist = tmp();+ mkdirSync(join(dist, 'assets'), { recursive: true });+ writeFileSync(join(dist, 'assets', 'inter-latin.woff2'), 'not text');++ const { status, stderr } = runGate(dist);++ expect(status).toBe(1);+ expect(stderr).toContain('nothing to scan');+ });+});++describe('the gate runs when the artifact is produced', () => {+ const scripts = (+ JSON.parse(readFileSync(join(APP_ROOT, 'package.json'), 'utf8')) as {+ scripts: Record<string, string>;+ }+ ).scripts;++ test('the production build invokes it', () => {+ expect(scripts.build).toContain('check:no-dev-harness');+ expect(scripts['check:no-dev-harness']).toContain('check-dev-harness-absent.mjs');+ });++ test('it runs after the bundler, not before', () => {+ // Ordered the other way it would grade whatever the previous build left+ // behind, which passes for as long as nobody clears `dist`.+ expect(scripts.build.indexOf('vite build')).toBeLessThan(+ scripts.build.indexOf('check:no-dev-harness'),+ );+ });+});diff --git a/packages/app/tests/perf/lib/bundle-check.test.ts b/packages/app/tests/perf/lib/bundle-check.test.tsindex 75dae55e2..f1ee7dd37 100644--- a/packages/app/tests/perf/lib/bundle-check.test.ts+++ b/packages/app/tests/perf/lib/bundle-check.test.ts@@ -1,11 +1,11 @@/*** Tests for bundle-check.*- * Strategy: rather than rebuild the app on every CI run (slow), the- * test exercises bundle-check against a synthetic `dist/assets` fixture- * that is faithful to the real build's structure. The integration with- * a real `bun run build` happens at the perf-tier — local dev- * runs `bun run build` once and re-runs assertBundleHealth manually.+ * Strategy: rather than rebuild the app (slow), the test exercises+ * bundle-check against a synthetic `dist/assets` fixture that is faithful to+ * the real build's structure. No vitest tier collects this directory, so both+ * this file and the module it covers run only when someone runs `pnpm run+ * build` and re-runs `assertBundleHealth` by hand.*/import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';@@ -95,6 +95,14 @@ describe('assertBundleHealth', () => {);});+ test("fails when '__acpThreadHarness' appears in a prod chunk", () => {+ write('telemetry-impl-abc.js', fakeTelemetryChunk());+ write('index-def.js', `${fakeIndexChunk()}\nwindow.__acpThreadHarness = {};`);+ const report = assertBundleHealth({ distAssetsDir: join(dir, 'assets') });+ expect(report.ok).toBe(false);+ expect(report.forbiddenHits.some((h) => h.sentinel === '__acpThreadHarness')).toBe(true);+ });+test('reports missing telemetry chunk', () => {write('index-def.js', fakeIndexChunk());// No telemetry-impl-*.jsdiff --git a/packages/app/tests/perf/lib/bundle-check.ts b/packages/app/tests/perf/lib/bundle-check.tsindex 5be7973d9..346ee289a 100644--- a/packages/app/tests/perf/lib/bundle-check.ts+++ b/packages/app/tests/perf/lib/bundle-check.ts@@ -10,17 +10,23 @@* (`ok-hdr-histogram-v1`) is absent from prod chunks.* 4. The typing-burst-detector sentinel* (`ok-typing-burst-detector-v1`) is absent from prod chunks.- * 5. The main `index-*.js` gzipped size has not regressed by more+ * 5. The `__acpThreadHarness` ACP thread-injection global is absent+ * from every prod chunk.+ * 6. The main `index-*.js` gzipped size has not regressed by more* than 2 KB vs the pre-spec baseline.*- * Run after `bun run build` in `packages/app`. The test that drives- * this skips with a warning if `dist/` is absent — local convenience;- * CI builds before invoking.+ * Run by hand after `pnpm run build` in `packages/app`: no vitest tier+ * collects `tests/perf/lib/`, so nothing here executes in CI. The DEV+ * ACP-harness sentinel is separately gated on every production build by+ * `scripts/check-dev-harness-absent.mjs`, which the `build` script invokes+ * against the emitted `dist/`; the entry below is the manual-run twin of that+ * gate, not a second one.*/import { existsSync, readdirSync, readFileSync } from 'node:fs';import { join } from 'node:path';import { gzipSync } from 'node:zlib';+import { DEV_HARNESS_SENTINEL } from '../../../scripts/check-dev-harness-absent.mjs';/*** Baseline for `index-*.js` gzipped size,@@ -41,6 +47,10 @@ const FORBIDDEN_SENTINELS = ['__ok_perf','ok-hdr-histogram-v1','ok-typing-burst-detector-v1',+ // Taken from the build gate rather than retyped: a rename that followed the+ // exported constant would otherwise leave this copy scanning for a string+ // nothing writes any more.+ DEV_HARNESS_SENTINEL,] as const;export interface BundleHealthReport {@@ -69,7 +79,7 @@ export interface AssertBundleHealthOpts {}/**- * Run all 5 assertions. Returns a structured report so callers can+ * Run all 6 assertions. Returns a structured report so callers can* decide between hard-fail and soft-warn (e.g. CI variant where dist/* isn't built fresh).*/@@ -81,7 +91,7 @@ export function assertBundleHealth(opts: AssertBundleHealthOpts = {}): BundleHeaif (!existsSync(distAssetsDir)) {return {ok: false,- failures: [`dist/assets not found at ${distAssetsDir}; run \`bun run build\` first`],+ failures: [`dist/assets not found at ${distAssetsDir}; run \`pnpm run build\` first`],forbiddenHits: [],};}@@ -106,7 +116,7 @@ export function assertBundleHealth(opts: AssertBundleHealthOpts = {}): BundleHea}}- // ── Assertions 2-4: forbidden sentinels in main / non-telemetry chunks ──+ // ── Assertions 2-5: forbidden sentinels in main / non-telemetry chunks ──const allFiles = readdirSync(distAssetsDir).filter((f) => f.endsWith('.js') && !f.startsWith('telemetry-impl-'),);@@ -122,7 +132,7 @@ export function assertBundleHealth(opts: AssertBundleHealthOpts = {}): BundleHea}}- // ── Assertion 5: index chunk gzipped size delta ─────────────────+ // ── Assertion 6: index chunk gzipped size delta ─────────────────const indexChunk = findFirstMatching(distAssetsDir, 'index-');let indexGzippedKb: number | undefined;if (indexChunk) {diff --git a/packages/core/package.json b/packages/core/package.jsonindex 997c05364..01dda47a7 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -55,6 +55,11 @@"types": "./src/acp/permissive-mode.ts","default": "./dist/acp-permissive-mode.mjs"},+ "./acp/codex-legacy-notice": {+ "development": "./src/acp/codex-legacy-notice.ts",+ "types": "./src/acp/codex-legacy-notice.ts",+ "default": "./dist/acp-codex-legacy-notice.mjs"+ },"./desktop-bridge": {"development": "./src/desktop-bridge.ts","types": "./src/desktop-bridge.ts",diff --git a/packages/core/src/acp/codex-legacy-notice.test.ts b/packages/core/src/acp/codex-legacy-notice.test.tsnew file mode 100644index 000000000..ca5eee01a--- /dev/null+++ b/packages/core/src/acp/codex-legacy-notice.test.ts@@ -0,0 +1,354 @@+import type { SessionUpdate } from '@agentclientprotocol/sdk';+import * as fc from 'fast-check';+import { afterEach, describe, expect, test, vi } from 'vitest';+import fixture from '../../../../test-support/fixtures/codex-legacy-warning-envelopes.json' with {+ type: 'json',+};+import {+ type CodexLegacyAgentIdentity,+ isCodexLegacyWarningUpdate,+} from './codex-legacy-notice.ts';++const PBT_NUM_RUNS = 200;++const CODEX: CodexLegacyAgentIdentity = fixture.agents.codexRegistry;++/**+ * The fixture is untyped wire JSON on purpose: several negatives are shapes the+ * SDK's own types forbid, which is exactly what the predicate has to survive.+ */+const asUpdate = (value: unknown) => value as SessionUpdate;++const agentNamed = (name: string | undefined): CodexLegacyAgentIdentity =>+ name === undefined ? CODEX : (fixture.agents as Record<string, CodexLegacyAgentIdentity>)[name];++/**+ * Literals restated independently of the implementation. A test that imported+ * the module's own constants would stay green through a typo in them.+ */+const WARNING_PREFIX = 'Warning: ';+const CONFIG_WARNING_PREFIX = 'Config warning: ';+const TERMINATOR = '\n\n';++const candidateFrom = (text: string): SessionUpdate =>+ asUpdate({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } });++/**+ * Openings exactly as long as the longer literal, so whatever follows one can+ * never reach back and change whether a prefix matched. Both matching and+ * near-miss members, so a property built on them constrains the rejecting+ * verdict as tightly as the accepting one.+ */+const HEADS = [+ CONFIG_WARNING_PREFIX,+ `${WARNING_PREFIX}abcdefg`,+ `${WARNING_PREFIX}${TERMINATOR}rest!`,+ 'warning: abcdefg',+ 'Warning:abcdefgh',+ ' Warning: abcdef',+ 'config warning: ',+ 'Notice: abcdefgh',+];++/** Endings exactly as long as the terminator, for the same reason. */+const TAILS = [TERMINATOR, '\nx', 'x\n', ' ', 'ab'];++describe('isCodexLegacyWarningUpdate — recorded producer envelopes', () => {+ test.each(+ fixture.candidates.map((c) => [c.name, c] as const),+ )('accepts %s', (_name, candidate) => {+ expect(isCodexLegacyWarningUpdate(asUpdate(candidate.update), CODEX)).toBe(true);+ });++ test('a config warning with internal detail paragraphs matches as ONE candidate', () => {+ const configWarning = fixture.candidates.find((c) => c.name === 'config-warning-with-details');+ const text = configWarning?.update.content?.text ?? '';++ expect(text).toContain(`${TERMINATOR}-`);+ expect(isCodexLegacyWarningUpdate(asUpdate(configWarning?.update), CODEX)).toBe(true);+ });++ test('an internal blank line never turns a near miss into a match', () => {+ // The same body with the producer's final terminator removed: still full of+ // blank lines, still not a candidate, and nothing to split on.+ const trimmed = `${WARNING_PREFIX}first paragraph${TERMINATOR}second paragraph`;++ expect(isCodexLegacyWarningUpdate(candidateFrom(trimmed), CODEX)).toBe(false);+ });++ test('a warning whose own message opens with a space still matches', () => {+ // Only the literal prefix is fixed. What the adapter interpolates after it+ // is the agent's message and is never further constrained.+ expect(isCodexLegacyWarningUpdate(candidateFrom(`${WARNING_PREFIX} spaced\n\n`), CODEX)).toBe(+ true,+ );+ });++ test('a multi-paragraph body is one verdict for the whole event, never a split', () => {+ // The characterized adapter cannot emit chrome and answer in one event, so+ // this shape is hypothetical. If it ever arrived it is classified whole:+ // carving the leading paragraph out would mean reinterpreting arbitrary+ // agent prose, which no producer contract supports.+ const { update, expectCandidate } = fixture.atomicity.multiParagraphWarning;+ const text = update.content.text;++ expect(text.split(TERMINATOR).length).toBeGreaterThan(2);+ expect(isCodexLegacyWarningUpdate(asUpdate(update), CODEX)).toBe(expectCandidate);+ });+});++describe('isCodexLegacyWarningUpdate — fails closed', () => {+ test.each(fixture.negatives.map((n) => [n.name, n] as const))('rejects %s', (_name, negative) => {+ expect(isCodexLegacyWarningUpdate(asUpdate(negative.update), agentNamed(negative.agent))).toBe(+ false,+ );+ });++ test.each(Object.entries(fixture.neighbors))('rejects the %s neighbour event', (_name, event) => {+ expect(isCodexLegacyWarningUpdate(asUpdate(event.update), CODEX)).toBe(false);+ });++ test('rejects an ordinary answer carrying an item id', () => {+ expect(isCodexLegacyWarningUpdate(asUpdate(fixture.ordinaryAnswer.update), CODEX)).toBe(false);+ });++ // The schema types this field `string | null | undefined`, and the SDK's+ // runtime validator rewrites anything else to `undefined` — but the app also+ // folds replayed log bytes and the server bounds events the validator never+ // saw, so the predicate cannot lean on that normalization.+ test.each([+ ['null', null],+ ['an empty string', ''],+ ['a string id', 'msg_01H8XK2Q4V7N3PZ'],+ ['zero', 0],+ ['a number', 42],+ ['false', false],+ ['true', true],+ ['an object', { id: 'msg_1' }],+ ['an array', ['msg_1']],+ ['NaN', Number.NaN],+ ])('rejects an otherwise exact envelope whose messageId is %s', (_label, messageId) => {+ const update = asUpdate({+ sessionUpdate: 'agent_message_chunk',+ messageId,+ content: { type: 'text', text: `${WARNING_PREFIX}budget exceeded${TERMINATOR}` },+ });++ expect(isCodexLegacyWarningUpdate(update, CODEX)).toBe(false);+ });++ test('an absent messageId and an explicitly undefined one both stay candidates', () => {+ const text = `${WARNING_PREFIX}budget exceeded${TERMINATOR}`;++ expect(isCodexLegacyWarningUpdate(candidateFrom(text), CODEX)).toBe(true);+ expect(+ isCodexLegacyWarningUpdate(+ asUpdate({+ sessionUpdate: 'agent_message_chunk',+ messageId: undefined,+ content: { type: 'text', text },+ }),+ CODEX,+ ),+ ).toBe(true);+ });++ test('rejects every candidate once the agent identity is missing', () => {+ for (const candidate of fixture.candidates) {+ const update = asUpdate(candidate.update);+ expect(isCodexLegacyWarningUpdate(update, null)).toBe(false);+ expect(isCodexLegacyWarningUpdate(update, undefined)).toBe(false);+ }+ });++ test('rejects a missing update', () => {+ expect(isCodexLegacyWarningUpdate(null, CODEX)).toBe(false);+ expect(isCodexLegacyWarningUpdate(undefined, CODEX)).toBe(false);+ });++ test('every gate is independently load-bearing', () => {+ // Each row flips exactly one gate away from a known-good candidate, so a+ // gate that silently stopped being checked shows up as a single failure+ // rather than being masked by the others.+ const body = 'Skill descriptions were shortened.';+ const good = `${WARNING_PREFIX}${body}${TERMINATOR}`;+ expect(isCodexLegacyWarningUpdate(candidateFrom(good), CODEX)).toBe(true);++ expect(+ isCodexLegacyWarningUpdate(candidateFrom(good), { source: 'custom', id: 'codex-acp' }),+ ).toBe(false);+ expect(+ isCodexLegacyWarningUpdate(candidateFrom(good), { source: 'registry', id: 'claude-acp' }),+ ).toBe(false);+ expect(+ isCodexLegacyWarningUpdate(+ asUpdate({ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: good } }),+ CODEX,+ ),+ ).toBe(false);+ expect(+ isCodexLegacyWarningUpdate(+ asUpdate({+ sessionUpdate: 'agent_message_chunk',+ messageId: 'msg_1',+ content: { type: 'text', text: good },+ }),+ CODEX,+ ),+ ).toBe(false);+ expect(isCodexLegacyWarningUpdate(candidateFrom(` ${good}`), CODEX)).toBe(false);+ expect(isCodexLegacyWarningUpdate(candidateFrom(good.trimEnd()), CODEX)).toBe(false);+ });+});++describe('isCodexLegacyWarningUpdate — properties', () => {+ test('is total over arbitrary inputs', () => {+ fc.assert(+ fc.property(fc.anything(), fc.anything(), (update, agent) => {+ const verdict = isCodexLegacyWarningUpdate(+ update as SessionUpdate,+ agent as CodexLegacyAgentIdentity,+ );+ return typeof verdict === 'boolean';+ }),+ { numRuns: PBT_NUM_RUNS },+ );+ });++ test('accepts exactly the recorded grammar over generated bodies', () => {+ fc.assert(+ fc.property(+ fc.constantFrom(WARNING_PREFIX, CONFIG_WARNING_PREFIX),+ fc.string(),+ fc.boolean(),+ (prefix, body, terminated) => {+ const text = `${prefix}${body}${terminated ? TERMINATOR : ''}`;+ const verdict = isCodexLegacyWarningUpdate(candidateFrom(text), CODEX);+ // A generated body can itself end in the terminator, so the oracle is+ // the finished bytes rather than the `terminated` flag.+ return verdict === text.endsWith(TERMINATOR);+ },+ ),+ { numRuns: PBT_NUM_RUNS },+ );+ });++ test('rejects any body whose leading bytes are not one of the two literals', () => {+ fc.assert(+ fc.property(fc.string(), (body) => {+ const text = `${body}${TERMINATOR}`;+ fc.pre(!text.startsWith(WARNING_PREFIX) && !text.startsWith(CONFIG_WARNING_PREFIX));+ return isCodexLegacyWarningUpdate(candidateFrom(text), CODEX) === false;+ }),+ { numRuns: PBT_NUM_RUNS },+ );+ });++ test('does not mutate the update or the agent it is given', () => {+ fc.assert(+ fc.property(fc.string(), (body) => {+ const update = candidateFrom(`${WARNING_PREFIX}${body}${TERMINATOR}`);+ const agent: CodexLegacyAgentIdentity = { ...CODEX };+ const updateBefore = JSON.stringify(update);+ const agentBefore = JSON.stringify(agent);++ isCodexLegacyWarningUpdate(update, agent);++ return JSON.stringify(update) === updateBefore && JSON.stringify(agent) === agentBefore;+ }),+ { numRuns: PBT_NUM_RUNS },+ );+ });++ test('no interior content changes the verdict, whatever its shape or size', () => {+ // The verdict must be settled by a bounded window at each end, so splicing+ // anything at all between those windows has to leave it alone. Stated this+ // way the claim is enforceable rather than aspirational: a body-length cap,+ // a corpus or digest lookup, and a rule that re-reads the interior for+ // paragraph structure each move one of these verdicts without moving the+ // empty-interior baseline it is compared against.+ //+ // Every middle is checked against every head/tail pair rather than sampled,+ // so detection does not depend on a generator happening to draw the one+ // combination that discriminates.+ for (const head of HEADS) expect(head).toHaveLength(CONFIG_WARNING_PREFIX.length);+ for (const tail of TAILS) expect(tail).toHaveLength(TERMINATOR.length);++ const middles = [+ 'plain body text',+ '\n',+ TERMINATOR,+ `${TERMINATOR}- detail: value${TERMINATOR}`,+ `${TERMINATOR}${WARNING_PREFIX}nested${TERMINATOR}`,+ `${TERMINATOR}${CONFIG_WARNING_PREFIX}nested${TERMINATOR}`,+ 'x'.repeat(50_000),+ ];++ for (const head of HEADS) {+ for (const tail of TAILS) {+ const emptyInterior = isCodexLegacyWarningUpdate(candidateFrom(`${head}${tail}`), CODEX);+ for (const middle of middles) {+ expect(isCodexLegacyWarningUpdate(candidateFrom(`${head}${middle}${tail}`), CODEX)).toBe(+ emptyInterior,+ );+ }+ }+ }+ });++ test('a multi-megabyte interior changes nothing on either side of the answer', () => {+ // Kept out of the cross product above so the table stays cheap, and split+ // across an accepting and a rejecting pair so a cap cannot hide behind a+ // verdict that was already false.+ const huge = 'x'.repeat(2_000_000);++ for (const tail of [TERMINATOR, 'ab']) {+ expect(+ isCodexLegacyWarningUpdate(candidateFrom(`${WARNING_PREFIX}${huge}${tail}`), CODEX),+ ).toBe(isCodexLegacyWarningUpdate(candidateFrom(`${WARNING_PREFIX}${tail}`), CODEX));+ }+ });++ test('an arbitrary generated interior changes nothing either', () => {+ // Breadth over the shapes the table above cannot enumerate. The empty+ // interior is the baseline here too, so each draw is its own witness.+ fc.assert(+ fc.property(+ fc.constantFrom(...HEADS),+ fc.constantFrom(...TAILS),+ fc.string(),+ (head, tail, body) =>+ isCodexLegacyWarningUpdate(candidateFrom(`${head}${body}${tail}`), CODEX) ===+ isCodexLegacyWarningUpdate(candidateFrom(`${head}${tail}`), CODEX),+ ),+ { numRuns: PBT_NUM_RUNS },+ );+ });+});++describe('isCodexLegacyWarningUpdate — no observability surface', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ test('performs no network work and writes nothing to the console', () => {+ const fetchSpy = vi.fn(() => {+ throw new Error('the predicate must not reach the network');+ });+ vi.stubGlobal('fetch', fetchSpy);+ const consoleSpies = (['log', 'warn', 'error', 'info', 'debug'] as const).map((level) =>+ vi.spyOn(console, level).mockImplementation(() => {}),+ );++ for (const candidate of fixture.candidates) {+ isCodexLegacyWarningUpdate(asUpdate(candidate.update), CODEX);+ }+ for (const negative of fixture.negatives) {+ isCodexLegacyWarningUpdate(asUpdate(negative.update), agentNamed(negative.agent));+ }++ expect(fetchSpy).not.toHaveBeenCalled();+ for (const spy of consoleSpies) expect(spy).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/acp/codex-legacy-notice.ts b/packages/core/src/acp/codex-legacy-notice.tsnew file mode 100644index 000000000..7ec617263--- /dev/null+++ b/packages/core/src/acp/codex-legacy-notice.ts@@ -0,0 +1,107 @@+/**+ * Recognition of the one legacy producer envelope OK restyles as runtime+ * status instead of agent speech.+ *+ * Codex models operational warnings as typed events internally, but its ACP+ * adapter forwards them typed only to a client that negotiated JetBrains'+ * private capability. Every other client — OK included — gets the legacy+ * fallback instead: the warning flattened into the assistant message stream as+ * an ordinary text chunk behind an English prefix the adapter fabricates.+ * Nothing structured survives that flattening, so the envelope's own shape is+ * the only evidence a client has to work with.+ *+ * That makes this a trust decision rather than a text-matching convenience,+ * and the rule is deliberately unforgiving: every gate must hold or the event+ * is ordinary prose. A false positive restyles something the agent genuinely+ * said, which is the defect this surface exists to fix, so ambiguity always+ * resolves toward prose. The decision is also all-or-nothing on the whole+ * event — a leading warning-looking paragraph is never carved out of a larger+ * body, because a blank line is content here, not a protocol boundary.+ *+ * Lives in core because the server (which must keep these events from merging+ * into their neighbours) and the app (which mints the notice) have to agree+ * byte for byte. A second copy of this rule is a drift bug waiting to happen.+ */++import type { SessionUpdate } from '@agentclientprotocol/sdk';++/**+ * The subset of the thread's agent identity this decision reads. Its own shape+ * rather than the full `ThreadAgentInfo` so callers can consult the predicate+ * before the handshake has filled in display fields.+ */+export interface CodexLegacyAgentIdentity {+ readonly source: 'registry' | 'custom';+ readonly id: string;+}++/**+ * The only producer whose envelope is characterized. A custom entry can reuse+ * the id while spawning a completely different executable, which is why the+ * source is checked alongside it.+ */+const CODEX_REGISTRY_AGENT_ID = 'codex-acp';++/**+ * The adapter's two fabricated literals, trailing space included. Neither is a+ * prefix of the other and neither contains a newline, so a match is never+ * ambiguous and can never overlap the terminator.+ */+const LEGACY_WARNING_PREFIXES = ['Warning: ', 'Config warning: '] as const;++/**+ * The adapter appends these bytes after interpolating the message, so requiring+ * them rejects a truncated or streamed-partial envelope, and any trimmed prose+ * that happens to open with one of the literals above. The gate is `endsWith`,+ * not an equality on the final two bytes, so a message whose own details close+ * with blank lines still matches on its longer trailing newline run. It does+ * NOT separate a warning from the adapter's other no-ID chrome: context+ * compaction and turn-error text terminate the same way. Only the prefix does+ * that, which is why relaxing the prefix gate would leave nothing behind it.+ */+const LEGACY_WARNING_TERMINATOR = '\n\n';++/**+ * Whether `update` is a complete legacy Codex warning envelope for a thread+ * running `agent`.+ *+ * Total by construction: `update` arrives as JSON parsed off a socket or off+ * the persisted event log, so its static type is a claim about untrusted bytes+ * rather than a guarantee, and every field is re-checked here.+ *+ * The verdict is settled by a bounded window at each end of the message text.+ * Whatever sits between those windows cannot move it, which is what keeps the+ * interior from being reinterpreted: no amount of body, and no structure+ * inside it, turns prose into a notice or a notice into prose.+ */+export function isCodexLegacyWarningUpdate(+ update: SessionUpdate | null | undefined,+ agent: CodexLegacyAgentIdentity | null | undefined,+): boolean {+ if (agent === null || agent === undefined) return false;+ if (agent.source !== 'registry' || agent.id !== CODEX_REGISTRY_AGENT_ID) return false;++ if (typeof update !== 'object' || update === null) return false;+ const candidate = update as { sessionUpdate?: unknown; messageId?: unknown; content?: unknown };+ if (candidate.sessionUpdate !== 'agent_message_chunk') return false;++ // The adapter drops the key entirely for these events while every ordinary+ // answer carries the item id, so an absent one is what survives. The schema+ // does admit an explicit null here, but a producer that sends one chose to+ // say something rather than say nothing, and this envelope is characterized+ // by the silence. Absent is not fully distinguishable downstream either: the+ // SDK's validator defaults a malformed id to undefined, so on the socket+ // path a mangled id reads as no id. `!== undefined` is still the right test+ // rather than an own-property check, because it is what keeps the server and+ // the app from disagreeing about a value the JSON round trip dropped.+ if (candidate.messageId !== undefined) return false;++ const content = candidate.content;+ if (typeof content !== 'object' || content === null) return false;+ const block = content as { type?: unknown; text?: unknown };+ if (block.type !== 'text' || typeof block.text !== 'string') return false;++ const text = block.text;+ if (!text.endsWith(LEGACY_WARNING_TERMINATOR)) return false;+ return LEGACY_WARNING_PREFIXES.some((prefix) => text.startsWith(prefix));+}diff --git a/packages/core/src/acp/thread-protocol.typelock.test.ts b/packages/core/src/acp/thread-protocol.typelock.test.tsnew file mode 100644index 000000000..4b46293b4--- /dev/null+++ b/packages/core/src/acp/thread-protocol.typelock.test.ts@@ -0,0 +1,89 @@+import { readFileSync } from 'node:fs';+import { createRequire } from 'node:module';+import { describe, expect, test } from 'vitest';+import { TRIAGED_SESSION_UPDATE_KINDS } from './thread-protocol.typelock.ts';++/**+ * The sibling typelock pins the session-update roster at compile time, which+ * only holds while that file is present and reachable by `tsc`. Deleting it,+ * or dropping it out of the typecheck include, would retire the tripwire in+ * silence. These read the same roster the SDK ships as data, so the alarm+ * survives independently of the type graph.+ */++/**+ * The JSON schema the SDK ships as a declared subpath export — the package's+ * own statement of the protocol it implements. What its generated runtime+ * validator does with a discriminator this roster omits is pinned separately,+ * by `packages/server/src/acp/typed-notice-canary.test.ts`.+ */+const SDK_SCHEMA_SPECIFIER = '@agentclientprotocol/sdk/schema/schema.json';++type SessionUpdateVariant = { properties?: { sessionUpdate?: { const?: unknown } } };+type ProtocolSchema = { $defs?: { SessionUpdate?: { oneOf?: SessionUpdateVariant[] } } };++/**+ * Throws rather than returning a short roster when the encoding moves. A+ * silently empty list would leave every check below passing while watching+ * nothing at all.+ */+function sessionUpdateKindsIn(schema: ProtocolSchema): string[] {+ const variants = schema.$defs?.SessionUpdate?.oneOf;+ if (variants === undefined) {+ throw new Error(+ `${SDK_SCHEMA_SPECIFIER} no longer exposes $defs.SessionUpdate.oneOf. The session-update roster moved; re-point this check before trusting it.`,+ );+ }+ return variants.map((variant, index) => {+ const kind = variant.properties?.sessionUpdate?.const;+ if (typeof kind !== 'string') {+ throw new Error(+ `SessionUpdate variant ${index} has no string sessionUpdate const. The discriminator encoding changed; re-point this check before trusting it.`,+ );+ }+ return kind;+ });+}++function loadSdkSchema(): ProtocolSchema {+ const path = createRequire(import.meta.url).resolve(SDK_SCHEMA_SPECIFIER);+ return JSON.parse(readFileSync(path, 'utf8')) as ProtocolSchema;+}++const declaredSessionUpdateKinds = (): string[] => sessionUpdateKindsIn(loadSdkSchema());++describe('installed SDK session-update roster', () => {+ test('declares exactly the discriminators that have been triaged', () => {+ expect([...declaredSessionUpdateKinds()].sort()).toEqual(+ [...TRIAGED_SESSION_UPDATE_KINDS].sort(),+ );+ });++ test('does not yet declare the typed notice discriminator', () => {+ const declared = declaredSessionUpdateKinds();++ // Naming a discriminator the SDK certainly has keeps the absence claim+ // from passing on an extraction that found nothing.+ expect(declared).toContain('agent_message_chunk');+ expect(declared).not.toContain('notice');+ });++ test('reports a notice discriminator once one is declared', () => {+ const grown = structuredClone(loadSdkSchema());+ grown.$defs?.SessionUpdate?.oneOf?.push({ properties: { sessionUpdate: { const: 'notice' } } });++ expect(sessionUpdateKindsIn(grown)).toContain('notice');+ });++ test('refuses a roster when the SessionUpdate variants have moved', () => {+ expect(() => sessionUpdateKindsIn({ $defs: {} })).toThrow(/re-point this check/);+ });++ test('refuses a roster when a variant carries no string discriminator', () => {+ const reshaped: ProtocolSchema = {+ $defs: { SessionUpdate: { oneOf: [{ properties: { sessionUpdate: {} } }] } },+ };++ expect(() => sessionUpdateKindsIn(reshaped)).toThrow(/discriminator encoding changed/);+ });+});diff --git a/packages/core/src/acp/thread-protocol.typelock.ts b/packages/core/src/acp/thread-protocol.typelock.tsindex ba0d6185f..04dfc5cda 100644--- a/packages/core/src/acp/thread-protocol.typelock.ts+++ b/packages/core/src/acp/thread-protocol.typelock.ts@@ -1,11 +1,17 @@/*** Compile-time pins on the `@agentclientprotocol/sdk` unions and shapes this- * codebase attaches BEHAVIOR to. Nothing here runs — each alias fails- * `tsc --noEmit` when an SDK upgrade changes the pinned contract, turning- * silent semantic drift (a new union member falling through a `default:`- * branch, a reshaped field read through a cast) into a loud, located build- * error on the upgrade PR. When a pin fires: review the dependents named on- * it, adapt them if needed, then update the pin to the new shape.+ * codebase attaches BEHAVIOR to. Every alias fails `tsc --noEmit` when an SDK+ * upgrade changes the pinned contract, turning silent semantic drift (a new+ * union member falling through a `default:` branch, a reshaped field read+ * through a cast) into a loud, located build error on the upgrade PR. When a+ * pin fires: review the dependents named on it, adapt them if needed, then+ * update the pin to the new shape.+ *+ * `TRIAGED_SESSION_UPDATE_KINDS` is the one runtime value here. It exists so+ * the session-update roster has a single spelling: the compile-time pin below+ * derives its expected union from it, and a runtime check compares it against+ * the discriminators the installed SDK actually declares. A second hand-copied+ * list would let those two tripwires disagree about what has been triaged.*/import type {@@ -29,27 +35,38 @@ type Equal<A, B> =(<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;type Expect<T extends true> = T;+/**+ * Every `session/update` discriminator that has been looked at and given a+ * deliberate disposition — rendered, folded, or knowingly ignored. Adding a+ * member here is the act of triaging it; there is no way to accept a new SDK+ * discriminator without editing this list.+ *+ * `notice` is deliberately absent: no released SDK carries it yet, and its+ * arrival is the trigger for adopting typed agent notices rather than a+ * routine roster update.+ */+export const TRIAGED_SESSION_UPDATE_KINDS = [+ 'user_message_chunk',+ 'agent_message_chunk',+ 'agent_thought_chunk',+ 'tool_call',+ 'tool_call_update',+ 'plan',+ 'plan_update',+ 'plan_removed',+ 'available_commands_update',+ 'current_mode_update',+ 'config_option_update',+ 'session_info_update',+ 'usage_update',+] as const;+// Dependents: the thread model's `applyUpdate` switch routes on this// discriminant with a permissive `default:` (forward compatibility), so a// NEW member never breaks the build — it silently renders as nothing. This// pin makes the addition loud so someone decides how it should render.export type PinSessionUpdateKinds = Expect<- Equal<- SessionUpdate['sessionUpdate'],- | 'user_message_chunk'- | 'agent_message_chunk'- | 'agent_thought_chunk'- | 'tool_call'- | 'tool_call_update'- | 'plan'- | 'plan_update'- | 'plan_removed'- | 'available_commands_update'- | 'current_mode_update'- | 'config_option_update'- | 'session_info_update'- | 'usage_update'- >+ Equal<SessionUpdate['sessionUpdate'], (typeof TRIAGED_SESSION_UPDATE_KINDS)[number]>>;// Dependents: the thread manager forwards `availableCommands` verbatim ontodiff --git a/packages/core/tsdown.config.ts b/packages/core/tsdown.config.tsindex 3ca1ad9fa..e99c9cd41 100644--- a/packages/core/tsdown.config.ts+++ b/packages/core/tsdown.config.ts@@ -12,6 +12,7 @@ export default defineConfig({'acp-thread-protocol': 'src/acp/thread-protocol.ts','acp-agent-posture': 'src/acp/agent-posture.ts','acp-permissive-mode': 'src/acp/permissive-mode.ts',+ 'acp-codex-legacy-notice': 'src/acp/codex-legacy-notice.ts','desktop-bridge': 'src/desktop-bridge.ts',},unbundle: false,diff --git a/packages/desktop/electron.vite.config.ts b/packages/desktop/electron.vite.config.tsindex 9ad59f753..01cf8c09b 100644--- a/packages/desktop/electron.vite.config.ts+++ b/packages/desktop/electron.vite.config.ts@@ -9,8 +9,13 @@ import { rendererHtmlInput } from '../app/vite.entries';import { RENDERER_BABEL_OPTIONS } from '../app/vite.react-babel';// Inject the app's version onto import.meta.env.VITE_APP_VERSION for the-// Electron renderer bundle — the separate build path the desktop app ships.-// `packages/app/vite.config.ts` covers dev + `ok ui`; this covers the renderer.+// renderer this config builds, which serves unpackaged runs only. A PACKAGED+// window loads `packages/app`'s own `dist` instead: the CLI copies it to+// `cli/dist/public` and electron-builder ships that as `Resources/app` (see+// `electron-builder.yml` `extraResources`, and the `app.isPackaged` branch in+// `src/main/index.ts`). Both bundles come out of `packages/app` by the same+// pipeline, so treat this as the second consumer of that source, not as a+// separate artifact the app ships.injectAppVersionEnv();/**diff --git a/packages/server/src/acp/event-log-bounds.test.ts b/packages/server/src/acp/event-log-bounds.test.tsindex bcda53d75..c32a3c721 100644--- a/packages/server/src/acp/event-log-bounds.test.ts+++ b/packages/server/src/acp/event-log-bounds.test.ts@@ -1,10 +1,18 @@import type { SessionUpdate } from '@agentclientprotocol/sdk';+import type { CodexLegacyAgentIdentity } from '@inkeep/open-knowledge-core/acp/codex-legacy-notice';import type { ThreadEvent } from '@inkeep/open-knowledge-core/acp/thread-protocol';import { describe, expect, test } from 'vitest';+import fixture from '../../../../test-support/fixtures/codex-legacy-warning-envelopes.json' with {+ type: 'json',+};import { boundSessionUpdateForLog, coalesceChunkInto } from './event-log-bounds.ts';const big = 'x'.repeat(50_000);+const CODEX: CodexLegacyAgentIdentity = fixture.agents.codexRegistry;+const CODEX_CUSTOM: CodexLegacyAgentIdentity = fixture.agents.codexCustom;+const OTHER_AGENT: CodexLegacyAgentIdentity = fixture.agents.claudeRegistry;+/** A `session_update` transcript event carrying a streamed text chunk. */function chunk(sessionUpdate: string,@@ -74,73 +82,75 @@ describe('boundSessionUpdateForLog', () => {describe('coalesceChunkInto', () => {test('folds consecutive same-stream text chunks into the tail, in order', () => {const prev = chunk('agent_message_chunk', 'Hello');- expect(coalesceChunkInto(prev, chunk('agent_message_chunk', ', '))).toBe(true);- expect(coalesceChunkInto(prev, chunk('agent_message_chunk', 'world'))).toBe(true);+ expect(coalesceChunkInto(prev, chunk('agent_message_chunk', ', '), CODEX)).toBe(true);+ expect(coalesceChunkInto(prev, chunk('agent_message_chunk', 'world'), CODEX)).toBe(true);expect(textOf(prev)).toBe('Hello, world');});test('folds thought and user chunks too (both coalesce client-side)', () => {const thought = chunk('agent_thought_chunk', 'think');- expect(coalesceChunkInto(thought, chunk('agent_thought_chunk', 'ing'))).toBe(true);+ expect(coalesceChunkInto(thought, chunk('agent_thought_chunk', 'ing'), CODEX)).toBe(true);expect(textOf(thought)).toBe('thinking');const user = chunk('user_message_chunk', 'a');- expect(coalesceChunkInto(user, chunk('user_message_chunk', 'b'))).toBe(true);+ expect(coalesceChunkInto(user, chunk('user_message_chunk', 'b'), CODEX)).toBe(true);expect(textOf(user)).toBe('ab');});test('does not fold across differing chunk kinds', () => {const message = chunk('agent_message_chunk', 'answer');- expect(coalesceChunkInto(message, chunk('agent_thought_chunk', 'thought'))).toBe(false);+ expect(coalesceChunkInto(message, chunk('agent_thought_chunk', 'thought'), CODEX)).toBe(false);expect(textOf(message)).toBe('answer');});test('does not fold non-streaming session updates', () => {const toolCall = chunk('tool_call', 'x');- expect(coalesceChunkInto(toolCall, chunk('tool_call', 'y'))).toBe(false);+ expect(coalesceChunkInto(toolCall, chunk('tool_call', 'y'), CODEX)).toBe(false);});test('does not fold across differing messageId (separate bubbles client-side)', () => {const a = chunk('agent_message_chunk', 'a', { messageId: 'm1' });- expect(coalesceChunkInto(a, chunk('agent_message_chunk', 'b', { messageId: 'm2' }))).toBe(- false,- );+ expect(+ coalesceChunkInto(a, chunk('agent_message_chunk', 'b', { messageId: 'm2' }), CODEX),+ ).toBe(false);// Same explicit messageId still folds.const c = chunk('agent_message_chunk', 'c', { messageId: 'm1' });- expect(coalesceChunkInto(c, chunk('agent_message_chunk', 'd', { messageId: 'm1' }))).toBe(true);+ expect(+ coalesceChunkInto(c, chunk('agent_message_chunk', 'd', { messageId: 'm1' }), CODEX),+ ).toBe(true);expect(textOf(c)).toBe('cd');});test('missing messageId matches missing messageId (both default)', () => {const a = chunk('agent_message_chunk', 'a');- expect(coalesceChunkInto(a, chunk('agent_message_chunk', 'b'))).toBe(true);+ expect(coalesceChunkInto(a, chunk('agent_message_chunk', 'b'), CODEX)).toBe(true);expect(textOf(a)).toBe('ab');});test('does not fold when either side is non-text content (image chunk)', () => {const image = chunk('agent_message_chunk', '', { type: 'image' });- expect(coalesceChunkInto(image, chunk('agent_message_chunk', 'text'))).toBe(false);+ expect(coalesceChunkInto(image, chunk('agent_message_chunk', 'text'), CODEX)).toBe(false);const text = chunk('agent_message_chunk', 'text');- expect(coalesceChunkInto(text, chunk('agent_message_chunk', '', { type: 'image' }))).toBe(- false,- );+ expect(+ coalesceChunkInto(text, chunk('agent_message_chunk', '', { type: 'image' }), CODEX),+ ).toBe(false);});test('does not fold non-session_update events', () => {const userMsg: ThreadEvent = { kind: 'user_message', content: 'hi', ts: 1 };- expect(coalesceChunkInto(userMsg, chunk('agent_message_chunk', 'x'))).toBe(false);- expect(coalesceChunkInto(chunk('agent_message_chunk', 'x'), userMsg)).toBe(false);+ expect(coalesceChunkInto(userMsg, chunk('agent_message_chunk', 'x'), CODEX)).toBe(false);+ expect(coalesceChunkInto(chunk('agent_message_chunk', 'x'), userMsg, CODEX)).toBe(false);});test('stops folding once the tail hits the size cap (bounds one line)', () => {const prev = chunk('agent_message_chunk', 'x'.repeat(16_000));// At the cap: refuses further folds so no single line grows unbounded.- expect(coalesceChunkInto(prev, chunk('agent_message_chunk', 'more'))).toBe(false);+ expect(coalesceChunkInto(prev, chunk('agent_message_chunk', 'more'), CODEX)).toBe(false);expect(textOf(prev)).toBe('x'.repeat(16_000));// Just under the cap still folds once (may exceed the cap by the added// chunk — the cap gates the NEXT fold, it doesn't truncate).const under = chunk('agent_message_chunk', 'y'.repeat(15_999));- expect(coalesceChunkInto(under, chunk('agent_message_chunk', 'zz'))).toBe(true);- expect(coalesceChunkInto(under, chunk('agent_message_chunk', 'no'))).toBe(false);+ expect(coalesceChunkInto(under, chunk('agent_message_chunk', 'zz'), CODEX)).toBe(true);+ expect(coalesceChunkInto(under, chunk('agent_message_chunk', 'no'), CODEX)).toBe(false);});});@@ -154,27 +164,157 @@ describe('coalesceChunkInto — terminal output', () => {test('folds consecutive chunks of the same terminal', () => {const prev = terminalChunk('t1', 'line one\n');- expect(coalesceChunkInto(prev, terminalChunk('t1', 'line two\n'))).toBe(true);+ expect(coalesceChunkInto(prev, terminalChunk('t1', 'line two\n'), CODEX)).toBe(true);if (prev.kind !== 'terminal_output') throw new Error('unreachable');expect(prev.chunk).toBe('line one\nline two\n');});test('does not fold across terminals or event kinds', () => {const prev = terminalChunk('t1', 'a');- expect(coalesceChunkInto(prev, terminalChunk('t2', 'b'))).toBe(false);+ expect(coalesceChunkInto(prev, terminalChunk('t2', 'b'), CODEX)).toBe(false);expect(- coalesceChunkInto(prev, {- kind: 'terminal_exit',- terminalId: 't1',- exitCode: 0,- signal: null,- ts: 2,- }),+ coalesceChunkInto(+ prev,+ {+ kind: 'terminal_exit',+ terminalId: 't1',+ exitCode: 0,+ signal: null,+ ts: 2,+ },+ CODEX,+ ),).toBe(false);});test('stops folding once the tail chunk hits the size cap', () => {const prev = terminalChunk('t1', 'x'.repeat(16_000));- expect(coalesceChunkInto(prev, terminalChunk('t1', 'more'))).toBe(false);+ expect(coalesceChunkInto(prev, terminalChunk('t1', 'more'), CODEX)).toBe(false);+ });+});++describe('coalesceChunkInto — Codex legacy warning boundaries', () => {+ /**+ * A retained event carrying one of the fixture's recorded producer envelopes.+ * Cloned because a fold mutates `prev` in place, and the fixture objects are+ * shared across every test in this file.+ */+ const recorded = (name: string): ThreadEvent => {+ const candidate = fixture.candidates.find((c) => c.name === name);+ if (candidate === undefined) throw new Error(`no recorded candidate '${name}'`);+ return {+ kind: 'session_update',+ update: structuredClone(candidate.update) as unknown as SessionUpdate,+ ts: 1,+ };+ };+ const neighbor = (name: 'contextCompacted' | 'turnError'): ThreadEvent => ({+ kind: 'session_update',+ update: structuredClone(fixture.neighbors[name].update) as unknown as SessionUpdate,+ ts: 1,+ });+ const nearMiss = (negative: { update: unknown }): ThreadEvent => ({+ kind: 'session_update',+ update: structuredClone(negative.update) as SessionUpdate,+ ts: 1,+ });++ test('a warning does not absorb the no-ID chrome that follows it', () => {+ const warning = recorded('warning-skills-budget');+ const before = textOf(warning);++ expect(coalesceChunkInto(warning, neighbor('contextCompacted'), CODEX)).toBe(false);+ expect(textOf(warning)).toBe(before);+ });++ test('no-ID chrome does not absorb the warning that follows it', () => {+ const chrome = neighbor('contextCompacted');+ const before = textOf(chrome);++ expect(coalesceChunkInto(chrome, recorded('warning-skills-budget'), CODEX)).toBe(false);+ expect(textOf(chrome)).toBe(before);+ });++ test('two adjacent warnings stay two events', () => {+ const first = recorded('warning-skills-budget');+ const before = textOf(first);++ expect(coalesceChunkInto(first, recorded('config-warning-summary-only'), CODEX)).toBe(false);+ expect(textOf(first)).toBe(before);+ });++ test('a config warning carrying internal blank lines is preserved whole', () => {+ const configWarning = recorded('config-warning-with-details');+ const before = textOf(configWarning);++ expect(before).toContain('\n\n-');+ expect(coalesceChunkInto(configWarning, neighbor('turnError'), CODEX)).toBe(false);+ expect(textOf(configWarning)).toBe(before);+ });++ test('ordinary no-ID Codex chrome still coalesces exactly as before', () => {+ const chrome = neighbor('contextCompacted');+ const joined = textOf(chrome) + textOf(neighbor('turnError'));++ expect(coalesceChunkInto(chrome, neighbor('turnError'), CODEX)).toBe(true);+ expect(textOf(chrome)).toBe(joined);+ });++ test('the same envelope from another registry agent coalesces unchanged', () => {+ const warning = recorded('warning-skills-budget');+ const joined = textOf(warning) + textOf(neighbor('contextCompacted'));++ expect(coalesceChunkInto(warning, neighbor('contextCompacted'), OTHER_AGENT)).toBe(true);+ expect(textOf(warning)).toBe(joined);+ });++ test('a custom agent reusing the Codex id coalesces unchanged', () => {+ const warning = recorded('warning-skills-budget');++ expect(coalesceChunkInto(warning, neighbor('contextCompacted'), CODEX_CUSTOM)).toBe(true);+ });++ test.each(+ fixture.negatives.map((n) => [n.name, n] as const),+ )('near miss %s folds as if the guard were not there', (_name, negative) => {+ // Whether a near miss folds at all is the ordinary predicate's business —+ // kind, messageId, and content shape. What must never happen is the guard+ // firing on one and inventing a boundary the producer never drew, so the+ // oracle is the verdict under an identity the guard can never match.+ // A few negatives are near misses only BECAUSE of their agent, which is+ // the identity the fixture records alongside them.+ const agentKey = (negative as { agent?: string }).agent;+ const declared =+ agentKey === undefined+ ? CODEX+ : (fixture.agents as Record<string, CodexLegacyAgentIdentity>)[agentKey];++ const asDeclared = coalesceChunkInto(+ nearMiss(negative),+ neighbor('contextCompacted'),+ declared,+ );+ const guardUnreachable = coalesceChunkInto(+ nearMiss(negative),+ neighbor('contextCompacted'),+ OTHER_AGENT,+ );++ expect(asDeclared).toBe(guardUnreachable);+ });++ test('a warning is preserved even when the neighbour would otherwise fold', () => {+ // The chrome pair folds (proved above), so refusing here isolates the+ // warning rather than reflecting a pair that was never mergeable.+ const chrome = neighbor('turnError');++ expect(coalesceChunkInto(chrome, recorded('config-warning-summary-only'), CODEX)).toBe(false);+ });++ test('terminal output is unaffected by the agent identity', () => {+ const prev: ThreadEvent = { kind: 'terminal_output', terminalId: 't1', chunk: 'a', ts: 1 };+ const next: ThreadEvent = { kind: 'terminal_output', terminalId: 't1', chunk: 'b', ts: 2 };++ expect(coalesceChunkInto(prev, next, CODEX)).toBe(true);});});diff --git a/packages/server/src/acp/event-log-bounds.ts b/packages/server/src/acp/event-log-bounds.tsindex 155aff19f..ce691caa9 100644--- a/packages/server/src/acp/event-log-bounds.ts+++ b/packages/server/src/acp/event-log-bounds.ts@@ -8,6 +8,8 @@*/import type { SessionUpdate } from '@agentclientprotocol/sdk';+import type { CodexLegacyAgentIdentity } from '@inkeep/open-knowledge-core/acp/codex-legacy-notice';+import { isCodexLegacyWarningUpdate } from '@inkeep/open-knowledge-core/acp/codex-legacy-notice';import type { ThreadEvent } from '@inkeep/open-knowledge-core/acp/thread-protocol';const EVENT_TEXT_CAP = 16_000;@@ -112,8 +114,16 @@ function chunkMessageId(u: ChunkUpdate): string {* Callable ONLY on the not-yet-flushed tail event: growing an event whose seq* was already broadcast/persisted would break the line-index-IS-the-seq* contract. A fold assigns no new seq, so that contract is preserved.+ *+ * `agent` is the thread's configured agent identity, required so no call site+ * can reach the fold without deciding whether the Codex legacy carve-out below+ * applies.*/-export function coalesceChunkInto(prev: ThreadEvent, next: ThreadEvent): boolean {+export function coalesceChunkInto(+ prev: ThreadEvent,+ next: ThreadEvent,+ agent: CodexLegacyAgentIdentity,+): boolean {// Terminal output folds along the same lines as streamed text: the app// concatenates a terminal's chunks anyway, so consecutive chunks of the// SAME terminal merge into one retained event (and one seq).@@ -124,6 +134,18 @@ export function coalesceChunkInto(prev: ThreadEvent, next: ThreadEvent): booleanreturn true;}if (prev.kind !== 'session_update' || next.kind !== 'session_update') return false;+ // One legacy producer flattens operational warnings into this same text+ // stream, and the only evidence that it did is the shape of the event the+ // producer emitted. Folding either side into its neighbour destroys that+ // evidence irreversibly, so a complete envelope is kept whole. Retention is+ // all this changes: the bytes, the event kind, and the order are the+ // producer's, and the warning reading is minted downstream, not here.+ if (+ isCodexLegacyWarningUpdate(prev.update, agent) ||+ isCodexLegacyWarningUpdate(next.update, agent)+ ) {+ return false;+ }const p = prev.update as ChunkUpdate;const n = next.update as ChunkUpdate;if (p.sessionUpdate !== n.sessionUpdate || !COALESCIBLE_CHUNK_KINDS.has(n.sessionUpdate)) {diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.tsindex 7f5d6fbc0..eff8ed408 100644--- a/packages/server/src/acp/thread-manager.integration.test.ts+++ b/packages/server/src/acp/thread-manager.integration.test.ts@@ -22,6 +22,9 @@ import type {} from '@inkeep/open-knowledge-core/acp/thread-protocol';import { afterEach, describe, expect, test } from 'vitest';import * as Y from 'yjs';+import codexFixture from '../../../../test-support/fixtures/codex-legacy-warning-envelopes.json' with {+ type: 'json',+};import type { AgentPresenceBroadcaster } from '../agent-presence.ts';import type { AgentSessionManager } from '../agent-sessions.ts';import { getLogger, type PinoLogger } from '../logger.ts';@@ -4281,3 +4284,366 @@ describe('agent failures reach the server log', () => {expect(String(exitLine?.obj.machineDetail)).toContain('ran out of memory');}, 30_000);});++/**+ * The one legacy producer envelope the transcript restyles as runtime status.+ * Recorded from the registry-selected adapter; the fake agent below replays+ * those exact bytes so the server's retention decision is made against real+ * producer output rather than a paraphrase of it.+ */+const CODEX_WARNING_TEXT = codexFixture.candidates.find((c) => c.name === 'warning-skills-budget')+ ?.update.content.text as string;+const CODEX_NEIGHBOR_TEXTS = [+ codexFixture.neighbors.contextCompacted.update.content.text,+ codexFixture.neighbors.turnError.update.content.text,+] as const;++/**+ * A turn that emits real no-ID Codex chrome on both sides of a real warning+ * envelope, written to stdout in ONE call so the whole run reaches the+ * coalescer inside a single flush window. Neighbours on both sides are what+ * makes the retention verdict observable: a boundary can then only come from+ * the guard, never from a flush landing there.+ */+function codexLegacyTurnTexts(): string[] {+ const [compacted, turnError] = CODEX_NEIGHBOR_TEXTS;+ return [compacted, compacted, turnError, CODEX_WARNING_TEXT, turnError, compacted, turnError];+}++function agentTextUpdate(text: string): unknown {+ return { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } };+}++/**+ * A fake ACP agent reachable the way a registry agent is: through an `npx`+ * shim on the manifest's own overlay PATH. Registry source is not cosmetic+ * here — it is half of the identity the retention guard consults, and a custom+ * entry could never carry it.+ *+ * `updates` are emitted verbatim as the payloads of one prompt turn, so a+ * caller can put a shape the SDK does not accept on the wire.+ */+function writeRegistryAgentShims(binDir: string, updates: readonly unknown[]): void {+ const agentPath = join(binDir, 'agent.mjs');+ writeFileSync(+ agentPath,+ `+const write = (m) => process.stdout.write(JSON.stringify(m) + '\\n');+const UPDATES = ${JSON.stringify(updates)};+let buffer = '';+process.stdin.setEncoding('utf8');+process.stdin.on('data', (chunk) => {+ buffer += chunk;+ let idx = buffer.indexOf('\\n');+ while (idx !== -1) {+ const line = buffer.slice(0, idx);+ buffer = buffer.slice(idx + 1);+ idx = buffer.indexOf('\\n');+ if (line.trim() === '') continue;+ const msg = JSON.parse(line);+ const reply = (result) => write({ jsonrpc: '2.0', id: msg.id, result });+ if (msg.method === 'initialize') {+ reply({ protocolVersion: 1, agentCapabilities: {} });+ } else if (msg.method === 'session/new') {+ reply({ sessionId: 'sess-fixed' });+ } else if (msg.method === 'session/prompt') {+ const burst = UPDATES.map((update) =>+ JSON.stringify({+ jsonrpc: '2.0',+ method: 'session/update',+ params: { sessionId: 'sess-fixed', update },+ }),+ ).join('\\n');+ process.stdout.write(burst + '\\n');+ reply({ stopReason: 'end_turn' });+ } else if (msg.id !== undefined) {+ reply({});+ }+ }+});+`,+ );+ writeFileSync(join(binDir, 'npx'), `#!/bin/sh\nexec "${process.execPath}" "${agentPath}"\n`, {+ mode: 0o755,+ });+ // The launch path probes `node --version` for npx compatibility before it+ // spawns anything, and the overlay PATH is the only place it can look.+ writeFileSync(+ join(binDir, 'node'),+ `#!/bin/sh\nif [ "$1" = "--version" ]; then echo v${process.versions.node}; exit 0; fi\nexec "${process.execPath}" "$@"\n`,+ { mode: 0o755 },+ );+}++function registryManagerFor(+ agentId: string,+ contentDir: string,+ localDir: string,+ binDir: string,+): AcpThreadManager {+ const manifest = {+ id: agentId,+ name: agentId,+ version: '1.6.2',+ distribution: { npx: { package: `@fake/${agentId}`, env: { PATH: binDir } } },+ };+ return makeManager(contentDir, localDir, {+ registry: new AcpRegistry({+ localDir,+ log,+ fetchImpl: (async () =>+ new Response(JSON.stringify({ agents: [manifest] }), {+ status: 200,+ })) as unknown as typeof fetch,+ }),+ });+}++describe.skipIf(process.platform === 'win32')('Codex legacy warning event boundaries', () => {+ type Retained = { seq: number; event: ThreadEvent };++ const collectAll =+ (into: Retained[]) =>+ (frame: ThreadServerFrame): void => {+ if (frame.op === 'event') into.push({ seq: frame.seq, event: frame.event });+ if (frame.op === 'events') {+ for (const [i, event] of frame.events.entries()) {+ into.push({ seq: frame.fromSeq + i, event });+ }+ }+ };++ const messageTexts = (retained: Retained[]): string[] =>+ retained+ .map((r) => r.event)+ .filter((e) => e.kind === 'session_update')+ .map((e) => (e as { update: Record<string, unknown> }).update)+ .filter((u) => u.sessionUpdate === 'agent_message_chunk')+ .map((u) => (u.content as { text: string }).text);++ async function runTurn(+ agentId: string,+ contentDir: string,+ localDir: string,+ binDir: string,+ ): Promise<{ manager: AcpThreadManager; threadId: string; retained: Retained[] }> {+ writeRegistryAgentShims(binDir, codexLegacyTurnTexts().map(agentTextUpdate));+ const manager = registryManagerFor(agentId, contentDir, localDir, binDir);+ await manager.init();+ const info = await manager.createThread({ agent: { source: 'registry', id: agentId } });+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'ready',+ 15_000,+ 'agent ready',+ );+ manager.sendPrompt(info.threadId, 'go');+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'turn ended');+ const retained: Retained[] = [];+ await manager.subscribe(info.threadId, 0, collectAll(retained));+ return { manager, threadId: info.threadId, retained };+ }++ test('a registry Codex warning is retained as its own event, never merged', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const { retained } = await runTurn('codex-acp', contentDir, localDir, tmp());+ const texts = messageTexts(retained);++ expect(texts.filter((t) => t === CODEX_WARNING_TEXT)).toHaveLength(1);+ expect(texts.filter((t) => t !== CODEX_WARNING_TEXT && t.includes(CODEX_WARNING_TEXT))).toEqual(+ [],+ );+ }, 45_000);++ test('the retained log keeps the producer bytes, kinds, and order intact', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const { retained } = await runTurn('codex-acp', contentDir, localDir, tmp());++ expect(messageTexts(retained).join('')).toBe(codexLegacyTurnTexts().join(''));+ // Retention is all the guard changes: no event kind was invented for it,+ // and folding still assigns no seq of its own.+ expect(retained.map((r) => r.event.kind)).not.toContain('agent_notice');+ expect(retained.map((r) => r.seq)).toEqual(retained.map((_, i) => i));+ }, 45_000);++ test('ordinary no-ID chrome around the warning still coalesces', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const { retained } = await runTurn('codex-acp', contentDir, localDir, tmp());+ const texts = messageTexts(retained);++ // Seven emitted chunks; the guard draws exactly two boundaries, so the+ // neighbours on each side must still have folded into far fewer events.+ expect(texts.length).toBeLessThan(codexLegacyTurnTexts().length);+ expect(+ texts.some((t) => t !== CODEX_WARNING_TEXT && t.length > CODEX_NEIGHBOR_TEXTS[0].length),+ ).toBe(true);+ }, 45_000);++ test('the same envelope from another registry agent is coalesced as before', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const { retained } = await runTurn('claude-acp', contentDir, localDir, tmp());+ const texts = messageTexts(retained);++ // The identity is what the decision turns on: byte-identical output from a+ // different registry agent must stay ordinary prose. A flush cannot fake+ // this — isolating the warning would take two timer fires inside one burst.+ expect(texts).not.toContain(CODEX_WARNING_TEXT);+ expect(texts.filter((t) => t.includes(CODEX_WARNING_TEXT))).toHaveLength(1);+ expect(texts.join('')).toBe(codexLegacyTurnTexts().join(''));+ }, 45_000);++ test('the warning occupies one NDJSON line at its own seq', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const { manager, threadId, retained } = await runTurn('codex-acp', contentDir, localDir, tmp());+ await manager.closeThread(threadId);++ const lines = readFileSync(join(localDir, 'threads', `${threadId}.ndjson`), 'utf8')+ .split('\n')+ .filter((line) => line !== '');+ const warningLines = lines.filter(+ (line) => messageTexts([{ seq: 0, event: JSON.parse(line) }])[0] === CODEX_WARNING_TEXT,+ );++ expect(warningLines).toHaveLength(1);+ // The line index IS the seq, so a line-for-line match with the broadcast+ // proves durability rode the same boundaries the subscriber saw.+ expect(lines.indexOf(warningLines[0])).toBe(+ retained.find((r) => messageTexts([r])[0] === CODEX_WARNING_TEXT)?.seq,+ );+ }, 45_000);++ test('a persisted warning replays with the same bytes, kind, and position', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const binDir = tmp();+ const { manager, threadId, retained } = await runTurn(+ 'codex-acp',+ contentDir,+ localDir,+ binDir,+ );+ const live = retained.map((r) => r.event);+ await manager.closeThread(threadId);++ const reopened = registryManagerFor('codex-acp', contentDir, localDir, binDir);+ await reopened.init();+ const replayed: Retained[] = [];+ await reopened.subscribe(threadId, 0, collectAll(replayed));++ const warningSeq = (rows: Retained[]): number[] =>+ rows.filter((r) => messageTexts([r])[0] === CODEX_WARNING_TEXT).map((r) => r.seq);++ expect(messageTexts(replayed)).toEqual(messageTexts(retained));+ // Close appends its own status after the live subscription was taken, so+ // the live log is a prefix of the replayed one rather than equal to it.+ expect(replayed.map((r) => r.event.kind).slice(0, live.length)).toEqual(+ live.map((e) => e.kind),+ );+ expect(warningSeq(replayed)).toEqual(warningSeq(retained));+ expect(replayed.map((r) => r.seq)).toEqual(replayed.map((_, i) => i));+ }, 60_000);+});++/**+ * The SDK-level canary characterizes the installed validator in isolation.+ * This one asks the question the product actually cares about: when an agent+ * puts a typed notice on the wire mid-turn, does OK's own thread keep working?+ * The rejection happens inside the SDK's static router, upstream of+ * `handleSessionUpdate`, so nothing short of a real spawned connection can+ * show whether the surrounding turn survives it.+ */+describe.skipIf(process.platform === 'win32')('a typed session notice mid-turn', () => {+ const BEFORE = 'chunk emitted before the notice';+ const AFTER = 'chunk emitted after the notice';++ /**+ * A `notice` session update carrying the required severity + title of ACP's+ * unstable Session Notices schema.+ */+ const typedNotice = {+ sessionUpdate: 'notice',+ severity: 'warning',+ title: 'skill bundle exceeded its budget',+ };++ type NoticeTurns = {+ manager: AcpThreadManager;+ threadId: string;+ /** Every retained session_update payload, in source order. */+ updates: () => Promise<Record<string, unknown>[]>;+ promptAgain: () => Promise<void>;+ };++ async function startThreadEmittingNotice(): Promise<NoticeTurns> {+ const contentDir = tmp();+ const localDir = tmp();+ const binDir = tmp();+ writeRegistryAgentShims(binDir, [agentTextUpdate(BEFORE), typedNotice, agentTextUpdate(AFTER)]);+ const manager = registryManagerFor('codex-acp', contentDir, localDir, binDir);+ await manager.init();+ const info = await manager.createThread({ agent: { source: 'registry', id: 'codex-acp' } });+ const ready = (what: string) =>+ waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, what);+ await ready('agent ready');++ const promptAgain = async () => {+ manager.sendPrompt(info.threadId, 'go');+ await ready('turn ended');+ };+ await promptAgain();++ return {+ manager,+ threadId: info.threadId,+ promptAgain,+ updates: async () => {+ const events: ThreadEvent[] = [];+ const sink = (frame: ThreadServerFrame) => {+ if (frame.op === 'event') events.push(frame.event);+ if (frame.op === 'events') events.push(...frame.events);+ };+ await manager.subscribe(info.threadId, 0, sink);+ // Read the log, don't keep watching it: a live subscriber also pins+ // the thread's unwatched-turn clock, which this is not testing.+ manager.unsubscribe(info.threadId, sink);+ return events+ .filter((e) => e.kind === 'session_update')+ .map((e) => (e as { update: Record<string, unknown> }).update);+ },+ };+ }++ const textOf = (updates: Record<string, unknown>[]): string =>+ updates.map((u) => (u.content as { text?: string })?.text ?? '').join('');++ test('never reaches the thread event log, while its turn-mates do', async () => {+ const updates = await (await startThreadEmittingNotice()).updates();++ // Asserted as the WHOLE discriminator set, not as the absence of one+ // string: an extractor reading the wrong key would report nothing but+ // `undefined` and still satisfy a bare `not.toContain('notice')`.+ expect(new Set(updates.map((u) => u.sessionUpdate))).toEqual(new Set(['agent_message_chunk']));+ // Both neighbours landing is the other half of the control: an empty+ // transcript would satisfy the absence claim without proving anything.+ expect(textOf(updates)).toContain(BEFORE);+ expect(textOf(updates)).toContain(AFTER);+ }, 45_000);++ test('leaves the connection usable for a whole further turn', async () => {+ const thread = await startThreadEmittingNotice();+ const firstTurn = textOf(await thread.updates());++ await thread.promptAgain();+ const bothTurns = textOf(await thread.updates());++ // A connection torn down by the notice would strand the second prompt+ // rather than answer it, so the doubling is the survival evidence.+ expect(bothTurns.split(AFTER)).toHaveLength(3);+ expect(bothTurns.length).toBe(firstTurn.length * 2);+ expect(thread.manager.getInfo(thread.threadId)?.status).toBe('ready');+ }, 60_000);+});diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.tsindex 825fdd256..40a2ab647 100644--- a/packages/server/src/acp/thread-manager.ts+++ b/packages/server/src/acp/thread-manager.ts@@ -765,10 +765,20 @@ export class AcpThreadManager {return t === undefined ? undefined : { ...t.info };}+ /**+ * Replay a thread from `sinceSeq` into `sink`, then attach it to the feed.+ *+ * The `subscribed` frame is emitted here rather than by the caller because+ * its `info` is only trustworthy in the window this method opens: before+ * `ensureLogResolved` a crash-recovered record still carries the meta's+ * stale `lastSeq`, and after the first replay frame the announcement is too+ * late to bound the replay a client is already receiving.+ */async subscribe(threadId: string, sinceSeq: number, sink: Subscriber): Promise<ThreadInfo> {const t = this.mustGet(threadId);await this.ensureLogResolved(t);const from = Math.max(sinceSeq, 0);+ sink({ op: 'subscribed', threadId, fromSeq: from, info: { ...t.info } });// Seqs below the in-memory window (an archived/rehydrated thread, or a// live log that trimmed past 5k events) replay from disk first. Looped:// `baseSeq` only ever grows, and a concurrent archive during the async@@ -814,11 +824,25 @@ export class AcpThreadManager {private ensureLogResolved(t: ThreadRecord): Promise<void> {if (t.logResolved) return Promise.resolve();t.logResolution ??= (async () => {- const resolved = await this.persistence.resolveEventLog(t.info.threadId);- t.baseSeq = resolved.count;- t.midTurnOnDisk = resolved.midTurn;- t.info.lastSeq = resolved.count - 1;- t.logResolved = true;+ try {+ const resolved = await this.persistence.resolveEventLog(t.info.threadId);+ t.baseSeq = resolved.count;+ t.midTurnOnDisk = resolved.midTurn;+ t.info.lastSeq = resolved.count - 1;+ t.logResolved = true;+ } catch (err) {+ // Drop the memo before rethrowing. `??=` will not replace a settled+ // promise, so a rejected one left in place makes every later subscribe+ // and resume re-await the same failure for the life of the process —+ // and since the `subscribed` frame is emitted after this resolves, the+ // thread would stay dark rather than merely lose its transcript.+ t.logResolution = null;+ this.opts.log.error(+ { err, threadId: t.info.threadId },+ '[acp-threads] durable log resolution failed',+ );+ throw err;+ }})();return t.logResolution;}@@ -3681,7 +3705,7 @@ export class AcpThreadManager {// pendingBroadcast non-empty also implies a flush timer is already pending// (set when it went non-empty below), so the fold needs no new timer.const pending = t.pendingBroadcast;- if (pending.length > 0 && coalesceChunkInto(pending[pending.length - 1], event)) {+ if (pending.length > 0 && coalesceChunkInto(pending[pending.length - 1], event, t.info.agent)) {return;}const seq = t.baseSeq + t.events.length;diff --git a/packages/server/src/acp/thread-socket.test.ts b/packages/server/src/acp/thread-socket.test.tsindex b6a12afc5..1d0b4f1b9 100644--- a/packages/server/src/acp/thread-socket.test.ts+++ b/packages/server/src/acp/thread-socket.test.ts@@ -7,10 +7,13 @@* through the socket's async path.*/-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import type { ThreadServerFrame } from '@inkeep/open-knowledge-core/acp/thread-protocol';+import type {+ ThreadEvent,+ ThreadServerFrame,+} from '@inkeep/open-knowledge-core/acp/thread-protocol';import { afterEach, describe, expect, test } from 'vitest';import type { AgentSessionManager } from '../agent-sessions.ts';import { getLogger } from '../logger.ts';@@ -625,3 +628,138 @@ describe('/collab/thread socket — queue ops', () => {socket.close();}, 45_000);});++describe('/collab/thread socket — crash-recovered replay bound', () => {+ /**+ * A crash leaves the meta behind the log: meta rewrites ride info changes,+ * not each appended event, so `lastSeq` on disk can name an event far short+ * of the log's real end. Both files are written by hand because that skew is+ * only reachable by killing a server mid-stream.+ */+ function writeCrashStaleThread(+ localDir: string,+ threadId: string,+ events: readonly ThreadEvent[],+ staleLastSeq: number,+ ): void {+ const threadsDir = join(localDir, 'threads');+ mkdirSync(threadsDir, { recursive: true });+ writeFileSync(+ join(threadsDir, `${threadId}.ndjson`),+ `${events.map((event) => JSON.stringify(event)).join('\n')}\n`,+ );+ writeFileSync(+ join(threadsDir, `${threadId}.meta.json`),+ JSON.stringify({+ version: 1,+ info: {+ threadId,+ agent: { id: 'codex-acp', name: 'Codex', source: 'registry' },+ title: 'Crashed thread',+ status: 'running',+ createdAt: 1,+ lastActivityAt: 2,+ modes: null,+ configOptions: null,+ lastSeq: staleLastSeq,+ },+ sessionId: 'sess-fixed',+ cwd: localDir,+ agentRef: { source: 'registry', id: 'codex-acp' },+ }),+ );+ }++ /** Longer than one replay chunk, so the log walks back in more than one frame. */+ const MULTI_CHUNK_EVENTS: ThreadEvent[] = Array.from({ length: 600 }, (_, i) => ({+ kind: 'user_message',+ content: `m${i}`,+ ts: i + 1,+ }));++ test('subscribed announces the durable log end, ahead of every replayed event', async () => {+ const localDir = tmp();+ const threadId = 'crash-stale';+ writeCrashStaleThread(localDir, threadId, MULTI_CHUNK_EVENTS, 2);+ const manager = makeManager(tmp(), localDir);+ await manager.init();+ // The rehydrated record still believes the stale meta until the log is read.+ expect(manager.getInfo(threadId)?.lastSeq).toBe(2);++ const socket = attachFakeSocket(manager);+ socket.emit(JSON.stringify({ op: 'subscribe', threadId, sinceSeq: 0 }));+ const subscribed = await socket.awaitFrame('subscribed');++ // The announced bound covers the whole log, so a client that waits for+ // delivery to reach it cannot mistake a later replay chunk for live traffic.+ expect(subscribed.info.lastSeq).toBe(MULTI_CHUNK_EVENTS.length - 1);+ const ops = socket.frames.map((f) => f.op);+ expect(ops.indexOf('subscribed')).toBeLessThan(ops.indexOf('events'));++ const deadline = Date.now() + 10_000;+ for (;;) {+ const replayed = socket.frames.filter(+ (f): f is Extract<ThreadServerFrame, { op: 'events' }> => f.op === 'events',+ );+ const delivered = replayed.reduce((n, f) => n + f.events.length, 0);+ if (delivered === MULTI_CHUNK_EVENTS.length) {+ // More than one frame is the point: a single-chunk replay could not+ // separate an accurate bound from a stale one.+ expect(replayed.length).toBeGreaterThan(1);+ expect(replayed[0].fromSeq).toBe(0);+ break;+ }+ if (Date.now() > deadline) throw new Error(`replay stalled at ${delivered} events`);+ await new Promise((r) => setTimeout(r, 25));+ }+ socket.close();+ }, 45_000);++ test('a failed log resolution is retried rather than cached for the process', async () => {+ const localDir = tmp();+ const threadId = 'unreadable-log';+ const events: ThreadEvent[] = [{ kind: 'user_message', content: 'hello', ts: 1 }];+ writeCrashStaleThread(localDir, threadId, events, 0);+ // A directory where the log belongs: it exists, so resolution reaches it,+ // and reading it throws the way an EACCES/EIO log would.+ const logPath = join(localDir, 'threads', `${threadId}.ndjson`);+ rmSync(logPath);+ mkdirSync(logPath);++ const manager = makeManager(tmp(), localDir);+ await manager.init();++ const failing = attachFakeSocket(manager);+ failing.emit(JSON.stringify({ op: 'subscribe', threadId, sinceSeq: 0 }));+ await failing.awaitFrame('error');+ expect(failing.frames.map((f) => f.op)).not.toContain('subscribed');+ failing.close();++ // Whatever made the log unreadable is gone. The next subscribe has to read+ // it again: a memoized rejection would answer every later subscribe and+ // resume for the life of the process, and since `subscribed` is emitted+ // behind that resolution the thread would stay dark rather than merely+ // lose its transcript.+ rmSync(logPath, { recursive: true });+ writeFileSync(logPath, `${events.map((event) => JSON.stringify(event)).join('\n')}\n`);++ const retry = attachFakeSocket(manager);+ retry.emit(JSON.stringify({ op: 'subscribe', threadId, sinceSeq: 0 }));+ const subscribed = await retry.awaitFrame('subscribed');+ expect(subscribed.info.lastSeq).toBe(events.length - 1);+ retry.close();+ }, 45_000);++ test('subscribing to a thread that does not exist errors without announcing a window', async () => {+ const manager = makeManager(tmp(), tmp());+ await manager.init();+ const socket = attachFakeSocket(manager);++ socket.emit(JSON.stringify({ op: 'subscribe', threadId: 'nope', sinceSeq: 0 }));+ const err = await socket.awaitFrame('error');++ expect(err.code).toBe('unknown-thread');+ expect(socket.frames.map((f) => f.op)).not.toContain('subscribed');+ socket.close();+ }, 45_000);+});diff --git a/packages/server/src/acp/thread-socket.ts b/packages/server/src/acp/thread-socket.tsindex 7332da8bb..d1c6746d5 100644--- a/packages/server/src/acp/thread-socket.ts+++ b/packages/server/src/acp/thread-socket.ts@@ -218,15 +218,9 @@ export function attachAcpThreadSocket(// for the same thread no-ops instead of double-attaching.subscriptions.set(threadId, sink);try {- // Replay happens inside subscribe() through the sink, AFTER the- // subscribed frame below has announced the replay window start.- const info = manager.getInfo(threadId);- if (info === undefined) {- subscriptions.delete(threadId);- sendError('unknown-thread', `no thread '${threadId}'`, { threadId });- return;- }- send({ op: 'subscribed', threadId, fromSeq: Math.max(sinceSeq, 0), info });+ // Both the `subscribed` announcement and the replay that follows it+ // reach the client through this sink — the manager emits them in the+ // one order that lets a client tell replayed history from live traffic.await manager.subscribe(threadId, sinceSeq, sink);} catch (err) {subscriptions.delete(threadId);diff --git a/packages/server/src/acp/typed-notice-canary.test.ts b/packages/server/src/acp/typed-notice-canary.test.tsnew file mode 100644index 000000000..9d41e00cd--- /dev/null+++ b/packages/server/src/acp/typed-notice-canary.test.ts@@ -0,0 +1,226 @@+import {+ client as acpClient,+ methods as acpMethods,+ ndJsonStream,+ type SessionNotification,+} from '@agentclientprotocol/sdk';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';++/**+ * ACP's typed `notice` update is the eventual home for agent warnings, but no+ * released SDK carries it. These characterize what the INSTALLED SDK does with+ * one today, so an upgrade that starts accepting notices cannot slip past as a+ * silent behavior change. The connection is built exactly as the thread+ * manager builds it — `acpClient(...)` over `ndJsonStream` — because the+ * rejection happens in the SDK's own static session-update router, upstream of+ * any handler this codebase registers.+ *+ * The agent side is a pair of in-memory web streams: no child process, no+ * socket, no registry fetch.+ */++/** JSON-RPC 2.0 "Invalid params". */+const INVALID_PARAMS = -32602;++const SESSION_ID = 'canary-session';++type Peer = {+ /** Deliver one raw JSON-RPC message from the agent side. */+ send: (message: unknown) => void;+ /** Close the agent's output stream, as a departing agent would. */+ endAgentOutput: () => void;+ /** Every `session/update` that survived the SDK's router. */+ delivered: SessionNotification[];+ connectionState: () => 'open' | 'settled';+ dispose: () => Promise<void>;+};++/**+ * A refused notification produces no JSON-RPC response — a notification has no+ * id to answer — so the SDK's log line is the only signal that it ran the+ * message and declined it. Collecting the error payloads makes "the SDK has+ * finished refusing N messages" a condition tests can wait on instead of a+ * duration they have to guess.+ */+let refusals: Record<string, unknown>[] = [];++beforeEach(() => {+ refusals = [];+ vi.spyOn(console, 'error').mockImplementation((...args: unknown[]) => {+ for (const arg of args) {+ if (typeof arg === 'object' && arg !== null && 'code' in arg) {+ refusals.push(arg as Record<string, unknown>);+ }+ }+ });+});++function connectToFakeAgent(): Peer {+ const encoder = new TextEncoder();+ let enqueue!: (line: string) => void;+ let endAgentOutput!: () => void;+ const agentToClient = new ReadableStream<Uint8Array>({+ start(controller) {+ enqueue = (line) => controller.enqueue(encoder.encode(`${line}\n`));+ endAgentOutput = () => controller.close();+ },+ });+ const clientToAgent = new WritableStream<Uint8Array>({ write() {} });++ const delivered: SessionNotification[] = [];+ const conn = acpClient({ name: 'open-knowledge-typed-notice-canary' })+ .onNotification(acpMethods.client.session.update, (ctx) => {+ delivered.push(ctx.params);+ })+ .connect(ndJsonStream(clientToAgent, agentToClient));++ let state: 'open' | 'settled' = 'open';+ const settle = () => {+ state = 'settled';+ };+ conn.closed.then(settle, settle);++ return {+ send: (message) => enqueue(JSON.stringify(message)),+ endAgentOutput,+ delivered,+ connectionState: () => state,+ dispose: async () => {+ if (state === 'open') endAgentOutput();+ await conn.closed.catch(() => {});+ },+ };+}++/**+ * A `notice` session update carrying the required severity + title of ACP's+ * unstable Session Notices schema. Whether the installed SDK knows the+ * discriminator at all is settled by the core session-update roster check;+ * this payload is here to characterize what the runtime validator does when+ * one arrives.+ */+function typedNoticeNotification(): unknown {+ return {+ jsonrpc: '2.0',+ method: 'session/update',+ params: {+ sessionId: SESSION_ID,+ update: {+ sessionUpdate: 'notice',+ severity: 'warning',+ title: 'skill bundle exceeded its budget',+ },+ },+ };+}++function agentTextNotification(text: string): unknown {+ return {+ jsonrpc: '2.0',+ method: 'session/update',+ params: {+ sessionId: SESSION_ID,+ update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } },+ },+ };+}++const deliveredText = (peer: Peer): string[] =>+ peer.delivered.map((n) => (n.update as { content?: { text?: string } }).content?.text ?? '');++async function until(pred: () => boolean, what: string): Promise<void> {+ const deadline = Date.now() + 5_000;+ while (!pred()) {+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`);+ await new Promise((resolve) => setTimeout(resolve, 5));+ }+}++let peers: Peer[] = [];+function openPeer(): Peer {+ const peer = connectToFakeAgent();+ peers.push(peer);+ return peer;+}++afterEach(async () => {+ const open = peers;+ peers = [];+ for (const peer of open) await peer.dispose();+ vi.restoreAllMocks();+});++describe('installed ACP SDK versus a typed session notice', () => {+ test('delivers a supported update through this transport', async () => {+ const peer = openPeer();++ peer.send(agentTextNotification('ordinary answer'));+ await until(() => peer.delivered.length > 0, 'the supported update to arrive');++ expect(deliveredText(peer)).toEqual(['ordinary answer']);+ });++ test('drops a typed notice before it reaches a session-update handler', async () => {+ const peer = openPeer();++ // The supported update behind it is the positive control: an empty+ // delivery list would otherwise read the same as a broken transport.+ peer.send(typedNoticeNotification());+ peer.send(agentTextNotification('ordinary answer'));+ await until(+ () => refusals.length > 0 && peer.delivered.length > 0,+ 'the notice to be refused and the supported update to arrive',+ );++ expect(peer.delivered.map((n) => n.update.sessionUpdate)).toEqual(['agent_message_chunk']);+ });++ test('refuses the typed notice as invalid params rather than ignoring it', async () => {+ const peer = openPeer();++ peer.send(typedNoticeNotification());+ await until(() => refusals.length > 0, 'the notice to be refused');++ expect(refusals.map((r) => r.code)).toEqual([INVALID_PARAMS]);+ });++ test('keeps the connection open and still delivers later supported updates', async () => {+ const peer = openPeer();++ peer.send(typedNoticeNotification());+ peer.send(agentTextNotification('answer after the notice'));+ peer.send(agentTextNotification('and the one after that'));+ await until(() => peer.delivered.length >= 2, 'both later updates to arrive');++ expect(peer.connectionState()).toBe('open');+ expect(deliveredText(peer)).toEqual(['answer after the notice', 'and the one after that']);+ });++ test('survives a run of typed notices without degrading', async () => {+ const peer = openPeer();+ const run = 5;++ for (let i = 0; i < run; i++) peer.send(typedNoticeNotification());+ peer.send(agentTextNotification('still answering'));+ await until(+ () => refusals.length >= run && peer.delivered.length > 0,+ 'every notice to be refused and the supported update to arrive',+ );++ expect(peer.connectionState()).toBe('open');+ expect(deliveredText(peer)).toEqual(['still answering']);+ expect(refusals).toHaveLength(run);+ });++ // Without this, every `connectionState() === 'open'` assertion above would+ // hold just as well for a probe that can never report anything else.+ test('settles the connection once the agent stops writing', async () => {+ const peer = openPeer();+ expect(peer.connectionState()).toBe('open');++ peer.endAgentOutput();+ await until(() => peer.connectionState() === 'settled', 'the connection to settle');++ expect(peer.connectionState()).toBe('settled');+ });+});diff --git a/test-support/fixtures/codex-legacy-warning-envelopes.json b/test-support/fixtures/codex-legacy-warning-envelopes.jsonnew file mode 100644index 000000000..52f657b4d--- /dev/null+++ b/test-support/fixtures/codex-legacy-warning-envelopes.json@@ -0,0 +1,325 @@+{+ "provenance": {+ "producerSourceRead": "@agentclientprotocol/[email protected]",+ "producerWireObserved": "@agentclientprotocol/[email protected]",+ "recheckedOn": "2026-08-26",+ "emission": [+ "createWarningEvent -> createAgentTextMessageChunk(`Warning: ${event.message}\\n\\n`)",+ "createConfigWarningEvent-> const text = details ? `${summary}\\n\\n${details}` : summary; createAgentTextMessageChunk(`Config warning: ${text}\\n\\n`)",+ "createTextEvent -> createAgentTextMessageChunk(event.delta, event.itemId, meta)"+ ],+ "note": "createAgentMessageChunk omits the messageId key entirely when the argument is falsy, which is why both warning families arrive without one while ordinary answers carry event.itemId. The legacy branches are reached whenever the client has not negotiated the JetBrains-private typed-failure capability, which Open Knowledge never advertises. Only candidates[0] is recorded traffic, from a thread whose meta names the wire-observed version; every Config warning entry is reconstructed from the emission templates above, which were read out of the source-read version. The two agree byte for byte on all three literals."+ },+ "agents": {+ "codexRegistry": {+ "source": "registry",+ "id": "codex-acp",+ "name": "Codex"+ },+ "codexCustom": {+ "source": "custom",+ "id": "codex-acp",+ "name": "Codex (local build)"+ },+ "claudeRegistry": {+ "source": "registry",+ "id": "claude-acp",+ "name": "Claude Agent"+ }+ },+ "candidates": [+ {+ "name": "warning-skills-budget",+ "why": "The payload observed on the wire and persisted to a real thread log.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "Warning: Skill descriptions were shortened to fit the skills context budget. Codex can still see every skill, but some descriptions are shorter. Disable unused skills or plugins to leave more room for the rest.\n\n"+ }+ }+ },+ {+ "name": "config-warning-with-details",+ "why": "The details branch puts a blank line INSIDE one event, which is why a blank line can never be a split point.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "Config warning: Ignored 2 invalid entries in config.toml.\n\n- `model_reasoning_effort`: expected one of low, medium, high\n- `sandbox_mode`: unknown value `full-access`\n\n"+ }+ }+ },+ {+ "name": "config-warning-summary-only",+ "why": "The no-details branch, whose whole body is a single line.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "Config warning: Ignored 1 invalid entry in config.toml.\n\n"+ }+ }+ },+ {+ "name": "warning-whose-message-opens-with-a-space",+ "why": "The adapter interpolates the message straight after the literal, so a message with its own leading space yields two spaces after the colon. The literal is still intact and this is still a warning; only the prefix itself is fixed, never what follows it.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "Warning: something happened\n\n"+ }+ }+ }+ ],+ "atomicity": {+ "multiParagraphWarning": {+ "why": "A single event whose body reads as chrome followed by prose. The adapter cannot produce this — warnings interpolate only the warning message, and answers are separate events carrying an item id — but if one ever arrived it is classified whole, as one notice, and is NEVER split at the blank line. Carving a leading paragraph out of a larger body would mean reinterpreting arbitrary agent prose, which is the failure mode the complete-envelope rule exists to prevent. The residual is a documented, accepted risk.",+ "expectCandidate": true,+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "Warning: Skill descriptions were shortened.\n\nYes, the refactor is safe. The call sites all pass the new argument.\n\n"+ }+ }+ }+ },+ "neighbors": {+ "contextCompacted": {+ "why": "Real adjacent no-ID Codex chrome. Terminates in \\n\\n like a candidate but carries neither prefix, so generic coalescing would happily merge it with one.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "*Context compacted to fit the model's context window.*\n\n"+ }+ }+ },+ "turnError": {+ "why": "Real adjacent no-ID Codex chrome from the turn-error path.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "stream disconnected before completion\n\n"+ }+ }+ }+ },+ "ordinaryAnswer": {+ "why": "An ordinary assistant answer. Carries event.itemId as messageId, which is the gate that keeps real prose out of the classifier.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "messageId": "msg_01H8XK2Q4V7N3PZ",+ "content": {+ "type": "text",+ "text": "The skills are all still loaded. Only their one-line descriptions were shortened.\n\n"+ }+ }+ },+ "negatives": [+ {+ "name": "other-registry-agent",+ "why": "Byte-identical warning text from a different registry agent. No producer contract exists outside codex-acp.",+ "agent": "claudeRegistry",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "Warning: Skill descriptions were shortened to fit the skills context budget.\n\n"+ }+ }+ },+ {+ "name": "custom-agent-same-id",+ "why": "A user-configured entry can reuse the id while spawning an entirely different executable.",+ "agent": "codexCustom",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "Warning: Skill descriptions were shortened to fit the skills context budget.\n\n"+ }+ }+ },+ {+ "name": "explicit-message-id",+ "why": "An answer that happens to open with the prefix still carries an item id, so it is ordinary prose.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "messageId": "msg_01H8XK2Q4V7N3PZ",+ "content": {+ "type": "text",+ "text": "Warning: Skill descriptions were shortened to fit the skills context budget.\n\n"+ }+ }+ },+ {+ "name": "null-message-id",+ "why": "The characterized producer omits the key outright, so an explicit null is a shape it cannot emit. The ACP schema admits null here, which makes this a value some other producer chose to send rather than an absence.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "messageId": null,+ "content": {+ "type": "text",+ "text": "Warning: Skill descriptions were shortened to fit the skills context budget.\n\n"+ }+ }+ },+ {+ "name": "lowercase-prefix",+ "why": "Casing is part of the producer's literal, not a normalizable detail.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "warning: something happened\n\n"+ }+ }+ },+ {+ "name": "no-space-after-colon",+ "why": "The producer's literal includes the trailing space.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "Warning:something happened\n\n"+ }+ }+ },+ {+ "name": "leading-whitespace",+ "why": "The prefix must be at byte zero; lstrip-style tolerance is what makes a prose heuristic unsafe.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": " Warning: something happened\n\n"+ }+ }+ },+ {+ "name": "config-warning-casing",+ "why": "Same casing rule for the sibling family.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "Config Warning: Ignored 1 invalid entry.\n\n"+ }+ }+ },+ {+ "name": "missing-terminator",+ "why": "Real review-mode chrome is emitted trimmed, so a trimmed warning-looking body is a shape the producer genuinely makes and must stay prose.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "Warning: this function swallows the error without logging it."+ }+ }+ },+ {+ "name": "single-trailing-newline",+ "why": "One newline is not the producer's two-byte terminator.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "Warning: something happened\n"+ }+ }+ },+ {+ "name": "trailing-space-after-terminator",+ "why": "The terminator must be the final bytes.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "Warning: something happened\n\n "+ }+ }+ },+ {+ "name": "thought-chunk",+ "why": "Reasoning is a different stream and renders as its own item.",+ "update": {+ "sessionUpdate": "agent_thought_chunk",+ "content": {+ "type": "text",+ "text": "Warning: something happened\n\n"+ }+ }+ },+ {+ "name": "user-message-chunk",+ "why": "A user echo is never agent chrome.",+ "update": {+ "sessionUpdate": "user_message_chunk",+ "content": {+ "type": "text",+ "text": "Warning: something happened\n\n"+ }+ }+ },+ {+ "name": "non-text-content",+ "why": "An image block has no text to classify.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "image",+ "mimeType": "image/png",+ "data": "iVBORw0KGgo="+ }+ }+ },+ {+ "name": "unrelated-update-kind",+ "why": "Non-chunk updates carry no message text at all.",+ "update": {+ "sessionUpdate": "usage_update",+ "used": 1200,+ "size": 200000+ }+ },+ {+ "name": "prefix-only-no-terminator",+ "why": "The bare prefix with nothing after it still fails the terminator gate.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "Warning: "+ }+ }+ },+ {+ "name": "empty-text",+ "why": "An empty body satisfies no gate.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": ""+ }+ }+ },+ {+ "name": "terminator-only",+ "why": "The terminator alone carries no prefix.",+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {+ "type": "text",+ "text": "\n\n"+ }+ }+ }+ ]+}diff --git a/turbo.json b/turbo.jsonindex 9a40ec77b..160f99449 100644--- a/turbo.json+++ b/turbo.json@@ -1,6 +1,9 @@{"$schema": "https://turbo.build/schema.json",- "globalDependencies": ["test-support/fixtures/share-url-v1-v2.json"],+ "globalDependencies": [+ "test-support/fixtures/share-url-v1-v2.json",+ "test-support/fixtures/codex-legacy-warning-envelopes.json"+ ],"tasks": {"build": {"dependsOn": ["^build"],@@ -121,6 +124,7 @@"src/**/*.tsx","tests/**/*.ts","tests/**/*.tsx",+ "scripts/**","playwright.config.ts","vitest.integration.config.ts","vitest.config.ts",@@ -140,6 +144,7 @@"src/**/*.tsx","tests/**/*.ts","tests/**/*.tsx",+ "scripts/**","playwright.config.ts","vitest.integration.config.ts","vitest.config.ts",@@ -159,6 +164,7 @@"src/**/*.tsx","tests/**/*.ts","tests/**/*.tsx",+ "scripts/**","playwright.config.ts","vitest.integration.config.ts","vitest.config.ts",@@ -178,6 +184,7 @@"src/**/*.tsx","tests/**/*.ts","tests/**/*.tsx",+ "scripts/**","playwright.config.ts","vitest.integration.config.ts","vitest.config.ts",