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