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

controller.test.ts

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