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

SpeechService.test.ts

947 lines37.5 KB

1import { beforeEach, expect, vi } from "vite-plus/test";
2import { it } from "@effect/vitest";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as Effect from "effect/Effect";
5import * as Deferred from "effect/Deferred";
6import * as TestClock from "effect/testing/TestClock";
7import * as Fiber from "effect/Fiber";
8import * as Layer from "effect/Layer";
9import * as Result from "effect/Result";
10import * as Scheduler from "effect/Scheduler";
11import * as Scope from "effect/Scope";
12import * as Exit from "effect/Exit";
13import * as PlatformError from "effect/PlatformError";
14import * as HostProcess from "@t3tools/shared/HostProcess";
15import { DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS } from "@t3tools/contracts";
16import * as ServerSettings from "../serverSettings.ts";
17import { listNativeSpeechGpuDevices } from "./native.ts";
18import * as SpeechModelStore from "./SpeechModelStore.ts";
19import * as SpeechService from "./SpeechService.ts";
20import { SILERO_VAD } from "./silero.ts";
21​
22const native = vi.hoisted(() => ({
23 backend: "Vulkan0",
24 supportsStreaming: true,
25 supportsLongForm: false,
26 supportsTranslation: true,
27 supportsVocabulary: false,
28 languages: ["en", "fr"] as readonly string[],
29 begin: vi.fn(async (_options?: unknown, _filterSilence?: boolean, _vadPath?: string) => {}),
30 feed: vi.fn(async (_pcm: Float32Array) => ({
31 revision: 1,
32 text: { committed: "", tentative: "hello" },
33 })),
34 finish: vi.fn(async () => "hello"),
35 reset: vi.fn(async () => {}),
36 dispose: vi.fn(),
37 transcribe: vi.fn(async (_pcm: Float32Array, _options?: unknown) => ({ text: "hello" })),
38}));
39const loadNative = vi.hoisted(() =>
40 vi.fn(
41 async (
42 _path: string,
43 _signal: AbortSignal,
44 _moduleUrl?: string,
45 backend: "auto" | "cpu" = "auto",
46 ) => {
47 native.backend = backend === "cpu" ? "CPU" : "Vulkan0";
48 return native;
49 },
50 ),
51);
52const readyModels = vi.hoisted(() => new Set(["test-model", "fallback-model"]));
53const modelDefinitions = vi.hoisted(() => [
54 {
55 id: "test-model",
56 name: "test",
57 description: "test",
58 size: 4,
59 languages: ["en", "fr"],
60 accuracy: 1,
61 benchmark: {
62 accuracy: { en: { grade: "A-", errorPercent: 4 } },
63 secondsPer30s: { cpu: 3, accelerated: 1.2 },
64 },
65 speed: 1,
66 recommended: true,
67 supportsStreaming: true,
68 supportsLanguageDetection: false,
69 supportsTranslation: true,
70 },
71 {
72 id: "fallback-model",
73 name: "fallback",
74 description: "fallback",
75 size: 8,
76 languages: ["en", "fr"],
77 accuracy: 2,
78 speed: 2,
79 recommended: false,
80 supportsStreaming: false,
81 supportsLanguageDetection: false,
82 supportsTranslation: true,
83 },
84]);
85vi.mock("./native.ts", () => ({
86 loadNativeSpeechModel: loadNative,
87 listNativeSpeechGpuDevices: vi.fn(async () => [{ id: '["vulkan","gpu-1"]', name: "Test GPU" }]),
88}));
89vi.mock("./model.ts", () => ({
90 DEFAULT_SPEECH_MODEL_ID: "test-model",
91 SPEECH_MODELS: modelDefinitions,
92 getSpeechModel: (modelId: string) => modelDefinitions.find((model) => model.id === modelId),
93 effectiveSpeechLanguage: (model: { languages: string[] }, intent: string) =>
94 intent !== "auto" && model.languages.includes(intent) ? intent : "en",
95}));
96const download = vi.fn<SpeechModelStore.SpeechModelStore["Service"]["download"]>(() =>
97 Effect.succeed("test.gguf"),
98);
99const store = Layer.succeed(
100 SpeechModelStore.SpeechModelStore,
101 SpeechModelStore.SpeechModelStore.of({
102 isReady: (model) => Effect.sync(() => readyModels.has(model.id)),
103 installedPath: (model) =>
104 Effect.sync(() => (readyModels.has(model.id) ? "test.gguf" : undefined)),
105 download,
106 link: () => Effect.succeed([]),
107 linkedFrom: () => Effect.undefined,
108 remove: (model) =>
109 Effect.sync(() => {
110 readyModels.delete(model.id);
111 }),
112 }),
113);
114const layer = SpeechService.layer.pipe(
115 Layer.provide(store),
116 Layer.provideMerge(ServerSettings.layerTest({ speechModelId: "test-model" })),
117 Layer.provide(NodeServices.layer),
118);
119const pcm = () => new Uint8Array(new Float32Array([0.25]).buffer);
120​
121beforeEach(() => {
122 vi.clearAllMocks();
123 loadNative.mockReset();
124 native.finish.mockReset();
125 native.backend = "Vulkan0";
126 native.supportsVocabulary = false;
127 native.supportsStreaming = true;
128 native.languages = ["en", "fr"];
129 readyModels.clear();
130 readyModels.add("test-model");
131 readyModels.add("fallback-model");
132});
133​
134it("decodes a pooled Node Buffer without reading adjacent bytes", () => {
135 const pool = Buffer.allocUnsafe(64);
136 pool.fill(0xff);
137 Buffer.from(new Float32Array([0.25]).buffer).copy(pool, 20);
138 expect([...SpeechService.decodeSpeechPcm(pool.subarray(20, 24))]).toEqual([0.25]);
139});
140​
141it("rejects empty, misaligned, non-finite, and oversized PCM as invalid audio", () => {
142 for (const input of [
143 new Uint8Array(),
144 new Uint8Array(3),
145 new Uint8Array(new Float32Array([Number.NaN]).buffer),
146 new Uint8Array(SpeechService.MAX_SPEECH_BYTES + 4),
147 ]) {
148 expect(() => SpeechService.decodeSpeechPcm(input)).toThrow(
149 expect.objectContaining({ _tag: "SpeechInvalidAudioError" }),
150 );
151 }
152});
153​
154it.effect.each(["CPU", "Vulkan0"])(
155 "prepares a batch model on %s before audio arrives and reuses it for transcription",
156 (backend) =>
157 Effect.gen(function* () {
158 const speech = yield* SpeechService.SpeechService;
159 yield* speech.selectModel("fallback-model");
160 loadNative.mockImplementationOnce(async () => {
161 native.backend = backend;
162 return native;
163 });
164 yield* speech.prepareModel;
165 expect(yield* speech.status).toMatchObject({
166 benchmarkTier: backend === "CPU" ? "cpu" : "accelerated",
167 });
168 expect(loadNative).toHaveBeenCalledTimes(1);
169 expect(native.transcribe).not.toHaveBeenCalled();
170 native.supportsStreaming = false;
171 yield* Effect.gen(function* () {
172 const stream = yield* speech.startStream({
173 ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
174 speechLanguage: "fr",
175 speechTranslateToEnglish: true,
176 speechSilenceFiltering: false,
177 });
178 expect(native.begin).toHaveBeenLastCalledWith(
179 { timestamps: "none", language: "fr", task: "translate", targetLanguage: "en" },
180 false,
181 "test.gguf",
182 );
183 expect(yield* stream.finish).toBe("hello");
184 }).pipe(Effect.scoped);
185 expect(yield* speech.transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS)).toBe("hello");
186 expect(loadNative).toHaveBeenCalledTimes(1);
187 }).pipe(Effect.provide(layer)),
188);
189​
190it.effect("sends the chosen language in the spelling the loaded model advertises", () =>
191 Effect.gen(function* () {
192 const speech = yield* SpeechService.SpeechService;
193 // Nemotron Streaming 3.5 advertises regional tags while the catalog lists bare codes.
194 native.languages = ["en-US", "en-GB", "fr-FR"];
195 yield* Effect.gen(function* () {
196 const stream = yield* speech.startStream({
197 ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
198 speechLanguage: "fr",
199 });
200 expect(native.begin).toHaveBeenLastCalledWith(
201 { timestamps: "none", language: "fr-FR" },
202 true,
203 "test.gguf",
204 );
205 expect(yield* stream.finish).toBe("hello");
206 }).pipe(Effect.scoped);
207 native.supportsStreaming = false;
208 expect(
209 yield* speech.transcribe(pcm(), {
210 ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
211 speechLanguage: "fr",
212 }),
213 ).toBe("hello");
214 expect(native.transcribe).toHaveBeenLastCalledWith(
215 expect.any(Float32Array),
216 { timestamps: "none", language: "fr-FR" },
217 true,
218 "test.gguf",
219 );
220 // A language the model does not advertise reaches it unchanged, so the model reports it.
221 yield* speech.updateAcceleration("cpu");
222 native.languages = ["en-US"];
223 native.transcribe.mockRejectedValueOnce(new Error("transcribe_run: unsupported language"));
224 const rejected = yield* Effect.result(
225 speech.transcribe(pcm(), { ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, speechLanguage: "fr" }),
226 );
227 expect(Result.isFailure(rejected) && rejected.failure).toMatchObject({
228 _tag: "SpeechOperationError",
229 operation: "inference",
230 });
231 expect(native.transcribe).toHaveBeenLastCalledWith(
232 expect.any(Float32Array),
233 { timestamps: "none", language: "fr" },
234 true,
235 "test.gguf",
236 );
237 expect(loadNative.mock.calls.map(([path, , , acceleration]) => [path, acceleration])).toEqual([
238 ["test.gguf", "auto"],
239 ["test.gguf", "cpu"],
240 ]);
241 }).pipe(Effect.provide(layer)),
242);
243​
244it.effect.each(["cancellation", "timeout"] as const)(
245 "releases a stalled model preparation on %s",
246 (reason) =>
247 Effect.gen(function* () {
248 const speech = yield* SpeechService.SpeechService;
249 const started = Promise.withResolvers<AbortSignal>();
250 const stalled = Promise.withResolvers<typeof native>();
251 const disposed = Promise.withResolvers<void>();
252 const abandoned = { ...native, dispose: vi.fn(() => disposed.resolve()) };
253 loadNative.mockImplementationOnce((_path, signal) => {
254 started.resolve(signal);
255 return stalled.promise;
256 });
257 const request = yield* speech.prepareModel.pipe(Effect.forkChild);
258 const signal = yield* Effect.promise(() => started.promise);
259 try {
260 if (reason === "cancellation") {
261 yield* Fiber.interrupt(request).pipe(Effect.forkChild({ startImmediately: true }));
262 }
263 yield* TestClock.adjust(reason === "timeout" ? "2 minutes" : 0);
264 expect(signal.aborted).toBe(true);
265 const exit = yield* Fiber.await(request);
266 expect(Exit.isFailure(exit)).toBe(true);
267 if (reason === "timeout") {
268 expect(Exit.findErrorOption(exit)).toMatchObject({
269 value: { _tag: "SpeechOperationError", operation: "model preparation" },
270 });
271 }
272 yield* speech.selectModel("fallback-model");
273 const transcribe = speech.transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS);
274 expect(yield* transcribe).toBe("hello");
275 stalled.resolve(abandoned);
276 yield* Effect.promise(() => disposed.promise);
277 expect(yield* transcribe).toBe("hello");
278 expect(loadNative).toHaveBeenCalledTimes(2);
279 } finally {
280 stalled.resolve(abandoned);
281 }
282 }).pipe(Effect.provide(layer)),
283);
284​
285it.effect("rejects model mutations outside the offered registry", () =>
286 Effect.gen(function* () {
287 const speech = yield* SpeechService.SpeechService;
288 for (const id of [
289 "handy-computer/canary-1b-gguf",
290 "handy-computer/granite-speech-5.0-470m-turboctc-nc-gguf",
291 "unknown-model",
292 ]) {
293 for (const mutation of [speech.downloadModel, speech.selectModel, speech.removeModel]) {
294 const result = yield* Effect.result(mutation(id));
295 expect(Result.isFailure(result) && result.failure).toMatchObject({
296 _tag: "SpeechModelNotFoundError",
297 modelId: id,
298 });
299 }
300 }
301 expect(download).not.toHaveBeenCalled();
302 const current = (yield* speech.models(false)).models.find((model) => model.active);
303 expect(current?.id).toBe("test-model");
304 expect(current).not.toHaveProperty("benchmark");
305 expect(
306 (yield* speech.models(true)).models.find((model) => model.active)?.benchmark?.secondsPer30s,
307 ).toEqual({ cpu: 3, accelerated: 1.2 });
308 }).pipe(Effect.provide(layer)),
309);
310​
311it.effect("keeps a detached download exclusive until the transfer finishes", () =>
312 Effect.gen(function* () {
313 const speech = yield* SpeechService.SpeechService;
314 const started = yield* Deferred.make<void>();
315 const finish = yield* Deferred.make<void>();
316 const helperStarted = yield* Deferred.make<void>();
317 let helperStartedDuringInstall = false;
318 let helperInterrupted = false;
319 download
320 .mockImplementationOnce(() =>
321 Deferred.succeed(started, undefined).pipe(
322 Effect.andThen(Deferred.await(finish)),
323 Effect.as("test.gguf"),
324 ),
325 )
326 .mockImplementationOnce(() =>
327 Deferred.isDone(finish).pipe(
328 Effect.tap((done) =>
329 Effect.sync(() => {
330 helperStartedDuringInstall = !done;
331 }),
332 ),
333 Effect.andThen(Deferred.succeed(helperStarted, undefined)),
334 Effect.andThen(Effect.never),
335 Effect.onInterrupt(() =>
336 Effect.sync(() => {
337 helperInterrupted = true;
338 }),
339 ),
340 ),
341 );
342 const request = yield* speech.downloadModel("test-model").pipe(Effect.forkChild);
343 yield* Deferred.await(started);
344 yield* Deferred.await(helperStarted);
345 yield* Fiber.interrupt(request);
346 yield* Deferred.succeed(finish, undefined);
347 yield* TestClock.adjust("16 seconds");
348 expect(helperInterrupted).toBe(false);
349 const removed = yield* Effect.result(speech.removeModel("test-model"));
350 expect(Result.isFailure(removed) && removed.failure).toMatchObject({ _tag: "SpeechBusyError" });
351 const join = yield* speech
352 .downloadModel("test-model")
353 .pipe(Effect.forkChild({ startImmediately: true }));
354 yield* TestClock.adjust("2 minutes");
355 expect(helperInterrupted).toBe(true);
356 yield* Fiber.join(join);
357 expect(download.mock.calls.map(([model]) => model.id)).toEqual(["test-model", SILERO_VAD.id]);
358 expect(helperStartedDuringInstall).toBe(true);
359 yield* speech.removeModel("test-model");
360 expect(readyModels.has("test-model")).toBe(false);
361 }).pipe(Effect.provide(layer)),
362);
363​
364it.effect("bounds missing Silero recovery during recording and continues with raw audio", () =>
365 Effect.gen(function* () {
366 const helperStarted = yield* Deferred.make<void>();
367 const helperInterrupted = yield* Deferred.make<void>();
368 download.mockImplementationOnce(() =>
369 Deferred.succeed(helperStarted, undefined).pipe(
370 Effect.andThen(Effect.never),
371 Effect.onInterrupt(() => Deferred.succeed(helperInterrupted, undefined)),
372 ),
373 );
374 const speech = yield* SpeechService.SpeechService;
375 const recording = yield* speech
376 .startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS)
377 .pipe(Effect.forkChild);
378 yield* Deferred.await(helperStarted);
379 yield* TestClock.adjust("14999 millis");
380 expect(native.begin).not.toHaveBeenCalled();
381 yield* TestClock.adjust("1 millis");
382 yield* Deferred.await(helperInterrupted);
383 const stream = yield* Fiber.join(recording);
384 expect(native.begin).toHaveBeenLastCalledWith(expect.anything(), true, undefined);
385 yield* stream.feed(pcm());
386 expect(yield* stream.finish).toBe("hello");
387 }).pipe(Effect.scoped, Effect.provide(layer)),
388);
389​
390it.effect("keeps the installed speech model usable when optional Silero acquisition fails", () =>
391 Effect.gen(function* () {
392 download
393 .mockImplementationOnce(() => Effect.succeed("test.gguf"))
394 .mockImplementationOnce(() =>
395 Effect.fail(
396 new PlatformError.PlatformError(
397 new PlatformError.SystemError({
398 _tag: "NotFound",
399 module: "FileSystem",
400 method: "open",
401 }),
402 ),
403 ),
404 );
405 const speech = yield* SpeechService.SpeechService;
406 const installed = yield* speech.downloadModel("test-model");
407 expect(installed.models.find((model) => model.id === "test-model")?.state).toBe("installed");
408 expect(yield* speech.transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS)).toBe("hello");
409 yield* Effect.scoped(
410 Effect.gen(function* () {
411 const stream = yield* speech.startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS);
412 expect(yield* stream.finish).toBe("hello");
413 }),
414 );
415 expect(download).toHaveBeenCalledTimes(2);
416 yield* TestClock.adjust("10 minutes");
417 expect(yield* speech.transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS)).toBe("hello");
418 expect(download).toHaveBeenCalledTimes(3);
419 }).pipe(Effect.provide(layer)),
420);
421​
422it.effect(
423 "allows another model operation after an already-installed download completes immediately",
424 () =>
425 Effect.gen(function* () {
426 const speech = yield* SpeechService.SpeechService;
427 const models = yield* speech.downloadModel("test-model").pipe(
428 Effect.provideService(Scheduler.Scheduler, {
429 executionMode: "sync",
430 shouldYield: () => false,
431 makeDispatcher: () => ({ scheduleTask: (task) => task(), flush: () => {} }),
432 }),
433 );
434 expect(models.models.find((model) => model.id === "test-model")?.state).toBe("installed");
435 yield* speech.selectModel("fallback-model");
436 }).pipe(Effect.provide(layer)),
437);
438​
439it.effect("honors exact aliases and phrase boundaries in batch and streamed text", () =>
440 Effect.gen(function* () {
441 const speech = yield* SpeechService.SpeechService;
442 const options = {
443 ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
444 speechCustomWords: [
445 { term: "AI", aliases: ["ay eye"] },
446 { term: "Bob", aliases: ["Robert"] },
447 { term: "Roberts", aliases: [] },
448 { term: "O'Reilly", aliases: ['"the publisher"'] },
449 { term: "GitHub", aliases: [] },
450 { term: "McDonald’s", aliases: [] },
451 { term: "King’s Cross", aliases: [] },
452 { term: "C#", aliases: [] },
453 { term: "React", aliases: ["瑞安特"] },
454 { term: "Kubernetes", aliases: [] },
455 ],
456 };
457 const spoken =
458 'a test with a i and ay eye. Robert, Roberts. "the publisher" and the publisher. (git hub), git (hub). ' +
459 "git hub's API, git hub’s API, git’s hub, mac donald's menu, king's cross. vitamin c and plan c. " +
460 "我用github和瑞安特,部署到kubernetis上。Robert用git hub。githubで管理する。";
461 const expected =
462 "a test with AI and AI. Bob, Roberts. O'Reilly and the publisher. (GitHub), git (hub). " +
463 "GitHub's API, GitHub’s API, git’s hub, McDonald’s menu, King’s Cross. vitamin c and plan c. " +
464 "我用GitHub和React,部署到Kubernetes上。Bob用GitHub。GitHubで管理する。";
465 native.transcribe.mockResolvedValueOnce({ text: spoken });
466 native.finish.mockResolvedValueOnce(spoken);
467 expect(yield* speech.transcribe(pcm(), options)).toBe(expected);
468 const stream = yield* speech.startStream(options);
469 expect(yield* stream.finish).toBe(expected);
470 }).pipe(Effect.scoped, Effect.provide(layer)),
471);
472​
473it.effect("uses vocabulary only for supported transcription and always applies aliases", () =>
474 Effect.gen(function* () {
475 for (const supportsVocabulary of [false, true]) {
476 for (const translate of [false, true]) {
477 yield* Effect.gen(function* () {
478 native.supportsVocabulary = supportsVocabulary;
479 const speech = yield* SpeechService.SpeechService;
480 const options = {
481 ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
482 speechLanguage: "fr" as const,
483 speechTranslateToEnglish: translate,
484 speechCustomWords: [
485 { term: "GitHub", aliases: [] },
486 { term: "Bob", aliases: ["Robert"] },
487 { term: "T3 Code", aliases: [] },
488 ],
489 };
490 const vocabulary =
491 supportsVocabulary && !translate ? ["GitHub", "Bob", "T3 Code"] : undefined;
492 native.transcribe.mockResolvedValueOnce({ text: "git hub and Robert" });
493 expect(yield* speech.transcribe(pcm(), options)).toBe(
494 vocabulary ? "git hub and Bob" : "GitHub and Bob",
495 );
496 const delivered = native.transcribe.mock.lastCall?.[1];
497 expect(delivered).toEqual({
498 timestamps: "none",
499 language: "fr",
500 ...(translate ? { task: "translate", targetLanguage: "en" } : {}),
501 ...(vocabulary ? { vocabulary } : {}),
502 });
503 if (translate) return;
504 native.feed.mockResolvedValueOnce({
505 revision: 1,
506 text: { committed: "git hub", tentative: "Robert" },
507 });
508 native.finish.mockResolvedValueOnce("git hub and Robert");
509 const stream = yield* speech.startStream(options);
510 expect(yield* stream.feed(pcm())).toEqual({
511 revision: 1,
512 text: { committed: vocabulary ? "git hub" : "GitHub", tentative: "Bob" },
513 });
514 expect(yield* stream.finish).toBe(vocabulary ? "git hub and Bob" : "GitHub and Bob");
515 expect(native.begin.mock.lastCall).toEqual([
516 { timestamps: "none", language: "fr", ...(vocabulary ? { vocabulary } : {}) },
517 true,
518 "test.gguf",
519 ]);
520 }).pipe(Effect.scoped, Effect.provide(layer));
521 }
522 }
523 }),
524);
525​
526it.effect("unloads after the chosen idle period and reloads on the next recording", () =>
527 Effect.gen(function* () {
528 const speech = yield* SpeechService.SpeechService;
529 yield* speech.updateModelUnloadTimeout("min_2");
530 yield* speech.transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS);
531 yield* TestClock.adjust(2 * 60_000 - 1);
532 expect(native.dispose).not.toHaveBeenCalled();
533 yield* TestClock.adjust(1);
534 expect(native.dispose).toHaveBeenCalledOnce();
535 yield* speech.transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS);
536 expect(loadNative).toHaveBeenCalledTimes(2);
537 }).pipe(Effect.provide(layer)),
538);
539​
540it.effect.each([
541 {
542 cue: undefined,
543 remove: true,
544 text: "First paragraph.\n\nSecond paragraph.",
545 expected: "First paragraph.\n\nSecond paragraph.",
546 },
547 {
548 cue: undefined,
549 remove: true,
550 text: "First um\n\nuh Second.",
551 expected: "First\n\nSecond.",
552 },
553 {
554 cue: undefined,
555 remove: true,
556 text: "First um\r\n\r\nuh Second.",
557 expected: "First\r\n\r\nSecond.",
558 },
559 { cue: "um", remove: true, text: "Make it red, um, blue.", expected: "Make it red, um, blue." },
560 {
561 cue: "uh no",
562 remove: true,
563 text: "Make it red, uh no, blue.",
564 expected: "Make it red, uh no, blue.",
565 },
566 {
567 cue: "uh no",
568 remove: true,
569 text: "Uh, Make it red, UH NO, blue. Uh nope.",
570 expected: "Make it red, UH NO, blue. nope.",
571 },
572 {
573 cue: " UM ",
574 remove: true,
575 text: "Uh, Make it red, um, blue.",
576 expected: "Make it red, um, blue.",
577 },
578 {
579 cue: undefined,
580 remove: true,
581 text: "Uh, Make it red, um, blue.",
582 expected: "Make it red, blue.",
583 },
584 {
585 cue: "um",
586 remove: false,
587 text: "Uh, Make it red, um, blue.",
588 expected: "Uh, Make it red, um, blue.",
589 },
590])(
591 "preserves only an explicit correction cue during batch and stream filler removal: $cue / $remove",
592 ({ cue, remove, text, expected }) =>
593 Effect.gen(function* () {
594 const speech = yield* SpeechService.SpeechService;
595 const options = {
596 ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
597 speechLanguage: "en",
598 speechRemoveFillerWords: remove,
599 speechCustomWords: [{ term: "um", aliases: [] }],
600 ...(cue === undefined ? {} : { speechCorrectionWord: cue }),
601 };
602 native.transcribe.mockResolvedValueOnce({ text });
603 native.finish.mockResolvedValueOnce(text);
604 expect(yield* speech.transcribe(pcm(), options)).toBe(expected);
605 const stream = yield* speech.startStream(options);
606 expect(yield* stream.finish).toBe(expected);
607 }).pipe(Effect.scoped, Effect.provide(layer)),
608);
609​
610it.effect("holds model ownership until the stream scope closes and preserves silence", () =>
611 Effect.gen(function* () {
612 const speech = yield* SpeechService.SpeechService;
613 yield* Effect.gen(function* () {
614 const stream = yield* speech.startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS);
615 const busy = yield* Effect.result(speech.selectModel("fallback-model"));
616 expect(Result.isFailure(busy) && busy.failure).toMatchObject({ _tag: "SpeechBusyError" });
617 yield* stream.feed(new Uint8Array(new Float32Array(160).buffer));
618 expect(native.feed.mock.calls[0]?.[0]).toHaveLength(160);
619 expect(yield* stream.finish).toBe("hello");
620 }).pipe(Effect.scoped);
621 expect(native.dispose).not.toHaveBeenCalled();
622 yield* speech.selectModel("fallback-model");
623 expect(native.dispose).toHaveBeenCalledOnce();
624 }).pipe(Effect.provide(layer)),
625);
626​
627it.effect("resets cancelled streams and reuses the loaded model", () =>
628 Effect.gen(function* () {
629 const speech = yield* SpeechService.SpeechService;
630 yield* speech.startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS).pipe(Effect.scoped);
631 expect(native.reset).toHaveBeenCalledOnce();
632 expect(native.dispose).not.toHaveBeenCalled();
633 yield* Effect.gen(function* () {
634 const stream = yield* speech.startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS);
635 yield* stream.feed(pcm());
636 yield* stream.finish;
637 }).pipe(Effect.scoped);
638 expect(loadNative).toHaveBeenCalledOnce();
639 }).pipe(Effect.provide(layer)),
640);
641​
642it.effect("releases a failed stream start without waiting for its socket scope to close", () =>
643 Effect.gen(function* () {
644 const speech = yield* SpeechService.SpeechService;
645 const socket = yield* Scope.fork(yield* Effect.scope);
646 yield* speech.updateAcceleration("cpu");
647 native.begin.mockRejectedValueOnce(new Error("cannot start streaming"));
648 const error = yield* speech
649 .startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS)
650 .pipe(Scope.provide(socket), Effect.flip);
651 expect(error._tag).toBe("SpeechOperationError");
652 expect(yield* speech.status).toMatchObject({ state: "ready" });
653 expect(native.dispose).toHaveBeenCalledOnce();
654 const next = yield* speech.startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS);
655 yield* Scope.close(socket, Exit.void);
656 expect(yield* speech.status).toMatchObject({ state: "transcribing" });
657 expect(yield* next.finish).toBe("hello");
658 }).pipe(Effect.scoped, Effect.provide(layer)),
659);
660​
661it.effect("closes its scope without waiting for hung native inference", () =>
662 Effect.gen(function* () {
663 const started = Promise.withResolvers<void>();
664 native.transcribe.mockImplementationOnce(() => {
665 started.resolve();
666 return new Promise(() => {});
667 });
668 yield* Effect.gen(function* () {
669 const speech = yield* SpeechService.SpeechService;
670 const request = yield* speech
671 .transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS)
672 .pipe(Effect.forkChild);
673 yield* Effect.promise(() => started.promise);
674 yield* Fiber.interrupt(request);
675 }).pipe(Effect.provide(layer));
676 expect(native.dispose).toHaveBeenCalledOnce();
677 }),
678);
679​
680it.effect("reports unsupported hosts without wrapping a synthetic cause", () =>
681 Effect.gen(function* () {
682 const result = yield* Effect.gen(function* () {
683 const speech = yield* SpeechService.SpeechService;
684 return yield* Effect.result(speech.transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS));
685 }).pipe(
686 Effect.provide(layer),
687 Effect.provideService(HostProcess.Platform, "win32"),
688 Effect.provideService(HostProcess.Architecture, "arm64"),
689 );
690 expect(Result.isFailure(result) && result.failure).toMatchObject({
691 _tag: "SpeechUnsupportedPlatformError",
692 platform: "win32",
693 architecture: "arm64",
694 });
695 }),
696);
697​
698it.effect.each([{ devices: [] }, { devices: [{ id: "gpu", name: "Test GPU" }] }])(
699 "retries failed GPU discovery without repeatedly probing on status polls: $devices",
700 ({ devices }) =>
701 Effect.gen(function* () {
702 const speech = yield* SpeechService.SpeechService;
703 const discover = vi.mocked(listNativeSpeechGpuDevices).mockReset();
704 discover.mockRejectedValueOnce(new Error("driver not ready")).mockResolvedValueOnce(devices);
705 expect(yield* speech.status).toMatchObject({ gpuDevices: [], benchmarkTier: "cpu" });
706 yield* speech.status;
707 expect(discover).toHaveBeenCalledOnce();
708 yield* TestClock.adjust("1 minute");
709 expect(yield* speech.status).toMatchObject({
710 gpuDevices: devices,
711 benchmarkTier: devices.length ? "accelerated" : "cpu",
712 });
713 expect(yield* speech.updateAcceleration("cpu")).toMatchObject({ benchmarkTier: "cpu" });
714 expect(yield* speech.updateAcceleration('gpu:["vulkan","gpu-1"]')).toMatchObject({
715 benchmarkTier: "accelerated",
716 });
717 yield* speech.updateAcceleration("auto");
718 yield* TestClock.adjust("1 minute");
719 expect(yield* speech.status).toMatchObject({ gpuDevices: devices });
720 expect(discover).toHaveBeenCalledTimes(2);
721 }).pipe(Effect.provide(layer)),
722);
723​
724it.effect(
725 "retries Auto-placed inference with the dictionary and the CPU's vocabulary capability",
726 () =>
727 Effect.gen(function* () {
728 for (const cpuSupportsVocabulary of [true, false]) {
729 yield* Effect.gen(function* () {
730 native.supportsVocabulary = true;
731 loadNative.mockImplementationOnce(async () => native);
732 loadNative.mockImplementationOnce(async () => ({
733 ...native,
734 backend: "CPU",
735 supportsVocabulary: cpuSupportsVocabulary,
736 }));
737 native.transcribe
738 .mockRejectedValueOnce(new Error("worker stopped"))
739 .mockResolvedValueOnce({ text: "git hub Robert" });
740 const options = {
741 ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
742 speechCustomWords: [
743 { term: "GitHub", aliases: [] },
744 { term: "Bob", aliases: ["Robert"] },
745 ],
746 };
747 const speech = yield* SpeechService.SpeechService;
748 expect(yield* speech.status).toMatchObject({ benchmarkTier: "accelerated" });
749 expect(yield* speech.transcribe(pcm(), options)).toBe(
750 cpuSupportsVocabulary ? "git hub Bob" : "GitHub Bob",
751 );
752 expect(yield* speech.status).toMatchObject({ benchmarkTier: "cpu" });
753 expect(yield* speech.transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS)).toBe(
754 "hello",
755 );
756 expect(loadNative.mock.calls.slice(-2).map((call) => call[3])).toEqual(["auto", "cpu"]);
757 expect(native.transcribe.mock.calls.slice(-3, -1).map((call) => call[1])).toEqual([
758 { timestamps: "none", language: "en", vocabulary: ["GitHub", "Bob"] },
759 {
760 timestamps: "none",
761 language: "en",
762 ...(cpuSupportsVocabulary ? { vocabulary: ["GitHub", "Bob"] } : {}),
763 },
764 ]);
765 }).pipe(Effect.provide(layer));
766 }
767 }),
768);
769​
770it.effect("reports a failure on a GPU the person chose instead of switching to CPU", () =>
771 Effect.gen(function* () {
772 const failure = new Error("GPU failed");
773 native.transcribe.mockRejectedValueOnce(failure);
774 const speech = yield* SpeechService.SpeechService;
775 const acceleration = 'gpu:["vulkan","gpu-1"]';
776 yield* speech.updateAcceleration(acceleration);
777 const result = yield* Effect.result(
778 speech.transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS),
779 );
780 expect(Result.isFailure(result) && result.failure).toMatchObject({
781 _tag: "SpeechOperationError",
782 operation: "inference",
783 cause: failure,
784 });
785 expect(loadNative).toHaveBeenCalledTimes(1);
786 expect(loadNative.mock.calls[0]?.[3]).toBe(acceleration);
787 }).pipe(Effect.provide(layer)),
788);
789​
790it.effect("replays streamed audio on CPU after an Auto-placed feed crashes, once", () =>
791 Effect.gen(function* () {
792 for (const cpuSupportsVocabulary of [true, false]) {
793 yield* Effect.gen(function* () {
794 native.supportsVocabulary = true;
795 const feedCalls = native.feed.mock.calls.length;
796 const text = { committed: "", tentative: "git hub Robert" };
797 const corrected = { committed: "", tentative: "git hub Bob" };
798 const options = {
799 ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
800 speechCustomWords: [
801 { term: "GitHub", aliases: [] },
802 { term: "Bob", aliases: ["Robert"] },
803 ],
804 };
805 native.feed
806 .mockResolvedValueOnce({ revision: 3, text })
807 .mockRejectedValueOnce(new Error("worker stopped"))
808 .mockResolvedValueOnce({ revision: 1, text })
809 .mockResolvedValueOnce({ revision: 2, text })
810 .mockResolvedValueOnce({ revision: 3, text });
811 loadNative.mockImplementationOnce(async () => native);
812 loadNative.mockImplementationOnce(async () => ({
813 ...native,
814 backend: "CPU",
815 supportsVocabulary: cpuSupportsVocabulary,
816 }));
817 const speech = yield* SpeechService.SpeechService;
818 const stream = yield* speech.startStream(options);
819 expect(yield* stream.feed(pcm())).toEqual({ revision: 3, text: corrected });
820 const recovered = {
821 committed: "",
822 tentative: cpuSupportsVocabulary ? "git hub Bob" : "GitHub Bob",
823 };
824 expect(yield* stream.feed(pcm())).toEqual({ revision: 5, text: recovered });
825 expect(loadNative.mock.calls.slice(-2).map((call) => call[3])).toEqual(["auto", "cpu"]);
826 expect(native.begin.mock.calls.slice(-2).map(([options]) => options)).toEqual([
827 { timestamps: "none", language: "en", vocabulary: ["GitHub", "Bob"] },
828 {
829 timestamps: "none",
830 language: "en",
831 ...(cpuSupportsVocabulary ? { vocabulary: ["GitHub", "Bob"] } : {}),
832 },
833 ]);
834 expect(native.feed).toHaveBeenCalledTimes(feedCalls + 4);
835 expect(yield* stream.feed(pcm())).toEqual({ revision: 6, text: recovered });
836 const loads = loadNative.mock.calls.length;
837 native.finish.mockRejectedValueOnce(new Error("CPU finish failed"));
838 expect(Result.isFailure(yield* Effect.result(stream.finish))).toBe(true);
839 expect(Result.isFailure(yield* Effect.result(stream.feed(pcm())))).toBe(true);
840 expect(loadNative).toHaveBeenCalledTimes(loads);
841 }).pipe(Effect.scoped, Effect.provide(layer));
842 }
843 }),
844);
845​
846it.effect.each([false, true])(
847 "recovers Auto stream finalization on a fresh CPU worker with retained audio: %s",
848 (withAudio) =>
849 Effect.gen(function* () {
850 const cpu = {
851 ...native,
852 backend: "CPU",
853 begin: vi.fn(async (_options?: unknown) => {}),
854 feed: vi.fn(async (_pcm: Float32Array) => ({
855 revision: 1,
856 text: { committed: "", tentative: "" },
857 })),
858 finish: vi.fn(async () => "Robert"),
859 dispose: vi.fn(),
860 };
861 const gpu = {
862 ...native,
863 finish: vi.fn(async () => {
864 throw new Error("GPU finish failed");
865 }),
866 };
867 loadNative.mockResolvedValueOnce(gpu).mockResolvedValueOnce(cpu);
868 const speech = yield* SpeechService.SpeechService;
869 const chunks = withAudio ? [new Float32Array([0.25, 0]), new Float32Array([-0.5])] : [];
870 yield* Effect.gen(function* () {
871 const stream = yield* speech.startStream({
872 ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
873 speechLanguage: "fr",
874 speechCustomWords: [{ term: "Bob", aliases: ["Robert"] }],
875 });
876 for (const chunk of chunks) yield* stream.feed(new Uint8Array(chunk.buffer));
877 expect(yield* stream.finish).toBe("Bob");
878 expect(cpu.feed.mock.calls.map(([chunk]) => [...chunk])).toEqual(
879 chunks.map((chunk) => [...chunk]),
880 );
881 expect(cpu.begin).toHaveBeenCalledWith(
882 { timestamps: "none", language: "fr" },
883 true,
884 "test.gguf",
885 );
886 expect(gpu.dispose).toHaveBeenCalledOnce();
887 expect(cpu.dispose).not.toHaveBeenCalled();
888 const busy = yield* Effect.result(speech.selectModel("fallback-model"));
889 expect(Result.isFailure(busy) && busy.failure).toMatchObject({ _tag: "SpeechBusyError" });
890 }).pipe(Effect.scoped);
891 expect(loadNative.mock.calls.map(([path, , , acceleration]) => [path, acceleration])).toEqual(
892 [
893 ["test.gguf", "auto"],
894 ["test.gguf", "cpu"],
895 ],
896 );
897 yield* speech.selectModel("fallback-model");
898 expect(cpu.dispose).toHaveBeenCalledOnce();
899 }).pipe(Effect.provide(layer)),
900);
901​
902it.effect.each(["auto", 'gpu:["vulkan","gpu-1"]', "cpu"] as const)(
903 "reports finalization failure without repeated or explicit-backend fallback: %s",
904 (acceleration) =>
905 Effect.gen(function* () {
906 const failure = new Error("finish failed");
907 const worker = {
908 ...native,
909 backend: acceleration === "cpu" ? "CPU" : "Vulkan0",
910 finish: vi.fn(async () => {
911 throw failure;
912 }),
913 };
914 const cpu = { ...worker, backend: "CPU", dispose: vi.fn() };
915 loadNative.mockResolvedValueOnce(worker);
916 if (acceleration === "auto") loadNative.mockResolvedValueOnce(cpu);
917 const speech = yield* SpeechService.SpeechService;
918 yield* speech.updateAcceleration(acceleration);
919 const stream = yield* speech.startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS);
920 expect(Result.isFailure(yield* Effect.result(stream.finish))).toBe(true);
921 expect(worker.finish).toHaveBeenCalledTimes(acceleration === "auto" ? 2 : 1);
922 expect(loadNative).toHaveBeenCalledTimes(acceleration === "auto" ? 2 : 1);
923 }).pipe(Effect.scoped, Effect.provide(layer)),
924);
925​
926it.effect("does not restart a stream cancelled while native finalization is pending", () =>
927 Effect.gen(function* () {
928 const pending = Promise.withResolvers<string>();
929 const started = Promise.withResolvers<void>();
930 native.finish.mockImplementationOnce(() => {
931 started.resolve();
932 return pending.promise;
933 });
934 const speech = yield* SpeechService.SpeechService;
935 const streamScope = yield* Scope.make();
936 const stream = yield* speech
937 .startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS)
938 .pipe(Effect.provideService(Scope.Scope, streamScope));
939 const request = yield* Effect.result(stream.finish).pipe(Effect.forkChild);
940 yield* Effect.promise(() => started.promise);
941 yield* Scope.close(streamScope, Exit.void);
942 pending.reject(new Error("cancelled worker stopped"));
943 expect(Result.isFailure(yield* Fiber.join(request))).toBe(true);
944 expect(loadNative).toHaveBeenCalledOnce();
945 expect(native.reset).toHaveBeenCalledOnce();
946 }).pipe(Effect.provide(layer)),
947);