@escapeaihq/client-core 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +27 -2
  2. package/dist/api.d.ts +180 -2
  3. package/dist/api.d.ts.map +1 -1
  4. package/dist/api.js +134 -0
  5. package/dist/api.js.map +1 -1
  6. package/dist/audio.d.ts +1 -1
  7. package/dist/index.d.ts +2 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +2 -0
  10. package/dist/index.js.map +1 -1
  11. package/dist/reactor/entityContext.d.ts +34 -0
  12. package/dist/reactor/entityContext.d.ts.map +1 -0
  13. package/dist/reactor/entityContext.js +119 -0
  14. package/dist/reactor/entityContext.js.map +1 -0
  15. package/dist/reactor/entitySearch.d.ts +71 -0
  16. package/dist/reactor/entitySearch.d.ts.map +1 -0
  17. package/dist/reactor/entitySearch.js +93 -0
  18. package/dist/reactor/entitySearch.js.map +1 -0
  19. package/dist/reactor/heliosCommandDispatcher.d.ts +98 -0
  20. package/dist/reactor/heliosCommandDispatcher.d.ts.map +1 -0
  21. package/dist/reactor/heliosCommandDispatcher.js +181 -0
  22. package/dist/reactor/heliosCommandDispatcher.js.map +1 -0
  23. package/dist/reactor/heliosTools.d.ts +156 -0
  24. package/dist/reactor/heliosTools.d.ts.map +1 -0
  25. package/dist/reactor/heliosTools.js +241 -0
  26. package/dist/reactor/heliosTools.js.map +1 -0
  27. package/dist/reactor/index.d.ts +17 -0
  28. package/dist/reactor/index.d.ts.map +1 -0
  29. package/dist/reactor/index.js +17 -0
  30. package/dist/reactor/index.js.map +1 -0
  31. package/dist/reactor/promptAddonRegistry.d.ts +37 -0
  32. package/dist/reactor/promptAddonRegistry.d.ts.map +1 -0
  33. package/dist/reactor/promptAddonRegistry.js +38 -0
  34. package/dist/reactor/promptAddonRegistry.js.map +1 -0
  35. package/dist/reactor/regenTemplate.d.ts +23 -0
  36. package/dist/reactor/regenTemplate.d.ts.map +1 -0
  37. package/dist/reactor/regenTemplate.js +103 -0
  38. package/dist/reactor/regenTemplate.js.map +1 -0
  39. package/dist/reactor/sceneEntry.d.ts +79 -0
  40. package/dist/reactor/sceneEntry.d.ts.map +1 -0
  41. package/dist/reactor/sceneEntry.js +177 -0
  42. package/dist/reactor/sceneEntry.js.map +1 -0
  43. package/dist/reactor/scenesFromEnrichment.d.ts +67 -0
  44. package/dist/reactor/scenesFromEnrichment.d.ts.map +1 -0
  45. package/dist/reactor/scenesFromEnrichment.js +344 -0
  46. package/dist/reactor/scenesFromEnrichment.js.map +1 -0
  47. package/dist/reactor/seedImageOrchestrator.d.ts +81 -0
  48. package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -0
  49. package/dist/reactor/seedImageOrchestrator.js +79 -0
  50. package/dist/reactor/seedImageOrchestrator.js.map +1 -0
  51. package/dist/reactor/toolPromptAddon.d.ts +44 -0
  52. package/dist/reactor/toolPromptAddon.d.ts.map +1 -0
  53. package/dist/reactor/toolPromptAddon.js +129 -0
  54. package/dist/reactor/toolPromptAddon.js.map +1 -0
  55. package/dist/reactor/toolPromptAddonId.d.ts +10 -0
  56. package/dist/reactor/toolPromptAddonId.d.ts.map +1 -0
  57. package/dist/reactor/toolPromptAddonId.js +10 -0
  58. package/dist/reactor/toolPromptAddonId.js.map +1 -0
  59. package/dist/reactor/types.d.ts +149 -0
  60. package/dist/reactor/types.d.ts.map +1 -0
  61. package/dist/reactor/types.js +2 -0
  62. package/dist/reactor/types.js.map +1 -0
  63. package/dist/reactor/upsamplePrompt.d.ts +30 -0
  64. package/dist/reactor/upsamplePrompt.d.ts.map +1 -0
  65. package/dist/reactor/upsamplePrompt.js +118 -0
  66. package/dist/reactor/upsamplePrompt.js.map +1 -0
  67. package/dist/timeFormat.d.ts +28 -0
  68. package/dist/timeFormat.d.ts.map +1 -0
  69. package/dist/timeFormat.js +48 -0
  70. package/dist/timeFormat.js.map +1 -0
  71. package/dist/visemeGeometry.d.ts +15 -0
  72. package/dist/visemeGeometry.d.ts.map +1 -1
  73. package/dist/visemeGeometry.js +26 -0
  74. package/dist/visemeGeometry.js.map +1 -1
  75. package/dist/visemeScheduler.d.ts +12 -0
  76. package/dist/visemeScheduler.d.ts.map +1 -1
  77. package/dist/visemeScheduler.js +24 -0
  78. package/dist/visemeScheduler.js.map +1 -1
  79. package/dist/websocket.d.ts +51 -3
  80. package/dist/websocket.d.ts.map +1 -1
  81. package/dist/websocket.js +52 -7
  82. package/dist/websocket.js.map +1 -1
  83. package/package.json +1 -1
  84. package/src/__tests__/reactor/__snapshots__/regenTemplate.test.ts.snap +5 -0
  85. package/src/__tests__/reactor/__snapshots__/scenesFromEnrichment.test.ts.snap +34 -0
  86. package/src/__tests__/reactor/api-reactor.test.ts +253 -0
  87. package/src/__tests__/reactor/entityContext.test.ts +237 -0
  88. package/src/__tests__/reactor/entitySearch.test.ts +223 -0
  89. package/src/__tests__/reactor/heliosCommandDispatcher.test.ts +438 -0
  90. package/src/__tests__/reactor/heliosTools.test.ts +164 -0
  91. package/src/__tests__/reactor/promptAddonRegistry.test.ts +40 -0
  92. package/src/__tests__/reactor/regenTemplate.test.ts +156 -0
  93. package/src/__tests__/reactor/sceneEntry.test.ts +342 -0
  94. package/src/__tests__/reactor/scenesFromEnrichment.test.ts +760 -0
  95. package/src/__tests__/reactor/seedImageOrchestrator.test.ts +139 -0
  96. package/src/__tests__/reactor/toolPromptAddon.test.ts +104 -0
  97. package/src/__tests__/reactor/upsamplePrompt.test.ts +245 -0
  98. package/src/__tests__/timeFormat.test.ts +80 -0
  99. package/src/__tests__/tools-wrappers.test.ts +219 -0
  100. package/src/__tests__/websocket.test.ts +278 -0
  101. package/src/api.ts +279 -2
  102. package/src/index.ts +2 -0
  103. package/src/reactor/entityContext.ts +147 -0
  104. package/src/reactor/entitySearch.ts +139 -0
  105. package/src/reactor/heliosCommandDispatcher.ts +293 -0
  106. package/src/reactor/heliosTools.ts +260 -0
  107. package/src/reactor/index.ts +17 -0
  108. package/src/reactor/promptAddonRegistry.ts +52 -0
  109. package/src/reactor/regenTemplate.ts +142 -0
  110. package/src/reactor/sceneEntry.ts +267 -0
  111. package/src/reactor/scenesFromEnrichment.ts +393 -0
  112. package/src/reactor/seedImageOrchestrator.ts +132 -0
  113. package/src/reactor/toolPromptAddon.ts +135 -0
  114. package/src/reactor/toolPromptAddonId.ts +9 -0
  115. package/src/reactor/types.ts +158 -0
  116. package/src/reactor/upsamplePrompt.ts +154 -0
  117. package/src/timeFormat.ts +57 -0
  118. package/src/visemeGeometry.ts +30 -0
  119. package/src/visemeScheduler.ts +25 -0
  120. package/src/websocket.ts +86 -7
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Tests for the §6 additions — `getEntityTimeline` and
3
+ * `createPersonaCharacter`. Both go through `request` → `makeRequest`
4
+ * → fetch (NOT chatRequest — entity-timeline + persona-character live
5
+ * on the tools API, not the chat API). Same global-fetch-mock pattern
6
+ * as `chat-auth.test.ts`.
7
+ */
8
+
9
+ import { ApiClient } from '../api';
10
+
11
+ const TEST_BASE_URL = 'http://test.local';
12
+ const TEST_CHAT_BASE_URL = 'http://test.local/chat';
13
+
14
+ const makeClient = (sessionToken: string = 'test-token') =>
15
+ new ApiClient(TEST_BASE_URL, sessionToken, TEST_CHAT_BASE_URL);
16
+
17
+ const originalFetch = (globalThis as { fetch?: typeof fetch }).fetch;
18
+
19
+ afterEach(() => {
20
+ if (originalFetch === undefined) {
21
+ delete (globalThis as { fetch?: typeof fetch }).fetch;
22
+ } else {
23
+ (globalThis as { fetch?: typeof fetch }).fetch = originalFetch;
24
+ }
25
+ jest.restoreAllMocks();
26
+ });
27
+
28
+ describe('getEntityTimeline', () => {
29
+ const buildResponse = () => ({
30
+ traceId: 'trace-abc',
31
+ results: [
32
+ {
33
+ shotId: 'shot-1',
34
+ videoId: 'video-1',
35
+ t0: 0.0,
36
+ t1: 4.2,
37
+ entityStart: 0.5,
38
+ entityEnd: 3.8,
39
+ caption: 'A wide shot of the protagonist',
40
+ dialog: [{ speaker: 'narrator', text: 'In a galaxy far, far away...' }],
41
+ citation: { videoId: 'video-1', t0: 0.0, t1: 4.2, shotId: 'shot-1' },
42
+ source: { system: 'neo4j', details: { node_id: 'n-1' } },
43
+ },
44
+ ],
45
+ });
46
+
47
+ it('POSTs to /api/v1/tools/entity-timeline on the tools base URL', async () => {
48
+ const fetchMock = jest.fn().mockResolvedValue({
49
+ ok: true,
50
+ status: 200,
51
+ json: async () => buildResponse(),
52
+ });
53
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
54
+
55
+ const result = await makeClient().getEntityTimeline('video-1', 'protagonist');
56
+
57
+ expect(fetchMock).toHaveBeenCalledTimes(1);
58
+ const [url, init] = fetchMock.mock.calls[0];
59
+ // Important: baseURL, NOT chatBaseUrl — entity-timeline lives on
60
+ // the tools API, not the chat API.
61
+ expect(url).toBe(`${TEST_BASE_URL}/api/v1/tools/entity-timeline`);
62
+ expect(init.method).toBe('POST');
63
+ expect(JSON.parse(init.body)).toEqual({
64
+ videoId: 'video-1',
65
+ entity: 'protagonist',
66
+ t0: undefined,
67
+ t1: undefined,
68
+ });
69
+ expect(result.results).toHaveLength(1);
70
+ expect(result.traceId).toBe('trace-abc');
71
+ });
72
+
73
+ it('passes optional t0/t1 bounds through to the request body', async () => {
74
+ const fetchMock = jest.fn().mockResolvedValue({
75
+ ok: true,
76
+ status: 200,
77
+ json: async () => ({ traceId: 't', results: [] }),
78
+ });
79
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
80
+
81
+ await makeClient().getEntityTimeline('video-1', 'protagonist', {
82
+ t0: 10,
83
+ t1: 30,
84
+ });
85
+
86
+ const [, init] = fetchMock.mock.calls[0];
87
+ expect(JSON.parse(init.body)).toEqual({
88
+ videoId: 'video-1',
89
+ entity: 'protagonist',
90
+ t0: 10,
91
+ t1: 30,
92
+ });
93
+ });
94
+
95
+ it('surfaces empty results as a normal response (server returns 200 with []) ', async () => {
96
+ // Server-side, an entity that resolves to "not found" returns 200
97
+ // with `results: []` rather than 404. Verify the client surfaces
98
+ // that to the caller faithfully — important because callers can
99
+ // then render an empty-state without try/catch.
100
+ const fetchMock = jest.fn().mockResolvedValue({
101
+ ok: true,
102
+ status: 200,
103
+ json: async () => ({ traceId: 't', results: [] }),
104
+ });
105
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
106
+
107
+ const result = await makeClient().getEntityTimeline('video-1', 'no-such-entity');
108
+ expect(result.results).toEqual([]);
109
+ });
110
+
111
+ it('propagates non-2xx responses as Errors with the backend detail', async () => {
112
+ const fetchMock = jest.fn().mockResolvedValue({
113
+ ok: false,
114
+ status: 422,
115
+ statusText: 'Unprocessable Entity',
116
+ json: async () => ({ detail: "Parameter 't1' must exceed 't0'" }),
117
+ });
118
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
119
+
120
+ await expect(
121
+ makeClient().getEntityTimeline('video-1', 'x', { t0: 30, t1: 10 }),
122
+ ).rejects.toThrow("Parameter 't1' must exceed 't0'");
123
+ });
124
+ });
125
+
126
+ describe('createPersonaCharacter', () => {
127
+ const buildResponse = () => ({
128
+ character_image_id: 'img-7',
129
+ status: 'pending' as const,
130
+ status_url: '/api/v1/images/img-7',
131
+ traceId: 'trace-xyz',
132
+ });
133
+
134
+ it('POSTs to /api/v1/personas/{id}/character with the body verbatim', async () => {
135
+ const fetchMock = jest.fn().mockResolvedValue({
136
+ ok: true,
137
+ status: 202,
138
+ json: async () => buildResponse(),
139
+ });
140
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
141
+
142
+ const result = await makeClient().createPersonaCharacter('persona-1', {
143
+ source_image_id: 'src-img-3',
144
+ style: 'noir, high contrast',
145
+ });
146
+
147
+ expect(fetchMock).toHaveBeenCalledTimes(1);
148
+ const [url, init] = fetchMock.mock.calls[0];
149
+ expect(url).toBe(`${TEST_BASE_URL}/api/v1/personas/persona-1/character`);
150
+ expect(init.method).toBe('POST');
151
+ expect(JSON.parse(init.body)).toEqual({
152
+ source_image_id: 'src-img-3',
153
+ style: 'noir, high contrast',
154
+ });
155
+ // 202 envelope passes through; the snake_case shape is intentional
156
+ // (mirrors the server) and downstream pollers key off
157
+ // `character_image_id`.
158
+ expect(result.character_image_id).toBe('img-7');
159
+ expect(result.status_url).toBe('/api/v1/images/img-7');
160
+ expect(result.status).toBe('pending');
161
+ });
162
+
163
+ it('URL-encodes the persona ID', async () => {
164
+ // Persona IDs are caller-controlled in some flows (e.g. synthesized
165
+ // personas). Guard against an unencoded slash splitting the path.
166
+ const fetchMock = jest.fn().mockResolvedValue({
167
+ ok: true,
168
+ status: 202,
169
+ json: async () => buildResponse(),
170
+ });
171
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
172
+
173
+ await makeClient().createPersonaCharacter('user/123', {
174
+ video_id: 'v-1',
175
+ entity: 'protagonist',
176
+ });
177
+
178
+ const [url] = fetchMock.mock.calls[0];
179
+ expect(url).toBe(`${TEST_BASE_URL}/api/v1/personas/user%2F123/character`);
180
+ });
181
+
182
+ it('passes the video-source path (entity + timestamp) through', async () => {
183
+ const fetchMock = jest.fn().mockResolvedValue({
184
+ ok: true,
185
+ status: 202,
186
+ json: async () => buildResponse(),
187
+ });
188
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
189
+
190
+ await makeClient().createPersonaCharacter('p-1', {
191
+ video_id: 'v-1',
192
+ entity: 'wizard',
193
+ timestamp: 42.5,
194
+ style: 'cel-shaded',
195
+ });
196
+
197
+ const [, init] = fetchMock.mock.calls[0];
198
+ expect(JSON.parse(init.body)).toEqual({
199
+ video_id: 'v-1',
200
+ entity: 'wizard',
201
+ timestamp: 42.5,
202
+ style: 'cel-shaded',
203
+ });
204
+ });
205
+
206
+ it('propagates non-2xx responses as Errors with the backend detail', async () => {
207
+ const fetchMock = jest.fn().mockResolvedValue({
208
+ ok: false,
209
+ status: 404,
210
+ statusText: 'Not Found',
211
+ json: async () => ({ detail: 'Persona not found: p-1' }),
212
+ });
213
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
214
+
215
+ await expect(
216
+ makeClient().createPersonaCharacter('p-1', { source_image_id: 'i-1' }),
217
+ ).rejects.toThrow('Persona not found: p-1');
218
+ });
219
+ });
@@ -0,0 +1,278 @@
1
+ /**
2
+ * Tests for the §2 additions to ChatWebSocket — `fetchToken` supplier
3
+ * (per-attempt) and `onReconnect` hello-payload hook — plus
4
+ * back-compat coverage for static `authToken` callers.
5
+ *
6
+ * Strategy: replace the global `WebSocket` constructor with a stub
7
+ * that captures the constructed URL, exposes `instances[]`, and lets
8
+ * each test drive open/close events synchronously via
9
+ * `instance.simulateOpen()` / `simulateClose()`. jsdom provides a
10
+ * `WebSocket` but it tries to actually dial — that's why we stub it.
11
+ */
12
+
13
+ import { ChatWebSocket } from '../websocket';
14
+
15
+ interface FakeWebSocket {
16
+ url: string;
17
+ readyState: number;
18
+ binaryType: string;
19
+ sent: string[];
20
+ onopen?: () => void;
21
+ onerror?: (err: Event) => void;
22
+ onmessage?: (event: MessageEvent) => void;
23
+ onclose?: () => void;
24
+ close: () => void;
25
+ send: (data: string | ArrayBuffer | Uint8Array) => void;
26
+ simulateOpen: () => void;
27
+ simulateClose: () => void;
28
+ }
29
+
30
+ const instances: FakeWebSocket[] = [];
31
+
32
+ class StubWebSocket {
33
+ static CONNECTING = 0;
34
+ static OPEN = 1;
35
+ static CLOSING = 2;
36
+ static CLOSED = 3;
37
+
38
+ url: string;
39
+ readyState = StubWebSocket.CONNECTING;
40
+ binaryType = 'blob';
41
+ sent: string[] = [];
42
+ onopen?: () => void;
43
+ onerror?: (err: Event) => void;
44
+ onmessage?: (event: MessageEvent) => void;
45
+ onclose?: () => void;
46
+
47
+ constructor(url: string) {
48
+ this.url = url;
49
+ const ref = this as unknown as FakeWebSocket;
50
+ ref.close = () => {
51
+ this.readyState = StubWebSocket.CLOSED;
52
+ };
53
+ ref.send = (data: string | ArrayBuffer | Uint8Array) => {
54
+ if (typeof data === 'string') {
55
+ this.sent.push(data);
56
+ }
57
+ };
58
+ ref.simulateOpen = () => {
59
+ this.readyState = StubWebSocket.OPEN;
60
+ this.onopen?.();
61
+ };
62
+ ref.simulateClose = () => {
63
+ this.readyState = StubWebSocket.CLOSED;
64
+ this.onclose?.();
65
+ };
66
+ instances.push(ref);
67
+ }
68
+ }
69
+
70
+ const originalWebSocket = globalThis.WebSocket;
71
+
72
+ beforeEach(() => {
73
+ instances.length = 0;
74
+ (globalThis as unknown as { WebSocket: typeof StubWebSocket }).WebSocket =
75
+ StubWebSocket;
76
+ });
77
+
78
+ afterEach(() => {
79
+ // Reconnect tests opt into fake timers per-test; restore here so a
80
+ // failure mid-test doesn't bleed timer state into the next case.
81
+ jest.useRealTimers();
82
+ (globalThis as { WebSocket?: typeof WebSocket }).WebSocket = originalWebSocket;
83
+ });
84
+
85
+ /**
86
+ * Flush enough microtask ticks for an awaited mocked promise + the
87
+ * resolved-then-chained constructor call to settle. Two ticks is the
88
+ * empirical minimum for `await this._resolveToken()` + the awaited
89
+ * `mockResolvedValue` to land before our test inspects `instances`.
90
+ */
91
+ const flushMicrotasks = async (): Promise<void> => {
92
+ await Promise.resolve();
93
+ await Promise.resolve();
94
+ };
95
+
96
+ const lastSocket = (): FakeWebSocket => {
97
+ const last = instances[instances.length - 1];
98
+ if (!last) throw new Error('No WebSocket has been constructed yet');
99
+ return last;
100
+ };
101
+
102
+ describe('ChatWebSocket — fetchToken supplier', () => {
103
+ it('invokes fetchToken on initial connect and uses its result in the URL', async () => {
104
+ const fetchToken = jest.fn().mockResolvedValue('ephemeral-aaa');
105
+ const ws = new ChatWebSocket({
106
+ url: 'ws://test/chat',
107
+ fetchToken,
108
+ });
109
+
110
+ const connectPromise = ws.connect();
111
+ // Drain the awaited fetchToken microtasks before we poke the stub.
112
+ await flushMicrotasks();
113
+ lastSocket().simulateOpen();
114
+ await connectPromise;
115
+
116
+ expect(fetchToken).toHaveBeenCalledTimes(1);
117
+ expect(lastSocket().url).toBe('ws://test/chat?token=ephemeral-aaa');
118
+ });
119
+
120
+ it('re-invokes fetchToken on every reconnect (proves no stale token)', async () => {
121
+ const fetchToken = jest
122
+ .fn()
123
+ .mockResolvedValueOnce('token-1')
124
+ .mockResolvedValueOnce('token-2');
125
+
126
+ const ws = new ChatWebSocket({
127
+ url: 'ws://test/chat',
128
+ fetchToken,
129
+ });
130
+
131
+ const firstConnect = ws.connect();
132
+ await flushMicrotasks();
133
+ lastSocket().simulateOpen();
134
+ await firstConnect;
135
+ expect(lastSocket().url).toBe('ws://test/chat?token=token-1');
136
+
137
+ // Switch to fake timers only AFTER the initial connect resolves —
138
+ // modern fake timers replace `queueMicrotask`, which would starve
139
+ // the awaited `fetchToken` during the initial connect.
140
+ jest.useFakeTimers();
141
+ lastSocket().simulateClose();
142
+ // 1000ms = reconnectDelay * 2^0. `advanceTimersByTimeAsync` drains
143
+ // microtasks between ticks so the awaited `_resolveToken()` inside
144
+ // the rescheduled `_connect(true)` settles before we look.
145
+ await jest.advanceTimersByTimeAsync(1000);
146
+ lastSocket().simulateOpen();
147
+
148
+ expect(fetchToken).toHaveBeenCalledTimes(2);
149
+ expect(lastSocket().url).toBe('ws://test/chat?token=token-2');
150
+ });
151
+
152
+ it('takes precedence over authToken when both are provided', async () => {
153
+ const fetchToken = jest.fn().mockResolvedValue('from-supplier');
154
+ const ws = new ChatWebSocket({
155
+ url: 'ws://test/chat',
156
+ authToken: 'from-static',
157
+ fetchToken,
158
+ });
159
+
160
+ const connectPromise = ws.connect();
161
+ await flushMicrotasks();
162
+ lastSocket().simulateOpen();
163
+ await connectPromise;
164
+
165
+ expect(lastSocket().url).toBe('ws://test/chat?token=from-supplier');
166
+ });
167
+
168
+ it('propagates fetchToken rejection on the initial connect', async () => {
169
+ const fetchToken = jest.fn().mockRejectedValue(new Error('token boom'));
170
+ const ws = new ChatWebSocket({
171
+ url: 'ws://test/chat',
172
+ fetchToken,
173
+ });
174
+
175
+ await expect(ws.connect()).rejects.toThrow('token boom');
176
+ expect(instances).toHaveLength(0);
177
+ });
178
+ });
179
+
180
+ describe('ChatWebSocket — onReconnect hello payload', () => {
181
+ const helloPayload = {
182
+ action: 'hello' as const,
183
+ sessionId: 'sess-1',
184
+ mode: 'hybrid' as const,
185
+ personaId: 'p-1',
186
+ };
187
+
188
+ it('sends the onReconnect payload after a successful reconnect', async () => {
189
+ const onReconnect = jest.fn().mockReturnValue(helloPayload);
190
+ const onReconnected = jest.fn();
191
+
192
+ const ws = new ChatWebSocket({
193
+ url: 'ws://test/chat',
194
+ fetchToken: jest.fn().mockResolvedValue('tok'),
195
+ onReconnect,
196
+ onReconnected,
197
+ });
198
+
199
+ const first = ws.connect();
200
+ await flushMicrotasks();
201
+ lastSocket().simulateOpen();
202
+ await first;
203
+
204
+ jest.useFakeTimers();
205
+ lastSocket().simulateClose();
206
+ await jest.advanceTimersByTimeAsync(1000);
207
+ lastSocket().simulateOpen();
208
+
209
+ expect(onReconnect).toHaveBeenCalledTimes(1);
210
+ expect(lastSocket().sent).toEqual([JSON.stringify(helloPayload)]);
211
+ expect(onReconnected).toHaveBeenCalledTimes(1);
212
+ });
213
+
214
+ it('skips the send when onReconnect returns null', async () => {
215
+ const onReconnect = jest.fn().mockReturnValue(null);
216
+ const ws = new ChatWebSocket({
217
+ url: 'ws://test/chat',
218
+ fetchToken: jest.fn().mockResolvedValue('tok'),
219
+ onReconnect,
220
+ });
221
+
222
+ const first = ws.connect();
223
+ await flushMicrotasks();
224
+ lastSocket().simulateOpen();
225
+ await first;
226
+
227
+ jest.useFakeTimers();
228
+ lastSocket().simulateClose();
229
+ await jest.advanceTimersByTimeAsync(1000);
230
+ lastSocket().simulateOpen();
231
+
232
+ expect(onReconnect).toHaveBeenCalledTimes(1);
233
+ expect(lastSocket().sent).toEqual([]);
234
+ });
235
+
236
+ it('does NOT fire on the initial connect (only on reconnects)', async () => {
237
+ const onReconnect = jest.fn();
238
+ const ws = new ChatWebSocket({
239
+ url: 'ws://test/chat',
240
+ authToken: 'tok',
241
+ onReconnect,
242
+ });
243
+
244
+ const connectPromise = ws.connect();
245
+ await flushMicrotasks();
246
+ lastSocket().simulateOpen();
247
+ await connectPromise;
248
+
249
+ expect(onReconnect).not.toHaveBeenCalled();
250
+ });
251
+ });
252
+
253
+ describe('ChatWebSocket — back-compat with static authToken', () => {
254
+ it('builds the URL from authToken when fetchToken is absent', async () => {
255
+ const ws = new ChatWebSocket({
256
+ url: 'ws://test/chat',
257
+ authToken: 'legacy-jwt',
258
+ });
259
+
260
+ const connectPromise = ws.connect();
261
+ await flushMicrotasks();
262
+ lastSocket().simulateOpen();
263
+ await connectPromise;
264
+
265
+ expect(lastSocket().url).toBe('ws://test/chat?token=legacy-jwt');
266
+ });
267
+
268
+ it('omits the ?token= query when neither authToken nor fetchToken is set', async () => {
269
+ const ws = new ChatWebSocket({ url: 'ws://test/chat' });
270
+
271
+ const connectPromise = ws.connect();
272
+ await flushMicrotasks();
273
+ lastSocket().simulateOpen();
274
+ await connectPromise;
275
+
276
+ expect(lastSocket().url).toBe('ws://test/chat');
277
+ });
278
+ });