Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
test(desktop): cover the transcription process, engine and capture window
Elian Doran6e38cb46d051
diff --git a/apps/client/src/widgets/launch_bar/LauncherContainer.spec.tsx b/apps/client/src/widgets/launch_bar/LauncherContainer.spec.tsxindex 9e2d6a177a..a25a925329 100644--- a/apps/client/src/widgets/launch_bar/LauncherContainer.spec.tsx+++ b/apps/client/src/widgets/launch_bar/LauncherContainer.spec.tsx@@ -1,12 +1,22 @@import { render } from "preact";import { act } from "preact/test-utils";-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import Component from "../../components/component.js";import type FNote from "../../entities/fnote.js";import { buildNote } from "../../test/easy-froca.js";import { ParentComponent } from "../react/react_utils.js";-import { useLauncherChildNotes } from "./LauncherContainer.js";+import LauncherContainer, { useLauncherChildNotes } from "./LauncherContainer.js";++const h = vi.hoisted(() => ({ isElectron: false }));++vi.mock("../../services/utils", async (importOriginal) => ({+ ...await importOriginal<typeof import("../../services/utils")>(),+ isElectron: () => h.isElectron+}));+vi.mock("./RecordMeetingButton", () => ({+ default: () => <span className="record-meeting-button" />+}));let container: HTMLDivElement;@@ -71,3 +81,38 @@ describe("useLauncherChildNotes", () => {expect(freshNote).not.toBe(staleNote);});});++describe("LauncherContainer", () => {+ it("shows the meeting transcription launcher only in the desktop app", async () => {+ buildNote({+ id: "_lbVisibleLaunchers",+ title: "Visible Launchers",+ children: [ {+ title: "Transcribe meeting",+ type: "launcher",+ "#launcherType": "builtinWidget",+ "#builtinWidget": "recordMeeting"+ } ]+ });+ const mount = () => {+ container = document.createElement("div");+ document.body.appendChild(container);+ act(() => render(+ <ParentComponent.Provider value={new Component()}>+ <LauncherContainer isHorizontalLayout={false} />+ </ParentComponent.Provider>, container));+ };++ mount();+ await flush();+ expect(container.querySelector("#launcher-container")).not.toBeNull();+ expect(container.querySelector(".record-meeting-button")).toBeNull();+ act(() => render(null, container));+ container.remove();++ h.isElectron = true;+ mount();+ await flush();+ expect(container.querySelector(".record-meeting-button")).not.toBeNull();+ });+});diff --git a/apps/client/src/widgets/launch_bar/RecordMeetingButton.spec.tsx b/apps/client/src/widgets/launch_bar/RecordMeetingButton.spec.tsxindex 95f6aa8a95..25215f6a7c 100644--- a/apps/client/src/widgets/launch_bar/RecordMeetingButton.spec.tsx+++ b/apps/client/src/widgets/launch_bar/RecordMeetingButton.spec.tsx@@ -24,7 +24,9 @@ vi.mock("../../services/i18n", () => ({t: (key: string, options?: { date?: string }) => `${key} ${options?.date}`}));vi.mock("./launch_bar_widgets", () => ({- LaunchBarActionButton: () => null,+ LaunchBarActionButton: ({ icon, text, disabled, onClick }: {+ icon: string; text: string; disabled?: boolean; onClick: () => void;+ }) => <button className={icon} disabled={disabled} onClick={onClick}>{text}</button>,useLauncherIconAndTitle: () => ({ icon: "bx bx-microphone", title: "Record meeting" })}));@@ -91,6 +93,13 @@ describe("toggleRecording", () => {expect(mocks.createNote).not.toHaveBeenCalled();});+ it("starts nothing when no meeting note could be created", async () => {+ mocks.getInboxNote.mockResolvedValue(null);+ vi.spyOn(console, "warn").mockImplementation(() => {});+ await toggleRecording("idle");+ expect(transcription.start).not.toHaveBeenCalled();+ });+it("does nothing outside the desktop app", async () => {window.electronApi = undefined;await toggleRecording("idle");@@ -127,4 +136,44 @@ describe("RecordMeetingButton", () => {expect(mocks.showError).toHaveBeenCalledTimes(2);window.electronApi = undefined;});++ it("shows the shared recording's state, and starts or stops it on a click", async () => {+ let onStateChanged: (state: TranscriptionState) => void = () => {};+ const report = (status: TranscriptionState["status"]) =>+ act(() => onStateChanged({ status, noteId: "meeting", pendingSources: [] }));+ const transcription = {+ getState: async () => ({ status: "recording", noteId: "meeting", pendingSources: [] }),+ onStateChanged: (callback: typeof onStateChanged) => {+ onStateChanged = callback;+ return () => {};+ },+ stop: vi.fn(async () => {}),+ start: vi.fn(async () => "")+ };+ window.electronApi = { transcription } as unknown as typeof window.electronApi;+ mocks.getInboxNote.mockResolvedValue({ noteId: "inbox", isProtected: false });+ mocks.createNote.mockResolvedValue({ note: { noteId: "meeting" } });+ let container: HTMLElement | null = null;+ act(() => {+ container = renderInto(<RecordMeetingButton launcherNote={{} as FNote} />);+ });+ const button = () => (container as HTMLElement | null)?.querySelector("button");++ await vi.waitFor(() => expect(button()?.className).toBe("bx bx-stop-circle"));+ await act(async () => button()?.click());+ expect(transcription.stop).toHaveBeenCalledOnce();++ for (const status of [ "starting", "stopping" ] as const) {+ await report(status);+ expect(button()?.className).toBe("bx bx-loader-alt bx-spin");+ expect(button()?.disabled).toBe(true);+ expect(button()?.textContent).toContain(`record_meeting.${status}`);+ }++ await report("idle");+ expect(button()?.className).toBe("bx bx-microphone");+ await act(async () => button()?.click());+ await vi.waitFor(() => expect(transcription.start).toHaveBeenCalledExactlyOnceWith("meeting"));+ window.electronApi = undefined;+ });});diff --git a/apps/desktop/src/services/transcription/attachment_sink.spec.ts b/apps/desktop/src/services/transcription/attachment_sink.spec.tsindex 7484e317e4..e462d9382f 100644--- a/apps/desktop/src/services/transcription/attachment_sink.spec.ts+++ b/apps/desktop/src/services/transcription/attachment_sink.spec.ts@@ -122,6 +122,7 @@ describe("AttachmentSink", () => {const sink = new AttachmentSink("meeting");expect(() => sink.write({ source: "system", offsetMs: 0, text: "Hi" })).toThrow("The transcript attachment was not created.");+ expect(() => sink.save()).toThrow("The transcript attachment was not created.");expect(h.setContent).not.toHaveBeenCalled();});});diff --git a/apps/desktop/src/services/transcription/capture.spec.ts b/apps/desktop/src/services/transcription/capture.spec.tsindex 683521482a..fcef2a134a 100644--- a/apps/desktop/src/services/transcription/capture.spec.ts+++ b/apps/desktop/src/services/transcription/capture.spec.ts@@ -1,9 +1,14 @@import { EventEmitter } from "events";-import { describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++type Handler = (...args: never[]) => unknown;const h = vi.hoisted(() => ({windows: [] as FakeWindow[],- log: { info: vi.fn(), error: vi.fn() }+ log: { info: vi.fn(), error: vi.fn() },+ sessionHandlers: {} as Record<string, Handler>,+ /** How the page answers each call; the default starts the source. */+ pageCalls: {} as Record<string, () => Promise<unknown>>}));/** The parts of a `BrowserWindow` the capture window uses. */@@ -12,7 +17,7 @@ class FakeWindow {webContents = Object.assign(new EventEmitter(), {ipc: new EventEmitter(),postMessage: vi.fn(),- executeJavaScript: vi.fn(async (call: string) => call)+ executeJavaScript: vi.fn((call: string) => h.pageCalls[call]?.() ?? Promise.resolve(call))});constructor() {@@ -31,9 +36,15 @@ vi.mock("electron", () => ({BrowserWindow: FakeWindow,session: {fromPartition: () => ({- setPermissionRequestHandler: vi.fn(),- setPermissionCheckHandler: vi.fn(),- setDisplayMediaRequestHandler: vi.fn()+ setPermissionRequestHandler: (handler: Handler) => {+ h.sessionHandlers.request = handler;+ },+ setPermissionCheckHandler: (handler: Handler) => {+ h.sessionHandlers.check = handler;+ },+ setDisplayMediaRequestHandler: (handler: Handler) => {+ h.sessionHandlers.displayMedia = handler;+ }})}}));@@ -97,6 +108,15 @@ describe("CAPTURE_PROCESSOR", () => {});describe("CaptureWindow", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ h.pageCalls = {};+ });++ afterEach(() => {+ vi.useRealTimers();+ });+async function startCapture() {h.windows.length = 0;const onLost = vi.fn();@@ -133,4 +153,66 @@ describe("CaptureWindow", () => {window.webContents.emit("render-process-gone", {}, { reason: "killed" });expect(onLost).not.toHaveBeenCalled();});++ it("grants its page the microphone and its own audio, and nothing else", async () => {+ await startCapture();+ const request = h.sessionHandlers.request as (...args: unknown[]) => void;+ const check = h.sessionHandlers.check as (...args: unknown[]) => boolean;+ const answers: boolean[] = [];+ for (const permission of [ "media", "display-capture", "geolocation" ]) {+ request({}, permission, (granted: boolean) => answers.push(granted));+ }+ expect(answers).toEqual([ true, true, false ]);+ expect(check({}, "media")).toBe(true);+ expect(check({}, "notifications")).toBe(false);++ const displayMedia = h.sessionHandlers.displayMedia as (...args: unknown[]) => void;+ const callback = vi.fn();+ displayMedia({ frame: "the page" }, callback);+ displayMedia({}, callback);+ expect(callback.mock.calls).toEqual([+ [ { video: "the page", audio: "loopback" } ],+ [ { video: undefined, audio: "loopback" } ]+ ]);+ });++ it("logs what its page logs", async () => {+ const { window } = await startCapture();+ window.webContents.emit("console-message", { message: "System track muted=false" });+ expect(h.log.info).toHaveBeenCalledWith(+ "Transcription (capture): System track muted=false");+ });++ it("runs the sources that start, and fails when none does", async () => {+ h.pageCalls["captureSystemAudio()"] = () => Promise.reject(new Error("NotAllowedError"));+ h.windows.length = 0;+ const capture = new CaptureWindow({ onLost: vi.fn() });+ expect(await capture.start("port" as never)).toEqual([ "microphone" ]);+ expect(h.log.error).toHaveBeenCalledWith(+ "Transcription: system unavailable: NotAllowedError");++ h.pageCalls["captureMicrophone()"] = () => Promise.reject(new Error("NotFoundError"));+ await expect(new CaptureWindow({ onLost: vi.fn() }).start("port" as never))+ .rejects.toThrow("No audio source could be captured.");+ expect(h.windows[1].destroy).toHaveBeenCalledOnce();+ });++ it("closes a page that does not finish in time, and one that is already gone", async () => {+ const { capture, window } = await startCapture();+ h.pageCalls["finishCapture()"] = () => new Promise(() => {});+ vi.useFakeTimers();+ const stopped = capture.stop();+ await vi.advanceTimersByTimeAsync(1000);+ await stopped;+ expect(h.log.error).toHaveBeenCalledWith(+ "Transcription: finishing the capture failed: timed out");+ expect(window.destroy).toHaveBeenCalledOnce();++ const crashed = await startCapture();+ crashed.window.destroyed = true;+ await crashed.capture.stop();+ await crashed.capture.stop();+ expect(crashed.window.webContents.executeJavaScript)+ .not.toHaveBeenCalledWith("finishCapture()");+ });});diff --git a/apps/desktop/src/services/transcription/engine.spec.ts b/apps/desktop/src/services/transcription/engine.spec.tsnew file mode 100644index 0000000000..edfd20bc6c--- /dev/null+++ b/apps/desktop/src/services/transcription/engine.spec.ts@@ -0,0 +1,173 @@+import path from "path";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { loadSherpaEngine } from "./engine";++const h = vi.hoisted(() => ({+ hasSpeakerModel: false,+ recognizerConfig: null as Record<string, unknown> | null,+ vadConfig: null as Record<string, unknown> | null,+ extractorConfig: null as Record<string, unknown> | null,+ decoded: [] as Float32Array[],+ isEmbeddingReady: true,+ embeddings: [] as number[][]+}));++/** Silero as the segmenter sees it: windows in, then whatever segments the spec queues. */+class FakeVad {+ windows: number[] = [];+ queued: { start: number; samples: Float32Array }[] = [];+ pendingAtFlush: { start: number; samples: Float32Array }[] = [];+ isSpeech = false;+ externalBuffers: boolean[] = [];++ constructor(config: Record<string, unknown>) {+ h.vadConfig = config;+ vads.push(this);+ }++ acceptWaveform(window: Float32Array) {+ this.windows.push(window.length);+ }+ flush() {+ this.queued.push(...this.pendingAtFlush);+ }+ isDetected() {+ return this.isSpeech;+ }+ isEmpty() {+ return !this.queued.length;+ }+ front(enableExternalBuffer: boolean) {+ this.externalBuffers.push(enableExternalBuffer);+ return this.queued[0];+ }+ pop() {+ this.queued.shift();+ }+}+const vads: FakeVad[] = [];++vi.mock("sherpa-onnx-node", () => ({+ default: {+ OfflineRecognizer: {+ createAsync: async (config: Record<string, unknown>) => {+ h.recognizerConfig = config;+ return {+ createStream: () => ({+ samples: null as Float32Array | null,+ acceptWaveform(input: { samples: Float32Array }) {+ this.samples = input.samples;+ }+ }),+ decodeAsync: async (stream: { samples: Float32Array }) => {+ h.decoded.push(stream.samples);+ return { text: " Hello there. " };+ }+ };+ }+ },+ Vad: FakeVad,+ SpeakerEmbeddingExtractor: class {+ constructor(config: Record<string, unknown>) {+ h.extractorConfig = config;+ }+ createStream() {+ return { acceptWaveform: vi.fn(), inputFinished: vi.fn() };+ }+ isReady() {+ return h.isEmbeddingReady;+ }+ compute(_stream: unknown, enableExternalBuffer: boolean) {+ expect(enableExternalBuffer).toBe(false);+ return Float32Array.from(h.embeddings.shift() ?? []);+ }+ }+ }+}));+vi.mock("fs", () => ({+ default: { existsSync: (file: string) => h.hasSpeakerModel && file.endsWith(".onnx") }+}));++const MODEL_DIR = "/models/parakeet";++beforeEach(() => {+ h.hasSpeakerModel = false;+ h.isEmbeddingReady = true;+ h.decoded.length = 0;+ h.embeddings.length = 0;+ vads.length = 0;+});++describe("loadSherpaEngine", () => {+ it("loads Parakeet and Silero from the model directory and reports their settings", async () => {+ const engine = await loadSherpaEngine(MODEL_DIR);++ expect(h.recognizerConfig).toMatchObject({+ featConfig: { sampleRate: 16000, featureDim: 80 },+ modelConfig: {+ transducer: {+ encoder: path.join(MODEL_DIR, "encoder.int8.onnx"),+ decoder: path.join(MODEL_DIR, "decoder.int8.onnx"),+ joiner: path.join(MODEL_DIR, "joiner.int8.onnx")+ },+ tokens: path.join(MODEL_DIR, "tokens.txt"),+ modelType: "nemo_transducer"+ },+ decodingMethod: "greedy_search",+ blankPenalty: 0.5+ });+ expect(engine.createSpeakerTracker).toBeUndefined();+ expect(engine.settings).toMatchObject({+ modelDirectory: path.resolve(MODEL_DIR),+ recognizer: { modelType: "nemo_transducer", blankPenalty: 0.5 },+ vad: { minSilenceDuration: 0.75, maxSpeechDuration: 20, windowSize: 512 },+ speakers: null+ });++ const samples = new Float32Array(1600);+ expect(await engine.recognizer.transcribe(samples)).toBe("Hello there.");+ expect(h.decoded).toEqual([ samples ]);+ });++ it("segments a source in whole 512-sample windows, handing out what the VAD completes", async () => {+ const engine = await loadSherpaEngine(MODEL_DIR);+ const segmenter = engine.createSegmenter();+ const vad = vads[0];+ expect(h.vadConfig).toMatchObject({+ sileroVad: { model: path.join(MODEL_DIR, "silero_vad.onnx"), threshold: 0.5 },+ sampleRate: 16000+ });++ const first = { start: 0, samples: new Float32Array(8000) };+ vad.queued.push(first);+ vad.isSpeech = true;+ expect(segmenter.accept(new Float32Array(1100))).toEqual([ first ]);+ expect(vad.windows).toEqual([ 512, 512 ]);+ expect(segmenter.isSpeaking()).toBe(true);++ const last = { start: 16000, samples: new Float32Array(4000) };+ vad.pendingAtFlush.push(last);+ expect(segmenter.accept(new Float32Array(512))).toEqual([]);+ expect(segmenter.flush()).toEqual([ last ]);+ expect(vad.externalBuffers).toEqual([ false, false ]);+ });++ it("tells speakers apart with the speaker model, when it is installed", async () => {+ h.hasSpeakerModel = true;+ const engine = await loadSherpaEngine(MODEL_DIR);+ expect(h.extractorConfig?.model)+ .toBe(path.join(MODEL_DIR, "speaker", "nemo_en_titanet_small.onnx"));+ expect(engine.settings.speakers).toMatchObject({+ model: "nemo_en_titanet_small.onnx", threshold: 0.5, minDurationSeconds: 1.5+ });++ const tracker = engine.createSpeakerTracker?.();+ const long = new Float32Array(16000 * 2);+ h.embeddings.push([ 1, 0 ], [ 0, 1 ], [ 0.9, 0.1 ]);+ expect([ 1, 2, 3 ].map(() => tracker?.identify(long))).toEqual([ 1, 2, 1 ]);++ h.isEmbeddingReady = false;+ expect(tracker?.identify(new Float32Array(100))).toBeNull();+ });+});diff --git a/apps/desktop/src/services/transcription/index.spec.ts b/apps/desktop/src/services/transcription/index.spec.tsindex cbf2b95f80..f826813ca8 100644--- a/apps/desktop/src/services/transcription/index.spec.ts+++ b/apps/desktop/src/services/transcription/index.spec.ts@@ -234,6 +234,41 @@ describe("transcription IPC", () => {h.sink.write.mockReset();});+ it("says why an unprotected transcript cannot be saved, and retries until a save works", async () => {+ const invoke = await loadService();+ await invoke("transcription-start", "meeting");+ h.sink.write.mockImplementationOnce(() => {+ throw new Error("disk full");+ });+ h.listeners?.onUtterance({ source: "system", offsetMs: 0, text: "Hi" });+ expect(h.broadcast.at(-1)?.error)+ .toBe(`transcription.save-failed {"message":"disk full"}`);+ await invoke("transcription-stop");++ h.sink.save.mockImplementationOnce(() => {+ throw new Error("still locked");+ });+ h.coreListeners.get("ENTER_PROTECTED_SESSION")?.();+ expect(h.log.error).toHaveBeenCalledWith(+ "Transcription: saving a transcript still failed: Error: still locked");+ h.coreListeners.get("ENTER_PROTECTED_SESSION")?.();+ h.coreListeners.get("ENTER_PROTECTED_SESSION")?.();+ expect(h.sink.save).toHaveBeenCalledTimes(2);+ });++ it("ignores a lost capture or a dead process once the recording has stopped", async () => {+ const invoke = await loadService();+ await invoke("transcription-start", "meeting");+ await invoke("transcription-stop");+ const broadcasts = h.broadcast.length;++ h.captureOptions?.onLost("the capture page ended (killed)");+ h.listeners?.onUnexpectedExit(0);+ await new Promise((resolve) => setTimeout(resolve));+ expect(h.broadcast).toHaveLength(broadcasts);+ expect(h.worker.stop).toHaveBeenCalledOnce();+ });+it("renames a speaker through the recording that writes the transcript, until it stops", async () => {const invoke = await loadService();const rename = (noteId: unknown, key: unknown, name: unknown) =>diff --git a/apps/desktop/src/services/transcription/session.spec.ts b/apps/desktop/src/services/transcription/session.spec.tsindex 14125d320d..dde412a779 100644--- a/apps/desktop/src/services/transcription/session.spec.ts+++ b/apps/desktop/src/services/transcription/session.spec.ts@@ -235,6 +235,35 @@ describe("RecordingSession", () => {"Transcription: identifying the speaker on system failed: Error: model crashed");});+ it("logs each source's peak level every 5 s, to spot a silent source", async () => {+ const { session, deliver } = createHarness();+ await session.start();+ for (let second = 1; second <= 5; second++) {+ deliver("system", speechChunk(false), 1000 + second * 1000);+ }+ expect(log.info).toHaveBeenCalledExactlyOnceWith("Transcription: system peak 1.0000 over 5 s");+ await session.stop();+ });++ it("logs a failed transcription or tap, and still finishes the rest", async () => {+ const tap = { write: vi.fn(), close: vi.fn(() => {+ throw new Error("disk full");+ }) };+ const { session, engine, deliver, written, onPendingChanged } = createHarness([], [ tap ]);+ engine.recognizer.transcribe.mockRejectedValueOnce(new Error("decoder crashed"));+ await session.start();++ deliver("microphone", utteranceChunk(1, 0), 2000);+ deliver("microphone", utteranceChunk(2, 16000), 3000);+ await session.stop();+ expect(written.map((utterance) => utterance.text)).toEqual([ "utterance 2" ]);+ expect(onPendingChanged).toHaveBeenLastCalledWith([]);+ expect(log.error.mock.calls).toEqual([+ [ "Transcription: closing an audio tap failed: Error: disk full" ],+ [ "Transcription failed: Error: decoder crashed" ]+ ]);+ });+it("logs a failing source instead of throwing into the capture", async () => {const { session, engine, deliver } = createHarness();engine.createSegmenter.mockImplementationOnce(() => {@@ -271,5 +300,11 @@ describe("PortCapture", () => {await capture.ended;capture.stop();expect(port.close).toHaveBeenCalledOnce();++ const closed = new PortCapture();+ const closedPort = Object.assign(new EventEmitter(), { start: vi.fn(), close: vi.fn() });+ closed.connect(closedPort as never);+ closedPort.emit("close");+ await closed.ended;});});diff --git a/apps/desktop/src/services/transcription/speakers.spec.ts b/apps/desktop/src/services/transcription/speakers.spec.tsindex 0ae07f6785..ce4049ddb4 100644--- a/apps/desktop/src/services/transcription/speakers.spec.ts+++ b/apps/desktop/src/services/transcription/speakers.spec.ts@@ -16,6 +16,12 @@ describe("SpeakerClusterer", () => {expect(clusterer.assign(new Float32Array([ 0, 0, 1 ]), 3)).toBe(3);});+ it("takes a silent, all-zero embedding as a speaker of its own rather than dividing by zero", () => {+ const clusterer = new SpeakerClusterer(options);+ expect(clusterer.assign(new Float32Array([ 0, 0, 0 ]), 3)).toBe(1);+ expect(clusterer.assign(new Float32Array([ 1, 0, 0 ]), 3)).toBe(2);+ });+it("lets a short utterance join a speaker but never start one or move a centroid", () => {const clusterer = new SpeakerClusterer(options);expect(clusterer.assign(new Float32Array([ 0, 1 ]), 1)).toBeNull();diff --git a/apps/desktop/src/services/transcription/transcription_worker.spec.ts b/apps/desktop/src/services/transcription/transcription_worker.spec.tsnew file mode 100644index 0000000000..d8e077a8fd--- /dev/null+++ b/apps/desktop/src/services/transcription/transcription_worker.spec.ts@@ -0,0 +1,177 @@+import { EventEmitter } from "events";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { WorkerEvent, WorkerRequest } from "./protocol";++const h = vi.hoisted(() => ({+ loadEngine: vi.fn(),+ fileSinks: [] as string[],+ recorders: [] as unknown[][]+}));++vi.mock("./engine", () => ({ loadSherpaEngine: h.loadEngine }));+vi.mock("./audio_recorder", () => ({+ TranscriptFileSink: class {+ constructor(directory: string) {+ h.fileSinks.push(directory);+ }+ write() {}+ },+ WavRecorder: class {+ constructor(...args: unknown[]) {+ h.recorders.push(args);+ (args[3] as { info(message: string): void }).info("keeping the audio");+ }+ write() {}+ }+}));++/** The parent port of an Electron utility process, as the transcription process uses it. */+class FakeParentPort extends EventEmitter {+ posted: WorkerEvent[] = [];+ postMessage = (event: WorkerEvent) => {+ this.posted.push(event);+ };++ send(request: WorkerRequest, ports: unknown[] = []) {+ this.emit("message", { data: request, ports });+ }++ /** Resolves with the first event of `type` posted so far or later. */+ async next(type: WorkerEvent["type"]) {+ await vi.waitFor(() => expect(this.posted.map((event) => event.type)).toContain(type));+ return this.posted.find((event) => event.type === type);+ }+}++/** An engine whose segmenter completes an utterance per chunk, transcribed as "Chunk <n>". */+const engine = {+ settings: { recognizer: { decodingMethod: "greedy_search" } },+ recognizer: { transcribe: async (samples: Float32Array) => `Chunk ${samples[0]}` },+ createSegmenter: () => ({+ accept: (samples: Float32Array) => [ { start: 0, samples } ],+ flush: () => [],+ isSpeaking: () => false+ })+};++let parentPort: FakeParentPort;++async function startWorker() {+ parentPort = new FakeParentPort();+ Object.defineProperty(process, "parentPort", { value: parentPort, configurable: true });+ vi.resetModules();+ await import("./transcription_worker");+ return parentPort;+}++function capturePort() {+ return Object.assign(new EventEmitter(), { start: vi.fn(), close: vi.fn() });+}++const START: WorkerRequest = {+ type: "start", noteId: "meeting", modelDirectory: "/models", recordingDirectory: null+};++beforeEach(() => {+ vi.clearAllMocks();+ h.fileSinks.length = 0;+ h.recorders.length = 0;+ h.loadEngine.mockResolvedValue(engine);+});++afterEach(() => {+ Reflect.deleteProperty(process, "parentPort");+ vi.useRealTimers();+});++describe("transcription process", () => {+ it("transcribes what the capture page posts, and stops once its last chunk arrived", async () => {+ const parent = await startWorker();+ parent.send(START);+ const ready = await parent.next("ready");+ expect(ready).toMatchObject({ type: "ready", settings: engine.settings });+ expect(h.loadEngine).toHaveBeenCalledExactlyOnceWith("/models");+ expect(h.fileSinks).toEqual([]);++ const port = capturePort();+ parent.send({ type: "capture" }, [ port ]);+ expect(port.start).toHaveBeenCalledOnce();+ port.emit("message", { data: { source: "system", samples: Float32Array.of(7) } });+ expect(await parent.next("utterance")).toMatchObject({+ utterance: { source: "system", text: "Chunk 7" }+ });++ parent.send({ type: "stop" });+ await new Promise((resolve) => setTimeout(resolve));+ expect(parent.posted.map((event) => event.type)).not.toContain("stopped");+ port.emit("message", { data: { end: true } });+ await parent.next("stopped");+ expect(port.close).toHaveBeenCalledOnce();+ });++ it("relays the session's errors, and stops even when its capture cannot close", async () => {+ const parent = await startWorker();+ h.loadEngine.mockResolvedValueOnce({+ ...engine,+ createSegmenter: () => {+ throw new Error("VAD model missing");+ }+ });+ parent.send(START);+ await parent.next("ready");+ parent.send({ type: "capture" });++ const port = capturePort();+ port.close.mockImplementation(() => {+ throw new Error("port already closed");+ });+ parent.send({ type: "capture" }, [ port ]);+ port.emit("message", { data: { source: "system", samples: Float32Array.of(1) } });+ expect(parent.posted).toContainEqual({+ type: "log", level: "error", message: "Transcription: system failed: VAD model missing"+ });++ port.emit("message", { data: { end: true } });+ parent.send({ type: "stop" });+ await parent.next("stopped");+ expect(parent.posted).toContainEqual({+ type: "log", level: "error",+ message: "Transcription: stopping failed: Error: port already closed"+ });+ });++ it("keeps the audio and the transcript of a development recording", async () => {+ const parent = await startWorker();+ parent.send({ ...START, recordingDirectory: "/recordings/meeting" });+ await parent.next("ready");++ expect(h.fileSinks).toEqual([ "/recordings/meeting" ]);+ expect(h.recorders).toEqual([+ [ "/recordings/meeting", "meeting", engine.settings, expect.anything() ]+ ]);+ expect(parent.posted).toContainEqual(+ { type: "log", level: "info", message: "keeping the audio" });+ });++ it("reports an engine that cannot load", async () => {+ h.loadEngine.mockRejectedValueOnce(new Error("Protobuf parsing failed"));+ const parent = await startWorker();+ parent.send(START);+ expect(await parent.next("failed"))+ .toEqual({ type: "failed", message: "Protobuf parsing failed" });+ });++ it("stops regardless when the capture page never posts its end", async () => {+ const parent = await startWorker();+ parent.send(START);+ await parent.next("ready");+ parent.send({ type: "capture" }, [ capturePort() ]);++ vi.useFakeTimers();+ parent.send({ type: "stop" });+ await vi.advanceTimersByTimeAsync(2000);+ vi.useRealTimers();+ await parent.next("stopped");+ });+});diff --git a/apps/desktop/src/services/transcription/worker_client.spec.ts b/apps/desktop/src/services/transcription/worker_client.spec.tsindex edabc231da..948cac1dd8 100644--- a/apps/desktop/src/services/transcription/worker_client.spec.ts+++ b/apps/desktop/src/services/transcription/worker_client.spec.ts@@ -7,12 +7,15 @@ import { TranscriptionWorker, type WorkerListeners } from "./worker_client";const h = vi.hoisted(() => ({fork: vi.fn(),- hasBundle: false+ hasBundle: false,+ hasSources: true}));vi.mock("electron", () => ({ utilityProcess: { fork: h.fork } }));vi.mock("fs", () => ({- default: { existsSync: (file: string) => !file.endsWith(".cjs") || h.hasBundle }+ default: {+ existsSync: (file: string) => file.endsWith(".cjs") ? h.hasBundle : h.hasSources+ }}));class FakeProcess extends EventEmitter {@@ -35,6 +38,7 @@ let listeners: {beforeEach(() => {vi.clearAllMocks();h.hasBundle = false;+ h.hasSources = true;child = new FakeProcess();h.fork.mockReturnValue(child);listeners = {@@ -56,9 +60,14 @@ describe("TranscriptionWorker", () => {new TranscriptionWorker(listeners);h.hasBundle = true;new TranscriptionWorker(listeners);+ // Neither: the bundle's path, so the failure names the file a build would have.+ h.hasBundle = false;+ h.hasSources = false;+ new TranscriptionWorker(listeners);- expect(h.fork.mock.calls.map(([ file ]) => path.basename(file as string)))- .toEqual([ "transcription_worker.ts", "transcription_worker.cjs" ]);+ expect(h.fork.mock.calls.map(([ file ]) => path.basename(file as string))).toEqual([+ "transcription_worker.ts", "transcription_worker.cjs", "transcription_worker.cjs"+ ]);});it("resolves once the engine is ready, then relays what the process reports", async () => {