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
feat(transcription): hide the feature where the engine does not load
Elian Doran8e879ce82adc
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 7a5ea64ed1..401fa47d99 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4650,7 +4650,8 @@"model_standard_description": "Parakeet TDT 0.6B v3 by NVIDIA, quantized so that it runs well on most computers.","model_high_accuracy_description": "Parakeet TDT 0.6B v3 by NVIDIA at full precision. It makes fewer mistakes, but needs about 1.6 GB more memory while recording.","model_size": "{{size}} download",- "keep_recordings_warning": "Before turning this on, ask everyone in the meeting to agree to being recorded. Germany, France and several US states make recording a conversation without everyone's consent a criminal offense, and when people join from different places, the strictest of their laws applies. The audio is stored unencrypted, even for protected notes."+ "keep_recordings_warning": "Before turning this on, ask everyone in the meeting to agree to being recorded. Germany, France and several US states make recording a conversation without everyone's consent a criminal offense, and when people join from different places, the strictest of their laws applies. The audio is stored unencrypted, even for protected notes.",+ "unsupported": "Meeting transcription is not available on this computer: its speech recognition engine could not be loaded."},"resources_options": {"list_title": "Resources",diff --git a/apps/client/src/widgets/launch_bar/RecordMeetingButton.spec.tsx b/apps/client/src/widgets/launch_bar/RecordMeetingButton.spec.tsxindex eb4a00b8b4..f142f14c48 100644--- a/apps/client/src/widgets/launch_bar/RecordMeetingButton.spec.tsx+++ b/apps/client/src/widgets/launch_bar/RecordMeetingButton.spec.tsx@@ -13,7 +13,8 @@ const mocks = vi.hoisted(() => ({transcriptionModel: null as string | null,speakersEnabled: true,transcriptionEnabled: true,- keepRecordings: false+ keepRecordings: false,+ isSupported: vi.fn()}));vi.mock("../react/hooks", async (importOriginal) => ({@@ -63,6 +64,7 @@ beforeEach(() => {mocks.speakersEnabled = true;mocks.transcriptionEnabled = true;mocks.keepRecordings = false;+ mocks.isSupported.mockResolvedValue(true);vi.useFakeTimers({ now: new Date(2026, 9, 13, 14, 30), toFake: [ "Date" ] });});@@ -178,6 +180,7 @@ describe("RecordMeetingButton", () => {async function renderWithState(state: Partial<TranscriptionState>) {window.electronApi = {transcription: {+ isSupported: mocks.isSupported,getState: async () => ({status: "idle", noteId: null, pendingSources: [], ...state}),@@ -226,11 +229,22 @@ describe("RecordMeetingButton", () => {window.electronApi = undefined;});- it("shows nothing while transcription is turned off in the settings", () => {+ it("shows nothing while transcription is turned off or the computer cannot transcribe", async () => {+ expect((await renderWithState({ status: "idle" }))?.querySelector("button")).not.toBeNull();+ expect(mocks.isSupported).toHaveBeenCalledOnce();+mocks.transcriptionEnabled = false;- const container = renderInto(<RecordMeetingButton launcherNote={{} as FNote} />);- expect(container.querySelector(".record-meeting-launcher")).toBeNull();- expect(container.querySelector("button")).toBeNull();+ const turnedOff = await renderWithState({ status: "idle" });+ expect(turnedOff?.querySelector(".record-meeting-launcher")).toBeNull();+ expect(turnedOff?.querySelector("button")).toBeNull();+ expect(mocks.isSupported).toHaveBeenCalledOnce();++ mocks.transcriptionEnabled = true;+ mocks.isSupported.mockResolvedValue(false);+ expect((await renderWithState({ status: "idle" }))?.querySelector("button")).toBeNull();+ window.electronApi = undefined;+ expect(renderInto(<RecordMeetingButton launcherNote={{} as FNote} />).querySelector("button"))+ .toBeNull();});it("keeps the stop button while a recording outlasts turning transcription off", async () => {@@ -243,10 +257,11 @@ describe("RecordMeetingButton", () => {window.electronApi = undefined;});- it("marks the launcher as beta", () => {- const container = renderInto(<RecordMeetingButton launcherNote={{} as FNote} />);- expect(container.querySelector(".record-meeting-launcher .record-meeting-beta-badge")?.textContent)+ it("marks the launcher as beta", async () => {+ const container = await renderWithState({ status: "idle" });+ expect(container?.querySelector(".record-meeting-launcher .record-meeting-beta-badge")?.textContent).toContain("common.beta");+ window.electronApi = undefined;});it("says once why a recording stopped by itself", async () => {@@ -256,6 +271,7 @@ describe("RecordMeetingButton", () => {}));window.electronApi = {transcription: {+ isSupported: async () => true,getState: async () => ({ status: "idle", noteId: null, pendingSources: [] }),onStateChanged: (callback: typeof onStateChanged) => {onStateChanged = callback;@@ -283,6 +299,7 @@ describe("RecordMeetingButton", () => {const report = (status: TranscriptionState["status"]) =>act(() => onStateChanged({ status, noteId: "meeting", pendingSources: [] }));const transcription = {+ isSupported: async () => true,getState: async () => ({ status: "recording", noteId: "meeting", pendingSources: [] }),onStateChanged: (callback: typeof onStateChanged) => {onStateChanged = callback;diff --git a/apps/client/src/widgets/launch_bar/RecordMeetingButton.tsx b/apps/client/src/widgets/launch_bar/RecordMeetingButton.tsxindex 940742e213..50beab05a6 100644--- a/apps/client/src/widgets/launch_bar/RecordMeetingButton.tsx+++ b/apps/client/src/widgets/launch_bar/RecordMeetingButton.tsx@@ -23,13 +23,14 @@ import {/*** Launcher button that records a meeting: the first click creates the meeting note and starts the* recording, the second stops it. Desktop only, since the main process does the recording, and- * shown only while `transcriptionEnabled` is on. Its corner badge reads "Beta" while idle and the+ * shown only while `transcriptionEnabled` is on and the computer can transcribe. Its corner badge reads "Beta" while idle and the* time elapsed while recording.*/export default function RecordMeetingButton({ launcherNote }: LauncherNoteProps) {const { icon, title } = useLauncherIconAndTitle(launcherNote);const { status, error, startedAt } = useTranscriptionState();const [ isEnabled ] = useTriliumOptionBool("transcriptionEnabled");+ const isSupported = useTranscriptionSupported(isEnabled);const [ keepsRecordings ] = useTriliumOptionBool("transcriptionKeepRecordings");const [ now, setNow ] = useState(Date.now);const handleClick = useCallback(() => {@@ -52,7 +53,7 @@ export default function RecordMeetingButton({ launcherNote }: LauncherNoteProps)}, [ status ]);// A recording outlives the switch turning off, so its stop button stays until it ends.- if (!isEnabled && status === "idle") {+ if ((!isEnabled || !isSupported) && status === "idle") {return null;}@@ -134,6 +135,35 @@ export function useTranscriptionState() {return state;}+/**+ * Whether this computer can transcribe, from `electronApi.transcription.isSupported()`, which+ * starts a process to find out: asked only once `shouldAsk` holds. `false` outside the desktop+ * app, `undefined` until the main process answers.+ */+export function useTranscriptionSupported(shouldAsk: boolean) {+ const [ isSupported, setIsSupported ] = useState<boolean | undefined>(+ window.electronApi?.transcription ? undefined : false);++ useEffect(() => {+ const api = window.electronApi?.transcription;+ if (!api || !shouldAsk) {+ return;+ }++ let mounted = true;+ void api.isSupported().then((value) => {+ if (mounted) {+ setIsSupported(value);+ }+ });+ return () => {+ mounted = false;+ };+ }, [ shouldAsk ]);++ return isSupported;+}+/** Starts a recording into a new meeting note when idle, stops the running one when recording. */export async function toggleRecording(status: TranscriptionStatus) {const api = window.electronApi?.transcription;diff --git a/apps/client/src/widgets/type_widgets/options/transcription.spec.tsx b/apps/client/src/widgets/type_widgets/options/transcription.spec.tsxindex 482787db76..faac7775fd 100644--- a/apps/client/src/widgets/type_widgets/options/transcription.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/transcription.spec.tsx@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({saved: [] as string[],bools: {} as Record<string, boolean>,getRecordingsDirectory: vi.fn(),+ isSupported: vi.fn(),savedBools: [] as [ string, boolean ][],getResources: vi.fn()}));@@ -86,8 +87,12 @@ beforeEach(() => {freeBytes: null,download: null});+ mocks.isSupported.mockReset().mockResolvedValue(true);window.electronApi = {- transcription: { getRecordingsDirectory: mocks.getRecordingsDirectory }+ transcription: {+ getRecordingsDirectory: mocks.getRecordingsDirectory,+ isSupported: mocks.isSupported+ }} as unknown as typeof window.electronApi;host = document.body.appendChild(document.createElement("div"));});@@ -236,6 +241,15 @@ describe("TranscriptionSettings", () => {.toContain("transcription_options.model_standard");});+ it("explains that this computer cannot transcribe, in place of the settings", async () => {+ mocks.isSupported.mockResolvedValue(false);+ expect(open()).not.toBeNull();+ await act(async () => {});+ expect(host.querySelector(".transcription-model-picker")).toBeNull();+ expect(host.querySelector("input.switch-toggle[id^='transcription-enabled-']")).toBeNull();+ expect(host.textContent).toContain("transcription_options.unsupported");+ });+it("explains that the page applies to desktop builds only, elsewhere", () => {mocks.electron = false;expect(open()).toBeNull();diff --git a/apps/client/src/widgets/type_widgets/options/transcription.tsx b/apps/client/src/widgets/type_widgets/options/transcription.tsxindex 352a018c42..3e604a073b 100644--- a/apps/client/src/widgets/type_widgets/options/transcription.tsx+++ b/apps/client/src/widgets/type_widgets/options/transcription.tsx@@ -9,6 +9,7 @@ import { useEffect, useState } from "preact/hooks";import { t } from "../../../services/i18n";import server from "../../../services/server";import { formatSize, isElectron } from "../../../services/utils";+import { useTranscriptionSupported } from "../../launch_bar/RecordMeetingButton";import { Badge } from "../../react/Badge";import { Card, CardSection, OptionCardSection } from "../../react/Card";import { DirectoryLocation } from "../../react/DirectoryLink";@@ -22,6 +23,7 @@ import RelatedSettings from "./components/RelatedSettings";export default function TranscriptionSettings() {const [ isEnabled, setIsEnabled ] = useTriliumOptionBool("transcriptionEnabled");+ const isSupported = useTranscriptionSupported(true);if (!isElectron()) {return (@@ -32,6 +34,15 @@ export default function TranscriptionSettings() {);}+ if (isSupported === false) {+ return (+ <>+ <OptionsPageHeader helpUrl="Y84QCbArmK3z" />+ <NoItems icon="bx bx-microphone-off" text={t("transcription_options.unsupported")} />+ </>+ );+ }+return (<><OptionsPageHeaderdiff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.tsindex 193e0ca7e5..19ea491a2b 100644--- a/apps/desktop/src/preload.spec.ts+++ b/apps/desktop/src/preload.spec.ts@@ -724,13 +724,15 @@ describe("preload script", () => {describe("transcription", () => {const transcription = () => getGroup("transcription");- it("start, stop, getState, renameSpeaker and getRecordingsDirectory invoke their IPC channels", async () => {+ it("isSupported, start, stop, getState, renameSpeaker and getRecordingsDirectory invoke their IPC channels", async () => {+ await transcription().isSupported();await transcription().start("meeting");await transcription().stop();await transcription().getState();await transcription().renameSpeaker("transcript1", "system:1", "Alexandra");await transcription().getRecordingsDirectory();expect(ipcRendererInvoked).toEqual([+ { channel: "transcription-is-supported", args: [] },{ channel: "transcription-start", args: [ "meeting" ] },{ channel: "transcription-stop", args: [] },{ channel: "transcription-get-state", args: [] },diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex 39910e06e0..fdd2f49d6d 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -255,6 +255,9 @@ contextBridge.exposeInMainWorld("electronApi", {},transcription: {+ isSupported() {+ return ipcRenderer.invoke("transcription-is-supported");+ },start(noteId: string) {return ipcRenderer.invoke("transcription-start", noteId);},diff --git a/apps/desktop/src/services/transcription/engine.spec.ts b/apps/desktop/src/services/transcription/engine.spec.tsindex d37e34868d..5b91ec9b1f 100644--- a/apps/desktop/src/services/transcription/engine.spec.ts+++ b/apps/desktop/src/services/transcription/engine.spec.ts@@ -1,7 +1,7 @@import path from "path";import { beforeEach, describe, expect, it, vi } from "vitest";-import { loadSherpaEngine } from "./engine";+import { loadSherpaEngine, probeSherpa } from "./engine";const h = vi.hoisted(() => ({/** Base names of the optional model files the model directory holds. */@@ -53,6 +53,7 @@ const vads: FakeVad[] = [];vi.mock("sherpa-onnx-node", () => ({default: {+ version: "1.13.8",OfflineRecognizer: {createAsync: async (config: Record<string, unknown>) => {h.recognizerConfig = config;@@ -110,6 +111,7 @@ const MODELS = {beforeEach(() => {h.installed = [];+ h.recognizerConfig = null;h.isEmbeddingReady = true;h.decoded.length = 0;h.embeddings.length = 0;@@ -117,6 +119,13 @@ beforeEach(() => {vads.length = 0;});+describe("probeSherpa", () => {+ it("loads sherpa-onnx without any model and reports its version", async () => {+ expect(await probeSherpa()).toBe("1.13.8");+ expect(h.recognizerConfig).toBeNull();+ });+});+describe("loadSherpaEngine", () => {it("loads Parakeet and Silero from their paths and reports their settings", async () => {// The precision comes from the paths, whatever else the directory holds.diff --git a/apps/desktop/src/services/transcription/engine.ts b/apps/desktop/src/services/transcription/engine.tsindex e70c22d559..c42cbde493 100644--- a/apps/desktop/src/services/transcription/engine.ts+++ b/apps/desktop/src/services/transcription/engine.ts@@ -102,6 +102,25 @@ const VAD_SETTINGS = {windowSize: VAD_WINDOW_SIZE};+/**+ * Loads sherpa-onnx's native addon, with onnxruntime, without any model.+ *+ * @returns The sherpa-onnx version of the addon.+ */+export async function probeSherpa() {+ try {+ const mod = await import("sherpa-onnx-node");+ const sherpa = mod.default ?? mod;+ return sherpa.version;+ } catch (e) {+ // `sherpa-onnx-node` reports only that no addon loaded; loading the platform package's+ // addon directly throws the reason, such as a missing shared library.+ const platform = process.platform === "win32" ? "win" : process.platform;+ require(`sherpa-onnx-${platform}-${process.arch}/sherpa-onnx.node`);+ throw e;+ }+}+/*** Loads the local engine from `models`: Silero VAD for segmentation and Parakeet TDT 0.6B v3 for* recognition, both through sherpa-onnx, and the speaker model when it is given and installed.diff --git a/apps/desktop/src/services/transcription/index.spec.ts b/apps/desktop/src/services/transcription/index.spec.tsindex 7ce35f2ba8..dd1b06fc5f 100644--- a/apps/desktop/src/services/transcription/index.spec.ts+++ b/apps/desktop/src/services/transcription/index.spec.ts@@ -21,6 +21,7 @@ const h = vi.hoisted(() => ({speakersEnabled: true,registerResource: vi.fn(),log: { info: vi.fn(), error: vi.fn() },+ probe: vi.fn(),listeners: null as WorkerListeners | null,captureOptions: null as CaptureWindowOptions | null,worker: { start: vi.fn(), connectCapture: vi.fn(), stop: vi.fn(), kill: vi.fn() },@@ -110,6 +111,7 @@ vi.mock("./attachment_sink", () => ({}}));vi.mock("./worker_client", () => ({+ probeEngine: h.probe,TranscriptionWorker: class {start = h.worker.start;connectCapture = h.worker.connectCapture;@@ -338,6 +340,21 @@ describe("transcription IPC", () => {vi.useRealTimers();});+ it("is supported where the engine loads, probing once per run and logging why it did not", async () => {+ h.probe.mockResolvedValue(null);+ let invoke = await loadService();+ expect(await invoke("transcription-is-supported")).toBe(true);+ expect(await invoke("transcription-is-supported")).toBe(true);+ expect(h.probe).toHaveBeenCalledOnce();+ expect(h.log.error).not.toHaveBeenCalled();++ h.probe.mockResolvedValue("libstdc++.so.6: version `GLIBCXX_3.4.29' not found");+ invoke = await loadService();+ expect(await invoke("transcription-is-supported")).toBe(false);+ expect(h.log.error).toHaveBeenCalledExactlyOnceWith("Transcription is unavailable on "+ + "this computer: libstdc++.so.6: version `GLIBCXX_3.4.29' not found");+ });+it("tells where the recordings are kept, as an absolute path, creating the directory", async () => {const invoke = await loadService();const directory = path.resolve("data", "transcription-recordings");diff --git a/apps/desktop/src/services/transcription/index.ts b/apps/desktop/src/services/transcription/index.tsindex e917c17dba..93d365ee64 100644--- a/apps/desktop/src/services/transcription/index.ts+++ b/apps/desktop/src/services/transcription/index.ts@@ -10,7 +10,7 @@ import path from "path";import { AttachmentSink } from "./attachment_sink";import { CaptureWindow } from "./capture";import { getModelPaths, TRANSCRIPTION_MODELS } from "./model";-import { TranscriptionWorker } from "./worker_client";+import { probeEngine, TranscriptionWorker } from "./worker_client";/*** Where the audio and the transcript as produced of each recording are kept, one directory per@@ -41,9 +41,12 @@ let stopping: Promise<void> | null = null;const unsavedSinks = new Set<AttachmentSink>();/** `waiting` while a quit waits for the transcription, `done` once it may go ahead. */let quitting: "no" | "waiting" | "done" = "no";+/** {@link isSupported}'s answer, once asked. */+let isSupportedHere: Promise<boolean> | null = null;export function setupTranscriptionHandlers() {resources.register(...TRANSCRIPTION_MODELS);+ ipcMain.handle("transcription-is-supported", () => isSupported());ipcMain.handle("transcription-start", (_event, noteId: unknown) => startRecording(noteId));ipcMain.handle("transcription-stop", () => stopRecording());ipcMain.handle("transcription-get-state", () => getState());@@ -145,6 +148,21 @@ export function getState() {return state;}+/**+ * Whether sherpa-onnx's native addon loads on this computer, which a transcription process tries+ * once per run, without any model. A build without the addon for this platform and processor, or+ * a system missing a library it needs, cannot transcribe.+ */+export function isSupported() {+ isSupportedHere ??= probeEngine().then((error) => {+ if (error) {+ getLog().error(`Transcription is unavailable on this computer: ${error}`);+ }+ return !error;+ });+ return isSupportedHere;+}+/*** Names a speaker of the transcript attachment `attachmentId` through the running recording's* sink, when that is the transcript it writes: the sink is then its only writer.diff --git a/apps/desktop/src/services/transcription/protocol.ts b/apps/desktop/src/services/transcription/protocol.tsindex abfa8ce24b..607b819761 100644--- a/apps/desktop/src/services/transcription/protocol.ts+++ b/apps/desktop/src/services/transcription/protocol.ts@@ -30,7 +30,9 @@ export type WorkerRequest =}/** Sent once the recording runs, with the port the capture page posts its samples to. */| { type: "capture" }- | { type: "stop" };+ | { type: "stop" }+ /** Sent instead of `start`: loads sherpa-onnx without any model, then reports `probed`. */+ | { type: "probe" };/** What the transcription process reports to the main process. */export type WorkerEvent =@@ -41,7 +43,9 @@ export type WorkerEvent =| { type: "utterance"; utterance: TranscriptUtterance }| { type: "log"; level: keyof Logger; message: string }/** Every utterance captured before `stop` has been sent. */- | { type: "stopped" };+ | { type: "stopped" }+ /** Answers `probe`: the version of sherpa-onnx that loaded, or why it did not load. */+ | { type: "probed"; version: string } | { type: "probed"; error: string };/** One chunk of samples, posted by the capture page straight to the transcription process. */export interface CaptureChunk {diff --git a/apps/desktop/src/services/transcription/transcription_worker.spec.ts b/apps/desktop/src/services/transcription/transcription_worker.spec.tsindex 56a6514d22..70708539fa 100644--- a/apps/desktop/src/services/transcription/transcription_worker.spec.ts+++ b/apps/desktop/src/services/transcription/transcription_worker.spec.ts@@ -5,11 +5,12 @@ import type { WorkerEvent, WorkerRequest } from "./protocol";const h = vi.hoisted(() => ({loadEngine: vi.fn(),+ probe: vi.fn(),fileSinks: [] as string[],recorders: [] as unknown[][]}));-vi.mock("./engine", () => ({ loadSherpaEngine: h.loadEngine }));+vi.mock("./engine", () => ({ loadSherpaEngine: h.loadEngine, probeSherpa: h.probe }));vi.mock("./audio_recorder", () => ({TranscriptFileSink: class {constructor(directory: string) {@@ -170,6 +171,20 @@ describe("transcription process", () => {.toEqual({ type: "failed", message: "Protobuf parsing failed" });});+ it("answers a probe with the engine's version, or why it did not load", async () => {+ h.probe.mockResolvedValueOnce("1.13.8");+ const parent = await startWorker();+ parent.send({ type: "probe" });+ expect(await parent.next("probed")).toEqual({ type: "probed", version: "1.13.8" });+ expect(h.loadEngine).not.toHaveBeenCalled();++ h.probe.mockRejectedValueOnce(new Error("Could not find sherpa-onnx-node."));+ const failing = await startWorker();+ failing.send({ type: "probe" });+ expect(await failing.next("probed"))+ .toEqual({ type: "probed", error: "Could not find sherpa-onnx-node." });+ });+it("stops regardless when the capture page never posts its end", async () => {const parent = await startWorker();parent.send(START);diff --git a/apps/desktop/src/services/transcription/transcription_worker.ts b/apps/desktop/src/services/transcription/transcription_worker.tsindex f40c5cfba3..3e3e3c32b9 100644--- a/apps/desktop/src/services/transcription/transcription_worker.ts+++ b/apps/desktop/src/services/transcription/transcription_worker.ts@@ -6,7 +6,7 @@*/import { TranscriptFileSink, WavRecorder } from "./audio_recorder";-import { loadSherpaEngine } from "./engine";+import { loadSherpaEngine, probeSherpa } from "./engine";import type { Logger, WorkerEvent, WorkerRequest } from "./protocol";import { type AudioTap, PortCapture, RecordingSession, type TranscriptSink } from "./session";@@ -39,6 +39,11 @@ process.parentPort.on("message", ({ data, ports }) => {case "stop":void stop();break;+ case "probe":+ probeSherpa().then(+ (version) => post({ type: "probed", version }),+ (e) => post({ type: "probed", error: (e as Error)?.message ?? String(e) }));+ break;}});diff --git a/apps/desktop/src/services/transcription/worker_client.spec.ts b/apps/desktop/src/services/transcription/worker_client.spec.tsindex fc406fd0e8..ef44414fdd 100644--- a/apps/desktop/src/services/transcription/worker_client.spec.ts+++ b/apps/desktop/src/services/transcription/worker_client.spec.ts@@ -3,7 +3,7 @@ import path from "path";import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from "vitest";import type { Logger, WorkerEvent } from "./protocol";-import { TranscriptionWorker, type WorkerListeners } from "./worker_client";+import { probeEngine, TranscriptionWorker, type WorkerListeners } from "./worker_client";const h = vi.hoisted(() => ({fork: vi.fn(),@@ -155,3 +155,35 @@ describe("TranscriptionWorker", () => {expect(listeners.onUnexpectedExit).toHaveBeenCalledOnce();});});++describe("probeEngine", () => {+ it("asks a process of its own to load the engine, and ends it with the answer", async () => {+ const loaded = probeEngine();+ expect(child.postMessage).toHaveBeenCalledExactlyOnceWith({ type: "probe" });+ child.report({ type: "probed", version: "1.13.8" });+ expect(await loaded).toBeNull();+ expect(child.kill).toHaveBeenCalledOnce();++ child = new FakeProcess();+ h.fork.mockReturnValue(child);+ const failed = probeEngine();+ child.report({ type: "log", level: "info", message: "loading" });+ child.report({ type: "probed", error: "Could not find sherpa-onnx-node." });+ expect(await failed).toBe("Could not find sherpa-onnx-node.");+ expect(child.kill).toHaveBeenCalledOnce();+ });++ it("says so when the process dies or does not answer", async () => {+ const crashed = probeEngine();+ child.emit("exit", 133);+ expect(await crashed).toBe("The transcription process exited with code 133.");++ vi.useFakeTimers();+ child = new FakeProcess();+ h.fork.mockReturnValue(child);+ const silent = probeEngine();+ await vi.advanceTimersByTimeAsync(30_000);+ expect(await silent).toBe("The transcription process did not answer in time.");+ expect(child.kill).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/services/transcription/worker_client.ts b/apps/desktop/src/services/transcription/worker_client.tsindex 284d63b12e..ee237bc48b 100644--- a/apps/desktop/src/services/transcription/worker_client.ts+++ b/apps/desktop/src/services/transcription/worker_client.ts@@ -18,6 +18,8 @@ type StartRequest = Extract<WorkerRequest, { type: "start" }>;/** How long {@link TranscriptionWorker.stop} waits for the speech still queued. */const STOP_TIMEOUT_MS = 2 * 60 * 1000;+/** How long {@link probeEngine} waits for the transcription process to load sherpa-onnx. */+const PROBE_TIMEOUT_MS = 30 * 1000;/*** The transcription process (`transcription_worker.ts`), from the main process: starts it,@@ -32,9 +34,7 @@ export class TranscriptionWorker {private hasExited = false;constructor(private readonly listeners: WorkerListeners) {- this.child = utilityProcess.fork(getWorkerEntry(), [], {- serviceName: "Trilium transcription"- });+ this.child = forkWorker();this.child.on("message", (event: WorkerEvent) => this.handle(event));this.child.on("exit", (code) => this.handleExit(code));}@@ -115,6 +115,38 @@ export class TranscriptionWorker {}}+/**+ * Starts a transcription process that only loads sherpa-onnx's native addon, without any model,+ * and ends it.+ *+ * @returns `null` once the addon loaded, or why it did not.+ */+export function probeEngine() {+ return new Promise<string | null>((resolve) => {+ const child = forkWorker();+ const timeout = setTimeout(+ () => finish("The transcription process did not answer in time."), PROBE_TIMEOUT_MS);+ function finish(error: string | null) {+ clearTimeout(timeout);+ child.removeAllListeners();+ child.kill();+ resolve(error);+ }++ child.on("message", (event: WorkerEvent) => {+ if (event.type === "probed") {+ finish("error" in event ? event.error : null);+ }+ });+ child.on("exit", (code) => finish(`The transcription process exited with code ${code}.`));+ child.postMessage({ type: "probe" } satisfies WorkerRequest);+ });+}++function forkWorker() {+ return utilityProcess.fork(getWorkerEntry(), [], { serviceName: "Trilium transcription" });+}+/*** The bundled `transcription_worker.cjs` beside the main bundle, or the TypeScript when running* from sources, which the utility process reads through the `--import tsx` it inherits indiff --git a/apps/desktop/src/sherpa-onnx-node.d.ts b/apps/desktop/src/sherpa-onnx-node.d.tsindex b660693379..47aa76bd38 100644--- a/apps/desktop/src/sherpa-onnx-node.d.ts+++ b/apps/desktop/src/sherpa-onnx-node.d.ts@@ -1,4 +1,7 @@declare module "sherpa-onnx-node" {+ /** The sherpa-onnx version of the native addon. */+ export const version: string;+export interface OfflineStream {acceptWaveform(wave: { samples: Float32Array; sampleRate: number }): void;}diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Meeting transcription.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Meeting transcription.htmlindex d68d9816ff..f86e19d675 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Meeting transcription.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Meeting transcription.html@@ -121,9 +121,11 @@</aside><h2>Limitations</h2><ul>- <li>Meeting transcription is not available on every processor. Where it is- not, the <em>Transcribe meeting</em> button does not appear, and the <em>Transcription</em> options- say so.</li>+ <li>Meeting transcription needs a speech recognition engine that does not+ load on every computer, for example on Linux distributions older than Ubuntu+ 22.04 or Debian 12. Where it does not load, the <em>Transcribe meeting</em> button+ does not appear, the <em>Transcription</em> options say so, and the log records+ why.</li><li>The transcript is made from the audio played by your device. A participantwhose voice does not come out of your speakers or headphones, for examplesomeone in the same room, is transcribed only as far as your microphonediff --git a/docs/User Guide/User Guide/Meeting transcription.md b/docs/User Guide/User Guide/Meeting transcription.mdindex cd04e92f9e..8fcd777745 100644--- a/docs/User Guide/User Guide/Meeting transcription.md+++ b/docs/User Guide/User Guide/Meeting transcription.md@@ -53,7 +53,7 @@ The settings are in <a class="reference-link" href="Basic%20Concepts%20and%20Fe## Limitations-* Meeting transcription is not available on every processor. Where it is not, the _Transcribe meeting_ button does not appear, and the _Transcription_ options say so.+* Meeting transcription needs a speech recognition engine that does not load on every computer, for example on Linux distributions older than Ubuntu 22.04 or Debian 12. Where it does not load, the _Transcribe meeting_ button does not appear, the _Transcription_ options say so, and the log records why.* The transcript is made from the audio played by your device. A participant whose voice does not come out of your speakers or headphones, for example someone in the same room, is transcribed only as far as your microphone picks them up, and is labeled _Me_.* Speaker identification works best with a few clearly distinct voices. Similar voices, many participants or poor call quality can lead to speakers being merged or split.* Accuracy is lower for languages other than English, and the model can switch to the wrong language for short passages.diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.tsindex b3a5ec8b85..34b0f5b70b 100644--- a/packages/commons/src/lib/electron_api_interface.ts+++ b/packages/commons/src/lib/electron_api_interface.ts@@ -741,6 +741,12 @@ export interface TranscriptionState {* renderer only starts and stops it; the audio never passes through the renderer.*/export interface ElectronTranscriptionApi {+ /**+ * Whether this build can transcribe on this computer: `false` when it carries no speech+ * recognition engine for the platform and processor it runs on.+ */+ isSupported(): Promise<boolean>;+/*** Starts recording the microphone and the system audio for the meeting note `noteId`.*