refactor(chat): route browser chat through one runtime
Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESFAnh2t9HmLwng8oW95St
This commit is contained in:
@@ -10,6 +10,8 @@ import type {
|
||||
AgentTextPayload,
|
||||
AgentThinkingPayload,
|
||||
ChatMessagePayload,
|
||||
ChatSendCapabilityPayload,
|
||||
ChatSendProtocol,
|
||||
ClientToServerEvents,
|
||||
CommandDef,
|
||||
CommandManifest,
|
||||
@@ -40,6 +42,8 @@ export type {
|
||||
AgentTextPayload,
|
||||
AgentThinkingPayload,
|
||||
ChatMessagePayload,
|
||||
ChatSendCapabilityPayload,
|
||||
ChatSendProtocol,
|
||||
ClientToServerEvents,
|
||||
CommandDef,
|
||||
CommandManifest,
|
||||
|
||||
@@ -3,12 +3,7 @@ import type { HarnessSelection } from '@/lib/types';
|
||||
import type { HarnessSelectionValue } from './use-harness-selection';
|
||||
|
||||
interface ComposerProps {
|
||||
onSend: (input: {
|
||||
content: string;
|
||||
provider?: string;
|
||||
modelId?: string;
|
||||
selection: HarnessSelection;
|
||||
}) => boolean;
|
||||
onSend: (input: { content: string; selection: HarnessSelection }) => boolean;
|
||||
onStop: () => void;
|
||||
streaming: boolean;
|
||||
/** True from local send time through server turn startup/ack and
|
||||
@@ -53,17 +48,11 @@ export function Composer({
|
||||
if (!harness.canSend || harness.persistedSelection === null) return;
|
||||
const trimmed = content.trim();
|
||||
if (!trimmed) return;
|
||||
// Pass BOTH the nested selection tuple (the turn-runtime contract) and the
|
||||
// flat provider/modelId (the legacy first-send that creates the conversation)
|
||||
// — both derived from the same validated persisted tuple. The hook decides
|
||||
// which path applies from whether a conversation is already established.
|
||||
// Pass the validated, persisted selection tuple only. The hook derives the
|
||||
// wire projection (legacy `message` provider/model, or `turn:send`) from the
|
||||
// negotiated `chat:send-capability` protocol — never from flat caller input.
|
||||
const selection = harness.persistedSelection;
|
||||
const ok = onSend({
|
||||
content: trimmed,
|
||||
selection,
|
||||
provider: selection.providerId,
|
||||
modelId: selection.modelId,
|
||||
});
|
||||
const ok = onSend({ content: trimmed, selection });
|
||||
// Clear the input only when the send was accepted — a refused turn (e.g. a
|
||||
// failed idempotency mint) must retain the user's text so it is not lost.
|
||||
if (ok) setContent('');
|
||||
|
||||
@@ -14,6 +14,10 @@ export interface EmittedEvent<K extends ClientEvent = ClientEvent> {
|
||||
/** The subset of a Socket.IO `ChatSocket` that `useChatConnection` drives. */
|
||||
export interface FakeChatSocket {
|
||||
connected: boolean;
|
||||
/** Mirrors socket.io-client's `Socket.id`: the connection identity the server
|
||||
* echoes in a `chat:send-capability` payload. The generation-bound send
|
||||
* protocol accepts an advertisement only when `payload.connectionId === id`. */
|
||||
id: string;
|
||||
connect(): FakeChatSocket;
|
||||
on<K extends ServerEvent>(event: K, handler: ServerHandler<K>): FakeChatSocket;
|
||||
off<K extends ServerEvent>(event: K, handler: ServerHandler<K>): FakeChatSocket;
|
||||
@@ -51,8 +55,10 @@ export function createFakeChatSocket(): {
|
||||
/** Simulates socket.io-client's automatic reconnect of the *same*
|
||||
* instance after a transient disconnect: marks the socket connected again
|
||||
* and fires any handler(s) registered via `socket.on('connect', ...)`,
|
||||
* without clearing or replacing any listeners. */
|
||||
simulateReconnect(): void;
|
||||
* without clearing or replacing any listeners. A real reconnect is assigned
|
||||
* a fresh `Socket.id`; pass `nextId` to model that new connection identity
|
||||
* (defaults to the current id so existing callers are unaffected). */
|
||||
simulateReconnect(nextId?: string): void;
|
||||
} {
|
||||
const listeners = new Map<ServerEvent, Set<(payload: never) => void>>();
|
||||
const emitted: EmittedEvent[] = [];
|
||||
@@ -63,6 +69,7 @@ export function createFakeChatSocket(): {
|
||||
// type-checked against ServerToClientEvents/ClientToServerEvents.
|
||||
const socket = {
|
||||
connected: false,
|
||||
id: 'socket-a',
|
||||
connect: vi.fn(function connect(this: void) {
|
||||
socket.connected = true;
|
||||
return socket;
|
||||
@@ -105,8 +112,9 @@ export function createFakeChatSocket(): {
|
||||
}
|
||||
}
|
||||
|
||||
function simulateReconnect(): void {
|
||||
function simulateReconnect(nextId: string = socket.id): void {
|
||||
socket.connected = true;
|
||||
socket.id = nextId;
|
||||
const lifecycleKey = 'connect' satisfies LifecycleEvent as unknown as ServerEvent;
|
||||
for (const handler of listeners.get(lifecycleKey) ?? []) {
|
||||
(handler as () => void)();
|
||||
|
||||
@@ -21,7 +21,7 @@ vi.mock('@/lib/socket', () => ({
|
||||
destroySocket: destroySocketMock,
|
||||
}));
|
||||
|
||||
import type { HarnessSelection } from '@mosaicstack/types';
|
||||
import type { ChatSendProtocol, HarnessSelection } from '@mosaicstack/types';
|
||||
import { useChatConnection, type ChatConnectionValue } from './use-chat-connection';
|
||||
|
||||
let fake: ReturnType<typeof createFakeChatSocket>;
|
||||
@@ -52,6 +52,21 @@ function harnessSend(): HarnessSendMessage {
|
||||
return latest?.actions.sendMessage as unknown as HarnessSendMessage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Task Five MAJOR-1 (browser send-protocol negotiation) support. The Gateway
|
||||
* advertises how this connection may send via a server-to-client-only
|
||||
* `chat:send-capability` (already part of the typed `ServerToClientEvents`
|
||||
* contract, so this uses the fake's typed `serverEmit` — no cast); the hook
|
||||
* holds the advertised protocol and routes `sendMessage` through an exhaustive
|
||||
* switch on it, never inferring it from conversation/selection. When no listener
|
||||
* is registered yet (CURRENT impl), the emit is an inert no-op, so the reds
|
||||
* below fail on BEHAVIOUR — the current send path still infers a protocol and
|
||||
* emits regardless of any advertisement — not on a missing module or type.
|
||||
*/
|
||||
function advertiseCapability(protocol: ChatSendProtocol, connectionId: string): void {
|
||||
fake.serverEmit('chat:send-capability', { protocol, connectionId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Install a controllable `crypto.randomUUID` on the global crypto object and
|
||||
* return a restore fn. Uses defineProperty on the instance so it works whether
|
||||
@@ -173,6 +188,20 @@ afterEach(async () => {
|
||||
});
|
||||
|
||||
describe('useChatConnection', () => {
|
||||
// Task Five MAJOR-1: the send path is PROTOCOL-driven — `sendMessage` routes
|
||||
// only on the negotiated `chat:send-capability`, never on inferred
|
||||
// conversation/selection state. These pre-existing cases exercise the legacy
|
||||
// `message` branch, so the connection is advertised `legacy-message` once here
|
||||
// (server-to-client, for this exact socket id) after the mount registers its
|
||||
// listener. Sub-describes that need the pi turn-runtime reset the generation
|
||||
// and re-advertise `turn-send`; the capability describe resets to the
|
||||
// unadvertised `unavailable` baseline and drives the protocol itself.
|
||||
beforeEach(async () => {
|
||||
await act(async () => {
|
||||
advertiseCapability('legacy-message', fake.socket.id);
|
||||
});
|
||||
});
|
||||
|
||||
it('establishes the active conversation from the first message:ack when message omitted conversationId', async () => {
|
||||
await act(async () => {
|
||||
fake.serverEmit('message:ack', { conversationId: 'c1', messageId: 'm1' });
|
||||
@@ -450,7 +479,10 @@ describe('useChatConnection', () => {
|
||||
|
||||
it('sendMessage emits optional conversationId/provider/modelId and appends an optimistic user turn', async () => {
|
||||
await act(async () => {
|
||||
latest?.actions.sendMessage({ content: 'hello', provider: 'anthropic', modelId: 'claude' });
|
||||
latest?.actions.sendMessage({
|
||||
content: 'hello',
|
||||
selection: { harnessId: 'pi', providerId: 'anthropic', modelId: 'claude' },
|
||||
});
|
||||
});
|
||||
|
||||
expect(fake.emitted).toContainEqual({
|
||||
@@ -487,6 +519,19 @@ describe('useChatConnection', () => {
|
||||
};
|
||||
const UUID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
|
||||
|
||||
// The pi turn-runtime routes sends through `turn:send`. Reset the generation
|
||||
// (clearing the outer `legacy-message` advertisement + first-wins lock) and
|
||||
// advertise `turn-send` for this exact connection, so every send below takes
|
||||
// the turn-runtime branch.
|
||||
beforeEach(async () => {
|
||||
await act(async () => {
|
||||
fake.simulateReconnect();
|
||||
});
|
||||
await act(async () => {
|
||||
advertiseCapability('turn-send', fake.socket.id);
|
||||
});
|
||||
});
|
||||
|
||||
async function establishConversation(): Promise<void> {
|
||||
await act(async () => {
|
||||
fake.serverEmit('message:ack', { conversationId: 'c1', messageId: 'm1' });
|
||||
@@ -619,6 +664,18 @@ describe('useChatConnection', () => {
|
||||
};
|
||||
const UUID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
|
||||
|
||||
// turn:ack is the receipt for a `turn:send`, so these establish under the pi
|
||||
// turn-runtime: reset the generation (clearing the outer `legacy-message`
|
||||
// advertisement + lock) and advertise `turn-send` for this connection.
|
||||
beforeEach(async () => {
|
||||
await act(async () => {
|
||||
fake.simulateReconnect();
|
||||
});
|
||||
await act(async () => {
|
||||
advertiseCapability('turn-send', fake.socket.id);
|
||||
});
|
||||
});
|
||||
|
||||
// Establish the conversation and send one accepted turn under a controlled
|
||||
// idempotency key. Returns the crypto restore fn so callers unwind it.
|
||||
async function establishAndSend(): Promise<() => void> {
|
||||
@@ -741,6 +798,18 @@ describe('useChatConnection', () => {
|
||||
const UUID_B = '22222222-2222-4222-9222-222222222222';
|
||||
const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
// The idempotency key is minted only on the pi turn-runtime `turn:send`
|
||||
// branch: reset the generation (clearing the outer `legacy-message`
|
||||
// advertisement + lock) and advertise `turn-send` for this connection.
|
||||
beforeEach(async () => {
|
||||
await act(async () => {
|
||||
fake.simulateReconnect();
|
||||
});
|
||||
await act(async () => {
|
||||
advertiseCapability('turn-send', fake.socket.id);
|
||||
});
|
||||
});
|
||||
|
||||
async function establish(): Promise<void> {
|
||||
await act(async () => {
|
||||
fake.serverEmit('message:ack', { conversationId: 'c1', messageId: 'm1' });
|
||||
@@ -1155,7 +1224,16 @@ describe('useChatConnection', () => {
|
||||
expect(latest?.state.approvalRequestPending).toBe(false);
|
||||
|
||||
// The send lock must also be released — a subsequent sendMessage after
|
||||
// reconnect must not be permanently blocked by the interrupted turn.
|
||||
// reconnect must not be permanently blocked by the interrupted turn. The
|
||||
// disconnect also voids the negotiated send protocol (MAJOR-1), so model the
|
||||
// reconnect handshake — the socket reconnects and the server re-advertises
|
||||
// how this connection may send — before probing the released lock.
|
||||
await act(async () => {
|
||||
fake.simulateReconnect();
|
||||
});
|
||||
await act(async () => {
|
||||
advertiseCapability('legacy-message', fake.socket.id);
|
||||
});
|
||||
await act(async () => {
|
||||
latest?.actions.sendMessage({ content: 'after reconnect' });
|
||||
});
|
||||
@@ -2136,4 +2214,319 @@ describe('useChatConnection', () => {
|
||||
}
|
||||
expect(destroySocketMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
describe('chat:send-capability protocol negotiation (Task Five MAJOR-1, red-first)', () => {
|
||||
const capSelection: HarnessSelection = {
|
||||
harnessId: 'pi',
|
||||
providerId: 'anthropic',
|
||||
modelId: 'claude',
|
||||
};
|
||||
const UUID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
|
||||
// The one fixed, safe user-facing notice the hook must surface (code
|
||||
// `send_protocol_unavailable`) when a send is attempted on a connection whose
|
||||
// advertised protocol is `unavailable`/unknown/absent. Contract-frozen string.
|
||||
const UNAVAILABLE_NOTICE = 'Chat sending is unavailable on this connection.';
|
||||
|
||||
// These tests each drive the protocol negotiation themselves, so they must
|
||||
// start from a clean, unadvertised generation. Reconnect resets protocolRef
|
||||
// to `unavailable` and clears the outer `legacy-message` first-wins lock
|
||||
// WITHOUT advertising — no client emit, so `fake.emitted` stays empty and the
|
||||
// "starts unavailable" premise holds.
|
||||
beforeEach(async () => {
|
||||
await act(async () => {
|
||||
fake.simulateReconnect();
|
||||
});
|
||||
});
|
||||
|
||||
async function establishConversation(): Promise<void> {
|
||||
await act(async () => {
|
||||
fake.serverEmit('message:ack', { conversationId: 'c1', messageId: 'm1' });
|
||||
});
|
||||
}
|
||||
|
||||
function connectCalls(): number {
|
||||
return (fake.socket.connect as unknown as { mock: { calls: unknown[] } }).mock.calls.length;
|
||||
}
|
||||
|
||||
it('starts with no advertised protocol: a send is refused, emits nothing, mints no key, and surfaces the fixed unavailable notice', async () => {
|
||||
// No `chat:send-capability` has arrived, so the connection has not been told
|
||||
// it may send at all. The current impl infers "selection + no conversation +
|
||||
// no flat provider/model → return false" but SURFACES NOTHING — the red is
|
||||
// that the fixed `send_protocol_unavailable` notice is never set.
|
||||
let uuidCalls = 0;
|
||||
const restore = installRandomUUID(() => {
|
||||
uuidCalls += 1;
|
||||
return UUID;
|
||||
});
|
||||
let returned: boolean | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
returned = harnessSend()({ content: 'hi', selection: capSelection });
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
expect(returned).toBe(false);
|
||||
expect(fake.emitted).toHaveLength(0);
|
||||
expect(latest?.state.error).toBe(UNAVAILABLE_NOTICE);
|
||||
// The test's name promises "mints no key": the unavailable branch must not
|
||||
// reach the idempotency mint at all. Without this assertion a defect that
|
||||
// mints a key before refusing survives.
|
||||
expect(uuidCalls).toBe(0);
|
||||
// ...and no user content may be optimistically appended on refusal.
|
||||
expect(latest?.state.messages.some((m) => m.text === 'hi')).toBe(false);
|
||||
});
|
||||
|
||||
it('legacy-message advertised overrides conversation-inference: an established conversation still routes the legacy message event, never turn:send', async () => {
|
||||
// Same inputs the inference impl routes to `turn:send` (selection + active
|
||||
// conversation). The advertised protocol is authoritative: it must emit the
|
||||
// legacy `message` event instead. Red: current impl emits turn:send.
|
||||
const restore = installRandomUUID(() => UUID);
|
||||
try {
|
||||
await establishConversation();
|
||||
await act(async () => {
|
||||
advertiseCapability('legacy-message', fake.socket.id);
|
||||
});
|
||||
await act(async () => {
|
||||
harnessSend()({ content: 'hi', selection: capSelection });
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
expect(fake.emitted.filter((e) => e.event === 'turn:send')).toHaveLength(0);
|
||||
expect(fake.emitted).toContainEqual({
|
||||
event: 'message',
|
||||
payload: { conversationId: 'c1', content: 'hi', provider: 'anthropic', modelId: 'claude' },
|
||||
});
|
||||
});
|
||||
|
||||
it('legacy-message advertised with no conversation: derives provider/model from the selection tuple and emits one message', async () => {
|
||||
// The flat provider/modelId caller inputs are gone; the legacy branch must
|
||||
// source them from the confirmed persisted selection. Red: current impl
|
||||
// refuses a bare harness send (selection + no flat fields → return false).
|
||||
let returned: boolean | undefined;
|
||||
const restore = installRandomUUID(() => UUID);
|
||||
try {
|
||||
await act(async () => {
|
||||
advertiseCapability('legacy-message', fake.socket.id);
|
||||
});
|
||||
await act(async () => {
|
||||
returned = harnessSend()({ content: 'first', selection: capSelection });
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
expect(returned).toBe(true);
|
||||
expect(fake.emitted).toContainEqual({
|
||||
event: 'message',
|
||||
payload: {
|
||||
conversationId: undefined,
|
||||
content: 'first',
|
||||
provider: 'anthropic',
|
||||
modelId: 'claude',
|
||||
},
|
||||
});
|
||||
expect(fake.emitted.some((e) => e.event === 'turn:send')).toBe(false);
|
||||
});
|
||||
|
||||
it('unavailable advertised: refuses even with an active conversation and selection, emits nothing, surfaces the fixed notice', async () => {
|
||||
// Red: current impl ignores the advertisement and emits turn:send.
|
||||
let uuidCalls = 0;
|
||||
const restore = installRandomUUID(() => {
|
||||
uuidCalls += 1;
|
||||
return UUID;
|
||||
});
|
||||
let returned: boolean | undefined;
|
||||
try {
|
||||
await establishConversation();
|
||||
await act(async () => {
|
||||
advertiseCapability('unavailable', fake.socket.id);
|
||||
});
|
||||
await act(async () => {
|
||||
returned = harnessSend()({ content: 'nope', selection: capSelection });
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
expect(returned).toBe(false);
|
||||
expect(fake.emitted).toHaveLength(0);
|
||||
expect(latest?.state.error).toBe(UNAVAILABLE_NOTICE);
|
||||
// Refusal must not optimistically append the user's turn to the transcript
|
||||
// (a distinct leak from the emit): the unavailable branch appends nothing.
|
||||
expect(latest?.state.messages.some((m) => m.text === 'nope')).toBe(false);
|
||||
// ...and must not mint an idempotency key on the refused path.
|
||||
expect(uuidCalls).toBe(0);
|
||||
});
|
||||
|
||||
it('ignores an advertisement whose connectionId does not match the socket id: protocol stays unavailable and the send is refused', async () => {
|
||||
// A capability minted for a different (stale/foreign) connection must never
|
||||
// arm this one. Red: current impl has no connection-id gate and emits
|
||||
// turn:send off the inferred path.
|
||||
const restore = installRandomUUID(() => UUID);
|
||||
let returned: boolean | undefined;
|
||||
try {
|
||||
await establishConversation();
|
||||
await act(async () => {
|
||||
advertiseCapability('legacy-message', 'a-different-connection');
|
||||
});
|
||||
await act(async () => {
|
||||
returned = harnessSend()({ content: 'spoof', selection: capSelection });
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
expect(returned).toBe(false);
|
||||
expect(fake.emitted).toHaveLength(0);
|
||||
expect(latest?.state.error).toBe(UNAVAILABLE_NOTICE);
|
||||
});
|
||||
|
||||
it('accepts only the first advertisement for the generation: a later conflicting protocol is ignored', async () => {
|
||||
// legacy-message wins; the subsequent turn-send is a replay/conflict and is
|
||||
// dropped. Red: current impl ignores both and infers turn:send.
|
||||
const restore = installRandomUUID(() => UUID);
|
||||
try {
|
||||
await establishConversation();
|
||||
await act(async () => {
|
||||
advertiseCapability('legacy-message', fake.socket.id);
|
||||
});
|
||||
await act(async () => {
|
||||
advertiseCapability('turn-send', fake.socket.id);
|
||||
});
|
||||
await act(async () => {
|
||||
harnessSend()({ content: 'hi', selection: capSelection });
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
expect(fake.emitted.filter((e) => e.event === 'turn:send')).toHaveLength(0);
|
||||
expect(fake.emitted).toContainEqual({
|
||||
event: 'message',
|
||||
payload: { conversationId: 'c1', content: 'hi', provider: 'anthropic', modelId: 'claude' },
|
||||
});
|
||||
});
|
||||
|
||||
it('resets to unavailable on disconnect: a later send is refused and never reconnects the socket', async () => {
|
||||
// Disconnect voids the advertised protocol for the generation. The send must
|
||||
// refuse and MUST NOT call socket.connect() to force a reconnection. Red:
|
||||
// current impl keeps the conversation, infers turn:send, and its turn:send
|
||||
// branch calls socket.connect() when the socket is disconnected.
|
||||
const restore = installRandomUUID(() => UUID);
|
||||
let returned: boolean | undefined;
|
||||
let connectsDuringSend = 0;
|
||||
try {
|
||||
await establishConversation();
|
||||
await act(async () => {
|
||||
advertiseCapability('legacy-message', fake.socket.id);
|
||||
});
|
||||
await act(async () => {
|
||||
fake.simulateDisconnect();
|
||||
});
|
||||
const before = connectCalls();
|
||||
await act(async () => {
|
||||
returned = harnessSend()({ content: 'after-drop', selection: capSelection });
|
||||
});
|
||||
connectsDuringSend = connectCalls() - before;
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
expect(returned).toBe(false);
|
||||
expect(fake.emitted).toHaveLength(0);
|
||||
expect(latest?.state.error).toBe(UNAVAILABLE_NOTICE);
|
||||
expect(connectsDuringSend).toBe(0);
|
||||
});
|
||||
|
||||
it('resets on reconnect to a fresh generation: refuses until re-advertised, then honors the new advertisement', async () => {
|
||||
// A reconnect mints a new Socket.id and a new generation; the prior
|
||||
// advertisement (bound to the old id) is stale and must not carry over. The
|
||||
// hook only trusts a fresh advertisement for the new connection. Red:
|
||||
// current impl has no connect listener and keeps inferring turn:send.
|
||||
const restore = installRandomUUID(() => UUID);
|
||||
let refusedAfterReconnect: boolean | undefined;
|
||||
try {
|
||||
await establishConversation();
|
||||
await act(async () => {
|
||||
advertiseCapability('legacy-message', fake.socket.id);
|
||||
});
|
||||
await act(async () => {
|
||||
fake.simulateReconnect('socket-b');
|
||||
});
|
||||
await act(async () => {
|
||||
refusedAfterReconnect = harnessSend()({ content: 'stale', selection: capSelection });
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
expect(refusedAfterReconnect).toBe(false);
|
||||
expect(fake.emitted).toHaveLength(0);
|
||||
expect(latest?.state.error).toBe(UNAVAILABLE_NOTICE);
|
||||
|
||||
// A fresh advertisement for the reconnected id (socket-b) re-arms sending.
|
||||
const restore2 = installRandomUUID(() => UUID);
|
||||
try {
|
||||
await act(async () => {
|
||||
advertiseCapability('legacy-message', 'socket-b');
|
||||
});
|
||||
await act(async () => {
|
||||
harnessSend()({ content: 'welcome-back', selection: capSelection });
|
||||
});
|
||||
} finally {
|
||||
restore2();
|
||||
}
|
||||
|
||||
expect(fake.emitted).toContainEqual({
|
||||
event: 'message',
|
||||
payload: {
|
||||
conversationId: 'c1',
|
||||
content: 'welcome-back',
|
||||
provider: 'anthropic',
|
||||
modelId: 'claude',
|
||||
},
|
||||
});
|
||||
expect(fake.emitted.some((e) => e.event === 'turn:send')).toBe(false);
|
||||
});
|
||||
|
||||
it('routes on the synchronous protocol ref, not the batched reducer mirror: an advertisement and a send in the SAME tick still route by the just-advertised protocol', async () => {
|
||||
// An advertisement lands and a send is issued within one synchronous tick,
|
||||
// before React commits the reducer's `sendProtocol` mirror. The send is
|
||||
// captured from the pre-advertisement render, so its closed-over reducer
|
||||
// state still reads `sendProtocol === 'unavailable'`; the capability
|
||||
// handler, however, has already set the synchronous `protocolRef` to
|
||||
// `legacy-message`. The hook must route on that ref. Red (against a
|
||||
// stale-mirror routing that reads `state.sendProtocol`): the send reads the
|
||||
// pre-advertisement `unavailable` and refuses instead of emitting `message`.
|
||||
const restore = installRandomUUID(() => UUID);
|
||||
try {
|
||||
await act(async () => {
|
||||
// Bound to the CURRENT (pre-advertisement) render — its closure still
|
||||
// sees the reset `unavailable` mirror even after the advert dispatches.
|
||||
const sendBeforeCommit = harnessSend();
|
||||
advertiseCapability('legacy-message', fake.socket.id);
|
||||
// Same tick, no await: React has not committed the new mirror yet, so
|
||||
// only `protocolRef` reflects `legacy-message`.
|
||||
sendBeforeCommit({ content: 'same-tick', selection: capSelection });
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
expect(fake.emitted).toContainEqual({
|
||||
event: 'message',
|
||||
payload: {
|
||||
conversationId: undefined,
|
||||
content: 'same-tick',
|
||||
provider: 'anthropic',
|
||||
modelId: 'claude',
|
||||
},
|
||||
});
|
||||
expect(fake.emitted.some((e) => e.event === 'turn:send')).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -22,6 +22,8 @@ import type {
|
||||
AgentStartPayload,
|
||||
AgentTextPayload,
|
||||
AgentThinkingPayload,
|
||||
ChatSendCapabilityPayload,
|
||||
ChatSendProtocol,
|
||||
CommandDef,
|
||||
CommandManifest,
|
||||
CommandManifestPayload,
|
||||
@@ -145,6 +147,14 @@ const TURN_REJECTED_NOTICE = 'This turn could not be sent. Please try again.';
|
||||
* 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
|
||||
@@ -307,6 +317,14 @@ 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). */
|
||||
@@ -351,12 +369,7 @@ export interface ChatConnectionState {
|
||||
}
|
||||
|
||||
export interface ChatConnectionActions {
|
||||
sendMessage: (input: {
|
||||
content: string;
|
||||
provider?: string;
|
||||
modelId?: string;
|
||||
selection?: HarnessSelection;
|
||||
}) => boolean;
|
||||
sendMessage: (input: { content: string; selection?: HarnessSelection }) => boolean;
|
||||
abort: () => void;
|
||||
setThinking: (level: string) => void;
|
||||
executeCommand: (input: { command: string; args?: string }) => void;
|
||||
@@ -389,6 +402,7 @@ const initialState: ChatConnectionState = {
|
||||
approvalRequestPending: false,
|
||||
systemReload: null,
|
||||
error: null,
|
||||
sendProtocol: 'unavailable',
|
||||
turnReceipt: null,
|
||||
messages: [],
|
||||
messageSeq: 0,
|
||||
@@ -412,6 +426,9 @@ type Action =
|
||||
| { 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' }
|
||||
@@ -877,6 +894,31 @@ 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 —
|
||||
@@ -965,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();
|
||||
|
||||
@@ -998,7 +1054,43 @@ export function useChatConnection(): ChatConnectionValue {
|
||||
};
|
||||
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' });
|
||||
};
|
||||
|
||||
@@ -1016,6 +1108,10 @@ export function useChatConnection(): ChatConnectionValue {
|
||||
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) {
|
||||
@@ -1037,54 +1133,78 @@ export function useChatConnection(): ChatConnectionValue {
|
||||
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, selection }) => {
|
||||
// Turn-runtime path: a selection tuple against an already-established
|
||||
// conversation routes through the exclusive `turn:send` contract. It is
|
||||
// lock-independent by design — it does not engage the send lock, does not
|
||||
// dispatch `local/send` (no optimistic append), and mints exactly one
|
||||
// idempotency key per accepted turn. A failed mint fails the turn closed.
|
||||
if (selection != null && state.conversationId !== null) {
|
||||
const idempotencyKey = mintIdempotencyKey();
|
||||
if (idempotencyKey === null) {
|
||||
dispatch({ type: 'local/turn-idempotency-unavailable' });
|
||||
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;
|
||||
}
|
||||
const socket = getSocket();
|
||||
if (!socket.connected) socket.connect();
|
||||
socket.emit('turn:send', {
|
||||
conversationId: state.conversationId,
|
||||
content,
|
||||
selection,
|
||||
idempotencyKey,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
// A selection tuple with no active conversation and no flat provider/model
|
||||
// is a bare harness call that cannot create a conversation — refuse it,
|
||||
// emitting nothing and appending nothing.
|
||||
if (selection != null && provider === undefined && modelId === undefined) {
|
||||
return false;
|
||||
}
|
||||
// Legacy `message` path (first send that creates the conversation, and every
|
||||
// pre-turn-runtime send) — unchanged behavior, now reporting acceptance.
|
||||
if (sendLockRef.current || state.streaming || state.sending) return false;
|
||||
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,
|
||||
});
|
||||
return true;
|
||||
},
|
||||
|
||||
abort: () => {
|
||||
|
||||
@@ -135,6 +135,31 @@ function installRandomUUID(fn: () => string): () => void {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Task Five MAJOR-1: the send path is PROTOCOL-driven — the browser may send only
|
||||
* as the server advertised, once per connection, over the server-to-client-only
|
||||
* `chat:send-capability`. Model that advertisement for THIS connection id so the
|
||||
* page send tests take the intended branch. `legacy-message` is the default
|
||||
* (advertised in `beforeEach`/`remountWithFetch`); the pi turn-runtime tests
|
||||
* reset the generation and re-advertise `turn-send` via the helper below.
|
||||
*/
|
||||
function advertiseSendCapability(protocol: 'legacy-message' | 'turn-send' | 'unavailable'): void {
|
||||
fake.serverEmit('chat:send-capability', { protocol, connectionId: fake.socket.id });
|
||||
}
|
||||
|
||||
/** Reset the negotiated protocol to a fresh, unlocked generation (clearing the
|
||||
* default `legacy-message` advertisement + first-wins lock), then advertise the
|
||||
* pi turn-runtime `turn:send` protocol for this connection. The per-test override
|
||||
* for the page send tests that route through `turn:send`. */
|
||||
async function advertiseTurnSendGeneration(): Promise<void> {
|
||||
await act(async () => {
|
||||
fake.simulateReconnect();
|
||||
});
|
||||
await act(async () => {
|
||||
advertiseSendCapability('turn-send');
|
||||
});
|
||||
}
|
||||
|
||||
let fake: ReturnType<typeof createFakeChatSocket>;
|
||||
let root: Root | null;
|
||||
let container: HTMLElement;
|
||||
@@ -164,6 +189,12 @@ beforeEach(async () => {
|
||||
// Settle the selection hook's mount fetches so the default in-catalog tuple
|
||||
// persists and `canSend` is true for the existing send-path tests.
|
||||
await flushAsync();
|
||||
// Model the server's post-auth send-capability advertisement (MAJOR-1). Most
|
||||
// page send tests exercise the legacy `message` branch; the pi turn-runtime
|
||||
// tests override to `turn-send` via advertiseTurnSendGeneration().
|
||||
await act(async () => {
|
||||
advertiseSendCapability('legacy-message');
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -186,6 +217,11 @@ async function remountWithFetch(fetchImpl: typeof fetch): Promise<void> {
|
||||
root?.render(<ChatPage />);
|
||||
});
|
||||
await flushAsync();
|
||||
// Re-advertise on the remounted connection — the prior generation's capability
|
||||
// does not carry across a remount (fresh hook instance, unadvertised protocol).
|
||||
await act(async () => {
|
||||
advertiseSendCapability('legacy-message');
|
||||
});
|
||||
}
|
||||
|
||||
describe('ChatPage', () => {
|
||||
@@ -599,6 +635,7 @@ describe('ChatPage', () => {
|
||||
});
|
||||
|
||||
it('emits turn:send with the nested persisted selection tuple and a UUID idempotency key (never the legacy message event)', async () => {
|
||||
await advertiseTurnSendGeneration();
|
||||
const restore = installRandomUUID(() => PAGE_UUID);
|
||||
try {
|
||||
// Send is disabled without an active conversation — establish one first.
|
||||
@@ -635,6 +672,7 @@ describe('ChatPage', () => {
|
||||
});
|
||||
|
||||
it('keeps the composer content and emits nothing when the send cannot mint an idempotency key, so the user can retry (composer clears only on success) — Task Five group 5', async () => {
|
||||
await advertiseTurnSendGeneration();
|
||||
const failing = installRandomUUID(() => {
|
||||
throw new Error('secure random unavailable');
|
||||
});
|
||||
@@ -668,6 +706,7 @@ describe('ChatPage', () => {
|
||||
});
|
||||
|
||||
it('clears the composer after a successful turn:send and never falls back to the legacy message event — Task Five group 5', async () => {
|
||||
await advertiseTurnSendGeneration();
|
||||
const restore = installRandomUUID(() => PAGE_UUID);
|
||||
try {
|
||||
await act(async () => {
|
||||
@@ -696,6 +735,7 @@ describe('ChatPage', () => {
|
||||
});
|
||||
|
||||
it('sends the freshly persisted selection as a nested turn:send tuple after the user changes provider/model — never a stale default or flat fields — Task Five group 5', async () => {
|
||||
await advertiseTurnSendGeneration();
|
||||
const restore = installRandomUUID(() => PAGE_UUID);
|
||||
try {
|
||||
// Change the selection away from the mount default and let it persist.
|
||||
|
||||
Reference in New Issue
Block a user