Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

controller.test.ts

857 lines30.6 KB

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 {
13 VoiceTranscriptionError,
14 type PreparedVoiceTranscription,
15 type VoiceTranscriber,
16} from "./transcription.ts";
17​
18function deferred<T>() {
19 let resolve!: (value: T) => void;
20 let reject!: (error: unknown) => void;
21 const promise = new Promise<T>((resolvePromise, rejectPromise) => {
22 resolve = resolvePromise;
23 reject = rejectPromise;
24 });
25 return { promise, resolve, reject };
27​
28class TestRecorder implements VoiceRecorder {
29 uri: string | null = "file:///voice.m4a";
30 readonly prepareToRecordAsync = vi.fn(async () => undefined);
31 readonly record = vi.fn();
32 readonly stop = vi.fn(async () => undefined);
34​
35function preparedTranscription(
36 transcribe: PreparedVoiceTranscription["transcribe"] = async () => "new text",
37): PreparedVoiceTranscription {
38 return { locale: "en-US", transcribe };
40​
41function preparedStreamingTranscription(
42 finish: (options: { readonly signal: AbortSignal }) => Promise<string>,
43): PreparedVoiceTranscription {
44 return { ...preparedTranscription(), streaming: { finish } };
46​
47function draft(overrides: Partial<VoiceDraftSnapshot> = {}): VoiceDraftSnapshot {
48 return {
49 ownerKey: "environment:thread",
50 text: "hello world",
51 selection: { start: 6, end: 11 },
52 revision: 1,
53 ...overrides,
54 };
56​
57function createHarness(
58 overrides: Partial<VoiceInputControllerDependencies> = {},
59 initialDraft = draft(),
60) {
61 const recorder = new TestRecorder();
62 let currentDraft: VoiceDraftSnapshot | null = initialDraft;
63 const commits: Array<{ text: string; selection: { start: number; end: number } }> = [];
64 const deleted: string[] = [];
65 const dependencies: VoiceInputControllerDependencies = {
66 recorder,
67 getTranscriber: () => ({ prepare: async () => preparedTranscription() }),
68 requestPermission: async () => ({ granted: true, canAskAgain: true }),
69 configureRecording: async () => undefined,
70 releaseRecording: async () => undefined,
71 deleteRecording: (uri) => deleted.push(uri),
72 readDraft: () => currentDraft,
73 commitDraft: (text, selection) => commits.push({ text, selection }),
74 onStateChange: vi.fn(),
75 ...overrides,
76 };
77 return {
78 controller: new VoiceInputController(dependencies),
79 recorder,
80 commits,
81 deleted,
82 setDraft: (next: VoiceDraftSnapshot | null) => {
83 currentDraft = next;
84 },
85 };
87​
88describe("environment voice input", () => {
89 beforeEach(() => resetVoiceInputGlobalsForTests());
90​
91 it("retries failed batch audio without recording again, then deletes it", async () => {
92 const transcribe = vi
93 .fn<PreparedVoiceTranscription["transcribe"]>()
94 .mockRejectedValueOnce(new Error("inference failed"))
95 .mockResolvedValueOnce("recovered text");
96 const harness = createHarness({
97 retryFailedRecording: true,
98 getTranscriber: () => ({ prepare: async () => preparedTranscription(transcribe) }),
99 });
100 await harness.controller.start();
101 await harness.controller.stop();
102 expect(harness.controller.currentState.phase).toBe("error");
103 expect(harness.deleted).toEqual([]);
104​
105 harness.setDraft(draft({ text: "updated ", revision: 2, selection: { start: 8, end: 8 } }));
106 await harness.controller.start();
107 expect(transcribe.mock.calls.map(([uri]) => uri)).toEqual([
108 "file:///voice.m4a",
109 "file:///voice.m4a",
110 ]);
111 expect(harness.recorder.record).toHaveBeenCalledOnce();
112 expect(harness.commits[0]?.text).toBe("updated recovered text");
113 expect(harness.deleted).toEqual(["file:///voice.m4a"]);
114 });
115​
116 it("deletes retained failed audio when the user cancels instead of retrying", async () => {
117 const harness = createHarness({
118 retryFailedRecording: true,
119 getTranscriber: () => ({
120 prepare: async () =>
121 preparedTranscription(async () => {
122 throw new Error("failed");
123 }),
124 }),
125 });
126 await harness.controller.start();
127 await harness.controller.stop();
128 harness.controller.cancel();
129 expect(harness.deleted).toEqual(["file:///voice.m4a"]);
130 });
131​
132 it("flushes capture before finishing a stream and commits once without a file", async () => {
133 const events: string[] = [];
134 const harness = createHarness({
135 getTranscriber: () => ({
136 prepare: async () =>
137 preparedStreamingTranscription(async () => {
138 events.push("finish");
139 return "new text";
140 }),
141 }),
142 });
143 harness.recorder.uri = null;
144 harness.recorder.stop.mockImplementation(async () => {
145 events.push("flush");
146 });
147 await harness.controller.start();
148 await harness.controller.stop();
149 expect(events).toEqual(["flush", "finish"]);
150 expect(harness.commits).toEqual([
151 { text: "hello new text", selection: { start: 14, end: 14 } },
152 ]);
153 });
154​
155 it("does not commit a late stream result after cancellation", async () => {
156 const started = deferred<void>();
157 const result = deferred<string>();
158 const harness = createHarness({
159 getTranscriber: () => ({
160 prepare: async () =>
161 preparedStreamingTranscription(() => {
162 started.resolve();
163 return result.promise;
164 }),
165 }),
166 });
167 harness.recorder.uri = null;
168 await harness.controller.start();
169 const pending = harness.controller.stop();
170 await started.promise;
171 harness.controller.cancel();
172 result.resolve("late result");
173 await pending;
174 expect(harness.commits).toEqual([]);
175 expect(harness.controller.currentState.phase).toBe("idle");
176 });
177​
178 it("closes a prepared stream when the microphone cannot start", async () => {
179 let signal: AbortSignal | undefined;
180 const harness = createHarness({
181 getTranscriber: () => ({
182 prepare: async (options) => {
183 signal = options.signal;
184 return preparedStreamingTranscription(async () => "unused");
185 },
186 }),
187 });
188 harness.recorder.prepareToRecordAsync.mockRejectedValue(new Error("Microphone unavailable"));
189 await harness.controller.start();
190 expect(signal?.aborted).toBe(true);
191 expect(harness.controller.currentState.phase).toBe("error");
192 });
193​
194 it("commits the raw transcript once when cleanup is skipped", async () => {
195 const started = deferred<void>();
196 const processed = deferred<string>();
197 const harness = createHarness({
198 postProcess: async () => {
199 started.resolve();
200 return processed.promise;
201 },
202 });
203 await harness.controller.start();
204 const stopping = harness.controller.stop();
205 await started.promise;
206 expect(harness.controller.currentState.phase).toBe("post-processing");
207 harness.controller.skipPostProcessing();
208 await stopping;
209 processed.resolve("late text");
210 await processed.promise;
211 expect(harness.commits).toEqual([
212 { text: "hello new text", selection: { start: 14, end: 14 } },
213 ]);
214 });
215​
216 it("falls back to the raw transcript and reports a cleanup failure", async () => {
217 const onPostProcessingError = vi.fn();
218 const harness = createHarness({
219 postProcess: async () => {
220 throw new Error("provider failed");
221 },
222 onPostProcessingError,
223 });
224 await harness.controller.start();
225 await harness.controller.stop();
226 expect(harness.commits).toEqual([
227 { text: "hello new text", selection: { start: 14, end: 14 } },
228 ]);
229 expect(onPostProcessingError).toHaveBeenCalledOnce();
230 });
231});
232​
233describe("resolveTranscriptCommit", () => {
234 it.each([
235 ["Hello", "world", "Hello world"],
236 ["Hello", "世界", "Hello世界"],
237 ["Hello", "𝟚", "Hello 𝟚"],
238 ["你好", "世界", "你好世界"],
239 ])(
240 "preserves script boundaries with an autodetected language: %s + %s",
241 (text, spoken, expected) => {
242 const captured = draft({ text, selection: { start: text.length, end: text.length } });
243 expect(resolveTranscriptCommit(captured, captured, spoken, "auto")).toMatchObject({
244 kind: "commit",
245 text: expected,
246 });
247 },
248 );
249​
250 it.each([
251 ["Korean", "코드를", 3, "검토해 주세요", "ko_KR", "코드를 검토해 주세요"],
252 ["a supplementary letter", "𞤀", 2, "𞤦", "ff-Adlm", "𞤀 𞤦"],
253 ["a trailing combining mark", "नमस्ते", 6, "दुनिया", "hi-IN", "नमस्ते दुनिया"],
254 ["a non-ASCII word after the caret", "Änderungen", 0, "Weitere", "de_DE", "Weitere Änderungen"],
255 ["spaceless Japanese", "修正キャッシュ", 7, "テストも", "ja-JP", "修正キャッシュテストも"],
256 ["spaceless Thai", "โลก", 0, "สวัสดี", "th-TH", "สวัสดีโลก"],
257 ])(
258 "inserts at a caret with the recorded language's word spacing: %s",
259 (_case, text, caret, spoken, locale, expected) => {
260 const captured = draft({ text, selection: { start: caret, end: caret } });
261 expect(resolveTranscriptCommit(captured, captured, spoken, locale)).toMatchObject({
262 kind: "commit",
263 text: expected,
264 });
265 },
266 );
267​
268 it("replaces the recorded UTF-16 selection around emoji and composer tokens", () => {
269 const text = "Fix 🧪 then $review please";
270 const tokenStart = text.indexOf("$review");
271 const captured = draft({
272 text,
273 selection: { start: tokenStart, end: tokenStart + "$review".length },
274 });
275​
276 expect(resolveTranscriptCommit(captured, captured, "use the mobile skill", "en-US")).toEqual({
277 kind: "commit",
278 text: "Fix 🧪 then use the mobile skill please",
279 selection: { start: tokenStart + "use the mobile skill".length, end: tokenStart + 20 },
280 });
281 });
282​
283 it("does not replace text after the owner, text, or revision changes", () => {
284 const captured = draft();
285 expect(
286 resolveTranscriptCommit(captured, draft({ ownerKey: "other" }), "text", "en-US"),
287 ).toEqual({
288 kind: "stale",
289 });
290 expect(resolveTranscriptCommit(captured, draft({ text: "newer" }), "text", "en-US")).toEqual({
291 kind: "stale",
292 });
293 expect(resolveTranscriptCommit(captured, draft({ revision: 2 }), "text", "en-US")).toEqual({
294 kind: "stale",
295 });
296 });
297});
298​
299describe("VoiceInputController", () => {
300 beforeEach(() => resetVoiceInputGlobalsForTests());
301​
302 it("checks support and permission before recording", async () => {
303 const unsupported = createHarness({ getTranscriber: () => null });
304 await unsupported.controller.start();
305 expect(unsupported.controller.currentState.error).toContain("not available");
306 expect(unsupported.recorder.record).not.toHaveBeenCalled();
307​
308 const reason = new VoiceTranscriptionError({
309 code: "unavailable",
310 message: "This device requires iOS 26 or later.",
311 });
312 const configureRecording = vi.fn(async () => undefined);
313 const unavailable = createHarness({
314 configureRecording,
315 getTranscriber: () => ({
316 prepare: async () => {
317 throw reason;
318 },
319 }),
320 });
321 await unavailable.controller.start();
322 expect(unavailable.controller.currentState.error).toBe(reason.message);
323 // Environment and web transcribers gate capture on consent checked during preparation.
324 expect(configureRecording).not.toHaveBeenCalled();
325 expect(unavailable.recorder.record).not.toHaveBeenCalled();
326​
327 const denied = createHarness({
328 requestPermission: async () => ({ granted: false, canAskAgain: false }),
329 });
330 await denied.controller.start();
331 expect(denied.controller.currentState.errorAction).toBe("settings");
332 expect(denied.recorder.record).not.toHaveBeenCalled();
333 });
334​
335 it.each(["permission", "transcription"] as const)(
336 "clears %s errors when switching to another draft",
337 async (failure) => {
338 const harness = createHarness(
339 failure === "permission"
340 ? { requestPermission: async () => ({ granted: false, canAskAgain: false }) }
341 : {
342 getTranscriber: () => ({
343 prepare: async () =>
344 preparedTranscription(async () => {
345 throw new Error("Transcription failed");
346 }),
347 }),
348 },
349 );
350 await harness.controller.start();
351 await harness.controller.stop();
352 expect(harness.controller.currentState).toMatchObject({
353 phase: "error",
354 error: expect.any(String),
355 errorAction: failure === "permission" ? "settings" : "retry",
356 });
357​
358 harness.setDraft(draft({ ownerKey: "environment:other-thread" }));
359 harness.controller.ownerChanged();
360​
361 expect(harness.controller.currentState).toEqual({
362 phase: "idle",
363 error: null,
364 errorAction: null,
365 });
366 expect(harness.commits).toEqual([]);
367 },
368 );
369​
370 it.each(["permission", "preparation", "recording"] as const)(
371 "keeps the selected transcriber when preferences change during %s",
372 async (changeDuring) => {
373 const permission = deferred<{ granted: boolean; canAskAgain: boolean }>();
374 const permissionEntered = deferred<void>();
375 const preparation = deferred<void>();
376 const preparationEntered = deferred<void>();
377 const preparationSignals: AbortSignal[] = [];
378 const transcriptionSignals: AbortSignal[] = [];
379 const transcriber = (text: string): VoiceTranscriber => ({
380 prepare: async ({ signal }) => {
381 preparationSignals.push(signal);
382 preparationEntered.resolve(undefined);
383 await preparation.promise;
384 return preparedTranscription(async (_uri, { signal }) => {
385 transcriptionSignals.push(signal);
386 return text;
387 });
388 },
389 });
390 const first = transcriber("first choice");
391 const second = transcriber("second choice");
392 let selected = first;
393 const harness = createHarness({
394 getTranscriber: () => selected,
395 requestPermission: () => {
396 permissionEntered.resolve(undefined);
397 return permission.promise;
398 },
399 });
400​
401 const starting = harness.controller.start();
402 await permissionEntered.promise;
403 if (changeDuring === "permission") selected = second;
404 permission.resolve({ granted: true, canAskAgain: true });
405 await preparationEntered.promise;
406 if (changeDuring === "preparation") selected = second;
407 preparation.resolve(undefined);
408 await starting;
409 if (changeDuring === "recording") selected = second;
410 await harness.controller.stop();
411​
412 expect(harness.commits.map((commit) => commit.text)).toEqual(["hello first choice"]);
413​
414 await harness.controller.start();
415 await harness.controller.stop();
416​
417 expect(harness.commits.map((commit) => commit.text)).toEqual([
418 "hello first choice",
419 "hello second choice",
420 ]);
421 expect(preparationSignals).toHaveLength(2);
422 expect(transcriptionSignals).toHaveLength(2);
423 expect(transcriptionSignals[0]).toBe(preparationSignals[0]);
424 expect(transcriptionSignals[1]).toBe(preparationSignals[1]);
425 expect(preparationSignals[1]).not.toBe(preparationSignals[0]);
426 },
427 );
428​
429 it("uses the native five-minute cap and commits one final transcript", async () => {
430 const harness = createHarness();
431 await harness.controller.start();
432 expect(harness.recorder.record).toHaveBeenCalledWith({
433 forDuration: VOICE_RECORDING_LIMIT_SECONDS,
434 });
435 await harness.controller.handleRecorderStatus({
436 isFinished: true,
437 hasError: false,
438 error: null,
439 url: "file:///previous-recording.m4a",
440 });
441 expect(harness.controller.currentState.phase).toBe("recording");
442​
443 const stopping = harness.controller.stop();
444 harness.controller.handleRecorderStatus({
445 isFinished: true,
446 hasError: false,
447 error: null,
448 url: "file:///voice.m4a",
449 });
450 await stopping;
451​
452 expect(harness.commits).toEqual([
453 { text: "hello new text", selection: { start: 14, end: 14 } },
454 ]);
455 expect(harness.deleted).toEqual(["file:///voice.m4a"]);
456 });
457​
458 it.each(["cancel", "dispose", "ownerChanged"] as const)(
459 "queues the next recording after %s until transcription and audio cleanup settle",
460 async (action) => {
461 const transcription = deferred<string>();
462 const transcriptionEntered = deferred<AbortSignal>();
463 const audioRelease = deferred<void>();
464 const audioReleaseEntered = deferred<void>();
465 const releaseRecording = vi
466 .fn<() => Promise<void>>()
467 .mockRejectedValueOnce(new Error("busy"))
468 .mockImplementationOnce(() => {
469 audioReleaseEntered.resolve(undefined);
470 return audioRelease.promise;
471 });
472 const harness = createHarness({
473 releaseRecording,
474 getTranscriber: () => ({
475 prepare: async () =>
476 preparedTranscription((_uri, { signal }) => {
477 transcriptionEntered.resolve(signal);
478 return transcription.promise;
479 }),
480 }),
481 });
482 await harness.controller.start();
483 const stopping = harness.controller.stop();
484 const signal = await transcriptionEntered.promise;
485 expect(signal.aborted).toBe(false);
486 if (action === "ownerChanged") {
487 harness.setDraft(draft({ ownerKey: "environment:other-thread" }));
488 }
489 harness.controller[action]();
490 expect(signal.aborted).toBe(true);
491​
492 const prepare = vi.fn(async () => preparedTranscription());
493 const next = createHarness({ getTranscriber: () => ({ prepare }) });
494 const nextStart = next.controller.start();
495 expect(next.controller.currentState).toEqual({
496 phase: "preparing",
497 error: null,
498 errorAction: null,
499 });
500 expect(prepare).not.toHaveBeenCalled();
501 expect(next.recorder.record).not.toHaveBeenCalled();
502​
503 transcription.resolve("late text");
504 await audioReleaseEntered.promise;
505 expect(prepare).not.toHaveBeenCalled();
506 expect(next.recorder.prepareToRecordAsync).not.toHaveBeenCalled();
507 audioRelease.resolve(undefined);
508 await stopping;
509 await nextStart;
510​
511 expect(harness.commits).toEqual([]);
512 expect(harness.deleted).toEqual(["file:///voice.m4a"]);
513 expect(harness.controller.currentState.phase).toBe("idle");
514​
515 expect(next.controller.currentState.phase).toBe("recording");
516 expect(prepare).toHaveBeenCalledTimes(1);
517 await next.controller.interruptRecording();
518 },
519 );
520​
521 it("releases the microphone before transcription starts", async () => {
522 const events: string[] = [];
523 const harness = createHarness({
524 releaseRecording: async () => {
525 events.push("released");
526 },
527 getTranscriber: () => ({
528 prepare: async () =>
529 preparedTranscription(async () => {
530 events.push("transcribed");
531 return "done";
532 }),
533 }),
534 });
535 await harness.controller.start();
536 await harness.controller.stop();
537​
538 expect(events).toEqual(["released", "transcribed"]);
539 });
540​
541 it("starts streaming transcription during recording and commits only after stopping", async () => {
542 const transcript = deferred<string>();
543 const start = vi.fn(() => transcript.promise);
544 const transcribe = vi.fn(async () => "replayed audio");
545 const harness = createHarness({
546 getTranscriber: () => ({
547 prepare: async () => ({ locale: "en-US", start, transcribe }),
548 }),
549 });
550 await harness.controller.start();
551 expect(start).toHaveBeenCalledWith("file:///voice.m4a", {
552 signal: expect.any(AbortSignal),
553 });
554 expect(harness.controller.currentState.phase).toBe("recording");
555 expect(harness.commits).toEqual([]);
556​
557 const stopping = harness.controller.stop();
558 transcript.resolve("opening middle and final words");
559 await stopping;
560 expect(harness.commits[0]?.text).toBe("hello opening middle and final words");
561 expect(transcribe).not.toHaveBeenCalled();
562 expect(harness.deleted).toEqual(["file:///voice.m4a"]);
563 });
564​
565 it("waits for canceled live inference before deleting its recording or starting again", async () => {
566 const transcript = deferred<string>();
567 const released = deferred<void>();
568 let signal: AbortSignal | undefined;
569 const harness = createHarness({
570 getTranscriber: () => ({
571 prepare: async () => ({
572 ...preparedTranscription(),
573 start: (_uri: string, options: { signal: AbortSignal }) => {
574 signal = options.signal;
575 return transcript.promise;
576 },
577 }),
578 }),
579 deleteRecording: () => released.resolve(undefined),
580 });
581 await harness.controller.start();
582 expect(signal).toBeDefined();
583 harness.controller.cancel();
584 expect(signal?.aborted).toBe(true);
585 const next = createHarness();
586 const nextStart = next.controller.start();
587 expect(next.recorder.record).not.toHaveBeenCalled();
588​
589 transcript.resolve("discard this");
590 await released.promise;
591 await nextStart;
592 expect(harness.commits).toEqual([]);
593 expect(next.controller.currentState.phase).toBe("recording");
594 await next.controller.interruptRecording();
595 });
596​
597 it("stops recording after a live inference failure and preserves the draft for retry", async () => {
598 const transcript = deferred<string>();
599 const released = deferred<void>();
600 const harness = createHarness({
601 getTranscriber: () => ({
602 prepare: async () => ({ ...preparedTranscription(), start: () => transcript.promise }),
603 }),
604 deleteRecording: () => released.resolve(undefined),
605 });
606 await harness.controller.start();
607 transcript.reject(
608 new VoiceTranscriptionError({
609 code: "transcription-failed",
610 message: "Speech quota reached.",
611 }),
612 );
613 await released.promise;
614 expect(harness.controller.currentState).toMatchObject({
615 phase: "error",
616 error: "Speech quota reached.",
617 errorAction: "retry",
618 });
619 expect(harness.recorder.stop).toHaveBeenCalled();
620 expect(harness.commits).toEqual([]);
621 const next = createHarness();
622 await next.controller.start();
623 expect(next.controller.currentState.phase).toBe("recording");
624 await next.controller.interruptRecording();
625 });
626​
627 it("ignores a late transcript after the draft owner changes", async () => {
628 const transcription = deferred<string>();
629 const transcriptionEntered = deferred<void>();
630 const harness = createHarness({
631 getTranscriber: () => ({
632 prepare: async () =>
633 preparedTranscription(() => {
634 transcriptionEntered.resolve(undefined);
635 return transcription.promise;
636 }),
637 }),
638 });
639 await harness.controller.start();
640 const stopping = harness.controller.stop();
641 await transcriptionEntered.promise;
642 harness.setDraft(draft({ ownerKey: "environment:other-thread" }));
643 transcription.resolve("late text");
644 await stopping;
645​
646 expect(harness.commits).toEqual([]);
647 expect(harness.controller.currentState.error).toContain("draft changed");
648 });
649​
650 it("queues the next recording until canceled preparation settles", async () => {
651 const preparation = deferred<PreparedVoiceTranscription>();
652 const preparationEntered = deferred<AbortSignal>();
653 const first = createHarness({
654 getTranscriber: () => ({
655 prepare: ({ signal }) => {
656 preparationEntered.resolve(signal);
657 return preparation.promise;
658 },
659 }),
660 });
661 const firstStart = first.controller.start();
662 const signal = await preparationEntered.promise;
663 first.controller.cancel();
664 expect(signal.aborted).toBe(true);
665​
666 const next = createHarness();
667 const nextStart = next.controller.start();
668 expect(next.controller.currentState.phase).toBe("preparing");
669 expect(next.recorder.prepareToRecordAsync).not.toHaveBeenCalled();
670​
671 preparation.resolve(preparedTranscription());
672 await firstStart;
673 expect(first.recorder.record).not.toHaveBeenCalled();
674 await nextStart;
675 expect(next.controller.currentState.phase).toBe("recording");
676 await next.controller.interruptRecording();
677 });
678​
679 it("still rejects a second start while the first recording is active", async () => {
680 const first = createHarness();
681 await first.controller.start();
682 const next = createHarness();
683 await next.controller.start();
684 expect(next.controller.currentState.error).toContain("already active");
685 expect(next.recorder.record).not.toHaveBeenCalled();
686 await first.controller.interruptRecording();
687 });
688​
689 it("does not start a canceled waiter or let it release another recording", async () => {
690 const preparation = deferred<PreparedVoiceTranscription>();
691 const preparationEntered = deferred<void>();
692 const first = createHarness({
693 getTranscriber: () => ({
694 prepare: () => {
695 preparationEntered.resolve(undefined);
696 return preparation.promise;
697 },
698 }),
699 });
700 const firstStart = first.controller.start();
701 await preparationEntered.promise;
702 first.controller.dispose();
703​
704 const next = createHarness();
705 const canceledStart = next.controller.start();
706 next.controller.cancel();
707 const nextStart = next.controller.start();
708 preparation.resolve(preparedTranscription());
709 await Promise.all([firstStart, canceledStart, nextStart]);
710​
711 expect(next.recorder.record).toHaveBeenCalledTimes(1);
712 expect(next.deleted).toEqual([]);
713 const blocked = createHarness();
714 await blocked.controller.start();
715 expect(blocked.controller.currentState.error).toContain("already active");
716 await next.controller.interruptRecording();
717 });
718​
719 it("releases an abandoned recording even if its native recorder was already disposed", async () => {
720 const harness = createHarness();
721 await harness.controller.start();
722 harness.recorder.stop.mockRejectedValueOnce(new Error("recorder released"));
723 Object.defineProperty(harness.recorder, "uri", {
724 get() {
725 throw new Error("recorder released");
726 },
727 });
728​
729 await expect(harness.controller.interruptRecording()).resolves.toBeUndefined();
730 expect(harness.deleted).toEqual(["file:///voice.m4a"]);
731 const next = createHarness();
732 await next.controller.start();
733 expect(next.controller.currentState.phase).toBe("recording");
734 await next.controller.interruptRecording();
735 });
736​
737 it("keeps the new abort controller when restarting the same composer after cancellation", async () => {
738 const transcription = deferred<string>();
739 const transcriptionEntered = deferred<void>();
740 const prepare = vi
741 .fn<VoiceTranscriber["prepare"]>()
742 .mockResolvedValueOnce(
743 preparedTranscription(() => {
744 transcriptionEntered.resolve(undefined);
745 return transcription.promise;
746 }),
747 )
748 .mockResolvedValue(preparedTranscription());
749 const harness = createHarness({ getTranscriber: () => ({ prepare }) });
750 await harness.controller.start();
751 const stopping = harness.controller.stop();
752 await transcriptionEntered.promise;
753 harness.controller.cancel();
754 const restarting = harness.controller.start();
755 transcription.resolve("late text");
756 await Promise.all([stopping, restarting]);
757 await harness.controller.stop();
758​
759 expect(harness.commits).toEqual([
760 { text: "hello new text", selection: { start: 14, end: 14 } },
761 ]);
762 expect(harness.controller.currentState.phase).toBe("idle");
763 });
764​
765 it("does not start the microphone for an owner that changed during preparation", async () => {
766 const preparation = deferred<PreparedVoiceTranscription>();
767 const preparationEntered = deferred<void>();
768 const harness = createHarness({
769 getTranscriber: () => ({
770 prepare: () => {
771 preparationEntered.resolve(undefined);
772 return preparation.promise;
773 },
774 }),
775 });
776 const starting = harness.controller.start();
777 await preparationEntered.promise;
778 harness.setDraft(draft({ ownerKey: "environment:other-thread", text: "other draft" }));
779 preparation.resolve(preparedTranscription());
780 await starting;
781​
782 expect(harness.recorder.record).not.toHaveBeenCalled();
783 expect(harness.controller.currentState.error).toContain("no longer available");
784 });
785​
786 it("discards recorder errors and audio interruptions without transcribing", async () => {
787 const transcribe = vi.fn(async () => "ignored");
788 const preparationEntered = deferred<AbortSignal>();
789 const harness = createHarness({
790 getTranscriber: () => ({
791 prepare: async ({ signal }) => {
792 preparationEntered.resolve(signal);
793 return preparedTranscription(transcribe);
794 },
795 }),
796 });
797 await harness.controller.start();
798 const signal = await preparationEntered.promise;
799 harness.recorder.uri = "file:///reset-empty.m4a";
800 await harness.controller.handleRecorderStatus({
801 isFinished: true,
802 hasError: true,
803 error: "Audio route changed",
804 url: "file:///voice.m4a",
805 });
806​
807 expect(harness.commits).toEqual([]);
808 expect(transcribe).not.toHaveBeenCalled();
809 expect(signal.aborted).toBe(true);
810 expect(harness.controller.currentState.error).toBe("Audio route changed");
811 expect(harness.deleted).toEqual(["file:///voice.m4a", "file:///reset-empty.m4a"]);
812 });
813​
814 it("never starts capture after the stream fails while the microphone is opening", async () => {
815 const opened = deferred<void>();
816 const waiting = deferred<void>();
817 const releaseRecording = vi.fn(async () => {});
818 const harness = createHarness({ releaseRecording });
819 harness.recorder.prepareToRecordAsync.mockImplementationOnce(() => {
820 waiting.resolve();
821 return opened.promise.then(() => undefined);
822 });
823 const starting = harness.controller.start();
824 await waiting.promise;
825 harness.controller.interruptRecording("Environment is busy");
826 opened.resolve();
827 await starting;
828 expect(harness.recorder.record).not.toHaveBeenCalled();
829 expect(harness.controller.currentState).toMatchObject({
830 phase: "error",
831 error: "Environment is busy",
832 });
833 expect(releaseRecording).toHaveBeenCalledOnce();
834 });
835​
836 it("cancels preparation when the app reaches the background", async () => {
837 const preparation = deferred<PreparedVoiceTranscription>();
838 const preparationEntered = deferred<AbortSignal>();
839 const harness = createHarness({
840 getTranscriber: () => ({
841 prepare: ({ signal }) => {
842 preparationEntered.resolve(signal);
843 return preparation.promise;
844 },
845 }),
846 });
847 const starting = harness.controller.start();
848 const signal = await preparationEntered.promise;
849 harness.controller.appMovedToBackground();
850 expect(signal.aborted).toBe(true);
851 preparation.resolve(preparedTranscription());
852 await starting;
853​
854 expect(harness.recorder.record).not.toHaveBeenCalled();
855 expect(harness.controller.currentState.error).toContain("background");
856 });
857});