From d2909c3bc8150729782e54935f15c1ffaf36313c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 13:47:31 +0000 Subject: [PATCH 1/4] CONTRACT: fix(ui-react): keep an ended question's answer recoverable and say when a turn timed out (#3356) A question whose turn ended before it was answered no longer loses its draft. The ended card stays the editable question and says the turn ended or timed out. Its Submit sends nothing to the ended request and keeps the answer on the card as Not delivered. Send as message is the only way to send it, as one ordinary new chat message, and it is offered once. The host's hard elapsed-time turn limit is unchanged and still counts the time a question waits. The timer now records the turn it ended. The bridge stamps that turn's cancelled terminal frames with result.outcomeDetail "host_timeout" (HOST_TIMEOUT_OUTCOME_DETAIL) and status.detail "Turn timed out", and the client shows a "Turn timed out" status. The Claude runtime's own stop notices ("No response requested.", "API Error: Request was aborted.") replay as SessionHistoryMessage.runtimeNotice rather than as the agent's text. Prefix digests hash a notice where its text used to be, so stored failure positions still join. Additive wire/package API: documented in the integration contract index and wire component; minor changeset. Co-Authored-By: Claude Opus 5.5 --- .changeset/ended-question-recovery.md | 7 + api-report/ui-react.txt | 8 + api-report/ui-sdk.txt | 30 ++ docs/decisions/answer-delivery.md | 76 +++- docs/integration-contract.md | 15 + docs/integration-contract/wire.md | 42 ++- packages/ui-backend-claude/src/history.ts | 54 ++- .../tests/history-api-failure.test.ts | 46 ++- .../chat/answer-delivery-status.tsx | 18 +- .../src/components/chat/ask-user-card.tsx | 8 +- .../components/chat/ask-user-form-card.tsx | 7 +- .../components/chat/ask-user-list-card.tsx | 8 +- .../components/chat/ask-user-rank-card.tsx | 7 +- .../src/components/chat/message-bubble.tsx | 57 ++- .../src/components/chat/turn-notice.tsx | 64 ++++ .../src/hooks/websocket-handlers/chat.ts | 11 +- .../ui-react/src/lib/answer-delivery/copy.ts | 3 + .../ui-react/src/lib/answer-delivery/types.ts | 5 + packages/ui-react/src/stores/chat-state.ts | 71 +++- .../tests/ended-question-runtime.test.ts | 335 ++++++++++++++++++ .../tests/render/ended-question-dom.ts | 21 ++ .../tests/render/ended-question.test.tsx | 232 ++++++++++++ packages/ui-sdk/src/protocol.ts | 30 ++ packages/ui-sdk/src/schemas.ts | 6 + packages/ui-server/src/ws/bridge.ts | 12 +- packages/ui-server/src/ws/run-session.ts | 1 + packages/ui-server/src/ws/turn-failures.ts | 6 +- packages/ui-server/src/ws/turns.ts | 7 + .../tests/turn-failure-notice-digest.test.ts | 30 ++ .../tests/ws-ask-turn-timeout.test.ts | 221 ++++++++++++ 30 files changed, 1402 insertions(+), 36 deletions(-) create mode 100644 .changeset/ended-question-recovery.md create mode 100644 packages/ui-react/src/components/chat/turn-notice.tsx create mode 100644 packages/ui-react/tests/ended-question-runtime.test.ts create mode 100644 packages/ui-react/tests/render/ended-question-dom.ts create mode 100644 packages/ui-react/tests/render/ended-question.test.tsx create mode 100644 packages/ui-server/tests/turn-failure-notice-digest.test.ts create mode 100644 packages/ui-server/tests/ws-ask-turn-timeout.test.ts diff --git a/.changeset/ended-question-recovery.md b/.changeset/ended-question-recovery.md new file mode 100644 index 0000000000..bcf720e9f1 --- /dev/null +++ b/.changeset/ended-question-recovery.md @@ -0,0 +1,7 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-backend-claude": minor +"@schlessera/brain-ui-react": minor +--- +A question whose turn ends before it is answered no longer loses what the user had entered, and a turn that hits the host's time limit now says so (#3356). The ended card keeps its draft and says the turn ended or timed out. Its Submit sends nothing to the ended request; it keeps the answer on the card as Not delivered. Send as message is the only way to send it, as one ordinary new chat message carrying the question and the answer, and it is offered once. The host's turn limit is unchanged: it is still a hard elapsed-time limit, and the time a question waits for the user counts against it. When it ends a turn, the cancelled `result` now carries `outcomeDetail: "host_timeout"` (`HOST_TIMEOUT_OUTCOME_DETAIL`) and the `status: cancelled` carries `detail: "Turn timed out"`, and the conversation shows a "Turn timed out" status. The Claude runtime's own stop notices, "No response requested." and "API Error: Request was aborted.", no longer replay as the agent's reply. They arrive as the new `SessionHistoryMessage.runtimeNotice` and are drawn as a short turn status. The same words written by the model or the user stay their text. diff --git a/api-report/ui-react.txt b/api-report/ui-react.txt index 284f79f6e7..8c85605f41 100644 --- a/api-report/ui-react.txt +++ b/api-report/ui-react.txt @@ -116,6 +116,7 @@ signatures (every public export and the types it is made of) editable?: boolean; mirror?: boolean; focus?: boolean; + sentAsMessage?: boolean; } AnswerPayload (packages/ui-react/src/lib/answer-delivery/types.ts) export type AnswerPayload = { @@ -160,6 +161,7 @@ signatures (every public export and the types it is made of) export interface AskUserExchange { requestId: string; terminal?: true; + endedBy?: "timeout"; turnId?: string; questions: AskUserQuestion[]; list?: AskUserListSpec; @@ -292,6 +294,8 @@ signatures (every public export and the types it is made of) failure?: TurnFailure; retryOfTurnId?: string; failureLive?: boolean; + runtimeNotice?: TurnNotice; + runtimeNoticeLive?: boolean; retry?: TurnRetry; } ChatPage (packages/ui-react/src/components/chat/chat-page.tsx) @@ -889,6 +893,10 @@ signatures (every public export and the types it is made of) view: TrackFileView; props: TrackMapProps; } + TurnNotice (packages/ui-react/src/stores/chat-state.ts) + export interface TurnNotice { + cause: "timeout" | "aborted" | "unspecified"; + } UIShellState (packages/ui-react/src/stores/shell-stores.ts) export interface UIShellState { readonly activeView: ActiveView; diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 170ac517a5..756baaed0c 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -169,6 +169,7 @@ export "." (./src/index.ts) HANDOFF_MAX_CHARS HANDOFF_MAX_REFERENCES HANDOFF_REFERENCES_HEADING + HOST_TIMEOUT_OUTCOME_DETAIL type HandoffRequest type HygieneAction type HygieneDiff @@ -241,6 +242,7 @@ export "." (./src/index.ts) type RenderFormat type RenderRequest type ResolutionEffect + type RuntimeNotice SESSION_DRAFT_LIMITS SESSION_NOT_FOUND SESSION_RECOVERY_CAPABILITY @@ -634,6 +636,7 @@ export "./client" (./src/client/index.ts) HANDOFF_MAX_CHARS HANDOFF_MAX_REFERENCES HANDOFF_REFERENCES_HEADING + HOST_TIMEOUT_OUTCOME_DETAIL type HandoffRequest type HelloState type HygieneAction @@ -763,6 +766,7 @@ export "./client" (./src/client/index.ts) type RequestImageMaskInput type ResolutionEffect type ResolveActionInput + type RuntimeNotice SESSION_DRAFT_LIMITS SESSION_NOT_FOUND SESSION_RECOVERY_CAPABILITY @@ -1456,6 +1460,7 @@ export "./protocol" (./src/protocol.ts) HANDOFF_MAX_CHARS HANDOFF_MAX_REFERENCES HANDOFF_REFERENCES_HEADING + HOST_TIMEOUT_OUTCOME_DETAIL type HandoffRequest type HygieneAction type HygieneDiff @@ -1523,6 +1528,7 @@ export "./protocol" (./src/protocol.ts) type RenderFormat type RenderRequest type ResolutionEffect + type RuntimeNotice SESSION_DRAFT_LIMITS SESSION_NOT_FOUND SESSION_RECOVERY_CAPABILITY @@ -2141,6 +2147,7 @@ export "./server" (./src/server/index.ts) HANDOFF_MAX_CHARS HANDOFF_MAX_REFERENCES HANDOFF_REFERENCES_HEADING + HOST_TIMEOUT_OUTCOME_DETAIL type HandoffRequest type HistoricalItem type HistoricalResultRef @@ -2285,6 +2292,7 @@ export "./server" (./src/server/index.ts) type ResolvedBackendModule type ReverseGeocodeConfig type ReverseGeocodeResult + type RuntimeNotice SESSION_DRAFT_LIMITS SESSION_NOT_FOUND SESSION_RECOVERY_CAPABILITY @@ -6733,6 +6741,8 @@ signatures (every public export and the types it is made of) const HANDOFF_MAX_REFERENCES: 8; HANDOFF_REFERENCES_HEADING (packages/ui-sdk/src/protocol.ts) const HANDOFF_REFERENCES_HEADING: "References:"; + HOST_TIMEOUT_OUTCOME_DETAIL (packages/ui-sdk/src/protocol.ts) + const HOST_TIMEOUT_OUTCOME_DETAIL: "host_timeout"; HandoffRequest (packages/ui-sdk/src/protocol.ts) export interface HandoffRequest { handoffId: string; @@ -8170,6 +8180,11 @@ signatures (every public export and the types it is made of) request: Request; url: URL; } + RuntimeNotice (packages/ui-sdk/src/protocol.ts) + export interface RuntimeNotice { + cause: "aborted" | "unspecified"; + message: string; + } SESSION_DRAFT_LIMITS (packages/ui-sdk/src/protocol.ts) const SESSION_DRAFT_LIMITS: Readonly; SESSION_NOT_FOUND (packages/ui-sdk/src/protocol.ts) @@ -10024,6 +10039,7 @@ signatures (every public export and the types it is made of) effectiveThinkingLevel?: ThinkingLevel; localAnswer?: LocalAnswer; failure?: TurnFailure; + runtimeNotice?: RuntimeNotice; retryOfTurnId?: string; turnId?: string; journal?: import("./turn-journal.js").TurnJournalSummary; @@ -17266,6 +17282,13 @@ signatures (every public export and the types it is made of) assistant: "assistant"; user: "user"; }>; + runtimeNotice: z.ZodCatch; + message: z.ZodString; + }, z.core.$loose>>>; source: z.ZodCatch; + runtimeNotice: z.ZodCatch; + message: z.ZodString; + }, z.core.$loose>>>; source: z.ZodCatch` model: `No response requested.`, or `API Error: Request was +aborted.` for an aborted request. These replayed as the agent's words. They +now replay as `SessionHistoryMessage.runtimeNotice` on the message they +ended, after any partial answer (`export function runtimeNotice`, +`packages/ui-backend-claude/src/history.ts:339-350`). Recognition needs +both the runtime's provenance and one of its two constant texts, read from +the installed CLI, so the same words from the model or the user stay theirs. +Only an aborted request names a cause, and neither notice says who stopped +the turn. A failure on the same message stays the one account of the stop. +Other synthetic texts, such as usage warnings, still replay as text. +`API Error: 499 Inference request cancelled` was already a classified +failure and is unchanged. Live, these messages arrive without text deltas, +so the stream never showed them. + +Evidence: `packages/ui-server/tests/ws-ask-turn-timeout.test.ts` (the +original deadline with the wait counted, the drain, the closed late answer, +a cancel that is not a timeout, a timely answer and an answer that wins the +race, for every kind); `packages/ui-backend-claude/tests/history-api-failure.test.ts`; +`packages/ui-react/tests/render/ended-question.test.tsx`; and +`packages/ui-react/tests/ended-question-runtime.test.ts`, which runs real +Chrome against the real host for all four kinds, at 320px, at 200% text and +in both themes, using the keyboard. + ## Rejected - **Explicit Retry only (Recovery A).** It was rejected by ruling. It also diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 6ab59be06a..db5b655f3e 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -20,6 +20,21 @@ same-commit update of the index or relevant authoritative component. How they ar The reasoning is in [decisions/contract-versioning.md](decisions/contract-versioning.md). +## Turn timeouts and runtime stop notices (additive, 0.45.0, #3356) + +A turn the host's hard elapsed-time limit ended stays `outcome: "cancelled"`, +and now says why: `result.outcomeDetail: "host_timeout"` +(`HOST_TIMEOUT_OUTCOME_DETAIL`), with `detail: "Turn timed out"` on its +`status: cancelled`. A replayed assistant message gains +`SessionHistoryMessage.runtimeNotice`, the agent runtime's own stop notice, +whose text is no longer replayed as the agent's `content`. No existing field +changes meaning; the limit and its configuration are unchanged. See +[wire](integration-contract/wire.md#turn-stops-additive-in-0450). The SDK +exports `HOST_TIMEOUT_OUTCOME_DETAIL` and `RuntimeNotice`; `@schlessera/brain-ui-react` +adds the optional `ChatMessage.runtimeNotice`/`runtimeNoticeLive`, +`AskUserExchange.endedBy`, `AnswerDelivery.sentAsMessage` and the `TurnNotice` +type. This ships in a minor; no breaking ruling is required. + ## Explicit local chat deletion (additive, #3230) An authenticated owner can delete its own chat's local history with diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 152433e4cf..36e834c08a 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -104,8 +104,8 @@ previous observation rather than adding it. The frame never opens a message, reopens run state or moves focus. Older clients may ignore it. The same optional `budget` is retained on `TurnJournalSummary` and replayed with the existing single below-turn disclosure. The additive types and validation are -(`ServerUsage`, `packages/ui-sdk/src/protocol.ts:3890-3896`) and -(`serverUsageSchema`, `packages/ui-sdk/src/schemas.ts:1898-1900`). +(`ServerUsage`, `packages/ui-sdk/src/protocol.ts:3920-3926`) and +(`serverUsageSchema`, `packages/ui-sdk/src/schemas.ts:1904-1906`). Budget list-price inference cost is separate from the journal's billing-aware `costUsd`. Unpriced totals remain null; known lower bounds, estimated rates, @@ -943,6 +943,44 @@ SessionHistoryMessage.failure?: TurnFailure // on the assistant message the fa frame is a turn's terminal. An unreadable `attempts` or `resetsAt` is dropped independently while keeping the rest of the failure and its frame. + + +### Turn timeouts and runtime stop notices (additive in 0.45.0, #3356) + +``` +result.outcomeDetail?: "host_timeout" // on outcome: "cancelled" +status.detail?: "Turn timed out" // on the same turn's status: "cancelled" +SessionHistoryMessage.runtimeNotice?: RuntimeNotice // on an assistant message +RuntimeNotice = { cause: "aborted" | "unspecified", message } +HOST_TIMEOUT_OUTCOME_DETAIL = "host_timeout" // exported from @schlessera/brain-ui-sdk/protocol +``` + +- **`host_timeout`** says the host's hard elapsed-time turn limit ended the + turn. It is set from the timeout itself, never inferred from an aborted + signal: a cancel someone asked for, a revoked principal, a budget or a + journal stop never carries it. The turn is still `outcome: "cancelled"` and + `isError: false`; a timeout is never reported as a success, and the field + does not change what `"timeout"` means under `outcome: "error"`. The limit + counts the time a question waits for the user and is neither paused nor + restarted by one. Pending questions are drained at the deadline, and a later + answer gets `ask_answer_receipt` `closed`/`ended`. +- **`runtimeNotice`** is what the agent runtime itself wrote into the + transcript when a turn stopped, as opposed to anything the model said. The + Claude backend recognises it by the runtime's `` model and its + own constant texts: `No response requested.` (`unspecified`) and + `API Error: Request was aborted.` (`aborted`). The same words from the model + or the user stay their text. The notice's text is not repeated in + `content`, which holds the partial answer before it. A message that carries + a `failure` does not also carry a notice, and the same notice observed + twice on one message is one notice. Neither cause says who stopped the + turn or whether earlier tool calls took effect. A replay's turn-position + digests hash the notice where its text used to be, so failure and turn + records written before this change still join. +- **Tolerance.** A client that does not read these keeps showing a + cancelled turn, and a notice-only assistant message as an empty one. A + client that validates with `@schlessera/brain-ui-sdk/schemas` drops an + unreadable `runtimeNotice` and keeps the message. + ### Manual retry receipts (additive in 0.40.0) diff --git a/packages/ui-backend-claude/src/history.ts b/packages/ui-backend-claude/src/history.ts index 3123ed8264..515a57f3dc 100644 --- a/packages/ui-backend-claude/src/history.ts +++ b/packages/ui-backend-claude/src/history.ts @@ -7,6 +7,7 @@ import { getSessionMessages as sdkGetSessionMessages, } from "@anthropic-ai/claude-agent-sdk"; import type { + RuntimeNotice, ChatSession, MessagePart, SessionHistoryMessage, @@ -199,6 +200,22 @@ export async function buildSessionHistory( } continue; } + // The runtime's own note that a turn stopped: a status for that turn, + // not something the model said (#3356). Like a failure, it lands on the + // assistant message it ended, after any partial answer, and the same + // notice observed again there is shown once. + const notice = runtimeNotice((entry as any).message, content); + if (notice) { + const last = messages[messages.length - 1]; + if (last?.role === "assistant") { + // A failure is the fuller account of the same stop, and an aborted + // request says more than an unspecified notice. + if (!last.failure && last.runtimeNotice?.cause !== "aborted") last.runtimeNotice = notice; + } else { + messages.push({ role: "assistant", content: "", toolCalls: [], parts: [], runtimeNotice: notice }); + } + continue; + } let text = ""; let thinking = ""; const toolCalls: Array<{ @@ -285,8 +302,9 @@ const SYNTHETIC_MODEL = ""; * How Claude Code words the API errors it writes into a transcript: its * "API Error" prefix (also mid-text, after "Failed to authenticate."), and the * login and billing texts it writes without one. A synthetic message that - * matches none of them — "No response requested.", a fallback notice — is - * not a failure and replays as text. + * matches none of them is not a failure: "No response requested." and an + * aborted request replay as a runtime notice (`runtimeNotice`), and any other + * fallback notice replays as text. */ const API_ERROR_TEXTS: ReadonlyArray<{ pattern: RegExp; errorClass: string }> = [ { pattern: /^Not logged in\b/, errorClass: FIRST_PARTY_FAILURE_CLASSES.authentication_failed }, @@ -299,6 +317,38 @@ const API_ERROR_TEXTS: ReadonlyArray<{ pattern: RegExp; errorClass: string }> = /** What Claude Code writes when a request is aborted: a cancellation. */ const ABORTED_TEXT = /^API Error: Request was aborted\.?$/; +/** + * What Claude Code writes into a transcript, under its own synthetic model, + * when a turn stops without an answer the model gave. Both strings are the + * installed CLI's own constants: "No response requested." is the reply it + * synthesises for an interrupted conversation it resumes, and "API Error: + * Request was aborted." is what it records for an aborted request. Only the + * second establishes anything about the cause, and neither says who stopped + * the turn. + */ +const RUNTIME_NOTICES: ReadonlyArray<{ text: string; cause: RuntimeNotice["cause"] }> = [ + { text: "No response requested.", cause: "unspecified" }, + { text: "API Error: Request was aborted.", cause: "aborted" }, +]; + +/** + * The runtime notice a replayed synthetic message records, or null for any + * other message. Provenance first: the same words from the model, or from + * the user, are theirs and replay as text. + */ +export function runtimeNotice(message: unknown, content: unknown[]): RuntimeNotice | null { + if ((message as { model?: unknown } | null)?.model !== SYNTHETIC_MODEL) return null; + const blocks = content as Array<{ type?: unknown; text?: unknown }>; + if (blocks.length === 0 || !blocks.every((block) => block.type === "text")) return null; + const text = blocks + .map((block) => (typeof block.text === "string" ? block.text : "")) + .join("") + .trim(); + const bare = text.replace(/\.$/, ""); + const known = RUNTIME_NOTICES.find((notice) => notice.text.replace(/\.$/, "") === bare); + return known ? { cause: known.cause, message: text } : null; +} + /** * The failure a replayed synthetic API-error message records, or null for * any other message. The class is read from the text only where the text diff --git a/packages/ui-backend-claude/tests/history-api-failure.test.ts b/packages/ui-backend-claude/tests/history-api-failure.test.ts index af8a461f28..93387df4d9 100644 --- a/packages/ui-backend-claude/tests/history-api-failure.test.ts +++ b/packages/ui-backend-claude/tests/history-api-failure.test.ts @@ -100,14 +100,54 @@ describe("an API error replays as the turn's failure", () => { } }); - test("the runtime's other synthetic messages replay as text", async () => { - for (const text of ["No response requested.", "API Error: Request was aborted."]) { + // #3356: what the runtime writes when a turn stopped is a status for that + // turn, never the agent's words, and only an aborted request names a cause. + test("the runtime's stop notices replay as a runtime notice, not as the agent's text", async () => { + for (const [text, cause] of [["No response requested.", "unspecified"], ["API Error: Request was aborted.", "aborted"]] as const) { const [, message] = await read([userTurn("hi"), syntheticEntry(text)]); expect(message!.failure).toBeUndefined(); - expect(message!.content).toBe(text); + expect(message!.content).toBe(""); + expect(message!.parts).toEqual([]); + expect(message!.runtimeNotice).toEqual({ cause, message: text }); } }); + test("a stop notice after a partial answer keeps that answer and lands on its message", async () => { + const history = await read([userTurn("Find it"), answerEntry(PARTIAL_ANSWER), syntheticEntry("No response requested.")]); + expect(history).toHaveLength(2); + expect(history[1]!.content).toBe(PARTIAL_ANSWER); + expect(history[1]!.parts).toEqual([{ kind: "text", text: PARTIAL_ANSWER }]); + expect(history[1]!.runtimeNotice).toEqual({ cause: "unspecified", message: "No response requested." }); + }); + + test("the same stop observed again is one notice, and a failure stays the fuller account", async () => { + const repeated = await read([userTurn("hi"), syntheticEntry("No response requested."), syntheticEntry("No response requested.")]); + expect(repeated).toHaveLength(2); + expect(repeated[1]!.content).toBe(""); + expect(repeated[1]!.runtimeNotice).toEqual({ cause: "unspecified", message: "No response requested." }); + const failed = await read([userTurn("hi"), syntheticEntry(OVERLOADED_TEXT), syntheticEntry("No response requested.")]); + expect(failed).toHaveLength(2); + expect(failed[1]!.failure).toEqual({ errorClass: "unknown", message: OVERLOADED_TEXT }); + expect(failed[1]!.runtimeNotice).toBeUndefined(); + }); + + test("the model or the user quoting a stop notice is their own text", async () => { + for (const text of ["No response requested.", "API Error: Request was aborted."]) { + const [user, answer] = await read([userTurn(text), answerEntry(text)]); + expect(user!.content).toBe(text); + expect(answer!.content).toBe(text); + expect(answer!.runtimeNotice).toBeUndefined(); + } + }); + + test("a 499 cancelled request stays a classified failure, not a notice", async () => { + const text = "API Error: 499 Inference request cancelled"; + const [, message] = await read([userTurn("hi"), syntheticEntry(text)]); + expect(message!.failure).toEqual({ errorClass: "unknown", status: 499, message: text }); + expect(message!.runtimeNotice).toBeUndefined(); + expect(message!.content).toBe(""); + }); + test("a model's answer that talks about an API error is not a failure", async () => { const [, message] = await read([userTurn("What does 400 mean?"), answerEntry("API Error: 400 means a bad request.")]); expect(message!.failure).toBeUndefined(); diff --git a/packages/ui-react/src/components/chat/answer-delivery-status.tsx b/packages/ui-react/src/components/chat/answer-delivery-status.tsx index af083e68aa..c5ee19521a 100644 --- a/packages/ui-react/src/components/chat/answer-delivery-status.tsx +++ b/packages/ui-react/src/components/chat/answer-delivery-status.tsx @@ -14,7 +14,7 @@ import { useEffect, useRef, useState } from "react"; import { Button } from "@schlessera/brain-ui-kit"; import { useBrainUiRoot } from "../../root-context.js"; -import { deliveryCopy, SEND_AS_MESSAGE_NOTE, type DeliveryAction } from "../../lib/answer-delivery/copy.js"; +import { deliveryCopy, SEND_AS_MESSAGE_NOTE, SENT_AS_MESSAGE_NOTE, type DeliveryAction } from "../../lib/answer-delivery/copy.js"; import type { AnswerDelivery } from "../../lib/answer-delivery/types.js"; const LABELS: Record = { @@ -74,15 +74,23 @@ export function AnswerDeliveryStatus({ () => {} ); return; - case "sendAsMessage": - onSendAsMessage?.(answerText()); + case "sendAsMessage": { + // Once (#3356): the action goes before the message does, and focus + // stays on this card's outcome rather than on a removed button. + const chat = root.stores.chat.getState(); + const current = chat.deliveries[delivery.requestId]; + if (!onSendAsMessage || current?.sentAsMessage) return; + if (current) chat.setDelivery(delivery.requestId, { ...current, sentAsMessage: true, focus: false }); + onSendAsMessage(answerText()); + tagRef.current?.focus(); return; + } } }; // A mirror shows the owner's state; only the owning tab acts on it. const actions = delivery.mirror ? [] - : copy.actions.filter((a) => a !== "sendAsMessage" || onSendAsMessage); + : copy.actions.filter((a) => a !== "sendAsMessage" || (onSendAsMessage && !delivery.sentAsMessage)); return (
{SEND_AS_MESSAGE_NOTE}

+ ) : delivery.sentAsMessage ? ( +

{SENT_AS_MESSAGE_NOTE}

) : null}
); diff --git a/packages/ui-react/src/components/chat/ask-user-card.tsx b/packages/ui-react/src/components/chat/ask-user-card.tsx index 608294c439..5ad2d31055 100644 --- a/packages/ui-react/src/components/chat/ask-user-card.tsx +++ b/packages/ui-react/src/components/chat/ask-user-card.tsx @@ -104,6 +104,7 @@ export function AskUserCard({ answered, cancelled, lapsedNote, + endedPrompt, typed, answeredAt, onSubmit, @@ -117,6 +118,11 @@ export function AskUserCard({ answered?: Record; cancelled?: boolean; lapsedNote?: string; + /** + * The turn that asked has ended (#3356): the card stays editable under + * this prompt, and its Submit no longer answers the request. + */ + endedPrompt?: string; /** The answer was typed into the composer rather than chosen. */ typed?: boolean; /** When the answer was given; absent on resumed history. */ @@ -135,7 +141,7 @@ export function AskUserCard({ onReask?: (text: string) => void; }) { const root = useBrainUiRoot(); - const prompt = `${root.config.assistantName} needs your input`; + const prompt = endedPrompt ?? `${root.config.assistantName} needs your input`; const [state, setState] = useState(() => questions.map(() => defaultState()) diff --git a/packages/ui-react/src/components/chat/ask-user-form-card.tsx b/packages/ui-react/src/components/chat/ask-user-form-card.tsx index e0233735c2..6acbb9dcdf 100644 --- a/packages/ui-react/src/components/chat/ask-user-form-card.tsx +++ b/packages/ui-react/src/components/chat/ask-user-form-card.tsx @@ -20,6 +20,11 @@ export function AskUserFormExchangeCard(p: { answers?: AskUserFormAnswers; cancelled?: boolean; lapsedNote?: string; + /** + * The turn that asked has ended (#3356): the card stays editable under + * this prompt, and its Submit no longer answers the request. + */ + endedPrompt?: string; answeredAt?: number; onSubmit?: ( requestId: string, @@ -62,7 +67,7 @@ export function AskUserFormExchangeCard(p: { {...base} key={reopened ? "reopened" : "live"} singleKeys={singleKeys} - prompt={`${root.config.assistantName} needs your input`} + prompt={p.endedPrompt ?? `${root.config.assistantName} needs your input`} onSubmit={(submitted) => { const result = askUserFormPayload(p.form, submitted); if (reopened) { diff --git a/packages/ui-react/src/components/chat/ask-user-list-card.tsx b/packages/ui-react/src/components/chat/ask-user-list-card.tsx index 7e7a691d49..7b8d3905e1 100644 --- a/packages/ui-react/src/components/chat/ask-user-list-card.tsx +++ b/packages/ui-react/src/components/chat/ask-user-list-card.tsx @@ -64,6 +64,7 @@ export function AskUserListExchangeCard({ notes, cancelled, lapsedNote, + endedPrompt, answeredAt, onSubmit, onCancel, @@ -77,6 +78,11 @@ export function AskUserListExchangeCard({ notes?: Record; cancelled?: boolean; lapsedNote?: string; + /** + * The turn that asked has ended (#3356): the card stays editable under + * this prompt, and its Submit no longer answers the request. + */ + endedPrompt?: string; answeredAt?: number; onSubmit: (requestId: string, answers: Record, notes?: Record) => void; onCancel: (requestId: string) => void; @@ -127,7 +133,7 @@ export function AskUserListExchangeCard({ key={reopened ? "reopened" : "live"} {...base} state="pending" - prompt={`${root.config.assistantName} needs your input`} + prompt={endedPrompt ?? `${root.config.assistantName} needs your input`} singleKeys={singleKeys} onSubmit={({ answers, notes: kept }) => { if (reopened) { diff --git a/packages/ui-react/src/components/chat/ask-user-rank-card.tsx b/packages/ui-react/src/components/chat/ask-user-rank-card.tsx index 06474d445e..e50e95abd8 100644 --- a/packages/ui-react/src/components/chat/ask-user-rank-card.tsx +++ b/packages/ui-react/src/components/chat/ask-user-rank-card.tsx @@ -18,6 +18,11 @@ export function AskUserRankExchangeCard(p: { unchanged?: boolean; cancelled?: boolean; lapsedNote?: string; + /** + * The turn that asked has ended (#3356): the card stays editable under + * this prompt, and its Submit no longer answers the request. + */ + endedPrompt?: string; answeredAt?: number; onSubmit?: (requestId: string, order: string[], unchanged: boolean) => void; onCancel: (requestId: string) => void; @@ -30,7 +35,7 @@ export function AskUserRankExchangeCard(p: { if (p.order) return ; if (p.cancelled && !reopened) return setReopened(true) : undefined} />; - return { if (reopened) { // A reask is a new message: the reader continues in the composer. diff --git a/packages/ui-react/src/components/chat/message-bubble.tsx b/packages/ui-react/src/components/chat/message-bubble.tsx index 1027893e3e..aac5bcf279 100644 --- a/packages/ui-react/src/components/chat/message-bubble.tsx +++ b/packages/ui-react/src/components/chat/message-bubble.tsx @@ -40,10 +40,11 @@ import { UserTurn, } from "./transcript-turn.js"; import { TurnError } from "./turn-error.js"; +import { TurnNotice } from "./turn-notice.js"; import { AnswerDeliveryStatus } from "./answer-delivery-status.js"; import { TurnJournal } from "./turn-journal.js"; import { answerAsMessage, UNCONFIRMED_RECORD, withSubmittedAnswer } from "./answer-text.js"; -import { isRefusedAdmission } from "../../lib/answer-delivery/types.js"; +import { isRefusedAdmission, type AnswerPayload } from "../../lib/answer-delivery/types.js"; import { useChatStore } from "../../stores/chat-store.js"; /** @@ -500,6 +501,10 @@ function AssistantContent({ first, live and on replay alike. */} {message.failure && !message.isStreaming ? : null} + {/* How the turn stopped, when no failure says so (#3356): a status + after its content, never the agent's words. */} + {message.runtimeNotice && !message.failure && !message.isStreaming ? : null} + {(message.isStreaming || approval?.restored) && (message.retry ? ( ) : approval ? ( @@ -591,19 +596,49 @@ function DeliveredExchange({ onAskUserRankSubmit?: (requestId: string, order: string[], unchanged: boolean) => void; onAskUserListSubmit: (requestId: string, answers: Record, notes?: Record) => void; }) { + const root = useBrainUiRoot(); + const sessionId = useChatStore((s) => s.activeSessionId); const delivery = useChatStore((s) => s.deliveries[exchange.requestId]); + // A question its turn ended before anything was submitted (#3356). Its + // card stays the editable question, so a draft in progress survives, but + // no answer can reach the ended request: Submit keeps the answer on this + // card as Not delivered, and only the footer's explicit Send as message + // sends it, as a new chat message. Dismiss closes it here; the host has + // nothing left to cancel. + const [endedDismissed, setEndedDismissed] = useState(false); + const ended = exchange.terminal === true && !endedDismissed && (!delivery || isRefusedAdmission(delivery.state)); + const endedBy = exchange.endedBy === "timeout" ? "timed out" : "ended"; + const keep = (payload: AnswerPayload) => { + const at = Date.now(); + root.stores.chat.getState().setDelivery(exchange.requestId, { + requestId: exchange.requestId, submissionId: "", sessionId, state: "closed", reason: "ended", + payload, submittedAt: at, settledAt: at, focus: true, + }); + }; + const submitAsk = ended ? (_: string, answers: Record, annotations?: Record) => + keep({ kind: "ask_user", answers, ...(annotations ? { annotations } : {}) }) : onAskUserSubmit; + const submitList = ended ? (_: string, answers: Record, notes?: Record) => + keep({ kind: "ask_user_list", answers, ...(notes ? { notes } : {}) }) : onAskUserListSubmit; + const submitRank = ended ? (_: string, order: string[], unchanged: boolean) => + keep({ kind: "ask_user_rank", order, unchanged }) : onAskUserRankSubmit; + const submitForm = ended ? (_: string, answers: AskUserFormAnswers, visibleNodes: string[]) => + keep({ kind: "ask_user_form", answers, visibleNodes }) : onAskUserFormSubmit; + const cancel = ended ? () => setEndedDismissed(true) : onAskUserCancel; + const endedPrompt = ended ? `The turn ${endedBy} before you answered · Submit keeps your answer here to send as a new message` : undefined; + const lapsedNote = exchange.terminal ? `no longer waiting · the turn ${endedBy}` : undefined; // While saving, or when nothing was admitted, the editable card stays // mounted with its draft; otherwise it shows the submitted answer. const shown = delivery && delivery.state !== "saving" && !isRefusedAdmission(delivery.state); - const ex = shown ? withSubmittedAnswer(exchange, delivery) : exchange; + const base = ended ? { ...exchange, cancelled: undefined } : exchange; + const ex = shown ? withSubmittedAnswer(base, delivery) : base; // A recorded answer the host has not confirmed must not read "Answered". const record = shown && delivery.state !== "answered" ? UNCONFIRMED_RECORD : undefined; const card = ( ex.form ? ( - + ) : ex.rank ? ( + cancelled={ex.cancelled} lapsedNote={lapsedNote} endedPrompt={endedPrompt} answeredAt={ex.answeredAt} onSubmit={submitRank} onCancel={cancel} onReask={onAskUserReask} /> ) : ex.list ? ( ) : ( @@ -623,11 +658,11 @@ function DeliveredExchange({ requestId={ex.requestId} questions={ex.questions} answered={ex.answers} - cancelled={ex.cancelled} lapsedNote={ex.terminal ? "no longer waiting · the turn ended" : undefined} + cancelled={ex.cancelled} lapsedNote={lapsedNote} endedPrompt={endedPrompt} typed={ex.typed} answeredAt={ex.answeredAt} - onSubmit={onAskUserSubmit} - onCancel={onAskUserCancel} + onSubmit={submitAsk} + onCancel={cancel} onReask={onAskUserReask} /> ) @@ -641,7 +676,7 @@ function DeliveredExchange({ // new parent when its footer appeared would remount, and a refused // answer's draft would be lost with it. return ( -
+
{card} {delivery ? ( = { + timeout: { + tag: "Turn timed out", + body: "The host's time limit for one turn ran out, so this turn stopped.", + }, + aborted: { + tag: "Turn stopped", + body: "The agent runtime recorded that this turn's request was aborted.", + }, + unspecified: { + tag: "Turn ended without a reply", + body: "The agent runtime noted that this turn ended without an answer.", + }, +}; + +export function TurnNotice({ message }: { message: ChatMessage }) { + const root = useBrainUiRoot(); + const sessionId = useChatStore((s) => s.activeSessionId); + const notice = message.runtimeNotice!; + const copy = TURN_NOTICE_COPY[notice.cause]; + // Fixed at mount: a replay that keeps this row mounted does not announce. + const [announce] = useState(Boolean(message.runtimeNoticeLive)); + useEffect(() => { + if (!message.runtimeNoticeLive) return; + const chat = root.stores.chat.getState(); + const buffer = sessionId ? chat.buffers[sessionId] : chat.draft; + if (!buffer) return; + const messages = buffer.messages.map((m) => (m.id === message.id ? { ...m, runtimeNoticeLive: false } : m)); + if (sessionId) root.stores.chat.setState({ buffers: { ...chat.buffers, [sessionId]: { ...buffer, messages } } }); + else root.stores.chat.setState({ draft: { ...buffer, messages } }); + }, [root, sessionId, message.id, message.runtimeNoticeLive]); + + return ( +
+

+ {copy.tag} +

+

{copy.body}

+

+ {announce ? `${copy.tag}. ${copy.body}` : ""} +

+
+ ); +} diff --git a/packages/ui-react/src/hooks/websocket-handlers/chat.ts b/packages/ui-react/src/hooks/websocket-handlers/chat.ts index b09b049fd9..11f5885b7c 100644 --- a/packages/ui-react/src/hooks/websocket-handlers/chat.ts +++ b/packages/ui-react/src/hooks/websocket-handlers/chat.ts @@ -1,4 +1,4 @@ -import { FIRST_PARTY_FAILURE_CLASSES } from "@schlessera/brain-ui-sdk/protocol"; +import { FIRST_PARTY_FAILURE_CLASSES, HOST_TIMEOUT_OUTCOME_DETAIL } from "@schlessera/brain-ui-sdk/protocol"; import { ASK_USER_FORM_INPUT_SCHEMA } from "@schlessera/brain-ui-sdk/tool-contracts"; import { askUserFormSpec, askUserFormPayload } from "@schlessera/brain-ui-sdk/internal/client"; import type { ChatMessage, ToolCall, AskUserExchange } from "../../stores/chat-store.js"; @@ -87,6 +87,9 @@ function convertHistoryMessage(msg: SessionHistoryMessage): ChatMessage { ...(msg.role === "assistant" && msg.journal ? { journal: msg.journal } : {}), // The failure that ended the turn (#575), drawn as it was live. ...(msg.role === "assistant" && msg.failure ? { failure: msg.failure, retryOfTurnId: msg.retryOfTurnId } : {}), + // The runtime's own note that the turn stopped (#3356): a status, never + // the agent's words, and never a fresh alert on replay. + ...(msg.role === "assistant" && msg.runtimeNotice && !msg.failure ? { runtimeNotice: { cause: msg.runtimeNotice.cause } } : {}), }; } @@ -381,7 +384,11 @@ export const chatFrameHandlers = { result: (msg, context) => { if (context.key !== null && msg.stateRoom && !["worker_state_busy", "session_too_large", "worker_state_exceeded"].includes(msg.failure?.errorClass ?? "")) context.state.setStateRoom(context.key, msg.stateRoom); - context.state.endTurnQuestions(context.key, context.frameTurnId); + // The host's hard turn limit ended it (#3356): the conversation says so, + // and its open questions say why they closed. + const timedOut = msg.outcome === "cancelled" && msg.outcomeDetail === HOST_TIMEOUT_OUTCOME_DETAIL; + context.state.endTurnQuestions(context.key, context.frameTurnId, timedOut ? "timeout" : undefined); + if (timedOut) context.state.setTurnNotice(context.key, { cause: "timeout" }, context.frameTurnId); context.state.finishAssistantMessage(context.key); // An absent outcome is the legacy wire, where `isError` alone decides. const failed = msg.outcome === "error" || (msg.outcome === undefined && msg.isError); diff --git a/packages/ui-react/src/lib/answer-delivery/copy.ts b/packages/ui-react/src/lib/answer-delivery/copy.ts index cb05b6445f..3d6bf23a41 100644 --- a/packages/ui-react/src/lib/answer-delivery/copy.ts +++ b/packages/ui-react/src/lib/answer-delivery/copy.ts @@ -18,6 +18,9 @@ export interface DeliveryCopy { /** The line under `Send as message` (ruling R1). */ export const SEND_AS_MESSAGE_NOTE = "Sends a new chat message; it doesn't answer this question."; +/** What replaces it once `Send as message` was used (#3356). */ +export const SENT_AS_MESSAGE_NOTE = "Sent as a new chat message; it didn't answer this question."; + const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; const pad = (n: number) => String(n).padStart(2, "0"); diff --git a/packages/ui-react/src/lib/answer-delivery/types.ts b/packages/ui-react/src/lib/answer-delivery/types.ts index 870db32e10..f8f9a7191e 100644 --- a/packages/ui-react/src/lib/answer-delivery/types.ts +++ b/packages/ui-react/src/lib/answer-delivery/types.ts @@ -111,6 +111,11 @@ export interface AnswerDelivery { mirror?: boolean; /** This tab just submitted it: the card moves focus to its status. */ focus?: boolean; + /** + * `Send as message` already sent this answer as a new chat message + * (#3356): it is offered once, so a repeated tap cannot send it twice. + */ + sentAsMessage?: boolean; } /** States in which the answer may still reach the host. */ diff --git a/packages/ui-react/src/stores/chat-state.ts b/packages/ui-react/src/stores/chat-state.ts index 1c655958e7..44bfc38459 100644 --- a/packages/ui-react/src/stores/chat-state.ts +++ b/packages/ui-react/src/stores/chat-state.ts @@ -107,6 +107,15 @@ export interface ChatMessage { retryOfTurnId?: string; /** Received live in this client; absent on history replay. */ failureLive?: boolean; + /** + * How the turn stopped, when the runtime or the host says so and no + * failure does (#3356): a status for the turn, drawn after its content, + * never the agent's words. `timeout` only from the host's own timeout + * report; `aborted`/`unspecified` from the runtime's replayed notice. + */ + runtimeNotice?: TurnNotice; + /** The notice arrived live in this client; absent on history replay. */ + runtimeNoticeLive?: boolean; /** While streaming: the failed model call the runtime is retrying (#575). */ retry?: TurnRetry; } @@ -197,10 +206,20 @@ export interface ToolCall { endedAt?: number; } +/** Why a turn stopped, as `ChatMessage.runtimeNotice` records it (#3356). */ +export interface TurnNotice { + cause: "timeout" | "aborted" | "unspecified"; +} + export interface AskUserExchange { requestId: string; /** Host terminal state ended the unanswered exchange. */ terminal?: true; + /** + * The host's turn limit is what ended it (#3356), from the terminal frame; + * absent when the host did not say why the turn ended. + */ + endedBy?: "timeout"; /** * The host turn that raised the request, from the request frame. A card * rebuilt from history has none until the host re-delivers the request. @@ -548,7 +567,18 @@ export interface ChatState { */ reopenAskExchange: (key: ChatKey, requestId: string) => void; clearAskUser: (key: ChatKey) => void; - endTurnQuestions: (key: ChatKey, turnId?: string) => void; + /** + * The turn ended: its unanswered questions can no longer be answered. + * `endedBy` records the host's stated reason on them, including on + * questions an earlier terminal frame of the same turn already ended. + */ + endTurnQuestions: (key: ChatKey, turnId?: string, endedBy?: "timeout") => void; + /** + * Record how a turn stopped (#3356) on its assistant message, as + * `failAssistantMessage` finds it. A turn that already shows a failure + * keeps that, the fuller account; the same notice twice is one notice. + */ + setTurnNotice: (key: ChatKey, notice: TurnNotice, turnId?: string) => void; /** * Delivery state of submitted ask answers, by request id (#910). Held * outside the transcript buffers: an answer queued in one session must @@ -1821,10 +1851,14 @@ export function createChatStore(env: StoreEnvironment, provider: StoreApi mutateBuffer(key, () => ({ askUser: null })), - endTurnQuestions: (key, turnId) => mutateBuffer(key, (chat) => { + endTurnQuestions: (key, turnId, endedBy) => mutateBuffer(key, (chat) => { const end = (exchange: AskUserExchange): AskUserExchange => { - if ((turnId && exchange.turnId !== turnId) || exchange.answers || exchange.order || exchange.formAnswers || exchange.cancelled) return exchange; - return { ...exchange, cancelled: true, terminal: true }; + if (turnId && exchange.turnId !== turnId) return exchange; + // A question this turn's earlier terminal frame already ended + // learns why, when the host says so (#3356). + if (exchange.terminal) return endedBy && exchange.endedBy !== endedBy ? { ...exchange, endedBy } : exchange; + if (exchange.answers || exchange.order || exchange.formAnswers || exchange.cancelled) return exchange; + return { ...exchange, cancelled: true, terminal: true, ...(endedBy ? { endedBy } : {}) }; }; return { messages: chat.messages.map((message) => message.askUserExchanges ? { ...message, askUserExchanges: message.askUserExchanges.map(end) } : message), @@ -1885,6 +1919,35 @@ export function createChatStore(env: StoreEnvironment, provider: StoreApi + mutateBuffer(key, (chat) => { + const msgs = [...chat.messages]; + let index = turnId ? msgs.findLastIndex((m) => m.role === "assistant" && (m.turnId ?? m.streamTurnId) === turnId) : -1; + if (index === -1) { + // As failAssistantMessage: the last assistant message, unless + // another turn owns it. + const last = msgs.findLastIndex((m) => m.role === "assistant"); + const owner = last === -1 ? undefined : msgs[last].turnId ?? msgs[last].streamTurnId; + if (last !== -1 && (owner === undefined || owner === turnId)) index = last; + } + if (index !== -1 && (msgs[index].failure || msgs[index].runtimeNotice?.cause === notice.cause)) return {}; + if (index === -1) { + msgs.push({ + id: nextId(), + role: "assistant", + content: "", + toolCalls: [], + parts: [], + isStreaming: false, + timestamp: Date.now(), + ...(turnId ? { turnId } : {}), + }); + index = msgs.length - 1; + } + msgs[index] = { ...msgs[index], runtimeNotice: notice, runtimeNoticeLive: true }; + return { messages: msgs }; + }), + setRetry: (key, retry) => mutateLastAssistant(key, (last) => { if (!last.isStreaming) return last; diff --git a/packages/ui-react/tests/ended-question-runtime.test.ts b/packages/ui-react/tests/ended-question-runtime.test.ts new file mode 100644 index 0000000000..fc329ea5d3 --- /dev/null +++ b/packages/ui-react/tests/ended-question-runtime.test.ts @@ -0,0 +1,335 @@ +import { runtimePackageBuild } from "./fixtures/runtime-package-build"; +/** + * A question left unanswered until the host's turn limit ran out (#3356), in + * real Chrome, on the public ChatPage, against the real host (`createApp`, + * its WebSocket, SQLite catalog, coordinator, bridge and dispatch) with a + * scripted backend that asks each of the four ask kinds and never gets an + * answer in time. + * + * The host's configured hard limit is short here, as the issue's + * verification asks; it is the same elapsed-time timer production arms. + * What is proved: the turn ends at that limit and says so; the card keeps the + * draft the user typed but did not submit; nothing is sent to the ended + * request, before or after the card's Submit; only the explicit Send as + * message, operated from the keyboard, starts one new, ordinary, admitted + * message carrying the question and that answer; and a replay of the + * runtime's stop notice shows a status without a fresh alert. Nothing leaves + * 127.0.0.1. + */ +import { runtimeHookPhases } from "./fixtures/runtime-hook-phases.ts"; +import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test"; +import { statSync } from "node:fs"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { resolve } from "node:path"; +import { chromium, type Browser, type BrowserContext, type Page } from "playwright"; +import { createRecordingObservability, createStaticBackendRegistry, resolveServerConfig } from "@schlessera/brain-ui-server"; +import { createFixtureApp as createApp } from "../../ui-server/tests/helpers/native-app-fixture.js"; +import type { AgentBackend, SessionHistoryMessage } from "@schlessera/brain-ui-sdk/server"; +import { askUserFormSpec } from "@schlessera/brain-ui-sdk/internal/client"; +import { createFixtureBrain } from "../../../scripts/captures/core-fixture.ts"; + +const candidates = [process.env.PUPPETEER_EXECUTABLE_PATH, "/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"]; +const executablePath = candidates.find((path) => path && statSync(path, { throwIfNoEntry: false })?.isFile()); +if (!executablePath && process.env.BRAIN_REQUIRE_CHROME === "1") throw new Error("Ended question runtime proof requires real Chrome"); +if (!executablePath) console.warn("SKIPPING ended question runtime proof: no Chrome; ended-card recovery is unverified locally."); + +type Kind = "ask_user" | "ask_user_list" | "ask_user_rank" | "ask_user_form"; +const KINDS: Kind[] = ["ask_user", "ask_user_list", "ask_user_rank", "ask_user_form"]; +const TOOL: Record = { + ask_user: "mcp__brain-ui__ask_user", + ask_user_list: "mcp__brain-ui__ask_user_list", + ask_user_rank: "mcp__brain-ui__ask_user_rank", + ask_user_form: "mcp__brain-ui__ask_user_form", +}; +const NOTE = "Bind the oars, Ὀδυσσεύς"; +const INPUT: Record> = { + ask_user: { questions: [{ question: "Which harbour first?", header: "Harbour", multiSelect: false, options: [{ label: "Ithaca", description: "Home" }, { label: "Pylos", description: "Nestor’s court" }] }] }, + ask_user_list: { prompt: "Choose raft supplies", items: [{ id: "rope", label: "Rope" }], scale: [{ label: "Pack" }, { label: "Leave" }], allowSkip: false, notes: false }, + ask_user_rank: { prompt: "Order raft supplies", items: [{ id: "rope", label: "Rope" }, { id: "timber", label: "Timber" }] }, + ask_user_form: { prompt: "Record raft supplies", nodes: [{ id: "note", kind: "text", prompt: "Supply note", required: true }] }, +}; +/** What the new message must carry: the question and the user's own draft. */ +const CARRIES: Record = { + ask_user: ["Which harbour first?", "Pylos"], + ask_user_list: ["Choose raft supplies", "Rope", "Leave"], + ask_user_rank: ["Order raft supplies", "1. Timber", "2. Rope"], + ask_user_form: ["Record raft supplies", NOTE], +}; + +/** The host's configured hard limit for every turn in this suite. */ +const TURN_TIMEOUT_MS = 4_000; + +let browser: Browser | undefined; +let app: Awaited> | undefined; +let server: ReturnType | undefined; +let scratch: string | undefined; +let origin = ""; +let sequence = 0; +/** Every settlement the backend's ask tools received, by request id. */ +const settlements = new Map(); +/** Every turn's first prompt line, in arrival order. */ +const prompts: string[] = []; +/** When each asking turn started and when its signal aborted, by request id. */ +const clocks = new Map(); +const histories = new Map(); + +const hook = runtimeHookPhases("ended-question-runtime"); + +beforeAll(async () => { + if (!executablePath) return; + const repo = resolve(import.meta.dir, "../../.."); + const [buildOut, buildErr, buildCode] = await runtimePackageBuild(repo, ["ui-react", "ui-server", "core"], hook); + if (buildCode !== 0) throw new Error(`Ended question fixture build failed (${buildCode}): ${buildOut}\n${buildErr}`); + scratch = await mkdtemp(resolve(tmpdir(), "odysseus-ended-question-")); + const brain = resolve(scratch, "brain"); + await hook.phase("fixture-brain", () => createFixtureBrain(repo, brain)); + const assets = resolve(scratch, "client"); + await mkdir(assets); + const bundle = await hook.phase("client-build", () => Bun.build({ + entrypoints: [resolve(import.meta.dir, "fixtures/answer-delivery-client.ts")], + target: "browser", + conditions: ["bun"], + outdir: assets, + naming: "client.js", + })); + if (!bundle.success) throw new Error(`Ended question client build failed: ${bundle.logs.join("\n")}`); + await writeFile(resolve(assets, "index.html"), '
'); + const backend: AgentBackend = { + id: "ended-scripted", + capabilities: { resume: true, permissions: false, thinking: false, attachments: false, askUser: true, costReporting: false, concurrentSessions: true, followUp: false }, + listProfiles: () => [{ id: "ended-scripted", label: "Local fixture" }], + listSessions: async () => [], + getHistory: async (sessionId) => histories.get(sessionId) ?? [], + async startTurn({ prompt: contextPrompt, bridge, signal, sessionId: resumed }) { + const prompt = contextPrompt.split("\n", 1)[0]!; + prompts.push(contextPrompt); + const kind = prompt.split(":", 1)[0] as Kind; + if (!KINDS.includes(kind)) { + // The recovery message: an ordinary new turn in the same session. + const sessionId = resumed!; + bridge.emit({ type: "session_info", sessionId, isNew: false }); + bridge.emit({ type: "text_delta", sessionId, text: "Noted." }); + bridge.emit({ type: "result", sessionId, outcome: "success", durationMs: 0, numTurns: 1, isError: false }); + return; + } + const input = INPUT[kind]; + const n = ++sequence; + const sessionId = `odysseus-ended-${n}`; + const requestId = `toolu_${kind}_${n}`; + const clock: { startedAt: number; askedAt?: number; abortedAt?: number } = { startedAt: Date.now() }; + clocks.set(requestId, clock); + signal.addEventListener("abort", () => { clock.abortedAt = Date.now(); }, { once: true }); + bridge.emit({ type: "session_info", sessionId, isNew: true }); + bridge.emit({ type: "text_delta", sessionId, text: "Before we sail: " }); + bridge.emit({ type: "tool_use_start", sessionId, toolUseId: requestId, toolName: TOOL[kind] }); + bridge.emit({ type: "tool_use_complete", sessionId, toolUseId: requestId, toolName: TOOL[kind], input }); + const call = { id: requestId, name: TOOL[kind], input } as SessionHistoryMessage["toolCalls"][number]; + const settled: unknown[] = []; + settlements.set(requestId, settled); + clock.askedAt = Date.now(); + try { + settled.push(kind === "ask_user" + ? await bridge.askUser!(requestId, input.questions as never) + : kind === "ask_user_list" + ? await bridge.askUserList!(requestId, input as never) + : kind === "ask_user_rank" + ? await bridge.askUserRank!(requestId, input as never) + : await bridge.askUserForm!(requestId, askUserFormSpec(input as never))); + } catch (error) { + const output = (error as Error).message; + // What the runtime's transcript holds afterwards: the interrupted + // call, and its own stop notice once the session is resumed. + histories.set(sessionId, [ + { role: "user", content: prompt, toolCalls: [] }, + { role: "assistant", content: "Before we sail: ", toolCalls: [{ ...call, output, isError: true }], + parts: [{ kind: "text", text: "Before we sail: " }, { kind: "tool", toolIndex: 0 }], + runtimeNotice: { cause: "unspecified", message: "No response requested." } }, + ]); + bridge.emit({ type: "tool_result", sessionId, toolUseId: requestId, output, isError: true }); + // The Claude turn runner's cancelled terminal: status, then result. + bridge.emit({ type: "status", sessionId, status: "cancelled" }); + bridge.emit({ type: "result", sessionId, outcome: "cancelled", durationMs: 0, numTurns: 1, isError: false }); + return; + } + bridge.emit({ type: "result", sessionId, outcome: "success", durationMs: 0, numTurns: 1, isError: false }); + }, + }; + app = await hook.phase("host-start", () => createApp({ + config: resolveServerConfig({ BRAIN_PATH: brain, DB_PATH: resolve(scratch!, "ui.db"), AUTH_MODE: "none", HOST: "127.0.0.1", NODE_ENV: "test", BRAIN_UI_PRICING_DISCOVERY: "0", BRAIN_UI_MODEL_DISCOVERY: "0" }), + staticRoot: assets, + registry: createStaticBackendRegistry([backend], backend.id), + observability: createRecordingObservability(), + turnTimeoutMs: TURN_TIMEOUT_MS, + })); + server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: app.fetch, websocket: app.websocket }); + origin = `http://127.0.0.1:${server.port}`; + browser = await hook.phase("chrome-launch", () => chromium.launch({ executablePath, headless: true, args: ["--no-sandbox", "--disable-dev-shm-usage"], timeout: 120_000 })); + console.error("[ended-question-browser]", browser.version()); +}, 180_000); + +afterEach(() => { + app?.cancelActiveTurns(); +}); + +afterAll(() => hook.phase("cleanup", async () => { + await browser?.close(); + server?.stop(true); + app?.cancelActiveTurns(); + await app?.close(); + if (scratch) await rm(scratch, { recursive: true, force: true }); +})); + +interface Frames { up: Array<{ type: string; requestId?: string; text?: string }> } + +async function newContext(width: number): Promise<{ context: BrowserContext; frames: Frames }> { + const context = await browser!.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" }); + await context.route("**/*", (route) => (new URL(route.request().url()).origin === origin ? route.continue() : route.abort())); + const frames: Frames = { up: [] }; + await context.routeWebSocket(/\/ws$/, (route) => { + const upstream = route.connectToServer(); + route.onMessage((message) => { + try { + const frame = JSON.parse(String(message)); + frames.up.push({ type: frame.type, requestId: frame.requestId, text: frame.text }); + } catch {} + upstream.send(message); + }); + upstream.onMessage((message) => route.send(message)); + }); + return { context, frames }; +} + +async function openPage(context: BrowserContext, theme: "dark" | "light"): Promise { + const page = await context.newPage(); + await page.goto(origin); + await page.waitForFunction("window.__answers?.connected()"); + for (const css of ["../../ui-kit/dist/styles.css", "../dist/styles.css"]) { + await page.addStyleTag({ content: await Bun.file(resolve(import.meta.dir, css)).text() }); + } + await page.evaluate((t) => { document.documentElement.dataset.theme = t; }, theme); + return page; +} + +/** When the test pressed Send for the latest question's turn (same process clock as the host). */ +let sentAt = 0; + +async function ask(page: Page, kind: Kind): Promise { + const composer = page.locator("textarea.bk-composer"); + await composer.fill(kind); + await page.waitForFunction(() => { + const send = document.querySelector('[role="button"][aria-label="Send"]'); + return send !== null && send.getAttribute("aria-disabled") !== "true" && send.getClientRects().length > 0; + }); + sentAt = Date.now(); + await composer.press("Enter"); + const request = await page.waitForFunction(() => { + const ids = (window as unknown as { __answers: { activeCardRequestIds(): string[] } }).__answers.activeCardRequestIds(); + return ids.length === 1 ? ids[0] : false; + }); + const requestId = await request.jsonValue() as string; + await request.dispose(); + return requestId; +} + +/** Leave a draft on the card, without submitting it. */ +async function draft(page: Page, kind: Kind): Promise { + if (kind === "ask_user") await page.getByRole("radio", { name: /Pylos/ }).click(); + else if (kind === "ask_user_list") await page.getByRole("radio", { name: "Leave, Rope", exact: true }).click(); + else if (kind === "ask_user_rank") { + await page.getByRole("button", { name: /^Timber, position 2 of 2/ }).click(); + await page.getByRole("button", { name: /^Rope, position 1 of 2/ }).click(); + } else await page.getByRole("textbox", { name: "Supply note", exact: true }).fill(NOTE); +} + +/** The draft is still what the card shows. */ +async function draftShown(page: Page, kind: Kind): Promise { + if (kind === "ask_user") return (await page.getByRole("radio", { name: /Pylos/ }).getAttribute("aria-checked")) === "true"; + if (kind === "ask_user_list") return (await page.getByRole("radio", { name: "Leave, Rope", exact: true }).getAttribute("aria-checked")) === "true"; + if (kind === "ask_user_rank") return (await page.getByRole("button", { name: "Submit order", exact: true }).count()) === 1; + return (await page.getByRole("textbox", { name: "Supply note", exact: true }).inputValue()) === NOTE; +} + +const ANSWER_FRAMES = new Set(["ask_user_response", "ask_user_list_response", "ask_user_rank_response", "ask_user_form_response", "ask_answer_status"]); + +describe.skipIf(!executablePath)("a question whose turn timed out, in Chrome", () => { + for (const kind of KINDS) { + const width = kind === "ask_user_list" ? 320 : 390; + const theme = kind === "ask_user_rank" ? "light" : "dark"; + test(`${kind}: the typed answer survives the timeout and leaves only by an explicit Send as message (${width}px, ${theme})`, async () => { + const { context, frames } = await newContext(width); + try { + const page = await openPage(context, theme); + if (kind === "ask_user_form") { + // 200% text: the ended card and its footer still wrap without overflow. + await page.evaluate(() => { document.documentElement.style.fontSize = "200%"; }); + } + const requestId = await ask(page, kind); + await draft(page, kind); + + // The host's limit ends the turn; the conversation says it timed out. + await page.locator('[data-turn-notice="timeout"]').waitFor({ timeout: TURN_TIMEOUT_MS + 15_000 }); + const clock = clocks.get(requestId)!; + // The host arms its limit when it admits the turn, before the backend + // starts: never earlier than the limit after the user's send, and + // less than the limit after the question arrived, so the question + // neither restarted nor extended it. + expect(clock.abortedAt! - sentAt, "TIMEOUT_NOT_EARLY").toBeGreaterThanOrEqual(TURN_TIMEOUT_MS); + expect(clock.abortedAt! - clock.askedAt!, "TIMEOUT_NOT_RESTARTED_BY_QUESTION").toBeLessThan(TURN_TIMEOUT_MS); + expect(await page.locator('[data-turn-notice="timeout"] [aria-live="polite"]').textContent(), "TIMEOUT_ANNOUNCED_ONCE_LIVE").toContain("Turn timed out"); + + // The ended card still holds the draft, and says why it ended. + const ended = page.locator("[data-ask-ended]"); + await ended.waitFor(); + expect(await ended.textContent()).toContain("The turn timed out before you answered"); + expect(await draftShown(page, kind), "ENDED_CARD_KEEPS_DRAFT").toBe(true); + expect(frames.up.filter((f) => ANSWER_FRAMES.has(f.type)), "NOTHING_SENT_TO_ENDED_REQUEST").toEqual([]); + + // Submit on the ended card keeps the answer here, as Not delivered. + const chatBefore = frames.up.filter((f) => f.type === "chat_message").length; + const submit = kind === "ask_user_list" ? page.getByRole("button", { name: "Submit 1", exact: true }) + : kind === "ask_user_rank" ? page.getByRole("button", { name: "Submit order", exact: true }) + : page.getByRole("button", { name: "Submit", exact: true }); + await submit.click(); + const status = page.locator('[data-answer-delivery="closed"]'); + await status.waitFor(); + expect(await status.locator("h4").textContent()).toBe("NOT DELIVERED · QUESTION CLOSED"); + expect(await page.evaluate(() => document.activeElement?.tagName), "FOCUS_ON_OUTCOME").toBe("H4"); + expect(frames.up.filter((f) => ANSWER_FRAMES.has(f.type)), "SUBMIT_ON_ENDED_CARD_SENDS_NOTHING").toEqual([]); + expect(frames.up.filter((f) => f.type === "chat_message").length, "NO_AUTOMATIC_CONTINUATION").toBe(chatBefore); + + // Send as message, from the keyboard: one ordinary new message. + const sendAs = status.getByRole("button", { name: "Send as message", exact: true }); + expect(await sendAs.evaluate((el) => el.getBoundingClientRect().height), "SEND_AS_TOUCH_HEIGHT").toBeGreaterThanOrEqual(44); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "ENDED_CARD_NO_OVERFLOW").toBe(true); + await sendAs.focus(); + await page.keyboard.press("Enter"); + await page.waitForFunction(() => document.body.textContent?.includes("Noted.")); + const sent = frames.up.filter((f) => f.type === "chat_message").slice(chatBefore); + expect(sent, "ONE_NEW_MESSAGE").toHaveLength(1); + for (const part of CARRIES[kind]) expect(sent[0]!.text, "MESSAGE_CARRIES_QUESTION_AND_ANSWER").toContain(part); + expect(prompts.at(-1)!.split("\n", 1)[0], "BACKEND_GOT_ORDINARY_MESSAGE").toBe(sent[0]!.text!.split("\n", 1)[0]); + expect(await status.getByRole("button", { name: "Send as message" }).count(), "SEND_AS_MESSAGE_ONCE").toBe(0); + expect(settlements.get(requestId), "OLD_REQUEST_NEVER_SETTLED").toEqual([]); + expect(frames.up.filter((f) => ANSWER_FRAMES.has(f.type)), "OLD_REQUEST_NEVER_ANSWERED").toEqual([]); + } finally { await context.close(); } + }, TURN_TIMEOUT_MS + 60_000); + } + + test("a reload replays the runtime's stop notice as a status, without a fresh alert or the agent's voice", async () => { + const { context } = await newContext(390); + try { + const page = await openPage(context, "dark"); + await ask(page, "ask_user"); + await page.locator('[data-turn-notice="timeout"]').waitFor({ timeout: TURN_TIMEOUT_MS + 15_000 }); + await page.reload(); + await page.waitForFunction("window.__answers?.connected()"); + const notice = page.locator('[data-turn-notice="unspecified"]'); + await notice.waitFor(); + expect(await notice.textContent()).toContain("Turn ended without a reply"); + expect(await notice.locator('[aria-live="polite"]').textContent(), "REPLAY_DOES_NOT_ANNOUNCE").toBe(""); + expect(await page.locator("body").textContent(), "NOTICE_NOT_AGENT_PROSE").not.toContain("No response requested."); + expect(await page.locator("body").textContent()).toContain("Before we sail:"); + } finally { await context.close(); } + }, TURN_TIMEOUT_MS + 60_000); +}); diff --git a/packages/ui-react/tests/render/ended-question-dom.ts b/packages/ui-react/tests/render/ended-question-dom.ts new file mode 100644 index 0000000000..bd27313f99 --- /dev/null +++ b/packages/ui-react/tests/render/ended-question-dom.ts @@ -0,0 +1,21 @@ +// happy-dom registration for the ended-question render test; a sibling of +// `dom.ts` for the reason `ask-user-dom.ts` states: that module's body runs +// once per process, so each render test file registers its own DOM and +// unregisters it in `afterAll`. Import it FIRST, before any component module. +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { act } from "react"; + +if (!GlobalRegistrator.isRegistered) { + GlobalRegistrator.register(); +} +( + globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } +).IS_REACT_ACT_ENVIRONMENT = true; + +export async function unregisterEndedQuestionDom(): Promise { + if (GlobalRegistrator.isRegistered) { + // Drain React callbacks before removing the globals they still read. + await act(async () => {}); + await GlobalRegistrator.unregister(); + } +} diff --git a/packages/ui-react/tests/render/ended-question.test.tsx b/packages/ui-react/tests/render/ended-question.test.tsx new file mode 100644 index 0000000000..4751510b2c --- /dev/null +++ b/packages/ui-react/tests/render/ended-question.test.tsx @@ -0,0 +1,232 @@ +/** + * A pending question whose turn the host's time limit ended (#3356), live, + * on each of the four ask cards: the frames a real host sends, through the + * real handlers, store and MessageBubble. + * + * Before the fix, the terminal frame turned the card into a dismissed stub: + * the question's draft vanished with its controls, and only a separate + * "Ask again" brought back an empty card. Now the ended card keeps the draft + * and says the turn timed out; its Submit keeps the answer on the card as + * Not delivered and sends nothing; only the footer's explicit Send as + * message sends it, once, as an ordinary new message. The conversation shows + * the timeout as a turn status, announced once. + */ +import { unregisterEndedQuestionDom } from "./ended-question-dom.js"; +import { afterAll, afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { act, cleanup, fireEvent, render as renderDom, within } from "@testing-library/react"; +import type { ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; +import { MessageBubble } from "../../src/components/chat/message-bubble.js"; +import type { ComponentProps } from "react"; +import { createBrainUiRoot, type BrainUiRoot } from "../../src/root.js"; +import { BrainUiProvider, useBrainUiRoot } from "../../src/root-context.js"; +import { useStore } from "zustand"; + +let root: BrainUiRoot; +afterEach(cleanup); +afterEach(() => root.dispose()); +afterAll(unregisterEndedQuestionDom); +beforeEach(() => { + root = createBrainUiRoot({ storage: null }); + root.stores.chat.setState({ buffers: {}, draft: null, pendingDraftId: null, activeSessionId: null, runStates: {}, deliveries: {} }); + root.stores.ui.setState({ singleKeyShortcuts: true }); +}); + +type Kind = "ask_user" | "ask_user_list" | "ask_user_rank" | "ask_user_form"; +const TURN = "turn-ithaca"; +const scoped = { sessionId: "s1", turnId: TURN }; + +const REQUESTS: Record = { + ask_user: { type: "ask_user_request", requestId: "req-1", ...scoped, questions: [{ question: "Which harbour first?", header: "Harbour", multiSelect: false, options: [{ label: "Ithaca", description: "Home" }, { label: "Pylos", description: "Nestor’s court" }] }] } as ServerMessage, + ask_user_list: { type: "ask_user_list_request", requestId: "req-1", ...scoped, prompt: "Which stores are aboard?", scale: [{ label: "Aboard" }, { label: "Missing" }], items: [{ id: "oars", label: "Spare oars" }], allowSkip: false, notes: false } as ServerMessage, + ask_user_rank: { type: "ask_user_rank_request", requestId: "req-1", ...scoped, prompt: "Rank the landings", items: [{ id: "aeolia", label: "Aeolia" }, { id: "scheria", label: "Scheria" }] } as ServerMessage, + ask_user_form: { type: "ask_user_form_request", requestId: "req-1", ...scoped, prompt: "Plan the crossing", nodes: [{ id: "note", kind: "text", prompt: "Note for the crew", required: true }] } as ServerMessage, +}; + +/** The draft the user leaves on each card, and what of it a sent message must carry. */ +const DRAFTS: Record) => void; carries: string[] }> = { + ask_user: { enter: (view) => fireEvent.click(view.getByText("Pylos")), carries: ["Which harbour first?", "Pylos"] }, + ask_user_list: { + enter: (view) => { + const radio = [...view.container.querySelectorAll('[role="radio"]')].find((r) => r.textContent?.includes("Missing")); + fireEvent.click(radio!); + }, + carries: ["Which stores are aboard?", "Spare oars", "Missing"], + }, + ask_user_rank: { + enter: (view) => { + fireEvent.click(view.getByRole("button", { name: /^Scheria, position 2 of 2/ })); + fireEvent.click(view.getByRole("button", { name: /^Aeolia, position 1 of 2/ })); + }, + carries: ["Rank the landings", "1. Scheria", "2. Aeolia"], + }, + ask_user_form: { + enter: (view) => { + const field = view.container.querySelector("[data-form-node] textarea, textarea")!; + fireEvent.input(field, { target: { value: "Bind the oars, Ὀδυσσεύς" } }); + }, + carries: ["Plan the crossing", "Bind the oars, Ὀδυσσεύς"], + }, +}; + +type Handlers = Partial, "message" | "onToolApproval">>; + +function Live({ handlers }: { handlers: Handlers }) { + const r = useBrainUiRoot(); + const message = useStore(r.stores.chat, (s) => s.buffers.s1?.messages.findLast((m) => m.role === "assistant")); + if (!message) return null; + return {}} onAskUserSubmit={() => {}} onAskUserListSubmit={() => {}} onAskUserCancel={() => {}} {...handlers} />; +} + +function start(kind: Kind) { + const calls = { submit: 0, cancel: 0, reask: [] as string[] }; + const handlers = { + onAskUserSubmit: () => { calls.submit++; }, + onAskUserListSubmit: () => { calls.submit++; }, + onAskUserRankSubmit: () => { calls.submit++; }, + onAskUserFormSubmit: () => { calls.submit++; }, + onAskUserCancel: () => { calls.cancel++; }, + onAskUserReask: (text: string) => { calls.reask.push(text); }, + }; + const send = (frame: ServerMessage) => act(() => { root.connection.handleServerMessage(frame); }); + root.stores.chat.getState().setActiveSession("s1"); + send({ type: "session_history", sessionId: "s1", messages: [{ role: "user", content: "Plan the voyage", toolCalls: [] }] } as ServerMessage); + send({ type: "status", status: "thinking", ...scoped } as ServerMessage); + send({ type: "text_delta", text: "Before we sail: ", ...scoped } as ServerMessage); + send(REQUESTS[kind]); + const view = renderDom(); + return { view, calls, send }; +} + +/** What the host sends when its hard turn limit ends the turn. */ +function timeOut(send: (frame: ServerMessage) => void) { + send({ type: "status", status: "cancelled", detail: "Turn timed out", ...scoped } as ServerMessage); + send({ type: "result", outcome: "cancelled", outcomeDetail: "host_timeout", durationMs: 1, numTurns: 1, isError: false, ...scoped } as ServerMessage); +} + +const submitButton = (view: ReturnType) => + view.getAllByRole("button").find((b) => /^(Submit|Keep this order|Submit order)/.test(b.textContent ?? "") || (b.getAttribute("aria-label") ?? "").startsWith("Submit"))!; + +for (const kind of Object.keys(REQUESTS) as Kind[]) { + describe(kind, () => { + test("the ended card keeps the draft; only an explicit Send as message sends it, once", async () => { + const { view, calls, send } = start(kind); + DRAFTS[kind].enter(view); + timeOut(send); + + // The turn says it timed out, as a status after the partial answer. + const notice = view.container.querySelector('[data-turn-notice="timeout"]')!; + expect(notice).not.toBeNull(); + expect(notice.textContent).toContain("Turn timed out"); + expect(view.container.textContent).toContain("Before we sail:"); + expect(notice.querySelector('[aria-live="polite"]')!.textContent).toContain("Turn timed out"); + + // The question is still there, editable, and says it can't be answered. + const card = view.container.querySelector("[data-ask-ended]")!; + expect(card).not.toBeNull(); + expect(card.textContent).toContain("The turn timed out before you answered"); + expect(view.container.querySelector("[data-answer-delivery]")).toBeNull(); + expect(calls).toEqual({ submit: 0, cancel: 0, reask: [] }); + + // Submit keeps the draft on the card as Not delivered; nothing is sent. + fireEvent.click(submitButton(view)); + expect(calls).toEqual({ submit: 0, cancel: 0, reask: [] }); + const status = view.container.querySelector('[data-answer-delivery="closed"]')!; + expect(status).not.toBeNull(); + expect(status.querySelector("h4")!.textContent).toBe("NOT DELIVERED · QUESTION CLOSED"); + expect(status.textContent).toContain("nothing was sent"); + + // Send as message is the one way out: an ordinary message with the + // question and the user's answer, sent once. + const sendAs = within(status as HTMLElement).getByRole("button", { name: "Send as message" }); + fireEvent.click(sendAs); + expect(calls.submit).toBe(0); + expect(calls.reask).toHaveLength(1); + for (const part of DRAFTS[kind].carries) expect(calls.reask[0]).toContain(part); + const after = view.container.querySelector('[data-answer-delivery="closed"]')!; + expect(within(after as HTMLElement).queryByRole("button", { name: "Send as message" })).toBeNull(); + expect(after.querySelector("[data-sent-as-message]")).not.toBeNull(); + expect(document.activeElement).toBe(after.querySelector("h4")); + expect(calls.reask).toHaveLength(1); + expect(root.stores.chat.getState().deliveries["req-1"]).toMatchObject({ state: "closed", reason: "ended", sentAsMessage: true, submissionId: "" }); + }); + + test("Dismiss on an ended card closes it here and sends nothing", () => { + const { view, calls, send } = start(kind); + timeOut(send); + const dismiss = view.getAllByRole("button").find((b) => b.textContent === "Dismiss")!; + fireEvent.click(dismiss); + expect(calls).toEqual({ submit: 0, cancel: 0, reask: [] }); + expect(view.container.querySelector("[data-ask-ended]")).toBeNull(); + expect(view.container.textContent).toContain("no longer waiting · the turn timed out"); + }); + }); +} + +test("a turn that ended without the host naming a timeout says the turn ended, with no timeout notice", () => { + const { view, send } = start("ask_user"); + send({ type: "status", status: "cancelled", ...scoped } as ServerMessage); + send({ type: "result", outcome: "cancelled", durationMs: 1, numTurns: 1, isError: false, ...scoped } as ServerMessage); + expect(view.container.querySelector("[data-turn-notice]")).toBeNull(); + expect(view.container.querySelector("[data-ask-ended]")!.textContent).toContain("The turn ended before you answered"); +}); + +test("a pending question of another turn is untouched by this turn's timeout", () => { + const { view, send } = start("ask_user"); + send({ type: "result", outcome: "cancelled", outcomeDetail: "host_timeout", durationMs: 1, numTurns: 1, isError: false, sessionId: "s1", turnId: "turn-other" } as ServerMessage); + const messages = root.stores.chat.getState().buffers.s1!.messages; + const asking = messages.find((m) => m.askUserExchanges?.some((e) => e.requestId === "req-1"))!; + expect(asking.askUserExchanges![0]).not.toHaveProperty("terminal"); + // The other turn's notice does not relabel this turn's message. + expect(asking.runtimeNotice).toBeUndefined(); + expect(view).toBeDefined(); +}); + +describe("a runtime stop notice on replay", () => { + function replay(messages: unknown[]) { + root.stores.chat.getState().setActiveSession("s1"); + act(() => { root.connection.handleServerMessage({ type: "session_history", sessionId: "s1", messages } as ServerMessage); }); + return renderDom(); + } + + test("draws a status after the partial answer, never the runtime's words as the agent's, and announces nothing", () => { + const view = replay([ + { role: "user", content: "Plan the voyage", toolCalls: [] }, + { role: "assistant", content: "Before we sail: ", toolCalls: [], parts: [{ kind: "text", text: "Before we sail: " }], runtimeNotice: { cause: "unspecified", message: "No response requested." } }, + ]); + const notice = view.container.querySelector('[data-turn-notice="unspecified"]')!; + expect(notice).not.toBeNull(); + expect(notice.textContent).toContain("Turn ended without a reply"); + expect(view.container.textContent).toContain("Before we sail:"); + expect(view.container.textContent).not.toContain("No response requested."); + expect(notice.querySelector('[aria-live="polite"]')!.textContent).toBe(""); + }); + + test("an aborted request says the request was aborted, not who stopped it", () => { + const view = replay([ + { role: "user", content: "Plan the voyage", toolCalls: [] }, + { role: "assistant", content: "", toolCalls: [], parts: [], runtimeNotice: { cause: "aborted", message: "API Error: Request was aborted." } }, + ]); + const notice = view.container.querySelector('[data-turn-notice="aborted"]')!; + expect(notice.textContent).toContain("request was aborted"); + expect(notice.textContent).not.toMatch(/you cancelled|cancelled by/i); + expect(view.container.textContent).not.toContain("API Error"); + }); + + test("a failure on the same message stays the one account of the stop", () => { + const view = replay([ + { role: "user", content: "Plan the voyage", toolCalls: [] }, + { role: "assistant", content: "", toolCalls: [], parts: [], failure: { errorClass: "overloaded", message: "API Error: 529 Overloaded" }, runtimeNotice: { cause: "unspecified", message: "No response requested." } }, + ]); + expect(view.container.querySelector("[data-turn-failure]")).not.toBeNull(); + expect(view.container.querySelector("[data-turn-notice]")).toBeNull(); + }); + + test("the model's own words quoting a notice stay its answer", () => { + const view = replay([ + { role: "user", content: "What does the runtime write?", toolCalls: [] }, + { role: "assistant", content: "It writes No response requested.", toolCalls: [], parts: [{ kind: "text", text: "It writes No response requested." }] }, + ]); + expect(view.container.textContent).toContain("It writes No response requested."); + expect(view.container.querySelector("[data-turn-notice]")).toBeNull(); + }); +}); diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index 4ed3283dad..4c9c8312c9 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -953,6 +953,13 @@ export interface SessionHistoryMessage { * whatever the turn answered before it failed. */ failure?: TurnFailure; + /** + * On an `assistant` message: a notice the agent runtime wrote into the + * transcript itself when a turn stopped, rather than anything the model + * said (additive; #3356). Its text is not repeated in `content`, which + * holds whatever the turn answered before it. + */ + runtimeNotice?: RuntimeNotice; /** Host-held exact original request, present only on an eligible latest failure. */ retryOfTurnId?: string; /** @@ -966,6 +973,18 @@ export interface SessionHistoryMessage { journal?: import("./turn-journal.js").TurnJournalSummary; } +/** + * A runtime-authored notice on a replayed assistant message (additive; + * #3356). `cause` is only what the runtime's own record establishes: + * `aborted` when it recorded an aborted request, otherwise `unspecified`. + * Neither says who stopped the turn or whether earlier tool calls took + * effect. `message` is the runtime's text, as written. + */ +export interface RuntimeNotice { + cause: "aborted" | "unspecified"; + message: string; +} + /** A replayed local exchange's answer, as `SessionHistoryMessage.localAnswer` carries it. */ export interface LocalAnswer { exchangeId: string; @@ -1146,6 +1165,11 @@ export interface ServerResultMessage { * "timeout" for a max-turns/max-budget stop. A new VALUE here never breaks * an old client because the field is free-form and advisory; the precise * taxonomy lives in the server's activity record. + * + * Under `outcome: "cancelled"` (additive; #3356), `"host_timeout"` says the + * host's hard elapsed-time turn limit ended the turn, rather than a cancel + * someone asked for. Absent on a cancelled turn means the host does not say + * why it was cancelled. */ outcomeDetail?: string; /** @@ -1160,6 +1184,12 @@ export interface ServerResultMessage { stateRoom?: StateRoomObservation; } +/** + * `result.outcomeDetail` on an `outcome: "cancelled"` turn that the host's + * hard elapsed-time turn limit ended (additive; #3356). + */ +export const HOST_TIMEOUT_OUTCOME_DETAIL = "host_timeout"; + /** * A provider or API failure that ended a turn (additive; #575), normalised * across backends. It rides the turn's terminal frame — `result`, or the bare diff --git a/packages/ui-sdk/src/schemas.ts b/packages/ui-sdk/src/schemas.ts index ed2032b665..79841e4e4f 100644 --- a/packages/ui-sdk/src/schemas.ts +++ b/packages/ui-sdk/src/schemas.ts @@ -1070,6 +1070,11 @@ export const turnJournalSummarySchema = z.looseObject({ budget: turnBudgetReceiptSchema.optional().catch(undefined), }) satisfies z.ZodType; +const runtimeNoticeSchema = z.looseObject({ + cause: z.enum(["aborted", "unspecified"]), + message: z.string().max(4_000), +}) satisfies z.ZodType; + const historyMessageSchema = z.looseObject({ role: z.enum(["user", "assistant"]), content: z.string(), @@ -1094,6 +1099,7 @@ const historyMessageSchema = z.looseObject({ effectiveThinkingLevel: thinkingLevelSchema.optional().catch(undefined), localAnswer: localAnswerSchema.optional().catch(undefined), failure: turnFailureSchema.optional().catch(undefined), + runtimeNotice: runtimeNoticeSchema.optional().catch(undefined), retryOfTurnId: id.optional().catch(undefined), turnId: id.optional().catch(undefined), journal: turnJournalSummarySchema.optional().catch(undefined), diff --git a/packages/ui-server/src/ws/bridge.ts b/packages/ui-server/src/ws/bridge.ts index 10f2001702..98b126fd07 100644 --- a/packages/ui-server/src/ws/bridge.ts +++ b/packages/ui-server/src/ws/bridge.ts @@ -7,7 +7,7 @@ import { readsIndex, type IndexBatch } from "../brain/index-batch.js"; import { createProviderMaskGuard, ProviderMaskRefusedError, ProviderRecordsRefusedError } from "../brain/provider-mask-refusal.js"; import type { TurnGovernancePolicy } from "../brain/governance-policy.js"; import { GOVERNANCE_POLICY_PATH } from "@schlessera/brain-common/internal/governance-policy"; -import { SHARE_STAGING_DIR } from "@schlessera/brain-ui-sdk/protocol"; +import { HOST_TIMEOUT_OUTCOME_DETAIL, SHARE_STAGING_DIR } from "@schlessera/brain-ui-sdk/protocol"; import type { BackendActivityEvent, BrainApplicationPolicy } from "@schlessera/brain-ui-sdk/server"; import { createHash } from "node:crypto"; import { realpathSync } from "node:fs"; @@ -30,6 +30,9 @@ import type { ApprovalChannel } from "@schlessera/brain-ui-sdk/protocol"; import type { TurnFailure } from "@schlessera/brain-ui-sdk/protocol"; import { approvalRequestFrame, withTurnScope } from "./frames.js"; import type { RunningTurn } from "./turns.js"; + +/** The words a timed-out turn's `status: cancelled` carries in `detail`. */ +const TURN_TIMED_OUT = "Turn timed out"; import { acceptDraft } from "./drafts.js"; import type { WsHost } from "./host.js"; import type { TurnRecorder } from "../activity/recorder.js"; @@ -210,6 +213,13 @@ export async function makeBridge( && !turn.sessionId && msg.type === "error" && !msg.sessionId && !msg.failure && msg.code === "agent_error" && msg.message === "The turn was cancelled before a session was acquired.") msg = { type: "status", status: "cancelled", detail: "Cancelled before starting", requestId }; + // The host's hard turn limit, not someone's cancel, ended this turn: + // its cancelled terminal says so, so the conversation can (#3356). Only + // the timed-out turn's own frames, and never over a real cancel. + if (turn.timedOutTurnId === turnId && turn.turnId === turnId && !turn.cancelled) { + if (msg.type === "status" && msg.status === "cancelled") msg = { ...msg, detail: TURN_TIMED_OUT }; + else if (msg.type === "result" && msg.outcome === "cancelled") msg = { ...msg, outcomeDetail: HOST_TIMEOUT_OUTCOME_DETAIL }; + } if (msg.type === "error" && requestId) msg = { ...msg, requestId }; if (msg.type === "session_info" || (msg.type === "status" && msg.effectiveThinkingLevel !== undefined)) { msg = { ...msg, ...(requestId ? { requestId } : {}), ...(thinkingLevel !== undefined ? { thinkingLevel } : {}) }; diff --git a/packages/ui-server/src/ws/run-session.ts b/packages/ui-server/src/ws/run-session.ts index a9b89b0025..a55a3fe2b7 100644 --- a/packages/ui-server/src/ws/run-session.ts +++ b/packages/ui-server/src/ws/run-session.ts @@ -393,6 +393,7 @@ async function runRetainedSession( // after this timer was armed. attributes: { ...turnLogAttributes(turn), "timeout.ms": host.turnTimeoutMs }, }); + turn.timedOutTurnId = turn.turnId; abortController.abort(); // Reject any pending interactive request for this turn too. A bridge // that awaits askUser/approval without racing the abort signal would diff --git a/packages/ui-server/src/ws/turn-failures.ts b/packages/ui-server/src/ws/turn-failures.ts index e96a76569d..fe1196dcaa 100644 --- a/packages/ui-server/src/ws/turn-failures.ts +++ b/packages/ui-server/src/ws/turn-failures.ts @@ -19,7 +19,11 @@ export function assistantCount(messages: SessionHistoryMessage[]): number { /** Guard against an edited/truncated/rebranched transcript reusing an old position. */ export function updatePrefix(hash: Bun.CryptoHasher, message: SessionHistoryMessage): void { - hash.update(JSON.stringify([message.role, message.content, message.thinking ?? null, + // A runtime notice was replayed as the message's closing text before #3356; + // hashing it there keeps positions recorded before then. + const notice = message.runtimeNotice?.message; + const content = notice ? (message.content ? `${message.content}\n\n${notice}` : notice) : message.content; + hash.update(JSON.stringify([message.role, content, message.thinking ?? null, message.toolCalls, message.attachmentCount ?? 0, message.failure?.message ?? null])); hash.update("\n"); } diff --git a/packages/ui-server/src/ws/turns.ts b/packages/ui-server/src/ws/turns.ts index 26c7773ec0..e62529b381 100644 --- a/packages/ui-server/src/ws/turns.ts +++ b/packages/ui-server/src/ws/turns.ts @@ -246,6 +246,13 @@ export interface RunningTurn { */ handingOver?: QueuedFollowUp; cancelled: boolean; + /** + * The turn the host's hard elapsed-time limit ended (#3356). Set by the + * timeout itself, never inferred from an aborted signal, so a cancel or a + * journal/egress abort is never reported as a timeout. Keyed by turn id + * because a queued follow-up reuses this slot. + */ + timedOutTurnId?: string; /** * Terminal disposition of the CURRENT turn's `result` frame, when one has * streamed. Backends RESOLVE startTurn for runtime failures (the failure diff --git a/packages/ui-server/tests/turn-failure-notice-digest.test.ts b/packages/ui-server/tests/turn-failure-notice-digest.test.ts new file mode 100644 index 0000000000..fbc9f3d2a6 --- /dev/null +++ b/packages/ui-server/tests/turn-failure-notice-digest.test.ts @@ -0,0 +1,30 @@ +/** + * A runtime stop notice (#3356) used to replay as the closing text of its + * assistant message. Failure and turn records keyed by a transcript-prefix + * digest before then must still join, so the digest hashes the notice where + * its text used to be. + */ +import { describe, expect, test } from "bun:test"; +import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; +import { prefixDigest } from "../src/ws/turn-failures"; + +const user: SessionHistoryMessage = { role: "user", content: "Plan the voyage", toolCalls: [] }; + +describe("prefix digests across the runtime notice change", () => { + test("a notice after a partial answer hashes as the text it replaced", () => { + const before: SessionHistoryMessage[] = [user, { role: "assistant", content: "Before we sail: \n\nNo response requested.", toolCalls: [] }]; + const after: SessionHistoryMessage[] = [user, { role: "assistant", content: "Before we sail: ", toolCalls: [], runtimeNotice: { cause: "unspecified", message: "No response requested." } }]; + expect(prefixDigest(after, 1)).toBe(prefixDigest(before, 1)); + }); + + test("a notice-only message hashes as the text it replaced", () => { + const before: SessionHistoryMessage[] = [user, { role: "assistant", content: "API Error: Request was aborted.", toolCalls: [] }]; + const after: SessionHistoryMessage[] = [user, { role: "assistant", content: "", toolCalls: [], runtimeNotice: { cause: "aborted", message: "API Error: Request was aborted." } }]; + expect(prefixDigest(after, 1)).toBe(prefixDigest(before, 1)); + }); + + test("a message without a notice hashes as before", () => { + const messages: SessionHistoryMessage[] = [user, { role: "assistant", content: "Ithaca first.", toolCalls: [] }]; + expect(prefixDigest(messages, 1)).not.toBe(prefixDigest([user, { ...messages[1]!, content: "Ithaca first.\n\nNo response requested." }], 1)); + }); +}); diff --git a/packages/ui-server/tests/ws-ask-turn-timeout.test.ts b/packages/ui-server/tests/ws-ask-turn-timeout.test.ts new file mode 100644 index 0000000000..ba3bf32fb9 --- /dev/null +++ b/packages/ui-server/tests/ws-ask-turn-timeout.test.ts @@ -0,0 +1,221 @@ +/** + * A pending question when the host's hard turn limit runs out (#3356), + * through the real host, coordinator, bridge and dispatch, for all four ask + * kinds. + * + * The limit stays a hard elapsed-time limit that counts the wait for the + * user: a question neither pauses nor restarts it. When it runs out, the + * question is drained, a late answer is closed rather than accepted, and the + * turn's cancelled terminal frames say the host's limit ended it, so the + * conversation can show a timeout rather than an unexplained stop. A cancel + * someone asked for never says so, and an answer that won the race stays the + * accepted one. + */ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { + HOST_TIMEOUT_OUTCOME_DETAIL, + type AskUserFormSpec, + type AskUserListSpec, + type AskUserQuestion, + type AskUserRankSpec, + type ClientMessage, + type ServerMessage, +} from "@schlessera/brain-ui-sdk/protocol"; +import type { AgentBackend, BackendBridge } from "@schlessera/brain-ui-sdk/server"; +import { createWsHandlers } from "../src/ws/connection"; +import { handleClientMessage as dispatch } from "../src/ws/dispatch"; +import type { WSContext } from "../src/ws/clients"; +import { closeDb, resetForTests, setBackendForTests, testHost } from "./helpers/test-host"; +import { testAuthorization, testPrincipal } from "./helpers/principal"; + +type Kind = "ask_user" | "ask_user_list" | "ask_user_rank" | "ask_user_form"; +const KINDS: Kind[] = ["ask_user", "ask_user_list", "ask_user_rank", "ask_user_form"]; + +const QUESTIONS: AskUserQuestion[] = [{ + question: "Which harbour first?", header: "Harbour", multiSelect: false, + options: [{ label: "Ithaca", description: "Home" }, { label: "Pylos", description: "Nestor’s court" }], +}]; +const LIST: AskUserListSpec = { + prompt: "Which stores are aboard?", scale: [{ label: "Aboard" }, { label: "Missing" }], + items: [{ id: "oars", label: "Spare oars" }, { id: "wine", label: "Wine from Maron" }], allowSkip: true, notes: true, +}; +const RANK: AskUserRankSpec = { prompt: "Rank the landings", items: [{ id: "aeolia", label: "Aeolia" }, { id: "scheria", label: "Scheria" }] }; +const FORM: AskUserFormSpec = { + prompt: "Plan the crossing", + nodes: [{ id: "course", kind: "single", prompt: "Which course?", options: [{ label: "Coast" }, { label: "Open sea" }] }], +}; + +function answerFrame(kind: Kind, extra: Record): ClientMessage { + const base = { requestId: "req-1", ...extra }; + switch (kind) { + case "ask_user": return { type: "ask_user_response", ...base, answers: { "Which harbour first?": "Ithaca" } } as ClientMessage; + case "ask_user_list": return { type: "ask_user_list_response", ...base, answers: { oars: "Aboard" } } as ClientMessage; + case "ask_user_rank": return { type: "ask_user_rank_response", ...base, order: ["scheria", "aeolia"], unchanged: false } as ClientMessage; + case "ask_user_form": return { type: "ask_user_form_response", ...base, answers: { course: { value: "Coast" } } } as ClientMessage; + } +} + +function ask(bridge: BackendBridge, kind: Kind): Promise { + switch (kind) { + case "ask_user": return bridge.askUser!("req-1", QUESTIONS); + case "ask_user_list": return bridge.askUserList!("req-1", LIST); + case "ask_user_rank": return bridge.askUserRank!("req-1", RANK); + case "ask_user_form": return bridge.askUserForm!("req-1", FORM); + } +} + +/** + * A backend that waits `askAfterMs`, asks, and ends its turn the way the + * Claude turn runner does: an aborted turn emits `status: cancelled` and a + * cancelled `result`; an answered one waits `answerHoldMs` and succeeds. + */ +function askingBackend(kind: Kind, timing: { askAfterMs: number; answerHoldMs?: number }) { + const settlements: unknown[] = []; + const failures: Error[] = []; + const clock: { startedAt?: number; askedAt?: number; abortedAt?: number } = {}; + const backend: AgentBackend = { + id: "fake", + capabilities: { + resume: true, permissions: true, thinking: true, attachments: true, askUser: true, + costReporting: true, concurrentSessions: true, followUp: false, + }, + listProfiles: () => [{ id: "default", label: "Default" }], + async startTurn({ bridge, signal }) { + clock.startedAt = performance.now(); + signal.addEventListener("abort", () => { clock.abortedAt = performance.now(); }, { once: true }); + bridge.emit({ type: "session_info", sessionId: "s1", isNew: true, providerId: "default" }); + await Bun.sleep(timing.askAfterMs); + clock.askedAt = performance.now(); + try { + settlements.push(await ask(bridge, kind)); + if (timing.answerHoldMs) await new Promise((resolve) => { + const timer = setTimeout(resolve, timing.answerHoldMs); + signal.addEventListener("abort", () => { clearTimeout(timer); resolve(undefined); }, { once: true }); + }); + } catch (error) { + failures.push(error as Error); + } + if (signal.aborted) { + bridge.emit({ type: "status", status: "cancelled" }); + bridge.emit({ type: "result", sessionId: "s1", outcome: "cancelled", durationMs: 1, numTurns: 1, isError: false }); + } else { + bridge.emit({ type: "result", sessionId: "s1", outcome: "success", durationMs: 1, numTurns: 1, isError: false }); + } + }, + async listSessions() { return []; }, + async getHistory() { return []; }, + }; + return { backend, settlements, failures, clock }; +} + +function fakeClient() { + const sent: ServerMessage[] = []; + const ws: WSContext = { send: (data: string) => sent.push(JSON.parse(data) as ServerMessage) }; + return { ws, sent }; +} + +async function waitFor(cond: () => boolean): Promise { + for (let i = 0; i < 600; i++) { + if (cond()) return; + await new Promise((r) => setTimeout(r, 5)); + } + throw new Error("waitFor timed out"); +} + +const asPrincipal = (id: string) => ({ principal: testPrincipal(id), authorization: testAuthorization(id) }); + +async function started(kind: Kind, turnTimeoutMs: number, timing: { askAfterMs: number; answerHoldMs?: number }) { + const fixture = askingBackend(kind, timing); + setBackendForTests(fixture.backend); + const host = testHost(); + // The configured value, as an operator sets it; nothing here changes it later. + host.turnTimeoutMs = turnTimeoutMs; + const c = fakeClient(); + await createWsHandlers(host, testPrincipal()).onOpen({} as Event, c.ws); + await dispatch(host, c.ws, { type: "chat_message", text: "Ask me" }, asPrincipal("test-principal")); + const requestType = kind === "ask_user" ? "ask_user_request" : `${kind}_request`; + await waitFor(() => c.sent.some((f) => f.type === requestType)); + const request = c.sent.find((f) => f.type === requestType) as { turnId: string; sessionId: string }; + const send = async (msg: ClientMessage) => { + const before = c.sent.length; + await dispatch(host, c.ws, msg, asPrincipal("test-principal")); + return c.sent.slice(before); + }; + const terminal = () => c.sent.find((f) => f.type === "result") as Extract | undefined; + return { ...fixture, host, c, request, send, terminal }; +} + +const receipts = (frames: ServerMessage[]) => frames.filter((f) => f.type === "ask_answer_receipt"); +const cancelledStatuses = (frames: ServerMessage[]) => + frames.filter((f): f is Extract => f.type === "status" && f.status === "cancelled"); + +describe("a pending question when the host's turn limit runs out", () => { + beforeEach(() => { resetForTests(); closeDb(); }); + afterEach(() => { resetForTests(); closeDb(); }); + + for (const kind of KINDS) { + describe(kind, () => { + test("expires at the original elapsed deadline, counting the wait, and says the host's limit ended it", async () => { + // The question arrives two thirds of the way in. A limit restarted + // by the question would end the turn no sooner than 300 ms after it. + const TIMEOUT = 300; + const { host, c, request, send, failures, settlements, clock, terminal } = await started(kind, TIMEOUT, { askAfterMs: 200 }); + await waitFor(() => terminal() !== undefined); + const elapsed = clock.abortedAt! - clock.startedAt!; + expect(elapsed).toBeGreaterThanOrEqual(TIMEOUT - 5); + expect(elapsed).toBeLessThan(clock.askedAt! - clock.startedAt! + TIMEOUT); + + // The pending question was drained, not answered. + await waitFor(() => failures.length === 1); + expect(failures[0]!.message).toContain("Turn timed out"); + expect(settlements).toEqual([]); + expect(host.coordinator.pendingAskUser.size + host.coordinator.pendingAskUserList.size + + host.coordinator.pendingAskUserRank.size + host.coordinator.pendingAskUserForm.size).toBe(0); + + // The terminal says so: still cancelled, never a success. + expect(cancelledStatuses(c.sent)).toEqual([expect.objectContaining({ detail: "Turn timed out", turnId: request.turnId })]); + expect(terminal()).toMatchObject({ outcome: "cancelled", outcomeDetail: HOST_TIMEOUT_OUTCOME_DETAIL, isError: false, turnId: request.turnId }); + await waitFor(() => host.coordinator.running.size === 0); + + // A late answer to the ended question is closed, never accepted. + const late = await send(answerFrame(kind, { submissionId: "sub-late", turnId: request.turnId, sessionId: "s1" })); + expect(receipts(late)[0]).toMatchObject({ state: "closed", reason: "ended" }); + expect(host.coordinator.askOutcome("req-1")?.state).not.toBe("accepted"); + expect(settlements).toEqual([]); + }); + }); + } + + test("a cancel someone asked for is not reported as a timeout", async () => { + const { host, c, failures, terminal } = await started("ask_user", 5_000, { askAfterMs: 0 }); + host.coordinator.cancelTurn(host.coordinator.bySession.get("s1")!, "Cancelled by user"); + await waitFor(() => failures.length === 1 && terminal() !== undefined); + expect(terminal()!.outcome).toBe("cancelled"); + expect(terminal()!.outcomeDetail).toBeUndefined(); + expect(cancelledStatuses(c.sent).map((f) => f.detail)).toEqual([undefined]); + }); + + test("a timely answer is receipt-confirmed and the turn completes without a timeout", async () => { + const { request, send, settlements, terminal } = await started("ask_user_list", 5_000, { askAfterMs: 0 }); + const frames = await send(answerFrame("ask_user_list", { submissionId: "sub-a", turnId: request.turnId, sessionId: "s1" })); + expect(receipts(frames)[0]).toMatchObject({ state: "accepted", submissionId: "sub-a" }); + await waitFor(() => terminal() !== undefined); + expect(settlements).toHaveLength(1); + expect(terminal()).toMatchObject({ outcome: "success" }); + expect(terminal()!.outcomeDetail).toBeUndefined(); + }); + + test("an answer that wins the race stays accepted when the limit then ends the turn", async () => { + const { host, request, send, settlements, failures, terminal } = await started("ask_user_rank", 250, { askAfterMs: 0, answerHoldMs: 5_000 }); + const frames = await send(answerFrame("ask_user_rank", { submissionId: "sub-a", turnId: request.turnId, sessionId: "s1" })); + expect(receipts(frames)[0]).toMatchObject({ state: "accepted" }); + await waitFor(() => terminal() !== undefined); + expect(terminal()).toMatchObject({ outcome: "cancelled", outcomeDetail: HOST_TIMEOUT_OUTCOME_DETAIL }); + // Only the winning outcome settled: the answer, once, and no drain of it. + expect(settlements).toHaveLength(1); + expect(failures).toEqual([]); + expect(host.coordinator.askOutcome("req-1")).toMatchObject({ state: "accepted", submissionId: "sub-a" }); + const repeat = await send(answerFrame("ask_user_rank", { submissionId: "sub-a", turnId: request.turnId, sessionId: "s1" })); + expect(receipts(repeat)[0]).toMatchObject({ state: "accepted", submissionId: "sub-a" }); + }); +}); From 6b8738aac68186119482c81e0545ee197f48fae6 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 13:47:31 +0000 Subject: [PATCH 2/4] docs: move code citations that #3356 shifted Co-Authored-By: Claude Opus 5.5 --- docs/decisions/async-collaboration.md | 2 +- docs/decisions/design-kit/follow-ups.md | 2 +- .../design-kit/sessions-and-drafts.md | 2 +- docs/decisions/governed-writable-workers.md | 6 +++--- docs/decisions/live-conversation.md | 2 +- docs/decisions/managed-worktrees.md | 4 ++-- docs/decisions/session-handoff.md | 2 +- docs/decisions/session-principals.md | 6 +++--- docs/decisions/voice-permission.md | 12 ++++++------ .../live-conversation-investigation.md | 2 +- docs/plans/async-collaboration-requirements.md | 10 +++++----- docs/plans/async-collaboration.md | 18 +++++++++--------- docs/plans/chat-history-deletion.md | 4 ++-- docs/plans/navigation-recovery.md | 14 +++++++------- docs/plans/voice-conversation.md | 6 +++--- docs/process/test-waits.md | 2 +- docs/process/theme-parity.md | 2 +- 17 files changed, 48 insertions(+), 48 deletions(-) diff --git a/docs/decisions/async-collaboration.md b/docs/decisions/async-collaboration.md index d6b60a7a30..e1640d1770 100644 --- a/docs/decisions/async-collaboration.md +++ b/docs/decisions/async-collaboration.md @@ -204,7 +204,7 @@ permission and unwinds the turn. Already completed side effects are not undone by an abort. Attempt staging and cleanup therefore need idempotent recovery, with filesystem compensation outside SQLite transactions. Ordinary permission parking still exists (`requestPermission: (req) => {`, -`packages/ui-server/src/ws/bridge.ts:362-455`); it is not a durable Action store. +`packages/ui-server/src/ws/bridge.ts:372-465`); it is not a durable Action store. Resolution validates the stored effect again, checks current authority, records one resolution and applies the guarded state transition in one transaction. diff --git a/docs/decisions/design-kit/follow-ups.md b/docs/decisions/design-kit/follow-ups.md index 075490ca5e..c22ee11125 100644 --- a/docs/decisions/design-kit/follow-ups.md +++ b/docs/decisions/design-kit/follow-ups.md @@ -45,7 +45,7 @@ does a replayed session show? last call that parses is lifted to the answer's closing row, after the text and the share menu. At its call position `groupParts` draws nothing (`payload?.block.kind === "suggestions"`, - `packages/ui-react/src/components/chat/message-bubble.tsx:292`), and shares + `packages/ui-react/src/components/chat/message-bubble.tsx:293`), and shares and prints leave it out. This also amends D37 §8's "chips while live, `FeedbackRow` later": #41 closed as not planned, so the closing row is suggestions or nothing. diff --git a/docs/decisions/design-kit/sessions-and-drafts.md b/docs/decisions/design-kit/sessions-and-drafts.md index 3e97e028b5..6275d46e23 100644 --- a/docs/decisions/design-kit/sessions-and-drafts.md +++ b/docs/decisions/design-kit/sessions-and-drafts.md @@ -341,7 +341,7 @@ event deletes the whole set. Draft content never enters this record (§5). null, no time is printed. - **`lastActiveAt` and `lastTouched` are never read.** A newer `lastActiveAt` can mean that a new turn started - (`export interface ChatSession`, `packages/ui-sdk/src/protocol.ts:1580-1610`), + (`export interface ChatSession`, `packages/ui-sdk/src/protocol.ts:1610-1640`), and `lastTouched` is LRU bookkeeping for buffer eviction. **Merging snapshots and live frames.** diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 1e338b8702..db6a1d9950 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -176,7 +176,7 @@ still holds. **Voice.** Ruling 1 makes voice `governed` too. Voice keeps its narrower membership (`VOICE_ALLOWED_TOOLS`, `packages/ui-backend-claude/src/tool-policy.ts:120`): no Bash, no raw `Write`/`Edit`, no archive, and approval returns false -(`const apply = createBrainApplication`, `packages/ui-server/src/ws/bridge.ts:666-671`). +(`const apply = createBrainApplication`, `packages/ui-server/src/ws/bridge.ts:676-681`). A voice turn therefore writes only through curated capture and update, now with a journal behind it. The writable mount gives voice no tool it lacked. Pi still refuses voice turns. @@ -1407,7 +1407,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.ts:226`). +(`void host.journal?.toolEnded`, `packages/ui-server/src/ws/bridge.ts:236`). 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:232-253`), @@ -1522,7 +1522,7 @@ unmet rather than relaxed. **Why.** Every governed turn queues an automatic index refresh after it (`host.governedTurns?.refresh(host.workerLock)`, -`packages/ui-server/src/ws/run-session.ts:934`). The refresh usually finishes +`packages/ui-server/src/ws/run-session.ts:935`). The refresh usually finishes while the next turn runs, so that turn's finish observation found a rewritten `brain.db` and copied a whole new version of it into retained objects, inside the observation's worker hold. #2831 measured 36 versions of a ~120 MB index in diff --git a/docs/decisions/live-conversation.md b/docs/decisions/live-conversation.md index 4e489d0125..f5aa93a55a 100644 --- a/docs/decisions/live-conversation.md +++ b/docs/decisions/live-conversation.md @@ -40,7 +40,7 @@ posture. A speech provider cannot reinterpret a visual grant, widen an allowlist, or settle an approval because it generated an answer. The host resolves pending exchanges when a turn ends -(`drainPendingForTurn`, `packages/ui-server/src/ws/turns.ts:704-738`). The +(`drainPendingForTurn`, `packages/ui-server/src/ws/turns.ts:711-745`). The conversation integration must also reconcile client cards and audible claims; that server method is not proof of a client receipt. Completion requires host terminal state plus local playback drained or discarded. Provider generation diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 3194de6862..50049fdd26 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -97,7 +97,7 @@ unknown; what happens next is in [hygiene and cleanup](#hygiene-and-cleanup). Each governed or strict turn whose journal is recording opens one worker generation, and every worker of that turn binds the generation's root-owned directory whole at `/tmp/brain-worktrees`, inside the turn's own `/tmp` -(`// Managed worktrees (#2430): a journaled turn's workers bind one empty generation.`, `packages/ui-server/src/ws/run-session.ts:570-582`; +(`// Managed worktrees (#2430): a journaled turn's workers bind one empty generation.`, `packages/ui-server/src/ws/run-session.ts:571-583`; `// Managed worktrees (#2430): the whole access generation`, `packages/ui-sdk/src/server/worker-launcher.ts:852-863`). A granted worktree appears there as `/tmp/brain-worktrees//` on the worker's next path lookup; the worker cannot create entries beside it, and a @@ -199,7 +199,7 @@ The host side is `createReferenceTools` start, the host records its principal and what those workers bind: the public view, the principal's private view and the turn's worker generation, if one opened -(`// Reference tools (#2432): the turn's workers bind the principal's source`, `packages/ui-server/src/ws/run-session.ts:583-589`). +(`// Reference tools (#2432): the turn's workers bind the principal's source`, `packages/ui-server/src/ws/run-session.ts:584-590`). A call carries only a repository, a revision or a worktree identity. The bridge adds the turn's own principal, and a call for a turn the host did not prepare, or under another principal, refuses diff --git a/docs/decisions/session-handoff.md b/docs/decisions/session-handoff.md index 43a0433eda..02a055f27c 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 (`if (msg.type === "result") {`, -`packages/ui-server/src/ws/bridge.ts:282-292`). +`packages/ui-server/src/ws/bridge.ts:292-302`). ### Historical state directories remain untouched diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index bf3df5549f..2bd4ba0d6b 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -102,7 +102,7 @@ Both reviewers verified every row below against the source. | WS upgrade | `ws/connection.ts:262-264` | `createWsUpgrade` ignores the request context | | WS admission | `ws/connection.ts:84` | `clients.add(ws)` — the socket's identity is unknown | | Turn record | `ws/run-session.ts:136-144` | recorder built from `{turnId, sessionId, billing}`; `RunningTurn` (`ws/turns.ts:55-77`) has no actor | -| Follow-up queue | `QueuedFollowUp`, `ws/turns.ts:61-103`; `slot.queue.push(entry)`, `run-session.ts:1125` | queued entries re-mint `turnId` in the same slot and may come from another socket | +| Follow-up queue | `QueuedFollowUp`, `ws/turns.ts:61-103`; `slot.queue.push(entry)`, `run-session.ts:1126` | queued entries re-mint `turnId` in the same slot and may come from another socket | | Password login | `acquirePasswordVerification(key)`, `auth.ts:739` | argon2id verify, failure counting, in-flight reservation, then `issueSessionCookie` | | Passkey login | `issueLoginSession`, `packages/ui-server/src/middleware/passkeys.ts:441` | assertion verified, then `issueSessionCookie`; `row.id` is in scope | | Passkey **registration** | `INSERT INTO passkey_credentials`, `packages/ui-server/src/db/account-writes.ts:31-36` | inserts a credential; calls **neither** helper | @@ -179,12 +179,12 @@ ceremony in flight can mint a session for a credential deleted meanwhile. revocation: `onMessage` dispatches without re-checking (`ws/connection.ts:173`), turn startup awaits routing and billing before `startTurn` (`resolveTurnTarget`, `ws/run-session.ts:215`; `const billing = await resolveRunBilling`, -`ws/run-session.ts:411`), and queued follow-ups execute later. Each connection holds a +`ws/run-session.ts:412`), and queued follow-ups execute later. Each connection holds a server-resolved authorization context; revocation marks it invalid synchronously, refuses later frames, drops that principal's queued unstarted follow-ups, and leaves running work running (cancelling a slot would take other principals' queued work with it — `drop its queued follow-ups`, -`ws/turns.ts:670`). The revocation itself is recorded in the activity record. +`ws/turns.ts:677`). The revocation itself is recorded in the activity record. > **2026-09-30 — Implementation context (decision 5's missing re-check).** The > [old dispatch](https://github.com/schlessera/brain-kit/blob/ea2c3d840920a4e73adc650566a6cfc110e9646e/packages/ui-server/src/ws/connection.ts#L162-L220) diff --git a/docs/decisions/voice-permission.md b/docs/decisions/voice-permission.md index 98f58d7964..02631394cb 100644 --- a/docs/decisions/voice-permission.md +++ b/docs/decisions/voice-permission.md @@ -398,8 +398,8 @@ budget. That is already fail-closed: nothing runs. The user hears nothing further, because a model that nags about a request the user ignored is worse than one that lets the turn lapse. When the budget expires the host drains every pending approval for that turn as a denial and deletes it -(`coordinator.drainPendingForTurn`, `packages/ui-server/src/ws/run-session.ts:401` → -`drainPendingForTurn`, `packages/ui-server/src/ws/turns.ts:704-738`), +(`coordinator.drainPendingForTurn`, `packages/ui-server/src/ws/run-session.ts:402` → +`drainPendingForTurn`, `packages/ui-server/src/ws/turns.ts:711-745`), so **on the server nothing is left waiting**: the request is resolved, not parked. The model therefore says that it stopped and that the thing has to be asked for again, never that it is @@ -411,7 +411,7 @@ those two citations and is left to #54. The chat store clears a pending approval on `tool_result` (`packages/ui-react/src/hooks/websocket-handlers/chat.ts`), and on the timeout path `abortController.abort()` fires before the drain -(`abortController.abort()`, `run-session.ts:396`; `drainPendingForTurn`, `run-session.ts:401`), +(`abortController.abort()`, `run-session.ts:397`; `drainPendingForTurn`, `run-session.ts:402`), so whether a `tool_result` still streams for that tool use is a question a live turn has to answer. It matters only for the wording: if a dead card can survive on screen, the spoken line above is right @@ -436,7 +436,7 @@ A microphone is a reflex surface with worse recognition than a keyboard. This costs nothing measurable: the server already refuses `always` for kind `command` requests (the block computing `remembers`, `dispatch.ts:450-456`, and the lookup computing -`remembered`, `ws/bridge.ts:372-392`), and 192 of 192 measured +`remembered`, `ws/bridge.ts:382-402`), and 192 of 192 measured approvals were kind `command`. ### When the announcement actually fires @@ -493,7 +493,7 @@ the request kind, and it patches the span (`onApprovalDecision`, `packages/ui-server/src/activity/recorder.ts:684-699`), fed from the bridge's `recorded()` wrapper -(`const recorded`, `packages/ui-server/src/ws/bridge.ts:414-429`). +(`const recorded`, `packages/ui-server/src/ws/bridge.ts:424-439`). One thing is missing and is a follow-up: **the event does not record the modality.** A denial decided by a phrase a microphone heard and one decided by a @@ -638,7 +638,7 @@ matters because a reader cannot otherwise tell a live hazard from a fixed one. purpose, so a grant that exists and is deliberately not applied can be logged — but refuses to answer from it or add to it for a tool the enforced allowlist left out (the lookup computing `remembered`, - `packages/ui-server/src/ws/bridge.ts:372-392`, + `packages/ui-server/src/ws/bridge.ts:382-402`, and the block computing `remembers`, `packages/ui-server/src/ws/dispatch.ts:450-456`). The evaluation happens diff --git a/docs/investigations/live-conversation-investigation.md b/docs/investigations/live-conversation-investigation.md index 77203e94f5..647b8d4418 100644 --- a/docs/investigations/live-conversation-investigation.md +++ b/docs/investigations/live-conversation-investigation.md @@ -312,7 +312,7 @@ is unknown, not queued against a replacement request. Terminal state invalidates every pending exchange for that turn without waiting for `tool_result`. Current client terminal handling finishes the assistant message and resyncs; its message-state helper only marks streaming false -(`finishAssistantMessage`, `packages/ui-react/src/stores/chat-state.ts:1835-1840`). +(`finishAssistantMessage`, `packages/ui-react/src/stores/chat-state.ts:1869-1874`). This observation is a required integration check, not proof that all cards currently clear. A host terminal event plus local audio drain/discard defines conversation completion; provider turn/audio end does not. diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index 9e5b2ca448..bbc25fc32e 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -43,7 +43,7 @@ session. Three consequences: 1. **Background work cannot ask.** Cron runs (`sync`, `validate`, `maintain`, module jobs) have no human attached. `bridge.requestPermission` parks a promise that nobody will - resolve (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge.ts:362-456`), so autonomous work is confined to + resolve (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge.ts:372-466`), so autonomous work is confined to whatever is pre-approved, and anything requiring judgment is not attempted. 2. **Inbound material has no path.** A forwarded email, a shared link, a captured note has nowhere to land that the agent will act on later. The PWA share target stages into @@ -256,17 +256,17 @@ Stated before the requirements because five of them derive from it. (`export function createTurnRecorder(`, `packages/ui-server/src/activity/recorder.ts:126-204`). - R25. **Autonomous work gets its own pool** (`MAX_AUTONOMOUS_RUNS`, default 2) — but a second counter alone does not deliver "interactive always wins". The host cap applies only when - starting WS sessions (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:1336-1348`), and an autonomous + starting WS sessions (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:1337-1349`), and an autonomous turn can hold a path write lock while an interactive turn waits or is denied at 30 seconds (`export function createTurnLockBinding(`, `packages/ui-backend-claude/src/turn-lock.ts:27-119`). Required: an admission controller with reserved interactive capacity and hybrid yield at an explicit denial-risk threshold (~20s of the 30s lock budget). Below it nothing yields; above it the holder checkpoints/unwinds/releases. Test both edges and independent paths. - R26. **Abort-and-redo needs a checkpoint primitive.** `requestPermission` parks a bare - promise (`return new Promise((resolve) => {`, `packages/ui-server/src/ws/bridge.ts:406-464`) — while blocked on it the model cannot write anything, so + promise (`return new Promise((resolve) => {`, `packages/ui-server/src/ws/bridge.ts:416-474`) — while blocked on it the model cannot write anything, so "writes its findings, then aborts" has nowhere to run. The autonomous bridge must, in one server-side step: capture the checkpoint, create the Action and block the item, unwind without a live approval promise, preserving the tested timeout - path's abort-then-drain order (`abortController.abort();`, `packages/ui-server/src/ws/run-session.ts:396-402`). Aborting does **not** undo completed tool side + path's abort-then-drain order (`abortController.abort();`, `packages/ui-server/src/ws/run-session.ts:397-403`). Aborting does **not** undo completed tool side effects, so every attempt gets an isolated staging directory with idempotent cleanup. This does not reopen the abort-and-redo decision; it corrects revision 1's claim that the decision needed no new machinery. @@ -336,7 +336,7 @@ Stated before the requirements because five of them derive from it. item makes no model call **and creates no Activity run** · T1 batch classification · T2 full agent run · T3 the user. - R39. **T1 batches are bounded by tokens and bytes, not count.** One share's text may carry ~200 KB - (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2469`), so "up to 20 items" is ~4 MB before overhead. + (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2499`), so "up to 20 items" is ~4 MB before overhead. Per-item truncation, a batch token budget, and independent structured outputs per item. - R40. **Every model-bearing operation is billed, recorded, classified, and counted**: T1 batches, T2 runs, retries, redo re-derivation, state compaction, premise revalidation, diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 8c01113cc0..4856b4ee74 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -28,7 +28,7 @@ than last. ## Problem Frame Collaboration is synchronous-only: background work cannot ask (`requestPermission` parks a -promise nobody resolves — (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge.ts:362-456`)), inbound material +promise nobody resolves — (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge.ts:372-466`)), inbound material has no path that survives until the user is present, and no decision accumulates into standing authority. See origin for the full frame. @@ -134,8 +134,8 @@ system gate. It is not a prerequisite to rebuild or a new independent package. - **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:907`) follows public routes; (`export function authGuard(`, `packages/ui-server/src/middleware/auth.ts:184-244`) binds principals in each auth mode. An internal poke needs independent token authorization before this guard. -- **Permission parking:** (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge.ts:362-456`). Timeout unwind is - (`abortController.abort();`, `packages/ui-server/src/ws/run-session.ts:396-402`). Durable escalation must checkpoint +- **Permission parking:** (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge.ts:372-466`). Timeout unwind is + (`abortController.abort();`, `packages/ui-server/src/ws/run-session.ts:397-403`). Durable escalation must checkpoint before unwinding; the existing ordinary bridge does not do that. - **Tool enforcement:** (`const enforcementHook: HookCallback`, `packages/ui-backend-claude/src/permission-hooks.ts:200-229`) closes measured bypasses. (`export const DEFAULT_ALLOWED_TOOLS = [`, `packages/ui-backend-claude/src/tool-policy.ts:27-80`) is still a broad interactive @@ -154,9 +154,9 @@ system gate. It is not a prerequisite to rebuild or a new independent package. (`async deliverPending(notifier) {`, `packages/ui-server/src/activity/push-sender.ts:218-286`) are run-bound and do not maintain an Actions aggregate count. - **Share provenance/limits:** (`const result = await stageShareAt(`, `packages/ui-server/src/inbox/intake.ts:101`) assigns the source in server code. - (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2469`) bounds text, not binary uploads; + (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2499`) bounds text, not binary uploads; extracted T1 context needs its own byte/token bound. -- **Interactive locks:** (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:1336-1348`) gates WS starts; +- **Interactive locks:** (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:1337-1349`) gates WS starts; (`export function createTurnLockBinding(`, `packages/ui-backend-claude/src/turn-lock.ts:27-119`) owns tool locks. Shared-target priority and cooperative yield belong to the keyed lock and backend lifecycle. @@ -807,7 +807,7 @@ recovered tick after killing the interval - T1: one batched classification call producing **independent structured output per item**, so one malformed item does not poison the batch - Batching bounded by a **token/byte budget**, not a count, with per-item truncation — a single - share may carry ~200 KB (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2469`). Budget: **40k input tokens per + share may carry ~200 KB (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2499`). Budget: **40k input tokens per batch, 4k per item** - **Batch completeness is verified, and missing items are re-submitted individually.** Every submitted item id must come back; any that does not is retried alone, then escalated if it @@ -884,7 +884,7 @@ AE3, AE4, AE8 **Approach:** - **Escalation** is one server-side step: capture the checkpoint → create the Action with validated effects → transition the Queue item to `blocked` → unwind without parking. The timeout path aborts then drains permissions at - `abortController.abort()`, (`abortController.abort();`, `packages/ui-server/src/ws/run-session.ts:396-402`) + `abortController.abort()`, (`abortController.abort();`, `packages/ui-server/src/ws/run-session.ts:397-403`) - **Resolution** is one transaction: record resolution (unique) → validate the effect against its schema again → apply it → transition the blocked item to `superseded` → for `enqueue` only, mint one follow-up with `dedup_key` from `(action_id, option_id)` @@ -1274,7 +1274,7 @@ full-v1 enablement; predicates and schema tests cannot substitute for it. **Approach:** **hybrid — reserve capacity normally, yield only at denial risk.** `MAX_AUTONOMOUS_RUNS` (default 2) is necessary but not sufficient: the host cap applies only at -WS session start (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:1336-1348`) and an autonomous turn can hold a path write lock +WS session start (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:1337-1349`) and an autonomous turn can hold a path write lock while an interactive turn waits or is denied at 30s (`export function createTurnLockBinding(`, `packages/ui-backend-claude/src/turn-lock.ts:27-119`). @@ -1285,7 +1285,7 @@ The hybrid has three pieces: waiter's continued wait signals the holder. The number is a constant, not a judgement call, so both edges are testable - **A yield channel into a running autonomous turn** — the signal aborts the holder through - the same unwind order as the timeout path (`abortController.abort();`, `packages/ui-server/src/ws/run-session.ts:396-402`), returning its item + the same unwind order as the timeout path (`abortController.abort();`, `packages/ui-server/src/ws/run-session.ts:397-403`), returning its item to `ready` and releasing its reservation Below the threshold nothing yields, so the common case costs nothing. Above it, one autonomous diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index d28d886b2c..7ff1954735 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -130,7 +130,7 @@ must be tested through their installed runtime, not inferred from directory name - **Native Claude history.** Live JSONL, per-session subordinate files, titles, archive manifests/index/staged or conflict copies can contain readable text. History reads can restore archived files before reading the SDK transcript - (`createHistory`, `packages/ui-backend-claude/src/history.ts:44-102`; + (`createHistory`, `packages/ui-backend-claude/src/history.ts:45-103`; `restoreArchivedSession`, `packages/ui-backend-claude/src/transcript-archive.ts:157-185`). The live/archive roots are resolved by the backend (`transcriptPaths`, `packages/ui-backend-claude/src/transcript-archive.ts:31-40`). @@ -254,7 +254,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:63-89`), +`FailureReplay` (`FailureReplay`, `packages/ui-server/src/ws/turn-failures.ts:67-93`), 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`, diff --git a/docs/plans/navigation-recovery.md b/docs/plans/navigation-recovery.md index 52dca629c1..e61af0b024 100644 --- a/docs/plans/navigation-recovery.md +++ b/docs/plans/navigation-recovery.md @@ -365,11 +365,11 @@ implementation. Any PR moving these lines owns their citation repairs. - New chat: (`{hasMessages && !wide && (`, `packages/ui-react/src/components/chat/chat-page.tsx:702-709`). -- Buffer eviction: (`function evictStale(`, `packages/ui-react/src/stores/chat-state.ts:1086-1102`). +- Buffer eviction: (`function evictStale(`, `packages/ui-react/src/stores/chat-state.ts:1116-1132`). - Root namespace: (`const prefix = options.storagePrefix ??`, `packages/ui-react/src/root.ts:182-237`). -- Clear transcript selection: (`clearMessages: () => {`, `packages/ui-react/src/stores/chat-state.ts:2139-2148`). +- Clear transcript selection: (`clearMessages: () => {`, `packages/ui-react/src/stores/chat-state.ts:2202-2211`). - Composer draft/acknowledgement: [`const [input, setInput] = useState("");`](https://github.com/schlessera/brain-kit/blob/7bfdc71074f4ff6243e0d7133e83dbb36eb2a971/packages/ui-react/src/components/chat/composer.tsx#L62-L85), before #951 moved the draft into the root's draft store (`stores/draft-state.ts`). @@ -379,7 +379,7 @@ implementation. Any PR moving these lines owns their citation repairs. - Demux: (`const frameSessionId = (msg as { sessionId?: string }).sessionId;`, `packages/ui-react/src/connection.ts:500-574`). -- History replay: (`session_history: (msg, context) => {`, `packages/ui-react/src/hooks/websocket-handlers/chat.ts:437-448`). +- History replay: (`session_history: (msg, context) => {`, `packages/ui-react/src/hooks/websocket-handlers/chat.ts:444-455`). - Single background drawer row: [`const backgroundSessionId =`](https://github.com/schlessera/brain-kit/blob/ea8506b0eb511a3e16dba685d250d34e5340afa4/packages/ui-react/src/components/chat/session-drawer.tsx#L59-L60), before #950 replaced it with the Working group. @@ -389,19 +389,19 @@ implementation. Any PR moving these lines owns their citation repairs. - Catalog activity: (`persistSessionStub(sessionId, promptText, providerId, backendId) {`, `packages/ui-server/src/ws/session-catalog.ts:486-493`). -- Session summary shape: (`export interface ChatSession {`, `packages/ui-sdk/src/protocol.ts:1580-1596`). +- Session summary shape: (`export interface ChatSession {`, `packages/ui-sdk/src/protocol.ts:1610-1626`). - Run identity: (`const runId = turn.turnId;`, `packages/ui-server/src/activity/recorder.ts:155-156`). -- Outcome vocabulary: (`export type ActivitySpanOutcome =`, `packages/ui-sdk/src/protocol.ts:3051-3074`). +- Outcome vocabulary: (`export type ActivitySpanOutcome =`, `packages/ui-sdk/src/protocol.ts:3081-3104`). - Activity resolution: (`.get("/activity/runs", (c) => {`, `packages/ui-server/src/routes/activity.ts:145-283`). - API authorization: (`app.use("/api/*", authGuard(authMode, auth, db));`, `packages/ui-server/src/app.ts:907`). -- Queued acceptance: (`// Queue it as the session's next turn; report queued immediately.`, `packages/ui-server/src/ws/run-session.ts:1102-1147`). +- Queued acceptance: (`// Queue it as the session's next turn; report queued immediately.`, `packages/ui-server/src/ws/run-session.ts:1103-1148`). -- Approval target: (`function mutateLastAssistant(`, `packages/ui-react/src/stores/chat-state.ts:1233-1263`). +- Approval target: (`function mutateLastAssistant(`, `packages/ui-react/src/stores/chat-state.ts:1263-1293`). ## Bounded follow-up ownership diff --git a/docs/plans/voice-conversation.md b/docs/plans/voice-conversation.md index 9cc55f574b..e735065ea7 100644 --- a/docs/plans/voice-conversation.md +++ b/docs/plans/voice-conversation.md @@ -207,7 +207,7 @@ existing pronunciation overrides only as disclosed text correction, retaining the distinction between recognized words and submitted text. The present `AsrEvent` carries partial/final text and `endsTurn`, not confidence, overlap evidence or an output transcript (`AsrEvent`, -`packages/ui-sdk/src/protocol.ts:1857`). #317 must resolve those gaps rather +`packages/ui-sdk/src/protocol.ts:1887`). #317 must resolve those gaps rather than pretending that dictation supplies them. Assistant text remains the generated answer; playback progress is a separate @@ -377,10 +377,10 @@ once, using the host outcome as truth. Silence produces no reminder. At expiry the server denies and removes pending requests (`drainPendingForTurn`, -`packages/ui-server/src/ws/turns.ts:704-738`). Clear the correlated card's +`packages/ui-server/src/ws/turns.ts:711-745`). Clear the correlated card's actionable state on the host terminal outcome even if no `tool_result` arrives; the current terminal-frame contract is (`ServerResultMessage`, -`packages/ui-sdk/src/protocol.ts:1119-1129`). Keep the existing card/receipt in +`packages/ui-sdk/src/protocol.ts:1138-1148`). Keep the existing card/receipt in the transcript with "Expired · denied" and no live approval controls. Speak once: "I stopped without doing it. Ask me again when you can look at a screen." Cancellation similarly resolves only the requests of the cancelled turn. diff --git a/docs/process/test-waits.md b/docs/process/test-waits.md index f2d6159c34..fd6a467064 100644 --- a/docs/process/test-waits.md +++ b/docs/process/test-waits.md @@ -169,7 +169,7 @@ case observes that later effect through its retained native window. The history and queue receiving observer is only a barrier for the current synchronous production handlers, not a generic asynchronous-handler completion claim: `session_history` and scoped `status` update the chat store synchronously -(`session_history`, `packages/ui-react/src/hooks/websocket-handlers/chat.ts:437-457`; +(`session_history`, `packages/ui-react/src/hooks/websocket-handlers/chat.ts:444-464`; `status`, `packages/ui-react/src/hooks/websocket-handlers/chat.ts:458-483`), while queue adoption updates the follow-up/draft stores synchronously (`if (msg.type === "session_queue")`, `packages/ui-react/src/connection.ts:412-424`). Native protocol diff --git a/docs/process/theme-parity.md b/docs/process/theme-parity.md index 9a512be335..d6595ff0ca 100644 --- a/docs/process/theme-parity.md +++ b/docs/process/theme-parity.md @@ -218,7 +218,7 @@ The suffix geometry checks compare the recovered drawing to that case's own baseline; they do not assert an absolute theme-specific message size. Both responsive branches still execute with the actual consumer stylesheet. The user path in (`MessageBubble`, -`packages/ui-react/src/components/chat/message-bubble.tsx:65-172`) uses +`packages/ui-react/src/components/chat/message-bubble.tsx:66-173`) uses (`UserTurn`, `packages/ui-react/src/components/chat/transcript-turn.tsx:61-69`) and the kit's user bubble. Its consumer padding, text wrapping and header layout do not branch on theme; the consumer `.chat-message-body` rule likewise From 045912f5d85dd5660f2d88f9869e35fb38b1807e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 13:53:42 +0000 Subject: [PATCH 3/4] chore: name the Claude backend package correctly in the #3356 changeset Co-Authored-By: Claude Opus 5.5 --- .changeset/ended-question-recovery.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/ended-question-recovery.md b/.changeset/ended-question-recovery.md index bcf720e9f1..e561faf430 100644 --- a/.changeset/ended-question-recovery.md +++ b/.changeset/ended-question-recovery.md @@ -1,7 +1,7 @@ --- "@schlessera/brain-ui-sdk": minor "@schlessera/brain-ui-server": minor -"@schlessera/brain-ui-backend-claude": minor +"@schlessera/brain-backend-claude": minor "@schlessera/brain-ui-react": minor --- A question whose turn ends before it is answered no longer loses what the user had entered, and a turn that hits the host's time limit now says so (#3356). The ended card keeps its draft and says the turn ended or timed out. Its Submit sends nothing to the ended request; it keeps the answer on the card as Not delivered. Send as message is the only way to send it, as one ordinary new chat message carrying the question and the answer, and it is offered once. The host's turn limit is unchanged: it is still a hard elapsed-time limit, and the time a question waits for the user counts against it. When it ends a turn, the cancelled `result` now carries `outcomeDetail: "host_timeout"` (`HOST_TIMEOUT_OUTCOME_DETAIL`) and the `status: cancelled` carries `detail: "Turn timed out"`, and the conversation shows a "Turn timed out" status. The Claude runtime's own stop notices, "No response requested." and "API Error: Request was aborted.", no longer replay as the agent's reply. They arrive as the new `SessionHistoryMessage.runtimeNotice` and are drawn as a short turn status. The same words written by the model or the user stay their text. From 0f9c4bd008adbb259170e7cc4c6e27129d45a527 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 13:56:04 +0000 Subject: [PATCH 4/4] test: re-pin the audited chat handler source after #3356 The result handler's body changed; the chatFrameHandlers map is still all private arrow-function properties with no new importers, so the reviewed dispatch binding holds. Co-Authored-By: Claude Opus 5.5 --- scripts/source-browser-dispatch.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/source-browser-dispatch.ts b/scripts/source-browser-dispatch.ts index 22b525565f..6059e0a2ea 100644 --- a/scripts/source-browser-dispatch.ts +++ b/scripts/source-browser-dispatch.ts @@ -22,7 +22,7 @@ const declarations=[ { "owner": "packages/ui-react/src/hooks/websocket-handlers/chat.ts", "name": "chatFrameHandlers", - "source": "50bd80b3dd6f9fc0f167f55e3596e64d35b471bb668f160d6c83424cb7edc11d" + "source": "c92372d533f83154ec28a41e89504cab7d5486dd4e6d9ed632c0c05c49dd9130" }, { "owner": "packages/ui-react/src/hooks/websocket-handlers/activity.ts",