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

controller.test.ts

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