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