From 9b0bf8faca8334a675846df7dcb8c032d6381d52 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 16:55:10 +0000 Subject: [PATCH 1/4] refactor(ui-server): dispatch client messages through a per-kind handler table handleClientMessage was a 590-line switch over 42 case labels sharing one closure. Each message kind now has a handler in packages/ui-server/src/ws/ handlers/ (one module per message family) taking an explicit HandlerContext { host, ws, connection, requireEcho }. CLIENT_MESSAGE_HANDLERS is typed as a mapped type over ClientMessage["type"], so a kind without an entry fails typecheck. Dispatch looks up own keys only. ConnectionState and turnIdMatches move to handlers/context.ts and are re-exported from dispatch.ts for existing importers. No protocol, ordering or concurrency change. Refs #1358 Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/ws/dispatch.ts | 679 +----------------- .../ui-server/src/ws/handlers/activity.ts | 18 + packages/ui-server/src/ws/handlers/ask.ts | 33 + packages/ui-server/src/ws/handlers/cancel.ts | 38 + .../ui-server/src/ws/handlers/chat-message.ts | 73 ++ .../ui-server/src/ws/handlers/client-hello.ts | 19 + packages/ui-server/src/ws/handlers/context.ts | 84 +++ .../ui-server/src/ws/handlers/conversation.ts | 47 ++ .../src/ws/handlers/dialogue-read.ts | 19 + packages/ui-server/src/ws/handlers/handoff.ts | 17 + packages/ui-server/src/ws/handlers/inbox.ts | 28 + packages/ui-server/src/ws/handlers/index.ts | 69 ++ .../src/ws/handlers/local-exchange.ts | 23 + .../ui-server/src/ws/handlers/location.ts | 14 + packages/ui-server/src/ws/handlers/mask.ts | 21 + packages/ui-server/src/ws/handlers/ping.ts | 7 + packages/ui-server/src/ws/handlers/retry.ts | 74 ++ .../src/ws/handlers/scope-decision.ts | 9 + .../src/ws/handlers/session-resume.ts | 71 ++ .../src/ws/handlers/tool-permission.ts | 140 ++++ 20 files changed, 822 insertions(+), 661 deletions(-) create mode 100644 packages/ui-server/src/ws/handlers/activity.ts create mode 100644 packages/ui-server/src/ws/handlers/ask.ts create mode 100644 packages/ui-server/src/ws/handlers/cancel.ts create mode 100644 packages/ui-server/src/ws/handlers/chat-message.ts create mode 100644 packages/ui-server/src/ws/handlers/client-hello.ts create mode 100644 packages/ui-server/src/ws/handlers/context.ts create mode 100644 packages/ui-server/src/ws/handlers/conversation.ts create mode 100644 packages/ui-server/src/ws/handlers/dialogue-read.ts create mode 100644 packages/ui-server/src/ws/handlers/handoff.ts create mode 100644 packages/ui-server/src/ws/handlers/inbox.ts create mode 100644 packages/ui-server/src/ws/handlers/index.ts create mode 100644 packages/ui-server/src/ws/handlers/local-exchange.ts create mode 100644 packages/ui-server/src/ws/handlers/location.ts create mode 100644 packages/ui-server/src/ws/handlers/mask.ts create mode 100644 packages/ui-server/src/ws/handlers/ping.ts create mode 100644 packages/ui-server/src/ws/handlers/retry.ts create mode 100644 packages/ui-server/src/ws/handlers/scope-decision.ts create mode 100644 packages/ui-server/src/ws/handlers/session-resume.ts create mode 100644 packages/ui-server/src/ws/handlers/tool-permission.ts diff --git a/packages/ui-server/src/ws/dispatch.ts b/packages/ui-server/src/ws/dispatch.ts index a8f85b57a3..ee1aa560b8 100644 --- a/packages/ui-server/src/ws/dispatch.ts +++ b/packages/ui-server/src/ws/dispatch.ts @@ -1,91 +1,18 @@ -import { requireKnownSession } from "./session-recovery.js"; -import { resolveChatFiles, withTrackFiles } from "../tracks/read.js"; -import { SHARE_MAX_FILES, SHARE_MAX_TOTAL_BYTES, type SharedFileMeta } from "@schlessera/brain-ui-sdk/protocol"; -import { estimateDecodedBase64Bytes } from "./attachments.js"; -import { FOLLOW_UP_QUEUE_CAPABILITY, PROTOCOL_REV_CLIENT_ECHO } from "@schlessera/brain-ui-sdk/protocol"; +import { PROTOCOL_REV_CLIENT_ECHO } from "@schlessera/brain-ui-sdk/protocol"; import type { ClientMessage } from "@schlessera/brain-ui-sdk/protocol"; import type { WSContext } from "./clients.js"; -import type { AuthorizationContext } from "./turns.js"; -import { approvalRequestFrame, locationErrorText, withTurnScope } from "./frames.js"; -import { sendSessionHistory } from "./history.js"; -import { validateAttachments } from "./attachments.js"; -import { handleChatMessage } from "./run-session.js"; -import { cancelHandoffPreparation, handoffStatus, prepareHandoff, startHandoff } from "./handoff.js"; -import { handleAskAnswer, handleAskAnswerStatus } from "./ask-answers.js"; -import { resendPendingApprovals, resendPendingAsks } from "./resend.js"; import type { WsHost } from "./host.js"; +import type { ClientMessageHandler, ClientMessageType, ConnectionState, HandlerContext } from "./handlers/context.js"; +import { CLIENT_MESSAGE_HANDLERS } from "./handlers/index.js"; -/** Per-connection negotiation state, owned by the socket handler. */ -export interface ConnectionState { - /** - * The transport is gone. Set by onClose, and separate from `authorization` - * because a disconnect is not a revocation: work already underway keeps its - * authority, but nothing may register new per-connection state afterwards. - */ - closed?: boolean; - /** Principal resolved once at the WebSocket upgrade boundary. */ - principal: import("../db/principals.js").Principal; - /** Mutable in-memory decision invalidated synchronously by revocation. */ - authorization: AuthorizationContext; - /** Revision the client declared via `client_hello`; absent means rev 2. */ - protocolRev?: number; - /** Opt-in flags the client declared via `client_hello`. */ - capabilities?: Readonly>; -} - -/** - * Answer a permission reply that applied to nothing pending (#957): the host - * says what actually happened instead of letting the sender assume. A reply - * whose turn echo does not match the settled request learns `unknown` — it - * was never about that request. - */ -function replyResolution( - host: WsHost, - ws: WSContext, - connection: ConnectionState, - toolUseId: string, - echoed: string | undefined, - requireEcho: boolean -): void { - if (connection.capabilities?.toolResolution !== true) return; - const record = host.coordinator.resolvedApprovals.get(toolUseId); - if (record && turnIdMatches(record, echoed, requireEcho)) { - host.sendMessage(ws, { - 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 } : {}), - }); - return; - } - host.sendMessage(ws, { type: "tool_resolution", toolUseId, outcome: "unknown", ...(echoed ? { turnId: echoed } : {}) }); -} +export type { ConnectionState } from "./handlers/context.js"; +export { turnIdMatches } from "./handlers/context.js"; /** - * Does this reply's echoed turnId identify the turn that raised the request? - * - * A wrong id is always refused: a stale echo from before a reconnect or a - * follow-up would resolve a different turn's pending promise. - * - * A MISSING id depends on who is speaking. A client that declared rev 3 - * promised to echo, so silence means the reply cannot be correlated and is - * refused. A client that declared nothing is rev 2, where the field is - * optional, and is still tolerated — that tolerance is the deprecation window, - * and it is what lets this be enforced at all without breaking clients that - * predate `client_hello`. + * Route one validated client frame to its handler in + * `CLIENT_MESSAGE_HANDLERS` (one module per message family under + * `./handlers/`). */ -export function turnIdMatches( - pending: { turnId: string }, - echoed: string | undefined, - requireEcho: boolean -): boolean { - if (echoed === undefined) return !requireEcho; - return echoed === pending.turnId; -} - export async function handleClientMessage( host: WsHost, ws: WSContext, @@ -105,584 +32,14 @@ export async function handleClientMessage( host.reportDroppedFrame("revoked_principal"); return; } - const { coordinator, catalog } = host; - const requireEcho = (connection.protocolRev ?? 2) >= PROTOCOL_REV_CLIENT_ECHO; - switch (msg.type) { - case "client_hello": { - // Record what this connection speaks. Never rejected on version: a - // future client declaring rev 9 is simply held to the rules this host - // knows, and an unknown capability flag is ignored. - connection.protocolRev = msg.protocolRev; - connection.capabilities = { ...(msg.capabilities ?? {}) }; - host.clients.setCapabilities(ws, msg.capabilities); - // A client that reloaded or reconnected rebuilds every session's - // pending follow-ups from these (#1002). An empty queue sends nothing: - // the client clears its own on each new server_hello. - if (connection.capabilities[FOLLOW_UP_QUEUE_CAPABILITY] === true) { - for (const sessionId of coordinator.sessionsWithFollowUps()) { - host.sendMessage(ws, host.followUpQueueFrame(sessionId)); - } - } - return; - } - - case "chat_message": { - if (msg.handoff) { - await startHandoff(host, ws, { ...msg, handoff: msg.handoff }, connection); - return; - } - const attachmentResult = validateAttachments(msg.attachments); - if (!attachmentResult.ok) { - host.sendMessage(ws, { - type: "error", - code: "ATTACHMENT_REJECTED", - ...(msg.requestId ? { requestId: msg.requestId } : {}), - message: attachmentResult.reason, - ...(msg.sessionId ? { sessionId: msg.sessionId } : {}), - }); - return; - } - let files: SharedFileMeta[]; - try { - files = await resolveChatFiles(host.brainPath, msg.files); - const bytes = files.reduce((n, f) => n + f.bytes, 0) + attachmentResult.attachments.reduce((n, f) => n + estimateDecodedBase64Bytes(f.data), 0); - if (files.length + attachmentResult.attachments.length > SHARE_MAX_FILES || bytes > SHARE_MAX_TOTAL_BYTES) throw Error("Attached files exceed the message limits."); - } catch (error) { - host.sendMessage(ws, { type: "error", code: "ATTACHMENT_REJECTED", message: error instanceof Error ? error.message : "Track attachment refused.", - ...(msg.requestId ? { requestId: msg.requestId } : {}), ...(msg.sessionId ? { sessionId: msg.sessionId } : {}) }); - return; - } - if (!connection.authorization.valid) return; - let shareSessionId = msg.sessionId; - if (msg.shareId) { - try { - if (!host.inboxTools?.shares) throw new Error("This host does not support bound share filing"); - shareSessionId = await host.inboxTools.shares.resolveSession(connection.authorization.principalId, msg.shareId, msg.sessionId, - () => !connection.closed && connection.authorization.valid); - // A repeated intake without an explicit continuation only recovers - // the binding. Admission may have succeeded before its reply was lost. - if (shareSessionId && !msg.sessionId) { - host.sendMessage(ws, { type: "session_info", sessionId: shareSessionId, isNew: false, - ...(msg.requestId ? { requestId: msg.requestId } : {}) }); - return; - } - } catch (error) { - host.sendMessage(ws, { type: "error", code: "SESSION_BUSY", message: error instanceof Error ? error.message : "Share binding refused", - ...(msg.requestId ? { requestId: msg.requestId } : {}) }); - return; - } - } - await handleChatMessage(host, ws, { - authorization: connection.authorization, - text: msg.text, - ...(msg.historyOwnerId && !shareSessionId ? {historyOwnerId:msg.historyOwnerId} : {}), - ...(msg.shareId ? { shareId: msg.shareId } : {}), - sessionId: shareSessionId, - attachments: attachmentResult.attachments, - ...(files.length ? { files } : {}), - providerId: msg.providerId, - client: msg.client, - source: msg.source, - draftId: msg.draftId, - ...(msg.profileDraftId && !msg.sessionId ? { profileDraftId: msg.profileDraftId } : {}), - // Ignored entirely by a host that does not store drafts. - ...(msg.draftRef && host.drafts ? { draftRef: msg.draftRef } : {}), - thinkingLevel: msg.thinkingLevel, - requestId: msg.requestId, - ...(msg.localExchanges?.length ? { localExchanges: msg.localExchanges } : {}), - }); - break; - } - - case "handoff_status": { - handoffStatus(host, ws, msg.handoffId); - return; - } - - case "handoff_prepare": { - if (connection.closed) return; - await prepareHandoff(host, ws, msg, connection); - return; - } - - case "handoff_prepare_cancel": { - cancelHandoffPreparation(host, msg.handoffId, connection); - return; - } - - case "retry_status": { - try { - // Retained retries and their invalidations commit off the event loop (#2850). - await catalog.settled?.(); - host.sendMessage(ws, catalog.retryReceipt?.(msg.sessionId, msg.requestId, connection.authorization.principalId) - ?? { type: "retry_receipt", sessionId: msg.sessionId, requestId: msg.requestId, state: "unknown" }); - } catch { - host.sendMessage(ws, { type: "retry_receipt", sessionId: msg.sessionId, requestId: msg.requestId, state: "unknown" }); - } - return; - } - - case "retry_turn": { - const refuse = async (message: string) => { - const receipt = { type: "retry_receipt" as const, sessionId: msg.sessionId, requestId: msg.requestId, state: "refused" as const, message }; - try { host.sendMessage(ws, (await catalog.refuseRetry?.(msg.sessionId, msg.requestId, connection.authorization.principalId, message)) ?? receipt); } - catch { host.sendMessage(ws, receipt); } - }; - try { - // Read and reserve against every retained request and invalidation - // submitted before this frame (#2850). One submitted during the file - // check below came with an accepted message, which the admission - // check after it refuses. - await catalog.settled?.(); - // Replay a receipt even while its turn runs. A repeated request id - // cannot become a queued follow-up, including after reconnect. - const prior = catalog.retryReceipt?.(msg.sessionId, msg.requestId, connection.authorization.principalId); - if (prior && prior.state !== "unknown") { host.sendMessage(ws, prior); return; } - if (coordinator.bySession.has(msg.sessionId) || coordinator.startingBySession.has(msg.sessionId)) { - await refuse("This session is busy. Wait for the current turn to finish."); return; - } - if (coordinator.activeRuns() >= host.maxConcurrentSessions()) { - await refuse("The server is busy. Wait for a turn to finish and try again."); return; - } - const original = catalog.peekRetry?.(msg.sessionId); - let files: import("@schlessera/brain-ui-sdk/protocol").SharedFileMeta[] | undefined; - if (original?.request.files?.length && original.turnId === msg.failedTurnId && original.principalId === connection.authorization.principalId) { - try { - files = await resolveChatFiles(host.brainPath, original.request.files); - if (!original.prompt.includes(withTrackFiles("", files))) { await refuse("An original track changed. Start a new message with the current file instead."); return; } - } catch { await refuse("An original track is unavailable. Attach it again in a new message."); return; } - if (!connection.authorization.valid) return; - // File reads yield; repeat admission before consuming eligibility. - if (coordinator.bySession.has(msg.sessionId) || coordinator.startingBySession.has(msg.sessionId) || coordinator.activeRuns() >= host.maxConcurrentSessions()) { - await refuse("The session or server became busy. Try again when it is free."); return; - } - } - const reserved = await catalog.reserveRetry?.(msg.sessionId, msg.failedTurnId, msg.requestId, connection.authorization.principalId, files ? original!.prompt : undefined); - if (!reserved) { await refuse("This server cannot retain the original request for Retry."); return; } - host.sendMessage(ws, { ...reserved.receipt, ...(reserved.request ? { - ...(files?.length ? { files } : {}), - text: reserved.request.text, attachmentCount: reserved.request.attachments?.length ?? 0, - source: reserved.request.source ?? "typed", - ...(reserved.request.thinkingLevel !== undefined ? { thinkingLevel: reserved.request.thinkingLevel } : {}), - } : {}) }); - if (reserved.request) { - await handleChatMessage(host, ws, { - ...reserved.request, authorization: connection.authorization, - requestId: msg.requestId, - attachments: reserved.request.attachments ?? [], - files, replayPrompt: reserved.prompt, isRetry: true, - }); - } - } catch { - // A failed database write must not execute an unacknowledged retry. - await refuse("The server could not confirm this retry. Check delivery before trying again."); - } - return; - } - - case "local_exchange": { - // A command the client answered itself (#582). Stored against the - // session; the next prompt handed to the backend carries its context. - // Answered either way, so the client can say when it is not kept. - // Answered once it is stored (#2850); the next prompt takes it meanwhile. - const saved = (await catalog.recordLocalExchange?.(msg.sessionId, msg.exchange, false)) ?? false; - host.sendMessage(ws, { - type: "local_exchange_result", - sessionId: msg.sessionId, - exchangeId: msg.exchange.id, - saved, - ...(saved - ? {} - : { - reason: catalog.recordLocalExchange - ? "The server could not store it." - : "This server does not keep local answers.", - }), - }); - return; - } - - case "scope_decision": { - // Resolves once the decision's own scope writes have committed, so the summary below reads them (#2850). - const receipt = await host.scope?.decide(msg, connection.authorization.valid && connection.authorization.expiresAt > Date.now()) - ?? { ...msg, type: "scope_decision_receipt" as const, state: "refused" as const, reason: "This host cannot answer scope decisions." }; - if (receipt.state !== "refused" && host.journal) host.sendMessage(ws, { type: "turn_journal", sessionId: msg.sessionId, turnId: msg.turnId, journal: { ...host.journal.summary(msg.turnId), ...(host.budgets?.saved(msg.turnId) ? { budget: host.budgets.saved(msg.turnId) } : {}) } }); - host.sendMessage(ws, receipt); - return; - } - case "ask_user_response": - case "ask_user_list_response": - case "ask_user_rank_response": - case "ask_user_form_response": { - handleAskAnswer(host, ws, msg, connection.authorization.principalId); - break; - } - - case "ask_answer_status": { - handleAskAnswerStatus(host, ws, msg, connection.authorization.principalId); - return; - } - - case "ping": { - // Liveness (rev 5): answered at once, to this socket only. Anything the - // client receives proves the path is open; the pong correlates it. - host.sendMessage(ws, { type: "pong", probeId: msg.probeId }); - return; - } - - case "ask_user_cancel": { - // Dismisses any ask kind: the ids share one space. - 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. - coordinator.cancelAsk(msg.requestId); - pending.turn.recorder?.recordCancellation( - connection.authorization.principalId, - "ask_user" - ); - pending.reject(new Error(msg.reason || "User cancelled the question")); - } - break; - } - - case "location_response": { - coordinator - .claimLocation(msg.requestId, (p) => turnIdMatches(p, msg.turnId, requireEcho)) - ?.resolve({ coords: msg.coords, timestamp: msg.timestamp }); - break; - } - - case "location_error": { - coordinator - .claimLocation(msg.requestId, (p) => turnIdMatches(p, msg.turnId, requireEcho)) - ?.reject(new Error(locationErrorText(msg.code, msg.message))); - break; - } - - case "mask_response": { - // 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": { - 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; - } - - case "tool_approval": { - const pending = coordinator.pendingApprovals.get(msg.toolUseId); - if (!pending || !turnIdMatches(pending, msg.turnId, requireEcho)) { - replyResolution(host, ws, connection, msg.toolUseId, msg.turnId, requireEcho); - } - if (pending && turnIdMatches(pending, msg.turnId, requireEcho)) { - // Voice may deny; it may never grant (docs/decisions/voice-permission.md). - // A grant attributed to voice is refused before anything else looks - // at it: the request stays pending, nothing is recorded or - // remembered, and the card is still there to answer it. The wire is - // not trusted to enforce policy — a client offering no spoken grant - // is not the reason this holds. - if (msg.channel === "voice") { - host.log.emit({ - severityText: "WARN", - body: "voice-attributed grant refused", - attributes: { - "tool.name": pending.request.toolName, - "toolUse.id": pending.request.toolUseId, - }, - }); - // The sender treated its reply as the end of the exchange — a - // client drops the request's turn correlation once it answers, and - // may have cleared the card — so hand it the card again, exactly - // as a reconnect would. Without this its next answer (the card's, - // or a spoken denial) arrives uncorrelated and is dropped too. - host.sendMessage( - ws, - withTurnScope( - approvalRequestFrame(pending.request, host.toolPermissions !== null), - pending.turn, - pending.turnId - ) - ); - break; - } - 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 - // this tool is outside of: the store is read by every OTHER turn, and - // a grant made inside a narrower posture must not widen the ones the - // user was not looking at. The call itself still runs — they approved - // it — it is only the memory that is refused. - // The store being absent is one of the reasons, not an exemption from - // them: optional-chaining the add() away would take the "remembered" - // branch, write nothing, log nothing, and still stamp the activity - // record `always_allow` — the exact silent refusal this block exists - // to rule out. Embedders wire a store (app.ts) so this is the - // test/embedder path, which is precisely where a silent no-op is - // hardest to notice. - const store = host.toolPermissions; - const remembers = - store !== null && - pending.request.kind !== "command" && pending.request.kind !== "policy" && - !pending.request.outsideEnforcedAllowlist; - if (msg.always && remembers) { - await store.add(pending.request.toolName); - } else if (msg.always) { - // The user asked for something the host will not do. Recorded for - // the same reason the bridge records a grant it declines to apply: - // a refusal nobody can see is indistinguishable from a bug, and for - // kind "command" it also says a client sent an option its own UI - // does not offer. - host.log.emit({ - severityText: "INFO", - body: "always-allow not remembered", - attributes: { - "tool.name": pending.request.toolName, - "toolUse.id": pending.request.toolUseId, - reason: - store === null - ? "no grant store configured" - : pending.request.kind === "command" - ? "per-use confirmation" - : "outside this turn's enforced allowlist", - }, - }); - } - coordinator.settleApproval( - msg.toolUseId, - pending, - msg.updatedInput - ? { behavior: "allow", updatedInput: msg.updatedInput } - : { behavior: "allow" }, - { - principalId: connection.authorization.principalId, - ...(msg.always && remembers ? { always: true } : {}), - ...(msg.channel ? { channel: msg.channel } : {}), - } - ); - } - break; - } - - case "tool_denial": { - 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 { - // Already granted, expired, or never pending: a denial that lost a - // race is told so, never confirmed (a visual grant stays a grant). - replyResolution(host, ws, connection, msg.toolUseId, msg.turnId, requireEcho); - } - break; - } - - case "cancel": { - if (msg.sessionId) { - const turn = coordinator.bySession.get(msg.sessionId); - if (turn) { - coordinator.recordCancellation(turn, connection.authorization.principalId); - coordinator.cancelTurn(turn, "Cancelled by user"); - } - // A cancel drops the session's queued follow-ups; a conversation's - // committed-but-unsubmitted work in that session goes with them. - host.conversations?.sessionCancelled(msg.sessionId); - const starting = coordinator.startingBySession.get(msg.sessionId); - if (starting) { - starting.cancelled = true; - // Releasing here, not in runSession: a start cancelled before it - // becomes a turn never reaches the loop that would drain its queue. - coordinator.dropStartingQueue(msg.sessionId, starting, "Cancelled by user"); - host.sendToClients({ type: "status", status: "idle", sessionId: msg.sessionId, detail: "Cancelled before starting" }); - } - return; - } - // No sessionId: cancel the sole running session; ambiguous if several run. - if (coordinator.running.size === 0) return; - if (coordinator.running.size > 1) { - host.sendMessage(ws, { - type: "error", - code: "CANCEL_AMBIGUOUS", - message: "Several sessions are running — specify which to cancel.", - }); - return; - } - const turn = [...coordinator.running][0]!; - coordinator.recordCancellation(turn, connection.authorization.principalId); - coordinator.cancelTurn(turn, "Cancelled by user"); - if (turn.sessionId) host.conversations?.sessionCancelled(turn.sessionId); - break; - } - - case "inbox_resolve": - case "inbox_snooze": { - if (connection.closed) break; - if (!host.inbox?.handleDecision) { - host.sendMessage(ws, { type: "error", code: "INBOX_UNAVAILABLE", message: "Inbox decisions are unavailable on this host." }); - break; - } - host.inbox.handleDecision(ws, msg, connection.authorization); - break; - } - - case "inbox_subscribe": { - if (connection.closed) break; - if (!host.inbox) { - host.sendMessage(ws, { type: "error", code: "INBOX_UNAVAILABLE", message: "Inbox subscriptions are unavailable on this host." }); - break; - } - host.inbox.handleSubscribe(ws, msg, connection.authorization); - break; - } - - case "inbox_unsubscribe": { - if (connection.closed) break; - if (!host.inbox) { - host.sendMessage(ws, { type: "error", code: "INBOX_UNAVAILABLE", message: "Inbox subscriptions are unavailable on this host." }); - break; - } - host.inbox.handleUnsubscribe(ws, msg); - break; - } - - case "activity_subscribe": { - // View-scoped opt-in: without a subscription this connection never - // receives an activity frame. No turn correlation — subscriptions are - // connection state, not turn state. - // - // Dispatch starts on a microtask, so this can run after onClose already - // dropped the connection's subscriptions. Registering here would resurrect - // a dead socket in the registry and keep the activity poller alive for the - // life of the process. - if (connection.closed) break; - host.activity?.stream.handleSubscribe(ws, msg, connection.authorization.principalId); - break; - } - - case "activity_unsubscribe": { - host.activity?.stream.handleUnsubscribe(ws, msg); - break; - } - - case "conversation_start": - case "conversation_audio": - case "conversation_endpoint": - case "conversation_commit": - case "conversation_playback": - case "conversation_stop": { - if (connection.closed) break; - const conversations = host.conversations; - if (!conversations) { - host.sendMessage(ws, { type: "error", code: "CONVERSATION_UNAVAILABLE", message: "Live conversation is not configured on this host." }); - break; - } - switch (msg.type) { - case "conversation_start": await conversations.start(ws, connection, msg); break; - case "conversation_audio": conversations.audio(ws, connection, msg); break; - case "conversation_endpoint": conversations.endpoint(ws, connection, msg); break; - case "conversation_commit": conversations.commit(ws, connection, msg); break; - case "conversation_playback": conversations.playback(ws, connection, msg); break; - case "conversation_stop": conversations.stop(ws, connection, msg); break; - } - break; - } - - case "dialogue_read": { - if (!connection.authorization.valid || !connection.capabilities?.sessionDialogue || !catalog.dialogueRead) break; - if (msg.sessionId && !await requireKnownSession(host, ws, connection, msg.sessionId, true, msg.requestId)) break; - try { - const page = await catalog.dialogueRead(connection.authorization.principalId, msg); - if (connection.closed || !connection.authorization.valid) break; - if (page) host.sendMessage(ws, { type: "dialogue_history", requestId: msg.requestId, ...page }); - else if (msg.sessionId) host.sendMessage(ws, { type: "dialogue_history", requestId: msg.requestId, - ownerId: msg.sessionId, sessionId: msg.sessionId, generation: 1, through: 0, records: [], coverage: "complete" }); - else throw new Error("Dialogue owner unavailable"); - } catch { - if (!connection.closed && connection.authorization.valid) host.sendMessage(ws, { type: "error", code: "DIALOGUE_UNAVAILABLE", requestId: msg.requestId, - ...(msg.sessionId ? {sessionId: msg.sessionId} : {}), message: "Conversation history unavailable. Try opening this chat again." }); - } - break; - } - - case "session_resume": { - let lookupError: string | undefined; - if (!await requireKnownSession(host, ws, connection, msg.sessionId, true, undefined, error => { - lookupError = error instanceof Error ? error.message : "Failed to load session"; - })) { - host.reportSessionResume(msg.sessionId, connection.authorization.valid ? "error" : "unauthorized", - { error: lookupError ?? "Session could not be verified" }); - if (lookupError !== undefined) host.reportTurnFailed("SESSION_LOAD_ERROR", { sessionId: msg.sessionId }, lookupError); - return; - } - host.sendMessage(ws, { - type: "session_info", - sessionId: msg.sessionId, - isNew: false, - providerId: catalog.getStoredProviderId(msg.sessionId) ?? undefined, - backendId: catalog.getStoredBackendId(msg.sessionId) ?? undefined, - }); - - // One log line per resume, whichever way it ends (#1328). - let resumeReported = false; - try { - const backend = await host.registry.getBackendForSession(catalog.getStoredBackendId(msg.sessionId)); - const published = await host.publishHistory(msg.sessionId, backend, () => connection.authorization.valid, (messages) => { - sendSessionHistory(ws, msg.sessionId, host.prepareHistory(msg.sessionId, messages), host.catalog.readStateRoom?.(msg.sessionId)); - host.reportSessionResume(msg.sessionId, "loaded", { messages: messages.length }); - resumeReported = true; - // Replacing history may remove live cards: restore pending requests - // after all chunks, then the whole waiting follow-up queue. - resendPendingApprovals(host, ws, msg.sessionId); - resendPendingAsks(host, ws, msg.sessionId); - if (connection.capabilities?.[FOLLOW_UP_QUEUE_CAPABILITY] === true) { - host.sendMessage(ws, host.followUpQueueFrame(msg.sessionId)); - } - // Read the current turn after history, including any queued turn - // that replaced the one running when the asynchronous read began. - const runningTurn = coordinator.bySession.get(msg.sessionId); - host.sendMessage(ws, { - type: "status", - ...(runningTurn && runningTurn.lastResult === null - ? { status: "thinking" as const, detail: "Session in progress", turnId: runningTurn.turnId } - : { status: "idle" as const, detail: "Session loaded" }), - sessionId: msg.sessionId, - }); - }); - if (!published) { - host.reportSessionResume(msg.sessionId, "unauthorized"); - return; - } - } catch (err) { - if (!connection.authorization.valid) { - host.reportSessionResume(msg.sessionId, "unauthorized"); - return; - } - const message = err instanceof Error ? err.message : "Failed to load session"; - if (!resumeReported) host.reportSessionResume(msg.sessionId, "error", { error: message }); - host.reportTurnFailed("SESSION_LOAD_ERROR", { sessionId: msg.sessionId }, message); - host.sendMessage(ws, { - type: "error", - code: "SESSION_LOAD_ERROR", - message: "The host could not load this conversation. No work was started; your draft is kept.", - sessionId: msg.sessionId, - }); - } - break; - } - } + // Own keys only: a frame typed "constructor" must not reach Object.prototype. + if (!Object.hasOwn(CLIENT_MESSAGE_HANDLERS, msg.type)) return; + const handle = CLIENT_MESSAGE_HANDLERS[msg.type] as ClientMessageHandler; + const ctx: HandlerContext = { + host, + ws, + connection, + requireEcho: (connection.protocolRev ?? 2) >= PROTOCOL_REV_CLIENT_ECHO, + }; + await handle(ctx, msg); } diff --git a/packages/ui-server/src/ws/handlers/activity.ts b/packages/ui-server/src/ws/handlers/activity.ts new file mode 100644 index 0000000000..4d7a34bc36 --- /dev/null +++ b/packages/ui-server/src/ws/handlers/activity.ts @@ -0,0 +1,18 @@ +import type { ClientMessageHandler } from "./context.js"; + +export const handleActivitySubscribe: ClientMessageHandler<"activity_subscribe"> = ({ host, ws, connection }, msg) => { + // View-scoped opt-in: without a subscription this connection never + // receives an activity frame. No turn correlation — subscriptions are + // connection state, not turn state. + // + // Dispatch starts on a microtask, so this can run after onClose already + // dropped the connection's subscriptions. Registering here would resurrect + // a dead socket in the registry and keep the activity poller alive for the + // life of the process. + if (connection.closed) return; + host.activity?.stream.handleSubscribe(ws, msg, connection.authorization.principalId); +}; + +export const handleActivityUnsubscribe: ClientMessageHandler<"activity_unsubscribe"> = ({ host, ws }, msg) => { + host.activity?.stream.handleUnsubscribe(ws, msg); +}; diff --git a/packages/ui-server/src/ws/handlers/ask.ts b/packages/ui-server/src/ws/handlers/ask.ts new file mode 100644 index 0000000000..f235de1328 --- /dev/null +++ b/packages/ui-server/src/ws/handlers/ask.ts @@ -0,0 +1,33 @@ +import { handleAskAnswer, handleAskAnswerStatus } from "../ask-answers.js"; +import { turnIdMatches, type ClientMessageHandler } from "./context.js"; + +export type AskAnswerType = + | "ask_user_response" + | "ask_user_list_response" + | "ask_user_rank_response" + | "ask_user_form_response"; + +/** Every ask kind answers through one path; see ask-answers.ts. */ +export const handleAskAnswerFrame: ClientMessageHandler = ({ host, ws, connection }, msg) => { + handleAskAnswer(host, ws, msg, connection.authorization.principalId); +}; + +export const handleAskAnswerStatusFrame: ClientMessageHandler<"ask_answer_status"> = ({ host, ws, connection }, msg) => { + handleAskAnswerStatus(host, ws, msg, connection.authorization.principalId); +}; + +export const handleAskUserCancel: ClientMessageHandler<"ask_user_cancel"> = ({ host, connection, requireEcho }, msg) => { + const { coordinator } = host; + // Dismisses any ask kind: the ids share one space. + 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. + coordinator.cancelAsk(msg.requestId); + pending.turn.recorder?.recordCancellation( + connection.authorization.principalId, + "ask_user" + ); + pending.reject(new Error(msg.reason || "User cancelled the question")); + } +}; diff --git a/packages/ui-server/src/ws/handlers/cancel.ts b/packages/ui-server/src/ws/handlers/cancel.ts new file mode 100644 index 0000000000..4aec619588 --- /dev/null +++ b/packages/ui-server/src/ws/handlers/cancel.ts @@ -0,0 +1,38 @@ +import type { ClientMessageHandler } from "./context.js"; + +export const handleCancel: ClientMessageHandler<"cancel"> = ({ host, ws, connection }, msg) => { + const { coordinator } = host; + if (msg.sessionId) { + const turn = coordinator.bySession.get(msg.sessionId); + if (turn) { + coordinator.recordCancellation(turn, connection.authorization.principalId); + coordinator.cancelTurn(turn, "Cancelled by user"); + } + // A cancel drops the session's queued follow-ups; a conversation's + // committed-but-unsubmitted work in that session goes with them. + host.conversations?.sessionCancelled(msg.sessionId); + const starting = coordinator.startingBySession.get(msg.sessionId); + if (starting) { + starting.cancelled = true; + // Releasing here, not in runSession: a start cancelled before it + // becomes a turn never reaches the loop that would drain its queue. + coordinator.dropStartingQueue(msg.sessionId, starting, "Cancelled by user"); + host.sendToClients({ type: "status", status: "idle", sessionId: msg.sessionId, detail: "Cancelled before starting" }); + } + return; + } + // No sessionId: cancel the sole running session; ambiguous if several run. + if (coordinator.running.size === 0) return; + if (coordinator.running.size > 1) { + host.sendMessage(ws, { + type: "error", + code: "CANCEL_AMBIGUOUS", + message: "Several sessions are running — specify which to cancel.", + }); + return; + } + const turn = [...coordinator.running][0]!; + coordinator.recordCancellation(turn, connection.authorization.principalId); + coordinator.cancelTurn(turn, "Cancelled by user"); + if (turn.sessionId) host.conversations?.sessionCancelled(turn.sessionId); +}; diff --git a/packages/ui-server/src/ws/handlers/chat-message.ts b/packages/ui-server/src/ws/handlers/chat-message.ts new file mode 100644 index 0000000000..a3a781494f --- /dev/null +++ b/packages/ui-server/src/ws/handlers/chat-message.ts @@ -0,0 +1,73 @@ +import { SHARE_MAX_FILES, SHARE_MAX_TOTAL_BYTES, type SharedFileMeta } from "@schlessera/brain-ui-sdk/protocol"; +import { resolveChatFiles } from "../../tracks/read.js"; +import { estimateDecodedBase64Bytes, validateAttachments } from "../attachments.js"; +import { startHandoff } from "../handoff.js"; +import { handleChatMessage } from "../run-session.js"; +import type { ClientMessageHandler } from "./context.js"; + +export const handleChatMessageFrame: ClientMessageHandler<"chat_message"> = async ({ host, ws, connection }, msg) => { + if (msg.handoff) { + await startHandoff(host, ws, { ...msg, handoff: msg.handoff }, connection); + return; + } + const attachmentResult = validateAttachments(msg.attachments); + if (!attachmentResult.ok) { + host.sendMessage(ws, { + type: "error", + code: "ATTACHMENT_REJECTED", + ...(msg.requestId ? { requestId: msg.requestId } : {}), + message: attachmentResult.reason, + ...(msg.sessionId ? { sessionId: msg.sessionId } : {}), + }); + return; + } + let files: SharedFileMeta[]; + try { + files = await resolveChatFiles(host.brainPath, msg.files); + const bytes = files.reduce((n, f) => n + f.bytes, 0) + attachmentResult.attachments.reduce((n, f) => n + estimateDecodedBase64Bytes(f.data), 0); + if (files.length + attachmentResult.attachments.length > SHARE_MAX_FILES || bytes > SHARE_MAX_TOTAL_BYTES) throw Error("Attached files exceed the message limits."); + } catch (error) { + host.sendMessage(ws, { type: "error", code: "ATTACHMENT_REJECTED", message: error instanceof Error ? error.message : "Track attachment refused.", + ...(msg.requestId ? { requestId: msg.requestId } : {}), ...(msg.sessionId ? { sessionId: msg.sessionId } : {}) }); + return; + } + if (!connection.authorization.valid) return; + let shareSessionId = msg.sessionId; + if (msg.shareId) { + try { + if (!host.inboxTools?.shares) throw new Error("This host does not support bound share filing"); + shareSessionId = await host.inboxTools.shares.resolveSession(connection.authorization.principalId, msg.shareId, msg.sessionId, + () => !connection.closed && connection.authorization.valid); + // A repeated intake without an explicit continuation only recovers + // the binding. Admission may have succeeded before its reply was lost. + if (shareSessionId && !msg.sessionId) { + host.sendMessage(ws, { type: "session_info", sessionId: shareSessionId, isNew: false, + ...(msg.requestId ? { requestId: msg.requestId } : {}) }); + return; + } + } catch (error) { + host.sendMessage(ws, { type: "error", code: "SESSION_BUSY", message: error instanceof Error ? error.message : "Share binding refused", + ...(msg.requestId ? { requestId: msg.requestId } : {}) }); + return; + } + } + await handleChatMessage(host, ws, { + authorization: connection.authorization, + text: msg.text, + ...(msg.historyOwnerId && !shareSessionId ? {historyOwnerId:msg.historyOwnerId} : {}), + ...(msg.shareId ? { shareId: msg.shareId } : {}), + sessionId: shareSessionId, + attachments: attachmentResult.attachments, + ...(files.length ? { files } : {}), + providerId: msg.providerId, + client: msg.client, + source: msg.source, + draftId: msg.draftId, + ...(msg.profileDraftId && !msg.sessionId ? { profileDraftId: msg.profileDraftId } : {}), + // Ignored entirely by a host that does not store drafts. + ...(msg.draftRef && host.drafts ? { draftRef: msg.draftRef } : {}), + thinkingLevel: msg.thinkingLevel, + requestId: msg.requestId, + ...(msg.localExchanges?.length ? { localExchanges: msg.localExchanges } : {}), + }); +}; diff --git a/packages/ui-server/src/ws/handlers/client-hello.ts b/packages/ui-server/src/ws/handlers/client-hello.ts new file mode 100644 index 0000000000..7c0cec7b7f --- /dev/null +++ b/packages/ui-server/src/ws/handlers/client-hello.ts @@ -0,0 +1,19 @@ +import { FOLLOW_UP_QUEUE_CAPABILITY } from "@schlessera/brain-ui-sdk/protocol"; +import type { ClientMessageHandler } from "./context.js"; + +export const handleClientHello: ClientMessageHandler<"client_hello"> = ({ host, ws, connection }, msg) => { + // Record what this connection speaks. Never rejected on version: a + // future client declaring rev 9 is simply held to the rules this host + // knows, and an unknown capability flag is ignored. + connection.protocolRev = msg.protocolRev; + connection.capabilities = { ...(msg.capabilities ?? {}) }; + host.clients.setCapabilities(ws, msg.capabilities); + // A client that reloaded or reconnected rebuilds every session's + // pending follow-ups from these (#1002). An empty queue sends nothing: + // the client clears its own on each new server_hello. + if (connection.capabilities[FOLLOW_UP_QUEUE_CAPABILITY] === true) { + for (const sessionId of host.coordinator.sessionsWithFollowUps()) { + host.sendMessage(ws, host.followUpQueueFrame(sessionId)); + } + } +}; diff --git a/packages/ui-server/src/ws/handlers/context.ts b/packages/ui-server/src/ws/handlers/context.ts new file mode 100644 index 0000000000..1b46861b53 --- /dev/null +++ b/packages/ui-server/src/ws/handlers/context.ts @@ -0,0 +1,84 @@ +import type { ClientMessage } from "@schlessera/brain-ui-sdk/protocol"; +import type { WSContext } from "../clients.js"; +import type { AuthorizationContext } from "../turns.js"; +import type { WsHost } from "../host.js"; + +/** Per-connection negotiation state, owned by the socket handler. */ +export interface ConnectionState { + /** + * The transport is gone. Set by onClose, and separate from `authorization` + * because a disconnect is not a revocation: work already underway keeps its + * authority, but nothing may register new per-connection state afterwards. + */ + closed?: boolean; + /** Principal resolved once at the WebSocket upgrade boundary. */ + principal: import("../../db/principals.js").Principal; + /** Mutable in-memory decision invalidated synchronously by revocation. */ + authorization: AuthorizationContext; + /** Revision the client declared via `client_hello`; absent means rev 2. */ + protocolRev?: number; + /** Opt-in flags the client declared via `client_hello`. */ + capabilities?: Readonly>; +} + +/** + * Everything a client message handler may use, passed explicitly instead of + * captured from one shared closure. Built once per dispatched frame, after + * the authorization check. + */ +export interface HandlerContext { + readonly host: WsHost; + /** The socket the frame arrived on; replies go here. */ + readonly ws: WSContext; + readonly connection: ConnectionState; + /** + * The connection declared a protocol revision that promises to echo turn + * ids, so a reply without one cannot be correlated (see `turnIdMatches`). + * Read at dispatch: a `client_hello` changes it for later frames only. + */ + readonly requireEcho: boolean; +} + +export type ClientMessageType = ClientMessage["type"]; + +/** The client message whose `type` is `K`. */ +export type ClientMessageOf = Extract; + +/** Handles one or more client message kinds; a shared handler takes their union. */ +export type ClientMessageHandler = ( + ctx: HandlerContext, + msg: ClientMessageOf +) => void | Promise; + +/** + * One handler per client message kind. Mapped over every `type` in + * `ClientMessage`, so a kind without an entry fails typecheck. The function + * type is spelled out rather than reusing `ClientMessageHandler`: through + * the alias TypeScript compares `K` invariantly, which would refuse one + * handler shared by several kinds. + */ +export type ClientMessageHandlers = { + readonly [K in ClientMessageType]: (ctx: HandlerContext, msg: ClientMessageOf) => void | Promise; +}; + +/** + * Does this reply's echoed turnId identify the turn that raised the request? + * + * A wrong id is always refused: a stale echo from before a reconnect or a + * follow-up would resolve a different turn's pending promise. + * + * A MISSING id depends on who is speaking. A client that declared rev 3 + * promised to echo, so silence means the reply cannot be correlated and is + * refused. A client that declared nothing is rev 2, where the field is + * optional, and is still tolerated — that tolerance is the deprecation window, + * and it is what lets this be enforced at all without breaking clients that + * predate `client_hello`. + */ +export function turnIdMatches( + pending: { turnId: string }, + echoed: string | undefined, + requireEcho: boolean +): boolean { + if (echoed === undefined) return !requireEcho; + return echoed === pending.turnId; +} diff --git a/packages/ui-server/src/ws/handlers/conversation.ts b/packages/ui-server/src/ws/handlers/conversation.ts new file mode 100644 index 0000000000..5868e01706 --- /dev/null +++ b/packages/ui-server/src/ws/handlers/conversation.ts @@ -0,0 +1,47 @@ +import type { ConversationHost } from "../conversation.js"; +import type { ClientMessageHandler, ClientMessageOf, HandlerContext } from "./context.js"; + +type ConversationType = + | "conversation_start" + | "conversation_audio" + | "conversation_endpoint" + | "conversation_commit" + | "conversation_playback" + | "conversation_stop"; + +/** + * Every live-conversation frame passes the same gate: nothing registers on a + * closed connection, and a host without a conversation provider says so. + */ +function conversationFrame( + run: (conversations: ConversationHost, ctx: HandlerContext, msg: ClientMessageOf) => void | Promise +): ClientMessageHandler { + return (ctx, msg) => { + if (ctx.connection.closed) return; + const conversations = ctx.host.conversations; + if (!conversations) { + ctx.host.sendMessage(ctx.ws, { type: "error", code: "CONVERSATION_UNAVAILABLE", message: "Live conversation is not configured on this host." }); + return; + } + return run(conversations, ctx, msg); + }; +} + +export const handleConversationStart = conversationFrame<"conversation_start">( + (conversations, { ws, connection }, msg) => conversations.start(ws, connection, msg) +); +export const handleConversationAudio = conversationFrame<"conversation_audio">( + (conversations, { ws, connection }, msg) => conversations.audio(ws, connection, msg) +); +export const handleConversationEndpoint = conversationFrame<"conversation_endpoint">( + (conversations, { ws, connection }, msg) => conversations.endpoint(ws, connection, msg) +); +export const handleConversationCommit = conversationFrame<"conversation_commit">( + (conversations, { ws, connection }, msg) => conversations.commit(ws, connection, msg) +); +export const handleConversationPlayback = conversationFrame<"conversation_playback">( + (conversations, { ws, connection }, msg) => conversations.playback(ws, connection, msg) +); +export const handleConversationStop = conversationFrame<"conversation_stop">( + (conversations, { ws, connection }, msg) => conversations.stop(ws, connection, msg) +); diff --git a/packages/ui-server/src/ws/handlers/dialogue-read.ts b/packages/ui-server/src/ws/handlers/dialogue-read.ts new file mode 100644 index 0000000000..a167cce830 --- /dev/null +++ b/packages/ui-server/src/ws/handlers/dialogue-read.ts @@ -0,0 +1,19 @@ +import { requireKnownSession } from "../session-recovery.js"; +import type { ClientMessageHandler } from "./context.js"; + +export const handleDialogueRead: ClientMessageHandler<"dialogue_read"> = async ({ host, ws, connection }, msg) => { + const { catalog } = host; + if (!connection.authorization.valid || !connection.capabilities?.sessionDialogue || !catalog.dialogueRead) return; + if (msg.sessionId && !await requireKnownSession(host, ws, connection, msg.sessionId, true, msg.requestId)) return; + try { + const page = await catalog.dialogueRead(connection.authorization.principalId, msg); + if (connection.closed || !connection.authorization.valid) return; + if (page) host.sendMessage(ws, { type: "dialogue_history", requestId: msg.requestId, ...page }); + else if (msg.sessionId) host.sendMessage(ws, { type: "dialogue_history", requestId: msg.requestId, + ownerId: msg.sessionId, sessionId: msg.sessionId, generation: 1, through: 0, records: [], coverage: "complete" }); + else throw new Error("Dialogue owner unavailable"); + } catch { + if (!connection.closed && connection.authorization.valid) host.sendMessage(ws, { type: "error", code: "DIALOGUE_UNAVAILABLE", requestId: msg.requestId, + ...(msg.sessionId ? {sessionId: msg.sessionId} : {}), message: "Conversation history unavailable. Try opening this chat again." }); + } +}; diff --git a/packages/ui-server/src/ws/handlers/handoff.ts b/packages/ui-server/src/ws/handlers/handoff.ts new file mode 100644 index 0000000000..0c962814d9 --- /dev/null +++ b/packages/ui-server/src/ws/handlers/handoff.ts @@ -0,0 +1,17 @@ +import { cancelHandoffPreparation, handoffStatus, prepareHandoff } from "../handoff.js"; +import type { ClientMessageHandler } from "./context.js"; + +// A `chat_message` carrying `handoff` starts one; see chat-message.ts. + +export const handleHandoffStatus: ClientMessageHandler<"handoff_status"> = ({ host, ws }, msg) => { + handoffStatus(host, ws, msg.handoffId); +}; + +export const handleHandoffPrepare: ClientMessageHandler<"handoff_prepare"> = async ({ host, ws, connection }, msg) => { + if (connection.closed) return; + await prepareHandoff(host, ws, msg, connection); +}; + +export const handleHandoffPrepareCancel: ClientMessageHandler<"handoff_prepare_cancel"> = ({ host, connection }, msg) => { + cancelHandoffPreparation(host, msg.handoffId, connection); +}; diff --git a/packages/ui-server/src/ws/handlers/inbox.ts b/packages/ui-server/src/ws/handlers/inbox.ts new file mode 100644 index 0000000000..6b7ec37c1d --- /dev/null +++ b/packages/ui-server/src/ws/handlers/inbox.ts @@ -0,0 +1,28 @@ +import type { ClientMessageHandler } from "./context.js"; + +export const handleInboxDecision: ClientMessageHandler<"inbox_resolve" | "inbox_snooze"> = ({ host, ws, connection }, msg) => { + if (connection.closed) return; + if (!host.inbox?.handleDecision) { + host.sendMessage(ws, { type: "error", code: "INBOX_UNAVAILABLE", message: "Inbox decisions are unavailable on this host." }); + return; + } + host.inbox.handleDecision(ws, msg, connection.authorization); +}; + +export const handleInboxSubscribe: ClientMessageHandler<"inbox_subscribe"> = ({ host, ws, connection }, msg) => { + if (connection.closed) return; + if (!host.inbox) { + host.sendMessage(ws, { type: "error", code: "INBOX_UNAVAILABLE", message: "Inbox subscriptions are unavailable on this host." }); + return; + } + host.inbox.handleSubscribe(ws, msg, connection.authorization); +}; + +export const handleInboxUnsubscribe: ClientMessageHandler<"inbox_unsubscribe"> = ({ host, ws, connection }, msg) => { + if (connection.closed) return; + if (!host.inbox) { + host.sendMessage(ws, { type: "error", code: "INBOX_UNAVAILABLE", message: "Inbox subscriptions are unavailable on this host." }); + return; + } + host.inbox.handleUnsubscribe(ws, msg); +}; diff --git a/packages/ui-server/src/ws/handlers/index.ts b/packages/ui-server/src/ws/handlers/index.ts new file mode 100644 index 0000000000..783c335e59 --- /dev/null +++ b/packages/ui-server/src/ws/handlers/index.ts @@ -0,0 +1,69 @@ +import type { ClientMessageHandlers } from "./context.js"; +import { handleActivitySubscribe, handleActivityUnsubscribe } from "./activity.js"; +import { handleAskAnswerFrame, handleAskAnswerStatusFrame, handleAskUserCancel } from "./ask.js"; +import { handleCancel } from "./cancel.js"; +import { handleChatMessageFrame } from "./chat-message.js"; +import { handleClientHello } from "./client-hello.js"; +import { + handleConversationAudio, + handleConversationCommit, + handleConversationEndpoint, + handleConversationPlayback, + handleConversationStart, + handleConversationStop, +} from "./conversation.js"; +import { handleDialogueRead } from "./dialogue-read.js"; +import { handleHandoffPrepare, handleHandoffPrepareCancel, handleHandoffStatus } from "./handoff.js"; +import { handleInboxDecision, handleInboxSubscribe, handleInboxUnsubscribe } from "./inbox.js"; +import { handleLocalExchange } from "./local-exchange.js"; +import { handleLocationError, handleLocationResponse } from "./location.js"; +import { handleMaskError, handleMaskResponse } from "./mask.js"; +import { handlePing } from "./ping.js"; +import { handleRetryStatus, handleRetryTurn } from "./retry.js"; +import { handleScopeDecision } from "./scope-decision.js"; +import { handleSessionResume } from "./session-resume.js"; +import { handleToolApproval, handleToolDenial } from "./tool-permission.js"; + +/** + * The client message dispatch table. Typed as `ClientMessageHandlers`, so a + * kind added to `ClientMessage` without a handler here fails typecheck. + */ +export const CLIENT_MESSAGE_HANDLERS: ClientMessageHandlers = { + client_hello: handleClientHello, + chat_message: handleChatMessageFrame, + handoff_status: handleHandoffStatus, + handoff_prepare: handleHandoffPrepare, + handoff_prepare_cancel: handleHandoffPrepareCancel, + retry_status: handleRetryStatus, + retry_turn: handleRetryTurn, + local_exchange: handleLocalExchange, + scope_decision: handleScopeDecision, + ask_user_response: handleAskAnswerFrame, + ask_user_list_response: handleAskAnswerFrame, + ask_user_rank_response: handleAskAnswerFrame, + ask_user_form_response: handleAskAnswerFrame, + ask_answer_status: handleAskAnswerStatusFrame, + ask_user_cancel: handleAskUserCancel, + ping: handlePing, + location_response: handleLocationResponse, + location_error: handleLocationError, + mask_response: handleMaskResponse, + mask_error: handleMaskError, + tool_approval: handleToolApproval, + tool_denial: handleToolDenial, + cancel: handleCancel, + inbox_resolve: handleInboxDecision, + inbox_snooze: handleInboxDecision, + inbox_subscribe: handleInboxSubscribe, + inbox_unsubscribe: handleInboxUnsubscribe, + activity_subscribe: handleActivitySubscribe, + activity_unsubscribe: handleActivityUnsubscribe, + conversation_start: handleConversationStart, + conversation_audio: handleConversationAudio, + conversation_endpoint: handleConversationEndpoint, + conversation_commit: handleConversationCommit, + conversation_playback: handleConversationPlayback, + conversation_stop: handleConversationStop, + dialogue_read: handleDialogueRead, + session_resume: handleSessionResume, +}; diff --git a/packages/ui-server/src/ws/handlers/local-exchange.ts b/packages/ui-server/src/ws/handlers/local-exchange.ts new file mode 100644 index 0000000000..8875d49d8c --- /dev/null +++ b/packages/ui-server/src/ws/handlers/local-exchange.ts @@ -0,0 +1,23 @@ +import type { ClientMessageHandler } from "./context.js"; + +export const handleLocalExchange: ClientMessageHandler<"local_exchange"> = async ({ host, ws }, msg) => { + const { catalog } = host; + // A command the client answered itself (#582). Stored against the + // session; the next prompt handed to the backend carries its context. + // Answered either way, so the client can say when it is not kept. + // Answered once it is stored (#2850); the next prompt takes it meanwhile. + const saved = (await catalog.recordLocalExchange?.(msg.sessionId, msg.exchange, false)) ?? false; + host.sendMessage(ws, { + type: "local_exchange_result", + sessionId: msg.sessionId, + exchangeId: msg.exchange.id, + saved, + ...(saved + ? {} + : { + reason: catalog.recordLocalExchange + ? "The server could not store it." + : "This server does not keep local answers.", + }), + }); +}; diff --git a/packages/ui-server/src/ws/handlers/location.ts b/packages/ui-server/src/ws/handlers/location.ts new file mode 100644 index 0000000000..ecf749d36b --- /dev/null +++ b/packages/ui-server/src/ws/handlers/location.ts @@ -0,0 +1,14 @@ +import { locationErrorText } from "../frames.js"; +import { turnIdMatches, type ClientMessageHandler } from "./context.js"; + +export const handleLocationResponse: ClientMessageHandler<"location_response"> = ({ host, requireEcho }, msg) => { + host.coordinator + .claimLocation(msg.requestId, (p) => turnIdMatches(p, msg.turnId, requireEcho)) + ?.resolve({ coords: msg.coords, timestamp: msg.timestamp }); +}; + +export const handleLocationError: ClientMessageHandler<"location_error"> = ({ host, requireEcho }, msg) => { + host.coordinator + .claimLocation(msg.requestId, (p) => turnIdMatches(p, msg.turnId, requireEcho)) + ?.reject(new Error(locationErrorText(msg.code, msg.message))); +}; diff --git a/packages/ui-server/src/ws/handlers/mask.ts b/packages/ui-server/src/ws/handlers/mask.ts new file mode 100644 index 0000000000..c694a0cfbc --- /dev/null +++ b/packages/ui-server/src/ws/handlers/mask.ts @@ -0,0 +1,21 @@ +import { turnIdMatches, type ClientMessageHandler } from "./context.js"; + +export const handleMaskResponse: ClientMessageHandler<"mask_response"> = ({ host, requireEcho }, msg) => { + // Decoded here rather than in the tool: the boundary already validated + // the base64 and its size, so the backend gets bytes it can trust. + host.coordinator + .claimMask(msg.requestId, (p) => turnIdMatches(p, msg.turnId, requireEcho)) + ?.resolve(Uint8Array.from(Buffer.from(msg.maskPng, "base64"))); +}; + +export const handleMaskError: ClientMessageHandler<"mask_error"> = ({ host, requireEcho }, msg) => { + host.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" + ) + ); +}; diff --git a/packages/ui-server/src/ws/handlers/ping.ts b/packages/ui-server/src/ws/handlers/ping.ts new file mode 100644 index 0000000000..40499f1c00 --- /dev/null +++ b/packages/ui-server/src/ws/handlers/ping.ts @@ -0,0 +1,7 @@ +import type { ClientMessageHandler } from "./context.js"; + +export const handlePing: ClientMessageHandler<"ping"> = ({ host, ws }, msg) => { + // Liveness (rev 5): answered at once, to this socket only. Anything the + // client receives proves the path is open; the pong correlates it. + host.sendMessage(ws, { type: "pong", probeId: msg.probeId }); +}; diff --git a/packages/ui-server/src/ws/handlers/retry.ts b/packages/ui-server/src/ws/handlers/retry.ts new file mode 100644 index 0000000000..0d745137b0 --- /dev/null +++ b/packages/ui-server/src/ws/handlers/retry.ts @@ -0,0 +1,74 @@ +import type { SharedFileMeta } from "@schlessera/brain-ui-sdk/protocol"; +import { resolveChatFiles, withTrackFiles } from "../../tracks/read.js"; +import { handleChatMessage } from "../run-session.js"; +import type { ClientMessageHandler } from "./context.js"; + +export const handleRetryStatus: ClientMessageHandler<"retry_status"> = async ({ host, ws, connection }, msg) => { + const { catalog } = host; + try { + // Retained retries and their invalidations commit off the event loop (#2850). + await catalog.settled?.(); + host.sendMessage(ws, catalog.retryReceipt?.(msg.sessionId, msg.requestId, connection.authorization.principalId) + ?? { type: "retry_receipt", sessionId: msg.sessionId, requestId: msg.requestId, state: "unknown" }); + } catch { + host.sendMessage(ws, { type: "retry_receipt", sessionId: msg.sessionId, requestId: msg.requestId, state: "unknown" }); + } +}; + +export const handleRetryTurn: ClientMessageHandler<"retry_turn"> = async ({ host, ws, connection }, msg) => { + const { coordinator, catalog } = host; + const refuse = async (message: string) => { + const receipt = { type: "retry_receipt" as const, sessionId: msg.sessionId, requestId: msg.requestId, state: "refused" as const, message }; + try { host.sendMessage(ws, (await catalog.refuseRetry?.(msg.sessionId, msg.requestId, connection.authorization.principalId, message)) ?? receipt); } + catch { host.sendMessage(ws, receipt); } + }; + try { + // Read and reserve against every retained request and invalidation + // submitted before this frame (#2850). One submitted during the file + // check below came with an accepted message, which the admission + // check after it refuses. + await catalog.settled?.(); + // Replay a receipt even while its turn runs. A repeated request id + // cannot become a queued follow-up, including after reconnect. + const prior = catalog.retryReceipt?.(msg.sessionId, msg.requestId, connection.authorization.principalId); + if (prior && prior.state !== "unknown") { host.sendMessage(ws, prior); return; } + if (coordinator.bySession.has(msg.sessionId) || coordinator.startingBySession.has(msg.sessionId)) { + await refuse("This session is busy. Wait for the current turn to finish."); return; + } + if (coordinator.activeRuns() >= host.maxConcurrentSessions()) { + await refuse("The server is busy. Wait for a turn to finish and try again."); return; + } + const original = catalog.peekRetry?.(msg.sessionId); + let files: SharedFileMeta[] | undefined; + if (original?.request.files?.length && original.turnId === msg.failedTurnId && original.principalId === connection.authorization.principalId) { + try { + files = await resolveChatFiles(host.brainPath, original.request.files); + if (!original.prompt.includes(withTrackFiles("", files))) { await refuse("An original track changed. Start a new message with the current file instead."); return; } + } catch { await refuse("An original track is unavailable. Attach it again in a new message."); return; } + if (!connection.authorization.valid) return; + // File reads yield; repeat admission before consuming eligibility. + if (coordinator.bySession.has(msg.sessionId) || coordinator.startingBySession.has(msg.sessionId) || coordinator.activeRuns() >= host.maxConcurrentSessions()) { + await refuse("The session or server became busy. Try again when it is free."); return; + } + } + const reserved = await catalog.reserveRetry?.(msg.sessionId, msg.failedTurnId, msg.requestId, connection.authorization.principalId, files ? original!.prompt : undefined); + if (!reserved) { await refuse("This server cannot retain the original request for Retry."); return; } + host.sendMessage(ws, { ...reserved.receipt, ...(reserved.request ? { + ...(files?.length ? { files } : {}), + text: reserved.request.text, attachmentCount: reserved.request.attachments?.length ?? 0, + source: reserved.request.source ?? "typed", + ...(reserved.request.thinkingLevel !== undefined ? { thinkingLevel: reserved.request.thinkingLevel } : {}), + } : {}) }); + if (reserved.request) { + await handleChatMessage(host, ws, { + ...reserved.request, authorization: connection.authorization, + requestId: msg.requestId, + attachments: reserved.request.attachments ?? [], + files, replayPrompt: reserved.prompt, isRetry: true, + }); + } + } catch { + // A failed database write must not execute an unacknowledged retry. + await refuse("The server could not confirm this retry. Check delivery before trying again."); + } +}; diff --git a/packages/ui-server/src/ws/handlers/scope-decision.ts b/packages/ui-server/src/ws/handlers/scope-decision.ts new file mode 100644 index 0000000000..da825794e6 --- /dev/null +++ b/packages/ui-server/src/ws/handlers/scope-decision.ts @@ -0,0 +1,9 @@ +import type { ClientMessageHandler } from "./context.js"; + +export const handleScopeDecision: ClientMessageHandler<"scope_decision"> = async ({ host, ws, connection }, msg) => { + // Resolves once the decision's own scope writes have committed, so the summary below reads them (#2850). + const receipt = await host.scope?.decide(msg, connection.authorization.valid && connection.authorization.expiresAt > Date.now()) + ?? { ...msg, type: "scope_decision_receipt" as const, state: "refused" as const, reason: "This host cannot answer scope decisions." }; + if (receipt.state !== "refused" && host.journal) host.sendMessage(ws, { type: "turn_journal", sessionId: msg.sessionId, turnId: msg.turnId, journal: { ...host.journal.summary(msg.turnId), ...(host.budgets?.saved(msg.turnId) ? { budget: host.budgets.saved(msg.turnId) } : {}) } }); + host.sendMessage(ws, receipt); +}; diff --git a/packages/ui-server/src/ws/handlers/session-resume.ts b/packages/ui-server/src/ws/handlers/session-resume.ts new file mode 100644 index 0000000000..8316632a93 --- /dev/null +++ b/packages/ui-server/src/ws/handlers/session-resume.ts @@ -0,0 +1,71 @@ +import { FOLLOW_UP_QUEUE_CAPABILITY } from "@schlessera/brain-ui-sdk/protocol"; +import { sendSessionHistory } from "../history.js"; +import { resendPendingApprovals, resendPendingAsks } from "../resend.js"; +import { requireKnownSession } from "../session-recovery.js"; +import type { ClientMessageHandler } from "./context.js"; + +export const handleSessionResume: ClientMessageHandler<"session_resume"> = async ({ host, ws, connection }, msg) => { + const { coordinator, catalog } = host; + let lookupError: string | undefined; + if (!await requireKnownSession(host, ws, connection, msg.sessionId, true, undefined, error => { + lookupError = error instanceof Error ? error.message : "Failed to load session"; + })) { + host.reportSessionResume(msg.sessionId, connection.authorization.valid ? "error" : "unauthorized", + { error: lookupError ?? "Session could not be verified" }); + if (lookupError !== undefined) host.reportTurnFailed("SESSION_LOAD_ERROR", { sessionId: msg.sessionId }, lookupError); + return; + } + host.sendMessage(ws, { + type: "session_info", + sessionId: msg.sessionId, + isNew: false, + providerId: catalog.getStoredProviderId(msg.sessionId) ?? undefined, + backendId: catalog.getStoredBackendId(msg.sessionId) ?? undefined, + }); + + // One log line per resume, whichever way it ends (#1328). + let resumeReported = false; + try { + const backend = await host.registry.getBackendForSession(catalog.getStoredBackendId(msg.sessionId)); + const published = await host.publishHistory(msg.sessionId, backend, () => connection.authorization.valid, (messages) => { + sendSessionHistory(ws, msg.sessionId, host.prepareHistory(msg.sessionId, messages), host.catalog.readStateRoom?.(msg.sessionId)); + host.reportSessionResume(msg.sessionId, "loaded", { messages: messages.length }); + resumeReported = true; + // Replacing history may remove live cards: restore pending requests + // after all chunks, then the whole waiting follow-up queue. + resendPendingApprovals(host, ws, msg.sessionId); + resendPendingAsks(host, ws, msg.sessionId); + if (connection.capabilities?.[FOLLOW_UP_QUEUE_CAPABILITY] === true) { + host.sendMessage(ws, host.followUpQueueFrame(msg.sessionId)); + } + // Read the current turn after history, including any queued turn + // that replaced the one running when the asynchronous read began. + const runningTurn = coordinator.bySession.get(msg.sessionId); + host.sendMessage(ws, { + type: "status", + ...(runningTurn && runningTurn.lastResult === null + ? { status: "thinking" as const, detail: "Session in progress", turnId: runningTurn.turnId } + : { status: "idle" as const, detail: "Session loaded" }), + sessionId: msg.sessionId, + }); + }); + if (!published) { + host.reportSessionResume(msg.sessionId, "unauthorized"); + return; + } + } catch (err) { + if (!connection.authorization.valid) { + host.reportSessionResume(msg.sessionId, "unauthorized"); + return; + } + const message = err instanceof Error ? err.message : "Failed to load session"; + if (!resumeReported) host.reportSessionResume(msg.sessionId, "error", { error: message }); + host.reportTurnFailed("SESSION_LOAD_ERROR", { sessionId: msg.sessionId }, message); + host.sendMessage(ws, { + type: "error", + code: "SESSION_LOAD_ERROR", + message: "The host could not load this conversation. No work was started; your draft is kept.", + sessionId: msg.sessionId, + }); + } +}; diff --git a/packages/ui-server/src/ws/handlers/tool-permission.ts b/packages/ui-server/src/ws/handlers/tool-permission.ts new file mode 100644 index 0000000000..7a4eb8b153 --- /dev/null +++ b/packages/ui-server/src/ws/handlers/tool-permission.ts @@ -0,0 +1,140 @@ +import { approvalRequestFrame, withTurnScope } from "../frames.js"; +import { turnIdMatches, type ClientMessageHandler, type HandlerContext } from "./context.js"; + +/** + * Answer a permission reply that applied to nothing pending (#957): the host + * says what actually happened instead of letting the sender assume. A reply + * whose turn echo does not match the settled request learns `unknown` — it + * was never about that request. + */ +export function replyResolution( + { host, ws, connection, requireEcho }: HandlerContext, + toolUseId: string, + echoed: string | undefined +): void { + if (connection.capabilities?.toolResolution !== true) return; + const record = host.coordinator.resolvedApprovals.get(toolUseId); + if (record && turnIdMatches(record, echoed, requireEcho)) { + host.sendMessage(ws, { + 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 } : {}), + }); + return; + } + host.sendMessage(ws, { type: "tool_resolution", toolUseId, outcome: "unknown", ...(echoed ? { turnId: echoed } : {}) }); +} + +export const handleToolApproval: ClientMessageHandler<"tool_approval"> = async (ctx, msg) => { + const { host, ws, connection, requireEcho } = ctx; + const { coordinator } = host; + const pending = coordinator.pendingApprovals.get(msg.toolUseId); + if (!pending || !turnIdMatches(pending, msg.turnId, requireEcho)) { + replyResolution(ctx, msg.toolUseId, msg.turnId); + return; + } + // Voice may deny; it may never grant (docs/decisions/voice-permission.md). + // A grant attributed to voice is refused before anything else looks + // at it: the request stays pending, nothing is recorded or + // remembered, and the card is still there to answer it. The wire is + // not trusted to enforce policy — a client offering no spoken grant + // is not the reason this holds. + if (msg.channel === "voice") { + host.log.emit({ + severityText: "WARN", + body: "voice-attributed grant refused", + attributes: { + "tool.name": pending.request.toolName, + "toolUse.id": pending.request.toolUseId, + }, + }); + // The sender treated its reply as the end of the exchange — a + // client drops the request's turn correlation once it answers, and + // may have cleared the card — so hand it the card again, exactly + // as a reconnect would. Without this its next answer (the card's, + // or a spoken denial) arrives uncorrelated and is dropped too. + host.sendMessage( + ws, + withTurnScope( + approvalRequestFrame(pending.request, host.toolPermissions !== null), + pending.turn, + pending.turnId + ) + ); + return; + } + 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 + // this tool is outside of: the store is read by every OTHER turn, and + // a grant made inside a narrower posture must not widen the ones the + // user was not looking at. The call itself still runs — they approved + // it — it is only the memory that is refused. + // The store being absent is one of the reasons, not an exemption from + // them: optional-chaining the add() away would take the "remembered" + // branch, write nothing, log nothing, and still stamp the activity + // record `always_allow` — the exact silent refusal this block exists + // to rule out. Embedders wire a store (app.ts) so this is the + // test/embedder path, which is precisely where a silent no-op is + // hardest to notice. + const store = host.toolPermissions; + const remembers = + store !== null && + pending.request.kind !== "command" && pending.request.kind !== "policy" && + !pending.request.outsideEnforcedAllowlist; + if (msg.always && remembers) { + await store.add(pending.request.toolName); + } else if (msg.always) { + // The user asked for something the host will not do. Recorded for + // the same reason the bridge records a grant it declines to apply: + // a refusal nobody can see is indistinguishable from a bug, and for + // kind "command" it also says a client sent an option its own UI + // does not offer. + host.log.emit({ + severityText: "INFO", + body: "always-allow not remembered", + attributes: { + "tool.name": pending.request.toolName, + "toolUse.id": pending.request.toolUseId, + reason: + store === null + ? "no grant store configured" + : pending.request.kind === "command" + ? "per-use confirmation" + : "outside this turn's enforced allowlist", + }, + }); + } + coordinator.settleApproval( + msg.toolUseId, + pending, + msg.updatedInput + ? { behavior: "allow", updatedInput: msg.updatedInput } + : { behavior: "allow" }, + { + principalId: connection.authorization.principalId, + ...(msg.always && remembers ? { always: true } : {}), + ...(msg.channel ? { channel: msg.channel } : {}), + } + ); +}; + +export const handleToolDenial: ClientMessageHandler<"tool_denial"> = (ctx, msg) => { + const { host, connection, requireEcho } = ctx; + const pending = host.coordinator.claimApproval(msg.toolUseId, (p) => turnIdMatches(p, msg.turnId, requireEcho)); + if (pending) { + host.coordinator.settleApproval(msg.toolUseId, pending, { behavior: "deny", message: msg.message }, { + principalId: connection.authorization.principalId, + ...(msg.channel ? { channel: msg.channel } : {}), + }); + } else { + // Already granted, expired, or never pending: a denial that lost a + // race is told so, never confirmed (a visual grant stays a grant). + replyResolution(ctx, msg.toolUseId, msg.turnId); + } +}; From 1c686184cea3f62df6d74f57bfe194018852c98d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 16:55:10 +0000 Subject: [PATCH 2/4] test(ui-server): test each client message handler directly and re-anchor moved citations Each handler is called with an explicit context over a real TurnCoordinator and a recording host stub. Citations of dispatch.ts follow the code into handlers/tool-permission.ts, handlers/session-resume.ts and handlers/context.ts. Refs #1358 Co-Authored-By: Claude Opus 5.5 --- docs/decisions/answer-delivery.md | 2 +- docs/decisions/session-principals.md | 2 +- docs/decisions/voice-permission.md | 10 +- .../live-conversation-investigation.md | 4 +- docs/plans/chat-history-deletion.md | 4 +- docs/plans/navigation-recovery.md | 2 +- packages/ui-server/tests/ws-handlers.test.ts | 486 ++++++++++++++++++ 7 files changed, 498 insertions(+), 12 deletions(-) create mode 100644 packages/ui-server/tests/ws-handlers.test.ts diff --git a/docs/decisions/answer-delivery.md b/docs/decisions/answer-delivery.md index 81796a218d..8410fba3c2 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:651`). Before this, a resume replaced +`packages/ui-server/src/ws/handlers/session-resume.ts:37`). Before this, a resume replaced the transcript and left only a history card behind, which was the second symptom. diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index 730ab1dae5..21ceee3645 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -243,7 +243,7 @@ mint (owner only, router mounted AFTER the guard) ──► upgradeWebSocket((c) => createWsHandlers(host, c.get("principal"))) (hono passes the context to createEvents: hono/helper/websocket/index.js:34) - ──► ConnectionState.principal (ws/dispatch.ts:14-17) + ──► ConnectionState.principal (ws/handlers/context.ts:14-15) ──► clients.add(ws, principalId) ──► QueuedFollowUp.principalId / RunningTurn.principalId (reset per queued follow-up, like lastResult) diff --git a/docs/decisions/voice-permission.md b/docs/decisions/voice-permission.md index 7dc06c57ca..4d488cc84c 100644 --- a/docs/decisions/voice-permission.md +++ b/docs/decisions/voice-permission.md @@ -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:437-443`) +(the block computing `remembers`, `packages/ui-server/src/ws/handlers/tool-permission.ts:86-92`) 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:437-443`, and the lookup computing +(the block computing `remembers`, `tool-permission.ts:86-92`, and the lookup computing `remembered`, `ws/bridge.ts:372-392`), and 192 of 192 measured approvals were kind `command`. @@ -504,8 +504,8 @@ the record is by construction a bug — which makes the field a detector, not ju 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:480-493`) with a message naming the +(its handler `handleToolDenial`, +`packages/ui-server/src/ws/handlers/tool-permission.ts:127-140`) 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:437-443`). + `packages/ui-server/src/ws/handlers/tool-permission.ts:86-92`). 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 82a01755a5..0e98526905 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:397-420`). +(`if (msg.channel === "voice")`, `packages/ui-server/src/ws/handlers/tool-permission.ts:46-69`). 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:480-493`). The +(`handleToolDenial`, `packages/ui-server/src/ws/handlers/tool-permission.ts:127-140`). 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/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index b830b24809..ed15b81423 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -229,8 +229,8 @@ and both handoff stages (`startHandoff`, `packages/ui-server/src/ws/handoff.ts:1 belongs to `createDraftClient` (`createDraftClient`, `packages/ui-react/src/lib/draft-client.ts:45-57`); browser reloadable work belongs to `createLocalWork` (`createLocalWork`, `packages/ui-react/src/lib/local-work.ts:227-245`). -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. +The paired WS dispatcher is `packages/ui-server/src/ws/dispatch.ts`, with one +handler per frame under `ws/handlers/`; gating its resume handler 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:540-574`). Future deletion diff --git a/docs/plans/navigation-recovery.md b/docs/plans/navigation-recovery.md index 01ea06e510..1f5b17afbc 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:622-686`). +- Host resume: (`export const handleSessionResume`, `packages/ui-server/src/ws/handlers/session-resume.ts:7-71`). - Catalog activity: (`persistSessionStub(sessionId, promptText, providerId, backendId) {`, `packages/ui-server/src/ws/session-catalog.ts:479-486`). diff --git a/packages/ui-server/tests/ws-handlers.test.ts b/packages/ui-server/tests/ws-handlers.test.ts new file mode 100644 index 0000000000..c9f02c83c7 --- /dev/null +++ b/packages/ui-server/tests/ws-handlers.test.ts @@ -0,0 +1,486 @@ +// Direct tests for each client message handler under src/ws/handlers/ (#1358). +// +// Every handler takes an explicit context, so each one is exercised here +// without a socket, an app or the dispatch closure: a real TurnCoordinator +// holds pending state, and the rest of the host is a recording stub carrying +// only what the handler reads. The runtime suites (ws-*.test.ts) remain the +// behavioural guard through the real dispatch path. + +import { describe, expect, test } from "bun:test"; +import type { ClientMessage, ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; +import type { WSContext } from "../src/ws/clients"; +import type { WsHost } from "../src/ws/host"; +import { TurnCoordinator, type PendingApproval, type RunningTurn } from "../src/ws/turns"; +import type { ClientMessageOf, ClientMessageType, ConnectionState, HandlerContext } from "../src/ws/handlers/context"; +import { CLIENT_MESSAGE_HANDLERS } from "../src/ws/handlers/index"; +import { handleActivitySubscribe, handleActivityUnsubscribe } from "../src/ws/handlers/activity"; +import { handleAskAnswerFrame, handleAskAnswerStatusFrame, handleAskUserCancel } from "../src/ws/handlers/ask"; +import { handleCancel } from "../src/ws/handlers/cancel"; +import { handleChatMessageFrame } from "../src/ws/handlers/chat-message"; +import { handleClientHello } from "../src/ws/handlers/client-hello"; +import { + handleConversationAudio, + handleConversationCommit, + handleConversationEndpoint, + handleConversationPlayback, + handleConversationStart, + handleConversationStop, +} from "../src/ws/handlers/conversation"; +import { handleDialogueRead } from "../src/ws/handlers/dialogue-read"; +import { handleHandoffPrepare, handleHandoffPrepareCancel, handleHandoffStatus } from "../src/ws/handlers/handoff"; +import { handleInboxDecision, handleInboxSubscribe, handleInboxUnsubscribe } from "../src/ws/handlers/inbox"; +import { handleLocalExchange } from "../src/ws/handlers/local-exchange"; +import { handleLocationError, handleLocationResponse } from "../src/ws/handlers/location"; +import { handleMaskError, handleMaskResponse } from "../src/ws/handlers/mask"; +import { handlePing } from "../src/ws/handlers/ping"; +import { handleRetryStatus, handleRetryTurn } from "../src/ws/handlers/retry"; +import { handleScopeDecision } from "../src/ws/handlers/scope-decision"; +import { handleSessionResume } from "../src/ws/handlers/session-resume"; +import { handleToolApproval, handleToolDenial } from "../src/ws/handlers/tool-permission"; +import { testAuthorization, testPrincipal } from "./helpers/principal"; + +const ws = { id: "socket" } as unknown as WSContext; + +interface Harness { + ctx: HandlerContext; + coordinator: TurnCoordinator; + sent: ServerMessage[]; + calls: string[]; +} + +/** A context whose host is `overrides` over a recording base. */ +function harness( + overrides: Record = {}, + connection: Partial = {}, + requireEcho = false +): Harness { + const coordinator = new TurnCoordinator(); + const sent: ServerMessage[] = []; + const calls: string[] = []; + const host = { + coordinator, + catalog: {}, + sendMessage: (_ws: WSContext, msg: ServerMessage) => { sent.push(msg); }, + sendToClients: (msg: ServerMessage) => { sent.push(msg); }, + log: { emit: (record: { body: string }) => { calls.push(`log:${record.body}`); } }, + toolPermissions: null, + conversations: null, + inbox: null, + activity: null, + closing: false, + expireAuthorizationContexts: () => {}, + reportDroppedFrame: (reason: string) => { calls.push(`dropped:${reason}`); }, + reportSessionResume: (_id: string, outcome: string) => { calls.push(`resume:${outcome}`); }, + reportTurnFailed: (code: string) => { calls.push(`failed:${code}`); }, + maxConcurrentSessions: () => 3, + ...overrides, + } as unknown as WsHost; + const ctx: HandlerContext = { + host, + ws, + connection: { principal: testPrincipal(), authorization: testAuthorization(), ...connection }, + requireEcho, + }; + return { ctx, coordinator, sent, calls }; +} + +function frame(msg: { type: K } & Record): ClientMessageOf { + return msg as unknown as ClientMessageOf; +} + +function turn(sessionId: string | null = "s1", turnId = "t1"): RunningTurn { + return { + sessionId, + turnId, + principalId: "test-principal", + pendingCancellationPrincipalIds: [], + abortController: new AbortController(), + timeoutHandle: setTimeout(() => {}, 0), + queue: [], + cancelled: false, + lastResult: null, + } as unknown as RunningTurn; +} + +/** A pending request whose settlement is observable. */ +function settleable() { + const seen: { resolved?: T; rejected?: string } = {}; + return { + seen, + resolve: (value: T) => { seen.resolved = value; }, + reject: (error: Error) => { seen.rejected = error.message; }, + }; +} + +function approval(t: RunningTurn, kind = "edit"): { entry: PendingApproval; decisions: unknown[] } { + const decisions: unknown[] = []; + return { + decisions, + entry: { + turn: t, + turnId: t.turnId, + request: { toolUseId: "tu1", toolName: "Edit", kind, input: {} }, + resolve: (decision, response) => { decisions.push({ decision, response }); }, + } as unknown as PendingApproval, + }; +} + +describe("the handler table", () => { + test("ignores a frame whose type names an inherited property", async () => { + // The table is a plain object; dispatch must not call Object.prototype. + const { handleClientMessage } = await import("../src/ws/dispatch"); + // `__proto__` resolves to Object.prototype, which is not callable. + const h = harness(); + await expect( + handleClientMessage(h.ctx.host, ws, { type: "__proto__" } as unknown as ClientMessage, h.ctx.connection) + ).resolves.toBeUndefined(); + expect(h.sent).toEqual([]); + }); + + test("passes the connection's echo requirement to the handler", async () => { + const { handleClientMessage } = await import("../src/ws/dispatch"); + const h = harness(); + const t = turn(); + const pending = settleable(); + h.coordinator.openLocation("loc1", { turn: t, turnId: "t1", ...pending }); + // A rev-3 client must echo; this reply does not, so it settles nothing. + await handleClientMessage(h.ctx.host, ws, frame({ type: "location_error", requestId: "loc1", code: "denied" }), + { ...h.ctx.connection, protocolRev: 3 }); + expect(pending.seen.rejected).toBeUndefined(); + expect(h.coordinator.pendingLocation.has("loc1")).toBe(true); + }); + + test("drops a frame on a revoked connection before any handler runs", async () => { + const { handleClientMessage } = await import("../src/ws/dispatch"); + const h = harness(); + await handleClientMessage(h.ctx.host, ws, frame({ type: "ping", probeId: "p" }), + { ...h.ctx.connection, authorization: { ...testAuthorization(), valid: false } as never }); + expect(h.sent).toEqual([]); + expect(h.calls).toEqual(["dropped:revoked_principal"]); + }); + + test("has an own entry for every kind", () => { + for (const handler of Object.values(CLIENT_MESSAGE_HANDLERS)) expect(typeof handler).toBe("function"); + }); +}); + +describe("client_hello", () => { + test("records the revision and capabilities and replays follow-up queues", () => { + const capabilities: unknown[] = []; + const h = harness({ + clients: { setCapabilities: (_ws: WSContext, caps: unknown) => { capabilities.push(caps); } }, + followUpQueueFrame: (sessionId: string) => ({ type: "follow_up_queue", sessionId, entries: [] }), + }); + (h.coordinator as unknown as { sessionsWithFollowUps: () => string[] }).sessionsWithFollowUps = () => ["s1", "s2"]; + handleClientHello(h.ctx, frame({ type: "client_hello", protocolRev: 4, capabilities: { followUpQueue: true } })); + expect(h.ctx.connection.protocolRev).toBe(4); + expect(h.ctx.connection.capabilities).toEqual({ followUpQueue: true }); + expect(capabilities).toEqual([{ followUpQueue: true }]); + expect(h.sent.map((m) => (m as { sessionId?: string }).sessionId)).toEqual(["s1", "s2"]); + }); +}); + +describe("chat_message", () => { + test("refuses a share intake on a host without bound share filing", async () => { + const h = harness(); + await handleChatMessageFrame(h.ctx, frame({ type: "chat_message", text: "hi", shareId: "sh1", requestId: "r1" })); + expect(h.sent).toEqual([{ type: "error", code: "SESSION_BUSY", message: "This host does not support bound share filing", requestId: "r1" }]); + }); + + test("refuses track files on a host without a brain path", async () => { + const h = harness(); + await handleChatMessageFrame(h.ctx, frame({ type: "chat_message", text: "hi", sessionId: "s1", + files: [{ kind: "file", path: "tracks/a.md" }] })); + expect(h.sent).toEqual([{ type: "error", code: "ATTACHMENT_REJECTED", message: "Track attachments are unavailable on this host.", sessionId: "s1" }]); + }); +}); + +describe("handoff frames", () => { + test("handoff_status reports a created handoff from the catalog", () => { + const h = harness({ catalog: { findHandoff: () => "s9" } }); + handleHandoffStatus(h.ctx, frame({ type: "handoff_status", handoffId: "h1" })); + expect(h.sent).toEqual([{ type: "handoff_receipt", handoffId: "h1", state: "created", sessionId: "s9" }]); + }); + + test("handoff_prepare does nothing on a closed connection", async () => { + const h = harness({}, { closed: true }); + await handleHandoffPrepare(h.ctx, frame({ type: "handoff_prepare", handoffId: "h1", sessionId: "s1" })); + expect(h.sent).toEqual([]); + }); + + test("handoff_prepare_cancel aborts only this connection's preparation", () => { + const h = harness(); + const mine = new AbortController(); + h.coordinator.registerHandoffPreparation("h1", { abort: mine, owner: h.ctx.connection }); + const theirs = new AbortController(); + h.coordinator.registerHandoffPreparation("h2", { abort: theirs, owner: {} }); + handleHandoffPrepareCancel(h.ctx, frame({ type: "handoff_prepare_cancel", handoffId: "h1" })); + handleHandoffPrepareCancel(h.ctx, frame({ type: "handoff_prepare_cancel", handoffId: "h2" })); + expect([mine.signal.aborted, theirs.signal.aborted]).toEqual([true, false]); + }); +}); + +describe("retry frames", () => { + test("retry_status answers unknown when the catalog keeps no receipts", async () => { + const h = harness(); + await handleRetryStatus(h.ctx, frame({ type: "retry_status", sessionId: "s1", requestId: "r1" })); + expect(h.sent).toEqual([{ type: "retry_receipt", sessionId: "s1", requestId: "r1", state: "unknown" }]); + }); + + test("retry_turn refuses while the server is at its run cap", async () => { + const h = harness({ maxConcurrentSessions: () => 0 }); + await handleRetryTurn(h.ctx, frame({ type: "retry_turn", sessionId: "s1", requestId: "r1", failedTurnId: "t0" })); + expect(h.sent).toEqual([{ type: "retry_receipt", sessionId: "s1", requestId: "r1", state: "refused", + message: "The server is busy. Wait for a turn to finish and try again." }]); + }); +}); + +describe("local_exchange", () => { + test("says when the host does not keep local answers", async () => { + const h = harness(); + await handleLocalExchange(h.ctx, frame({ type: "local_exchange", sessionId: "s1", exchange: { id: "x1" } })); + expect(h.sent).toEqual([{ type: "local_exchange_result", sessionId: "s1", exchangeId: "x1", saved: false, + reason: "This server does not keep local answers." }]); + }); +}); + +describe("scope_decision", () => { + test("refuses on a host without a scope service", async () => { + const h = harness(); + await handleScopeDecision(h.ctx, frame({ type: "scope_decision", sessionId: "s1", turnId: "t1", decisionId: "d1" })); + expect(h.sent).toEqual([{ type: "scope_decision_receipt", sessionId: "s1", turnId: "t1", decisionId: "d1", + state: "refused", reason: "This host cannot answer scope decisions." }]); + }); +}); + +describe("ask frames", () => { + test("an answer without a submission id is dropped and told to update", () => { + const h = harness(); + for (const type of ["ask_user_response", "ask_user_list_response", "ask_user_rank_response", "ask_user_form_response"] as const) { + handleAskAnswerFrame(h.ctx, frame({ type, requestId: "q1" })); + } + expect(h.calls).toEqual(Array(4).fill("dropped:ask_answer_without_receipt")); + expect(h.sent.map((m) => m.type)).toEqual(["error", "error", "error", "error"]); + }); + + test("ask_answer_status reports a pending ask", () => { + const h = harness(); + const t = turn(); + h.coordinator.openAsk("ask_user", { turn: t, turnId: "t1", requestId: "q1", questions: [], ...settleable() } as never); + handleAskAnswerStatusFrame(h.ctx, frame({ type: "ask_answer_status", requestId: "q1", submissionId: "sub1" })); + expect(h.sent).toMatchObject([{ requestId: "q1", submissionId: "sub1", state: "pending", sessionId: "s1", turnId: "t1" }]); + }); + + test("ask_user_cancel rejects a matching ask and records the dismissal", () => { + const h = harness({}, {}, true); + const t = turn(); + const pending = settleable(); + h.coordinator.openAsk("ask_user", { turn: t, turnId: "t1", requestId: "q1", questions: [], ...pending } as never); + handleAskUserCancel(h.ctx, frame({ type: "ask_user_cancel", requestId: "q1" })); + expect(pending.seen.rejected).toBeUndefined(); // a rev-3 client must echo + handleAskUserCancel(h.ctx, frame({ type: "ask_user_cancel", requestId: "q1", turnId: "t1", reason: "not now" })); + expect(pending.seen.rejected).toBe("not now"); + expect(h.coordinator.askOutcome("q1")).toMatchObject({ state: "closed", reason: "cancelled" }); + }); +}); + +describe("ping", () => { + test("answers with a pong carrying the probe id", () => { + const h = harness(); + handlePing(h.ctx, frame({ type: "ping", probeId: "p1" })); + expect(h.sent).toEqual([{ type: "pong", probeId: "p1" }]); + }); +}); + +describe("location frames", () => { + test("location_response resolves the matching request", () => { + const h = harness(); + const pending = settleable(); + h.coordinator.openLocation("l1", { turn: turn(), turnId: "t1", ...pending }); + handleLocationResponse(h.ctx, frame({ type: "location_response", requestId: "l1", turnId: "t1", coords: { latitude: 1 }, timestamp: 5 })); + expect(pending.seen.resolved).toEqual({ coords: { latitude: 1 }, timestamp: 5 }); + }); + + test("location_error rejects the request, and a wrong turn leaves it pending", () => { + const h = harness(); + const pending = settleable(); + h.coordinator.openLocation("l1", { turn: turn(), turnId: "t1", ...pending }); + handleLocationError(h.ctx, frame({ type: "location_error", requestId: "l1", turnId: "other", code: "denied" })); + expect(h.coordinator.pendingLocation.has("l1")).toBe(true); + handleLocationError(h.ctx, frame({ type: "location_error", requestId: "l1", turnId: "t1", code: "denied" })); + expect(pending.seen.rejected).toBeString(); + expect(h.coordinator.pendingLocation.has("l1")).toBe(false); + }); +}); + +describe("mask frames", () => { + test("mask_response decodes the PNG bytes", () => { + const h = harness(); + const pending = settleable(); + h.coordinator.openMask("m1", { turn: turn(), turnId: "t1", ...pending }); + handleMaskResponse(h.ctx, frame({ type: "mask_response", requestId: "m1", maskPng: Buffer.from([1, 2, 3]).toString("base64") })); + expect([...pending.seen.resolved!]).toEqual([1, 2, 3]); + }); + + test("mask_error names a cancelled mark", () => { + const h = harness(); + const pending = settleable(); + h.coordinator.openMask("m1", { turn: turn(), turnId: "t1", ...pending }); + handleMaskError(h.ctx, frame({ type: "mask_error", requestId: "m1", code: "cancelled", message: "closed" })); + expect(pending.seen.rejected).toBe("The user did not mark an area: closed"); + }); +}); + +describe("tool permission frames", () => { + test("tool_approval grants a matching request and refuses to remember a command", async () => { + const h = harness({ toolPermissions: { add: async () => {} } }); + const { entry, decisions } = approval(turn(), "command"); + h.coordinator.openApproval("tu1", entry); + await handleToolApproval(h.ctx, frame({ type: "tool_approval", toolUseId: "tu1", turnId: "t1", always: true })); + expect(decisions).toEqual([{ decision: { behavior: "allow" }, response: { principalId: "test-principal" } }]); + expect(h.calls).toEqual(["log:always-allow not remembered"]); + expect(h.coordinator.resolvedApprovals.get("tu1")).toMatchObject({ outcome: "granted" }); + }); + + test("tool_approval refuses a voice grant and re-sends the card", async () => { + const h = harness(); + const { entry, decisions } = approval(turn()); + h.coordinator.openApproval("tu1", entry); + await handleToolApproval(h.ctx, frame({ type: "tool_approval", toolUseId: "tu1", turnId: "t1", channel: "voice" })); + expect(decisions).toEqual([]); + expect(h.coordinator.pendingApprovals.has("tu1")).toBe(true); + expect(h.calls).toEqual(["log:voice-attributed grant refused"]); + expect(h.sent).toMatchObject([{ type: "tool_approval_request", toolUseId: "tu1", turnId: "t1" }]); + }); + + test("tool_approval for nothing pending is answered unknown to a resolution-aware client", async () => { + const h = harness({}, { capabilities: { toolResolution: true } }); + await handleToolApproval(h.ctx, frame({ type: "tool_approval", toolUseId: "tu9", turnId: "t1" })); + expect(h.sent).toEqual([{ type: "tool_resolution", toolUseId: "tu9", outcome: "unknown", turnId: "t1" }]); + }); + + test("tool_denial denies a matching request, and a late denial learns the grant", () => { + const h = harness({}, { capabilities: { toolResolution: true } }); + const { entry, decisions } = approval(turn()); + h.coordinator.openApproval("tu1", entry); + handleToolDenial(h.ctx, frame({ type: "tool_denial", toolUseId: "tu1", turnId: "t1", message: "no" })); + expect(decisions).toEqual([{ decision: { behavior: "deny", message: "no" }, response: { principalId: "test-principal" } }]); + handleToolDenial(h.ctx, frame({ type: "tool_denial", toolUseId: "tu1", turnId: "t1", message: "again" })); + expect(h.sent).toEqual([{ type: "tool_resolution", toolUseId: "tu1", outcome: "denied", sessionId: "s1", turnId: "t1" }]); + }); +}); + +describe("cancel", () => { + test("cancels a session's running turn and tells its conversation", () => { + const cancelled: string[] = []; + const h = harness({ conversations: { sessionCancelled: (id: string) => { cancelled.push(id); } } }); + const t = turn(); + h.coordinator.registerTurn(t); + handleCancel(h.ctx, frame({ type: "cancel", sessionId: "s1" })); + expect(t.cancelled).toBe(true); + expect(t.abortController.signal.aborted).toBe(true); + expect(t.pendingCancellationPrincipalIds).toEqual(["test-principal"]); + expect(cancelled).toEqual(["s1"]); + }); + + test("refuses an unscoped cancel while several sessions run", () => { + const h = harness(); + h.coordinator.registerTurn(turn("s1")); + h.coordinator.registerTurn(turn("s2")); + handleCancel(h.ctx, frame({ type: "cancel" })); + expect(h.sent).toMatchObject([{ type: "error", code: "CANCEL_AMBIGUOUS" }]); + }); +}); + +describe("inbox frames", () => { + test("each inbox frame says when the host has no inbox", () => { + const h = harness(); + handleInboxDecision(h.ctx, frame({ type: "inbox_resolve", id: "i1" })); + handleInboxDecision(h.ctx, frame({ type: "inbox_snooze", id: "i1" })); + handleInboxSubscribe(h.ctx, frame({ type: "inbox_subscribe" })); + handleInboxUnsubscribe(h.ctx, frame({ type: "inbox_unsubscribe" })); + expect(h.sent.map((m) => (m as { code?: string }).code)).toEqual(Array(4).fill("INBOX_UNAVAILABLE")); + }); + + test("forwards to the inbox, and not on a closed connection", () => { + const seen: string[] = []; + const inbox = { + handleDecision: (_ws: WSContext, msg: ClientMessage) => { seen.push(msg.type); }, + handleSubscribe: (_ws: WSContext, msg: ClientMessage) => { seen.push(msg.type); }, + handleUnsubscribe: (_ws: WSContext, msg: ClientMessage) => { seen.push(msg.type); }, + }; + const open = harness({ inbox }); + handleInboxDecision(open.ctx, frame({ type: "inbox_snooze", id: "i1" })); + handleInboxSubscribe(open.ctx, frame({ type: "inbox_subscribe" })); + handleInboxUnsubscribe(open.ctx, frame({ type: "inbox_unsubscribe" })); + const closed = harness({ inbox }, { closed: true }); + handleInboxSubscribe(closed.ctx, frame({ type: "inbox_subscribe" })); + expect(seen).toEqual(["inbox_snooze", "inbox_subscribe", "inbox_unsubscribe"]); + }); +}); + +describe("activity frames", () => { + test("subscribes an open connection only, and always unsubscribes", () => { + const seen: string[] = []; + const activity = { stream: { + handleSubscribe: (_ws: WSContext, _msg: unknown, principalId: string) => { seen.push(`sub:${principalId}`); }, + handleUnsubscribe: () => { seen.push("unsub"); }, + } }; + handleActivitySubscribe(harness({ activity }, { closed: true }).ctx, frame({ type: "activity_subscribe" })); + const h = harness({ activity }); + handleActivitySubscribe(h.ctx, frame({ type: "activity_subscribe" })); + handleActivityUnsubscribe(h.ctx, frame({ type: "activity_unsubscribe" })); + expect(seen).toEqual(["sub:test-principal", "unsub"]); + }); +}); + +describe("conversation frames", () => { + const handlers = { + conversation_start: handleConversationStart, + conversation_audio: handleConversationAudio, + conversation_endpoint: handleConversationEndpoint, + conversation_commit: handleConversationCommit, + conversation_playback: handleConversationPlayback, + conversation_stop: handleConversationStop, + } as const; + + test("each frame reaches its own conversation method", async () => { + const seen: string[] = []; + const record = (name: string) => () => { seen.push(name); }; + const conversations = { start: async () => { seen.push("start"); }, audio: record("audio"), endpoint: record("endpoint"), + commit: record("commit"), playback: record("playback"), stop: record("stop") }; + const h = harness({ conversations }); + for (const [type, handle] of Object.entries(handlers)) { + await (handle as (ctx: HandlerContext, msg: unknown) => unknown)(h.ctx, frame({ type: type as ClientMessageType })); + } + expect(seen).toEqual(["start", "audio", "endpoint", "commit", "playback", "stop"]); + }); + + test("a host without conversations says so; a closed connection hears nothing", () => { + const h = harness(); + handleConversationAudio(h.ctx, frame({ type: "conversation_audio" })); + handleConversationStop(harness({}, { closed: true }).ctx, frame({ type: "conversation_stop" })); + expect(h.sent).toMatchObject([{ type: "error", code: "CONVERSATION_UNAVAILABLE" }]); + }); +}); + +describe("dialogue_read", () => { + test("is silent without the capability, and reports an unavailable owner", async () => { + const dialogueRead = async () => null; + const without = harness({ catalog: { dialogueRead } }); + await handleDialogueRead(without.ctx, frame({ type: "dialogue_read", requestId: "r1" })); + expect(without.sent).toEqual([]); + const h = harness({ catalog: { dialogueRead } }, { capabilities: { sessionDialogue: true } }); + await handleDialogueRead(h.ctx, frame({ type: "dialogue_read", requestId: "r1" })); + expect(h.sent).toMatchObject([{ type: "error", code: "DIALOGUE_UNAVAILABLE", requestId: "r1" }]); + }); +}); + +describe("session_resume", () => { + test("reports a catalog failure once, as a load error", async () => { + const h = harness({ catalog: { hasSession: () => { throw new Error("disk"); } } }); + await handleSessionResume(h.ctx, frame({ type: "session_resume", sessionId: "s1" })); + expect(h.sent).toMatchObject([{ type: "error", code: "SESSION_LOAD_ERROR", sessionId: "s1" }]); + expect(h.calls).toEqual(["resume:error", "failed:SESSION_LOAD_ERROR"]); + }); +}); From f1c63eef85dc1ca12174cd22427c2327f1d9bae9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 16:55:39 +0000 Subject: [PATCH 3/4] chore(ui-server): changeset for the client message handler table Refs #1358 Co-Authored-By: Claude Opus 5.5 --- .changeset/client-message-handler-table.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/client-message-handler-table.md diff --git a/.changeset/client-message-handler-table.md b/.changeset/client-message-handler-table.md new file mode 100644 index 0000000000..8e950ff4c3 --- /dev/null +++ b/.changeset/client-message-handler-table.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +WebSocket client messages are now dispatched through a per-message handler table. Behaviour and the wire protocol are unchanged. From 25ac5788da0dc22040bd32f02e746ce7120a500f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 17:36:54 +0000 Subject: [PATCH 4/4] test(ui-server): type the handler-table test frames against the protocol The strict typecheck refused two fixtures in ws-handlers.test.ts: the approval double's resolve parameters were implicitly any, and the scope_decision frame used a decisionId field the protocol does not have. The frame now carries the protocol's eventId, submissionId and action, and the receipt assertion checks those fields. Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/tests/ws-handlers.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/ui-server/tests/ws-handlers.test.ts b/packages/ui-server/tests/ws-handlers.test.ts index c9f02c83c7..49dbe6db3f 100644 --- a/packages/ui-server/tests/ws-handlers.test.ts +++ b/packages/ui-server/tests/ws-handlers.test.ts @@ -120,7 +120,7 @@ function approval(t: RunningTurn, kind = "edit"): { entry: PendingApproval; deci turn: t, turnId: t.turnId, request: { toolUseId: "tu1", toolName: "Edit", kind, input: {} }, - resolve: (decision, response) => { decisions.push({ decision, response }); }, + resolve: (decision: unknown, response: unknown) => { decisions.push({ decision, response }); }, } as unknown as PendingApproval, }; } @@ -247,8 +247,8 @@ describe("local_exchange", () => { describe("scope_decision", () => { test("refuses on a host without a scope service", async () => { const h = harness(); - await handleScopeDecision(h.ctx, frame({ type: "scope_decision", sessionId: "s1", turnId: "t1", decisionId: "d1" })); - expect(h.sent).toEqual([{ type: "scope_decision_receipt", sessionId: "s1", turnId: "t1", decisionId: "d1", + await handleScopeDecision(h.ctx, frame({ type: "scope_decision", sessionId: "s1", turnId: "t1", eventId: "e1", submissionId: "sub1", action: "continue" })); + expect(h.sent).toMatchObject([{ type: "scope_decision_receipt", sessionId: "s1", turnId: "t1", eventId: "e1", submissionId: "sub1", state: "refused", reason: "This host cannot answer scope decisions." }]); }); });