Open History to see the last commit
1import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
2
3import {
4 resetVoiceInputGlobalsForTests,
5 resolveTranscriptCommit,
6 VoiceInputController,
7 VOICE_RECORDING_LIMIT_SECONDS,
8 type VoiceDraftSnapshot,
9 type VoiceInputControllerDependencies,
10 type VoiceRecorder,
11} from "./controller.ts";
12import type { PreparedVoiceTranscription, VoiceTranscriber } from "./transcription.ts";
13
14function deferred<T>() {
15 let resolve!: (value: T) => void;
16 let reject!: (error: unknown) => void;
17 const promise = new Promise<T>((resolvePromise, rejectPromise) => {
18 resolve = resolvePromise;
19 reject = rejectPromise;
20 });
21 return { promise, resolve, reject };
22}
23
24class TestRecorder implements VoiceRecorder {
25 uri: string | null = "file:///voice.m4a";
26 readonly prepareToRecordAsync = vi.fn(async () => undefined);
27 readonly record = vi.fn();
28 readonly stop = vi.fn(async () => undefined);
29}
30
31function preparedTranscription(
32 transcribe: PreparedVoiceTranscription["transcribe"] = async () => "new text",
33): PreparedVoiceTranscription {
34 return { locale: "en-US", transcribe };
35}
36
37function draft(overrides: Partial<VoiceDraftSnapshot> = {}): VoiceDraftSnapshot {
38 return {
39 ownerKey: "environment:thread",
40 text: "hello world",
41 selection: { start: 6, end: 11 },
42 revision: 1,
43 ...overrides,
44 };
45}
46
47function createHarness(
48 overrides: Partial<VoiceInputControllerDependencies> = {},
49 initialDraft = draft(),
50) {
51 const recorder = new TestRecorder();
52 let currentDraft: VoiceDraftSnapshot | null = initialDraft;
53 const commits: Array<{ text: string; selection: { start: number; end: number } }> = [];
54 const deleted: string[] = [];
55 const dependencies: VoiceInputControllerDependencies = {
56 recorder,
57 getTranscriber: () => ({ prepare: async () => preparedTranscription() }),
58 requestPermission: async () => ({ granted: true, canAskAgain: true }),
59 configureRecording: async () => undefined,
60 releaseRecording: async () => undefined,
61 deleteRecording: (uri) => deleted.push(uri),
62 readDraft: () => currentDraft,
63 commitDraft: (text, selection) => commits.push({ text, selection }),
64 onStateChange: vi.fn(),
65 ...overrides,
66 };
67 return {
68 controller: new VoiceInputController(dependencies),
69 recorder,
70 commits,
71 deleted,
72 setDraft: (next: VoiceDraftSnapshot | null) => {
73 currentDraft = next;
74 },
75 };
76}
77
78describe("resolveTranscriptCommit", () => {
79 it("replaces the recorded UTF-16 selection around emoji and composer tokens", () => {
80 const text = "Fix 🧪 then $review please";
81 const tokenStart = text.indexOf("$review");
82 const captured = draft({
83 text,
84 selection: { start: tokenStart, end: tokenStart + "$review".length },
85 });
86
87 expect(resolveTranscriptCommit(captured, captured, "use the mobile skill", "en-US")).toEqual({
88 kind: "commit",
89 text: "Fix 🧪 then use the mobile skill please",
90 selection: { start: tokenStart + "use the mobile skill".length, end: tokenStart + 20 },
91 });
92 });
93
94 it("does not replace text after the owner, text, or revision changes", () => {
95 const captured = draft();
96 expect(
97 resolveTranscriptCommit(captured, draft({ ownerKey: "other" }), "text", "en-US"),
98 ).toEqual({
99 kind: "stale",
100 });
101 expect(resolveTranscriptCommit(captured, draft({ text: "newer" }), "text", "en-US")).toEqual({
102 kind: "stale",
103 });
104 expect(resolveTranscriptCommit(captured, draft({ revision: 2 }), "text", "en-US")).toEqual({
105 kind: "stale",
106 });
107 });
108});
109
110describe("VoiceInputController", () => {
111 beforeEach(() => resetVoiceInputGlobalsForTests());
112
113 it("checks support and permission before recording", async () => {
114 const unsupported = createHarness({ getTranscriber: () => null });
115 await unsupported.controller.start();
116 expect(unsupported.controller.currentState.error).toContain("not available");
117 expect(unsupported.recorder.record).not.toHaveBeenCalled();
118
119 const denied = createHarness({
120 requestPermission: async () => ({ granted: false, canAskAgain: false }),
121 });
122 await denied.controller.start();
123 expect(denied.controller.currentState.errorAction).toBe("settings");
124 expect(denied.recorder.record).not.toHaveBeenCalled();
125 });
126
127 it.each(["permission", "transcription"] as const)(
128 "clears %s errors when switching to another draft",
129 async (failure) => {
130 const harness = createHarness(
131 failure === "permission"
132 ? { requestPermission: async () => ({ granted: false, canAskAgain: false }) }
133 : {
134 getTranscriber: () => ({
135 prepare: async () =>
136 preparedTranscription(async () => {
137 throw new Error("Transcription failed");
138 }),
139 }),
140 },
141 );
142 await harness.controller.start();
143 await harness.controller.stop();
144 expect(harness.controller.currentState).toMatchObject({
145 phase: "error",
146 error: expect.any(String),
147 errorAction: failure === "permission" ? "settings" : "retry",
148 });
149
150 harness.setDraft(draft({ ownerKey: "environment:other-thread" }));
151 harness.controller.ownerChanged();
152
153 expect(harness.controller.currentState).toEqual({
154 phase: "idle",
155 error: null,
156 errorAction: null,
157 });
158 expect(harness.commits).toEqual([]);
159 },
160 );
161
162 it.each(["permission", "preparation", "recording"] as const)(
163 "keeps the selected transcriber when preferences change during %s",
164 async (changeDuring) => {
165 const permission = deferred<{ granted: boolean; canAskAgain: boolean }>();
166 const permissionEntered = deferred<void>();
167 const preparation = deferred<void>();
168 const preparationEntered = deferred<void>();
169 const preparationSignals: AbortSignal[] = [];
170 const transcriptionSignals: AbortSignal[] = [];
171 const transcriber = (text: string): VoiceTranscriber => ({
172 prepare: async ({ signal }) => {
173 preparationSignals.push(signal);
174 preparationEntered.resolve(undefined);
175 await preparation.promise;
176 return preparedTranscription(async (_uri, { signal }) => {
177 transcriptionSignals.push(signal);
178 return text;
179 });
180 },
181 });
182 const first = transcriber("first choice");
183 const second = transcriber("second choice");
184 let selected = first;
185 const harness = createHarness({
186 getTranscriber: () => selected,
187 requestPermission: () => {
188 permissionEntered.resolve(undefined);
189 return permission.promise;
190 },
191 });
192
193 const starting = harness.controller.start();
194 await permissionEntered.promise;
195 if (changeDuring === "permission") selected = second;
196 permission.resolve({ granted: true, canAskAgain: true });
197 await preparationEntered.promise;
198 if (changeDuring === "preparation") selected = second;
199 preparation.resolve(undefined);
200 await starting;
201 if (changeDuring === "recording") selected = second;
202 await harness.controller.stop();
203
204 expect(harness.commits.map((commit) => commit.text)).toEqual(["hello first choice"]);
205
206 await harness.controller.start();
207 await harness.controller.stop();
208
209 expect(harness.commits.map((commit) => commit.text)).toEqual([
210 "hello first choice",
211 "hello second choice",
212 ]);
213 expect(preparationSignals).toHaveLength(2);
214 expect(transcriptionSignals).toHaveLength(2);
215 expect(transcriptionSignals[0]).toBe(preparationSignals[0]);
216 expect(transcriptionSignals[1]).toBe(preparationSignals[1]);
217 expect(preparationSignals[1]).not.toBe(preparationSignals[0]);
218 },
219 );
220
221 it("uses the native five-minute cap and commits one final transcript", async () => {
222 const harness = createHarness();
223 await harness.controller.start();
224 expect(harness.recorder.record).toHaveBeenCalledWith({
225 forDuration: VOICE_RECORDING_LIMIT_SECONDS,
226 });
227
228 const stopping = harness.controller.stop();
229 harness.controller.handleRecorderStatus({
230 isFinished: true,
231 hasError: false,
232 error: null,
233 url: "file:///voice.m4a",
234 });
235 await stopping;
236
237 expect(harness.commits).toEqual([
238 { text: "hello new text", selection: { start: 14, end: 14 } },
239 ]);
240 expect(harness.deleted).toEqual(["file:///voice.m4a"]);
241 });
242
243 it.each(["cancel", "dispose", "ownerChanged"] as const)(
244 "queues the next recording after %s until transcription and audio cleanup settle",
245 async (action) => {
246 const transcription = deferred<string>();
247 const transcriptionEntered = deferred<AbortSignal>();
248 const audioRelease = deferred<void>();
249 const audioReleaseEntered = deferred<void>();
250 const releaseRecording = vi
251 .fn<() => Promise<void>>()
252 .mockRejectedValueOnce(new Error("busy"))
253 .mockImplementationOnce(() => {
254 audioReleaseEntered.resolve(undefined);
255 return audioRelease.promise;
256 });
257 const harness = createHarness({
258 releaseRecording,
259 getTranscriber: () => ({
260 prepare: async () =>
261 preparedTranscription((_uri, { signal }) => {
262 transcriptionEntered.resolve(signal);
263 return transcription.promise;
264 }),
265 }),
266 });
267 await harness.controller.start();
268 const stopping = harness.controller.stop();
269 const signal = await transcriptionEntered.promise;
270 expect(signal.aborted).toBe(false);
271 if (action === "ownerChanged") {
272 harness.setDraft(draft({ ownerKey: "environment:other-thread" }));
273 }
274 harness.controller[action]();
275 expect(signal.aborted).toBe(true);
276
277 const prepare = vi.fn(async () => preparedTranscription());
278 const next = createHarness({ getTranscriber: () => ({ prepare }) });
279 const nextStart = next.controller.start();
280 expect(next.controller.currentState).toEqual({
281 phase: "preparing",
282 error: null,
283 errorAction: null,
284 });
285 expect(prepare).not.toHaveBeenCalled();
286 expect(next.recorder.record).not.toHaveBeenCalled();
287
288 transcription.resolve("late text");
289 await audioReleaseEntered.promise;
290 expect(prepare).not.toHaveBeenCalled();
291 expect(next.recorder.prepareToRecordAsync).not.toHaveBeenCalled();
292 audioRelease.resolve(undefined);
293 await stopping;
294 await nextStart;
295
296 expect(harness.commits).toEqual([]);
297 expect(harness.deleted).toEqual(["file:///voice.m4a"]);
298 expect(harness.controller.currentState.phase).toBe("idle");
299
300 expect(next.controller.currentState.phase).toBe("recording");
301 expect(prepare).toHaveBeenCalledTimes(1);
302 await next.controller.interruptRecording();
303 },
304 );
305
306 it("releases the microphone before transcription starts", async () => {
307 const events: string[] = [];
308 const harness = createHarness({
309 releaseRecording: async () => {
310 events.push("released");
311 },
312 getTranscriber: () => ({
313 prepare: async () =>
314 preparedTranscription(async () => {
315 events.push("transcribed");
316 return "done";
317 }),
318 }),
319 });
320 await harness.controller.start();
321 await harness.controller.stop();
322
323 expect(events).toEqual(["released", "transcribed"]);
324 });
325
326 it("ignores a late transcript after the draft owner changes", async () => {
327 const transcription = deferred<string>();
328 const transcriptionEntered = deferred<void>();
329 const harness = createHarness({
330 getTranscriber: () => ({
331 prepare: async () =>
332 preparedTranscription(() => {
333 transcriptionEntered.resolve(undefined);
334 return transcription.promise;
335 }),
336 }),
337 });
338 await harness.controller.start();
339 const stopping = harness.controller.stop();
340 await transcriptionEntered.promise;
341 harness.setDraft(draft({ ownerKey: "environment:other-thread" }));
342 transcription.resolve("late text");
343 await stopping;
344
345 expect(harness.commits).toEqual([]);
346 expect(harness.controller.currentState.error).toContain("draft changed");
347 });
348
349 it("queues the next recording until canceled preparation settles", async () => {
350 const preparation = deferred<PreparedVoiceTranscription>();
351 const preparationEntered = deferred<AbortSignal>();
352 const first = createHarness({
353 getTranscriber: () => ({
354 prepare: ({ signal }) => {
355 preparationEntered.resolve(signal);
356 return preparation.promise;
357 },
358 }),
359 });
360 const firstStart = first.controller.start();
361 const signal = await preparationEntered.promise;
362 first.controller.cancel();
363 expect(signal.aborted).toBe(true);
364
365 const next = createHarness();
366 const nextStart = next.controller.start();
367 expect(next.controller.currentState.phase).toBe("preparing");
368 expect(next.recorder.prepareToRecordAsync).not.toHaveBeenCalled();
369
370 preparation.resolve(preparedTranscription());
371 await firstStart;
372 expect(first.recorder.record).not.toHaveBeenCalled();
373 await nextStart;
374 expect(next.controller.currentState.phase).toBe("recording");
375 await next.controller.interruptRecording();
376 });
377
378 it("still rejects a second start while the first recording is active", async () => {
379 const first = createHarness();
380 await first.controller.start();
381 const next = createHarness();
382 await next.controller.start();
383 expect(next.controller.currentState.error).toContain("already active");
384 expect(next.recorder.record).not.toHaveBeenCalled();
385 await first.controller.interruptRecording();
386 });
387
388 it("does not start a canceled waiter or let it release another recording", async () => {
389 const preparation = deferred<PreparedVoiceTranscription>();
390 const preparationEntered = deferred<void>();
391 const first = createHarness({
392 getTranscriber: () => ({
393 prepare: () => {
394 preparationEntered.resolve(undefined);
395 return preparation.promise;
396 },
397 }),
398 });
399 const firstStart = first.controller.start();
400 await preparationEntered.promise;
401 first.controller.dispose();
402
403 const next = createHarness();
404 const canceledStart = next.controller.start();
405 next.controller.cancel();
406 const nextStart = next.controller.start();
407 preparation.resolve(preparedTranscription());
408 await Promise.all([firstStart, canceledStart, nextStart]);
409
410 expect(next.recorder.record).toHaveBeenCalledTimes(1);
411 expect(next.deleted).toEqual([]);
412 const blocked = createHarness();
413 await blocked.controller.start();
414 expect(blocked.controller.currentState.error).toContain("already active");
415 await next.controller.interruptRecording();
416 });
417
418 it("releases an abandoned recording even if its native recorder was already disposed", async () => {
419 const harness = createHarness();
420 await harness.controller.start();
421 harness.recorder.stop.mockRejectedValueOnce(new Error("recorder released"));
422 Object.defineProperty(harness.recorder, "uri", {
423 get() {
424 throw new Error("recorder released");
425 },
426 });
427
428 await expect(harness.controller.interruptRecording()).resolves.toBeUndefined();
429 expect(harness.deleted).toEqual(["file:///voice.m4a"]);
430 const next = createHarness();
431 await next.controller.start();
432 expect(next.controller.currentState.phase).toBe("recording");
433 await next.controller.interruptRecording();
434 });
435
436 it("keeps the new abort controller when restarting the same composer after cancellation", async () => {
437 const transcription = deferred<string>();
438 const transcriptionEntered = deferred<void>();
439 const prepare = vi
440 .fn<VoiceTranscriber["prepare"]>()
441 .mockResolvedValueOnce(
442 preparedTranscription(() => {
443 transcriptionEntered.resolve(undefined);
444 return transcription.promise;
445 }),
446 )
447 .mockResolvedValue(preparedTranscription());
448 const harness = createHarness({ getTranscriber: () => ({ prepare }) });
449 await harness.controller.start();
450 const stopping = harness.controller.stop();
451 await transcriptionEntered.promise;
452 harness.controller.cancel();
453 const restarting = harness.controller.start();
454 transcription.resolve("late text");
455 await Promise.all([stopping, restarting]);
456 await harness.controller.stop();
457
458 expect(harness.commits).toEqual([
459 { text: "hello new text", selection: { start: 14, end: 14 } },
460 ]);
461 expect(harness.controller.currentState.phase).toBe("idle");
462 });
463
464 it("does not start the microphone for an owner that changed during preparation", async () => {
465 const preparation = deferred<PreparedVoiceTranscription>();
466 const preparationEntered = deferred<void>();
467 const harness = createHarness({
468 getTranscriber: () => ({
469 prepare: () => {
470 preparationEntered.resolve(undefined);
471 return preparation.promise;
472 },
473 }),
474 });
475 const starting = harness.controller.start();
476 await preparationEntered.promise;
477 harness.setDraft(draft({ ownerKey: "environment:other-thread", text: "other draft" }));
478 preparation.resolve(preparedTranscription());
479 await starting;
480
481 expect(harness.recorder.record).not.toHaveBeenCalled();
482 expect(harness.controller.currentState.error).toContain("no longer available");
483 });
484
485 it("discards recorder errors and audio interruptions without transcribing", async () => {
486 const transcribe = vi.fn(async () => "ignored");
487 const preparationEntered = deferred<AbortSignal>();
488 const harness = createHarness({
489 getTranscriber: () => ({
490 prepare: async ({ signal }) => {
491 preparationEntered.resolve(signal);
492 return preparedTranscription(transcribe);
493 },
494 }),
495 });
496 await harness.controller.start();
497 const signal = await preparationEntered.promise;
498 harness.recorder.uri = "file:///reset-empty.m4a";
499 await harness.controller.handleRecorderStatus({
500 isFinished: true,
501 hasError: true,
502 error: "Audio route changed",
503 url: "file:///voice.m4a",
504 });
505
506 expect(harness.commits).toEqual([]);
507 expect(transcribe).not.toHaveBeenCalled();
508 expect(signal.aborted).toBe(true);
509 expect(harness.controller.currentState.error).toBe("Audio route changed");
510 expect(harness.deleted).toEqual(["file:///voice.m4a", "file:///reset-empty.m4a"]);
511 });
512
513 it("cancels preparation when the app reaches the background", async () => {
514 const preparation = deferred<PreparedVoiceTranscription>();
515 const preparationEntered = deferred<AbortSignal>();
516 const harness = createHarness({
517 getTranscriber: () => ({
518 prepare: ({ signal }) => {
519 preparationEntered.resolve(signal);
520 return preparation.promise;
521 },
522 }),
523 });
524 const starting = harness.controller.start();
525 const signal = await preparationEntered.promise;
526 harness.controller.appMovedToBackground();
527 expect(signal.aborted).toBe(true);
528 preparation.resolve(preparedTranscription());
529 await starting;
530
531 expect(harness.recorder.record).not.toHaveBeenCalled();
532 expect(harness.controller.currentState.error).toContain("background");
533 });
534});