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