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

SpeechService.test.ts

1,031 lines41.0 KB

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