import { describe, test, expect, beforeEach, mock } from 'bun:test' import { mockConfigModule } from './helpers/mock-config' // Mock config before imports mock.module('../config', () => mockConfigModule()) import { storeReset, storeCreateEnvironment, storeCreateSession, } from '../store' import { getEventBus, removeEventBus, getAllEventBuses, } from '../transport/event-bus' import { ingestBridgeMessage, handleWebSocketOpen, handleWebSocketMessage, handleWebSocketClose, closeAllConnections, touchClientActivity, closeInactiveClient, } from '../transport/ws-handler' import { publishSessionEvent } from '../services/transport' // Minimal WSContext mock function createMockWs(readyState = 1) { const sent: string[] = [] return { readyState, send: (data: string) => sent.push(data), close: (_code?: number, _reason?: string) => {}, getSentData: () => sent, } as any } describe('ws-handler', () => { beforeEach(() => { storeReset() for (const [key] of getAllEventBuses()) { removeEventBus(key) } closeAllConnections() }) describe('ingestBridgeMessage', () => { test('ignores keep_alive messages', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('s1', { type: 'keep_alive' }) expect(events).toHaveLength(0) }) test('derives type from message.role for user messages', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('s1', { message: { role: 'user', content: 'hello' }, uuid: 'u1', }) expect(events).toHaveLength(1) expect((events[0] as any).type).toBe('user') expect((events[0] as any).direction).toBe('inbound') }) test('preserves synthetic flag on inbound user messages', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('s1', { message: { role: 'user', content: 'scheduled job: refresh analytics cache', }, uuid: 'u_synth', isSynthetic: true, }) expect(events).toHaveLength(1) expect((events[0] as any).payload.isSynthetic).toBe(true) }) test('derives type from message.role for assistant messages', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('s1', { message: { role: 'assistant', content: [{ type: 'text', text: 'response' }], }, uuid: 'u2', }) expect(events).toHaveLength(1) expect((events[0] as any).type).toBe('assistant') const payload = (events[0] as any).payload as Record expect(payload.content).toBe('response') }) test('derives type from explicit type field', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('s1', { type: 'control_request', request_id: 'r1', request: { subtype: 'interrupt' }, }) expect(events).toHaveLength(1) expect((events[0] as any).type).toBe('control_request') }) test('worker conversation_cleared status wipes history instead of publishing status event', () => { const bus = getEventBus('s1') // Seed history like a real session would have. ingestBridgeMessage('s1', { message: { role: 'user', content: 'hello' }, uuid: 'u_before_clear', }) expect(bus.getEventsSince(0).length).toBeGreaterThan(0) const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('s1', { type: 'status', subtype: 'status', status: 'conversation_cleared', message: 'conversation_cleared', uuid: 'u_clear_status', }) // Live viewers get the transient conversation_cleared signal… const cleared = events.find(e => (e as any).type === 'session_status') expect(cleared).toBeDefined() expect((cleared as any).payload.status).toBe('conversation_cleared') // …the raw status event is NOT published (would pollute the fresh log)… expect(events.some(e => (e as any).type === 'status')).toBe(false) // …and the replay window is empty again. expect(bus.getEventsSince(0)).toHaveLength(0) }) test('derives result type from subtype/result fields', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('s1', { subtype: 'success', uuid: 'u3', result: 'done', }) expect(events).toHaveLength(1) expect((events[0] as any).type).toBe('result') }) test('derives system type from session_id field', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('s1', { session_id: 's1', init: true }) expect(events).toHaveLength(1) expect((events[0] as any).type).toBe('system') }) test('system/init keeps command tables and remote capabilities for the Web UI', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('s1', { type: 'system', subtype: 'init', uuid: 'u-init-1', slash_commands: ['compact', 'cost'], slash_command_details: [ { name: 'compact', description: '压缩上下文', argumentHint: '' }, { name: 'cost', description: '查看会话费用' }, ], skills: ['code-review'], skill_details: [{ name: 'code-review', description: 'Review code' }], remote_capabilities: { file_search: true, clear: true, set_max_thinking_tokens: true, get_context_usage: true, stop_task: true, set_model: true, set_permission_mode: true, interrupt: true, }, }) expect(events).toHaveLength(1) const payload = (events[0] as any).payload // Both the ingest layer (top of payload) and normalizePayload's raw // copy must carry the fields — the web adapter reads either. expect(payload.slash_command_details).toEqual([ { name: 'compact', description: '压缩上下文', argumentHint: '' }, { name: 'cost', description: '查看会话费用' }, ]) expect(payload.remote_capabilities).toEqual({ file_search: true, clear: true, set_max_thinking_tokens: true, get_context_usage: true, stop_task: true, set_model: true, set_permission_mode: true, interrupt: true, }) expect(payload.skill_details).toEqual([ { name: 'code-review', description: 'Review code' }, ]) expect(payload.slash_commands).toEqual(['compact', 'cost']) expect(payload.skills).toEqual(['code-review']) expect((payload.raw as any).slash_commands).toEqual(['compact', 'cost']) expect((payload.raw as any).remote_capabilities).toBeDefined() }) test('non-init system messages do not carry init fields', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('s1', { type: 'system', subtype: 'status', uuid: 'u-status-1', permissionMode: 'default', slash_commands: ['should-not-leak'], }) expect(events).toHaveLength(1) const payload = (events[0] as any).payload // Neither the relayed payload nor raw (the ingest output, not the // original wire message) carries the init-only fields — the web // adapter's extractWorkerInfo only reads them for subtype 'init'. expect(payload.slash_commands).toBeUndefined() expect((payload.raw as any).slash_commands).toBeUndefined() expect(payload.permissionMode).toBe('default') }) test('handles control_response type', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('s1', { type: 'control_response', response: { subtype: 'success' }, }) expect(events).toHaveLength(1) expect((events[0] as any).type).toBe('control_response') }) test('handles partial_assistant type', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('s1', { type: 'partial_assistant', message: { content: 'partial...' }, uuid: 'u4', }) expect(events).toHaveLength(1) expect((events[0] as any).type).toBe('partial_assistant') }) test('falls back to unknown type', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('s1', { data: 'something' }) expect(events).toHaveLength(1) expect((events[0] as any).type).toBe('unknown') }) test('skips isReplay acks from child', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('s1', { type: 'user', uuid: 'replay-ack-1', message: { role: 'user', content: 'hello' }, isReplay: true, }) expect(events).toHaveLength(0) }) test('skips assistant message echo with duplicate UUID', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) // Simulate the original inbound assistant event already in the bus bus.publish({ id: 'orig-1', sessionId: 's1', type: 'assistant', payload: { uuid: 'dup-uuid-1', content: 'hi' }, direction: 'inbound', }) events.length = 0 // Child echoes the same message back on WS reconnect ingestBridgeMessage('s1', { type: 'assistant', uuid: 'dup-uuid-1', message: { role: 'assistant', content: [{ type: 'text', text: 'hi' }], }, }) expect(events).toHaveLength(0) }) test('publishes first-time assistant message with fresh UUID', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('s1', { type: 'assistant', uuid: 'fresh-uuid-1', message: { role: 'assistant', content: [{ type: 'text', text: 'fresh reply' }], }, }) expect(events).toHaveLength(1) }) test('preserves SDK fields on system task_started events', () => { const bus = getEventBus('sdk1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('sdk1', { type: 'system', subtype: 'task_started', task_id: 'task-1', tool_use_id: 'tu-1', description: 'Investigate auth', task_type: 'local_agent', }) expect(events).toHaveLength(1) const payload = (events[0] as any).payload as Record expect(payload.subtype).toBe('task_started') expect(payload.task_id).toBe('task-1') expect(payload.tool_use_id).toBe('tu-1') expect(payload.description).toBe('Investigate auth') expect(payload.task_type).toBe('local_agent') }) test('preserves usage on system task_progress events', () => { const bus = getEventBus('sdk2') const events: unknown[] = [] bus.subscribe(e => events.push(e)) const usage = { total_tokens: 100, tool_uses: 3, duration_ms: 5000 } ingestBridgeMessage('sdk2', { type: 'system', subtype: 'task_progress', task_id: 'task-2', usage, last_tool_name: 'Grep', summary: 'searching', }) expect(events).toHaveLength(1) const payload = (events[0] as any).payload as Record expect(payload.subtype).toBe('task_progress') expect(payload.task_id).toBe('task-2') expect(payload.usage).toEqual(usage) expect(payload.last_tool_name).toBe('Grep') expect(payload.summary).toBe('searching') }) test('preserves status and output_file on system task_notification events', () => { const bus = getEventBus('sdk3') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('sdk3', { type: 'system', subtype: 'task_notification', task_id: 'task-3', status: 'completed', output_file: '/tmp/out.json', summary: 'Done', }) expect(events).toHaveLength(1) const payload = (events[0] as any).payload as Record expect(payload.subtype).toBe('task_notification') expect(payload.status).toBe('completed') expect(payload.output_file).toBe('/tmp/out.json') expect(payload.summary).toBe('Done') }) test('drops task fields from non-task system subtypes', () => { const bus = getEventBus('sdk4') const events: unknown[] = [] bus.subscribe(e => events.push(e)) ingestBridgeMessage('sdk4', { type: 'system', subtype: 'init', session_id: 'sdk4', task_id: 'should-not-leak', }) expect(events).toHaveLength(1) const payload = (events[0] as any).payload as Record expect(payload.subtype).toBe('init') expect(payload.task_id).toBeUndefined() expect(payload.description).toBeUndefined() }) }) describe('handleWebSocketOpen', () => { test('subscribes to event bus and replays missed events', () => { // Publish some events before WS connects const bus = getEventBus('s1') bus.publish({ id: 'e1', sessionId: 's1', type: 'user', payload: { content: 'hello' }, direction: 'outbound', }) bus.publish({ id: 'e2', sessionId: 's1', type: 'assistant', payload: { content: 'hi' }, direction: 'inbound', }) const ws = createMockWs() handleWebSocketOpen(ws, 's1') // Should have replayed the outbound event (only outbound events are forwarded to WS) const sent = ws.getSentData() expect(sent.length).toBeGreaterThanOrEqual(1) // First message should be the outbound user event const msg = JSON.parse(sent[0]) expect(msg.type).toBe('user') }) test('replays synthetic user metadata back to the bridge', () => { const bus = getEventBus('s3') bus.publish({ id: 'e1', sessionId: 's3', type: 'user', payload: { content: 'scheduled job: refresh analytics cache', isSynthetic: true, }, direction: 'outbound', }) const ws = createMockWs() handleWebSocketOpen(ws, 's3') const msg = JSON.parse(ws.getSentData()[0]) expect(msg.type).toBe('user') expect(msg.isSynthetic).toBe(true) }) test('replay skips point-in-time control traffic (interrupt, permission RPCs)', () => { // Regression: the replay used to forward EVERY retained event, // including one-shot RPCs. A replayed `interrupt` control_request was // re-executed by the bridge — aborting whatever turn was running // AFTER the reconnect. const bus = getEventBus('replay_ctrl') bus.publish({ id: 'e1', sessionId: 'replay_ctrl', type: 'user', payload: { content: 'task prompt' }, direction: 'outbound', }) bus.publish({ id: 'e2', sessionId: 'replay_ctrl', type: 'control_request', payload: { request_id: 'r1', request: { subtype: 'interrupt' } }, direction: 'outbound', }) bus.publish({ id: 'e3', sessionId: 'replay_ctrl', type: 'permission_response', payload: { request_id: 'r2', approved: true }, direction: 'outbound', }) bus.publish({ id: 'e4', sessionId: 'replay_ctrl', type: 'assistant', payload: { content: 'done' }, direction: 'inbound', }) const ws = createMockWs() handleWebSocketOpen(ws, 'replay_ctrl') const sent = ws.getSentData() const types = sent.map( (line: string) => (JSON.parse(line) as { type: string }).type, ) expect(types).toContain('user') expect(types).toContain('assistant') expect(types).not.toContain('control_request') expect(types).not.toContain('permission_response') expect(types).not.toContain('interrupt') }) test('replaces existing connection for same session', () => { const ws1 = createMockWs() const ws2 = createMockWs() handleWebSocketOpen(ws1, 's2') handleWebSocketOpen(ws2, 's2') // ws2 should be the active connection const bus = getEventBus('s2') bus.publish({ id: 'e1', sessionId: 's2', type: 'user', payload: { content: 'test' }, direction: 'outbound', }) expect(ws2.getSentData().length).toBeGreaterThanOrEqual(1) }) }) describe('handleWebSocketMessage', () => { test('parses NDJSON and ingests each message', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) const ws = createMockWs() const data = JSON.stringify({ type: 'user', message: { role: 'user', content: 'hello' }, }) + '\n' + JSON.stringify({ type: 'assistant', message: { role: 'assistant', content: 'hi' }, }) + '\n' handleWebSocketMessage(ws, 's1', data) expect(events).toHaveLength(2) }) test('ignores malformed JSON lines', () => { const bus = getEventBus('s1') const events: unknown[] = [] bus.subscribe(e => events.push(e)) const ws = createMockWs() handleWebSocketMessage(ws, 's1', 'not json\n') expect(events).toHaveLength(0) }) }) describe('touchClientActivity', () => { test('updates lastClientActivity for an open connection', () => { const ws = createMockWs() handleWebSocketOpen(ws, 'touch1') // Simulate passage of time by backdating the open activity timestamp // via a fake timer so the touch is observable. const originalNow = Date.now const baseTime = originalNow() Date.now = () => baseTime try { // Advance the clock by 90s without triggering real timers — // the activity timestamp captured at open is now stale. Date.now = () => baseTime + 90_000 touchClientActivity('touch1') // Reset to the touched timestamp; calling again should move it forward. Date.now = () => baseTime + 120_000 touchClientActivity('touch1') } finally { Date.now = originalNow } // The connection should still be tracked (not closed by the keepalive // loop). We can't drive the real keepalive timer here without waiting, // but verifying the entry survives is enough — a closed connection // would have been removed from cleanupBySession. expect(() => { const bus = getEventBus('touch1') bus.publish({ id: 'p1', sessionId: 'touch1', type: 'user', payload: { content: 'still alive' }, direction: 'outbound', }) }).not.toThrow() }) test('is a no-op for unknown sessions', () => { expect(() => touchClientActivity('never-opened')).not.toThrow() }) }) describe('closeInactiveClient', () => { // Regression: the original keepalive interval read a const closure // variable captured at open time — touchClientActivity mutated a // different copy on the cleanup entry, so EVERY connection was closed // exactly CLIENT_ACTIVITY_TIMEOUT after open ("client inactive" 误报, // observed as duration=300s closes on actively-POSTing workers). test('client activity via touchClientActivity resets the inactivity clock', () => { const closed: Array<{ code?: number; reason?: string }> = [] const ws = { readyState: 1, send: () => {}, close: (code?: number, reason?: string) => closed.push({ code, reason }), } as any handleWebSocketOpen(ws, 'inact1') // Connection opened at T0; the worker POSTs (touch) at T0+10min. // Measured 100s after the touch → within the 300s budget → NOT closed. const touchedAt = Date.now() + 600_000 const originalNow = Date.now Date.now = () => touchedAt try { touchClientActivity('inact1') } finally { Date.now = originalNow } expect(closeInactiveClient('inact1', touchedAt + 100_000)).toBe(false) expect(closed).toHaveLength(0) handleWebSocketClose(ws, 'inact1', 1000, 'done') }) test('closes a truly silent client and queues a recovery work item', async () => { const env = storeCreateEnvironment({ secret: 's' }) const session = storeCreateSession({ environmentId: env.id }) const closed: Array<{ code?: number; reason?: string }> = [] const ws = { readyState: 1, send: () => {}, close: (code?: number, reason?: string) => closed.push({ code, reason }), } as any handleWebSocketOpen(ws, session.id) // Opened at ~now; nothing touches for 400s → closed as dead. const openedAt = Date.now() expect(closeInactiveClient(session.id, openedAt + 400_000)).toBe(true) expect(closed).toHaveLength(1) expect(closed[0]?.code).toBe(1000) // Redispatch is fire-and-forget — let the microtask settle. await new Promise(resolve => setTimeout(resolve, 0)) const { storeGetPendingWorkItem } = await import('../store') expect(storeGetPendingWorkItem(env.id)?.sessionId).toBe(session.id) handleWebSocketClose(ws, session.id, 1000, 'done') }) test('does not close within the inactivity budget', () => { const ws = createMockWs() handleWebSocketOpen(ws, 'inact3') expect(closeInactiveClient('inact3', Date.now() + 100_000)).toBe(false) handleWebSocketClose(ws, 'inact3', 1000, 'done') }) test('is a no-op for unknown sessions and dead sockets', () => { expect(closeInactiveClient('never-opened')).toBe(false) const ws = createMockWs(3) // CLOSED handleWebSocketOpen(ws, 'inact4') expect(closeInactiveClient('inact4', Date.now() + 400_000)).toBe(false) handleWebSocketClose(ws, 'inact4', 1000, 'done') }) // HybridTransport workers send WS-level keep_alive frames (direct // socket writes) even when their POST write path is dead — counting // them as activity would make the inactivity close unreachable for // exactly the zombie state it exists to detect. test('WS keep_alive frames do NOT refresh the inactivity clock', () => { const closed: Array<{ code?: number; reason?: string }> = [] const ws = { readyState: 1, send: () => {}, close: (code?: number, reason?: string) => closed.push({ code, reason }), } as any handleWebSocketOpen(ws, 'ka1') // keep_alive 帧到达 +250s(预算内)— 不刷新时钟 const at250 = Date.now() + 250_000 const originalNow = Date.now Date.now = () => at250 try { handleWebSocketMessage(ws, 'ka1', '{"type":"keep_alive"}\n') } finally { Date.now = originalNow } // +350s(自打开起超预算)→ 尽管 keepalive 一直在发,仍然关闭 expect(closeInactiveClient('ka1', Date.now() + 350_000)).toBe(true) expect(closed).toHaveLength(1) handleWebSocketClose(ws, 'ka1', 1000, 'done') }) test('real WS messages still refresh the inactivity clock', () => { const ws = createMockWs() handleWebSocketOpen(ws, 'ka2') // 真实消息(非 keep_alive)到达 +250s — 刷新时钟 const at250 = Date.now() + 250_000 const originalNow = Date.now Date.now = () => at250 try { handleWebSocketMessage( ws, 'ka2', '{"type":"user","message":{"role":"user","content":"hi"},"uuid":"u-ka"}\n', ) } finally { Date.now = originalNow } // +350s 距打开超预算,但距上次活动(+250s)仅 100s → 不关闭 expect(closeInactiveClient('ka2', at250 + 100_000)).toBe(false) handleWebSocketClose(ws, 'ka2', 1000, 'done') }) }) describe('handleWebSocketClose', () => { test('cleans up on close', () => { const ws = createMockWs() handleWebSocketOpen(ws, 's3') handleWebSocketClose(ws, 's3', 1000, 'done') // After close, publishing events should not cause errors const bus = getEventBus('s3') expect(() => bus.publish({ id: 'e1', sessionId: 's3', type: 'user', payload: {}, direction: 'outbound', }), ).not.toThrow() }) }) describe('toSDKMessage (via handleWebSocketOpen outbound delivery)', () => { test('converts permission_response with approved=true', () => { const bus = getEventBus('pr1') const ws = createMockWs() handleWebSocketOpen(ws, 'pr1') bus.publish({ id: 'e1', sessionId: 'pr1', type: 'permission_response', payload: { approved: true, request_id: 'req1' }, direction: 'outbound', }) const sent = ws.getSentData() const lastMsg = JSON.parse(sent[sent.length - 1]) expect(lastMsg.type).toBe('control_response') expect(lastMsg.response.subtype).toBe('success') expect(lastMsg.response.request_id).toBe('req1') expect(lastMsg.response.response.behavior).toBe('allow') }) test('converts permission_response with approved=false', () => { const bus = getEventBus('pr2') const ws = createMockWs() handleWebSocketOpen(ws, 'pr2') bus.publish({ id: 'e2', sessionId: 'pr2', type: 'permission_response', payload: { approved: false, request_id: 'req2' }, direction: 'outbound', }) const sent = ws.getSentData() const lastMsg = JSON.parse(sent[sent.length - 1]) expect(lastMsg.type).toBe('control_response') expect(lastMsg.response.subtype).toBe('error') expect(lastMsg.response.error).toBe('Permission denied by user') expect(lastMsg.response.response.behavior).toBe('deny') }) test('converts permission_response with existing response object', () => { const bus = getEventBus('pr3') const ws = createMockWs() handleWebSocketOpen(ws, 'pr3') bus.publish({ id: 'e3', sessionId: 'pr3', type: 'control_response', payload: { response: { subtype: 'success', data: 'custom' } }, direction: 'outbound', }) const sent = ws.getSentData() const lastMsg = JSON.parse(sent[sent.length - 1]) expect(lastMsg.type).toBe('control_response') expect(lastMsg.response.subtype).toBe('success') expect(lastMsg.response.data).toBe('custom') }) test('converts interrupt event', () => { const bus = getEventBus('int1') const ws = createMockWs() handleWebSocketOpen(ws, 'int1') bus.publish({ id: 'e4', sessionId: 'int1', type: 'interrupt', payload: { action: 'interrupt' }, direction: 'outbound', }) const sent = ws.getSentData() const lastMsg = JSON.parse(sent[sent.length - 1]) expect(lastMsg.type).toBe('control_request') expect(lastMsg.request_id).toBe('e4') expect(lastMsg.request.subtype).toBe('interrupt') }) test('converts control_request event', () => { const bus = getEventBus('cr1') const ws = createMockWs() handleWebSocketOpen(ws, 'cr1') bus.publish({ id: 'e5', sessionId: 'cr1', type: 'control_request', payload: { request_id: 'req5', request: { subtype: 'permission', tool_name: 'Bash' }, }, direction: 'outbound', }) const sent = ws.getSentData() const lastMsg = JSON.parse(sent[sent.length - 1]) expect(lastMsg.type).toBe('control_request') expect(lastMsg.request_id).toBe('req5') expect(lastMsg.request.subtype).toBe('permission') }) test('converts user_message event type', () => { const bus = getEventBus('um1') const ws = createMockWs() handleWebSocketOpen(ws, 'um1') bus.publish({ id: 'e6', sessionId: 'um1', type: 'user_message', payload: { content: 'hello world' }, direction: 'outbound', }) const sent = ws.getSentData() const lastMsg = JSON.parse(sent[sent.length - 1]) expect(lastMsg.type).toBe('user') expect(lastMsg.message.content).toBe('hello world') }) test('preserves payload uuid for outbound user events', () => { const bus = getEventBus('um2') const ws = createMockWs() handleWebSocketOpen(ws, 'um2') bus.publish({ id: 'internal-event-id', sessionId: 'um2', type: 'user', payload: { uuid: 'web-message-uuid', content: 'hello from web' }, direction: 'outbound', }) const sent = ws.getSentData() const lastMsg = JSON.parse(sent[sent.length - 1]) expect(lastMsg.type).toBe('user') expect(lastMsg.uuid).toBe('web-message-uuid') expect(lastMsg.message.content).toBe('hello from web') }) test('converts generic event type', () => { const bus = getEventBus('gen1') const ws = createMockWs() handleWebSocketOpen(ws, 'gen1') bus.publish({ id: 'e7', sessionId: 'gen1', type: 'status', payload: { state: 'running' }, direction: 'outbound', }) const sent = ws.getSentData() const lastMsg = JSON.parse(sent[sent.length - 1]) expect(lastMsg.type).toBe('status') expect(lastMsg.message).toEqual({ state: 'running' }) }) test('permission_response with updated_input', () => { const bus = getEventBus('ui1') const ws = createMockWs() handleWebSocketOpen(ws, 'ui1') bus.publish({ id: 'e8', sessionId: 'ui1', type: 'permission_response', payload: { approved: true, request_id: 'req8', updated_input: { cmd: 'ls -la' }, }, direction: 'outbound', }) const sent = ws.getSentData() const lastMsg = JSON.parse(sent[sent.length - 1]) expect(lastMsg.response.response.behavior).toBe('allow') expect(lastMsg.response.response.updatedInput).toEqual({ cmd: 'ls -la' }) }) test('permission_response with updated_permissions', () => { const bus = getEventBus('up1') const ws = createMockWs() handleWebSocketOpen(ws, 'up1') const permissions = [ { type: 'setMode', mode: 'acceptEdits', destination: 'session' }, ] bus.publish({ id: 'ep1', sessionId: 'up1', type: 'permission_response', payload: { approved: true, request_id: 'req-ep1', updated_input: { plan: 'my plan' }, updated_permissions: permissions, }, direction: 'outbound', }) const sent = ws.getSentData() const lastMsg = JSON.parse(sent[sent.length - 1]) expect(lastMsg.type).toBe('control_response') expect(lastMsg.response.subtype).toBe('success') expect(lastMsg.response.response.behavior).toBe('allow') expect(lastMsg.response.response.updatedInput).toEqual({ plan: 'my plan', }) expect(lastMsg.response.response.updatedPermissions).toEqual(permissions) }) test('plain approval without updated_input defaults updatedInput to {} (worker schema requires it)', () => { const bus = getEventBus('pa1') const ws = createMockWs() handleWebSocketOpen(ws, 'pa1') bus.publish({ id: 'pa1', sessionId: 'pa1', type: 'permission_response', payload: { approved: true, request_id: 'req-pa1', }, direction: 'outbound', }) const sent = ws.getSentData() const lastMsg = JSON.parse(sent[sent.length - 1]) expect(lastMsg.type).toBe('control_response') expect(lastMsg.response.subtype).toBe('success') // worker 侧 PermissionPromptToolResultSchema 要求 updatedInput 必填 — // 缺失时 schema.parse 抛错、批准被误转为 deny(移动端推送响应发 {} 的 // 同款模式;worker 侧把空对象当作"沿用原始输入") expect(lastMsg.response.response.updatedInput).toEqual({}) }) test('always-allow with only updated_permissions carries empty updatedInput', () => { const bus = getEventBus('aa1') const ws = createMockWs() handleWebSocketOpen(ws, 'aa1') bus.publish({ id: 'aa1', sessionId: 'aa1', type: 'permission_response', payload: { approved: true, request_id: 'req-aa1', updated_permissions: [ { type: 'addRules', rules: [{ toolName: 'Bash', ruleContent: 'git status:*' }], behavior: 'allow', destination: 'session', }, ], }, direction: 'outbound', }) const sent = ws.getSentData() const lastMsg = JSON.parse(sent[sent.length - 1]) expect(lastMsg.response.subtype).toBe('success') expect(lastMsg.response.response.behavior).toBe('allow') expect(lastMsg.response.response.updatedInput).toEqual({}) expect(lastMsg.response.response.updatedPermissions).toEqual([ { type: 'addRules', rules: [{ toolName: 'Bash', ruleContent: 'git status:*' }], behavior: 'allow', destination: 'session', }, ]) }) test('plain deny without feedback message gets default deny message (worker schema requires it)', () => { const bus = getEventBus('pd1') const ws = createMockWs() handleWebSocketOpen(ws, 'pd1') bus.publish({ id: 'pd1', sessionId: 'pd1', type: 'permission_response', payload: { approved: false, request_id: 'req-pd1', }, direction: 'outbound', }) const sent = ws.getSentData() const lastMsg = JSON.parse(sent[sent.length - 1]) expect(lastMsg.response.subtype).toBe('error') expect(lastMsg.response.response.behavior).toBe('deny') // worker 侧 deny schema 要求 message 必填 — 无反馈时服务端补默认文案 expect(lastMsg.response.response.message).toBe( 'Permission denied by user', ) }) test('permission_response denied with feedback message', () => { const bus = getEventBus('dm1') const ws = createMockWs() handleWebSocketOpen(ws, 'dm1') bus.publish({ id: 'dm1', sessionId: 'dm1', type: 'permission_response', payload: { approved: false, request_id: 'req-dm1', message: 'Please add more tests', }, direction: 'outbound', }) const sent = ws.getSentData() const lastMsg = JSON.parse(sent[sent.length - 1]) expect(lastMsg.type).toBe('control_response') expect(lastMsg.response.subtype).toBe('error') expect(lastMsg.response.response.behavior).toBe('deny') expect(lastMsg.response.message).toBe('Please add more tests') }) test('does not forward inbound events to WS', () => { const bus = getEventBus('no_in') const ws = createMockWs() handleWebSocketOpen(ws, 'no_in') bus.publish({ id: 'e9', sessionId: 'no_in', type: 'assistant', payload: { content: 'reply' }, direction: 'inbound', }) // Only replayed events, no new inbound delivery const sent = ws.getSentData() // No outbound events were published, so only replay (if any) // Since the bus was fresh, no replay expect(sent).toHaveLength(0) }) test('control_request falls back to payload when no request field', () => { const bus = getEventBus('cf1') const ws = createMockWs() handleWebSocketOpen(ws, 'cf1') bus.publish({ id: 'e10', sessionId: 'cf1', type: 'control_request', payload: { request_id: 'req10', subtype: 'custom', data: 'test' }, direction: 'outbound', }) const sent = ws.getSentData() const lastMsg = JSON.parse(sent[sent.length - 1]) expect(lastMsg.type).toBe('control_request') expect(lastMsg.request_id).toBe('req10') }) }) // ───────────────────────────────────────────────────────────────────────── // Regression: permission approval lost during a WS gap → turn parked on // the permission wait forever (session stuck requires_action, card already // optimistically removed → total deadlock). Root cause is two-fold on the // server→worker direction (the worker→server direction is covered by the // bridge's verified-write retry): // 1. the live subscriber silently drops outbound events while // ws.readyState !== 1 (reconnect window), and // 2. on reconnect, NON_REPLAYABLE_EVENT_TYPES filtered // permission_response / control_response out of the history replay — // the approval was never re-delivered. // Outbound RESPONSES are replay-safe (the worker settles by request_id; // already-settled ids are logged and ignored) and must be replayed. // Outbound control_REQUESTS stay non-replayable (a replayed interrupt // aborts the post-reconnect turn). describe('approval replay across WS reconnect (lost-response regression)', () => { test('approval sent during the WS gap is re-delivered on reconnect', () => { const env = storeCreateEnvironment({ secret: 's' }) const session = storeCreateSession({ environmentId: env.id }) const bus = getEventBus(session.id) // 1. Worker connects and asks for permission mid-turn. const ws1 = createMockWs() handleWebSocketOpen(ws1, session.id) ingestBridgeMessage(session.id, { type: 'control_request', request_id: 'perm-lost-1', request: { subtype: 'can_use_tool', tool_name: 'Bash', input: { command: 'echo hi' }, tool_use_id: 'tu1', }, }) const { getSession } = require('../services/session') expect(getSession(session.id)?.status).toBe('requires_action') // 2. The worker's WS drops (zombie recovery / network blip). handleWebSocketClose(ws1, session.id, 1006, 'network') // 3. The remote user approves while no WS is live — the same publish // POST /web/sessions/:id/control performs. subscriberCount is 0: // the live path drops it. expect(bus.subscriberCount()).toBe(0) publishSessionEvent( session.id, 'permission_response', { type: 'permission_response', approved: true, request_id: 'perm-lost-1', }, 'outbound', ) // 4. The worker reconnects (auto-reconnect, seconds later). const ws2 = createMockWs() handleWebSocketOpen(ws2, session.id) // 5. The approval MUST be re-delivered — otherwise the turn stays // parked on the permission wait forever (the reported stuck). const frames = ws2 .getSentData() .map((d: string) => JSON.parse(d)) .filter((m: { type?: string }) => m.type === 'control_response') expect(frames).toHaveLength(1) expect(frames[0].response.request_id).toBe('perm-lost-1') expect(frames[0].response.response.behavior).toBe('allow') handleWebSocketClose(ws2, session.id, 1000, 'done') }) test('denials (with feedback) replay identically', () => { const session = storeCreateSession({}) const ws1 = createMockWs() handleWebSocketOpen(ws1, session.id) handleWebSocketClose(ws1, session.id, 1006, 'network') publishSessionEvent( session.id, 'permission_response', { type: 'permission_response', approved: false, request_id: 'perm-deny-1', message: 'use the other file', }, 'outbound', ) const ws2 = createMockWs() handleWebSocketOpen(ws2, session.id) const frames = ws2 .getSentData() .map((d: string) => JSON.parse(d)) .filter((m: { type?: string }) => m.type === 'control_response') expect(frames).toHaveLength(1) expect(frames[0].response.response.behavior).toBe('deny') expect(frames[0].response.response.message).toBe('use the other file') handleWebSocketClose(ws2, session.id, 1000, 'done') }) test('the worker\u2019s own inbound control_response echoes are NOT replayed', () => { const session = storeCreateSession({}) ingestBridgeMessage(session.id, { type: 'control_response', response: { subtype: 'success', request_id: 'ctx-1', response: {}, }, }) const ws = createMockWs() handleWebSocketOpen(ws, session.id) const frames = ws .getSentData() .map((d: string) => JSON.parse(d)) .filter((m: { type?: string }) => m.type === 'control_response') expect(frames).toHaveLength(0) handleWebSocketClose(ws, session.id, 1000, 'done') }) test('outbound control_request (interrupt / RPC) stays non-replayable', () => { const session = storeCreateSession({}) const ws1 = createMockWs() handleWebSocketOpen(ws1, session.id) handleWebSocketClose(ws1, session.id, 1006, 'network') // A user prompt and an interrupt both land during the gap. publishSessionEvent( session.id, 'user', { type: 'user', uuid: 'gap-user-1', content: 'hello' }, 'outbound', ) publishSessionEvent( session.id, 'interrupt', { action: 'interrupt' }, 'outbound', ) const ws2 = createMockWs() handleWebSocketOpen(ws2, session.id) const sent = ws2.getSentData().map((d: string) => JSON.parse(d)) // Conversation replay still works… expect( sent.filter((m: { type?: string; uuid?: string }) => m.type === 'user'), ).toHaveLength(1) // …but a point-in-time interrupt must never resurrect on reconnect // (it would abort the post-reconnect turn). expect( sent.filter( (m: { type?: string; request?: { subtype?: string } }) => m.type === 'control_request' && m.request?.subtype === 'interrupt', ), ).toHaveLength(0) handleWebSocketClose(ws2, session.id, 1000, 'done') }) }) describe('closeAllConnections', () => { test('closes all active connections', () => { const ws1 = createMockWs() const ws2 = createMockWs() handleWebSocketOpen(ws1, 's1') handleWebSocketOpen(ws2, 's2') closeAllConnections() // No errors thrown }) test('no-op when no connections', () => { expect(() => closeAllConnections()).not.toThrow() }) }) })