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