Open History to see the last commit
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 ],
453 };
454 const spoken =
455 'a test with a i and ay eye. Robert, Roberts. "the publisher" and the publisher. (git hub), git (hub). ' +
456 "git hub's API, git hub’s API, git’s hub, mac donald's menu, king's cross.";
457 const expected =
458 "a test with AI and AI. Bob, Roberts. O'Reilly and the publisher. (GitHub), git (hub). " +
459 "GitHub's API, GitHub’s API, git’s hub, McDonald’s menu, King’s Cross.";
460 native.transcribe.mockResolvedValueOnce({ text: spoken });
461 native.finish.mockResolvedValueOnce(spoken);
462 expect(yield* speech.transcribe(pcm(), options)).toBe(expected);
463 const stream = yield* speech.startStream(options);
464 expect(yield* stream.finish).toBe(expected);
465 }).pipe(Effect.scoped, Effect.provide(layer)),
466);
467
468it.effect("uses vocabulary only for supported transcription and always applies aliases", () =>
469 Effect.gen(function* () {
470 for (const supportsVocabulary of [false, true]) {
471 for (const translate of [false, true]) {
472 yield* Effect.gen(function* () {
473 native.supportsVocabulary = supportsVocabulary;
474 const speech = yield* SpeechService.SpeechService;
475 const options = {
476 ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
477 speechLanguage: "fr" as const,
478 speechTranslateToEnglish: translate,
479 speechCustomWords: [
480 { term: "GitHub", aliases: [] },
481 { term: "Bob", aliases: ["Robert"] },
482 { term: "T3 Code", aliases: [] },
483 ],
484 };
485 const vocabulary =
486 supportsVocabulary && !translate ? ["GitHub", "Bob", "T3 Code"] : undefined;
487 native.transcribe.mockResolvedValueOnce({ text: "git hub and Robert" });
488 expect(yield* speech.transcribe(pcm(), options)).toBe(
489 vocabulary ? "git hub and Bob" : "GitHub and Bob",
490 );
491 const delivered = native.transcribe.mock.lastCall?.[1];
492 expect(delivered).toEqual({
493 timestamps: "none",
494 language: "fr",
495 ...(translate ? { task: "translate", targetLanguage: "en" } : {}),
496 ...(vocabulary ? { vocabulary } : {}),
497 });
498 if (translate) return;
499 native.feed.mockResolvedValueOnce({
500 revision: 1,
501 text: { committed: "git hub", tentative: "Robert" },
502 });
503 native.finish.mockResolvedValueOnce("git hub and Robert");
504 const stream = yield* speech.startStream(options);
505 expect(yield* stream.feed(pcm())).toEqual({
506 revision: 1,
507 text: { committed: vocabulary ? "git hub" : "GitHub", tentative: "Bob" },
508 });
509 expect(yield* stream.finish).toBe(vocabulary ? "git hub and Bob" : "GitHub and Bob");
510 expect(native.begin.mock.lastCall).toEqual([
511 { timestamps: "none", language: "fr", ...(vocabulary ? { vocabulary } : {}) },
512 true,
513 "test.gguf",
514 ]);
515 }).pipe(Effect.scoped, Effect.provide(layer));
516 }
517 }
518 }),
519);
520
521it.effect("unloads after the chosen idle period and reloads on the next recording", () =>
522 Effect.gen(function* () {
523 const speech = yield* SpeechService.SpeechService;
524 yield* speech.updateModelUnloadTimeout("min_2");
525 yield* speech.transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS);
526 yield* TestClock.adjust(2 * 60_000 - 1);
527 expect(native.dispose).not.toHaveBeenCalled();
528 yield* TestClock.adjust(1);
529 expect(native.dispose).toHaveBeenCalledOnce();
530 yield* speech.transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS);
531 expect(loadNative).toHaveBeenCalledTimes(2);
532 }).pipe(Effect.provide(layer)),
533);
534
535it.effect.each([
536 {
537 cue: undefined,
538 remove: true,
539 text: "First paragraph.\n\nSecond paragraph.",
540 expected: "First paragraph.\n\nSecond paragraph.",
541 },
542 {
543 cue: undefined,
544 remove: true,
545 text: "First um\n\nuh Second.",
546 expected: "First\n\nSecond.",
547 },
548 {
549 cue: undefined,
550 remove: true,
551 text: "First um\r\n\r\nuh Second.",
552 expected: "First\r\n\r\nSecond.",
553 },
554 { cue: "um", remove: true, text: "Make it red, um, blue.", expected: "Make it red, um, blue." },
555 {
556 cue: "uh no",
557 remove: true,
558 text: "Make it red, uh no, blue.",
559 expected: "Make it red, uh no, blue.",
560 },
561 {
562 cue: "uh no",
563 remove: true,
564 text: "Uh, Make it red, UH NO, blue. Uh nope.",
565 expected: "Make it red, UH NO, blue. nope.",
566 },
567 {
568 cue: " UM ",
569 remove: true,
570 text: "Uh, Make it red, um, blue.",
571 expected: "Make it red, um, blue.",
572 },
573 {
574 cue: undefined,
575 remove: true,
576 text: "Uh, Make it red, um, blue.",
577 expected: "Make it red, blue.",
578 },
579 {
580 cue: "um",
581 remove: false,
582 text: "Uh, Make it red, um, blue.",
583 expected: "Uh, Make it red, um, blue.",
584 },
585])(
586 "preserves only an explicit correction cue during batch and stream filler removal: $cue / $remove",
587 ({ cue, remove, text, expected }) =>
588 Effect.gen(function* () {
589 const speech = yield* SpeechService.SpeechService;
590 const options = {
591 ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
592 speechLanguage: "en",
593 speechRemoveFillerWords: remove,
594 speechCustomWords: [{ term: "um", aliases: [] }],
595 ...(cue === undefined ? {} : { speechCorrectionWord: cue }),
596 };
597 native.transcribe.mockResolvedValueOnce({ text });
598 native.finish.mockResolvedValueOnce(text);
599 expect(yield* speech.transcribe(pcm(), options)).toBe(expected);
600 const stream = yield* speech.startStream(options);
601 expect(yield* stream.finish).toBe(expected);
602 }).pipe(Effect.scoped, Effect.provide(layer)),
603);
604
605it.effect("holds model ownership until the stream scope closes and preserves silence", () =>
606 Effect.gen(function* () {
607 const speech = yield* SpeechService.SpeechService;
608 yield* Effect.gen(function* () {
609 const stream = yield* speech.startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS);
610 const busy = yield* Effect.result(speech.selectModel("fallback-model"));
611 expect(Result.isFailure(busy) && busy.failure).toMatchObject({ _tag: "SpeechBusyError" });
612 yield* stream.feed(new Uint8Array(new Float32Array(160).buffer));
613 expect(native.feed.mock.calls[0]?.[0]).toHaveLength(160);
614 expect(yield* stream.finish).toBe("hello");
615 }).pipe(Effect.scoped);
616 expect(native.dispose).not.toHaveBeenCalled();
617 yield* speech.selectModel("fallback-model");
618 expect(native.dispose).toHaveBeenCalledOnce();
619 }).pipe(Effect.provide(layer)),
620);
621
622it.effect("resets cancelled streams and reuses the loaded model", () =>
623 Effect.gen(function* () {
624 const speech = yield* SpeechService.SpeechService;
625 yield* speech.startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS).pipe(Effect.scoped);
626 expect(native.reset).toHaveBeenCalledOnce();
627 expect(native.dispose).not.toHaveBeenCalled();
628 yield* Effect.gen(function* () {
629 const stream = yield* speech.startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS);
630 yield* stream.feed(pcm());
631 yield* stream.finish;
632 }).pipe(Effect.scoped);
633 expect(loadNative).toHaveBeenCalledOnce();
634 }).pipe(Effect.provide(layer)),
635);
636
637it.effect("releases a failed stream start without waiting for its socket scope to close", () =>
638 Effect.gen(function* () {
639 const speech = yield* SpeechService.SpeechService;
640 const socket = yield* Scope.fork(yield* Effect.scope);
641 yield* speech.updateAcceleration("cpu");
642 native.begin.mockRejectedValueOnce(new Error("cannot start streaming"));
643 const error = yield* speech
644 .startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS)
645 .pipe(Scope.provide(socket), Effect.flip);
646 expect(error._tag).toBe("SpeechOperationError");
647 expect(yield* speech.status).toMatchObject({ state: "ready" });
648 expect(native.dispose).toHaveBeenCalledOnce();
649 const next = yield* speech.startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS);
650 yield* Scope.close(socket, Exit.void);
651 expect(yield* speech.status).toMatchObject({ state: "transcribing" });
652 expect(yield* next.finish).toBe("hello");
653 }).pipe(Effect.scoped, Effect.provide(layer)),
654);
655
656it.effect("closes its scope without waiting for hung native inference", () =>
657 Effect.gen(function* () {
658 const started = Promise.withResolvers<void>();
659 native.transcribe.mockImplementationOnce(() => {
660 started.resolve();
661 return new Promise(() => {});
662 });
663 yield* Effect.gen(function* () {
664 const speech = yield* SpeechService.SpeechService;
665 const request = yield* speech
666 .transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS)
667 .pipe(Effect.forkChild);
668 yield* Effect.promise(() => started.promise);
669 yield* Fiber.interrupt(request);
670 }).pipe(Effect.provide(layer));
671 expect(native.dispose).toHaveBeenCalledOnce();
672 }),
673);
674
675it.effect("reports unsupported hosts without wrapping a synthetic cause", () =>
676 Effect.gen(function* () {
677 const result = yield* Effect.gen(function* () {
678 const speech = yield* SpeechService.SpeechService;
679 return yield* Effect.result(speech.transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS));
680 }).pipe(
681 Effect.provide(layer),
682 Effect.provideService(HostProcess.Platform, "win32"),
683 Effect.provideService(HostProcess.Architecture, "arm64"),
684 );
685 expect(Result.isFailure(result) && result.failure).toMatchObject({
686 _tag: "SpeechUnsupportedPlatformError",
687 platform: "win32",
688 architecture: "arm64",
689 });
690 }),
691);
692
693it.effect.each([{ devices: [] }, { devices: [{ id: "gpu", name: "Test GPU" }] }])(
694 "retries failed GPU discovery without repeatedly probing on status polls: $devices",
695 ({ devices }) =>
696 Effect.gen(function* () {
697 const speech = yield* SpeechService.SpeechService;
698 const discover = vi.mocked(listNativeSpeechGpuDevices).mockReset();
699 discover.mockRejectedValueOnce(new Error("driver not ready")).mockResolvedValueOnce(devices);
700 expect(yield* speech.status).toMatchObject({ gpuDevices: [], benchmarkTier: "cpu" });
701 yield* speech.status;
702 expect(discover).toHaveBeenCalledOnce();
703 yield* TestClock.adjust("1 minute");
704 expect(yield* speech.status).toMatchObject({
705 gpuDevices: devices,
706 benchmarkTier: devices.length ? "accelerated" : "cpu",
707 });
708 expect(yield* speech.updateAcceleration("cpu")).toMatchObject({ benchmarkTier: "cpu" });
709 expect(yield* speech.updateAcceleration('gpu:["vulkan","gpu-1"]')).toMatchObject({
710 benchmarkTier: "accelerated",
711 });
712 yield* speech.updateAcceleration("auto");
713 yield* TestClock.adjust("1 minute");
714 expect(yield* speech.status).toMatchObject({ gpuDevices: devices });
715 expect(discover).toHaveBeenCalledTimes(2);
716 }).pipe(Effect.provide(layer)),
717);
718
719it.effect(
720 "retries Auto-placed inference with the dictionary and the CPU's vocabulary capability",
721 () =>
722 Effect.gen(function* () {
723 for (const cpuSupportsVocabulary of [true, false]) {
724 yield* Effect.gen(function* () {
725 native.supportsVocabulary = true;
726 loadNative.mockImplementationOnce(async () => native);
727 loadNative.mockImplementationOnce(async () => ({
728 ...native,
729 backend: "CPU",
730 supportsVocabulary: cpuSupportsVocabulary,
731 }));
732 native.transcribe
733 .mockRejectedValueOnce(new Error("worker stopped"))
734 .mockResolvedValueOnce({ text: "git hub Robert" });
735 const options = {
736 ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
737 speechCustomWords: [
738 { term: "GitHub", aliases: [] },
739 { term: "Bob", aliases: ["Robert"] },
740 ],
741 };
742 const speech = yield* SpeechService.SpeechService;
743 expect(yield* speech.status).toMatchObject({ benchmarkTier: "accelerated" });
744 expect(yield* speech.transcribe(pcm(), options)).toBe(
745 cpuSupportsVocabulary ? "git hub Bob" : "GitHub Bob",
746 );
747 expect(yield* speech.status).toMatchObject({ benchmarkTier: "cpu" });
748 expect(yield* speech.transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS)).toBe(
749 "hello",
750 );
751 expect(loadNative.mock.calls.slice(-2).map((call) => call[3])).toEqual(["auto", "cpu"]);
752 expect(native.transcribe.mock.calls.slice(-3, -1).map((call) => call[1])).toEqual([
753 { timestamps: "none", language: "en", vocabulary: ["GitHub", "Bob"] },
754 {
755 timestamps: "none",
756 language: "en",
757 ...(cpuSupportsVocabulary ? { vocabulary: ["GitHub", "Bob"] } : {}),
758 },
759 ]);
760 }).pipe(Effect.provide(layer));
761 }
762 }),
763);
764
765it.effect("reports a failure on a GPU the person chose instead of switching to CPU", () =>
766 Effect.gen(function* () {
767 const failure = new Error("GPU failed");
768 native.transcribe.mockRejectedValueOnce(failure);
769 const speech = yield* SpeechService.SpeechService;
770 const acceleration = 'gpu:["vulkan","gpu-1"]';
771 yield* speech.updateAcceleration(acceleration);
772 const result = yield* Effect.result(
773 speech.transcribe(pcm(), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS),
774 );
775 expect(Result.isFailure(result) && result.failure).toMatchObject({
776 _tag: "SpeechOperationError",
777 operation: "inference",
778 cause: failure,
779 });
780 expect(loadNative).toHaveBeenCalledTimes(1);
781 expect(loadNative.mock.calls[0]?.[3]).toBe(acceleration);
782 }).pipe(Effect.provide(layer)),
783);
784
785it.effect("replays streamed audio on CPU after an Auto-placed feed crashes, once", () =>
786 Effect.gen(function* () {
787 for (const cpuSupportsVocabulary of [true, false]) {
788 yield* Effect.gen(function* () {
789 native.supportsVocabulary = true;
790 const feedCalls = native.feed.mock.calls.length;
791 const text = { committed: "", tentative: "git hub Robert" };
792 const corrected = { committed: "", tentative: "git hub Bob" };
793 const options = {
794 ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
795 speechCustomWords: [
796 { term: "GitHub", aliases: [] },
797 { term: "Bob", aliases: ["Robert"] },
798 ],
799 };
800 native.feed
801 .mockResolvedValueOnce({ revision: 3, text })
802 .mockRejectedValueOnce(new Error("worker stopped"))
803 .mockResolvedValueOnce({ revision: 1, text })
804 .mockResolvedValueOnce({ revision: 2, text })
805 .mockResolvedValueOnce({ revision: 3, text });
806 loadNative.mockImplementationOnce(async () => native);
807 loadNative.mockImplementationOnce(async () => ({
808 ...native,
809 backend: "CPU",
810 supportsVocabulary: cpuSupportsVocabulary,
811 }));
812 const speech = yield* SpeechService.SpeechService;
813 const stream = yield* speech.startStream(options);
814 expect(yield* stream.feed(pcm())).toEqual({ revision: 3, text: corrected });
815 const recovered = {
816 committed: "",
817 tentative: cpuSupportsVocabulary ? "git hub Bob" : "GitHub Bob",
818 };
819 expect(yield* stream.feed(pcm())).toEqual({ revision: 5, text: recovered });
820 expect(loadNative.mock.calls.slice(-2).map((call) => call[3])).toEqual(["auto", "cpu"]);
821 expect(native.begin.mock.calls.slice(-2).map(([options]) => options)).toEqual([
822 { timestamps: "none", language: "en", vocabulary: ["GitHub", "Bob"] },
823 {
824 timestamps: "none",
825 language: "en",
826 ...(cpuSupportsVocabulary ? { vocabulary: ["GitHub", "Bob"] } : {}),
827 },
828 ]);
829 expect(native.feed).toHaveBeenCalledTimes(feedCalls + 4);
830 expect(yield* stream.feed(pcm())).toEqual({ revision: 6, text: recovered });
831 const loads = loadNative.mock.calls.length;
832 native.finish.mockRejectedValueOnce(new Error("CPU finish failed"));
833 expect(Result.isFailure(yield* Effect.result(stream.finish))).toBe(true);
834 expect(Result.isFailure(yield* Effect.result(stream.feed(pcm())))).toBe(true);
835 expect(loadNative).toHaveBeenCalledTimes(loads);
836 }).pipe(Effect.scoped, Effect.provide(layer));
837 }
838 }),
839);
840
841it.effect.each([false, true])(
842 "recovers Auto stream finalization on a fresh CPU worker with retained audio: %s",
843 (withAudio) =>
844 Effect.gen(function* () {
845 const cpu = {
846 ...native,
847 backend: "CPU",
848 begin: vi.fn(async (_options?: unknown) => {}),
849 feed: vi.fn(async (_pcm: Float32Array) => ({
850 revision: 1,
851 text: { committed: "", tentative: "" },
852 })),
853 finish: vi.fn(async () => "Robert"),
854 dispose: vi.fn(),
855 };
856 const gpu = {
857 ...native,
858 finish: vi.fn(async () => {
859 throw new Error("GPU finish failed");
860 }),
861 };
862 loadNative.mockResolvedValueOnce(gpu).mockResolvedValueOnce(cpu);
863 const speech = yield* SpeechService.SpeechService;
864 const chunks = withAudio ? [new Float32Array([0.25, 0]), new Float32Array([-0.5])] : [];
865 yield* Effect.gen(function* () {
866 const stream = yield* speech.startStream({
867 ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
868 speechLanguage: "fr",
869 speechCustomWords: [{ term: "Bob", aliases: ["Robert"] }],
870 });
871 for (const chunk of chunks) yield* stream.feed(new Uint8Array(chunk.buffer));
872 expect(yield* stream.finish).toBe("Bob");
873 expect(cpu.feed.mock.calls.map(([chunk]) => [...chunk])).toEqual(
874 chunks.map((chunk) => [...chunk]),
875 );
876 expect(cpu.begin).toHaveBeenCalledWith(
877 { timestamps: "none", language: "fr" },
878 true,
879 "test.gguf",
880 );
881 expect(gpu.dispose).toHaveBeenCalledOnce();
882 expect(cpu.dispose).not.toHaveBeenCalled();
883 const busy = yield* Effect.result(speech.selectModel("fallback-model"));
884 expect(Result.isFailure(busy) && busy.failure).toMatchObject({ _tag: "SpeechBusyError" });
885 }).pipe(Effect.scoped);
886 expect(loadNative.mock.calls.map(([path, , , acceleration]) => [path, acceleration])).toEqual(
887 [
888 ["test.gguf", "auto"],
889 ["test.gguf", "cpu"],
890 ],
891 );
892 yield* speech.selectModel("fallback-model");
893 expect(cpu.dispose).toHaveBeenCalledOnce();
894 }).pipe(Effect.provide(layer)),
895);
896
897it.effect.each(["auto", 'gpu:["vulkan","gpu-1"]', "cpu"] as const)(
898 "reports finalization failure without repeated or explicit-backend fallback: %s",
899 (acceleration) =>
900 Effect.gen(function* () {
901 const failure = new Error("finish failed");
902 const worker = {
903 ...native,
904 backend: acceleration === "cpu" ? "CPU" : "Vulkan0",
905 finish: vi.fn(async () => {
906 throw failure;
907 }),
908 };
909 const cpu = { ...worker, backend: "CPU", dispose: vi.fn() };
910 loadNative.mockResolvedValueOnce(worker);
911 if (acceleration === "auto") loadNative.mockResolvedValueOnce(cpu);
912 const speech = yield* SpeechService.SpeechService;
913 yield* speech.updateAcceleration(acceleration);
914 const stream = yield* speech.startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS);
915 expect(Result.isFailure(yield* Effect.result(stream.finish))).toBe(true);
916 expect(worker.finish).toHaveBeenCalledTimes(acceleration === "auto" ? 2 : 1);
917 expect(loadNative).toHaveBeenCalledTimes(acceleration === "auto" ? 2 : 1);
918 }).pipe(Effect.scoped, Effect.provide(layer)),
919);
920
921it.effect("does not restart a stream cancelled while native finalization is pending", () =>
922 Effect.gen(function* () {
923 const pending = Promise.withResolvers<string>();
924 const started = Promise.withResolvers<void>();
925 native.finish.mockImplementationOnce(() => {
926 started.resolve();
927 return pending.promise;
928 });
929 const speech = yield* SpeechService.SpeechService;
930 const streamScope = yield* Scope.make();
931 const stream = yield* speech
932 .startStream(DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS)
933 .pipe(Effect.provideService(Scope.Scope, streamScope));
934 const request = yield* Effect.result(stream.finish).pipe(Effect.forkChild);
935 yield* Effect.promise(() => started.promise);
936 yield* Scope.close(streamScope, Exit.void);
937 pending.reject(new Error("cancelled worker stopped"));
938 expect(Result.isFailure(yield* Fiber.join(request))).toBe(true);
939 expect(loadNative).toHaveBeenCalledOnce();
940 expect(native.reset).toHaveBeenCalledOnce();
941 }).pipe(Effect.provide(layer)),
942);