@escapeaihq/client-core 0.4.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 (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -0
  3. package/dist/api.d.ts +836 -0
  4. package/dist/api.d.ts.map +1 -0
  5. package/dist/api.js +781 -0
  6. package/dist/api.js.map +1 -0
  7. package/dist/audio.d.ts +278 -0
  8. package/dist/audio.d.ts.map +1 -0
  9. package/dist/audio.js +758 -0
  10. package/dist/audio.js.map +1 -0
  11. package/dist/audioProtocol.d.ts +101 -0
  12. package/dist/audioProtocol.d.ts.map +1 -0
  13. package/dist/audioProtocol.js +62 -0
  14. package/dist/audioProtocol.js.map +1 -0
  15. package/dist/index.d.ts +28 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +28 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/visemeGeometry.d.ts +198 -0
  20. package/dist/visemeGeometry.d.ts.map +1 -0
  21. package/dist/visemeGeometry.js +297 -0
  22. package/dist/visemeGeometry.js.map +1 -0
  23. package/dist/visemeScheduler.d.ts +28 -0
  24. package/dist/visemeScheduler.d.ts.map +1 -0
  25. package/dist/visemeScheduler.js +94 -0
  26. package/dist/visemeScheduler.js.map +1 -0
  27. package/dist/websocket.d.ts +196 -0
  28. package/dist/websocket.d.ts.map +1 -0
  29. package/dist/websocket.js +250 -0
  30. package/dist/websocket.js.map +1 -0
  31. package/package.json +40 -0
  32. package/src/__tests__/api-pollers.test.ts +524 -0
  33. package/src/__tests__/audio.test.ts +714 -0
  34. package/src/__tests__/visemeGeometry.test.ts +465 -0
  35. package/src/__tests__/visemeScheduler.test.ts +256 -0
  36. package/src/api.ts +1577 -0
  37. package/src/audio.ts +934 -0
  38. package/src/audioProtocol.ts +163 -0
  39. package/src/index.ts +28 -0
  40. package/src/visemeGeometry.ts +353 -0
  41. package/src/visemeScheduler.ts +133 -0
  42. package/src/websocket.ts +385 -0
@@ -0,0 +1,714 @@
1
+ /**
2
+ * Tests for the audio pipeline behaviors ported from web-app:
3
+ * - AudioFramePlayer.clearQueue mutes gain and stops active sources cleanly
4
+ * - AudioFramePlayer routes through gainNode for clean barge-in
5
+ * - AudioSessionClient uses audioPlayer.getPlaybackTime() for live position
6
+ * - AudioPipeline detects sentence boundaries when re-scheduling visemes
7
+ */
8
+
9
+ import { TAG_AI, encodeAudioFrame, FRAME_BYTES } from '../audioProtocol';
10
+
11
+ // ─────────────────────────────────────────────────────────────
12
+ // Minimal AudioContext mock — covers the surface AudioFramePlayer uses
13
+ // ─────────────────────────────────────────────────────────────
14
+
15
+ interface MockGain {
16
+ gain: { setValueAtTime: jest.Mock; value: number };
17
+ connect: jest.Mock;
18
+ }
19
+
20
+ interface MockSource {
21
+ buffer: AudioBuffer | null;
22
+ connect: jest.Mock;
23
+ start: jest.Mock;
24
+ stop: jest.Mock;
25
+ onended: (() => void) | null;
26
+ _started: boolean;
27
+ _stopped: boolean;
28
+ }
29
+
30
+ interface MockContext {
31
+ sampleRate: number;
32
+ state: 'running' | 'suspended' | 'closed';
33
+ destination: object;
34
+ currentTime: number;
35
+ createGain: jest.Mock<MockGain, []>;
36
+ createBuffer: jest.Mock;
37
+ createBufferSource: jest.Mock<MockSource, []>;
38
+ resume: jest.Mock;
39
+ close: jest.Mock;
40
+ _setTime: (t: number) => void;
41
+ _gains: MockGain[];
42
+ _sources: MockSource[];
43
+ }
44
+
45
+ function createMockContext(): MockContext {
46
+ let time = 0;
47
+ const ctx: Partial<MockContext> = {
48
+ sampleRate: 16000,
49
+ state: 'running',
50
+ destination: { __isDestination: true },
51
+ };
52
+ Object.defineProperty(ctx, 'currentTime', { get: () => time });
53
+ ctx._setTime = (t: number) => {
54
+ time = t;
55
+ };
56
+ ctx._gains = [];
57
+ ctx._sources = [];
58
+
59
+ ctx.createGain = jest.fn(() => {
60
+ const g: MockGain = {
61
+ gain: { setValueAtTime: jest.fn(), value: 1 },
62
+ connect: jest.fn(),
63
+ };
64
+ ctx._gains!.push(g);
65
+ return g;
66
+ });
67
+ ctx.createBuffer = jest.fn(() => ({
68
+ copyToChannel: jest.fn(),
69
+ duration: 0.02,
70
+ } as unknown as AudioBuffer));
71
+ ctx.createBufferSource = jest.fn(() => {
72
+ const s: MockSource = {
73
+ buffer: null,
74
+ connect: jest.fn(),
75
+ start: jest.fn(function (this: MockSource) {
76
+ this._started = true;
77
+ }),
78
+ stop: jest.fn(function (this: MockSource) {
79
+ if (this._stopped) throw new Error('already stopped');
80
+ this._stopped = true;
81
+ }),
82
+ onended: null,
83
+ _started: false,
84
+ _stopped: false,
85
+ };
86
+ ctx._sources!.push(s);
87
+ return s;
88
+ });
89
+ ctx.resume = jest.fn(async () => {});
90
+ ctx.close = jest.fn(async () => {});
91
+
92
+ return ctx as MockContext;
93
+ }
94
+
95
+ // Install AudioContext globally before importing anything that uses it
96
+ let activeMock: MockContext;
97
+ beforeEach(() => {
98
+ activeMock = createMockContext();
99
+ (globalThis as unknown as { AudioContext: jest.Mock }).AudioContext = jest.fn(
100
+ () => activeMock,
101
+ ) as unknown as jest.Mock;
102
+ });
103
+
104
+ function buildAiFrame(): ArrayBuffer {
105
+ // Tag + 640 zero bytes (one PCM16 frame at 320 samples)
106
+ const samples = new Int16Array(FRAME_BYTES / 2);
107
+ const tagged = encodeAudioFrame(TAG_AI, samples);
108
+ return tagged.buffer.slice(
109
+ tagged.byteOffset,
110
+ tagged.byteOffset + tagged.byteLength,
111
+ ) as ArrayBuffer;
112
+ }
113
+
114
+ // ─────────────────────────────────────────────────────────────
115
+ // AudioFramePlayer
116
+ // ─────────────────────────────────────────────────────────────
117
+
118
+ describe('AudioFramePlayer', () => {
119
+ it('routes playback through a gain node, not directly to destination', async () => {
120
+ const { AudioFramePlayer } = await import('../audio');
121
+ const player = new AudioFramePlayer();
122
+
123
+ player.playFrame(buildAiFrame());
124
+
125
+ // First gain is the player's master gain; constructor connects it to destination
126
+ const masterGain = activeMock._gains[0];
127
+ expect(masterGain.connect).toHaveBeenCalledWith(activeMock.destination);
128
+
129
+ // Source connects to the gain, not destination
130
+ const source = activeMock._sources[0];
131
+ expect(source.connect).toHaveBeenCalledWith(masterGain);
132
+ expect(source.connect).not.toHaveBeenCalledWith(activeMock.destination);
133
+ });
134
+
135
+ it('clearQueue stops all in-flight sources to silence playback', async () => {
136
+ const { AudioFramePlayer } = await import('../audio');
137
+ const player = new AudioFramePlayer();
138
+
139
+ player.playFrame(buildAiFrame());
140
+ player.playFrame(buildAiFrame());
141
+ expect(activeMock._sources).toHaveLength(2);
142
+ expect(activeMock._sources.every((s) => s._started)).toBe(true);
143
+
144
+ player.clearQueue();
145
+
146
+ // Silence comes from stop()ing the sources. (An earlier version also
147
+ // tried to mute the gain node, but both setValueAtTime events at the
148
+ // same currentTime cancelled out, so we no longer rely on it.)
149
+ expect(activeMock._sources.every((s) => s._stopped)).toBe(true);
150
+ });
151
+
152
+ it('clearQueue swallows stop() errors from already-ended sources', async () => {
153
+ const { AudioFramePlayer } = await import('../audio');
154
+ const player = new AudioFramePlayer();
155
+ player.playFrame(buildAiFrame());
156
+
157
+ // Pre-stop the source to force throw on the second stop attempt
158
+ const src = activeMock._sources[0];
159
+ src.stop();
160
+
161
+ expect(() => player.clearQueue()).not.toThrow();
162
+ });
163
+
164
+ it('removes finished sources via onended', async () => {
165
+ const { AudioFramePlayer } = await import('../audio');
166
+ const player = new AudioFramePlayer();
167
+ player.playFrame(buildAiFrame());
168
+
169
+ const src = activeMock._sources[0];
170
+ expect(src.onended).toBeDefined();
171
+ src.onended!();
172
+
173
+ // After onended fires, clearQueue should not call stop on it
174
+ player.clearQueue();
175
+ // src.stop was never called by clearQueue (already removed from set)
176
+ expect(src.stop).not.toHaveBeenCalled();
177
+ });
178
+ });
179
+
180
+ // ─────────────────────────────────────────────────────────────
181
+ // AudioSessionClient — playback position uses player time
182
+ // ─────────────────────────────────────────────────────────────
183
+
184
+ describe('AudioSessionClient.startPlaybackTracking', () => {
185
+ beforeEach(() => {
186
+ jest.useFakeTimers();
187
+ });
188
+ afterEach(() => {
189
+ jest.useRealTimers();
190
+ });
191
+
192
+ it('uses audioPlayer.getPlaybackTime() when player is attached', async () => {
193
+ const { AudioFramePlayer, AudioSessionClient } = await import('../audio');
194
+ const player = new AudioFramePlayer();
195
+ jest.spyOn(player, 'getPlaybackTime').mockReturnValue(2.5);
196
+
197
+ const ws = {
198
+ readyState: 1, // WebSocket.OPEN
199
+ send: jest.fn(),
200
+ } as unknown as WebSocket;
201
+ const session = new AudioSessionClient(ws);
202
+ session.setAudioPlayer(player);
203
+
204
+ session.startPlaybackTracking(50);
205
+ jest.advanceTimersByTime(60);
206
+
207
+ expect(player.getPlaybackTime).toHaveBeenCalled();
208
+ expect(session.getPlaybackTracker().getPosition()).toBe(2.5);
209
+ expect((ws as unknown as { send: jest.Mock }).send).toHaveBeenCalledWith(
210
+ expect.stringContaining('"position":2.5'),
211
+ );
212
+
213
+ session.cleanup();
214
+ });
215
+ });
216
+
217
+ // ─────────────────────────────────────────────────────────────
218
+ // AudioPipeline — sentence-boundary viseme scheduling
219
+ // ─────────────────────────────────────────────────────────────
220
+
221
+ describe('AudioPipeline.handleAudioMetadata sentence-boundary detection', () => {
222
+ it('anchors a new sentence when next chunk starts before previous ended', async () => {
223
+ const { AudioPipeline } = await import('../audio');
224
+ const pipeline = new AudioPipeline(jest.fn());
225
+
226
+ const scheduleSpy = jest
227
+ .spyOn(pipeline.visemeScheduler, 'scheduleChunk')
228
+ .mockImplementation(() => {});
229
+
230
+ // First chunk: chunkStartTime = 100, last phoneme ends at 0.30
231
+ jest.spyOn(pipeline.player, 'getChunkStartTime').mockReturnValue(100);
232
+ jest.spyOn(pipeline.player, 'hasChunkStart').mockReturnValue(true);
233
+ pipeline.handleAudioMetadata({
234
+ type: 'audio_metadata',
235
+ chunkId: 'a',
236
+ wordTimestamps: [],
237
+ processedChars: 0,
238
+ isFinal: false,
239
+ cumulativeTime: 0,
240
+ phonemes: [
241
+ {
242
+ wordIndex: 0,
243
+ phones: [
244
+ { phoneSymbol: 'h', startTime: 0.0, duration: 0.1, visemeSymbol: 'aei' },
245
+ { phoneSymbol: 'i', startTime: 0.1, duration: 0.2, visemeSymbol: 'ee' },
246
+ ],
247
+ },
248
+ ],
249
+ });
250
+ expect(scheduleSpy).toHaveBeenLastCalledWith(expect.anything(), 100);
251
+
252
+ // Second chunk: chunkStartTime = 200, but its first phoneme starts at 0.0
253
+ // (well below the previous lastPhonemeEnd of 0.30) → must re-anchor to 200
254
+ (pipeline.player.getChunkStartTime as jest.Mock).mockReturnValue(200);
255
+ pipeline.handleAudioMetadata({
256
+ type: 'audio_metadata',
257
+ chunkId: 'b',
258
+ wordTimestamps: [],
259
+ processedChars: 0,
260
+ isFinal: false,
261
+ cumulativeTime: 0,
262
+ phonemes: [
263
+ {
264
+ wordIndex: 0,
265
+ phones: [
266
+ { phoneSymbol: 't', startTime: 0.0, duration: 0.05, visemeSymbol: 'cdgknstxyz' },
267
+ ],
268
+ },
269
+ ],
270
+ });
271
+ expect(scheduleSpy).toHaveBeenLastCalledWith(expect.anything(), 200);
272
+ });
273
+
274
+ it('keeps the same sentence anchor when next chunk continues forward in time', async () => {
275
+ const { AudioPipeline } = await import('../audio');
276
+ const pipeline = new AudioPipeline(jest.fn());
277
+
278
+ const scheduleSpy = jest
279
+ .spyOn(pipeline.visemeScheduler, 'scheduleChunk')
280
+ .mockImplementation(() => {});
281
+
282
+ // First chunk: anchor at 100, ends at 0.30
283
+ jest.spyOn(pipeline.player, 'getChunkStartTime').mockReturnValue(100);
284
+ jest.spyOn(pipeline.player, 'hasChunkStart').mockReturnValue(true);
285
+ pipeline.handleAudioMetadata({
286
+ type: 'audio_metadata',
287
+ chunkId: 'a',
288
+ wordTimestamps: [],
289
+ processedChars: 0,
290
+ isFinal: false,
291
+ cumulativeTime: 0,
292
+ phonemes: [
293
+ {
294
+ wordIndex: 0,
295
+ phones: [
296
+ { phoneSymbol: 'h', startTime: 0.0, duration: 0.1, visemeSymbol: 'aei' },
297
+ { phoneSymbol: 'i', startTime: 0.1, duration: 0.2, visemeSymbol: 'ee' },
298
+ ],
299
+ },
300
+ ],
301
+ });
302
+
303
+ // Second chunk: continues — first phoneme starts at 0.30 (not before 0.30)
304
+ // chunkStartTime advances but sentenceStartTime stays at 100
305
+ (pipeline.player.getChunkStartTime as jest.Mock).mockReturnValue(150);
306
+ pipeline.handleAudioMetadata({
307
+ type: 'audio_metadata',
308
+ chunkId: 'b',
309
+ wordTimestamps: [],
310
+ processedChars: 0,
311
+ isFinal: false,
312
+ cumulativeTime: 0,
313
+ phonemes: [
314
+ {
315
+ wordIndex: 0,
316
+ phones: [
317
+ { phoneSymbol: 't', startTime: 0.30, duration: 0.05, visemeSymbol: 'cdgknstxyz' },
318
+ ],
319
+ },
320
+ ],
321
+ });
322
+ // Anchor stayed at 100 from the first chunk
323
+ expect(scheduleSpy).toHaveBeenLastCalledWith(expect.anything(), 100);
324
+ });
325
+
326
+ it('resetTurn clears the sentence anchor for the next conversation turn', async () => {
327
+ const { AudioPipeline } = await import('../audio');
328
+ const pipeline = new AudioPipeline(jest.fn());
329
+ const scheduleSpy = jest
330
+ .spyOn(pipeline.visemeScheduler, 'scheduleChunk')
331
+ .mockImplementation(() => {});
332
+
333
+ jest.spyOn(pipeline.player, 'getChunkStartTime').mockReturnValue(100);
334
+ jest.spyOn(pipeline.player, 'hasChunkStart').mockReturnValue(true);
335
+ pipeline.handleAudioMetadata({
336
+ type: 'audio_metadata',
337
+ chunkId: 'a',
338
+ wordTimestamps: [],
339
+ processedChars: 0,
340
+ isFinal: false,
341
+ cumulativeTime: 0,
342
+ phonemes: [
343
+ {
344
+ wordIndex: 0,
345
+ phones: [
346
+ { phoneSymbol: 'h', startTime: 0, duration: 0.1, visemeSymbol: 'aei' },
347
+ ],
348
+ },
349
+ ],
350
+ });
351
+ expect(scheduleSpy).toHaveBeenLastCalledWith(expect.anything(), 100);
352
+
353
+ pipeline.resetTurn();
354
+
355
+ // Next chunk on the new turn: anchor must reset to the new chunkStartTime
356
+ (pipeline.player.getChunkStartTime as jest.Mock).mockReturnValue(500);
357
+ pipeline.handleAudioMetadata({
358
+ type: 'audio_metadata',
359
+ chunkId: 'b',
360
+ wordTimestamps: [],
361
+ processedChars: 0,
362
+ isFinal: false,
363
+ cumulativeTime: 0,
364
+ phonemes: [
365
+ {
366
+ wordIndex: 0,
367
+ phones: [
368
+ { phoneSymbol: 'h', startTime: 0, duration: 0.1, visemeSymbol: 'aei' },
369
+ ],
370
+ },
371
+ ],
372
+ });
373
+ expect(scheduleSpy).toHaveBeenLastCalledWith(expect.anything(), 500);
374
+ });
375
+
376
+ it('buffers metadata that arrives before binary and processes it once a frame lands', async () => {
377
+ const { AudioPipeline } = await import('../audio');
378
+ const pipeline = new AudioPipeline(jest.fn());
379
+
380
+ const scheduleSpy = jest
381
+ .spyOn(pipeline.visemeScheduler, 'scheduleChunk')
382
+ .mockImplementation(() => {});
383
+
384
+ // Inworld ASYNC: metadata arrives first, before any binary frame, so
385
+ // hasChunkStart() is false. The pipeline must defer scheduling.
386
+ const hasChunkStart = jest.spyOn(pipeline.player, 'hasChunkStart').mockReturnValue(false);
387
+ jest.spyOn(pipeline.player, 'getChunkStartTime').mockReturnValue(700);
388
+
389
+ pipeline.handleAudioMetadata({
390
+ type: 'audio_metadata',
391
+ chunkId: 'late-binary',
392
+ wordTimestamps: [],
393
+ processedChars: 0,
394
+ isFinal: false,
395
+ cumulativeTime: 0,
396
+ phonemes: [
397
+ {
398
+ wordIndex: 0,
399
+ phones: [
400
+ { phoneSymbol: 'h', startTime: 0, duration: 0.1, visemeSymbol: 'aei' },
401
+ ],
402
+ },
403
+ ],
404
+ });
405
+ expect(scheduleSpy).not.toHaveBeenCalled();
406
+
407
+ // Binary frame arrives → scheduling runs against the real chunk start.
408
+ hasChunkStart.mockReturnValue(true);
409
+ const ctx = pipeline.player.getContext();
410
+ Object.defineProperty(ctx, 'state', { value: 'running', configurable: true });
411
+ jest.spyOn(pipeline.player, 'playFrame').mockImplementation(() => {});
412
+
413
+ pipeline.handleBinaryFrame(new ArrayBuffer(8));
414
+
415
+ expect(scheduleSpy).toHaveBeenCalledTimes(1);
416
+ expect(scheduleSpy).toHaveBeenLastCalledWith(expect.anything(), 700);
417
+ });
418
+
419
+ it('drains only one queued metadata per binary frame (multi-chunk)', async () => {
420
+ // Codex P2 regression on PR #168: with two metadata messages
421
+ // queued for two distinct chunks, draining both after the first
422
+ // binary frame would consume the player's chunk start once and
423
+ // anchor chunk B's visemes to ``getNextFrameStartTime()`` — the
424
+ // exact drift the buffer is meant to prevent. Each binary frame
425
+ // must drain at most one queued metadata.
426
+ const { AudioPipeline } = await import('../audio');
427
+ const pipeline = new AudioPipeline(jest.fn());
428
+
429
+ const scheduleSpy = jest
430
+ .spyOn(pipeline.visemeScheduler, 'scheduleChunk')
431
+ .mockImplementation(() => {});
432
+
433
+ const hasChunkStart = jest.spyOn(pipeline.player, 'hasChunkStart').mockReturnValue(false);
434
+ // First call → chunk A's start; second call → chunk B's start.
435
+ const getChunkStart = jest
436
+ .spyOn(pipeline.player, 'getChunkStartTime')
437
+ .mockReturnValueOnce(100)
438
+ .mockReturnValueOnce(200);
439
+
440
+ const phonemeMsg = (chunkId: string) => ({
441
+ type: 'audio_metadata' as const,
442
+ chunkId,
443
+ wordTimestamps: [],
444
+ processedChars: 0,
445
+ isFinal: false,
446
+ cumulativeTime: 0,
447
+ phonemes: [
448
+ {
449
+ wordIndex: 0,
450
+ phones: [
451
+ { phoneSymbol: 'h', startTime: 0, duration: 0.1, visemeSymbol: 'aei' as const },
452
+ ],
453
+ },
454
+ ],
455
+ });
456
+
457
+ // Two metadata messages queued before any binary frame lands.
458
+ pipeline.handleAudioMetadata(phonemeMsg('chunk-a'));
459
+ pipeline.handleAudioMetadata(phonemeMsg('chunk-b'));
460
+ expect(scheduleSpy).not.toHaveBeenCalled();
461
+
462
+ const ctx = pipeline.player.getContext();
463
+ Object.defineProperty(ctx, 'state', { value: 'running', configurable: true });
464
+ jest.spyOn(pipeline.player, 'playFrame').mockImplementation(() => {});
465
+
466
+ // First binary frame → drain chunk A only.
467
+ hasChunkStart.mockReturnValue(true);
468
+ pipeline.handleBinaryFrame(new ArrayBuffer(8));
469
+ expect(scheduleSpy).toHaveBeenCalledTimes(1);
470
+ expect(scheduleSpy).toHaveBeenLastCalledWith(expect.anything(), 100);
471
+
472
+ // Second binary frame → drain chunk B with its own start.
473
+ pipeline.handleBinaryFrame(new ArrayBuffer(8));
474
+ expect(scheduleSpy).toHaveBeenCalledTimes(2);
475
+ expect(scheduleSpy).toHaveBeenLastCalledWith(expect.anything(), 200);
476
+ // Both chunk-start consumptions used the per-chunk getter, not
477
+ // the fallback path.
478
+ expect(getChunkStart).toHaveBeenCalledTimes(2);
479
+ });
480
+ });
481
+
482
+ // ─────────────────────────────────────────────────────────────
483
+ // AudioPipeline.bargeIn — must reach the server, not just clear local state
484
+ // ─────────────────────────────────────────────────────────────
485
+
486
+ describe('AudioPipeline.bargeIn', () => {
487
+ it('sends barge_in over the WebSocket when a session is attached', async () => {
488
+ const { AudioPipeline } = await import('../audio');
489
+ const pipeline = new AudioPipeline(jest.fn());
490
+
491
+ const sentMessages: string[] = [];
492
+ const ws = {
493
+ readyState: 1, // WebSocket.OPEN
494
+ send: jest.fn((data: string) => sentMessages.push(data)),
495
+ } as unknown as WebSocket;
496
+ pipeline.attachSession(ws);
497
+
498
+ // Pre-populate a tracker entry so InterruptResult is non-empty
499
+ pipeline.sessionClient!.addWordTimestamps([
500
+ { word: 'hello', startTime: 0, endTime: 0.5 },
501
+ ]);
502
+ pipeline.sessionClient!.getPlaybackTracker().updatePosition(1.0);
503
+
504
+ const visemeClearSpy = jest.spyOn(pipeline.visemeScheduler, 'clear');
505
+
506
+ const result = await pipeline.bargeIn();
507
+
508
+ // The WS must receive a barge_in action — that's the whole point of this fix
509
+ expect(sentMessages.some((m) => m.includes('"action":"barge_in"'))).toBe(true);
510
+ // Visemes get cleared locally regardless of session
511
+ expect(visemeClearSpy).toHaveBeenCalled();
512
+ // InterruptResult surfaces what was spoken
513
+ expect(result).not.toBeNull();
514
+ expect(result!.spokenText).toBe('hello');
515
+ });
516
+
517
+ it('falls back to clearing the player queue when no session is attached', async () => {
518
+ const { AudioPipeline } = await import('../audio');
519
+ const pipeline = new AudioPipeline(jest.fn());
520
+
521
+ const playerClearSpy = jest.spyOn(pipeline.player, 'clearQueue');
522
+ const visemeClearSpy = jest.spyOn(pipeline.visemeScheduler, 'clear');
523
+
524
+ const result = await pipeline.bargeIn();
525
+
526
+ expect(playerClearSpy).toHaveBeenCalled();
527
+ expect(visemeClearSpy).toHaveBeenCalled();
528
+ expect(result).toBeNull();
529
+ });
530
+ });
531
+
532
+ // ─────────────────────────────────────────────────────────────
533
+ // AudioPipeline word-timestamp coordinate frame
534
+ // ─────────────────────────────────────────────────────────────
535
+
536
+ describe('AudioPipeline.handleAudioMetadata word-timestamp coordinates', () => {
537
+ it('stores word timestamps relative to playbackOrigin so getSpokenWords works', async () => {
538
+ const { AudioPipeline } = await import('../audio');
539
+ const pipeline = new AudioPipeline(jest.fn());
540
+
541
+ const ws = {
542
+ readyState: 1, // WebSocket.OPEN
543
+ send: jest.fn(),
544
+ } as unknown as WebSocket;
545
+ pipeline.attachSession(ws);
546
+
547
+ // Pretend playback started at AudioContext time 100 and this chunk's
548
+ // first frame is also at 100 (so the chunk is the first one).
549
+ jest.spyOn(pipeline.player, 'getChunkStartTime').mockReturnValue(100);
550
+ jest.spyOn(pipeline.player, 'getPlaybackOrigin').mockReturnValue(100);
551
+ jest.spyOn(pipeline.player, 'hasChunkStart').mockReturnValue(true);
552
+
553
+ pipeline.handleAudioMetadata({
554
+ type: 'audio_metadata',
555
+ chunkId: 'a',
556
+ wordTimestamps: [
557
+ { word: 'hello', startTime: 0, endTime: 0.5 },
558
+ { word: 'world', startTime: 0.5, endTime: 1.0 },
559
+ ],
560
+ processedChars: 0,
561
+ isFinal: false,
562
+ cumulativeTime: 0,
563
+ });
564
+
565
+ // `currentPosition` written by handleBinaryFrame / startPlaybackTracking
566
+ // is `currentTime - playbackOrigin` (relative). At a relative position
567
+ // of 0.6s, "hello" (0.0–0.5) is fully spoken; "world" (0.5–1.0) is not.
568
+ pipeline.sessionClient!.getPlaybackTracker().updatePosition(0.6);
569
+ expect(pipeline.sessionClient!.getPlaybackTracker().getSpokenWords()).toEqual(['hello']);
570
+
571
+ // At 1.1s both words are done.
572
+ pipeline.sessionClient!.getPlaybackTracker().updatePosition(1.1);
573
+ expect(pipeline.sessionClient!.getPlaybackTracker().getSpokenWords()).toEqual(['hello', 'world']);
574
+ });
575
+ });
576
+
577
+ // ─────────────────────────────────────────────────────────────
578
+ // AudioPipeline.destroy — teardown ordering
579
+ // ─────────────────────────────────────────────────────────────
580
+
581
+ describe('AudioPipeline.destroy', () => {
582
+ it('cleans up session, scheduler, and player in that order', async () => {
583
+ const { AudioPipeline } = await import('../audio');
584
+ const pipeline = new AudioPipeline(jest.fn());
585
+
586
+ const ws = {
587
+ readyState: 1,
588
+ send: jest.fn(),
589
+ } as unknown as WebSocket;
590
+ pipeline.attachSession(ws);
591
+
592
+ const order: string[] = [];
593
+ const sessionCleanupSpy = jest
594
+ .spyOn(pipeline.sessionClient!, 'cleanup')
595
+ .mockImplementation(() => {
596
+ order.push('sessionClient.cleanup');
597
+ });
598
+ const visemeDestroySpy = jest
599
+ .spyOn(pipeline.visemeScheduler, 'destroy')
600
+ .mockImplementation(() => {
601
+ order.push('visemeScheduler.destroy');
602
+ });
603
+ const playerStopSpy = jest
604
+ .spyOn(pipeline.player, 'stop')
605
+ .mockImplementation(async () => {
606
+ order.push('player.stop');
607
+ });
608
+
609
+ await pipeline.destroy();
610
+
611
+ // The orchestrator's contract is: hand the WS-touching pieces back
612
+ // first (so any in-flight position updates stop), then tear down
613
+ // the rAF loop, then close the audio graph. Reordering would
614
+ // surface as either dropped frames or a wedged audio worklet.
615
+ expect(order).toEqual([
616
+ 'sessionClient.cleanup',
617
+ 'visemeScheduler.destroy',
618
+ 'player.stop',
619
+ ]);
620
+ expect(sessionCleanupSpy).toHaveBeenCalledTimes(1);
621
+ expect(visemeDestroySpy).toHaveBeenCalledTimes(1);
622
+ expect(playerStopSpy).toHaveBeenCalledTimes(1);
623
+
624
+ // sessionClient is unset post-destroy so a stray bargeIn() is a no-op.
625
+ expect(pipeline.sessionClient).toBeNull();
626
+ });
627
+
628
+ it('runs without a session attached', async () => {
629
+ const { AudioPipeline } = await import('../audio');
630
+ const pipeline = new AudioPipeline(jest.fn());
631
+
632
+ jest.spyOn(pipeline.visemeScheduler, 'destroy').mockImplementation(() => {});
633
+ jest.spyOn(pipeline.player, 'stop').mockResolvedValue(undefined);
634
+
635
+ await expect(pipeline.destroy()).resolves.toBeUndefined();
636
+ expect(pipeline.sessionClient).toBeNull();
637
+ });
638
+ });
639
+
640
+ // ─────────────────────────────────────────────────────────────
641
+ // AudioPipeline.attachSession — reconnect cleanup
642
+ // ─────────────────────────────────────────────────────────────
643
+
644
+ describe('AudioPipeline.attachSession', () => {
645
+ it('cleans up the previous session before swapping in a new one (reconnect path)', async () => {
646
+ const { AudioPipeline } = await import('../audio');
647
+ const pipeline = new AudioPipeline(jest.fn());
648
+
649
+ const ws1 = { readyState: 1, send: jest.fn() } as unknown as WebSocket;
650
+ pipeline.attachSession(ws1);
651
+ const firstSession = pipeline.sessionClient!;
652
+ const cleanupSpy = jest.spyOn(firstSession, 'cleanup');
653
+
654
+ // Reconnect — without the cleanup call, the first session's
655
+ // setInterval would keep ticking against a dead socket.
656
+ const ws2 = { readyState: 1, send: jest.fn() } as unknown as WebSocket;
657
+ pipeline.attachSession(ws2);
658
+
659
+ expect(cleanupSpy).toHaveBeenCalledTimes(1);
660
+ expect(pipeline.sessionClient).not.toBe(firstSession);
661
+ });
662
+ });
663
+
664
+ // ─────────────────────────────────────────────────────────────
665
+ // AudioPipeline.handleBinaryFrame — suspended context path
666
+ // ─────────────────────────────────────────────────────────────
667
+
668
+ describe('AudioPipeline.handleBinaryFrame suspended-context flow', () => {
669
+ it('schedules tracker update inside resume().then() so position reads after playFrame', async () => {
670
+ const { AudioPipeline } = await import('../audio');
671
+ const pipeline = new AudioPipeline(jest.fn());
672
+
673
+ // Start the context as suspended so handleBinaryFrame takes the
674
+ // resume() branch.
675
+ activeMock.state = 'suspended';
676
+
677
+ const ws = { readyState: 1, send: jest.fn() } as unknown as WebSocket;
678
+ pipeline.attachSession(ws);
679
+
680
+ // Inject deterministic order: resume() resolves AFTER we read
681
+ // playbackTime baselines, so any tracker write outside .then()
682
+ // would be visible immediately. We capture the order with spies.
683
+ const order: string[] = [];
684
+ jest
685
+ .spyOn(pipeline.player, 'resume')
686
+ .mockImplementation(async () => {
687
+ order.push('resume.start');
688
+ await Promise.resolve();
689
+ order.push('resume.end');
690
+ });
691
+ jest.spyOn(pipeline.player, 'playFrame').mockImplementation(() => {
692
+ order.push('playFrame');
693
+ });
694
+ jest.spyOn(pipeline.player, 'getPlaybackTime').mockImplementation(() => {
695
+ order.push('getPlaybackTime');
696
+ return 1.5;
697
+ });
698
+
699
+ pipeline.handleBinaryFrame(buildAiFrame());
700
+ // Let microtasks drain so resume().then() runs
701
+ await Promise.resolve();
702
+ await Promise.resolve();
703
+
704
+ // The contract: resume → playFrame → getPlaybackTime (inside .then),
705
+ // never getPlaybackTime before playFrame on this path.
706
+ const playFrameIdx = order.indexOf('playFrame');
707
+ const getPlaybackIdx = order.indexOf('getPlaybackTime');
708
+ expect(playFrameIdx).toBeGreaterThanOrEqual(0);
709
+ expect(getPlaybackIdx).toBeGreaterThan(playFrameIdx);
710
+
711
+ // Tracker reflects the post-playFrame position.
712
+ expect(pipeline.sessionClient!.getPlaybackTracker().getPosition()).toBe(1.5);
713
+ });
714
+ });