@escapeaihq/client-core 0.6.0 → 0.6.1

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.
@@ -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
+ });
package/src/api.ts CHANGED
@@ -364,6 +364,34 @@ export interface GenerateCharacterResponse {
364
364
  statusUrl: string;
365
365
  }
366
366
 
367
+ /** Request body for `POST /api/v1/personas/{personaId}/character` —
368
+ * generate AND link a rest-pose character in one shot. The server-side
369
+ * `model_validator` requires **exactly one** of `source_image_id` or
370
+ * `video_id`; `entity` / `timestamp` are only valid alongside
371
+ * `video_id`. Mirrors `api/personas/character.py::CreateCharacterRequest`. */
372
+ export interface CreatePersonaCharacterRequest {
373
+ source_image_id?: string;
374
+ video_id?: string;
375
+ entity?: string;
376
+ timestamp?: number;
377
+ style?: string;
378
+ }
379
+
380
+ /** 202 Accepted envelope for `POST /api/v1/personas/{personaId}/character`.
381
+ *
382
+ * Snake-case to mirror the server's `CreateCharacterResponse` model —
383
+ * the `traceId` field stays camel-case because cross-endpoint trace
384
+ * correlation already uses that key everywhere else. The persona's
385
+ * `character_image_id` is set upfront on the persona row, so the
386
+ * persona detail page can render the link immediately and the caller
387
+ * just polls `status_url` for completion. */
388
+ export interface CreatePersonaCharacterResponse {
389
+ character_image_id: string;
390
+ status: 'pending';
391
+ status_url: string;
392
+ traceId: string;
393
+ }
394
+
367
395
  export interface CreatePersonaRequest {
368
396
  name: string;
369
397
  description?: string | null;
@@ -549,6 +577,30 @@ export interface DialogSearchResponse {
549
577
  results: DialogSearchResult[];
550
578
  }
551
579
 
580
+ /** One shot in the entity-timeline result list. `entityStart`/`entityEnd`
581
+ * are the entity-tracking span within the shot when known. Mirrors
582
+ * `api/tools/schemas.py::TimelineEntry`. */
583
+ export interface EntityTimelineEntry {
584
+ shotId: string;
585
+ videoId: string;
586
+ t0: number;
587
+ t1: number;
588
+ entityStart?: number | null;
589
+ entityEnd?: number | null;
590
+ caption?: string | null;
591
+ /** Dialog lines spoken by (or near) the entity in this shot.
592
+ * Backend returns an opaque dict per line — leave loose here rather
593
+ * than tying client-core to a transcript schema that may evolve. */
594
+ dialog?: Array<Record<string, unknown>> | null;
595
+ citation: Citation;
596
+ source: SourceMetadata;
597
+ }
598
+
599
+ export interface EntityTimelineResponse {
600
+ traceId: string;
601
+ results: EntityTimelineEntry[];
602
+ }
603
+
552
604
  // ---------------------------------------------------------------------------
553
605
  // Narrative / Enrichment types
554
606
  // ---------------------------------------------------------------------------
@@ -1141,6 +1193,35 @@ export class ApiClient {
1141
1193
  );
1142
1194
  }
1143
1195
 
1196
+ /**
1197
+ * Generate AND link a rest-pose character image for a persona in one
1198
+ * shot — the alternative to `generateCharacter` (which only generates;
1199
+ * the caller assigns later via PATCH).
1200
+ *
1201
+ * Returns 202 with `character_image_id` (stable for the lifetime of
1202
+ * the row) and `status_url` (== `/api/v1/images/{character_image_id}`).
1203
+ * Poll the status URL via `getImage()` / `pollImageUntilDone()` until
1204
+ * `status` flips off `'pending'`. The persona's `character_image_id`
1205
+ * is set upfront so the persona detail page can show the linkage
1206
+ * immediately and just renders the image once the poll resolves.
1207
+ *
1208
+ * The server's `model_validator` enforces "exactly one source" —
1209
+ * provide either `source_image_id` OR `video_id` (with optional
1210
+ * `entity`/`timestamp`), never both, never neither.
1211
+ */
1212
+ async createPersonaCharacter(
1213
+ personaId: string,
1214
+ body: CreatePersonaCharacterRequest,
1215
+ ): Promise<CreatePersonaCharacterResponse> {
1216
+ return this.request<CreatePersonaCharacterResponse>(
1217
+ `/api/v1/personas/${encodeURIComponent(personaId)}/character`,
1218
+ {
1219
+ method: 'POST',
1220
+ body: JSON.stringify(body),
1221
+ },
1222
+ );
1223
+ }
1224
+
1144
1225
  /**
1145
1226
  * Extract a raw video frame at an entity's location or a specific
1146
1227
  * timestamp. Synchronous (no polling) — the path is ffmpeg-only with
@@ -1360,6 +1441,34 @@ export class ApiClient {
1360
1441
  });
1361
1442
  }
1362
1443
 
1444
+ /**
1445
+ * Return a time-ordered list of shots where an entity appears.
1446
+ * Optional `t0`/`t1` bounds (seconds) narrow the query window —
1447
+ * the server validates `t1 > t0` when both are provided.
1448
+ *
1449
+ * Backed by `POST /api/v1/tools/entity-timeline`. Returns an empty
1450
+ * `results` array (not a 404) when the entity isn't found after
1451
+ * graph resolution — callers can treat "no results" uniformly.
1452
+ */
1453
+ async getEntityTimeline(
1454
+ videoId: string,
1455
+ entity: string,
1456
+ bounds?: { t0?: number; t1?: number },
1457
+ ): Promise<EntityTimelineResponse> {
1458
+ return this.request<EntityTimelineResponse>(
1459
+ '/api/v1/tools/entity-timeline',
1460
+ {
1461
+ method: 'POST',
1462
+ body: JSON.stringify({
1463
+ videoId,
1464
+ entity,
1465
+ t0: bounds?.t0,
1466
+ t1: bounds?.t1,
1467
+ }),
1468
+ },
1469
+ );
1470
+ }
1471
+
1363
1472
  // ==================== Graph Editor API Methods ====================
1364
1473
 
1365
1474
  async getVideoGraph(videoId: string): Promise<VideoGraphResponse> {
@@ -7,6 +7,36 @@
7
7
  * without rendering a React tree.
8
8
  */
9
9
 
10
+ import type { VisemeSymbol } from './visemeScheduler';
11
+
12
+ /**
13
+ * Fallback SVG path table used by mouth renderers BEFORE a persona's
14
+ * viseme bundle has finished loading (and as a backstop for personas
15
+ * that don't ship a custom bundle). Each value is the `d` attribute
16
+ * for the `<path>` driven by the viseme switch.
17
+ *
18
+ * Coordinates assume a 200×100 viewBox centered horizontally — the
19
+ * same canvas the Web-App `seer-character-face.vue` and seer-agent
20
+ * `CharacterFace.tsx` renderers use. Promoted from
21
+ * `seer-character-face.vue` so both renderers can share the source
22
+ * of truth; this is the §7 cleanup from
23
+ * `specs/2026-05-14-client-core-cleanup-plan.md`.
24
+ */
25
+ export const DEFAULT_MOUTH_PATHS: Record<VisemeSymbol, string> = {
26
+ rest: 'M 40,50 C 60,50 140,50 160,50 C 160,52 140,54 100,54 C 60,54 40,52 40,50 C 40,50 40,50 40,50',
27
+ aei: 'M 40,38 C 60,32 140,32 160,38 C 160,56 140,72 100,74 C 60,72 40,56 40,38 C 40,38 40,38 40,38',
28
+ o: 'M 62,34 C 78,28 122,28 138,34 C 142,50 138,70 100,72 C 62,70 58,50 62,34 C 62,34 62,34 62,34',
29
+ ee: 'M 28,44 C 52,40 148,40 172,44 C 172,52 148,58 100,58 C 52,58 28,52 28,44 C 28,44 28,44 28,44',
30
+ bmp: 'M 48,48 C 68,46 132,46 152,48 C 152,52 132,54 100,54 C 68,54 48,52 48,48 C 48,48 48,48 48,48',
31
+ fv: 'M 42,44 C 62,42 138,42 158,44 C 158,52 138,58 100,58 C 62,58 42,52 42,44 C 42,44 42,44 42,44',
32
+ l: 'M 42,40 C 62,36 138,36 158,40 C 158,54 138,64 100,66 C 62,64 42,54 42,40 C 42,40 42,40 42,40',
33
+ r: 'M 52,38 C 72,34 128,34 148,38 C 148,52 128,64 100,66 C 72,64 52,52 52,38 C 52,38 52,38 52,38',
34
+ th: 'M 42,42 C 62,38 138,38 158,42 C 158,52 138,60 100,62 C 62,60 42,52 42,42 C 42,42 42,42 42,42',
35
+ qw: 'M 58,36 C 76,30 124,30 142,36 C 146,52 138,68 100,70 C 62,68 54,52 58,36 C 58,36 58,36 58,36',
36
+ cdgknstxyz:
37
+ 'M 44,46 C 64,43 136,43 156,46 C 156,53 136,57 100,57 C 64,57 44,53 44,46 C 44,46 44,46 44,46',
38
+ };
39
+
10
40
  export interface Point {
11
41
  x: number;
12
42
  y: number;
@@ -34,6 +34,31 @@ const VALID_VISEMES: ReadonlySet<string> = new Set<string>([
34
34
  'cdgknstxyz',
35
35
  ]);
36
36
 
37
+ /**
38
+ * Map VisemeSymbol → 0-14 integer index expected by the PlayCanvas
39
+ * iframe TTS bridge (Web-App: `utils/seer/iframeMessaging.ts`).
40
+ *
41
+ * The indices are intentionally sparse (gaps at 4, 6, 7, 11): they
42
+ * match the PlayCanvas mouth animation channel constants and **must
43
+ * not be re-densified** without updating the engine side. Promoted to
44
+ * client-core so the next renderer (or a future seer-agent PlayCanvas
45
+ * iframe consumer) inherits the same mapping — §8 in
46
+ * `specs/2026-05-14-client-core-cleanup-plan.md`.
47
+ */
48
+ export const iframeVisemeIndexMap: Readonly<Record<VisemeSymbol, number>> = {
49
+ rest: 0,
50
+ bmp: 1,
51
+ fv: 2,
52
+ th: 3,
53
+ cdgknstxyz: 5,
54
+ l: 8,
55
+ r: 9,
56
+ aei: 10,
57
+ ee: 12,
58
+ o: 13,
59
+ qw: 14,
60
+ };
61
+
37
62
  interface ScheduledViseme {
38
63
  startTime: number; // Absolute AudioContext.currentTime
39
64
  endTime: number;
package/src/websocket.ts CHANGED
@@ -207,12 +207,45 @@ export type BinaryHandler = (data: ArrayBuffer) => void;
207
207
 
208
208
  export interface ChatWebSocketOptions {
209
209
  url: string;
210
+ /**
211
+ * Static token baked into the URL at construction time. Reused on
212
+ * every reconnect attempt — fine for tokens that don't expire, but
213
+ * stale for ephemeral tokens (e.g. seer-agent's 10-min `ws-token`).
214
+ * Prefer {@link ChatWebSocketOptions.fetchToken} for ephemeral tokens.
215
+ */
210
216
  authToken?: string;
217
+ /**
218
+ * Async supplier invoked once per connect attempt (initial + every
219
+ * reconnect). Takes precedence over `authToken` when both are
220
+ * provided. Typical wiring:
221
+ *
222
+ * ```ts
223
+ * fetchToken: () => apiClient.getChatWsToken().then(r => r.wsToken),
224
+ * ```
225
+ *
226
+ * If this throws on a reconnect attempt, the failure counts against
227
+ * `maxReconnectAttempts` and the loop schedules another attempt with
228
+ * the existing backoff. On the initial connect the rejection
229
+ * propagates to the caller of `connect()`.
230
+ */
231
+ fetchToken?: () => Promise<string>;
211
232
  onOpen?: () => void;
212
233
  onClose?: () => void;
213
234
  onError?: (error: Event) => void;
214
235
  onReconnecting?: (attempt: number) => void;
215
236
  onReconnected?: () => void;
237
+ /**
238
+ * Called after a successful reconnect, immediately before
239
+ * `onReconnected`. If the caller returns a {@link HelloPayload}, it
240
+ * is serialized and sent so the server can restore voice/session
241
+ * state; returning `null` skips the send (e.g. text-only sessions
242
+ * that don't need a hello).
243
+ *
244
+ * Synchronous on purpose — the payload is built from in-memory
245
+ * state, and we want to send it on the same tick the socket opens
246
+ * to avoid racing other queued messages.
247
+ */
248
+ onReconnect?: () => HelloPayload | null;
216
249
  }
217
250
 
218
251
  export class ChatWebSocket {
@@ -221,11 +254,13 @@ export class ChatWebSocket {
221
254
  private binaryHandlers: BinaryHandler[] = [];
222
255
  private url: string;
223
256
  private authToken?: string;
257
+ private fetchToken?: () => Promise<string>;
224
258
  private onOpenCallback?: () => void;
225
259
  private onCloseCallback?: () => void;
226
260
  private onErrorCallback?: (error: Event) => void;
227
261
  private onReconnectingCallback?: (attempt: number) => void;
228
262
  private onReconnectedCallback?: () => void;
263
+ private onReconnectCallback?: () => HelloPayload | null;
229
264
 
230
265
  // Reconnection state
231
266
  private maxReconnectAttempts = 5;
@@ -237,11 +272,13 @@ export class ChatWebSocket {
237
272
  constructor(options: ChatWebSocketOptions) {
238
273
  this.url = options.url;
239
274
  this.authToken = options.authToken;
275
+ this.fetchToken = options.fetchToken;
240
276
  this.onOpenCallback = options.onOpen;
241
277
  this.onCloseCallback = options.onClose;
242
278
  this.onErrorCallback = options.onError;
243
279
  this.onReconnectingCallback = options.onReconnecting;
244
280
  this.onReconnectedCallback = options.onReconnected;
281
+ this.onReconnectCallback = options.onReconnect;
245
282
  }
246
283
 
247
284
  /**
@@ -252,15 +289,43 @@ export class ChatWebSocket {
252
289
  return this._connect(false);
253
290
  }
254
291
 
292
+ /**
293
+ * Resolve the auth token for the next connect attempt. `fetchToken`
294
+ * wins over `authToken` when both are set — the supplier is the
295
+ * forward-looking path; `authToken` is back-compat.
296
+ */
297
+ private async _resolveToken(): Promise<string | undefined> {
298
+ if (this.fetchToken) {
299
+ return await this.fetchToken();
300
+ }
301
+ return this.authToken;
302
+ }
303
+
255
304
  /**
256
305
  * Internal connect method. When isReconnect is true, calls
257
- * onReconnected instead of onOpen on success.
306
+ * onReconnected (and dispatches any onReconnect hello payload)
307
+ * instead of onOpen on success.
258
308
  */
259
- private _connect(isReconnect: boolean): Promise<void> {
309
+ private async _connect(isReconnect: boolean): Promise<void> {
310
+ let token: string | undefined;
311
+ try {
312
+ token = await this._resolveToken();
313
+ } catch (err) {
314
+ // Token fetch failed before any socket was opened, so onclose
315
+ // can't fire to drive the next reconnect attempt. On a reconnect
316
+ // pass we explicitly schedule another attempt so transient
317
+ // token-fetch failures (network blip, brief 502 on the token
318
+ // endpoint) don't kill the loop. On the initial connect we let
319
+ // the caller see the failure.
320
+ if (isReconnect && !this.intentionalDisconnect) {
321
+ this._attemptReconnect();
322
+ }
323
+ throw err;
324
+ }
325
+
260
326
  return new Promise((resolve, reject) => {
261
- // Append auth token to URL if provided
262
- const urlWithAuth = this.authToken
263
- ? `${this.url}?token=${encodeURIComponent(this.authToken)}`
327
+ const urlWithAuth = token
328
+ ? `${this.url}?token=${encodeURIComponent(token)}`
264
329
  : this.url;
265
330
 
266
331
  this.ws = new WebSocket(urlWithAuth);
@@ -270,6 +335,14 @@ export class ChatWebSocket {
270
335
  console.log('WebSocket connected');
271
336
  this.reconnectAttempts = 0;
272
337
  if (isReconnect) {
338
+ // Re-send hello BEFORE onReconnected so the caller observes
339
+ // a fully restored session, not a half-open one. Skip when
340
+ // the caller returns null (text-only sessions don't need a
341
+ // hello to resume).
342
+ const helloPayload = this.onReconnectCallback?.();
343
+ if (helloPayload && this.ws) {
344
+ this.ws.send(JSON.stringify(helloPayload));
345
+ }
273
346
  this.onReconnectedCallback?.();
274
347
  }
275
348
  this.onOpenCallback?.();
@@ -476,17 +549,23 @@ export class ChatWebSocket {
476
549
  }
477
550
 
478
551
  /**
479
- * Example usage:
552
+ * Example usage with an ephemeral token + voice-session restore:
480
553
  *
481
554
  * ```typescript
482
555
  * const ws = new ChatWebSocket({
483
556
  * url: 'ws://localhost:8080/api/chat/ws',
484
- * authToken: 'Bearer xyz123',
557
+ * fetchToken: () => apiClient.getChatWsToken().then((r) => r.wsToken),
558
+ * onReconnect: () => (voiceModeActive ? buildHelloPayload(...) : null),
485
559
  * onOpen: () => console.log('Connected!'),
486
560
  * onClose: () => console.log('Disconnected'),
487
561
  * onError: (error) => console.error('Error:', error),
488
562
  * });
489
563
  *
564
+ * // Back-compat: static-token sessions still work without `fetchToken`.
565
+ * const wsLegacy = new ChatWebSocket({
566
+ * url: 'ws://localhost:8080/api/chat/ws',
567
+ * authToken: 'Bearer xyz123',
568
+ *
490
569
  * await ws.connect();
491
570
  *
492
571
  * ws.onMessage((message) => {