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

controller.test.ts

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