From 85a78b6ae9d272f2fd1c1588d5c97ba820c52b28 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 12:34:23 +0000 Subject: [PATCH 1/3] test(ui-server): characterize today's ask-user id collision rules per kind and turn Refs #2515 Co-Authored-By: Claude Opus 5.5 --- .../tests/ws-ask-collision-matrix.test.ts | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 packages/ui-server/tests/ws-ask-collision-matrix.test.ts diff --git a/packages/ui-server/tests/ws-ask-collision-matrix.test.ts b/packages/ui-server/tests/ws-ask-collision-matrix.test.ts new file mode 100644 index 0000000000..a1f32a588a --- /dev/null +++ b/packages/ui-server/tests/ws-ask-collision-matrix.test.ts @@ -0,0 +1,134 @@ +/** + * Characterization of today's ask-user id collision rules (#2515). Every cell + * of four kinds × same/other turn × same/other kind records whether a second + * request with a pending id is accepted or refused, and whether the host logs + * an ERROR for it. Unifying these rules is a separate ruling (#2773); this + * test pins the current behaviour so the coordinator refactor cannot move it. + */ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import type { ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; +import type { AgentBackend, BackendBridge } from "@schlessera/brain-ui-sdk/server"; +import { parseClientMessage } from "@schlessera/brain-ui-sdk/schemas"; +import { createWsHandlers } from "../src/ws/connection"; +import type { WSContext } from "../src/ws/clients"; +import { closeDb, resetForTests, setBackendForTests, testHost } from "./helpers/test-host"; +import { testPrincipal } from "./helpers/principal"; + +const KINDS = ["ask_user", "ask_user_list", "ask_user_rank", "ask_user_form"] as const; +type Kind = (typeof KINDS)[number]; + +function ask(bridge: BackendBridge, kind: Kind): Promise { + switch (kind) { + case "ask_user": + return bridge.askUser!("ithaca", [ + { question: "Which road?", header: "Road", multiSelect: false, + options: [{ label: "Sea", description: "By ship" }, { label: "Land", description: "On foot" }] }, + ]); + case "ask_user_list": + return bridge.askUserList!("ithaca", { + prompt: "Rate the crew", allowSkip: true, notes: false, + scale: [{ label: "Loyal" }, { label: "Wavering" }], items: [{ id: "eurylochus", label: "Eurylochus" }], + }); + case "ask_user_rank": + return bridge.askUserRank!("ithaca", { + prompt: "Rank the perils", items: [{ id: "scylla", label: "Scylla" }, { id: "charybdis", label: "Charybdis" }], + }); + case "ask_user_form": + return bridge.askUserForm!("ithaca", { + prompt: "Choose a course", + nodes: [{ id: "course", kind: "single", prompt: "Which?", options: [{ label: "Sea" }, { label: "Land" }] }], + }); + } +} + +/** + * Today's rule, per cell. `ask_user` and `ask_user_list` accept a repeat of + * their own id from the same turn and refuse (with an ERROR log) one from + * another turn; any other combination is refused without a log. + */ +function expected(original: Kind, duplicate: Kind, sameTurn: boolean): { accepted: boolean; logged: boolean } { + const lenient = duplicate === "ask_user" || duplicate === "ask_user_list"; + if (original !== duplicate || !lenient) return { accepted: false, logged: false }; + return sameTurn ? { accepted: true, logged: false } : { accepted: false, logged: true }; +} + +async function until(condition: () => boolean): Promise { + for (let i = 0; i < 200; i++) { + if (condition()) return; + await Bun.sleep(5); + } + throw new Error("host did not start the scripted turns"); +} + +/** Two concurrent turns on the real host/connection/dispatch, each held until teardown. */ +async function setup() { + const bridges: BackendBridge[] = []; + 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 }) { + bridge.emit({ type: "session_info", sessionId: `aeaea-${bridges.length + 1}`, isNew: true }); + bridges.push(bridge); + await new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true })); + }, + async listSessions() { return []; }, + async getHistory() { return []; }, + }; + setBackendForTests(backend); + const host = testHost(); + const sent: ServerMessage[] = []; + const ws: WSContext = { send(data) { sent.push(JSON.parse(data) as ServerMessage); } }; + const handlers = createWsHandlers(host, testPrincipal()); + await handlers.onOpen({} as Event, ws); + for (const text of ["Sail for Ithaca", "Consult Tiresias"]) { + const data = JSON.stringify({ type: "chat_message", text }); + expect(parseClientMessage(data).ok).toBe(true); + handlers.onMessage({ data } as MessageEvent, ws); + await Bun.sleep(0); + } + await until(() => bridges.length === 2); + return { host, sent, bridges }; +} + +describe("ask-user id collisions (today's per-kind rules)", () => { + beforeEach(() => { resetForTests(); closeDb(); }); + afterEach(() => { resetForTests(); closeDb(); }); + + for (const original of KINDS) { + for (const duplicate of KINDS) { + for (const sameTurn of [true, false]) { + const want = expected(original, duplicate, sameTurn); + const cell = `${duplicate} after a pending ${original} from ${sameTurn ? "the same" : "another"} turn`; + test(`${cell}: ${want.accepted ? "accepted" : "refused"}${want.logged ? ", logged" : ""}`, async () => { + const { host, sent, bridges } = await setup(); + const first = ask(bridges[0]!, original); + first.catch(() => {}); + await Bun.sleep(0); + const frames = sent.length; + const emit = spyOn(host.log, "emit"); + try { + let refused: unknown; + const second = ask(bridges[sameTurn ? 0 : 1]!, duplicate); + second.catch((error: unknown) => { refused = error; }); + await Bun.sleep(0); + const collisions = emit.mock.calls.filter(([record]) => record.body === "interactive id collision: already pending for another turn"); + expect(collisions.length, "ERROR collision log").toBe(want.logged ? 1 : 0); + if (want.logged) expect(collisions[0]![0]).toMatchObject({ severityText: "ERROR", attributes: { "request.id": "ithaca" } }); + if (want.accepted) { + expect(refused).toBeUndefined(); + expect(sent.slice(frames).map(frame => frame.type)).toContain(`${duplicate}_request` as never); + } else { + expect(refused).toBeInstanceOf(Error); + expect((refused as Error).message).toBe("Duplicate ask-user request id"); + expect(sent.slice(frames), "a refused request sends nothing").toEqual([]); + } + } finally { + emit.mockRestore(); + } + }); + } + } + } +}); From e4b168aa2ddbf10f76a667b5c92ffe7062e2f00f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 13:22:21 +0000 Subject: [PATCH 2/3] refactor(ui-server): own turn state in TurnCoordinator behind intent methods The coordinator's collections are private. Other modules read them through read-only views and change them only through intent methods (open/claim/ settle for approvals, asks, location and mask; register/bind/unregister for turns; begin/end for session starts; register/release for handoffs), so each invariant is written once. - The four ask-user maps become one map with a kind discriminant. Each kind's current collision rule is preserved and expressed once in openAsk; unifying it is #2773. - log, onApprovalSettled and onQueueChanged go through the constructor. turnReverts and the shared worker lock go through WsHostOptions, and beginClosing() replaces the direct `closing` assignment. - Queue limits and turnLogAttributes move to the leaf ws/limits.ts (host.ts re-exports them), removing the host -> conversation -> run-session -> host value cycle. - reset() is gone. cancelAll() now also settles pending requests whose turn no longer runs, so close() leaves nothing a caller awaits unsettled. Teardowns use close()/cancelAll(). - Moved doc citations follow their anchors. Refs #2515 Co-Authored-By: Claude Opus 5.5 --- docs/decisions/answer-delivery.md | 6 +- docs/decisions/design-kit/show-block-brief.md | 2 +- docs/decisions/governed-writable-workers.md | 4 +- docs/decisions/http-api-boundary.md | 8 +- docs/decisions/live-conversation.md | 2 +- docs/decisions/managed-worktrees.md | 4 +- docs/decisions/session-principals.md | 14 +- docs/decisions/voice-permission.md | 16 +- .../live-conversation-investigation.md | 4 +- .../plans/async-collaboration-requirements.md | 6 +- docs/plans/async-collaboration.md | 12 +- docs/plans/chat-history-deletion.md | 8 +- docs/plans/navigation-recovery.md | 6 +- docs/plans/voice-conversation.md | 2 +- .../contextual-conversation-browser-server.ts | 2 +- .../fixtures/conversation-browser-server.ts | 2 +- packages/ui-server/src/app.ts | 15 +- packages/ui-server/src/ws/ask-answers.ts | 49 +- packages/ui-server/src/ws/bridge.ts | 60 +- packages/ui-server/src/ws/dispatch.ts | 72 +-- packages/ui-server/src/ws/handoff.ts | 9 +- packages/ui-server/src/ws/host.ts | 123 ++-- packages/ui-server/src/ws/limits.ts | 49 ++ packages/ui-server/src/ws/recovery.ts | 15 +- packages/ui-server/src/ws/resend.ts | 8 +- packages/ui-server/src/ws/run-session.ts | 29 +- packages/ui-server/src/ws/turns.ts | 533 +++++++++++++----- .../tests/app-writes-offloop.test.ts | 5 +- .../tests/gemini-conversation.test.ts | 2 +- .../tests/gpt-live-conversation.test.ts | 2 +- .../tests/helpers/contextual-refusals.ts | 2 +- packages/ui-server/tests/helpers/test-host.ts | 1 - .../tests/host-capability-note.test.ts | 4 +- .../tests/live-history-track.test.ts | 2 +- packages/ui-server/tests/run-session.test.ts | 15 +- .../tests/session-start-reliability.test.ts | 2 +- .../ui-server/tests/turn-coordinator.test.ts | 118 ++++ .../ui-server/tests/turn-data-tree.test.ts | 2 +- .../tests/ws-allowlist-enforcement.test.ts | 1 - .../tests/ws-approval-channel.test.ts | 1 - .../ui-server/tests/ws-conversation.test.ts | 11 +- .../tests/ws-follow-up-queue.test.ts | 6 +- packages/ui-server/tests/ws-handoff.test.ts | 2 +- .../tests/ws-live-policy-parity.test.ts | 2 +- .../ui-server/tests/ws-pill-labels.test.ts | 1 - .../tests/ws-promoted-block-replay.test.ts | 4 +- .../ui-server/tests/ws-revocation.test.ts | 21 +- .../tests/ws-session-recovery.test.ts | 1 - .../tests/ws-tool-resolution.test.ts | 1 - .../ui-server/tests/ws-track-files.test.ts | 10 +- tests/fixtures/claude-worker-probe.ts | 6 +- tests/fixtures/policy-boundary-probe.ts | 11 +- 52 files changed, 777 insertions(+), 516 deletions(-) create mode 100644 packages/ui-server/src/ws/limits.ts create mode 100644 packages/ui-server/tests/turn-coordinator.test.ts diff --git a/docs/decisions/answer-delivery.md b/docs/decisions/answer-delivery.md index 28c82b40c7..81796a218d 100644 --- a/docs/decisions/answer-delivery.md +++ b/docs/decisions/answer-delivery.md @@ -82,7 +82,7 @@ carries, no longer by position. The host also re-sends a session's pending questions after `session_resume` (`resendPendingAsks(host, ws, msg.sessionId)`, -`packages/ui-server/src/ws/dispatch.ts:677`). Before this, a resume replaced +`packages/ui-server/src/ws/dispatch.ts:651`). Before this, a resume replaced the transcript and left only a history card behind, which was the second symptom. @@ -91,7 +91,7 @@ symptom. Each answer carries a client-minted `submissionId`, reused for every retry of that answer. The host settles the request at most once, records the outcome, and answers the sender with `ask_answer_receipt` (`handleAskAnswer`, -`packages/ui-server/src/ws/ask-answers.ts:105-181`). A repeat of the same +`packages/ui-server/src/ws/ask-answers.ts:84-138`). A repeat of the same submission gets the same receipt and settles nothing. Revision 3's echo is negotiated per connection: a client that declares @@ -106,7 +106,7 @@ capability flag is what peers check, because a revision number alone was ruled not to establish receipt support. Outcomes are remembered in memory for 24 hours, at most 1,024 of them -(`ASK_OUTCOME_TTL_MS`, `packages/ui-server/src/ws/turns.ts:374`). That is the +(`ASK_OUTCOME_TTL_MS`, `packages/ui-server/src/ws/turns.ts:412`). That is the client's maximum replay age, so any answer a client may still replay finds its outcome. Persisting outcomes would not help after a restart: the requests themselves are gone then, and an answer for them must stop, not diff --git a/docs/decisions/design-kit/show-block-brief.md b/docs/decisions/design-kit/show-block-brief.md index 9606b0875f..ab2d083f99 100644 --- a/docs/decisions/design-kit/show-block-brief.md +++ b/docs/decisions/design-kit/show-block-brief.md @@ -38,7 +38,7 @@ Four rules decide what counts, and each of them changed a number: frames a subagent produced, and the chat adapter keeps those off the surface. - **The turn budget is enforced, not just advertised.** Production aborts a turn at `turnTimeoutMs` (`timeoutHandle = setTimeout`, - `packages/ui-server/src/ws/run-session.ts:388`), so + `packages/ui-server/src/ws/run-session.ts:378`), so the harness aborts at the same 180 s. Without it an answer no reader could have received still scored: an earlier run had five turns of 190–306 s. - **A turn that did not complete is excluded from every rate**, in both diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 80076ee763..3956b066b7 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:632-637`). 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. @@ -1520,7 +1520,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:924`). 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/http-api-boundary.md b/docs/decisions/http-api-boundary.md index e82378d919..c4971dcc4f 100644 --- a/docs/decisions/http-api-boundary.md +++ b/docs/decisions/http-api-boundary.md @@ -46,11 +46,11 @@ explicit supported rows, not silently excluded by this distinction. The source audit on 2026-09-30 used `e0875269b21b707482545be9e94901acb897893b`. The public health mount precedes auth -(`createHealthRoutes`, `packages/ui-server/src/app.ts:884`), the API guard follows -public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:905`), and the -WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1095`). +(`createHealthRoutes`, `packages/ui-server/src/app.ts:891`), the API guard follows +public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:912`), and the +WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1098`). Static serving is conditional (`if (options.staticRoot)`, -`packages/ui-server/src/app.ts:1115-1136`). That order establishes access; +`packages/ui-server/src/app.ts:1118-1139`). That order establishes access; it does not select compatibility status. A hermetic real-app launch, with temporary brain root, in-memory database, diff --git a/docs/decisions/live-conversation.md b/docs/decisions/live-conversation.md index 2a4d862347..4adf5589d7 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:993-1012`). 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 d97580e7a4..75cd8b3a21 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:560-572`; `// 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:573-579`). 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-principals.md b/docs/decisions/session-principals.md index 58fc171748..730ab1dae5 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -96,13 +96,13 @@ Both reviewers verified every row below against the source. | Cookie verify | `auth.ts:265-296` | strict `^(\d+)\.(\d+)$`, safe integers, future/expired rejection, `cookieEpoch === sessionsEpoch(db)` | | Global epoch | `auth.ts:302-318` | `settings` row; missing = 0; non-integer **throws** | | Global revoke | `auth.ts:321-330` | `setSetting` (overflow-guarded) + `clients.closeAll(1008, …)` | -| Auth routes | `authRoutes`, `app.ts:890` | mounted **before** the guard at `authGuard(authMode`, `app.ts:905`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | -| Passkey management | `passkeyManagementRoutes`, `app.ts:915` | mounted **after** the guard ("Mount AFTER the auth guard") | -| WS guard | `"/ws"`, `app.ts:1095-1112` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | +| Auth routes | `authRoutes`, `app.ts:897` | mounted **before** the guard at `authGuard(authMode`, `app.ts:912`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | +| Passkey management | `passkeyManagementRoutes`, `app.ts:922` | mounted **after** the guard ("Mount AFTER the auth guard") | +| WS guard | `"/ws"`, `app.ts:1098-1115` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | | 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:1112` | 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 | @@ -178,13 +178,13 @@ ceremony in flight can mint a session for a credential deleted meanwhile. **5. Revocation is a boundary that outlives admission.** Closing a socket is not 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 +(`resolveTurnTarget`, `ws/run-session.ts:209`; `const billing = await resolveRunBilling`, +`ws/run-session.ts:401`), 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:959`). 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 c96791bcc1..7dc06c57ca 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:391` → +`drainPendingForTurn`, `packages/ui-server/src/ws/turns.ts:993-1012`), 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:386`; `drainPendingForTurn`, `run-session.ts:391`), 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 @@ -426,7 +426,7 @@ exchange over a security decision is a second chance for noise to produce a grant. **"Always allow" cannot be given by voice.** It is a persistent policy change -(the block computing `remembers`, `packages/ui-server/src/ws/dispatch.ts:449-455`) +(the block computing `remembers`, `packages/ui-server/src/ws/dispatch.ts:437-443`) and it is the one decision on the card with no keyboard shortcut, by D37's ruling 5, and the reason given there is exactly the one that applies here: *"a letter that grants standing @@ -435,7 +435,7 @@ permission by reflex is the one footgun in the vocabulary"* 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:449-455`, and the lookup computing +(the block computing `remembers`, `dispatch.ts:437-443`, and the lookup computing `remembered`, `ws/bridge.ts:372-392`), and 192 of 192 measured approvals were kind `command`. @@ -493,7 +493,7 @@ the request kind, and it patches the span (`onApprovalDecision`, `packages/ui-server/src/activity/recorder.ts:674-689`), 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:410-425`). 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 @@ -505,7 +505,7 @@ provenance. The wire needs nothing new: a spoken refusal is an ordinary `tool_denial` (in `handleClientMessage`, the arm `case "tool_denial"`, -`packages/ui-server/src/ws/dispatch.ts:496-519`) with a message naming the +`packages/ui-server/src/ws/dispatch.ts:480-493`) with a message naming the phrase that produced it. ## Containment: shared with #51, deliberately not identical @@ -640,7 +640,7 @@ matters because a reader cannot otherwise tell a live hazard from a fixed one. left out (the lookup computing `remembered`, `packages/ui-server/src/ws/bridge.ts:372-392`, and the block computing `remembers`, - `packages/ui-server/src/ws/dispatch.ts:449-455`). + `packages/ui-server/src/ws/dispatch.ts:437-443`). The evaluation happens before the lookup, which is what this record asked for. diff --git a/docs/investigations/live-conversation-investigation.md b/docs/investigations/live-conversation-investigation.md index c7d41aedca..82a01755a5 100644 --- a/docs/investigations/live-conversation-investigation.md +++ b/docs/investigations/live-conversation-investigation.md @@ -297,12 +297,12 @@ matcher. An isolated ambiguous refusal denies all **current** pending requests; an exact refusal can name one. With none pending, it is ordinary input. Bind each denial to existing IDs, echoed turn and `channel:"voice"`; the server still rejects voice grants -(`if (msg.channel === "voice")`, `packages/ui-server/src/ws/dispatch.ts:409-432`). +(`if (msg.channel === "voice")`, `packages/ui-server/src/ws/dispatch.ts:397-420`). Never add a spoken approve or always-allow path. On the evidence date the denial handler removed/resolved a matched request but provided no dedicated denial receipt at that branch; #957 added one -(`case "tool_denial"`, `packages/ui-server/src/ws/dispatch.ts:496-519`). The +(`case "tool_denial"`, `packages/ui-server/src/ws/dispatch.ts:480-493`). The integration therefore needs host-authoritative resolution/replay: denied, already granted, expired, or unknown/disconnected. Speak a denial confirmation only for a confirmed denied outcome. A visual grant winning the race remains diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index b546783c15..30d61b337e 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -226,7 +226,7 @@ Stated before the requirements because five of them derive from it. that is the shape to copy, including its `close()` lifecycle. - R19. **The cron backstop has independent authorization before the general guard.** Mount it on the existing listener before - (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:905`). + (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:912`). Authorize a boot-minted ephemeral token, rotated each boot and stored in a 0600 runtime file, with the actual socket address as an additional check. Proxy headers cannot authorize it. The poke succeeds in every auth mode @@ -256,7 +256,7 @@ Stated before the requirements because five of them derive from it. (`export function createTurnRecorder(`, `packages/ui-server/src/activity/recorder.ts:125-203`). - 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:1323-1335`), 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 @@ -266,7 +266,7 @@ Stated before the requirements because five of them derive from it. promise (`return new Promise((resolve) => {`, `packages/ui-server/src/ws/bridge.ts:406-464`) — 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:386-392`). 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. diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 65939d5ea0..cfbc875a4f 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -131,11 +131,11 @@ system gate. It is not a prerequisite to rebuild or a new independent package. owns manual triggers/history; it does not tick the inbox. - **Two connections:** (`export function createUiDb(`, `packages/ui-server/src/db/client.ts:27-44`) sets WAL, foreign keys and a 5-second busy timeout. Claims are immediate transactions. -- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:905`) follows public routes; +- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:912`) 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 + (`abortController.abort();`, `packages/ui-server/src/ws/run-session.ts:386-392`). 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 @@ -156,7 +156,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. - **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:2401`) 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:1323-1335`) 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. @@ -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:386-392`) - **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:1323-1335`) 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:386-392`), 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 78ff9c5144..b830b24809 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -146,7 +146,7 @@ must be tested through their installed runtime, not inferred from directory name readable projections according to the adopted extent. Retained digests can reveal guessed short text; discard unnecessary hashes, not just plaintext. Native history joins several of these owners - (`prepareHistory`, `packages/ui-server/src/ws/host.ts:638-650`). + (`prepareHistory`, `packages/ui-server/src/ws/host.ts:614-626`). - **Independent session ledgers.** `retry_receipts`, `session_work`, `turn_boundaries`, draft send/save/upload receipts and revisions, handoff IDs/lineage, Claude usage deduplication, worker profiles, provider-exposure and born-masked lineage are @@ -222,7 +222,7 @@ cron scratch-pin refresh; backend native resume/archive/restore; and all browser 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-220`), +(`readSessionRecovery`, `packages/ui-server/src/ws/recovery.ts:202-213`), `FailureReplay` (`FailureReplay`, `packages/ui-server/src/ws/turn-failures.ts:63-89`), 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 @@ -233,7 +233,7 @@ The paired WS dispatcher is `packages/ui-server/src/ws/dispatch.ts`; gating its resume case alone would leave HTTP, background readers and provider startup open. Existing ordinary history publication checks concurrent turn changes -(`publishHistory`, `packages/ui-server/src/ws/host.ts:564-598`). Future deletion +(`publishHistory`, `packages/ui-server/src/ws/host.ts:540-574`). Future deletion must additionally invalidate it even when no turn starts or ends. Startup reads native history, canonical evidence and completed facts, and freezes a snapshot (`readLiveHistory`, `packages/ui-server/src/ws/live-history.ts:8-65`). Recheck the @@ -267,7 +267,7 @@ Preserve the existing bounded-wait ownership distinction during that drain. writers; rejection retains the original cleanup continuation, writer and reader until genuine settlement, rather than authorizing their replacement (`guardSqliteCleanup`, `packages/ui-server/src/db/write-worker.ts:206-234`; -`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1205-1254`). +`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1208-1257`). The native lease manager retains its own pending operations and durable unknown root outcomes through close (`return { client, writer, recoverDeadOwners`, `packages/ui-server/src/brain/native-brain-leases.ts:274-287`). A caller deadline diff --git a/docs/plans/navigation-recovery.md b/docs/plans/navigation-recovery.md index 7442d97504..01ea06e510 100644 --- a/docs/plans/navigation-recovery.md +++ b/docs/plans/navigation-recovery.md @@ -385,7 +385,7 @@ implementation. Any PR moving these lines owns their citation repairs. - Host reconnect: (`const runningTurns = [...coordinator.running].filter((t) => t.sessionId);`, `packages/ui-server/src/ws/connection.ts:128-193`). -- Host resume: (`case "session_resume": {`, `packages/ui-server/src/ws/dispatch.ts:648-712`). +- Host resume: (`case "session_resume": {`, `packages/ui-server/src/ws/dispatch.ts:622-686`). - Catalog activity: (`persistSessionStub(sessionId, promptText, providerId, backendId) {`, `packages/ui-server/src/ws/session-catalog.ts:479-486`). @@ -397,9 +397,9 @@ implementation. Any PR moving these lines owns their citation repairs. - 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:905`). +- API authorization: (`app.use("/api/*", authGuard(authMode, auth, db));`, `packages/ui-server/src/app.ts:912`). -- 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:1089-1134`). - Approval target: (`function mutateLastAssistant(`, `packages/ui-react/src/stores/chat-state.ts:1233-1263`). diff --git a/docs/plans/voice-conversation.md b/docs/plans/voice-conversation.md index 3d430eefbd..5ce834308e 100644 --- a/docs/plans/voice-conversation.md +++ b/docs/plans/voice-conversation.md @@ -377,7 +377,7 @@ 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:993-1012`). 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:1115-1125`). Keep the existing card/receipt in diff --git a/packages/ui-react/tests/fixtures/contextual-conversation-browser-server.ts b/packages/ui-react/tests/fixtures/contextual-conversation-browser-server.ts index 26ccf2c068..011b890739 100644 --- a/packages/ui-react/tests/fixtures/contextual-conversation-browser-server.ts +++ b/packages/ui-react/tests/fixtures/contextual-conversation-browser-server.ts @@ -160,5 +160,5 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { await Bun.sleep(10); return Response.json({ frames: frames.splice(0), sent: sent.splice(0), tasks, released, opening, validationHeld, validationCalls, historyPending: pendingHistory.length > 0, providerOpens, providerCloses, missingChatExists: catalog.hasSession!("odysseus-ithaca"), effect: existsSync(join(root, "notes/contextual-raft.md")) }); } }); -process.on("SIGTERM", async () => { releaseValidation(); releaseOpening(); release(); host.coordinator.reset(); await host.close(); for (const reject of pendingHistory.splice(0)) reject(new Error("Odysseus history fixture closed.")); db.close(); await native.close(); remote?.close(); upstream.stop(true); server.stop(true); rmSync(root, { recursive: true, force: true }); rmSync(state, { recursive: true, force: true }); process.exit(0); }); +process.on("SIGTERM", async () => { releaseValidation(); releaseOpening(); release(); await host.close(); for (const reject of pendingHistory.splice(0)) reject(new Error("Odysseus history fixture closed.")); db.close(); await native.close(); remote?.close(); upstream.stop(true); server.stop(true); rmSync(root, { recursive: true, force: true }); rmSync(state, { recursive: true, force: true }); process.exit(0); }); console.log(JSON.stringify({ url: `http://127.0.0.1:${server.port}` })); diff --git a/packages/ui-react/tests/fixtures/conversation-browser-server.ts b/packages/ui-react/tests/fixtures/conversation-browser-server.ts index 2ffae37ebb..337b40ccfa 100644 --- a/packages/ui-react/tests/fixtures/conversation-browser-server.ts +++ b/packages/ui-react/tests/fixtures/conversation-browser-server.ts @@ -61,5 +61,5 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { await Bun.sleep(20); return Response.json({ frames: frames.splice(0), sent: sent.splice(0) }); } }); -process.on("SIGTERM", async () => { clearInterval(silence); host.coordinator.reset(); await host.close(); db.close(); remote?.close(); upstream.stop(true); server.stop(true); process.exit(0); }); +process.on("SIGTERM", async () => { clearInterval(silence); await host.close(); db.close(); remote?.close(); upstream.stop(true); server.stop(true); process.exit(0); }); console.log(JSON.stringify({ url: `http://127.0.0.1:${server.port}` })); diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index be0eea1fc4..fa75f1e15b 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -140,7 +140,7 @@ import { ensureIndexDirectory, retireLegacyIndex } from "./brain/index-directory import { createGovernedTurns } from "./brain/governed-turn.js"; import { createProviderExposures } from "./brain/provider-exposure.js"; import type { BackendVersionRequirements, ExecWrapperConfig, LiveConversationProvider, SpeechProvider } from "@schlessera/brain-ui-sdk/server"; -import { validateVersionMinimum } from "@schlessera/brain-ui-sdk/server"; +import { createKeyedLock, validateVersionMinimum } from "@schlessera/brain-ui-sdk/server"; import { createCronScheduler } from "./cron/scheduler.js"; import { createScratchPins } from "./cron/scratch-pins.js"; import { startScratchPrune } from "./cron/scratch-prune.js"; @@ -657,7 +657,14 @@ export async function createApp(options: CreateAppOptions = {}): Promise host.clients.hasClients(), changed(turnId, sessionId) { host.clients.broadcast({ type: "turn_journal", sessionId, turnId, journal: { ...journal.summary(turnId), ...(host.budgets?.saved(turnId) ? { budget: host.budgets.saved(turnId) } : {}) } }); } }); + // Built before the host it is handed to, so the two share one worker lock. + const workerLock = createKeyedLock(); + const reverts = createTurnReverts(db, { brainPath: config.brainPath, journal, gate: hostExecution.gate()!, lock: workerLock, governance: activity.governanceWrites, + isAuthorized(id) { const principal = resolvePrincipal(db, id); return !!principal && ["owner", "ambient"].includes(principal.kind) && isUsablePrincipal(principal, Date.now()); }, + refresh() { host.governedTurns?.refresh(host.workerLock); } }); const host = new WsHost({ + turnReverts: reverts, + workerLock, identitySentinelDirectory, scope, policyProposals, @@ -1024,11 +1031,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise storageRemoval.close()); app.route("/api", createStorageRemovalRoutes(storageRemoval)); - const reverts = createTurnReverts(db, { brainPath: config.brainPath, journal, gate: hostExecution.gate()!, lock: host.workerLock, governance: activity.governanceWrites, - isAuthorized(id) { const principal = resolvePrincipal(db, id); return !!principal && ["owner", "ambient"].includes(principal.kind) && isUsablePrincipal(principal, Date.now()); }, - refresh() { host.governedTurns?.refresh(host.workerLock); } }); bootCleanup.push(() => reverts.close()); - host.turnReverts = reverts; app.route("/api", createTurnRevertRoutes(reverts)); // Only where server_hello advertises it: elsewhere the route is absent, // which a client reads as a host too old to answer (#964). @@ -1205,7 +1208,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise closing ??= guardSqliteCleanup([writer, nativeLeases.writer], (async () => { // Refuse new requests immediately; every remaining owner drains even // when a native deletion reply is unknown and its durable row stays. - host.closing = true; + host.beginClosing(); // Queued module metadata is cancelled now (#2457). In-flight work gets a // short grace period; then shared CLI runs (reads and plain index) are // cancelled so they cannot hold close open (#2473). diff --git a/packages/ui-server/src/ws/ask-answers.ts b/packages/ui-server/src/ws/ask-answers.ts index 2d1e0bbe88..18bcf52984 100644 --- a/packages/ui-server/src/ws/ask-answers.ts +++ b/packages/ui-server/src/ws/ask-answers.ts @@ -24,14 +24,7 @@ import { } from "@schlessera/brain-ui-sdk/protocol"; import type { WSContext } from "./clients.js"; import type { WsHost } from "./host.js"; -import type { - AskKind, - PendingAskUser, - PendingAskUserForm, - PendingAskUserList, - PendingAskUserRank, - TurnCoordinator, -} from "./turns.js"; +import type { AskKind, PendingAsk, TurnCoordinator } from "./turns.js"; type AskAnswer = | ClientAskUserResponse @@ -39,12 +32,6 @@ type AskAnswer = | ClientAskUserRankResponse | ClientAskUserFormResponse; -type PendingAsk = - | { kind: "ask_user"; entry: PendingAskUser } - | { kind: "ask_user_list"; entry: PendingAskUserList } - | { kind: "ask_user_rank"; entry: PendingAskUserRank } - | { kind: "ask_user_form"; entry: PendingAskUserForm }; - const ANSWER_KIND: Record = { ask_user_response: "ask_user", ask_user_list_response: "ask_user_list", @@ -54,15 +41,7 @@ const ANSWER_KIND: Record = { /** The pending ask with this id, of whichever kind. The kinds share one id space. */ export function findPendingAsk(coordinator: TurnCoordinator, requestId: string): PendingAsk | undefined { - const ask = coordinator.pendingAskUser.get(requestId); - if (ask) return { kind: "ask_user", entry: ask }; - const list = coordinator.pendingAskUserList.get(requestId); - if (list) return { kind: "ask_user_list", entry: list }; - const rank = coordinator.pendingAskUserRank.get(requestId); - if (rank) return { kind: "ask_user_rank", entry: rank }; - const form = coordinator.pendingAskUserForm.get(requestId); - if (form) return { kind: "ask_user_form", entry: form }; - return undefined; + return coordinator.pendingAsk(requestId); } /** The receipt for a request that is no longer pending, from its recorded outcome. */ @@ -144,29 +123,7 @@ export function handleAskAnswer( return; } - switch (pending.kind) { - case "ask_user": - coordinator.pendingAskUser.delete(msg.requestId); - break; - case "ask_user_list": - coordinator.pendingAskUserList.delete(msg.requestId); - break; - case "ask_user_rank": - coordinator.pendingAskUserRank.delete(msg.requestId); - break; - case "ask_user_form": - coordinator.pendingAskUserForm.delete(msg.requestId); - break; - } - coordinator.recordAskOutcome({ - requestId: msg.requestId, - sessionId: entry.turn.sessionId, - turnId: entry.turnId, - state: "accepted", - submissionId, - principalId, - at: Date.now(), - }); + coordinator.acceptAsk(pending, { submissionId, principalId }); entry.turn.recorder?.recordAskUserResponse(principalId); if (pending.kind === "ask_user" && msg.type === "ask_user_response") { pending.entry.resolve({ answers: msg.answers, annotations: msg.annotations }); diff --git a/packages/ui-server/src/ws/bridge.ts b/packages/ui-server/src/ws/bridge.ts index 10f2001702..72b11b9aa6 100644 --- a/packages/ui-server/src/ws/bridge.ts +++ b/packages/ui-server/src/ws/bridge.ts @@ -236,7 +236,7 @@ export async function makeBridge( // injected backend that omits (or mislabels) it still scopes the // client's tool rendering correctly. msg = { ...msg, backendId }; - coordinator.bySession.set(msg.sessionId, turn); + coordinator.bindSession(msg.sessionId, turn); // Persist ownership the moment the identity exists — a turn that // later fails or is cancelled must not leave an unowned transcript. catalog.persistSessionStub(msg.sessionId, promptText, turn.providerId, backendId); @@ -404,10 +404,6 @@ export async function makeBridge( return Promise.resolve({ behavior: "allow" }); } return new Promise((resolve) => { - if (coordinator.collidesAcrossTurns(coordinator.pendingApprovals, req.toolUseId, turn)) { - resolve({ behavior: "deny", message: "Duplicate tool-approval id" }); - return; - } // The decision stamps the wait/execution boundary on the tool span // (grant) or lands the denied outcome (deny) before the backend's // own error tool_result can mislabel it — write-once protects it. @@ -428,12 +424,10 @@ export async function makeBridge( ); resolve(decision); }; - coordinator.pendingApprovals.set(req.toolUseId, { - turn, - turnId, - request: req, - resolve: recorded, - }); + if (!coordinator.openApproval(req.toolUseId, { turn, turnId, request: req, resolve: recorded })) { + resolve({ behavior: "deny", message: "Duplicate tool-approval id" }); + return; + } if (!host.clients.hasClients()) { // Not a failure — the card is parked and re-delivered on reconnect // (see resendPendingInteractive) — but the wait was invisible before @@ -504,23 +498,10 @@ export async function makeBridge( : {}), askUser: (requestId, questions) => { return new Promise((resolve, reject) => { - if ( - coordinator.collidesAcrossTurns(coordinator.pendingAskUser, requestId, turn) || - coordinator.pendingAskUserList.has(requestId) || - coordinator.pendingAskUserRank.has(requestId) || - coordinator.pendingAskUserForm.has(requestId) - ) { + if (!coordinator.openAsk("ask_user", { turn, turnId, requestId, questions, resolve, reject })) { reject(new Error("Duplicate ask-user request id")); return; } - coordinator.pendingAskUser.set(requestId, { - turn, - turnId, - requestId, - questions, - resolve, - reject, - }); host.sendToClients( withTurnScope({ type: "ask_user_request", requestId, questions }, turn, turnId) ); @@ -537,23 +518,10 @@ export async function makeBridge( return new Promise((resolve, reject) => { // One id space across all ask kinds: a single `ask_user_cancel` // dismisses any of them, so an id pending as one must not open as the other. - if ( - coordinator.collidesAcrossTurns(coordinator.pendingAskUserList, requestId, turn) || - coordinator.pendingAskUser.has(requestId) || - coordinator.pendingAskUserRank.has(requestId) || - coordinator.pendingAskUserForm.has(requestId) - ) { + if (!coordinator.openAsk("ask_user_list", { turn, turnId, requestId, request, resolve, reject })) { reject(new Error("Duplicate ask-user request id")); return; } - coordinator.pendingAskUserList.set(requestId, { - turn, - turnId, - requestId, - request, - resolve, - reject, - }); host.sendToClients( withTurnScope({ type: "ask_user_list_request", requestId, ...request }, turn, turnId) ); @@ -568,11 +536,11 @@ export async function makeBridge( }, askUserRank: (requestId, request) => { // Cancellation shares one id space across all four ask kinds. - if (coordinator.pendingAskUserRank.has(requestId) || coordinator.pendingAskUser.has(requestId) || coordinator.pendingAskUserList.has(requestId) || coordinator.pendingAskUserForm.has(requestId)) { + if (coordinator.pendingAsk(requestId)) { return Promise.reject(new Error("Duplicate ask-user request id")); } return new Promise((resolve, reject) => { - coordinator.pendingAskUserRank.set(requestId, { turn, turnId, requestId, request, resolve, reject }); + coordinator.openAsk("ask_user_rank", { turn, turnId, requestId, request, resolve, reject }); host.sendToClients(withTurnScope({ type: "ask_user_rank_request", requestId, ...request }, turn, turnId)); host.sendToClients(withTurnScope({ type: "status", status: "tool_executing", detail: "Waiting for your input" }, turn, turnId)); }); @@ -580,11 +548,11 @@ export async function makeBridge( askUserFormLimits: host.askUserFormLimits, askUserForm: (requestId, request) => { const validated = askUserFormSpec(request, host.askUserFormLimits); - if (coordinator.pendingAskUserForm.has(requestId) || coordinator.pendingAskUser.has(requestId) || coordinator.pendingAskUserList.has(requestId) || coordinator.pendingAskUserRank.has(requestId)) { + if (coordinator.pendingAsk(requestId)) { return Promise.reject(new Error("Duplicate ask-user request id")); } return new Promise((resolve, reject) => { - coordinator.pendingAskUserForm.set(requestId, { turn, turnId, requestId, request: validated, resolve, reject }); + coordinator.openAsk("ask_user_form", { turn, turnId, requestId, request: validated, resolve, reject }); host.sendToClients(withTurnScope({ type: "ask_user_form_request", requestId, ...validated }, turn, turnId)); host.sendToClients(withTurnScope({ type: "status", status: "tool_executing", detail: "Waiting for your input" }, turn, turnId)); }); @@ -597,11 +565,10 @@ export async function makeBridge( } const requestId = coordinator.nextLocationRequestId(); return new Promise((resolve, reject) => { - if (coordinator.collidesAcrossTurns(coordinator.pendingLocation, requestId, turn)) { + if (!coordinator.openLocation(requestId, { turn, turnId, resolve, reject })) { reject(new Error("Duplicate location request id")); return; } - coordinator.pendingLocation.set(requestId, { turn, turnId, resolve, reject }); host.sendToClients( withTurnScope({ type: "location_request", requestId, options }, turn, turnId) ); @@ -622,11 +589,10 @@ export async function makeBridge( } const requestId = coordinator.nextMaskRequestId(); return new Promise((resolve, reject) => { - if (coordinator.collidesAcrossTurns(coordinator.pendingMask, requestId, turn)) { + if (!coordinator.openMask(requestId, { turn, turnId, resolve, reject })) { reject(new Error("Duplicate mask request id")); return; } - coordinator.pendingMask.set(requestId, { turn, turnId, resolve, reject }); host.sendToClients( withTurnScope({ type: "mask_request", requestId, imagePath, instruction }, turn, turnId) ); diff --git a/packages/ui-server/src/ws/dispatch.ts b/packages/ui-server/src/ws/dispatch.ts index 106aecd65e..a8f85b57a3 100644 --- a/packages/ui-server/src/ws/dispatch.ts +++ b/packages/ui-server/src/ws/dispatch.ts @@ -332,11 +332,7 @@ export async function handleClientMessage( case "ask_user_cancel": { // Dismisses any ask kind: the ids share one space. - const pending = - coordinator.pendingAskUser.get(msg.requestId) ?? - coordinator.pendingAskUserList.get(msg.requestId) ?? - coordinator.pendingAskUserRank.get(msg.requestId) ?? - coordinator.pendingAskUserForm.get(msg.requestId); + const pending = coordinator.pendingAsk(msg.requestId)?.entry; if (pending && turnIdMatches(pending, msg.turnId, requireEcho)) { // Recorded as `cancelled`, so a queued answer arriving later is told // the question was dismissed instead of meeting silence. @@ -351,46 +347,38 @@ export async function handleClientMessage( } case "location_response": { - const pending = coordinator.pendingLocation.get(msg.requestId); - if (pending && turnIdMatches(pending, msg.turnId, requireEcho)) { - coordinator.pendingLocation.delete(msg.requestId); - pending.resolve({ coords: msg.coords, timestamp: msg.timestamp }); - } + coordinator + .claimLocation(msg.requestId, (p) => turnIdMatches(p, msg.turnId, requireEcho)) + ?.resolve({ coords: msg.coords, timestamp: msg.timestamp }); break; } case "location_error": { - const pending = coordinator.pendingLocation.get(msg.requestId); - if (pending && turnIdMatches(pending, msg.turnId, requireEcho)) { - coordinator.pendingLocation.delete(msg.requestId); - pending.reject(new Error(locationErrorText(msg.code, msg.message))); - } + coordinator + .claimLocation(msg.requestId, (p) => turnIdMatches(p, msg.turnId, requireEcho)) + ?.reject(new Error(locationErrorText(msg.code, msg.message))); break; } case "mask_response": { - const pending = coordinator.pendingMask.get(msg.requestId); - if (pending && turnIdMatches(pending, msg.turnId, requireEcho)) { - coordinator.pendingMask.delete(msg.requestId); - // Decoded here rather than in the tool: the boundary already validated - // the base64 and its size, so the backend gets bytes it can trust. - pending.resolve(Uint8Array.from(Buffer.from(msg.maskPng, "base64"))); - } + // Decoded here rather than in the tool: the boundary already validated + // the base64 and its size, so the backend gets bytes it can trust. + coordinator + .claimMask(msg.requestId, (p) => turnIdMatches(p, msg.turnId, requireEcho)) + ?.resolve(Uint8Array.from(Buffer.from(msg.maskPng, "base64"))); break; } case "mask_error": { - const pending = coordinator.pendingMask.get(msg.requestId); - if (pending && turnIdMatches(pending, msg.turnId, requireEcho)) { - coordinator.pendingMask.delete(msg.requestId); - pending.reject( + coordinator + .claimMask(msg.requestId, (p) => turnIdMatches(p, msg.turnId, requireEcho)) + ?.reject( new Error( msg.code === "cancelled" ? `The user did not mark an area${msg.message ? `: ${msg.message}` : ""}` : msg.message || "The mask editor failed" ) ); - } break; } @@ -430,7 +418,7 @@ export async function handleClientMessage( ); break; } - coordinator.pendingApprovals.delete(msg.toolUseId); + coordinator.claimApproval(msg.toolUseId); // Remember-on-approve. Kind "command" never persists (the client // hides the option, but the wire is not trusted to enforce policy). // Neither does an approval given under an enforced allowlist that @@ -473,7 +461,9 @@ export async function handleClientMessage( }, }); } - pending.resolve( + coordinator.settleApproval( + msg.toolUseId, + pending, msg.updatedInput ? { behavior: "allow", updatedInput: msg.updatedInput } : { behavior: "allow" }, @@ -483,31 +473,15 @@ export async function handleClientMessage( ...(msg.channel ? { channel: msg.channel } : {}), } ); - coordinator.recordApprovalOutcome(msg.toolUseId, { - outcome: "granted", - turnId: pending.turnId, - sessionId: pending.turn.sessionId, - ...(msg.channel ? { channel: msg.channel } : {}), - }); } break; } case "tool_denial": { - const pending = coordinator.pendingApprovals.get(msg.toolUseId); - if (pending && turnIdMatches(pending, msg.turnId, requireEcho)) { - coordinator.pendingApprovals.delete(msg.toolUseId); - pending.resolve( - { behavior: "deny", message: msg.message }, - { - principalId: connection.authorization.principalId, - ...(msg.channel ? { channel: msg.channel } : {}), - } - ); - coordinator.recordApprovalOutcome(msg.toolUseId, { - outcome: "denied", - turnId: pending.turnId, - sessionId: pending.turn.sessionId, + const pending = coordinator.claimApproval(msg.toolUseId, (p) => turnIdMatches(p, msg.turnId, requireEcho)); + if (pending) { + coordinator.settleApproval(msg.toolUseId, pending, { behavior: "deny", message: msg.message }, { + principalId: connection.authorization.principalId, ...(msg.channel ? { channel: msg.channel } : {}), }); } else { diff --git a/packages/ui-server/src/ws/handoff.ts b/packages/ui-server/src/ws/handoff.ts index d16a7cf6d7..d0af6ce1f2 100644 --- a/packages/ui-server/src/ws/handoff.ts +++ b/packages/ui-server/src/ws/handoff.ts @@ -131,7 +131,7 @@ export async function startHandoff( return; } const entry: { sessionId?: string } = {}; - coordinator.handoffs.set(handoff.handoffId, entry); + coordinator.registerHandoff(handoff.handoffId, entry); let handedOver = false; let recorded = false; let settled = false; @@ -140,7 +140,7 @@ export async function startHandoff( // stored keeps its key here, so a retry still finds it rather than // starting a second one. It lasts as long as the process does. if (entry.sessionId && !recorded) return; - if (coordinator.handoffs.get(handoff.handoffId) === entry) coordinator.handoffs.delete(handoff.handoffId); + coordinator.releaseHandoff(handoff.handoffId, entry); }; try { const sourceBackendId = catalog.getStoredBackendId(handoff.sourceSessionId); @@ -291,7 +291,7 @@ export async function prepareHandoff( return answer({ state: "failed", message: "The server is busy, so no summary was drafted." }); } const abort = new AbortController(); - coordinator.handoffPreparations.set(msg.handoffId, { abort, owner: connection }); + coordinator.registerHandoffPreparation(msg.handoffId, { abort, owner: connection }); const releaseAuthorization = connection.authorization.retain(); let timedOut = false; const timer = setTimeout(() => { timedOut = true; abort.abort(); }, HANDOFF_PREPARATION_TIMEOUT_MS); @@ -408,7 +408,6 @@ export async function prepareHandoff( clearTimeout(timer); recorder?.finish(outcome, failureReason); releaseAuthorization(); - const current = coordinator.handoffPreparations.get(msg.handoffId); - if (current?.abort === abort) coordinator.handoffPreparations.delete(msg.handoffId); + coordinator.releaseHandoffPreparation(msg.handoffId, abort); } } diff --git a/packages/ui-server/src/ws/host.ts b/packages/ui-server/src/ws/host.ts index b7bb3e6362..8157054d80 100644 --- a/packages/ui-server/src/ws/host.ts +++ b/packages/ui-server/src/ws/host.ts @@ -27,6 +27,7 @@ import type { AgentBackend, LiveConversationProvider } from "@schlessera/brain-u import { createKeyedLock, type KeyedLock } from "@schlessera/brain-ui-sdk/server"; import { assertLiveConversationProvider } from "@schlessera/brain-ui-sdk/server"; import { ConversationHost } from "./conversation.js"; +import { turnLogAttributes, type TurnLogContext } from "./limits.js"; import type { Labeller } from "../labels/labeller.js"; import { createPillLabels, type PillLabels } from "../labels/pill-labels.js"; import type { ApplicationPlanner } from "../brain/application.js"; @@ -58,32 +59,19 @@ const AUTHORIZATION_EXPIRY_SWEEP_MS = 1_000; const SESSION_EXPIRED_CLOSE_CODE = 1008; const SESSION_EXPIRED_CLOSE_REASON = "Session expired"; -/** - * Budget for the host-side follow-up queue of ONE session (backends without a - * native `followUp`; with one, messages go into the running turn and none of - * this applies). - * - * Bytes rather than a message count, because that is what the cost actually - * tracks: a queued entry is retained in this process until its turn runs, and - * an entry carrying four images outweighs a hundred carrying text. Counting - * messages made a text-only queue and a 50 MB image queue look identical. - * - * Past the warn mark the message is still accepted — the sender is told the - * queue is getting heavy, in `detail` on the `queued` status and in the server - * log. Past the hard cap it is refused with SESSION_QUEUE_FULL, which is an - * explicit error frame, never a silent drop. - */ -export const QUEUE_WARN_BYTES = 20 * 1024 * 1024; -export const QUEUE_MAX_BYTES = 50 * 1024 * 1024; - -/** - * Backstop on depth. Bytes do not bound COUNT, and every queued entry becomes - * its own turn: without this, ~500k one-line messages fit inside the byte cap - * and would run the session for days. Not the limit anyone should hit. - */ -export const MAX_SESSION_QUEUE = 50; +export { + MAX_SESSION_QUEUE, + QUEUE_MAX_BYTES, + QUEUE_WARN_BYTES, + turnLogAttributes, + type TurnLogContext, +} from "./limits.js"; export interface WsHostOptions { + /** @internal Concrete user history service mounted by this host, not agent authority. */ + turnReverts?: import("../brain/turn-revert.js").TurnReverts; + /** @internal The brain/git lock the host shares, when the app built a service that needs it first. */ + workerLock?: KeyedLock; /** @internal Trusted server-state placement for the existing identity probe. */ identitySentinelDirectory?: string; /** @internal Host-owned observed changes; absent histories remain unrecorded. */ @@ -219,25 +207,6 @@ export interface ToolPermissions { add(toolName: string): void | Promise; } -/** Identity of one turn, as it appears on a log record. */ -export interface TurnLogContext { - sessionId?: string | null; - turnId?: string | null; - providerId?: string | null; -} - -/** - * Log attributes for one turn. Null fields are omitted rather than stringified - * — a new session has no sessionId until `session_info` names it. - */ -export function turnLogAttributes(turn: TurnLogContext): Record { - return { - ...(turn.sessionId ? { "session.id": turn.sessionId } : {}), - ...(turn.turnId ? { "turn.id": turn.turnId } : {}), - ...(turn.providerId ? { profile: turn.providerId } : {}), - }; -} - /** * Everything one WebSocket coordinator instance owns: turn state, the session * catalog, the backend registry, the attached client sockets, branding copy, @@ -253,12 +222,12 @@ export function turnLogAttributes(turn: TurnLogContext): Record */ export class WsHost { /** @internal Concrete user history service mounted by this host, not agent authority. */ - turnReverts?: import("../brain/turn-revert.js").TurnReverts; + readonly turnReverts?: import("../brain/turn-revert.js").TurnReverts; /** @internal Concrete host-owned scope observation and process control. */ readonly scope?: import("../brain/turn-scope.js").TurnScope; readonly journal?: import("../brain/turn-journal.js").TurnJournal; /** @internal Shared across adapters, native tools, curated applications and index refresh. */ - readonly workerLock: KeyedLock = createKeyedLock(); + readonly workerLock: KeyedLock; /** @internal Trusted server-state placement, revalidated at each turn. */ readonly identitySentinelDirectory?: string; readonly brainPath?: string; @@ -287,11 +256,14 @@ export class WsHost { readonly failureReplay: FailureReplay; readonly askUserFormLimits: AskUserFormLimits; /** @internal Turn bookkeeping shared with the package's own connection and dispatch modules. */ - readonly coordinator: TurnCoordinator = new TurnCoordinator(); + readonly coordinator: TurnCoordinator; /** @internal Keep native leases/state open until cancelled runners settle. */ readonly turnTasks = new Set>(); - /** @internal Application shutdown refuses new runners. */ - closing = false; + #closing = false; + /** @internal Application shutdown refuses new runners; set once by `beginClosing`. */ + get closing(): boolean { + return this.#closing; + } /** @internal Receipt order is compared only within this host's session queues. */ nextSendOrder = 0; /** @internal Host wiring (#1053). */ @@ -361,6 +333,8 @@ export class WsHost { private readonly historyReads = new Set<{ sessionId: string; changed: boolean; resultTurnId?: string }>(); constructor(options: WsHostOptions) { + this.turnReverts = options.turnReverts; + this.workerLock = options.workerLock ?? createKeyedLock(); this.journal = options.journal; this.policyProposals = options.policyProposals; this.scope = options.scope; @@ -387,6 +361,28 @@ export class WsHost { this.maxConcurrentSessions = options.maxConcurrentSessions ?? (() => DEFAULT_MAX_CONCURRENT_SESSIONS); this.observability = options.observability ?? createSilentObservability(); + this.log = this.observability.logger("ws"); + this.coordinator = new TurnCoordinator({ + log: this.log, + // Every settled permission request, by any path, reaches the connections + // that asked for host outcomes (#957). + onApprovalSettled: (toolUseId, record) => { + this.sendToCapable("toolResolution", { + type: "tool_resolution", + toolUseId, + outcome: record.outcome, + ...(record.sessionId ? { sessionId: record.sessionId } : {}), + turnId: record.turnId, + ...(record.channel ? { channel: record.channel } : {}), + ...(record.reason ? { reason: record.reason } : {}), + }); + }, + // Every change to a session's pending follow-ups reaches the connections + // that asked for the queue (#1002). + onQueueChanged: (sessionId, change) => { + this.sendToCapable(FOLLOW_UP_QUEUE_CAPABILITY, this.followUpQueueFrame(sessionId, change)); + }, + }); this.wsRate = options.wsRate && options.wsRate.ratePerSecond > 0 ? options.wsRate : null; this.isPrincipalValid = options.isPrincipalValid ?? (() => true); @@ -421,7 +417,6 @@ export class WsHost { ? createPillLabels({ labeller: options.labeller, catalog: this.catalog, coordinator: this.coordinator }) : null; if (options.scratchPrune) this.scratchPrune = options.scratchPrune; - this.log = this.observability.logger("ws"); this.failureReplay = new FailureReplay(this.catalog, this.log); const meter = this.observability.meter("ws"); this.framesDropped = meter.createCounter("ws.frames.dropped", { @@ -442,25 +437,6 @@ export class WsHost { this.connectionsRefused = meter.createCounter("ws.connections.refused", { description: "WebSocket connections refused before admission", }); - this.coordinator.log = this.log; - // Every settled permission request, by any path, reaches the connections - // that asked for host outcomes (#957). - this.coordinator.onApprovalSettled = (toolUseId, record) => { - this.sendToCapable("toolResolution", { - type: "tool_resolution", - toolUseId, - outcome: record.outcome, - ...(record.sessionId ? { sessionId: record.sessionId } : {}), - turnId: record.turnId, - ...(record.channel ? { channel: record.channel } : {}), - ...(record.reason ? { reason: record.reason } : {}), - }); - }; - // Every change to a session's pending follow-ups reaches the connections - // that asked for the queue (#1002). - this.coordinator.onQueueChanged = (sessionId, change) => { - this.sendToCapable(FOLLOW_UP_QUEUE_CAPABILITY, this.followUpQueueFrame(sessionId, change)); - }; this.authorizationExpiryTimer = setInterval( () => this.expireAuthorizationContexts(), AUTHORIZATION_EXPIRY_SWEEP_MS @@ -800,9 +776,18 @@ export class WsHost { body: "expired principal push unbind failed", attributes: { error: error instanceof Error ? error.message : String(error) } })); } + /** + * Refuse new runners from now on. Application shutdown calls it first, so + * nothing starts while the rest of the app drains. + * @internal Host wiring (#2515). + */ + beginClosing(): void { + this.#closing = true; + } + /** Stop host-owned timers during application/test teardown. */ close(): Promise { - this.closing = true; + this.beginClosing(); this.coordinator.cancelAll("Server shutting down"); clearInterval(this.authorizationExpiryTimer); this.scope?.close(); diff --git a/packages/ui-server/src/ws/limits.ts b/packages/ui-server/src/ws/limits.ts new file mode 100644 index 0000000000..adf72f9de0 --- /dev/null +++ b/packages/ui-server/src/ws/limits.ts @@ -0,0 +1,49 @@ +/** + * Host queue limits and turn log attributes. A leaf module (#2515): the + * session runner reads these values without importing the host that runs it, + * so `host → conversation → run-session` never leads back to `host.ts`. + */ + +/** + * Budget for the host-side follow-up queue of ONE session (backends without a + * native `followUp`; with one, messages go into the running turn and none of + * this applies). + * + * Bytes rather than a message count, because that is what the cost actually + * tracks: a queued entry is retained in this process until its turn runs, and + * an entry carrying four images outweighs a hundred carrying text. Counting + * messages made a text-only queue and a 50 MB image queue look identical. + * + * Past the warn mark the message is still accepted — the sender is told the + * queue is getting heavy, in `detail` on the `queued` status and in the server + * log. Past the hard cap it is refused with SESSION_QUEUE_FULL, which is an + * explicit error frame, never a silent drop. + */ +export const QUEUE_WARN_BYTES = 20 * 1024 * 1024; +export const QUEUE_MAX_BYTES = 50 * 1024 * 1024; + +/** + * Backstop on depth. Bytes do not bound COUNT, and every queued entry becomes + * its own turn: without this, ~500k one-line messages fit inside the byte cap + * and would run the session for days. Not the limit anyone should hit. + */ +export const MAX_SESSION_QUEUE = 50; + +/** Identity of one turn, as it appears on a log record. */ +export interface TurnLogContext { + sessionId?: string | null; + turnId?: string | null; + providerId?: string | null; +} + +/** + * Log attributes for one turn. Null fields are omitted rather than stringified + * — a new session has no sessionId until `session_info` names it. + */ +export function turnLogAttributes(turn: TurnLogContext): Record { + return { + ...(turn.sessionId ? { "session.id": turn.sessionId } : {}), + ...(turn.turnId ? { "turn.id": turn.turnId } : {}), + ...(turn.providerId ? { profile: turn.providerId } : {}), + }; +} diff --git a/packages/ui-server/src/ws/recovery.ts b/packages/ui-server/src/ws/recovery.ts index a413bd87ec..3219da385e 100644 --- a/packages/ui-server/src/ws/recovery.ts +++ b/packages/ui-server/src/ws/recovery.ts @@ -44,7 +44,6 @@ export function acceptRequest( backendId: string | null ): number | undefined { if (!host.catalog.acceptWork) return undefined; - const { unorderedSessions } = host.coordinator; const latest = latestAcceptance.get(host.coordinator) ?? new Map(); latestAcceptance.set(host.coordinator, latest); const mine = (latest.get(sessionId) ?? 0) + 1; @@ -52,10 +51,10 @@ export function acceptRequest( const revision = host.catalog.acceptWork(sessionId, requestId ?? null, backendId, (stored) => { if (latest.get(sessionId) !== mine) return; latest.delete(sessionId); - if (stored) unorderedSessions.delete(sessionId); else unorderedSessions.add(sessionId); + host.coordinator.setSessionOrdered(sessionId, stored); }); if (revision === null) { - unorderedSessions.add(sessionId); + host.coordinator.setSessionOrdered(sessionId, false); return undefined; } return revision; @@ -151,14 +150,8 @@ function pendingOf(host: WsHost, sessionId: string): SessionRecoveryPending[] { for (const [toolUseId, p] of coordinator.pendingApprovals) { if (p.turn.sessionId === sessionId) pending.push({ kind: "approval", requestId: toolUseId, turnId: p.turnId }); } - const asks = [ - ["ask_user", coordinator.pendingAskUser], - ["ask_user_list", coordinator.pendingAskUserList], - ["ask_user_rank", coordinator.pendingAskUserRank], - ["ask_user_form", coordinator.pendingAskUserForm], - ] as const; - for (const [kind, map] of asks) { - for (const p of map.values()) { + for (const kind of ["ask_user", "ask_user_list", "ask_user_rank", "ask_user_form"] as const) { + for (const p of coordinator.pendingAsks(kind).values()) { if (p.turn.sessionId === sessionId) pending.push({ kind, requestId: p.requestId, turnId: p.turnId }); } } diff --git a/packages/ui-server/src/ws/resend.ts b/packages/ui-server/src/ws/resend.ts index 87b11b99d7..fc6d53f1ae 100644 --- a/packages/ui-server/src/ws/resend.ts +++ b/packages/ui-server/src/ws/resend.ts @@ -46,22 +46,22 @@ export function resendPendingAsks(host: WsHost, ws: WSContext, sessionId?: strin const { coordinator } = host; const wanted = (p: { turn: { sessionId: string | null } }) => sessionId === undefined || p.turn.sessionId === sessionId; - for (const p of coordinator.pendingAskUser.values()) { + for (const p of coordinator.pendingAsks("ask_user").values()) { if (!wanted(p)) continue; host.sendMessage( ws, withTurnScope({ type: "ask_user_request", requestId: p.requestId, questions: p.questions }, p.turn, p.turnId) ); } - for (const p of coordinator.pendingAskUserList.values()) { + for (const p of coordinator.pendingAsks("ask_user_list").values()) { if (!wanted(p)) continue; host.sendMessage(ws, withTurnScope({ type: "ask_user_list_request", requestId: p.requestId, ...p.request }, p.turn, p.turnId)); } - for (const p of coordinator.pendingAskUserRank.values()) { + for (const p of coordinator.pendingAsks("ask_user_rank").values()) { if (!wanted(p)) continue; host.sendMessage(ws, withTurnScope({ type: "ask_user_rank_request", requestId: p.requestId, ...p.request }, p.turn, p.turnId)); } - for (const p of coordinator.pendingAskUserForm.values()) { + for (const p of coordinator.pendingAsks("ask_user_form").values()) { if (!wanted(p)) continue; host.sendMessage(ws, withTurnScope({ type: "ask_user_form_request", requestId: p.requestId, ...p.request }, p.turn, p.turnId)); } diff --git a/packages/ui-server/src/ws/run-session.ts b/packages/ui-server/src/ws/run-session.ts index a9b89b0025..cbe727c94a 100644 --- a/packages/ui-server/src/ws/run-session.ts +++ b/packages/ui-server/src/ws/run-session.ts @@ -30,18 +30,13 @@ import { resolveTurnTarget } from "./routing.js"; import { withLocalContext } from "./local-exchanges.js"; import { acceptDraft } from "./drafts.js"; import { acceptRequest } from "./recovery.js"; -import type { AuthorizationContext, HostWork, HostWorkOutcome, QueuedFollowUp, RunningTurn } from "./turns.js"; +import type { AuthorizationContext, HostWork, HostWorkOutcome, QueuedFollowUp, RunningTurn, StartingSession } from "./turns.js"; import { queuedBytes, queuedFollowUpBytes, REVOKED_REASON } from "./turns.js"; /** Why a follow-up leaves when its session's slot ends without running it (#1002). */ const SLOT_ENDED_REASON = "The session stopped before it ran."; -import { - MAX_SESSION_QUEUE, - QUEUE_MAX_BYTES, - QUEUE_WARN_BYTES, - turnLogAttributes, - type WsHost, -} from "./host.js"; +import type { WsHost } from "./host.js"; +import { MAX_SESSION_QUEUE, QUEUE_MAX_BYTES, QUEUE_WARN_BYTES, turnLogAttributes } from "./limits.js"; /** * Run one session slot: the initial turn, then any queued follow-up turns in @@ -205,13 +200,12 @@ async function runRetainedSession( initialLifecycle: ReturnType | undefined ): Promise { const { coordinator } = host; - const starting: { queue: QueuedFollowUp[]; cancelled: boolean; revision?: number } = { + const starting: StartingSession = { queue: [], cancelled: false, ...(initial.revision !== undefined ? { revision: initial.revision } : {}), }; - if (initial.sessionId) coordinator.startingBySession.set(initial.sessionId, starting); - coordinator.startingSessions += 1; + coordinator.beginStarting(initial.sessionId, starting); let target: Awaited>; try { target = await resolveTurnTarget(host.registry, host.catalog, initial.sessionId, initial.providerId); @@ -236,10 +230,7 @@ async function runRetainedSession( }); return; } finally { - coordinator.startingSessions = Math.max(0, coordinator.startingSessions - 1); - if (initial.sessionId && coordinator.startingBySession.get(initial.sessionId) === starting) { - coordinator.startingBySession.delete(initial.sessionId); - } + coordinator.endStarting(initial.sessionId, starting); } if (starting.cancelled || host.closing) { @@ -285,8 +276,7 @@ async function runRetainedSession( turn.shareId = initial.shareId; const firstTurnId = turn.turnId; clearTimeout(turn.timeoutHandle); - coordinator.running.add(turn); - if (turn.sessionId) coordinator.bySession.set(turn.sessionId, turn); + coordinator.registerTurn(turn); let profileId = initialProfileId; let resumeId = initial.sessionId; @@ -990,10 +980,7 @@ async function runRetainedSession( coordinator.queueChanged(turn.sessionId, { dropped: { entries: unstarted ? [unstarted, ...queued] : queued, reason: SLOT_ENDED_REASON }, }); - if (turn.sessionId && coordinator.bySession.get(turn.sessionId) === turn) { - coordinator.bySession.delete(turn.sessionId); - } - coordinator.running.delete(turn); + coordinator.unregisterTurn(turn); coordinator.drainPendingForTurn(turn, "Session ended"); } } diff --git a/packages/ui-server/src/ws/turns.ts b/packages/ui-server/src/ws/turns.ts index 26c7773ec0..599ba4a3f4 100644 --- a/packages/ui-server/src/ws/turns.ts +++ b/packages/ui-server/src/ws/turns.ts @@ -346,6 +346,44 @@ export interface PendingAskUserForm { /** The four ask kinds, which share one request-id space. */ export type AskKind = "ask_user" | "ask_user_list" | "ask_user_rank" | "ask_user_form"; +/** One pending ask of any kind. The kinds share one id space, so they share one map. */ +export type PendingAsk = + | { kind: "ask_user"; entry: PendingAskUser } + | { kind: "ask_user_list"; entry: PendingAskUserList } + | { kind: "ask_user_rank"; entry: PendingAskUserRank } + | { kind: "ask_user_form"; entry: PendingAskUserForm }; + +/** The entry type a pending ask of kind `K` carries. */ +export type PendingAskEntry = Extract["entry"]; + +/** A session start reserved before asynchronous backend routing finishes. */ +export interface StartingSession { + queue: QueuedFollowUp[]; + cancelled: boolean; + revision?: number; +} + +/** A handoff creation in flight (#61); `sessionId` is set once its destination exists. */ +export interface PendingHandoff { + sessionId?: string; +} + +/** A running handoff preparation summary (#61). */ +export interface HandoffPreparation { + abort: AbortController; + owner: unknown; +} + +/** What a coordinator reports to, fixed when it is constructed. */ +export interface TurnCoordinatorOptions { + /** Where collisions are reported; absent (a bare coordinator in a test) means silence. */ + log?: Logger; + /** Told about every settled permission request, whichever path settled it. */ + onApprovalSettled?: (toolUseId: string, record: ToolResolutionRecord) => void; + /** Told whenever a session's pending follow-ups change (#1002). */ + onQueueChanged?: (sessionId: string, change: FollowUpQueueChange) => void; +} + /** * What became of an ask request that is no longer pending (#910). Kept so a * repeated or late answer, or a status query after a lost receipt, gets the @@ -388,64 +426,134 @@ export interface PendingMask { reject: (err: Error) => void; } + +/** The ask kinds in the order every per-kind walk visits them. */ +const ASK_KINDS: readonly AskKind[] = ["ask_user", "ask_user_list", "ask_user_rank", "ask_user_form"]; + /** * Mutable turn state for one ws host: the running session slots and every * pending interactive round-trip. This used to be six module-level globals * inside a 976-line handler; as instance state it is testable and owned by an * explicit object with a defined lifecycle. + * + * Every collection is private (#2515). Other modules read it through + * read-only views and change it only through the intent methods below, so + * each invariant (remove before settling, record the outcome, keep the + * starting count and the session index in step) is written once, here. */ export class TurnCoordinator { - /** - * Where collisions are reported. Assigned by the owning WsHost so the - * coordinator reports through the same consumer as everything else; absent - * (a bare coordinator in a test) means silence. - */ - log?: Logger; + readonly #log?: Logger; + readonly #onApprovalSettled?: (toolUseId: string, record: ToolResolutionRecord) => void; + readonly #onQueueChanged?: (sessionId: string, change: FollowUpQueueChange) => void; + + readonly #running = new Set(); + readonly #bySession = new Map(); + #startingSessions = 0; + readonly #startingBySession = new Map(); + readonly #unorderedSessions = new Set(); + readonly #pendingApprovals = new Map(); + readonly #resolvedApprovals = new Map(); + readonly #asks = new Map(); + readonly #pendingLocation = new Map(); + readonly #pendingMask = new Map(); + readonly #handoffs = new Map(); + readonly #handoffPreparations = new Map(); + readonly #askOutcomes = new Map(); + readonly #authorizationRegistry = new Map(); + + constructor(options: TurnCoordinatorOptions = {}) { + this.#log = options.log; + this.#onApprovalSettled = options.onApprovalSettled; + this.#onQueueChanged = options.onQueueChanged; + } + + /** Every running session slot. */ + get running(): ReadonlySet { + return this.#running; + } + + /** Running slots by the session id they have been bound to. */ + get bySession(): ReadonlyMap { + return this.#bySession; + } + + /** Session starts still resolving their backend, counted against the concurrency cap. */ + get startingSessions(): number { + return this.#startingSessions; + } + + /** Known sessions reserved before asynchronous backend routing. */ + get startingBySession(): ReadonlyMap { + return this.#startingBySession; + } - readonly running = new Set(); - readonly bySession = new Map(); - startingSessions = 0; - /** Reserve a known session before asynchronous backend routing. */ - readonly startingBySession = new Map(); /** * Sessions whose newest acceptance could not be recorded (#964). Their * recovery reads `unknown` until a later acceptance is recorded, so an * older persisted request can never stand in for newer work. */ - readonly unorderedSessions = new Set(); + get unorderedSessions(): ReadonlySet { + return this.#unorderedSessions; + } + + /** Permission requests waiting for an answer, by toolUseId. */ + get pendingApprovals(): ReadonlyMap { + return this.#pendingApprovals; + } - readonly pendingApprovals = new Map(); /** Settled permission outcomes by toolUseId, bounded by MAX_RESOLVED_APPROVALS. */ - readonly resolvedApprovals = new Map(); - /** - * Told about every settled permission request, whichever path settled it. - * Assigned by the owning WsHost, which publishes `tool_resolution`. - */ - onApprovalSettled?: (toolUseId: string, record: ToolResolutionRecord) => void; - /** - * Told whenever a session's pending follow-ups change (#1002). Assigned by - * the owning WsHost, which publishes `session_queue`. - */ - onQueueChanged?: (sessionId: string, change: FollowUpQueueChange) => void; - readonly pendingAskUser = new Map(); - readonly pendingAskUserList = new Map(); - readonly pendingAskUserRank = new Map(); - readonly pendingAskUserForm = new Map(); - readonly pendingLocation = new Map(); - readonly pendingMask = new Map(); + get resolvedApprovals(): ReadonlyMap { + return this.#resolvedApprovals; + } + + /** Pending `ask_user` requests, in the order they were opened. */ + get pendingAskUser(): ReadonlyMap { + return this.pendingAsks("ask_user"); + } + + /** Pending `ask_user_list` requests, in the order they were opened. */ + get pendingAskUserList(): ReadonlyMap { + return this.pendingAsks("ask_user_list"); + } + + /** Pending `ask_user_rank` requests, in the order they were opened. */ + get pendingAskUserRank(): ReadonlyMap { + return this.pendingAsks("ask_user_rank"); + } + + /** Pending `ask_user_form` requests, in the order they were opened. */ + get pendingAskUserForm(): ReadonlyMap { + return this.pendingAsks("ask_user_form"); + } + + /** Location requests waiting for the client. */ + get pendingLocation(): ReadonlyMap { + return this.#pendingLocation; + } + + /** Mask requests waiting for the client. */ + get pendingMask(): ReadonlyMap { + return this.#pendingMask; + } + /** * Handoff creations in flight, by client-minted key (#61). Present from * acceptance until the destination is recorded or the attempt ends, so a * repeated key answers `pending` instead of starting a second session. */ - readonly handoffs = new Map(); + get handoffs(): ReadonlyMap { + return this.#handoffs; + } + /** Running handoff preparation summaries, by handoff key (#61). */ - readonly handoffPreparations = new Map(); - /** Settled and closed ask requests, by request id (see AskOutcome). */ - readonly askOutcomes = new Map(); + get handoffPreparations(): ReadonlyMap { + return this.#handoffPreparations; + } /** Every authorization context with at least one live owner or async lease. */ - readonly authorizationRegistry = new Map(); + get authorizationRegistry(): ReadonlyMap { + return this.#authorizationRegistry; + } /** * A session's follow-ups that the agent has not received yet, in send @@ -454,19 +562,19 @@ export class TurnCoordinator { */ pendingFollowUps(sessionId: string): QueuedFollowUp[] { // The same precedence as chat dispatch, which queues into a start first. - const starting = this.startingBySession.get(sessionId); + const starting = this.#startingBySession.get(sessionId); if (starting) return [...starting.queue]; - const turn = this.bySession.get(sessionId); + const turn = this.#bySession.get(sessionId); return turn ? [...(turn.handingOver ? [turn.handingOver] : []), ...turn.queue] : []; } /** Every session that has at least one pending follow-up. */ sessionsWithFollowUps(): string[] { const ids = new Set(); - for (const [sessionId, turn] of this.bySession) { + for (const [sessionId, turn] of this.#bySession) { if (turn.handingOver || turn.queue.length > 0) ids.add(sessionId); } - for (const [sessionId, starting] of this.startingBySession) { + for (const [sessionId, starting] of this.#startingBySession) { if (starting.queue.length > 0) ids.add(sessionId); } return [...ids]; @@ -477,7 +585,7 @@ export class TurnCoordinator { if (!sessionId) return; // Dropping nothing changed nothing. if (change.dropped?.entries.length === 0 && !change.started) return; - this.onQueueChanged?.(sessionId, change); + this.#onQueueChanged?.(sessionId, change); } /** @@ -498,24 +606,87 @@ export class TurnCoordinator { this.queueChanged(sessionId, { dropped: { entries: dropped, reason } }); } + /** + * Count a session start against the concurrency cap and, for a known + * session, reserve it so chat dispatch queues behind it. Pair with + * `endStarting` on every exit. + */ + beginStarting(sessionId: string | null | undefined, starting: StartingSession): void { + if (sessionId) this.#startingBySession.set(sessionId, starting); + this.#startingSessions += 1; + } + + /** End a start begun with `beginStarting`; a newer reservation for the session is kept. */ + endStarting(sessionId: string | null | undefined, starting: StartingSession): void { + this.#startingSessions = Math.max(0, this.#startingSessions - 1); + if (sessionId && this.#startingBySession.get(sessionId) === starting) { + this.#startingBySession.delete(sessionId); + } + } + + /** Make a slot running, indexed by its session once it has one. */ + registerTurn(turn: RunningTurn): void { + this.#running.add(turn); + if (turn.sessionId) this.#bySession.set(turn.sessionId, turn); + } + + /** Index a running slot under the session id its backend just named. */ + bindSession(sessionId: string, turn: RunningTurn): void { + this.#bySession.set(sessionId, turn); + } + + /** Remove an ended slot; a newer slot indexed under the same session is kept. */ + unregisterTurn(turn: RunningTurn): void { + if (turn.sessionId && this.#bySession.get(turn.sessionId) === turn) { + this.#bySession.delete(turn.sessionId); + } + this.#running.delete(turn); + } + + /** Record whether a session's newest acceptance was stored, ordering its recovery (#964). */ + setSessionOrdered(sessionId: string, ordered: boolean): void { + if (ordered) this.#unorderedSessions.delete(sessionId); + else this.#unorderedSessions.add(sessionId); + } + + /** Reserve a handoff key (#61) until `releaseHandoff` is called with the same entry. */ + registerHandoff(handoffId: string, entry: PendingHandoff): void { + this.#handoffs.set(handoffId, entry); + } + + /** Release a handoff key, unless a newer attempt holds it. */ + releaseHandoff(handoffId: string, entry: PendingHandoff): void { + if (this.#handoffs.get(handoffId) === entry) this.#handoffs.delete(handoffId); + } + + /** Track a running handoff preparation summary (#61); it counts as an active run. */ + registerHandoffPreparation(handoffId: string, preparation: HandoffPreparation): void { + this.#handoffPreparations.set(handoffId, preparation); + } + + /** Stop tracking a preparation, unless a newer one holds the key. */ + releaseHandoffPreparation(handoffId: string, abort: AbortController): void { + if (this.#handoffPreparations.get(handoffId)?.abort === abort) this.#handoffPreparations.delete(handoffId); + } + /** Remember what became of an ask request, within the TTL/count bounds. */ recordAskOutcome(outcome: AskOutcome): void { const cutoff = outcome.at - ASK_OUTCOME_TTL_MS; - for (const [id, existing] of this.askOutcomes) { - if (existing.at > cutoff && this.askOutcomes.size < ASK_OUTCOME_MAX) break; - this.askOutcomes.delete(id); + for (const [id, existing] of this.#askOutcomes) { + if (existing.at > cutoff && this.#askOutcomes.size < ASK_OUTCOME_MAX) break; + this.#askOutcomes.delete(id); } // Re-inserting moves the entry to the end, so map order stays age order. - this.askOutcomes.delete(outcome.requestId); - this.askOutcomes.set(outcome.requestId, outcome); + this.#askOutcomes.delete(outcome.requestId); + this.#askOutcomes.set(outcome.requestId, outcome); } /** The outcome for a request id, unless it has aged out. */ askOutcome(requestId: string, now = Date.now()): AskOutcome | undefined { - const outcome = this.askOutcomes.get(requestId); + const outcome = this.#askOutcomes.get(requestId); if (!outcome) return undefined; if (outcome.at <= now - ASK_OUTCOME_TTL_MS) { - this.askOutcomes.delete(requestId); + this.#askOutcomes.delete(requestId); return undefined; } return outcome; @@ -532,21 +703,128 @@ export class TurnCoordinator { }); } + /** The pending ask with this id, of whichever kind. */ + pendingAsk(requestId: string): PendingAsk | undefined { + return this.#asks.get(requestId); + } + + /** Pending asks of one kind, in the order they were opened. */ + pendingAsks(kind: K): ReadonlyMap> { + const asks = new Map>(); + for (const [id, ask] of this.#asks) { + if (ask.kind === kind) asks.set(id, ask.entry as PendingAskEntry); + } + return asks; + } + + /** + * Open an ask unless its id is already pending, and say whether it opened. + * + * The rule differs by kind today, and is preserved here until #2773 rules + * on one: `ask_user` and `ask_user_list` replace their own kind's entry + * from the same turn and refuse (and log) one from another turn, while any + * other pending id refuses every kind without a log. + */ + openAsk(kind: K, entry: PendingAskEntry): boolean { + const existing = this.#asks.get(entry.requestId); + if (existing) { + if (existing.kind !== kind || (kind !== "ask_user" && kind !== "ask_user_list")) return false; + if (this.collides(existing.entry, entry.requestId, entry.turn)) return false; + } + this.#asks.set(entry.requestId, { kind, entry } as PendingAsk); + return true; + } + + /** + * Settle a pending ask with an answer: remove it and record who accepted + * it. The caller resolves the entry's promise with the answer. + */ + acceptAsk(ask: PendingAsk, submission: { submissionId: string; principalId: string }): void { + const { entry } = ask; + if (this.#asks.get(entry.requestId) === ask) this.#asks.delete(entry.requestId); + this.recordAskOutcome({ + requestId: entry.requestId, + sessionId: entry.turn.sessionId, + turnId: entry.turnId, + state: "accepted", + submissionId: submission.submissionId, + principalId: submission.principalId, + at: Date.now(), + }); + } + /** * Remove a pending ask of any kind and record why. Used by dismissal; a * turn ending goes through drainPendingForTurn. */ cancelAsk(requestId: string): void { - const p = - this.pendingAskUser.get(requestId) ?? - this.pendingAskUserList.get(requestId) ?? - this.pendingAskUserRank.get(requestId) ?? - this.pendingAskUserForm.get(requestId); - this.pendingAskUser.delete(requestId); - this.pendingAskUserList.delete(requestId); - this.pendingAskUserRank.delete(requestId); - this.pendingAskUserForm.delete(requestId); - if (p) this.closeAsk(p, "cancelled"); + const p = this.#asks.get(requestId); + this.#asks.delete(requestId); + if (p) this.closeAsk(p.entry, "cancelled"); + } + + /** Open a permission request unless another turn holds its id; says whether it opened. */ + openApproval(toolUseId: string, entry: PendingApproval): boolean { + if (this.collides(this.#pendingApprovals.get(toolUseId), toolUseId, entry.turn)) return false; + this.#pendingApprovals.set(toolUseId, entry); + return true; + } + + /** + * Remove a pending permission request that `accepts` matches, so no other + * path can settle it, and return it. Settle it with `settleApproval`. + */ + claimApproval(toolUseId: string, accepts: (p: PendingApproval) => boolean = () => true): PendingApproval | undefined { + const p = this.#pendingApprovals.get(toolUseId); + if (!p || !accepts(p)) return undefined; + this.#pendingApprovals.delete(toolUseId); + return p; + } + + /** Answer a claimed permission request and record its outcome. */ + settleApproval( + toolUseId: string, + claimed: PendingApproval, + decision: PermissionDecision, + response: { principalId: string; always?: boolean; channel?: ApprovalChannel } + ): void { + claimed.resolve(decision, response); + this.recordApprovalOutcome(toolUseId, { + outcome: decision.behavior === "deny" ? "denied" : "granted", + turnId: claimed.turnId, + sessionId: claimed.turn.sessionId, + ...(response.channel ? { channel: response.channel } : {}), + }); + } + + /** Open a location request unless another turn holds its id; says whether it opened. */ + openLocation(requestId: string, entry: PendingLocation): boolean { + if (this.collides(this.#pendingLocation.get(requestId), requestId, entry.turn)) return false; + this.#pendingLocation.set(requestId, entry); + return true; + } + + /** Remove and return a pending location request that `accepts` matches; the caller settles it. */ + claimLocation(requestId: string, accepts: (p: PendingLocation) => boolean = () => true): PendingLocation | undefined { + const p = this.#pendingLocation.get(requestId); + if (!p || !accepts(p)) return undefined; + this.#pendingLocation.delete(requestId); + return p; + } + + /** Open a mask request unless another turn holds its id; says whether it opened. */ + openMask(requestId: string, entry: PendingMask): boolean { + if (this.collides(this.#pendingMask.get(requestId), requestId, entry.turn)) return false; + this.#pendingMask.set(requestId, entry); + return true; + } + + /** Remove and return a pending mask request that `accepts` matches; the caller settles it. */ + claimMask(requestId: string, accepts: (p: PendingMask) => boolean = () => true): PendingMask | undefined { + const p = this.#pendingMask.get(requestId); + if (!p || !accepts(p)) return undefined; + this.#pendingMask.delete(requestId); + return p; } private locationCounter = 0; @@ -560,18 +838,18 @@ export class TurnCoordinator { return `mask-${Date.now().toString(36)}-${++this.maskCounter}`; } - /** True while any session has a running turn. */ /** * Backend runs occupying the concurrency cap: running and starting turns, * and handoff preparation summaries (#61). Every admission check reads * this, so no kind of run can slip past the others. */ activeRuns(): number { - return this.running.size + this.startingSessions + this.handoffPreparations.size; + return this.#running.size + this.#startingSessions + this.#handoffPreparations.size; } + /** True while any session has a running turn. */ isTurnActive(): boolean { - return this.running.size > 0; + return this.#running.size > 0; } /** Construct and synchronously register a context with its initial reference. */ @@ -580,22 +858,23 @@ export class TurnCoordinator { expiresAt: number; valid: boolean; }): AuthorizationContext { + const registry = this.#authorizationRegistry; let initialReleased = false; const releaseReference = () => { - const count = this.authorizationRegistry.get(authorization); + const count = registry.get(authorization); if (count === undefined) return; - if (count === 1) this.authorizationRegistry.delete(authorization); - else this.authorizationRegistry.set(authorization, count - 1); + if (count === 1) registry.delete(authorization); + else registry.set(authorization, count - 1); }; const authorization: AuthorizationContext = { [authorizationContextBrand]: true, ...input, retain: () => { - const count = this.authorizationRegistry.get(authorization); + const count = registry.get(authorization); if (count === undefined) { throw new Error("Cannot retain a released authorization context"); } - this.authorizationRegistry.set(authorization, count + 1); + registry.set(authorization, count + 1); let released = false; return () => { if (released) return; @@ -609,13 +888,13 @@ export class TurnCoordinator { releaseReference(); }, }; - this.authorizationRegistry.set(authorization, 1); + registry.set(authorization, 1); return authorization; } /** Add principals whose registered authorization context has expired. */ collectExpiredPrincipalIds(now: number, ids: Set): void { - for (const authorization of this.authorizationRegistry.keys()) { + for (const authorization of this.#authorizationRegistry.keys()) { if (authorization.valid && authorization.expiresAt <= now) { ids.add(authorization.principalId); } @@ -624,7 +903,7 @@ export class TurnCoordinator { /** Invalidate every registered context belonging to one of these principals. */ invalidateAuthorizations(principalIds: ReadonlySet): void { - for (const authorization of this.authorizationRegistry.keys()) { + for (const authorization of this.#authorizationRegistry.keys()) { if (principalIds.has(authorization.principalId)) authorization.valid = false; } } @@ -636,7 +915,7 @@ export class TurnCoordinator { revokePrincipals(principalIds: ReadonlySet): RunningTurn[] { const affectedRunning: RunningTurn[] = []; this.invalidateAuthorizations(principalIds); - for (const turn of this.running) { + for (const turn of this.#running) { if (principalIds.has(turn.principalId)) { affectedRunning.push(turn); } @@ -654,17 +933,27 @@ export class TurnCoordinator { return affectedRunning; } - /** Cancel every running turn (used on shutdown). */ + /** + * Cancel every running turn and session start (used on shutdown), then + * settle any pending request whose turn is no longer running, so nothing a + * caller awaits is left unsettled. Returns whether any turn or start was + * cancelled. + */ cancelAll(reason: string): boolean { - const hadWork = this.running.size > 0 || this.startingBySession.size > 0; - for (const [sessionId, starting] of this.startingBySession) { + const hadWork = this.#running.size > 0 || this.#startingBySession.size > 0; + for (const [sessionId, starting] of this.#startingBySession) { starting.cancelled = true; // Release, never truncate: each entry's lease settles host work it carries. this.dropStartingQueue(sessionId, starting, reason); } - if (!hadWork) return false; - for (const turn of [...this.running]) this.cancelTurn(turn, reason); - return true; + for (const turn of [...this.#running]) this.cancelTurn(turn, reason); + const orphaned = new Set(); + for (const p of this.#pendingApprovals.values()) orphaned.add(p.turn); + for (const p of this.#asks.values()) orphaned.add(p.entry.turn); + for (const p of this.#pendingLocation.values()) orphaned.add(p.turn); + for (const p of this.#pendingMask.values()) orphaned.add(p.turn); + for (const turn of orphaned) this.drainPendingForTurn(turn, reason); + return hadWork; } /** Cancel a session's current turn and drop its queued follow-ups. */ @@ -690,49 +979,34 @@ export class TurnCoordinator { /** Record a settled permission outcome and tell the host. */ recordApprovalOutcome(toolUseId: string, record: ToolResolutionRecord): void { - this.resolvedApprovals.delete(toolUseId); - this.resolvedApprovals.set(toolUseId, record); - while (this.resolvedApprovals.size > MAX_RESOLVED_APPROVALS) { - const oldest = this.resolvedApprovals.keys().next().value; + this.#resolvedApprovals.delete(toolUseId); + this.#resolvedApprovals.set(toolUseId, record); + while (this.#resolvedApprovals.size > MAX_RESOLVED_APPROVALS) { + const oldest = this.#resolvedApprovals.keys().next().value; if (oldest === undefined) break; - this.resolvedApprovals.delete(oldest); + this.#resolvedApprovals.delete(oldest); } - this.onApprovalSettled?.(toolUseId, record); + this.#onApprovalSettled?.(toolUseId, record); } /** Resolve/reject every pending interactive request belonging to one turn. */ drainPendingForTurn(turn: RunningTurn, reason: string): void { - for (const [id, p] of this.pendingApprovals) { + for (const [id, p] of this.#pendingApprovals) { if (p.turn !== turn) continue; p.resolve({ behavior: "deny", message: reason }); - this.pendingApprovals.delete(id); + this.#pendingApprovals.delete(id); // A terminal turn settles its own cards: no tool_result is coming, and // a client must be able to clear the card without waiting for one. this.recordApprovalOutcome(id, { outcome: "expired", turnId: p.turnId, sessionId: p.turn.sessionId, reason }); } - for (const [id, p] of this.pendingAskUser) { - if (p.turn !== turn) continue; - p.reject(new Error(reason)); - this.pendingAskUser.delete(id); - this.closeAsk(p, "ended"); - } - for (const [id, p] of this.pendingAskUserList) { - if (p.turn !== turn) continue; - p.reject(new Error(reason)); - this.pendingAskUserList.delete(id); - this.closeAsk(p, "ended"); - } - for (const [id, p] of this.pendingAskUserRank) { - if (p.turn !== turn) continue; - p.reject(new Error(reason)); - this.pendingAskUserRank.delete(id); - this.closeAsk(p, "ended"); - } - for (const [id, p] of this.pendingAskUserForm) { - if (p.turn !== turn) continue; - p.reject(new Error(reason)); - this.pendingAskUserForm.delete(id); - this.closeAsk(p, "ended"); + // Kind by kind, in the order the per-kind maps were once drained. + for (const kind of ASK_KINDS) { + for (const [id, { kind: pendingKind, entry: p }] of this.#asks) { + if (pendingKind !== kind || p.turn !== turn) continue; + p.reject(new Error(reason)); + this.#asks.delete(id); + this.closeAsk(p, "ended"); + } } this.drainClientBoundForTurn(turn, reason); } @@ -748,15 +1022,15 @@ export class TurnCoordinator { * re-deliver on reconnect. */ drainClientBoundForTurn(turn: RunningTurn, reason: string): void { - for (const [id, p] of this.pendingLocation) { + for (const [id, p] of this.#pendingLocation) { if (p.turn !== turn) continue; p.reject(new Error(reason)); - this.pendingLocation.delete(id); + this.#pendingLocation.delete(id); } - for (const [id, p] of this.pendingMask) { + for (const [id, p] of this.#pendingMask) { if (p.turn !== turn) continue; p.reject(new Error(reason)); - this.pendingMask.delete(id); + this.#pendingMask.delete(id); } } @@ -768,14 +1042,9 @@ export class TurnCoordinator { * a future backend broke that invariant — fail the new request loudly rather * than silently overwriting (and thus resolving) another turn's entry. */ - collidesAcrossTurns( - map: Map, - id: string, - turn: RunningTurn - ): boolean { - const existing = map.get(id); + private collides(existing: { turn: RunningTurn } | undefined, id: string, turn: RunningTurn): boolean { if (existing && existing.turn !== turn) { - this.log?.emit({ + this.#log?.emit({ severityText: "ERROR", body: "interactive id collision: already pending for another turn", attributes: { "request.id": id }, @@ -784,34 +1053,4 @@ export class TurnCoordinator { } return false; } - - /** Test seam: abort everything and clear all turn/pending state. */ - reset(): void { - for (const turn of [...this.running]) { - clearTimeout(turn.timeoutHandle); - turn.abortController.abort(); - for (const entry of turn.queue.splice(0)) entry.releaseAuthorization(); - } - for (const starting of this.startingBySession.values()) { - starting.cancelled = true; - // Release, never truncate: each entry's lease settles host work it carries. - for (const entry of starting.queue.splice(0)) entry.releaseAuthorization(); - } - this.startingBySession.clear(); - this.unorderedSessions.clear(); - this.running.clear(); - this.bySession.clear(); - this.pendingApprovals.clear(); - this.resolvedApprovals.clear(); - this.pendingAskUser.clear(); - this.pendingAskUserList.clear(); - this.pendingAskUserRank.clear(); - this.pendingAskUserForm.clear(); - this.askOutcomes.clear(); - this.pendingLocation.clear(); - for (const preparation of this.handoffPreparations.values()) preparation.abort.abort(); - this.handoffPreparations.clear(); - this.handoffs.clear(); - this.startingSessions = 0; - } } diff --git a/packages/ui-server/tests/app-writes-offloop.test.ts b/packages/ui-server/tests/app-writes-offloop.test.ts index 882c92ce60..2e395693d4 100644 --- a/packages/ui-server/tests/app-writes-offloop.test.ts +++ b/packages/ui-server/tests/app-writes-offloop.test.ts @@ -18,6 +18,7 @@ import { watchWriteSites } from "./helpers/write-sites.js"; import type { Logger } from "@opentelemetry/api-logs"; import { createPrincipal } from "../src/db/principals.js"; import { createSessionCatalog } from "../src/ws/session-catalog.js"; +import { TurnCoordinator } from "../src/ws/turns.js"; import { createSessionProfiles, SessionProfileError } from "../src/ws/session-profiles.js"; import { expectRejection } from "./helpers/expect-rejection.js"; import { createPolicyProposals } from "../src/brain/policy-proposal.js"; @@ -238,7 +239,7 @@ test("history readers wait for pending catalog writes; a failed acceptance's rev try { db.exec("CREATE TRIGGER refuse_odysseus BEFORE INSERT ON session_work WHEN NEW.request_id = 'refused' BEGIN SELECT RAISE(ABORT, 'Scylla'); END"); const catalog = createSessionCatalog(() => db, quietLog); - const host = { catalog, coordinator: { unorderedSessions: new Set() } } as never as Parameters[0]; + const host = { catalog, coordinator: new TurnCoordinator() } as never as Parameters[0]; expect(acceptRequest(host, "troy", "refused", null), "WORK_FAILED_ACCEPTANCE_HAS_A_REVISION").toBe(1); await catalog.settled!(); expect(host.coordinator.unorderedSessions.has("troy"), "WORK_FAILED_ACCEPTANCE_UNORDERS").toBe(true); @@ -291,7 +292,7 @@ test("only a session's newest acceptance orders or unorders it", () => { const settle: Array<(stored: boolean) => void> = []; let next: number | null = 1; const host = { catalog: { acceptWork: (_s: string, _r: string | null, _b: string | null, settled?: (stored: boolean) => void) => { settle.push(settled!); return next; } }, - coordinator: { unorderedSessions: new Set() } } as never as Parameters[0]; + coordinator: new TurnCoordinator() } as never as Parameters[0]; expect(acceptRequest(host, "troy", "req-1", null)).toBe(1); next = null; expect(acceptRequest(host, "troy", "req-2", null), "WORK_UNASSIGNED_ACCEPTANCE").toBeUndefined(); diff --git a/packages/ui-server/tests/gemini-conversation.test.ts b/packages/ui-server/tests/gemini-conversation.test.ts index 6ad6e4785d..6fd0c3e8ba 100644 --- a/packages/ui-server/tests/gemini-conversation.test.ts +++ b/packages/ui-server/tests/gemini-conversation.test.ts @@ -506,7 +506,7 @@ test.each(["text", "binary"] as const)("real %s adapter and host keep chat progr } }); const host = new WsHost({ registry: createStaticBackendRegistry([backend], "fake"), catalog: createSessionCatalog(() => db), conversationProvider: f.provider }); const oldCleanup = cleanup!; - cleanup = async () => { release(); host.coordinator.reset(); await host.close(); db.close(); await oldCleanup(); }; + cleanup = async () => { release(); await host.close(); db.close(); await oldCleanup(); }; const handlers = createWsHandlers(host, testPrincipal()); const frames: any[] = []; const ws = { send: (data: string) => frames.push(JSON.parse(data)) } as WSContext; diff --git a/packages/ui-server/tests/gpt-live-conversation.test.ts b/packages/ui-server/tests/gpt-live-conversation.test.ts index 789b31b9d0..a35ba88c96 100644 --- a/packages/ui-server/tests/gpt-live-conversation.test.ts +++ b/packages/ui-server/tests/gpt-live-conversation.test.ts @@ -224,7 +224,7 @@ test("real adapter and host keep chat progress and a question interactive while } }); const host = new WsHost({ registry: createStaticBackendRegistry([backend], "fake"), catalog: createSessionCatalog(() => db), conversationProvider: f.provider }); const oldCleanup = cleanup!; - cleanup = async () => { release(); host.coordinator.reset(); await host.close(); db.close(); await oldCleanup(); }; + cleanup = async () => { release(); await host.close(); db.close(); await oldCleanup(); }; const handlers = createWsHandlers(host, testPrincipal()); const frames: any[] = []; const ws = { send: (data: string) => frames.push(JSON.parse(data)) } as WSContext; diff --git a/packages/ui-server/tests/helpers/contextual-refusals.ts b/packages/ui-server/tests/helpers/contextual-refusals.ts index 87846663db..6b30922ad3 100644 --- a/packages/ui-server/tests/helpers/contextual-refusals.ts +++ b/packages/ui-server/tests/helpers/contextual-refusals.ts @@ -32,7 +32,7 @@ export async function contextualRefusals(provider: "gemini" | "gpt", mode: "miss const save = host.catalog.saveConversationTask!.bind(host.catalog); Object.defineProperty(host.catalog, "saveConversationTask", { value: (principal: string, receipt: Parameters[1]) => rejectAdmission && receipt.state === "queued" ? Promise.reject(new Error("Fixture admission storage failure")) : save(principal, receipt) }); - registerCleanup(async () => { for (const release of releases) release(); host.coordinator.reset(); await host.close(); db.close(); }); + registerCleanup(async () => { for (const release of releases) release(); await host.close(); db.close(); }); const frames: any[] = []; const ws = { send: (data: string) => frames.push(JSON.parse(data)) } as WSContext; const handlers = createWsHandlers(host, testPrincipal()); diff --git a/packages/ui-server/tests/helpers/test-host.ts b/packages/ui-server/tests/helpers/test-host.ts index 9a39020141..51e0867e9b 100644 --- a/packages/ui-server/tests/helpers/test-host.ts +++ b/packages/ui-server/tests/helpers/test-host.ts @@ -81,7 +81,6 @@ export function setToolPermissionsForTests(tp: ToolPermissions | null): void { /** Drop host, registry and cap back to pristine (db handled separately). */ export function resetForTests(): void { - host?.coordinator.reset(); host?.close(); host = null; registry = null; diff --git a/packages/ui-server/tests/host-capability-note.test.ts b/packages/ui-server/tests/host-capability-note.test.ts index 7d4ae96e72..2abcbc42d3 100644 --- a/packages/ui-server/tests/host-capability-note.test.ts +++ b/packages/ui-server/tests/host-capability-note.test.ts @@ -59,8 +59,8 @@ test("actual hosted admission supplies only real journal/revert capabilities, in await parity(app.wsHost,true,true); // A restoration service without a journal cannot promise recovery either. for(const [withJournal,withRevert] of [[true,false],[false,true],[false,false]] as const) { - const host=new WsHost({brainPath:brain,registry,catalog:app.wsHost.catalog,governedTurns:app.wsHost.governedTurns,conversationProvider:live.provider,...(withJournal?{journal:app.wsHost.journal}: {})}); - host.turnReverts=withRevert?app.wsHost.turnReverts:undefined;extraHosts.push(host); + const host=new WsHost({brainPath:brain,registry,catalog:app.wsHost.catalog,governedTurns:app.wsHost.governedTurns,conversationProvider:live.provider,...(withJournal?{journal:app.wsHost.journal}: {}),...(withRevert?{turnReverts:app.wsHost.turnReverts}:{})}); + extraHosts.push(host); await parity(host,withJournal,false); } }finally{for(const host of extraHosts)await host.close();await app.close();await rm(root,{recursive:true,force:true});} diff --git a/packages/ui-server/tests/live-history-track.test.ts b/packages/ui-server/tests/live-history-track.test.ts index 67f25ed4e7..f7f443378c 100644 --- a/packages/ui-server/tests/live-history-track.test.ts +++ b/packages/ui-server/tests/live-history-track.test.ts @@ -53,5 +53,5 @@ test("live history keeps track-file native identity joins before source normaliz expect(live.at(-1)!.failure,"LIVE_HISTORY_RETAINS_NATIVE_FAILURE_JOIN").toEqual(ordinary.at(-1)!.failure); expect(live.at(-1)!.toolCalls).toEqual(ordinary.at(-1)!.toolCalls); expect(env!.items.filter(i=>i.kind === "typed").map(i=>i.text)).toContain("The loop is short."); - } finally { host.coordinator.reset(); await host.close(); db.close(); rmSync(root,{recursive:true,force:true}); } + } finally { await host.close(); db.close(); rmSync(root,{recursive:true,force:true}); } }); diff --git a/packages/ui-server/tests/run-session.test.ts b/packages/ui-server/tests/run-session.test.ts index 2525c67bbc..4ad63e55d2 100644 --- a/packages/ui-server/tests/run-session.test.ts +++ b/packages/ui-server/tests/run-session.test.ts @@ -163,8 +163,7 @@ function queuedFollowUp( } function installParkedTurn(host: WsHost, turn: RunningTurn): void { - host.coordinator.running.add(turn); - host.coordinator.bySession.set("session-1", turn); + host.coordinator.registerTurn(turn); } describe("runSession", () => { @@ -660,7 +659,7 @@ describe("handleChatMessage concurrency", () => { const { host, sent, ws } = setupHost(backend, { maxConcurrentSessions: 2 }); const existing = parkedTurn(backend); installParkedTurn(host, existing); - host.coordinator.startingSessions = 1; + host.coordinator.beginStarting(undefined, { queue: [], cancelled: false }); await handleChatMessage(host, ws, { text: "new session", @@ -677,7 +676,7 @@ describe("handleChatMessage concurrency", () => { sessionId: "session-2", }, ]); - host.coordinator.reset(); + host.coordinator.cancelAll("Test teardown"); }); }); @@ -708,7 +707,7 @@ describe("runSession follow-up queue boundaries", () => { expect(queuedStatuses(sent)).toHaveLength(1); expect(queueErrors(sent)).toHaveLength(1); expect(queueErrors(sent)[0]!.message).toContain("queue is full (50 messages)"); - host.coordinator.reset(); + host.coordinator.cancelAll("Test teardown"); }); test("the warning starts at 20.0 MB and the message remains queued", async () => { @@ -737,7 +736,7 @@ describe("runSession follow-up queue boundaries", () => { expect( observability.logs.count({ severity: "WARN", body: "session follow-up queue is heavy" }) ).toBe(1); - host.coordinator.reset(); + host.coordinator.cancelAll("Test teardown"); }); test("one byte below 20.0 MB has no warning or queued-status detail", async () => { @@ -765,7 +764,7 @@ describe("runSession follow-up queue boundaries", () => { expect( observability.logs.count({ severity: "WARN", body: "session follow-up queue is heavy" }) ).toBe(0); - host.coordinator.reset(); + host.coordinator.cancelAll("Test teardown"); }); test("exactly 50.0 MB is accepted and the next byte is rejected", async () => { @@ -796,7 +795,7 @@ describe("runSession follow-up queue boundaries", () => { expect(queueErrors(sent)).toHaveLength(1); expect(queueErrors(sent)[0]!.message).toContain("50.0 MB of 50.0 MB"); expect(queueErrors(sent)[0]!.message).toContain("this message needs 0.0 MB"); - host.coordinator.reset(); + host.coordinator.cancelAll("Test teardown"); }); }); diff --git a/packages/ui-server/tests/session-start-reliability.test.ts b/packages/ui-server/tests/session-start-reliability.test.ts index f88fbb386d..0e693cfbe3 100644 --- a/packages/ui-server/tests/session-start-reliability.test.ts +++ b/packages/ui-server/tests/session-start-reliability.test.ts @@ -14,7 +14,7 @@ async function until(check: () => boolean) { throw new Error("condition timed out"); } const hosts: WsHost[] = []; -afterEach(() => { for (const host of hosts.splice(0)) host.coordinator.reset(); }); +afterEach(() => { for (const host of hosts.splice(0)) void host.close(); }); const principal = testPrincipal(); const connection = { principal, authorization: testAuthorization(principal.id) }; diff --git a/packages/ui-server/tests/turn-coordinator.test.ts b/packages/ui-server/tests/turn-coordinator.test.ts new file mode 100644 index 0000000000..0c27ea0dc3 --- /dev/null +++ b/packages/ui-server/tests/turn-coordinator.test.ts @@ -0,0 +1,118 @@ +/** + * Coordinator ownership (#2515): teardown settles everything a caller awaits, + * and the session runner never imports the host that runs it for values. + */ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import type { AgentBackend, BackendBridge } from "@schlessera/brain-ui-sdk/server"; +import { createWsHandlers } from "../src/ws/connection"; +import type { RunningTurn } from "../src/ws/turns"; +import { closeDb, resetForTests, setBackendForTests, testHost } from "./helpers/test-host"; +import { testPrincipal } from "./helpers/principal"; + +/** How a request settled within a second: its rejection message, "resolved", or "unsettled". */ +function settlement(request: Promise): Promise { + return Promise.race([ + request.then(() => "resolved", (error: unknown) => (error instanceof Error ? error.message : String(error))), + Bun.sleep(1_000).then(() => "unsettled"), + ]); +} + +async function until(condition: () => boolean): Promise { + for (let i = 0; i < 200; i++) { + if (condition()) return; + await Bun.sleep(5); + } + throw new Error("host did not start the scripted turn"); +} + +describe("closing a host settles pending mask requests", () => { + beforeEach(() => { resetForTests(); closeDb(); }); + afterEach(() => { resetForTests(); closeDb(); }); + + test("a running turn's pending mask request rejects when the host closes", async () => { + const bridges: BackendBridge[] = []; + 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 }) { + bridge.emit({ type: "session_info", sessionId: "aeaea", isNew: true }); + bridges.push(bridge); + await new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true })); + }, + async listSessions() { return []; }, + async getHistory() { return []; }, + }; + setBackendForTests(backend); + const host = testHost(); + const handlers = createWsHandlers(host, testPrincipal()); + await handlers.onOpen({} as Event, { send() {} }); + handlers.onMessage({ data: JSON.stringify({ type: "chat_message", text: "Mark the sail" }) } as MessageEvent, { send() {} }); + await until(() => bridges.length === 1); + + const mask = bridges[0]!.requestMask!("assets/sail.png", "The torn corner"); + await until(() => host.coordinator.pendingMask.size === 1); + await host.close(); + + expect(await settlement(mask), "MASK_SETTLED_ON_CLOSE").toBe("Server shutting down"); + expect(host.coordinator.pendingMask.size).toBe(0); + }); + + test("a mask request whose turn is not running still rejects when the host closes", async () => { + setBackendForTests({ id: "fake" } as AgentBackend); + const host = testHost(); + // A turn no slot owns: before #2515 the test-only reset() dropped such an + // entry without settling it, and cancelAll() never reached it. + const turn = { turnId: "circe-turn", sessionId: null } as RunningTurn; + const mask = new Promise((resolve, reject) => { + expect(host.coordinator.openMask("mask-circe", { turn, turnId: turn.turnId, resolve, reject })).toBe(true); + }); + await host.close(); + + expect(await settlement(mask), "MASK_SETTLED_ON_CLOSE").toBe("Server shutting down"); + expect(host.coordinator.pendingMask.size).toBe(0); + }); +}); + +/** + * Relative imports a module needs at runtime. The TypeScript transpiler drops + * `import type` and imports used only as types, exactly as Bun does when it + * loads the module. + */ +function valueImports(file: string): string[] { + const transpiler = new Bun.Transpiler({ loader: "ts" }); + return transpiler + .scanImports(readFileSync(file, "utf8")) + .map((entry) => entry.path) + .filter((path) => path.startsWith(".")) + .map((path) => resolve(dirname(file), path.replace(/\.js$/, ".ts"))); +} + +describe("ws module graph", () => { + const packageSrc = join(import.meta.dir, "../src"); + const src = join(packageSrc, "ws"); + + test("run-session has no value import from host", () => { + expect(valueImports(join(src, "run-session.ts"))).not.toContain(join(src, "host.ts")); + }); + + test("no value-import cycle leads from host back to host", () => { + const host = join(src, "host.ts"); + const seen = new Set(); + const cycles: string[][] = []; + const walk = (file: string, path: string[]) => { + for (const next of valueImports(file)) { + if (next === host) cycles.push([...path, next]); + else if (!seen.has(next) && next.startsWith(packageSrc)) { + seen.add(next); + walk(next, [...path, next]); + } + } + }; + walk(host, [host]); + expect(cycles.map((cycle) => cycle.map((file) => file.slice(packageSrc.length + 1)).join(" → "))).toEqual([]); + }); +}); diff --git a/packages/ui-server/tests/turn-data-tree.test.ts b/packages/ui-server/tests/turn-data-tree.test.ts index 83422716b6..65fbfeb936 100644 --- a/packages/ui-server/tests/turn-data-tree.test.ts +++ b/packages/ui-server/tests/turn-data-tree.test.ts @@ -109,7 +109,7 @@ async function hostedTurn(f: Fixture, profile: "strict" | "governed", script: Sc const approve = async (pending: Promise): Promise => { const deadline = Date.now() + 10_000; while (!ws!.coordinator.pendingApprovals.size) { if (Date.now() > deadline) throw new Error("no approval requested"); await Bun.sleep(5); } - for (const [id, entry] of ws!.coordinator.pendingApprovals) { ws!.coordinator.pendingApprovals.delete(id); entry.resolve({ behavior: "allow" }); } + for (const id of [...ws!.coordinator.pendingApprovals.keys()]) ws!.coordinator.claimApproval(id)!.resolve({ behavior: "allow" }); return pending; }; const backend = { ...makeFakeBackend({ id: "claude", startTurn: async request => { diff --git a/packages/ui-server/tests/ws-allowlist-enforcement.test.ts b/packages/ui-server/tests/ws-allowlist-enforcement.test.ts index a0d3075225..06eb12d35b 100644 --- a/packages/ui-server/tests/ws-allowlist-enforcement.test.ts +++ b/packages/ui-server/tests/ws-allowlist-enforcement.test.ts @@ -361,7 +361,6 @@ describe("a refused always-allow is recorded", () => { close = () => { // A failed assertion skips the test's own finish(): drop the turn and // its pending approval here so the timeout does not outlive the test. - host.coordinator.reset(); host.close(); db.close(); }; diff --git a/packages/ui-server/tests/ws-approval-channel.test.ts b/packages/ui-server/tests/ws-approval-channel.test.ts index a16d2d5f2b..c17b71e955 100644 --- a/packages/ui-server/tests/ws-approval-channel.test.ts +++ b/packages/ui-server/tests/ws-approval-channel.test.ts @@ -89,7 +89,6 @@ function setup() { const ws = fakeSocket(); cleanup = () => { state.finish(); - host.coordinator.reset(); host.close(); stream.close(); db.close(); diff --git a/packages/ui-server/tests/ws-conversation.test.ts b/packages/ui-server/tests/ws-conversation.test.ts index c184025daa..f1aeea5437 100644 --- a/packages/ui-server/tests/ws-conversation.test.ts +++ b/packages/ui-server/tests/ws-conversation.test.ts @@ -80,7 +80,6 @@ function setup(options: { }); cleanup = async () => { for (const turn of turns) turn.answer(""); - host.coordinator.reset(); await host.close(); db.close(); }; @@ -602,7 +601,7 @@ describe("second review pass: identity, resync and retry", () => { }, }); const host = new WsHost({ registry: createStaticBackendRegistry([backend], "fake"), catalog: createSessionCatalog(() => db), conversationProvider: live.provider }); - cleanup = async () => { host.coordinator.reset(); await host.close(); db.close(); }; + cleanup = async () => { await host.close(); db.close(); }; const handlers = createWsHandlers(host, testPrincipal()); const sent: string[] = []; const ws = { send: (d: string) => sent.push(d) } as WSContext; @@ -641,7 +640,7 @@ describe("third review pass: failure, metering and teardown", () => { }, }); const host = new WsHost({ registry: createStaticBackendRegistry([backend], "fake"), catalog: createSessionCatalog(() => db), conversationProvider: live.provider }); - cleanup = async () => { host.coordinator.reset(); await host.close(); db.close(); }; + cleanup = async () => { await host.close(); db.close(); }; const handlers = createWsHandlers(host, testPrincipal()); const sent: string[] = []; const ws = { send: (d: string) => sent.push(d) } as WSContext; @@ -805,7 +804,7 @@ describe("fifth review pass: cancellation and follow-up boundaries", () => { }, }); const host = new WsHost({ registry: createStaticBackendRegistry([backend], "fake"), catalog: createSessionCatalog(() => db), conversationProvider: live.provider }); - cleanup = async () => { for (const t of turns) t.answer(""); host.coordinator.reset(); await host.close(); db.close(); }; + cleanup = async () => { for (const t of turns) t.answer(""); await host.close(); db.close(); }; const handlers = createWsHandlers(host, testPrincipal()); const sent: string[] = []; const ws = { send: (d: string) => sent.push(d) } as WSContext; @@ -979,7 +978,7 @@ describe("permission authority stays with the host", () => { }, }); const host = new WsHost({ registry: createStaticBackendRegistry([backend], "fake"), catalog: createSessionCatalog(() => db), conversationProvider: live.provider }); - cleanup = async () => { host.coordinator.reset(); await host.close(); db.close(); }; + cleanup = async () => { await host.close(); db.close(); }; const handlers = createWsHandlers(host, testPrincipal()); const sent: string[] = []; const ws = { send: (d: string) => sent.push(d) } as WSContext; @@ -1026,7 +1025,7 @@ describe("permission authority stays with the host", () => { }, }); const host = new WsHost({ registry: createStaticBackendRegistry([backend], "fake"), catalog: createSessionCatalog(() => db), conversationProvider: live.provider }); - cleanup = async () => { host.coordinator.reset(); await host.close(); db.close(); }; + cleanup = async () => { await host.close(); db.close(); }; const handlers = createWsHandlers(host, testPrincipal()); const sent: string[] = []; const ws = { send: (d: string) => sent.push(d) } as WSContext; diff --git a/packages/ui-server/tests/ws-follow-up-queue.test.ts b/packages/ui-server/tests/ws-follow-up-queue.test.ts index ab3724651c..57dd597b37 100644 --- a/packages/ui-server/tests/ws-follow-up-queue.test.ts +++ b/packages/ui-server/tests/ws-follow-up-queue.test.ts @@ -56,7 +56,6 @@ function setup() { }); cleanup = () => { for (const finish of finishers) finish(); - host.coordinator.reset(); host.close(); db.close(); }; @@ -263,9 +262,10 @@ describe("session_queue", () => { const s = setup(); const entry = { followUpId: "fu-1", requestId: "req-winds", text: "Ask Aeolus", attachments: [], queuedAt: 1 } as never; const queued = { followUpId: "fu-2", requestId: "req-bag", text: "Keep the bag shut", attachments: [], queuedAt: 2 } as never; - s.host.coordinator.bySession.set(SESSION, { handingOver: entry, queue: [queued] } as never); + const slot = { sessionId: SESSION, handingOver: entry, queue: [queued] } as never; + s.host.coordinator.bindSession(SESSION, slot); expect(s.host.followUpQueueFrame(SESSION).followUps.map((f) => f.requestId)).toEqual(["req-winds", "req-bag"]); expect(s.host.coordinator.sessionsWithFollowUps()).toEqual([SESSION]); - s.host.coordinator.bySession.delete(SESSION); + s.host.coordinator.unregisterTurn(slot); }); }); diff --git a/packages/ui-server/tests/ws-handoff.test.ts b/packages/ui-server/tests/ws-handoff.test.ts index 4c32611cdc..b89b2991cf 100644 --- a/packages/ui-server/tests/ws-handoff.test.ts +++ b/packages/ui-server/tests/ws-handoff.test.ts @@ -224,7 +224,7 @@ function rig(options: RigOptions = {}): Rig { }); // One handler set per socket: each owns its connection state, like a real upgrade. const handlersFor = new Map>(); - teardown = () => { host.coordinator.reset(); host.close(); stream.close(); db.close(); rmSync(brain, { recursive: true, force: true }); }; + teardown = () => { host.close(); stream.close(); db.close(); rmSync(brain, { recursive: true, force: true }); }; return { host, db, store, stream, brain, scripts, starts, open() { diff --git a/packages/ui-server/tests/ws-live-policy-parity.test.ts b/packages/ui-server/tests/ws-live-policy-parity.test.ts index c390d94d2a..f94036feee 100644 --- a/packages/ui-server/tests/ws-live-policy-parity.test.ts +++ b/packages/ui-server/tests/ws-live-policy-parity.test.ts @@ -131,7 +131,7 @@ for (const backendId of ["claude", "pi"] as const) { expect(calls, "LIVE_POLICY_NO_EFFECT_REPLAY").toBe(1); } } finally { - host.coordinator.reset(); await host.close(); db.close(); rmSync(root, { recursive: true, force: true }); + await host.close(); db.close(); rmSync(root, { recursive: true, force: true }); } }); } diff --git a/packages/ui-server/tests/ws-pill-labels.test.ts b/packages/ui-server/tests/ws-pill-labels.test.ts index 73424d23fe..276a5f0b3b 100644 --- a/packages/ui-server/tests/ws-pill-labels.test.ts +++ b/packages/ui-server/tests/ws-pill-labels.test.ts @@ -92,7 +92,6 @@ function setup(options: { labeller?: boolean; fail?: boolean; namingDelayMs?: nu cleanup = () => { for (const finish of finishers) finish(); for (const release of held) release(); - host.coordinator.reset(); host.close(); db.close(); }; diff --git a/packages/ui-server/tests/ws-promoted-block-replay.test.ts b/packages/ui-server/tests/ws-promoted-block-replay.test.ts index 5b153e7964..c8b99eb0d3 100644 --- a/packages/ui-server/tests/ws-promoted-block-replay.test.ts +++ b/packages/ui-server/tests/ws-promoted-block-replay.test.ts @@ -110,7 +110,7 @@ for (const order of ["classification-first", "promotion-first", "no-promotion"] if (order === "no-promotion") expect(blocks).toEqual(live.blocks); } finally { releaseClassification(); - host.coordinator.reset(); host.close(); db.close(); + host.close(); db.close(); } }); } @@ -187,6 +187,6 @@ test("delayed classification and promotion stay with their turn after queued slo expect(history.messages[2]!.blocks).toBeUndefined(); } finally { releaseFirstTurn(); releaseFirstClassification(); - host.coordinator.reset(); host.close(); db.close(); + host.close(); db.close(); } }); diff --git a/packages/ui-server/tests/ws-revocation.test.ts b/packages/ui-server/tests/ws-revocation.test.ts index 71037cd745..5760064c32 100644 --- a/packages/ui-server/tests/ws-revocation.test.ts +++ b/packages/ui-server/tests/ws-revocation.test.ts @@ -368,7 +368,7 @@ describe("principal revocation boundary", () => { bystanderHandlers.onClose({ code: 1000 } as CloseEvent, bystanderSocket.ws); handlers.onClose({ code: 1008 } as CloseEvent, socket.ws); - host.coordinator.reset(); + host.coordinator.cancelAll("Test teardown"); }); test("revocation during asynchronous routing prevents startTurn", async () => { @@ -524,7 +524,7 @@ describe("principal revocation boundary", () => { expect(lifecycle.hostEvents).toContainEqual(expect.objectContaining({kind:"turn_cancelled",principalId:"owner-b"})); expect(lifecycle.backendRunId).toBeNull(); expect(store.snapshotRun(lifecycle.turnId)).toBeNull(); - host.coordinator.reset(); + host.coordinator.cancelAll("Test teardown"); }); test("revocation keeps a running turn, drops its sender's queued work, and runs another sender's", async () => { @@ -909,8 +909,8 @@ describe("principal revocation boundary", () => { lastResult: null, }; let decision: PermissionDecision | null = null; - host.coordinator.running.add(turn); - host.coordinator.pendingApprovals.set("tool-1", { + host.coordinator.registerTurn(turn); + host.coordinator.openApproval("tool-1", { turn, turnId: turn.turnId, request: { toolUseId: "tool-1", toolName: "Write", input: {} }, @@ -937,7 +937,7 @@ describe("principal revocation boundary", () => { expect(decision).toBeNull(); expect(host.coordinator.pendingApprovals.has("tool-1")).toBe(true); - host.coordinator.reset(); + host.coordinator.cancelAll("Test teardown"); authorization.release(); }); }); @@ -968,7 +968,7 @@ describe("disconnect is not revocation, but it does end registration", () => { // Without the guard this is 1: the registry holds a closed socket forever, // and isWatched keeps the activity poller running for the process's life. expect(host.activity!.stream.subscriptionCount()).toBe(0); - host.coordinator.reset(); + host.coordinator.cancelAll("Test teardown"); }); for (const fails of [false, true]) test(`snapshot-on-connect stays revocable while history settles, fails=${fails}`, async () => { @@ -990,7 +990,7 @@ describe("disconnect is not revocation, but it does end registration", () => { const socket = fakeSocket(); // One running turn puts onOpen on the snapshot-on-connect path. - host.coordinator.running.add({ + const parked = { sessionId: "session-1", turnId: "turn-1", backend, @@ -999,7 +999,8 @@ describe("disconnect is not revocation, but it does end registration", () => { cancelled: false, queue: [], lastResult: null, - } as never); + } as never; + host.coordinator.registerTurn(parked); const opening = handlers.onOpen({} as Event, socket.ws); await Promise.resolve(); @@ -1016,7 +1017,7 @@ describe("disconnect is not revocation, but it does end registration", () => { .map((raw) => JSON.parse(raw).type as string) .filter((type) => type === "session_history" || type === "error" || type === "status"); expect(framesAfterRevocation).toEqual([]); - host.coordinator.running.clear(); - host.coordinator.reset(); + host.coordinator.unregisterTurn(parked); + host.coordinator.cancelAll("Test teardown"); }); }); diff --git a/packages/ui-server/tests/ws-session-recovery.test.ts b/packages/ui-server/tests/ws-session-recovery.test.ts index 2e9c6b0689..ebd606dca2 100644 --- a/packages/ui-server/tests/ws-session-recovery.test.ts +++ b/packages/ui-server/tests/ws-session-recovery.test.ts @@ -133,7 +133,6 @@ function world(options: { db?: Database; principalValid?: () => boolean; turnTim const connection = { principal, authorization: testAuthorization() }; cleanups.push(() => { for (const turn of turns) turn.finish({ answer: null }); - host.coordinator.reset(); host.close(); stream.close(); if (!options.db) db.close(); diff --git a/packages/ui-server/tests/ws-tool-resolution.test.ts b/packages/ui-server/tests/ws-tool-resolution.test.ts index 994879eb26..6661cac038 100644 --- a/packages/ui-server/tests/ws-tool-resolution.test.ts +++ b/packages/ui-server/tests/ws-tool-resolution.test.ts @@ -51,7 +51,6 @@ function setup() { const host = new WsHost({ registry: createStaticBackendRegistry([backend], backend.id), catalog: createSessionCatalog(() => db) }); cleanup = () => { state.finish(); - host.coordinator.reset(); host.close(); db.close(); }; diff --git a/packages/ui-server/tests/ws-track-files.test.ts b/packages/ui-server/tests/ws-track-files.test.ts index b9448f14b9..7cc43bef57 100644 --- a/packages/ui-server/tests/ws-track-files.test.ts +++ b/packages/ui-server/tests/ws-track-files.test.ts @@ -60,7 +60,7 @@ test("actual dispatch carries nonempty server-derived track evidence through fir expect(history.messages.map(m => m.content)).toEqual(["Show this file", "Compare this file"]); expect(history.messages.map(m => m.files?.[0]?.path)).toEqual([path, path]); expect(history.messages[0]!.files![0]!.summary!.measurements.distance.value!).toBeGreaterThan(100); - } finally { release(); host.coordinator.reset(); host.close(); db.close(); } + } finally { release(); host.close(); db.close(); } }); test("the real socket parser refuses bad file references before a backend runs", async () => { @@ -78,7 +78,7 @@ test("the real socket parser refuses bad file references before a backend runs", await until(() => frames.length > 1); expect(frames[1]).toMatchObject({ type: "error", code: "ATTACHMENT_REJECTED" }); expect(calls).toBe(0); - } finally { host.coordinator.reset(); host.close(); db.close(); } + } finally { host.close(); db.close(); } }); import { writeFile } from "node:fs/promises"; @@ -123,7 +123,7 @@ test("track Retry refuses changed original bytes before acceptance and retains e expect(calls[0]!.prompt).toBe(prompt); const receipt = frames.find(f => f.type === "retry_receipt" && f.requestId === "exact-file"); expect(receipt?.type === "retry_receipt" && receipt.files?.[0]?.sha256).toBe(files[0]!.sha256); - } finally { host.coordinator.reset(); host.close(); db.close(); } + } finally { host.close(); db.close(); } }); test("a native live follow-up receives validated track evidence and replay restores its nonempty file chip", async () => { @@ -148,7 +148,7 @@ test("a native live follow-up receives validated track evidence and replay resto await handleClientMessage(host, ws, { type: "session_resume", sessionId: "native-track-session" }, connection); const replay = frames.findLast(frame => frame.type === "session_history"); if (replay?.type !== "session_history") throw Error("No replay."); expect(replay.messages[1]!.content).toBe("Use this original"); expect(replay.messages[1]!.files).toHaveLength(1); expect(replay.messages[1]!.files![0]!.summary!.counts.retained).toBe(2); - } finally { release(); host.coordinator.reset(); host.close(); db.close(); } + } finally { release(); host.close(); db.close(); } }); for (const withFile of [true, false]) { @@ -180,6 +180,6 @@ for (const withFile of [true, false]) { expect(result.retryOfTurnId).toBeTruthy(); expect(db.query("SELECT COUNT(*) AS n FROM retry_requests").get()).toEqual({ n: 1 }); } - } finally { host.coordinator.reset(); host.close(); db.close(); } + } finally { host.close(); db.close(); } }); } diff --git a/tests/fixtures/claude-worker-probe.ts b/tests/fixtures/claude-worker-probe.ts index dd5b3614f3..72ca090aa1 100644 --- a/tests/fixtures/claude-worker-probe.ts +++ b/tests/fixtures/claude-worker-probe.ts @@ -127,12 +127,10 @@ host = new WsHost({ ...nativeHost, brainPath, registry: createStaticBackendRegis host.clients.add({ send(text: string) { const frame = JSON.parse(text); frames.push(frame); if (frame.type === "mask_request") { - const pending = host.coordinator.pendingMask.get(frame.requestId)!; - host.coordinator.pendingMask.delete(frame.requestId); pending.resolve(png); + host.coordinator.claimMask(frame.requestId)!.resolve(png); } if (frame.type === "tool_approval_request") { - const pending = host.coordinator.pendingApprovals.get(frame.toolUseId)!; - host.coordinator.pendingApprovals.delete(frame.toolUseId); pending.resolve({ behavior: "allow" }); + host.coordinator.claimApproval(frame.toolUseId)!.resolve({ behavior: "allow" }); } } }, "odysseus"); try { diff --git a/tests/fixtures/policy-boundary-probe.ts b/tests/fixtures/policy-boundary-probe.ts index 7607bcb103..3c0721e8ac 100644 --- a/tests/fixtures/policy-boundary-probe.ts +++ b/tests/fixtures/policy-boundary-probe.ts @@ -443,18 +443,17 @@ async function server(): Promise { host.clients.add({ send(text: string) { const frame = JSON.parse(text); frames.push(frame); if (frame.type === "tool_approval_request") { - const pending = host.coordinator.pendingApprovals.get(frame.toolUseId); - host.coordinator.pendingApprovals.delete(frame.toolUseId); pending?.resolve({ behavior: "allow" }); + host.coordinator.claimApproval(frame.toolUseId)?.resolve({ behavior: "allow" }); } if (frame.type === "mask_request") { maskRequests++; - const pending = host.coordinator.pendingMask.get(frame.requestId)!; - host.coordinator.pendingMask.delete(frame.requestId); pending.resolve(png); + host.coordinator.claimMask(frame.requestId)!.resolve(png); } if (frame.type === "ask_user_request") { askRequests++; - const pending = host.coordinator.pendingAskUser.get(frame.requestId)!; - host.coordinator.pendingAskUser.delete(frame.requestId); pending.resolve({ answers: { Policy: "context/policies/crew.md" } } as any); + const pending = host.coordinator.pendingAsk(frame.requestId)!; + host.coordinator.acceptAsk(pending, { submissionId: "policy-probe", principalId: "odysseus" }); + (pending.entry.resolve as (result: unknown) => void)({ answers: { Policy: "context/policies/crew.md" } }); } } } as any, "odysseus"); From 6b641c3a39d4be2712bc7abb41acdb77201ca324 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 13:37:13 +0000 Subject: [PATCH 3/3] chore(ui-server): changeset for turn coordinator ownership Refs #2515 Co-Authored-By: Claude Opus 5.5 --- .changeset/turn-coordinator-ownership.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/turn-coordinator-ownership.md diff --git a/.changeset/turn-coordinator-ownership.md b/.changeset/turn-coordinator-ownership.md new file mode 100644 index 0000000000..363bd29003 --- /dev/null +++ b/.changeset/turn-coordinator-ownership.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +Closing the host now rejects every pending location and mask request and denies every pending approval or question, including ones whose turn had already stopped. Previously those requests could stay unsettled. Turn state is now owned by the coordinator; the ask-user duplicate-id rules are unchanged.