From c1f1f1c0dc6b8cbf763414207a044dbc3b5a68ce Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 9 Nov 2026 15:50:09 +0000 Subject: [PATCH 1/5] fix(ui-server): hold a session's history reads until its turn's boundary is recorded A client can read history again the moment a turn's result arrives, while host teardown still runs. That replay happened before the turn boundary was recorded, so the answer replayed without its turn id and nothing replayed it again. Reads of that session now wait for the turn's finish, bounded by BOUNDARY_READ_MS. Not landed ahead of #3155's image PR (maintainer ruling); see the issue. Co-Authored-By: Claude Opus 5.5 --- .../src/ws/bridge-capabilities/context.ts | 2 ++ .../src/ws/bridge-capabilities/emission.ts | 5 ++-- .../src/ws/session-run/backend-entry.ts | 2 ++ packages/ui-server/src/ws/turn-failures.ts | 30 ++++++++++++++++--- .../tests/ws-turn-failure-replay.test.ts | 28 +++++++++++++++++ 5 files changed, 61 insertions(+), 6 deletions(-) diff --git a/packages/ui-server/src/ws/bridge-capabilities/context.ts b/packages/ui-server/src/ws/bridge-capabilities/context.ts index 7f0e062029..0f3d2c7722 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/context.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/context.ts @@ -21,6 +21,8 @@ export interface MakeBridgeOptions { */ onSessionNamed?: ((sessionId: string) => void) | undefined; onTerminalFailure?: ((sessionId: string, failure: TurnFailure) => void) | undefined; + /** Called before this turn's own result frame goes out. */ + onTurnResult?: ((sessionId: string) => void) | undefined; /** The pill label the request already has, read when the session is named (#1004). */ promptLabel?: (() => string | undefined) | undefined; applicationPolicy?: BrainApplicationPolicy | undefined; diff --git a/packages/ui-server/src/ws/bridge-capabilities/emission.ts b/packages/ui-server/src/ws/bridge-capabilities/emission.ts index 7b9a8d0748..5feabeef86 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/emission.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/emission.ts @@ -112,10 +112,10 @@ function offerRetry(ctx: BridgeContext, msg: ResultFrame): ResultFrame { /** Frame emission: stamps, persists and forwards every frame the backend emits. */ export function createEmission(ctx: BridgeContext, transcript: TurnTranscript, - options: Pick): BridgeSlice<"emit"> { + options: Pick): BridgeSlice<"emit"> { const { host, turn, turnId, requestId, backendId, principalId, authorization, work, recorder, mainModel, workerProfile } = ctx; const { coordinator, catalog } = host; - const { promptText, onTerminalFailure, promptLabel, pricingContext } = options; + const { promptText, onTerminalFailure, onTurnResult, promptLabel, pricingContext } = options; const { thinkingLevel, draftRef, attachmentFileIds, draftPrincipalId, resumedSession } = captureFrameFields(ctx); let profileBound = false; let draftSettled = false; @@ -224,6 +224,7 @@ export function createEmission(ctx: BridgeContext, transcript: TurnTranscript, if (turn.turnId === turnId && msg.failure && (msg.outcome === "error" || (msg.outcome === undefined && msg.isError))) { onTerminalFailure?.(msg.sessionId, msg.failure); } + if (turn.turnId === turnId) onTurnResult?.(msg.sessionId); return offerRetry(ctx, msg); }; diff --git a/packages/ui-server/src/ws/session-run/backend-entry.ts b/packages/ui-server/src/ws/session-run/backend-entry.ts index 9ad4ca335b..833f245598 100644 --- a/packages/ui-server/src/ws/session-run/backend-entry.ts +++ b/packages/ui-server/src/ws/session-run/backend-entry.ts @@ -91,6 +91,8 @@ export async function openTurnBridge( }, // A terminal failure is recorded against the session it ended. onTerminalFailure: failureRecording.observe, + // History read after the result waits for the turn's boundary (#3155). + onTurnResult: failureRecording.resulted, // A follow-up's pill label is its turn's request label (#1004). promptLabel: () => current.label, applicationPolicy: backend.brainApplicationPolicy?.({ profileId, diff --git a/packages/ui-server/src/ws/turn-failures.ts b/packages/ui-server/src/ws/turn-failures.ts index 00be94a7e6..b9f65b9f50 100644 --- a/packages/ui-server/src/ws/turn-failures.ts +++ b/packages/ui-server/src/ws/turn-failures.ts @@ -129,6 +129,8 @@ export class FailureReplay { async begin(backend: AgentBackend, sessionId: string | undefined, turnId: string, signal: AbortSignal): Promise<{ observe: (sessionId: string, failure: TurnFailure) => void; + /** The turn's own result went out: history reads of its session wait for its end (`finish`). */ + resulted: (sessionId: string) => void; /** `sessionId` is the session the turn ran in, when it ran; boundaries are recorded only then. */ finish: (sessionId?: string | null) => Promise; }> { @@ -143,6 +145,9 @@ export class FailureReplay { const settled = new Promise((resolve) => { release = resolve; }); let write: Promise | undefined; let closed = false; + let end!: () => void; + const ended = new Promise((resolve) => { end = resolve; }); + let held = false; return { observe: (sid, failure) => { if (closed || before === null || write) return; @@ -162,12 +167,29 @@ export class FailureReplay { })(); this.track(sid, write); }, + resulted: (sid) => { + // A client may read the history again the moment the result + // arrives, while host teardown still runs. Its replay must wait for + // this turn's boundary, or the answer it ends replays without its + // turn id and nothing replays it again (#3155). Bounded like the + // boundary read, so a teardown that never finishes cannot hold + // the session's history. + if (closed || held || before === null || !this.catalog.recordTurnBoundary) return; + held = true; + let timer: ReturnType | undefined; + const hold = Promise.race([ended, new Promise((resolve) => { timer = setTimeout(resolve, BOUNDARY_READ_MS); })]) + .finally(() => clearTimeout(timer)); + this.track(sid, hold); + }, finish: async (sid) => { const first = !closed; - closed = true; release(); await write; - if (first && sid && ((before !== null && this.catalog.recordTurnBoundary) || this.catalog.recordScratchPins)) { - await this.boundary(backend, sid, turnId, before); - } + closed = true; release(); + try { + await write; + if (first && sid && ((before !== null && this.catalog.recordTurnBoundary) || this.catalog.recordScratchPins)) { + await this.boundary(backend, sid, turnId, before); + } + } finally { end(); } }, }; } diff --git a/packages/ui-server/tests/ws-turn-failure-replay.test.ts b/packages/ui-server/tests/ws-turn-failure-replay.test.ts index 5b4e428921..57e3c0a156 100644 --- a/packages/ui-server/tests/ws-turn-failure-replay.test.ts +++ b/packages/ui-server/tests/ws-turn-failure-replay.test.ts @@ -43,6 +43,7 @@ function harness(id: "claude" | "pi") { let turns = 0; let persist = true; let historyHold: Promise | undefined; + let endHold: Promise | undefined; let reads = 0; const bridges: BackendBridge[] = []; let lateFailure: TurnFailure | undefined; @@ -67,6 +68,8 @@ function harness(id: "claude" | "pi") { isError: true, outcome: "error", failure: lateFailure }); req.bridge.emit({ type: "result", sessionId: "s1", numTurns: 1, durationMs: 1, isError: !!failure, outcome: failure ? "error" : "success", ...(failure ? { failure } : {}) }); + // A backend may still be settling after its result: the turn ends later. + await endHold; }, async getHistory() { reads++; @@ -85,6 +88,11 @@ function harness(id: "claude" | "pi") { get reads() { return reads; }, withholdTranscript() { persist = false; }, emitLateFailure(next: TurnFailure) { lateFailure = next; }, + holdEnd() { + let release!: () => void; + endHold = new Promise((resolve) => { release = () => { endHold = undefined; resolve(); }; }); + return release; + }, holdHistory() { let release!: () => void; historyHold = new Promise((resolve) => { release = () => { historyHold = undefined; resolve(); }; }); @@ -313,4 +321,24 @@ for (const id of ["claude", "pi"] as const) describe(`${id}: live failure surviv expect(replay?.type === "session_history" && replay.messages.at(-1)?.failure).toEqual(live); } finally { release(); await sending; } }); + + test("a resume between a turn's result and its end waits for the turn's boundary", async () => { + const h = harness(id); + const release = h.holdEnd(); + const sending = h.send(); + try { + for (let i = 0; i < 200 && !h.frames.some((frame) => frame.type === "result"); i++) await Bun.sleep(5); + const result = h.frames.find((frame) => frame.type === "result"); + expect(result?.type === "result" && result.turnId).toBeString(); + // A client reads the history again on the result, as a started + // follow-up carrying composer originals does (#3155). + const frames: ServerMessage[] = []; + const loading = handleClientMessage({ send: (data) => frames.push(JSON.parse(data)) }, { type: "session_resume", sessionId: "s1" }); + for (let i = 0; i < 20 && !frames.some((frame) => frame.type === "session_history"); i++) await Bun.sleep(5); + release(); + await sending; await loading; + const replay = frames.find((frame) => frame.type === "session_history"); + expect(replay?.type === "session_history" && replay.messages.at(-1)?.turnId, "the answer carries its turn").toBe(result?.type === "result" ? result.turnId : ""); + } finally { release(); await sending; } + }); }); From fc3f2054919da91ac2171db641ae18fe4dbb6cae Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:59:43 +0000 Subject: [PATCH 2/5] test(ui-server): a turn-boundary hold blocks only its session and ends at the boundary deadline (#3803) The result-to-finish hold is keyed by session and raced against the boundary deadline. Two unit tests pin both: an unrelated session's history read is never held, and a teardown that never finishes releases the hold with no pending entry left and no boundary made up. The deadline is a constructor option so the second test runs in milliseconds. Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/ws/turn-failures.ts | 7 ++- .../tests/turn-boundary-hold.test.ts | 56 +++++++++++++++++++ 2 files changed, 60 insertions(+), 3 deletions(-) create mode 100644 packages/ui-server/tests/turn-boundary-hold.test.ts diff --git a/packages/ui-server/src/ws/turn-failures.ts b/packages/ui-server/src/ws/turn-failures.ts index b9f65b9f50..0fc799fdbb 100644 --- a/packages/ui-server/src/ws/turn-failures.ts +++ b/packages/ui-server/src/ws/turn-failures.ts @@ -66,7 +66,8 @@ const BOUNDARY_READ_MS = 10_000; /** One concrete host's in-flight writes; never shared across apps or sessions. */ export class FailureReplay { private readonly pending = new Map>>(); - constructor(private readonly catalog: SessionCatalog, private readonly log: Logger) {} + /** `boundaryReadMs` bounds a boundary read and a result-to-finish hold; tests shorten it. */ + constructor(private readonly catalog: SessionCatalog, private readonly log: Logger, private readonly boundaryReadMs = BOUNDARY_READ_MS) {} async wait(sessionId: string): Promise { for (;;) { @@ -111,7 +112,7 @@ export class FailureReplay { // so the read is bounded by its own timer instead. const messages = await Promise.race([ backend.getHistory(sessionId), - new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("history read timed out")), BOUNDARY_READ_MS); }), + new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("history read timed out")), this.boundaryReadMs); }), ]); this.catalog.recordScratchPins?.(sessionId, backend.id, messages); const count = assistantCount(messages); @@ -177,7 +178,7 @@ export class FailureReplay { if (closed || held || before === null || !this.catalog.recordTurnBoundary) return; held = true; let timer: ReturnType | undefined; - const hold = Promise.race([ended, new Promise((resolve) => { timer = setTimeout(resolve, BOUNDARY_READ_MS); })]) + const hold = Promise.race([ended, new Promise((resolve) => { timer = setTimeout(resolve, this.boundaryReadMs); })]) .finally(() => clearTimeout(timer)); this.track(sid, hold); }, diff --git a/packages/ui-server/tests/turn-boundary-hold.test.ts b/packages/ui-server/tests/turn-boundary-hold.test.ts new file mode 100644 index 0000000000..1835f554d3 --- /dev/null +++ b/packages/ui-server/tests/turn-boundary-hold.test.ts @@ -0,0 +1,56 @@ +import { expect, test } from "bun:test"; +import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; +import type { AgentBackend } from "@schlessera/brain-ui-sdk/server"; +import { createRecordingObservability } from "../src/observability/index"; +import type { SessionCatalog } from "../src/ws/session-catalog"; +import { FailureReplay } from "../src/ws/turn-failures"; + +// The result-to-finish hold (#3803): a history read of a session waits for +// its turn's boundary, never for another session's, and never for longer +// than the boundary deadline. + +const answer = (content: string): SessionHistoryMessage => ({ role: "assistant", content, toolCalls: [] } as unknown as SessionHistoryMessage); + +function setup(boundaryReadMs?: number) { + const recorded: string[] = []; + const catalog = { recordTurnBoundary: (_sessionId: string, _backendId: string, boundary: { turnId: string }) => { recorded.push(boundary.turnId); } } as unknown as SessionCatalog; + let history: SessionHistoryMessage[] = []; + const backend = { id: "claude", getHistory: async () => structuredClone(history) } as unknown as AgentBackend; + const replay = new FailureReplay(catalog, createRecordingObservability().logger("turn"), boundaryReadMs); + const pending = () => (replay as unknown as { pending: Map>> }).pending; + return { replay, backend, recorded, pending, answer: (content: string) => { history = [...history, answer(content)]; } }; +} + +/** Whether `promise` settles within a few event-loop turns. */ +async function settlesSoon(promise: Promise): Promise { + let done = false; + void promise.then(() => { done = true; }); + for (let i = 0; i < 20 && !done; i++) await Bun.sleep(1); + return done; +} + +test("a held session's reads wait for its boundary; an unrelated session's do not", async () => { + const h = setup(); + const turn = await h.replay.begin(h.backend, "ithaca", "turn-ithaca", new AbortController().signal); + h.answer("The ship is rostered."); + turn.resulted("ithaca"); + expect(await settlesSoon(h.replay.wait("aeaea")), "another session reads at once").toBe(true); + const held = h.replay.wait("ithaca"); + expect(await settlesSoon(held), "this session waits for its turn's end").toBe(false); + await turn.finish("ithaca"); + expect(await settlesSoon(held), "and reads once the boundary is recorded").toBe(true); + expect(h.recorded).toEqual(["turn-ithaca"]); + expect(h.pending().size, "no pending entry is left").toBe(0); +}); + +test("a teardown that never finishes releases the hold at the boundary deadline", async () => { + const h = setup(50); + const turn = await h.replay.begin(h.backend, "ithaca", "turn-ithaca", new AbortController().signal); + turn.resulted("ithaca"); + const held = h.replay.wait("ithaca"); + expect(await settlesSoon(held), "held before the deadline").toBe(false); + await Bun.sleep(80); + expect(await settlesSoon(held), "released by the deadline without a finish").toBe(true); + expect(h.pending().size, "no pending entry is left").toBe(0); + expect(h.recorded, "no boundary is made up").toEqual([]); +}); From 079afebbf57192b5c740952a85551dce22b6625a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:59:49 +0000 Subject: [PATCH 3/5] chore: changeset for the turn-boundary hold (#3803) Co-Authored-By: Claude Opus 5.5 --- .changeset/3803-turn-boundary-hold.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/3803-turn-boundary-hold.md diff --git a/.changeset/3803-turn-boundary-hold.md b/.changeset/3803-turn-boundary-hold.md new file mode 100644 index 0000000000..d03264b534 --- /dev/null +++ b/.changeset/3803-turn-boundary-hold.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +A session's history read between a turn's result and the end of its teardown now waits for that turn's boundary. Before, it could replay the answer without its turn id, so a tracked session could never clear as seen. The wait is per session and bounded by the existing boundary deadline. From f088f63fdfd0729c7c1b15dcb74260c64214b52e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:04:42 +0000 Subject: [PATCH 4/5] docs: move the citations the turn-boundary hold shifted (#3803) Co-Authored-By: Claude Opus 5.5 --- docs/decisions/governed-writable-workers.md | 2 +- docs/decisions/session-handoff.md | 2 +- docs/plans/chat-history-deletion.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 8696cf4ed9..b65fde19a1 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1466,7 +1466,7 @@ from worker transcripts, and no extension of the observed-shell guarantee. **Where the next request waited.** The bridge never awaits an observation: it starts one per result and carries on -(`void host.journal?.toolEnded`, `packages/ui-server/src/ws/bridge-capabilities/emission.ts:272`). +(`void host.journal?.toolEnded`, `packages/ui-server/src/ws/bridge-capabilities/emission.ts:273`). The wait is the observation's hold. `held` takes it synchronously, before it queues the capture (`function held`, `packages/ui-server/src/brain/turn-journal.ts:279-300`), diff --git a/docs/decisions/session-handoff.md b/docs/decisions/session-handoff.md index 28c2f27b22..8603089495 100644 --- a/docs/decisions/session-handoff.md +++ b/docs/decisions/session-handoff.md @@ -160,7 +160,7 @@ its distinct retry treatment. Nothing archives, purges or automatically sends. The notice's presentation and actions are (`StateRoomNotice`, `packages/ui-react/src/components/chat/state-room-notice.tsx:22-100`); the host keeps the measurement and first quiet event (`const onResult`, -`packages/ui-server/src/ws/bridge-capabilities/emission.ts:203-228`). +`packages/ui-server/src/ws/bridge-capabilities/emission.ts:203-229`). ### Historical state directories remain untouched diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index b0931cdd97..3d23055b15 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -290,7 +290,7 @@ restore, resend, draft autosave and answer-delivery callbacks. Activity/Inbox/ journal APIs remain independent retained surfaces under the selected exclusion. Concrete entry points include `readSessionRecovery` (`readSessionRecovery`, `packages/ui-server/src/ws/recovery.ts:209-222`), -`FailureReplay` (`FailureReplay`, `packages/ui-server/src/ws/turn-failures.ts:67-93`), +`FailureReplay` (`FailureReplay`, `packages/ui-server/src/ws/turn-failures.ts:67-94`), and both handoff stages (`startHandoff`, `packages/ui-server/src/ws/handoff.ts:100-110`; `prepareHandoff`, `packages/ui-server/src/ws/handoff.ts:273-285`). Draft autosave belongs to `createDraftClient` (`createDraftClient`, From 1917da1c711fb0de6bcc773aaa96b02614393241 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:41:53 +0000 Subject: [PATCH 5/5] test(ui-server): read the result frame's stamped turn id through a typed guard (#3803) ServerResultMessage declares no turnId; servers stamp it on every frame. Strict typecheck refused the direct property read. Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/tests/ws-turn-failure-replay.test.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/ui-server/tests/ws-turn-failure-replay.test.ts b/packages/ui-server/tests/ws-turn-failure-replay.test.ts index 57e3c0a156..7ef9d318e5 100644 --- a/packages/ui-server/tests/ws-turn-failure-replay.test.ts +++ b/packages/ui-server/tests/ws-turn-failure-replay.test.ts @@ -328,8 +328,9 @@ for (const id of ["claude", "pi"] as const) describe(`${id}: live failure surviv const sending = h.send(); try { for (let i = 0; i < 200 && !h.frames.some((frame) => frame.type === "result"); i++) await Bun.sleep(5); - const result = h.frames.find((frame) => frame.type === "result"); - expect(result?.type === "result" && result.turnId).toBeString(); + // Servers stamp the turn id on every frame (protocol.ts, RESERVED). + const result = h.frames.find((frame): frame is Extract & { turnId?: string } => frame.type === "result"); + expect(result?.turnId).toBeString(); // A client reads the history again on the result, as a started // follow-up carrying composer originals does (#3155). const frames: ServerMessage[] = []; @@ -338,7 +339,7 @@ for (const id of ["claude", "pi"] as const) describe(`${id}: live failure surviv release(); await sending; await loading; const replay = frames.find((frame) => frame.type === "session_history"); - expect(replay?.type === "session_history" && replay.messages.at(-1)?.turnId, "the answer carries its turn").toBe(result?.type === "result" ? result.turnId : ""); + expect(replay?.type === "session_history" && replay.messages.at(-1)?.turnId, "the answer carries its turn").toBe(result?.turnId); } finally { release(); await sending; } }); });