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

SpeechService.test.ts

922 lines36.6 KB

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