refactor(chat): route browser chat through one runtime (P3 Slice-Zero Task 5) (#1172)
ci/woodpecker/push/publish Pipeline failed

Co-authored-by: shaggy <[email protected]>
This commit was merged in pull request #1172.
This commit is contained in:
2026-08-12 20:11:12 +00:00
committed by mos-dt-0
parent 6a8ce66702
commit 216cd72226
33 changed files with 7209 additions and 672 deletions
+250 -13
View File
@@ -12,6 +12,7 @@ import {
import {
asConversationId,
asFiniteNumber,
asHarnessSelection,
asString,
asStringArray,
isRecord,
@@ -21,10 +22,14 @@ import type {
AgentStartPayload,
AgentTextPayload,
AgentThinkingPayload,
ChatSendCapabilityPayload,
ChatSendProtocol,
CommandDef,
CommandManifest,
CommandManifestPayload,
ErrorPayload,
HarnessSelection,
HarnessTurnAckPayload,
MessageAckPayload,
SessionInfoPayload,
SessionUsagePayload,
@@ -130,6 +135,42 @@ const CONVERSATION_START_FAILURE = 'Unable to start this conversation. Please tr
* dropped. */
const APPROVAL_LIMIT_MESSAGE = 'Approval limit reached for this session. This command was not run.';
/** Fixed, browser-safe notice surfaced when the harness runtime rejects a turn
* (`turn:ack` with `ok:false`). It is deliberately generic: the raw server
* `code`/`message`/`error` can carry adapter internals or entropy-source detail,
* so no rejection ever leaks its cause into the UI — every distinct rejection
* shows this same string. */
const TURN_REJECTED_NOTICE = 'This turn could not be sent. Please try again.';
/** Fixed, browser-safe notice surfaced when a turn is refused because the
* idempotency-key mint failed closed (`crypto.randomUUID` absent or throwing).
* Like {@link TURN_REJECTED_NOTICE}, it never carries the thrown message. */
const IDEMPOTENCY_UNAVAILABLE_NOTICE = 'This turn could not be sent. Please try again.';
/** The single fixed, browser-safe notice surfaced (with safe code
* `send_protocol_unavailable`) when a send is attempted on a connection whose
* negotiated send protocol is `unavailable` — the server never advertised a
* usable `chat:send-capability`, advertised `unavailable` (e.g. a pi-rpc runtime
* in this slice), or the advertisement was rejected (wrong connection id, replay,
* or an unknown protocol). It carries no dynamic detail. */
const SEND_PROTOCOL_UNAVAILABLE_NOTICE = 'Chat sending is unavailable on this connection.';
/** Mints a single idempotency key for one accepted `turn:send`, fail-closed.
* Returns a fresh RFC-4122 UUID from `crypto.randomUUID`, or `null` when that
* source is absent (not a function) or throws — the caller then refuses the turn
* rather than falling back to any non-cryptographic source (Math.random, a
* clock, or a counter would all be forgeable/collision-prone). Never throws. */
function mintIdempotencyKey(): string | null {
try {
const c: unknown = globalThis.crypto;
if (!isRecord(c) || typeof c.randomUUID !== 'function') return null;
const key = (c.randomUUID as () => unknown)();
return typeof key === 'string' && key.length > 0 ? key : null;
} catch {
return null;
}
}
/** True only for the narrow case a malformed-conversationId `error`/`agent:end`
* must be treated as a terminal startup failure: no conversation has ever been
* established yet, and a send is still pending one. Once a conversation is
@@ -236,6 +277,14 @@ export interface PendingApproval {
args?: string;
}
/** Receipt captured from an accepted harness `turn:ack` — the minimal record proving the
* server accepted this exact turn under its minted idempotency key and selection tuple. */
export interface HarnessTurnReceipt {
idempotencyKey: string;
receiptId: string;
selection: HarnessSelection;
}
export interface ChatConnectionState {
conversationId: string | null;
/** True once a message has been sent while no conversation is active yet, so the
@@ -268,6 +317,18 @@ export interface ChatConnectionState {
approvalRequestPending: boolean;
systemReload: SystemReloadPayload | null;
error: string | null;
/** How this connection is currently permitted to send, negotiated via the
* server-to-client-only `chat:send-capability` advertisement. Starts and resets
* to `'unavailable'` on every (re)connect and disconnect — a fresh or dropped
* connection has no usable protocol until the server (re-)advertises. This is
* the reactive/UI mirror of the synchronous `protocolRef` that `sendMessage`
* actually reads; the ref is authoritative because an advertisement and a send
* can occur in the same tick before React re-renders. */
sendProtocol: ChatSendProtocol;
/** Receipt from the most recently accepted harness `turn:ack`, or null before any
* turn has been accepted. A rejected turn:ack surfaces via `error` and leaves this
* untouched (a prior accepted receipt is not erased by a later rejection). */
turnReceipt: HarnessTurnReceipt | null;
messages: ChatTranscriptMessage[];
/** Monotonically increasing counter used to mint transcript message ids —
* never reset while retained messages remain, so ids stay unique across the
@@ -308,7 +369,7 @@ export interface ChatConnectionState {
}
export interface ChatConnectionActions {
sendMessage: (input: { content: string; provider?: string; modelId?: string }) => void;
sendMessage: (input: { content: string; selection?: HarnessSelection }) => boolean;
abort: () => void;
setThinking: (level: string) => void;
executeCommand: (input: { command: string; args?: string }) => void;
@@ -341,6 +402,8 @@ const initialState: ChatConnectionState = {
approvalRequestPending: false,
systemReload: null,
error: null,
sendProtocol: 'unavailable',
turnReceipt: null,
messages: [],
messageSeq: 0,
toolSeq: 0,
@@ -361,7 +424,12 @@ type Action =
| { type: 'server/command:approval'; payload: SlashCommandApprovalResultPayload }
| { type: 'server/system:reload'; payload: SystemReloadPayload }
| { type: 'server/error'; payload: ErrorPayload }
| { type: 'server/turn:ack'; payload: HarnessTurnAckPayload }
| { type: 'local/send'; content: string }
| { type: 'local/capability'; protocol: ChatSendProtocol }
| { type: 'local/reset-protocol' }
| { type: 'local/send-unavailable' }
| { type: 'local/turn-idempotency-unavailable' }
| { type: 'local/approve-request'; command: string; args?: string }
| { type: 'local/consume-approval' }
| { type: 'local/approval-saturated' }
@@ -778,6 +846,30 @@ function reduce(state: ChatConnectionState, action: Action): ChatConnectionState
};
}
case 'server/turn:ack': {
// The harness runtime's turn acknowledgement. The success shape carries a
// receipt id + minted idempotencyKey + echoed selection; the failure shape
// is discriminated on `ok === false`. Every field is runtime-untrusted (the
// top-of-reducer guard already rejected a non-object payload).
const record = action.payload as Record<string, unknown>;
if (record.ok === false) {
// A rejected turn surfaces a FIXED browser-safe notice — never the raw
// server `message`/`error`/`code`, which can carry adapter internals — and
// does not disturb any previously accepted receipt.
return { ...state, error: TURN_REJECTED_NOTICE };
}
const idempotencyKey = asString(record.idempotencyKey);
// The web ack uses `receiptId`; fall back to the frozen contract's `turnId`.
const receiptId = asString(record.receiptId) || asString(record.turnId);
const selection = asHarnessSelection(record.selection);
if (idempotencyKey.length === 0 || receiptId.length === 0 || selection === null) {
// A malformed success frame is ignored outright rather than recorded as a
// half-populated receipt.
return state;
}
return { ...state, turnReceipt: { idempotencyKey, receiptId, selection } };
}
case 'local/send': {
const message: ChatTranscriptMessage = {
// Sourced from the reducer-owned `messageSeq` counter — see the
@@ -802,6 +894,39 @@ function reduce(state: ChatConnectionState, action: Action): ChatConnectionState
};
}
case 'local/capability': {
// The FIRST valid `chat:send-capability` for this connection generation has
// been accepted (connection-id gating + first-wins enforced in the handler);
// record how this connection may now send. This is the reactive mirror of
// the synchronous `protocolRef` the send path reads.
return { ...state, sendProtocol: action.protocol };
}
case 'local/reset-protocol': {
// A (re)connect or disconnect voids any negotiated protocol: a fresh or
// dropped connection has no usable send capability until the server
// (re-)advertises. Reset to `unavailable` so no stale advertisement can
// authorize a send across a connection boundary.
if (state.sendProtocol === 'unavailable') return state;
return { ...state, sendProtocol: 'unavailable' };
}
case 'local/send-unavailable': {
// A send was attempted while the negotiated protocol is `unavailable`
// (never advertised / advertised unavailable / rejected advertisement).
// Surface the single FIXED safe notice — nothing was emitted, minted,
// appended, or locked.
return { ...state, error: SEND_PROTOCOL_UNAVAILABLE_NOTICE };
}
case 'local/turn-idempotency-unavailable': {
// The idempotency-key mint failed closed (crypto.randomUUID absent or
// throwing), so the turn was refused before emit. Surface a FIXED notice —
// never the underlying thrown message, which can leak entropy-source
// internals.
return { ...state, error: IDEMPOTENCY_UNAVAILABLE_NOTICE };
}
case 'local/disconnect': {
// A transient socket disconnect must not leave the UI stuck waiting on
// a turn/approval/send that will never resolve on this connection.
@@ -882,6 +1007,20 @@ export function useChatConnection(): ChatConnectionValue {
approveLockRef.current = state.approvalRequestPending;
}, [state.approvalRequestPending]);
// Synchronous, generation-bound send protocol. `state.sendProtocol` drives the
// reactive UI, but reducer updates are batched/async — a `chat:send-capability`
// advertisement and a `sendMessage` can land in the same tick before React
// re-renders — so this ref is the source of truth the send path reads. Unlike
// sendLockRef/approveLockRef (synchronized FROM the reducer), this ref is
// written directly by the socket lifecycle/capability handlers below, which
// also dispatch the reducer mirror. It is NOT synchronized from state, because
// its whole purpose is to be correct BEFORE the reducer has re-rendered.
const protocolRef = useRef<ChatSendProtocol>('unavailable');
// True once the first valid advertisement for the CURRENT connection generation
// has been accepted; every later advertisement (a conflicting or replayed one)
// is ignored until the next (re)connect/disconnect resets the generation.
const protocolLockedRef = useRef(false);
useEffect(() => {
const socket = getSocket();
@@ -913,7 +1052,45 @@ export function useChatConnection(): ChatConnectionValue {
const onError = (payload: ErrorPayload): void => {
dispatch({ type: 'server/error', payload });
};
const onTurnAck = (payload: HarnessTurnAckPayload): void =>
dispatch({ type: 'server/turn:ack', payload });
// Void the negotiated send protocol at every connection-lifecycle boundary.
// A fresh or dropped connection has no usable capability until the server
// (re-)advertises, so no advertisement bound to a prior connection may carry
// across the boundary and authorize a send. Both write the synchronous ref
// AND unlock first-wins, then dispatch the reducer mirror.
const resetSendProtocol = (): void => {
protocolRef.current = 'unavailable';
protocolLockedRef.current = false;
dispatch({ type: 'local/reset-protocol' });
};
const onConnect = (): void => {
resetSendProtocol();
};
const onCapability = (payload: ChatSendCapabilityPayload): void => {
// Server-to-client-only advertisement of how THIS connection may send.
// Accept only the FIRST valid one per generation, and only when it names
// this exact connection (`connectionId === socket.id`): a capability minted
// for another or stale connection must never arm this one. The payload is
// runtime-untrusted despite its compile-time type, so every field is
// guard-checked and an unknown protocol is dropped (leaving `unavailable`).
if (protocolLockedRef.current) return;
if (!isRecord(payload)) return;
const { protocol, connectionId } = payload as {
protocol?: unknown;
connectionId?: unknown;
};
if (typeof connectionId !== 'string' || connectionId !== socket.id) return;
if (protocol !== 'legacy-message' && protocol !== 'turn-send' && protocol !== 'unavailable') {
return;
}
protocolLockedRef.current = true;
protocolRef.current = protocol;
dispatch({ type: 'local/capability', protocol });
};
const onDisconnect = (): void => {
resetSendProtocol();
dispatch({ type: 'local/disconnect' });
};
@@ -930,6 +1107,11 @@ export function useChatConnection(): ChatConnectionValue {
socket.on('command:approval', onCommandApproval);
socket.on('system:reload', onSystemReload);
socket.on('error', onError);
socket.on('turn:ack', onTurnAck);
// Registered BEFORE connect so the initial post-auth advertisement (and any
// reconnect) can never race ahead of its listener.
socket.on('connect', onConnect);
socket.on('chat:send-capability', onCapability);
socket.on('disconnect', onDisconnect);
if (!socket.connected) {
@@ -950,24 +1132,79 @@ export function useChatConnection(): ChatConnectionValue {
socket.off('command:approval', onCommandApproval);
socket.off('system:reload', onSystemReload);
socket.off('error', onError);
socket.off('turn:ack', onTurnAck);
socket.off('connect', onConnect);
socket.off('chat:send-capability', onCapability);
socket.off('disconnect', onDisconnect);
destroySocket();
};
}, []);
const actions: ChatConnectionActions = {
sendMessage: ({ content, provider, modelId }) => {
if (sendLockRef.current || state.streaming || state.sending) return;
sendLockRef.current = true;
const socket = getSocket();
if (!socket.connected) socket.connect();
dispatch({ type: 'local/send', content });
socket.emit('message', {
conversationId: state.conversationId ?? undefined,
content,
provider,
modelId,
});
sendMessage: ({ content, selection }) => {
// Routing is PROTOCOL-driven, never inferred from conversation/selection/
// provider/local mode: the server advertised, once per connection, exactly
// how this connection may send, and that advertisement is authoritative.
// The exhaustive switch maps each protocol to its ONE event; the send path
// never reconnects the socket (a dropped connection has already reset the
// protocol to `unavailable`, so no emit branch is reachable while offline).
switch (protocolRef.current) {
case 'legacy-message': {
// Embedded/legacy runtime: EVERY browser turn — the first (which
// creates the conversation) and every later one — is the `message`
// event. provider/model are sourced ONLY from the confirmed persisted
// selection tuple, never from separate flat caller inputs.
if (sendLockRef.current || state.streaming || state.sending) return false;
sendLockRef.current = true;
const socket = getSocket();
dispatch({ type: 'local/send', content });
socket.emit('message', {
conversationId: state.conversationId ?? undefined,
content,
provider: selection?.providerId,
modelId: selection?.modelId,
});
return true;
}
case 'turn-send': {
// Pi turn-runtime: the exclusive `turn:send` contract. Requires an
// already-established conversation AND a confirmed persisted selection
// tuple; it is lock-independent (no send lock, no optimistic append),
// and mints exactly one idempotency key per accepted turn, failing the
// turn closed if the mint fails. A premature send (no conversation yet,
// or no selection) is refused with no emit and no notice.
if (selection == null || state.conversationId === null) return false;
const idempotencyKey = mintIdempotencyKey();
if (idempotencyKey === null) {
dispatch({ type: 'local/turn-idempotency-unavailable' });
return false;
}
const socket = getSocket();
socket.emit('turn:send', {
conversationId: state.conversationId,
content,
selection,
idempotencyKey,
});
return true;
}
case 'unavailable': {
// No usable protocol negotiated for this connection: refuse without
// emitting, minting, appending, or acquiring the lock, and surface the
// one fixed safe notice (code `send_protocol_unavailable`).
dispatch({ type: 'local/send-unavailable' });
return false;
}
default: {
// Exhaustiveness guard: every ChatSendProtocol member is handled above.
// An unknown value can never arm a send — refuse exactly as
// `unavailable` rather than falling through to any emit.
const _exhaustive: never = protocolRef.current;
void _exhaustive;
dispatch({ type: 'local/send-unavailable' });
return false;
}
}
},
abort: () => {