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

controller.test.ts

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