-
-
Notifications
You must be signed in to change notification settings - Fork 268
Expand file tree
/
Copy pathuseWhisperTranscription.test.ts
More file actions
524 lines (419 loc) · 19.2 KB
/
Copy pathuseWhisperTranscription.test.ts
File metadata and controls
524 lines (419 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
import { renderHook, act } from '@testing-library/react-native';
import { useWhisperTranscription } from '../../../src/hooks/useWhisperTranscription';
const mockLoadModel = jest.fn();
const mockWhisperStoreState = {
downloadedModelId: null as string | null,
isModelLoaded: false,
isModelLoading: false,
loadModel: mockLoadModel,
};
jest.mock('../../../src/services/whisperService', () => ({
whisperService: {
isModelLoaded: jest.fn(() => false),
isCurrentlyTranscribing: jest.fn(() => false),
startRealtimeTranscription: jest.fn(),
stopTranscription: jest.fn(),
forceReset: jest.fn(),
},
// Pure helper used by finalizeTranscription — strip whisper no-speech markers,
// return '' when only markers/punctuation remain (mirrors the real impl).
cleanTranscription: (raw: string) => {
if (!raw) return '';
const s = raw.replace(/\[[^\]]*\]/g, ' ').replace(/\([^)]*\)/g, ' ').replace(/\s+/g, ' ').trim();
return /[a-z0-9]/i.test(s) ? s : '';
},
}));
jest.mock('../../../src/stores/whisperStore', () => ({
useWhisperStore: jest.fn(() => mockWhisperStoreState),
}));
// Get mock reference after jest.mock hoisting
const { whisperService: mockWhisperService } = require('../../../src/services/whisperService');
jest.mock('react-native', () => ({
Vibration: {
vibrate: jest.fn(),
},
}));
describe('useWhisperTranscription', () => {
beforeEach(() => {
jest.clearAllMocks();
jest.useFakeTimers();
mockWhisperService.isModelLoaded.mockReturnValue(false);
mockWhisperService.isCurrentlyTranscribing.mockReturnValue(false);
mockWhisperStoreState.downloadedModelId = null;
mockWhisperStoreState.isModelLoaded = false;
mockWhisperStoreState.isModelLoading = false;
});
afterEach(() => {
jest.useRealTimers();
});
it('returns correct initial state', () => {
const { result } = renderHook(() => useWhisperTranscription());
expect(result.current.isRecording).toBe(false);
expect(result.current.isTranscribing).toBe(false);
expect(result.current.isModelLoaded).toBe(false);
expect(result.current.isModelLoading).toBe(false);
expect(result.current.partialResult).toBe('');
expect(result.current.finalResult).toBe('');
expect(result.current.error).toBeNull();
expect(result.current.recordingTime).toBe(0);
expect(typeof result.current.startRecording).toBe('function');
expect(typeof result.current.stopRecording).toBe('function');
expect(typeof result.current.clearResult).toBe('function');
});
it('sets error when startRecording called with no model loaded and no downloadedModelId', async () => {
mockWhisperService.isModelLoaded.mockReturnValue(false);
mockWhisperStoreState.downloadedModelId = null;
const { result } = renderHook(() => useWhisperTranscription());
await act(async () => {
await result.current.startRecording();
});
expect(result.current.error).toBe(
'No transcription model downloaded. Go to Settings to download one.',
);
expect(mockWhisperService.startRealtimeTranscription).not.toHaveBeenCalled();
});
it('calls loadModel when startRecording called with model not loaded but downloadedModelId exists', async () => {
mockWhisperService.isModelLoaded.mockReturnValue(false);
mockWhisperStoreState.downloadedModelId = 'whisper-tiny';
mockLoadModel.mockResolvedValue(undefined);
// After loadModel, model is still not loaded from service perspective
// so startRealtimeTranscription won't be called unless we update the mock
mockWhisperService.isModelLoaded
.mockReturnValueOnce(false) // auto-load check
.mockReturnValueOnce(false) // console.log check
.mockReturnValueOnce(false); // the guard check in startRecording
const { result } = renderHook(() => useWhisperTranscription());
await act(async () => {
await result.current.startRecording();
});
expect(mockLoadModel).toHaveBeenCalled();
});
it('sets error when loadModel fails during startRecording', async () => {
mockWhisperService.isModelLoaded.mockReturnValue(false);
mockWhisperStoreState.downloadedModelId = 'whisper-tiny';
mockLoadModel.mockRejectedValue(new Error('Load failed'));
const { result } = renderHook(() => useWhisperTranscription());
await act(async () => {
await result.current.startRecording();
});
expect(result.current.error).toBe(
'Failed to load Whisper model. Please try again.',
);
});
it('calls startRealtimeTranscription and sets isRecording on success', async () => {
mockWhisperService.isModelLoaded.mockReturnValue(true);
mockWhisperService.startRealtimeTranscription.mockImplementation(
async (callback: any) => {
callback({ isCapturing: true, text: 'partial', recordingTime: 1 });
},
);
const { result } = renderHook(() => useWhisperTranscription());
await act(async () => {
await result.current.startRecording();
});
expect(mockWhisperService.startRealtimeTranscription).toHaveBeenCalled();
expect(result.current.partialResult).toBe('partial');
expect(result.current.recordingTime).toBe(1);
});
it('cleans whisper markers out of partial results (never shows "[BLANK_AUDIO]" in the UI)', async () => {
mockWhisperService.isModelLoaded.mockReturnValue(true);
mockWhisperService.startRealtimeTranscription.mockImplementation(
async (callback: any) => {
// Mid-capture partial with a leading no-speech marker.
callback({ isCapturing: true, text: '[BLANK_AUDIO] hello', recordingTime: 1 });
},
);
const { result } = renderHook(() => useWhisperTranscription());
await act(async () => {
await result.current.startRecording();
});
// Stripped through cleanTranscription (the single owner of marker stripping).
expect(result.current.partialResult).toBe('hello');
});
it('does not let an empty cleaned partial clobber an existing good partial', async () => {
mockWhisperService.isModelLoaded.mockReturnValue(true);
mockWhisperService.startRealtimeTranscription.mockImplementation(
async (callback: any) => {
// First a real partial, then a pure-marker partial (silence mid-capture):
// the marker-only result cleans to '' and must NOT wipe the good text.
callback({ isCapturing: true, text: 'hello world', recordingTime: 1 });
callback({ isCapturing: true, text: '[BLANK_AUDIO]', recordingTime: 2 });
},
);
const { result } = renderHook(() => useWhisperTranscription());
await act(async () => {
await result.current.startRecording();
});
expect(result.current.partialResult).toBe('hello world');
});
it('sets error and calls forceReset when startRecording throws', async () => {
mockWhisperService.isModelLoaded.mockReturnValue(true);
mockWhisperService.startRealtimeTranscription.mockRejectedValue(
new Error('Mic access denied'),
);
const { result } = renderHook(() => useWhisperTranscription());
await act(async () => {
await result.current.startRecording();
});
expect(result.current.error).toBe('Mic access denied');
expect(result.current.isRecording).toBe(false);
expect(result.current.isTranscribing).toBe(false);
expect(mockWhisperService.forceReset).toHaveBeenCalled();
});
it('stopRecording sets isRecording false and calls stopTranscription after delay', async () => {
mockWhisperService.isModelLoaded.mockReturnValue(true);
mockWhisperService.stopTranscription.mockResolvedValue(undefined);
mockWhisperService.startRealtimeTranscription.mockImplementation(
async (callback: any) => {
callback({ isCapturing: true, text: 'hello', recordingTime: 2 });
},
);
const { result } = renderHook(() => useWhisperTranscription());
// Start recording first
await act(async () => {
await result.current.startRecording();
});
// Stop recording
let stopPromise: Promise<void>;
act(() => {
stopPromise = result.current.stopRecording();
});
// isRecording should be false immediately
expect(result.current.isRecording).toBe(false);
// Advance past the trailing record time (2500ms)
await act(async () => {
jest.advanceTimersByTime(2500);
await stopPromise;
});
expect(mockWhisperService.stopTranscription).toHaveBeenCalled();
});
it('clearResult clears finalResult, partialResult, and isTranscribing', async () => {
mockWhisperService.isModelLoaded.mockReturnValue(true);
mockWhisperService.startRealtimeTranscription.mockImplementation(
async (callback: any) => {
callback({ isCapturing: false, text: 'final text', recordingTime: 3 });
},
);
const { result } = renderHook(() => useWhisperTranscription());
await act(async () => {
await result.current.startRecording();
});
// Advance timers to resolve any pending finalizeTranscription timeouts
await act(async () => {
jest.advanceTimersByTime(1000);
});
// Now clear
act(() => {
result.current.clearResult();
});
expect(result.current.finalResult).toBe('');
expect(result.current.partialResult).toBe('');
expect(result.current.isTranscribing).toBe(false);
});
it('does NOT eager-load whisper on mount — it loads on demand, so it never fights a residency eviction', async () => {
// Regression for the eviction race: an eager mount effect keyed on isModelLoaded reloaded
// whisper the instant the residency manager evicted it for a text model. Loading is now
// on-demand (startRecording) + fits-gated launch preload (modelPreloader), never here.
mockWhisperStoreState.downloadedModelId = 'whisper-base';
mockWhisperStoreState.isModelLoaded = false;
mockWhisperService.isModelLoaded.mockReturnValue(false);
mockLoadModel.mockResolvedValue(undefined);
renderHook(() => useWhisperTranscription());
await act(async () => {});
expect(mockLoadModel).not.toHaveBeenCalled(); // no eager load — eviction sticks
});
it('returns isModelLoaded true when store or service reports loaded', () => {
mockWhisperStoreState.isModelLoaded = false;
mockWhisperService.isModelLoaded.mockReturnValue(true);
const { result } = renderHook(() => useWhisperTranscription());
expect(result.current.isModelLoaded).toBe(true);
});
// ========================================================================
// startRecording: already-recording branch (lines 143-147)
// ========================================================================
it('stops current recording before starting a new one when isCurrentlyTranscribing is true', async () => {
mockWhisperService.isModelLoaded.mockReturnValue(true);
// First check in startRecording returns true (triggers stop), then false for subsequent checks
mockWhisperService.isCurrentlyTranscribing
.mockReturnValueOnce(true)
.mockReturnValue(false);
mockWhisperService.stopTranscription.mockResolvedValue(undefined);
mockWhisperService.startRealtimeTranscription.mockResolvedValue(undefined);
const { result } = renderHook(() => useWhisperTranscription());
// Start recording - it will internally call stopRecording() which has a 2500ms wait,
// then startRecording waits 150ms after stop completes.
let startPromise: Promise<void>;
act(() => {
startPromise = result.current.startRecording();
});
// Advance past stopRecording's TRAILING_RECORD_TIME (2500ms)
await act(async () => {
jest.advanceTimersByTime(2600);
});
// Advance past startRecording's 150ms debounce after stopRecording
await act(async () => {
jest.advanceTimersByTime(200);
await startPromise!;
});
// stopTranscription called as part of stopping the previous session
expect(mockWhisperService.stopTranscription).toHaveBeenCalled();
// startRealtimeTranscription called for the new session
expect(mockWhisperService.startRealtimeTranscription).toHaveBeenCalled();
});
// ========================================================================
// transcription callback: no text path (lines 197-200)
// ========================================================================
it('clears isTranscribing when recording finishes with no text result', async () => {
mockWhisperService.isModelLoaded.mockReturnValue(true);
// Simulate callback: capturing=false, no text
mockWhisperService.startRealtimeTranscription.mockImplementation(
async (callback: any) => {
callback({ isCapturing: false, text: null, recordingTime: 0 });
},
);
const { result } = renderHook(() => useWhisperTranscription());
await act(async () => {
await result.current.startRecording();
});
expect(result.current.isTranscribing).toBe(false);
expect(result.current.partialResult).toBe('');
expect(result.current.finalResult).toBe('');
});
it('clears isTranscribing when recording finishes with empty string text', async () => {
mockWhisperService.isModelLoaded.mockReturnValue(true);
mockWhisperService.startRealtimeTranscription.mockImplementation(
async (callback: any) => {
callback({ isCapturing: false, text: '', recordingTime: 0 });
},
);
const { result } = renderHook(() => useWhisperTranscription());
await act(async () => {
await result.current.startRecording();
});
expect(result.current.isTranscribing).toBe(false);
expect(result.current.finalResult).toBe('');
});
// ========================================================================
// clearResult: calls stopTranscription when currently transcribing (line 132-134)
// ========================================================================
it('calls stopTranscription in clearResult when isCurrentlyTranscribing is true', async () => {
mockWhisperService.isModelLoaded.mockReturnValue(true);
mockWhisperService.isCurrentlyTranscribing.mockReturnValue(true);
mockWhisperService.stopTranscription.mockResolvedValue(undefined);
const { result } = renderHook(() => useWhisperTranscription());
act(() => {
result.current.clearResult();
});
expect(mockWhisperService.stopTranscription).toHaveBeenCalled();
});
it('does not call stopTranscription in clearResult when not transcribing', async () => {
mockWhisperService.isCurrentlyTranscribing.mockReturnValue(false);
const { result } = renderHook(() => useWhisperTranscription());
act(() => {
result.current.clearResult();
});
expect(mockWhisperService.stopTranscription).not.toHaveBeenCalled();
});
// ========================================================================
// stopRecording: cancelled during trailing capture (lines 104-108)
// ========================================================================
it('aborts stopRecording early and calls forceReset when cancelled during trailing capture', async () => {
mockWhisperService.isModelLoaded.mockReturnValue(true);
mockWhisperService.stopTranscription.mockResolvedValue(undefined);
mockWhisperService.startRealtimeTranscription.mockImplementation(
async (callback: any) => {
callback({ isCapturing: true, text: 'partial', recordingTime: 1 });
},
);
const { result } = renderHook(() => useWhisperTranscription());
await act(async () => {
await result.current.startRecording();
});
// Start stopping (triggers 2500ms trailing wait)
let stopPromise: Promise<void>;
act(() => {
stopPromise = result.current.stopRecording();
});
// Cancel during the trailing wait (before 2500ms)
act(() => {
result.current.clearResult(); // sets isCancelled.current = true
});
// Advance past trailing time
await act(async () => {
jest.advanceTimersByTime(3000);
await stopPromise!;
});
// forceReset is called because cancelled during trailing capture
expect(mockWhisperService.forceReset).toHaveBeenCalled();
// stopTranscription should NOT be called (returned early)
expect(mockWhisperService.stopTranscription).not.toHaveBeenCalled();
});
// ========================================================================
// stopRecording: error path (lines 114-121)
// ========================================================================
it('calls forceReset and clears transcribing state when stopTranscription throws', async () => {
mockWhisperService.isModelLoaded.mockReturnValue(true);
mockWhisperService.stopTranscription.mockRejectedValue(new Error('Stop failed'));
mockWhisperService.startRealtimeTranscription.mockImplementation(
async (callback: any) => {
callback({ isCapturing: true, text: 'partial', recordingTime: 1 });
},
);
const { result } = renderHook(() => useWhisperTranscription());
await act(async () => {
await result.current.startRecording();
});
await act(async () => {
const stopPromise = result.current.stopRecording();
jest.advanceTimersByTime(3000);
await stopPromise;
});
expect(mockWhisperService.forceReset).toHaveBeenCalled();
expect(result.current.isTranscribing).toBe(false);
});
// ========================================================================
// finalizeTranscription: cancelled branch inside deferred timeout (lines 68-71)
// When transcribingStartTime is set and remaining > 0, a deferred setTimeout
// is created. If cancelled before it fires, isTranscribing is cleared.
// ========================================================================
it('does not set finalResult when cancelled before deferred finalizeTranscription fires', async () => {
mockWhisperService.isModelLoaded.mockReturnValue(true);
mockWhisperService.stopTranscription.mockResolvedValue(undefined);
// Provide a callback that fires after stop (simulating real Whisper behaviour)
// We set transcribingStartTime via stopRecording(), then trigger the callback
let capturedCallback: ((result: any) => void) | null = null;
mockWhisperService.startRealtimeTranscription.mockImplementation(
async (callback: any) => {
capturedCallback = callback;
// Emit a partial result so we're "recording"
callback({ isCapturing: true, text: 'partial', recordingTime: 1 });
},
);
const { result } = renderHook(() => useWhisperTranscription());
await act(async () => {
await result.current.startRecording();
});
// Begin stopping - this sets transcribingStartTime.current = Date.now()
let stopPromise: Promise<void>;
act(() => {
stopPromise = result.current.stopRecording();
});
// Fire the final callback BEFORE the 2500ms trailing wait ends
// transcribingStartTime was just set, so elapsed ≈ 0 → remaining ≈ 600ms
act(() => {
capturedCallback!({ isCapturing: false, text: 'hello world', recordingTime: 5 });
});
// Now cancel (sets isCancelled = true) while the deferred timer is pending
act(() => {
result.current.clearResult();
});
// Advance past trailing wait and the deferred MIN_TRANSCRIBING_TIME timer
await act(async () => {
jest.advanceTimersByTime(3200);
await stopPromise!;
});
// clearResult cleared the result; the deferred timer should NOT override it
expect(result.current.finalResult).toBe('');
expect(result.current.isTranscribing).toBe(false);
});
});