refactor(chat): route browser chat through one runtime (P3 Slice-Zero Task 5) (#1172)
ci/woodpecker/push/publish Pipeline failed
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:
@@ -21,6 +21,7 @@ vi.mock('@/lib/socket', () => ({
|
||||
destroySocket: destroySocketMock,
|
||||
}));
|
||||
|
||||
import type { ChatSendProtocol, HarnessSelection } from '@mosaicstack/types';
|
||||
import { useChatConnection, type ChatConnectionValue } from './use-chat-connection';
|
||||
|
||||
let fake: ReturnType<typeof createFakeChatSocket>;
|
||||
@@ -33,6 +34,126 @@ function Harness(): null {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Task Five, Step Two (web send path) red-first support. These probe the FUTURE
|
||||
* pi-rpc send contract against the CURRENT implementation, so the desired API is
|
||||
* expressed here as a localized cast — production types stay untouched until Step
|
||||
* Three. The reds fail on behaviour (legacy `message` emitted instead of
|
||||
* `turn:send`; no nested selection; no idempotency key; void return; no
|
||||
* conversation-id gating), never on a missing module or type.
|
||||
*/
|
||||
interface HarnessTurnSendInput {
|
||||
readonly content: string;
|
||||
readonly selection: HarnessSelection;
|
||||
}
|
||||
type HarnessSendMessage = (input: HarnessTurnSendInput) => boolean;
|
||||
|
||||
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
|
||||
* or not the native method is configurable (it lives on the prototype, so an own
|
||||
* property simply shadows it).
|
||||
*/
|
||||
function installRandomUUID(fn: () => string): () => void {
|
||||
const g = globalThis as { crypto?: { randomUUID?: () => string } };
|
||||
if (!g.crypto) {
|
||||
Object.defineProperty(g, 'crypto', { configurable: true, writable: true, value: {} });
|
||||
}
|
||||
const cryptoObj = g.crypto as { randomUUID?: () => string };
|
||||
const original = Object.getOwnPropertyDescriptor(cryptoObj, 'randomUUID');
|
||||
Object.defineProperty(cryptoObj, 'randomUUID', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: fn,
|
||||
});
|
||||
return () => {
|
||||
if (original) {
|
||||
Object.defineProperty(cryptoObj, 'randomUUID', original);
|
||||
} else {
|
||||
Reflect.deleteProperty(cryptoObj, 'randomUUID');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Force `crypto.randomUUID` to read as ABSENT by shadowing it with an own
|
||||
* `undefined` property. The native method lives on `Crypto.prototype`, so a
|
||||
* bare delete of the (non-existent) own property would leave the inherited
|
||||
* method visible — the shadow is what actually makes the call site see no
|
||||
* secure generator. Returns a restore fn.
|
||||
*/
|
||||
function removeRandomUUID(): () => void {
|
||||
const g = globalThis as { crypto?: { randomUUID?: () => string } };
|
||||
if (!g.crypto) {
|
||||
Object.defineProperty(g, 'crypto', { configurable: true, writable: true, value: {} });
|
||||
}
|
||||
const cryptoObj = g.crypto as { randomUUID?: () => string };
|
||||
const original = Object.getOwnPropertyDescriptor(cryptoObj, 'randomUUID');
|
||||
Object.defineProperty(cryptoObj, 'randomUUID', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: undefined,
|
||||
});
|
||||
return () => {
|
||||
if (original) {
|
||||
Object.defineProperty(cryptoObj, 'randomUUID', original);
|
||||
} else {
|
||||
Reflect.deleteProperty(cryptoObj, 'randomUUID');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Task Five, Step Two group 4/5 support — the FUTURE `turn:ack` receipt surface
|
||||
* and the FUTURE fixed idempotency/rejection notice, expressed as a localized
|
||||
* read-only view over `state`. Production `ChatConnectionState` gains
|
||||
* `turnReceipt` at Step Three; the cast keeps production types untouched until
|
||||
* then, so a success assertion against it fails on BEHAVIOUR (no turn:ack
|
||||
* handler runs), never on a missing module. `error` already exists on state.
|
||||
*/
|
||||
interface HarnessTurnReceiptView {
|
||||
readonly idempotencyKey: string;
|
||||
readonly receiptId: string;
|
||||
readonly selection: HarnessSelection;
|
||||
}
|
||||
interface HarnessTurnStateView {
|
||||
readonly turnReceipt: HarnessTurnReceiptView | null | undefined;
|
||||
readonly error: string | null;
|
||||
}
|
||||
function harnessTurnState(): HarnessTurnStateView {
|
||||
return latest?.state as unknown as HarnessTurnStateView;
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit a server `turn:ack` the CURRENT hook has no listener for — a safe no-op
|
||||
* today (the fake iterates an empty handler set), so the group-4 reds fail
|
||||
* because nothing is surfaced, not because this throws. The event name is cast
|
||||
* past the compile-time `ServerToClientEvents` contract exactly as the
|
||||
* `turn:send` client cast is; the typed event map lands at Step Three.
|
||||
*/
|
||||
function serverEmitTurnAck(payload: unknown): void {
|
||||
fake.serverEmitRaw('turn:ack' as unknown as Parameters<typeof fake.serverEmitRaw>[0], payload);
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
@@ -67,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' });
|
||||
@@ -344,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({
|
||||
@@ -373,6 +511,408 @@ describe('useChatConnection', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('turn:send harness routing (Task Five, Step Two red-first)', () => {
|
||||
const selection: HarnessSelection = {
|
||||
harnessId: 'pi',
|
||||
providerId: 'anthropic',
|
||||
modelId: 'claude',
|
||||
};
|
||||
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' });
|
||||
});
|
||||
}
|
||||
|
||||
it('emits a single turn:send with the nested selection tuple and a UUID idempotencyKey — never the legacy message event', async () => {
|
||||
const restore = installRandomUUID(() => UUID);
|
||||
try {
|
||||
await establishConversation();
|
||||
await act(async () => {
|
||||
harnessSend()({ content: 'hello', selection });
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
const sends = fake.emitted.filter((e) => e.event === 'turn:send');
|
||||
expect(sends).toHaveLength(1);
|
||||
expect(sends[0]?.payload).toEqual({
|
||||
conversationId: 'c1',
|
||||
content: 'hello',
|
||||
selection,
|
||||
idempotencyKey: UUID,
|
||||
});
|
||||
// The pi-rpc sender must not fall back to the embedded `message` event.
|
||||
expect(fake.emitted.some((e) => e.event === 'message')).toBe(false);
|
||||
});
|
||||
|
||||
it('generates the idempotencyKey with exactly one crypto.randomUUID() call per accepted send', async () => {
|
||||
const gen = vi.fn(() => UUID);
|
||||
const restore = installRandomUUID(gen);
|
||||
try {
|
||||
await establishConversation();
|
||||
await act(async () => {
|
||||
harnessSend()({ content: 'first', selection });
|
||||
});
|
||||
await act(async () => {
|
||||
harnessSend()({ content: 'second', selection });
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
expect(gen).toHaveBeenCalledTimes(2);
|
||||
const keys = fake.emitted
|
||||
.filter((e) => e.event === 'turn:send')
|
||||
.map((e) => (e.payload as { idempotencyKey: string }).idempotencyKey);
|
||||
expect(keys).toEqual([UUID, UUID]);
|
||||
});
|
||||
|
||||
it('does not send before an active conversation id exists (no first-send auto-create)', async () => {
|
||||
const restore = installRandomUUID(() => UUID);
|
||||
let returned: boolean | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
returned = harnessSend()({ content: 'too early', selection });
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
expect(returned).toBe(false);
|
||||
expect(fake.emitted.some((e) => e.event === 'turn:send')).toBe(false);
|
||||
expect(fake.emitted.some((e) => e.event === 'message')).toBe(false);
|
||||
// Nothing optimistically appended when the send is refused.
|
||||
expect(latest?.state.messages.some((m) => m.text === 'too early')).toBe(false);
|
||||
});
|
||||
|
||||
it('returns true when it emits and false when the send is refused', async () => {
|
||||
const restore = installRandomUUID(() => UUID);
|
||||
let refusedEarly: boolean | undefined;
|
||||
let acceptedAfter: boolean | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
refusedEarly = harnessSend()({ content: 'early', selection });
|
||||
});
|
||||
await establishConversation();
|
||||
await act(async () => {
|
||||
acceptedAfter = harnessSend()({ content: 'now', selection });
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
expect(refusedEarly).toBe(false);
|
||||
expect(acceptedAfter).toBe(true);
|
||||
});
|
||||
|
||||
it('when secure UUID generation throws: emits nothing, appends nothing, releases the lock, and a later send succeeds', async () => {
|
||||
await establishConversation();
|
||||
|
||||
const failing = installRandomUUID(() => {
|
||||
throw new Error('secure random unavailable');
|
||||
});
|
||||
let firstReturn: boolean | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
firstReturn = harnessSend()({ content: 'blocked', selection });
|
||||
});
|
||||
} finally {
|
||||
failing();
|
||||
}
|
||||
|
||||
expect(firstReturn).toBe(false);
|
||||
expect(fake.emitted.some((e) => e.event === 'turn:send')).toBe(false);
|
||||
expect(latest?.state.messages.some((m) => m.text === 'blocked')).toBe(false);
|
||||
|
||||
// The send lock must have been released, so a subsequent valid send works.
|
||||
const restore = installRandomUUID(() => UUID);
|
||||
let secondReturn: boolean | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
secondReturn = harnessSend()({ content: 'retry', selection });
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
expect(secondReturn).toBe(true);
|
||||
expect(fake.emitted.some((e) => e.event === 'turn:send')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('turn:ack receipt + rejection contract (Task Five, Step Two group 4)', () => {
|
||||
const selection: HarnessSelection = {
|
||||
harnessId: 'pi',
|
||||
providerId: 'anthropic',
|
||||
modelId: 'claude',
|
||||
};
|
||||
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> {
|
||||
const restore = installRandomUUID(() => UUID);
|
||||
await act(async () => {
|
||||
fake.serverEmit('message:ack', { conversationId: 'c1', messageId: 'm1' });
|
||||
});
|
||||
await act(async () => {
|
||||
harnessSend()({ content: 'hello', selection });
|
||||
});
|
||||
return restore;
|
||||
}
|
||||
|
||||
it('surfaces a turn:ack receipt echoing the exact idempotencyKey, server receiptId, and requested selection tuple', async () => {
|
||||
const restore = await establishAndSend();
|
||||
try {
|
||||
await act(async () => {
|
||||
serverEmitTurnAck({
|
||||
conversationId: 'c1',
|
||||
idempotencyKey: UUID,
|
||||
receiptId: 'r1',
|
||||
selection,
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
// RED anchor: no turn:ack handler exists, so nothing is recorded. Green
|
||||
// only when Step Three echoes the exact tuple back into state — never a
|
||||
// substituted or fabricated one.
|
||||
expect(harnessTurnState().turnReceipt).toEqual({
|
||||
idempotencyKey: UUID,
|
||||
receiptId: 'r1',
|
||||
selection,
|
||||
});
|
||||
});
|
||||
|
||||
it('on a rejected turn:ack surfaces a visible safe notice, never the raw internal error, and fabricates no receipt tuple', async () => {
|
||||
const restore = await establishAndSend();
|
||||
try {
|
||||
await act(async () => {
|
||||
serverEmitTurnAck({
|
||||
conversationId: 'c1',
|
||||
idempotencyKey: UUID,
|
||||
ok: false,
|
||||
code: 'runtime_unsupported',
|
||||
error: 'ADAPTER_BOOM internal stack: pi adapter unavailable at 0xdeadbeef',
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
// RED anchor: a rejected ack must surface a visible notice; today no
|
||||
// handler runs, so state.error stays null.
|
||||
expect(harnessTurnState().error).toBeTruthy();
|
||||
// The raw internal exception text must never reach the browser surface.
|
||||
expect(harnessTurnState().error ?? '').not.toContain('ADAPTER_BOOM');
|
||||
expect(harnessTurnState().error ?? '').not.toContain('0xdeadbeef');
|
||||
// A rejection must not fabricate a success receipt tuple.
|
||||
expect(harnessTurnState().turnReceipt ?? null).toBeNull();
|
||||
});
|
||||
|
||||
it('uses one fixed safe rejection notice regardless of the internal cause (frozen union, not a passthrough)', async () => {
|
||||
const firstRestore = await establishAndSend();
|
||||
try {
|
||||
await act(async () => {
|
||||
serverEmitTurnAck({
|
||||
conversationId: 'c1',
|
||||
idempotencyKey: UUID,
|
||||
ok: false,
|
||||
code: 'runtime_unsupported',
|
||||
error: 'cause-ALPHA adapter_unavailable',
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
firstRestore();
|
||||
}
|
||||
const firstNotice = harnessTurnState().error;
|
||||
|
||||
// A fresh turn on the same conversation, rejected for a DIFFERENT internal
|
||||
// reason, must surface the identical fixed notice.
|
||||
const secondRestore = installRandomUUID(() => UUID);
|
||||
try {
|
||||
await act(async () => {
|
||||
harnessSend()({ content: 'again', selection });
|
||||
});
|
||||
await act(async () => {
|
||||
serverEmitTurnAck({
|
||||
conversationId: 'c1',
|
||||
idempotencyKey: UUID,
|
||||
ok: false,
|
||||
code: 'runtime_unsupported',
|
||||
error: 'cause-BRAVO conversation_service_unavailable',
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
secondRestore();
|
||||
}
|
||||
const secondNotice = harnessTurnState().error;
|
||||
|
||||
// RED anchor: both are null today; green requires a single frozen safe
|
||||
// string surfaced for both distinct internal causes.
|
||||
expect(firstNotice).toBeTruthy();
|
||||
expect(secondNotice).toBeTruthy();
|
||||
expect(firstNotice).toBe(secondNotice);
|
||||
expect(firstNotice ?? '').not.toContain('ALPHA');
|
||||
expect(secondNotice ?? '').not.toContain('BRAVO');
|
||||
});
|
||||
});
|
||||
|
||||
describe('idempotency-key failure semantics (Task Five, Step Two group 5)', () => {
|
||||
const selection: HarnessSelection = {
|
||||
harnessId: 'pi',
|
||||
providerId: 'anthropic',
|
||||
modelId: 'claude',
|
||||
};
|
||||
const UUID_A = '11111111-1111-4111-8111-111111111111';
|
||||
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' });
|
||||
});
|
||||
}
|
||||
|
||||
it('mints a DISTINCT UUID-v4 idempotencyKey for each of two accepted turns — a key is never reused across turns', async () => {
|
||||
const keys = [UUID_A, UUID_B];
|
||||
let call = 0;
|
||||
const restore = installRandomUUID(() => keys[call++] ?? UUID_A);
|
||||
try {
|
||||
await establish();
|
||||
await act(async () => {
|
||||
harnessSend()({ content: 'first', selection });
|
||||
});
|
||||
await act(async () => {
|
||||
harnessSend()({ content: 'second', selection });
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
const sent = fake.emitted
|
||||
.filter((e) => e.event === 'turn:send')
|
||||
.map((e) => (e.payload as { idempotencyKey: string }).idempotencyKey);
|
||||
// RED anchor: current sendMessage emits the legacy `message`, so no
|
||||
// turn:send keys exist at all.
|
||||
expect(sent).toHaveLength(2);
|
||||
expect(sent[0]).toMatch(UUID_V4);
|
||||
expect(sent[1]).toMatch(UUID_V4);
|
||||
expect(sent[0]).not.toBe(sent[1]);
|
||||
});
|
||||
|
||||
it('when crypto.randomUUID is ABSENT: surfaces a visible fixed idempotency-unavailable notice, emits nothing, appends nothing, releases the lock synchronously, and a later valid send succeeds', async () => {
|
||||
await establish();
|
||||
|
||||
const restoreCrypto = removeRandomUUID();
|
||||
let firstReturn: boolean | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
firstReturn = harnessSend()({ content: 'no-secure-random', selection });
|
||||
});
|
||||
} finally {
|
||||
restoreCrypto();
|
||||
}
|
||||
|
||||
// RED anchors: a refused send returns false and surfaces a visible notice.
|
||||
expect(firstReturn).toBe(false);
|
||||
expect(harnessTurnState().error).toBeTruthy();
|
||||
expect(fake.emitted.some((e) => e.event === 'turn:send')).toBe(false);
|
||||
expect(latest?.state.messages.some((m) => m.text === 'no-secure-random')).toBe(false);
|
||||
|
||||
// The lock released synchronously (no server event needed): a later valid
|
||||
// send goes through.
|
||||
const restore = installRandomUUID(() => UUID_A);
|
||||
let secondReturn: boolean | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
secondReturn = harnessSend()({ content: 'recovered', selection });
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
expect(secondReturn).toBe(true);
|
||||
expect(fake.emitted.some((e) => e.event === 'turn:send')).toBe(true);
|
||||
});
|
||||
|
||||
it('surfaces the SAME fixed idempotency-unavailable notice whether randomUUID is absent or throws, never leaking the thrown message', async () => {
|
||||
// Case 1: absent.
|
||||
await establish();
|
||||
const restoreAbsent = removeRandomUUID();
|
||||
try {
|
||||
await act(async () => {
|
||||
harnessSend()({ content: 'absent', selection });
|
||||
});
|
||||
} finally {
|
||||
restoreAbsent();
|
||||
}
|
||||
const absentNotice = harnessTurnState().error;
|
||||
|
||||
// Case 2: throws with a distinctive internal message.
|
||||
const failing = installRandomUUID(() => {
|
||||
throw new Error('SECURE_RANDOM_BOOM entropy pool drained');
|
||||
});
|
||||
try {
|
||||
await act(async () => {
|
||||
harnessSend()({ content: 'throws', selection });
|
||||
});
|
||||
} finally {
|
||||
failing();
|
||||
}
|
||||
const throwNotice = harnessTurnState().error;
|
||||
|
||||
// RED anchor: both are null today.
|
||||
expect(absentNotice).toBeTruthy();
|
||||
expect(throwNotice).toBeTruthy();
|
||||
expect(absentNotice).toBe(throwNotice);
|
||||
// The thrown internal detail must never reach the browser surface.
|
||||
expect(throwNotice ?? '').not.toContain('SECURE_RANDOM_BOOM');
|
||||
expect(throwNotice ?? '').not.toContain('entropy pool');
|
||||
});
|
||||
});
|
||||
|
||||
it('abort emits abort with the active conversationId', async () => {
|
||||
await act(async () => {
|
||||
fake.serverEmit('message:ack', { conversationId: 'c1', messageId: 'm1' });
|
||||
@@ -684,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' });
|
||||
});
|
||||
@@ -1665,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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user