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(desktop): start meeting transcription from the launcher
Elian Doran736571c0cb16
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex a88ec5e0b5..af734a4189 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4579,6 +4579,9 @@"edit_excerpt": "Edit excerpt"},"record_meeting": {- "note_title": "Meeting {{date}}"+ "note_title": "Meeting {{date}}",+ "starting": "Starting the recording…",+ "stop": "Stop recording",+ "stopping": "Finishing the transcript…"}}diff --git a/apps/client/src/widgets/launch_bar/RecordMeetingButton.css b/apps/client/src/widgets/launch_bar/RecordMeetingButton.cssnew file mode 100644index 0000000000..c2deb6e5c9--- /dev/null+++ b/apps/client/src/widgets/launch_bar/RecordMeetingButton.css@@ -0,0 +1,3 @@+.launcher-button.record-meeting-active {+ color: var(--danger-color, #dc3545);+}diff --git a/apps/client/src/widgets/launch_bar/RecordMeetingButton.spec.tsx b/apps/client/src/widgets/launch_bar/RecordMeetingButton.spec.tsxindex 4fc6edc66e..fb334d388b 100644--- a/apps/client/src/widgets/launch_bar/RecordMeetingButton.spec.tsx+++ b/apps/client/src/widgets/launch_bar/RecordMeetingButton.spec.tsx@@ -2,7 +2,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({getInboxNote: vi.fn(),- createNote: vi.fn()+ createNote: vi.fn(),+ showError: vi.fn()}));vi.mock("../../services/date_notes", () => ({@@ -11,11 +12,14 @@ vi.mock("../../services/date_notes", () => ({vi.mock("../../services/note_create", () => ({default: { createNote: mocks.createNote }}));+vi.mock("../../services/toast", () => ({+ default: { showError: mocks.showError }+}));vi.mock("../../services/i18n", () => ({t: (key: string, options?: { date?: string }) => `${key} ${options?.date}`}));-import { createMeetingNote } from "./RecordMeetingButton";+import { createMeetingNote, toggleRecording } from "./RecordMeetingButton";beforeEach(() => {vi.clearAllMocks();@@ -46,3 +50,41 @@ describe("createMeetingNote", () => {expect(mocks.createNote).not.toHaveBeenCalled();});});++describe("toggleRecording", () => {+ const transcription = { start: vi.fn(), stop: vi.fn() };++ beforeEach(() => {+ window.electronApi = { transcription } as unknown as typeof window.electronApi;+ mocks.getInboxNote.mockResolvedValue({ noteId: "inbox", isProtected: false });+ mocks.createNote.mockResolvedValue({ note: { noteId: "meeting" } });+ });++ it("starts recording into a new meeting note, and shows why it could not", async () => {+ transcription.start.mockResolvedValueOnce("");+ await toggleRecording("idle");+ expect(transcription.start).toHaveBeenCalledExactlyOnceWith("meeting");+ expect(mocks.showError).not.toHaveBeenCalled();++ transcription.start.mockResolvedValueOnce("No speech model");+ await toggleRecording("idle");+ expect(mocks.showError).toHaveBeenCalledExactlyOnceWith("No speech model");+ expect(mocks.createNote).toHaveBeenCalledTimes(2);+ });++ it("stops a running recording, and leaves one that is starting or stopping alone", async () => {+ await toggleRecording("recording");+ await toggleRecording("starting");+ await toggleRecording("stopping");++ expect(transcription.stop).toHaveBeenCalledOnce();+ expect(transcription.start).not.toHaveBeenCalled();+ expect(mocks.createNote).not.toHaveBeenCalled();+ });++ it("does nothing outside the desktop app", async () => {+ window.electronApi = undefined;+ await toggleRecording("idle");+ expect(mocks.createNote).not.toHaveBeenCalled();+ });+});diff --git a/apps/client/src/widgets/launch_bar/RecordMeetingButton.tsx b/apps/client/src/widgets/launch_bar/RecordMeetingButton.tsxindex bbefe15fee..a62a76731b 100644--- a/apps/client/src/widgets/launch_bar/RecordMeetingButton.tsx+++ b/apps/client/src/widgets/launch_bar/RecordMeetingButton.tsx@@ -1,9 +1,12 @@-import { dayjs } from "@triliumnext/commons";-import { useCallback } from "preact/hooks";+import "./RecordMeetingButton.css";++import { dayjs, type TranscriptionState, type TranscriptionStatus } from "@triliumnext/commons";+import { useCallback, useEffect, useState } from "preact/hooks";import dateNoteService from "../../services/date_notes";import { t } from "../../services/i18n";import noteCreateService from "../../services/note_create";+import toast from "../../services/toast";import {LaunchBarActionButton,LauncherNoteProps,@@ -14,25 +17,95 @@ import {export const MEETING_RECORDING_LABEL = "meetingRecording";/**- * Launcher button that starts a meeting recording. For now it only creates the meeting note in the- * inbox and opens it.+ * 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.*/export default function RecordMeetingButton({ launcherNote }: LauncherNoteProps) {const { icon, title } = useLauncherIconAndTitle(launcherNote);+ const { status } = useTranscriptionState();const handleClick = useCallback(() => {- void createMeetingNote();- }, []);+ void toggleRecording(status);+ }, [ status ]);return (<LaunchBarActionButtonlauncherNote={launcherNote}- icon={icon}- text={title}onClick={handleClick}+ {...getAppearance(status, icon, title)}/>);}+const BUSY_ICON = "bx bx-loader-alt bx-spin";++function getAppearance(status: TranscriptionStatus, idleIcon: string, idleTitle: string) {+ switch (status) {+ case "idle":+ return { icon: idleIcon, text: idleTitle };+ case "starting":+ return { icon: BUSY_ICON, text: t("record_meeting.starting"), disabled: true };+ case "recording":+ return {+ icon: "bx bx-stop-circle",+ text: t("record_meeting.stop"),+ className: "record-meeting-active"+ };+ case "stopping":+ return { icon: BUSY_ICON, text: t("record_meeting.stopping"), disabled: true };+ }+}++/** Follows the main process's recording, which every window shares. */+export function useTranscriptionState() {+ const [ state, setState ] = useState<TranscriptionState>({ status: "idle", noteId: null });++ useEffect(() => {+ const api = window.electronApi?.transcription;+ if (!api) {+ return;+ }++ let mounted = true;+ void api.getState().then((current) => {+ if (mounted) {+ setState(current);+ }+ });+ const unsubscribe = api.onStateChanged(setState);+ return () => {+ mounted = false;+ unsubscribe();+ };+ }, []);++ return state;+}++/** 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;+ if (!api) {+ return;+ }++ if (status === "recording") {+ await api.stop();+ return;+ }+ if (status !== "idle") {+ return;+ }++ const note = (await createMeetingNote())?.note;+ if (!note) {+ return;+ }+ const error = await api.start(note.noteId);+ if (error) {+ toast.showError(error);+ }+}+/** Creates a text note titled with the current date and time in the inbox, and opens it. */export async function createMeetingNote() {const inboxNote = await dateNoteService.getInboxNote();diff --git a/apps/desktop/src/main.spec.ts b/apps/desktop/src/main.spec.tsindex 118da24c3c..b2b2a20d5d 100644--- a/apps/desktop/src/main.spec.ts+++ b/apps/desktop/src/main.spec.ts@@ -255,6 +255,7 @@ vi.mock("./services/startup_metrics", () => ({markStartupMetric: vi.fn(),setupStartupMetricsIpc: vi.fn()}));+vi.mock("./services/transcription", () => ({ setupTranscriptionHandlers: vi.fn() }));const realPlatform = process.platform;function setPlatform(platform: NodeJS.Platform) {diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex e4b73c8ad7..6ef7bbfd48 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -47,7 +47,7 @@ import { setupRestoreHandlers } from "./services/restore";import { getSecuritySettings, registerSecurityIpcHandlers } from "./services/security_settings";import { setupShellHandlers } from "./services/shell";import { markStartupMetric, setupStartupMetricsIpc } from "./services/startup_metrics";-import { startTranscription } from "./services/transcription";+import { setupTranscriptionHandlers } from "./services/transcription";import { setupSystemTray } from "./services/tray";import windowService, { setupWindowing } from "./services/window";@@ -146,6 +146,7 @@ export async function main() {registerSecurityIpcHandlers();registerBackupPassphraseIpcHandlers();setupStartupMetricsIpc();+ setupTranscriptionHandlers();app.on("will-quit", () => {globalShortcut.unregisterAll();@@ -367,7 +368,6 @@ async function onReady() {// available to summon it from.const startHidden = wasLaunchedHidden() && !options.getOptionBool("disableTray");await windowService.createMainWindow(startHidden);- startTranscription().catch((e) => getLog().error(`Transcription did not start: ${e}`));// Repair the OS autostart entry so it matches the stored option (it can// drift if the user toggled it elsewhere). Options are loaded now that thediff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.tsindex d8f20e74fa..48c161f7ac 100644--- a/apps/desktop/src/preload.spec.ts+++ b/apps/desktop/src/preload.spec.ts@@ -720,4 +720,32 @@ describe("preload script", () => {expect(ipcRendererInvoked).toContainEqual({ channel: "restore-pick-backup", args: [] });});});++ describe("transcription", () => {+ const transcription = () => getGroup("transcription");++ it("start, stop and getState invoke their IPC channels", async () => {+ await transcription().start("meeting");+ await transcription().stop();+ await transcription().getState();+ expect(ipcRendererInvoked).toEqual([+ { channel: "transcription-start", args: [ "meeting" ] },+ { channel: "transcription-stop", args: [] },+ { channel: "transcription-get-state", args: [] }+ ]);+ });++ it("onStateChanged relays each state until unsubscribed", () => {+ const callback = vi.fn();+ const unsubscribe = transcription().onStateChanged(callback);++ const listeners = ipcRendererListeners.get("transcription-state") ?? [];+ expect(listeners).toHaveLength(1);+ listeners[0]({}, { status: "recording", noteId: "meeting" });+ expect(callback).toHaveBeenCalledExactlyOnceWith({ status: "recording", noteId: "meeting" });++ unsubscribe();+ expect(ipcRendererListeners.has("transcription-state")).toBe(false);+ });+ });});diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex 73cc4144e0..7d13bb03bf 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -5,7 +5,8 @@ import type {ElectronContextMenuParams,NativeImportOptions,OneNoteLoginResult,- RendererStartupMetric+ RendererStartupMetric,+ TranscriptionState} from "@triliumnext/commons";import { contextBridge, ipcRenderer, webFrame, webUtils } from "electron";@@ -253,6 +254,23 @@ contextBridge.exposeInMainWorld("electronApi", {}},+ transcription: {+ start(noteId: string) {+ return ipcRenderer.invoke("transcription-start", noteId);+ },+ stop() {+ return ipcRenderer.invoke("transcription-stop");+ },+ getState() {+ return ipcRenderer.invoke("transcription-get-state");+ },+ onStateChanged(callback: (state: TranscriptionState) => void) {+ const listener = (_event: unknown, state: TranscriptionState) => callback(state);+ ipcRenderer.on("transcription-state", listener);+ return () => ipcRenderer.removeListener("transcription-state", listener);+ }+ },+ws: {// Renderer → main process. Mirror channel name with the server-side// IpcMessagingProvider constants.diff --git a/apps/desktop/src/services/transcription.ts b/apps/desktop/src/services/transcription.tsdeleted file mode 100644index 98f48c2479..0000000000--- a/apps/desktop/src/services/transcription.ts+++ /dev/null@@ -1,250 +0,0 @@-import { getLog } from "@triliumnext/core";-import dataDirs from "@triliumnext/server/src/services/data_dir.js";-import { app, BrowserWindow, ipcMain, session } from "electron";-import fs from "fs";-import path from "path";-import type { OfflineRecognizer, Vad } from "sherpa-onnx-node";--const SAMPLE_RATE = 16000;-/** Silero VAD consumes 512-sample windows at 16 kHz. */-const VAD_WINDOW_SIZE = 512;-const SAMPLES_CHANNEL = "transcription-poc-samples";-const MODEL_DIR = path.join(dataDirs.TRILIUM_DATA_DIR, "transcription-model");--/** The microphone carries the local speaker; the system output carries everyone else. */-const SOURCE_LABELS = {- microphone: "Me",- system: "Others"-} as const;--type AudioSource = keyof typeof SOURCE_LABELS;--/**- * Proof of concept: records the default microphone and the system audio output in a hidden window,- * splits each into utterances with its own Silero VAD and logs what Parakeet hears in each,- * labeled by source. Runs only when `<data dir>/transcription-model` holds- * `sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8` plus `silero_vad.onnx`.- */-export async function startTranscription() {- const log = getLog();- if (!fs.existsSync(MODEL_DIR)) {- log.info(`Transcription: no model in ${MODEL_DIR}, not starting.`);- return;- }-- const mod = await import("sherpa-onnx-node");- const sherpa = mod.default ?? mod;- const recognizer = await sherpa.OfflineRecognizer.createAsync({- featConfig: { sampleRate: SAMPLE_RATE, 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",- numThreads: 2,- provider: "cpu"- },- decodingMethod: "greedy_search"- });- const createVad = () => new sherpa.Vad({- sileroVad: {- model: path.join(MODEL_DIR, "silero_vad.onnx"),- threshold: 0.5,- minSilenceDuration: 0.5,- minSpeechDuration: 0.25,- maxSpeechDuration: 20,- windowSize: VAD_WINDOW_SIZE- },- sampleRate: SAMPLE_RATE,- numThreads: 1,- provider: "cpu"- }, 60);-- const startedAt = Date.now();- const transcriber = new Transcriber(recognizer, startedAt);- const pipelines = {- microphone: new SourcePipeline("microphone", createVad(), transcriber),- system: new SourcePipeline("system", createVad(), transcriber)- };-- const captureWindow = await createCaptureWindow();-- ipcMain.on(SAMPLES_CHANNEL, (event, source: AudioSource, samples: Float32Array) => {- if (event.sender !== captureWindow.webContents || !Object.hasOwn(pipelines, source)) {- return;- }-- try {- pipelines[source].accept(samples);- } catch (e) {- log.error(`Transcription failed: ${e instanceof Error ? e.message : String(e)}`);- }- });-- try {- // getDisplayMedia() requires a user gesture, which the hidden window can only get this way.- const tracks = await captureWindow.webContents- .executeJavaScript("captureSystemAudio()", true);- log.info(`Transcription: capturing system audio from ${tracks}.`);- } catch (e) {- log.error(`Transcription: system audio unavailable: ${(e as Error)?.message ?? e}`);- }-}--/** Decodes utterances one at a time, so the log keeps their order. */-class Transcriber {- private queue = Promise.resolve();-- constructor(- private readonly recognizer: OfflineRecognizer,- private readonly startedAt: number- ) {}-- enqueue(source: AudioSource, capturedAt: number, samples: Float32Array) {- this.queue = this.queue- .then(() => this.transcribe(source, capturedAt, samples))- .catch((e) => getLog().error(`Transcription failed: ${e}`));- }-- private async transcribe(source: AudioSource, capturedAt: number, samples: Float32Array) {- const stream = this.recognizer.createStream();- stream.acceptWaveform({ samples, sampleRate: SAMPLE_RATE });- const text = (await this.recognizer.decodeAsync(stream)).text.trim();- if (text) {- const offset = formatOffset(capturedAt - this.startedAt);- getLog().info(`Transcription [${offset}] ${SOURCE_LABELS[source]}: ${text}`);- }- }-}--/**- * Runs one source through its own VAD, so speech on one source never splits an utterance on the- * other.- */-class SourcePipeline {- /** Wall-clock time of the source's first sample, which the VAD counts segment starts from. */- private firstSampleAt: number | null = null;-- constructor(- private readonly source: AudioSource,- private readonly vad: Vad,- private readonly transcriber: Transcriber- ) {}-- private peak = 0;- private sampleCount = 0;-- accept(samples: Float32Array) {- this.firstSampleAt ??= Date.now() - samples.length / SAMPLE_RATE * 1000;-- for (const sample of samples) {- this.peak = Math.max(this.peak, Math.abs(sample));- }- this.sampleCount += samples.length;- if (this.sampleCount >= 5 * SAMPLE_RATE) {- getLog().info(`Transcription: ${this.source} peak ${this.peak.toFixed(4)} over 5 s`);- this.peak = 0;- this.sampleCount = 0;- }-- for (let i = 0; i + VAD_WINDOW_SIZE <= samples.length; i += VAD_WINDOW_SIZE) {- this.vad.acceptWaveform(samples.subarray(i, i + VAD_WINDOW_SIZE));- }-- while (!this.vad.isEmpty()) {- const segment = this.vad.front(false);- this.vad.pop();- const capturedAt = this.firstSampleAt + segment.start / SAMPLE_RATE * 1000;- this.transcriber.enqueue(this.source, capturedAt, segment.samples);- }- }-}--function formatOffset(milliseconds: number) {- const seconds = Math.max(0, Math.floor(milliseconds / 1000));- return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;-}--/**- * The window runs only {@link CAPTURE_PAGE}, a local file, so it gets Node integration to reach- * `ipcRenderer` without a preload. Its in-memory session grants the microphone and screen capture- * and nothing else; every screen capture request gets the window itself plus the system audio.- */-async function createCaptureWindow() {- const captureSession = session.fromPartition("transcription");- const isAllowed = (permission: string) =>- permission === "media" || permission === "display-capture";- captureSession.setPermissionRequestHandler((_webContents, permission, callback) =>- callback(isAllowed(permission)));- captureSession.setPermissionCheckHandler((_webContents, permission) => isAllowed(permission));- // Capturing the requesting frame instead of a screen keeps the Wayland screen-cast portal- // out of the request.- captureSession.setDisplayMediaRequestHandler((request, callback) => {- callback({ video: request.frame ?? undefined, audio: "loopback" });- });-- const pagePath = path.join(app.getPath("temp"), "trilium-transcription.html");- fs.writeFileSync(pagePath, CAPTURE_PAGE);-- const window = new BrowserWindow({- show: false,- webPreferences: {- session: captureSession,- nodeIntegration: true,- contextIsolation: false,- sandbox: false,- autoplayPolicy: "no-user-gesture-required",- // Without hardware acceleration, a hidden window renders no frames, so the- // self-capture in CAPTURE_PAGE times out waiting for its video source.- offscreen: true- }- });- window.webContents.on("console-message", ({ message }) =>- getLog().info(`Transcription (capture): ${message}`));- await window.loadFile(pagePath);- return window;-}--const CAPTURE_PAGE = `<!DOCTYPE html>-<script>-const { ipcRenderer } = require("electron");-const context = new AudioContext({ sampleRate: ${SAMPLE_RATE} });--function pipe(source, media) {- const processor = context.createScriptProcessor(4096, 1, 1);- processor.onaudioprocess = (e) =>- ipcRenderer.send("${SAMPLES_CHANNEL}", source, e.inputBuffer.getChannelData(0).slice());- context.createMediaStreamSource(media).connect(processor);- processor.connect(context.destination);-}--async function captureSystemAudio() {- const media = await navigator.mediaDevices.getDisplayMedia({- video: true,- audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: false }- }).catch((e) => {- throw new Error(e.name + ": " + e.message);- });- for (const track of media.getVideoTracks()) {- track.stop();- }- const audioTracks = media.getAudioTracks();- if (!audioTracks.length) {- throw new Error("the screen capture has no audio track");- }- for (const track of audioTracks) {- console.log("System track muted=" + track.muted + " settings="- + JSON.stringify(track.getSettings()));- }- pipe("system", new MediaStream(audioTracks));- return audioTracks.map((track) => track.label).join(", ");-}--navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1 } }).then((media) => {- pipe("microphone", media);- console.log("Capturing the microphone at " + context.sampleRate + " Hz.");-}).catch((e) => console.error("Microphone unavailable: " + e));-</script>`;diff --git a/apps/desktop/src/services/transcription/capture.ts b/apps/desktop/src/services/transcription/capture.tsnew file mode 100644index 0000000000..0834e99124--- /dev/null+++ b/apps/desktop/src/services/transcription/capture.ts@@ -0,0 +1,170 @@+import { getLog } from "@triliumnext/core";+import { app, BrowserWindow, ipcMain, type IpcMainEvent, session } from "electron";+import fs from "fs";+import path from "path";++import { SAMPLE_RATE } from "./engine";++/** The microphone carries the local speaker; the system output carries everyone else. */+export type AudioSource = "microphone" | "system";++export type SamplesListener = (source: AudioSource, samples: Float32Array) => void;++/** Produces mono {@link SAMPLE_RATE} samples per source until stopped. */+export interface AudioCapture {+ /**+ * Starts every source it can and returns the ones that run.+ *+ * @throws when no source could start.+ */+ start(onSamples: SamplesListener): Promise<AudioSource[]>;+ stop(): void;+}++const SAMPLES_CHANNEL = "transcription-samples";++/** The page function that starts each source. */+const SOURCE_STARTERS = [+ [ "microphone", "captureMicrophone()" ],+ [ "system", "captureSystemAudio()" ]+] as const;++type SamplesIpcListener = (event: IpcMainEvent, source: AudioSource, samples: Float32Array) => void;++/**+ * Captures the default microphone and the system audio output in a hidden window, which streams+ * the samples to the main process over IPC.+ */+export class ElectronAudioCapture implements AudioCapture {+ private window: BrowserWindow | null = null;+ private listener: SamplesIpcListener | null = null;++ async start(onSamples: SamplesListener) {+ const window = await createCaptureWindow();+ this.window = window;+ this.listener = (event, source, samples) => {+ const isSource = source === "microphone" || source === "system";+ if (event.sender === window.webContents && isSource) {+ onSamples(source, samples);+ }+ };+ ipcMain.on(SAMPLES_CHANNEL, this.listener);++ const sources: AudioSource[] = [];+ for (const [ source, call ] of SOURCE_STARTERS) {+ try {+ // getDisplayMedia() requires a user gesture, which the hidden window only gets+ // this way.+ const tracks = await window.webContents.executeJavaScript(call, true);+ getLog().info(`Transcription: capturing ${source} from ${tracks}.`);+ sources.push(source);+ } catch (e) {+ const message = (e as Error)?.message ?? e;+ getLog().error(`Transcription: ${source} unavailable: ${message}`);+ }+ }++ if (!sources.length) {+ this.stop();+ throw new Error("No audio source could be captured.");+ }+ return sources;+ }++ stop() {+ if (this.listener) {+ ipcMain.removeListener(SAMPLES_CHANNEL, this.listener);+ this.listener = null;+ }+ if (this.window && !this.window.isDestroyed()) {+ this.window.destroy();+ }+ this.window = null;+ }+}++/**+ * The window runs only {@link CAPTURE_PAGE}, a local file, so it gets Node integration to reach+ * `ipcRenderer` without a preload. Its in-memory session grants the microphone and screen capture+ * and nothing else; every screen capture request gets the window itself plus the system audio.+ */+async function createCaptureWindow() {+ const captureSession = session.fromPartition("transcription");+ const isAllowed = (permission: string) =>+ permission === "media" || permission === "display-capture";+ captureSession.setPermissionRequestHandler((_webContents, permission, callback) =>+ callback(isAllowed(permission)));+ captureSession.setPermissionCheckHandler((_webContents, permission) => isAllowed(permission));+ // Capturing the requesting frame instead of a screen keeps the Wayland screen-cast portal+ // out of the request.+ captureSession.setDisplayMediaRequestHandler((request, callback) => {+ callback({ video: request.frame ?? undefined, audio: "loopback" });+ });++ const pagePath = path.join(app.getPath("temp"), "trilium-transcription.html");+ fs.writeFileSync(pagePath, CAPTURE_PAGE);++ const window = new BrowserWindow({+ show: false,+ webPreferences: {+ session: captureSession,+ nodeIntegration: true,+ contextIsolation: false,+ sandbox: false,+ autoplayPolicy: "no-user-gesture-required",+ // Without hardware acceleration, a hidden window renders no frames, so the+ // self-capture in CAPTURE_PAGE times out waiting for its video source.+ offscreen: true+ }+ });+ window.webContents.on("console-message", ({ message }) =>+ getLog().info(`Transcription (capture): ${message}`));+ await window.loadFile(pagePath);+ return window;+}++const CAPTURE_PAGE = `<!DOCTYPE html>+<script>+const { ipcRenderer } = require("electron");+const context = new AudioContext({ sampleRate: ${SAMPLE_RATE} });++function pipe(source, media) {+ const processor = context.createScriptProcessor(4096, 1, 1);+ processor.onaudioprocess = (e) =>+ ipcRenderer.send("${SAMPLES_CHANNEL}", source, e.inputBuffer.getChannelData(0).slice());+ context.createMediaStreamSource(media).connect(processor);+ processor.connect(context.destination);+}++function describe(tracks) {+ return tracks.map((track) => track.label).join(", ");+}++async function captureMicrophone() {+ const media = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1 } });+ pipe("microphone", media);+ return describe(media.getAudioTracks());+}++async function captureSystemAudio() {+ const media = await navigator.mediaDevices.getDisplayMedia({+ video: true,+ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: false }+ }).catch((e) => {+ throw new Error(e.name + ": " + e.message);+ });+ for (const track of media.getVideoTracks()) {+ track.stop();+ }+ const audioTracks = media.getAudioTracks();+ if (!audioTracks.length) {+ throw new Error("the screen capture has no audio track");+ }+ for (const track of audioTracks) {+ console.log("System track muted=" + track.muted + " settings="+ + JSON.stringify(track.getSettings()));+ }+ pipe("system", new MediaStream(audioTracks));+ return describe(audioTracks);+}+</script>`;diff --git a/apps/desktop/src/services/transcription/engine.ts b/apps/desktop/src/services/transcription/engine.tsnew file mode 100644index 0000000000..fa56ba15c7--- /dev/null+++ b/apps/desktop/src/services/transcription/engine.ts@@ -0,0 +1,120 @@+import dataDirs from "@triliumnext/server/src/services/data_dir.js";+import fs from "fs";+import path from "path";+import type { Vad } from "sherpa-onnx-node";++/** Every source and engine works on mono 16 kHz samples. */+export const SAMPLE_RATE = 16000;++/** Turns one utterance into text. */+export interface SpeechRecognizer {+ transcribe(samples: Float32Array): Promise<string>;+}++/** A stretch of speech found in a source, `start` counted in samples from the source's start. */+export interface SpeechSegment {+ start: number;+ samples: Float32Array;+}++/** Cuts one source's audio into utterances at its pauses. Each source needs its own. */+export interface SpeechSegmenter {+ /** Takes the next samples and returns the utterances they complete. */+ accept(samples: Float32Array): SpeechSegment[];+ /** Ends the source and returns the utterance still in progress, if any. */+ flush(): SpeechSegment[];+}++export interface SpeechEngine {+ recognizer: SpeechRecognizer;+ createSegmenter(): SpeechSegmenter;+}++/** Where the models live: Parakeet TDT 0.6B v3 (int8) plus `silero_vad.onnx`. */+export const MODEL_DIR = path.join(dataDirs.TRILIUM_DATA_DIR, "transcription-model");++/** Silero VAD consumes 512-sample windows at 16 kHz. */+const VAD_WINDOW_SIZE = 512;++/**+ * Loads the local engine: Silero VAD for segmentation and Parakeet for recognition, both through+ * sherpa-onnx. Recognition runs on the libuv thread pool, so it never blocks the main process.+ */+export async function loadSherpaEngine(): Promise<SpeechEngine> {+ if (!fs.existsSync(MODEL_DIR)) {+ throw new ModelMissingError(MODEL_DIR);+ }++ const mod = await import("sherpa-onnx-node");+ const sherpa = mod.default ?? mod;+ const recognizer = await sherpa.OfflineRecognizer.createAsync({+ featConfig: { sampleRate: SAMPLE_RATE, 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",+ numThreads: 2,+ provider: "cpu"+ },+ decodingMethod: "greedy_search"+ });++ return {+ recognizer: {+ async transcribe(samples) {+ const stream = recognizer.createStream();+ stream.acceptWaveform({ samples, sampleRate: SAMPLE_RATE });+ return (await recognizer.decodeAsync(stream)).text.trim();+ }+ },+ createSegmenter: () => new VadSegmenter(new sherpa.Vad({+ sileroVad: {+ model: path.join(MODEL_DIR, "silero_vad.onnx"),+ threshold: 0.5,+ minSilenceDuration: 0.5,+ minSpeechDuration: 0.25,+ maxSpeechDuration: 20,+ windowSize: VAD_WINDOW_SIZE+ },+ sampleRate: SAMPLE_RATE,+ numThreads: 1,+ provider: "cpu"+ }, 60))+ };+}++export class ModelMissingError extends Error {+ constructor(readonly directory: string) {+ super(`No speech model in ${directory}`);+ }+}++class VadSegmenter implements SpeechSegmenter {+ constructor(private readonly vad: Vad) {}++ accept(samples: Float32Array) {+ for (let i = 0; i + VAD_WINDOW_SIZE <= samples.length; i += VAD_WINDOW_SIZE) {+ this.vad.acceptWaveform(samples.subarray(i, i + VAD_WINDOW_SIZE));+ }+ return this.drain();+ }++ flush() {+ this.vad.flush();+ return this.drain();+ }++ private drain() {+ const segments: SpeechSegment[] = [];+ while (!this.vad.isEmpty()) {+ // Electron's V8 memory cage rejects the external buffers sherpa-onnx uses by default.+ segments.push(this.vad.front(false));+ this.vad.pop();+ }+ return segments;+ }+}diff --git a/apps/desktop/src/services/transcription/index.spec.ts b/apps/desktop/src/services/transcription/index.spec.tsnew file mode 100644index 0000000000..08e46b8a9c--- /dev/null+++ b/apps/desktop/src/services/transcription/index.spec.ts@@ -0,0 +1,114 @@+import type { TranscriptionState } from "@triliumnext/commons";+import { beforeEach, describe, expect, it, vi } from "vitest";++const h = vi.hoisted(() => ({+ handlers: new Map<string, (...args: unknown[]) => unknown>(),+ broadcast: [] as TranscriptionState[],+ notes: new Set<string>([ "meeting" ]),+ loadEngine: vi.fn(),+ sessionStart: vi.fn(),+ sessionStop: vi.fn()+}));++vi.mock("electron", () => ({+ ipcMain: {+ handle: (channel: string, handler: (...args: unknown[]) => unknown) =>+ h.handlers.set(channel, handler)+ },+ BrowserWindow: {+ getAllWindows: () => [ 1, 2 ].map(() => ({+ webContents: {+ send: (channel: string, state: TranscriptionState) => {+ if (channel === "transcription-state") {+ h.broadcast.push(state);+ }+ }+ }+ }))+ }+}));+vi.mock("@triliumnext/core", () => ({+ becca: { getNote: (noteId: string) => h.notes.has(noteId) ? { noteId } : null },+ getLog: () => ({ info: vi.fn(), error: vi.fn() })+}));+vi.mock("i18next", () => ({+ t: (key: string, options?: object) => options ? `${key} ${JSON.stringify(options)}` : key+}));+vi.mock("@triliumnext/server/src/services/data_dir.js", () => ({+ default: { TRILIUM_DATA_DIR: "/data" }+}));+vi.mock("./capture", () => ({ ElectronAudioCapture: class {} }));+vi.mock("./engine", async (importOriginal) => ({+ ...(await importOriginal<typeof import("./engine")>()),+ loadSherpaEngine: h.loadEngine+}));+vi.mock("./session", () => ({+ LogSink: class {},+ RecordingSession: class {+ start = h.sessionStart;+ stop = h.sessionStop;+ }+}));++const { ModelMissingError } = await import("./engine");++async function loadService() {+ vi.resetModules();+ const service = await import("./index");+ service.setupTranscriptionHandlers();+ return (channel: string, ...args: unknown[]) => h.handlers.get(channel)?.({}, ...args);+}++beforeEach(() => {+ vi.clearAllMocks();+ h.handlers.clear();+ h.broadcast.length = 0;+ h.loadEngine.mockResolvedValue({});+ h.sessionStart.mockResolvedValue([ "microphone", "system" ]);+});++describe("transcription IPC", () => {+ it("records one meeting at a time and tells every window about each step", async () => {+ const invoke = await loadService();++ expect(await invoke("transcription-start", "meeting")).toBe("");+ expect(await invoke("transcription-start", "meeting"))+ .toBe("transcription.already-recording");+ expect(await invoke("transcription-get-state"))+ .toEqual({ status: "recording", noteId: "meeting" });++ await invoke("transcription-stop");+ expect(h.sessionStop).toHaveBeenCalledOnce();+ expect(h.broadcast.map((state) => state.status)).toEqual([+ "starting", "starting", "recording", "recording",+ "stopping", "stopping", "idle", "idle"+ ]);+ expect(await invoke("transcription-get-state")).toEqual({ status: "idle", noteId: null });+ });++ it("refuses a note that does not exist, without changing state", async () => {+ const invoke = await loadService();++ expect(await invoke("transcription-start", "deleted")).toBe("transcription.note-not-found");+ expect(await invoke("transcription-start", { noteId: "meeting" }))+ .toBe("transcription.note-not-found");+ expect(h.loadEngine).not.toHaveBeenCalled();+ expect(h.broadcast).toEqual([]);+ });++ it("explains why it could not start and returns to idle", async () => {+ const invoke = await loadService();++ h.loadEngine.mockRejectedValueOnce(new ModelMissingError("/data/transcription-model"));+ expect(await invoke("transcription-start", "meeting"))+ .toBe(`transcription.model-missing {"directory":"/data/transcription-model"}`);++ h.sessionStart.mockRejectedValueOnce(new Error("No audio source could be captured."));+ expect(await invoke("transcription-start", "meeting"))+ .toBe(`transcription.start-failed {"message":"No audio source could be captured."}`);++ expect(await invoke("transcription-get-state")).toEqual({ status: "idle", noteId: null });+ await invoke("transcription-stop");+ expect(h.sessionStop).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/services/transcription/index.ts b/apps/desktop/src/services/transcription/index.tsnew file mode 100644index 0000000000..f2fa140b6c--- /dev/null+++ b/apps/desktop/src/services/transcription/index.ts@@ -0,0 +1,83 @@+import type { TranscriptionState } from "@triliumnext/commons";+import { becca, getLog } from "@triliumnext/core";+import { BrowserWindow, ipcMain } from "electron";+import { t } from "i18next";++import { ElectronAudioCapture } from "./capture";+import { loadSherpaEngine, ModelMissingError } from "./engine";+import { LogSink, RecordingSession, type TranscriptSink } from "./session";++let state: TranscriptionState = { status: "idle", noteId: null };+let activeSession: RecordingSession | null = null;++export function setupTranscriptionHandlers() {+ ipcMain.handle("transcription-start", (_event, noteId: unknown) => startRecording(noteId));+ ipcMain.handle("transcription-stop", () => stopRecording());+ ipcMain.handle("transcription-get-state", () => getState());+}++/**+ * Starts recording for the meeting note `noteId`.+ *+ * @returns An empty string once recording runs, or the reason it cannot start.+ */+export async function startRecording(noteId: unknown): Promise<string> {+ if (state.status !== "idle") {+ return t("transcription.already-recording");+ }+ if (typeof noteId !== "string" || !becca.getNote(noteId)) {+ return t("transcription.note-not-found");+ }++ setState({ status: "starting", noteId });+ try {+ const session = new RecordingSession({+ capture: new ElectronAudioCapture(),+ engine: await loadSherpaEngine(),+ sinks: createSinks(noteId)+ });+ const sources = await session.start();+ activeSession = session;+ getLog().info(`Transcription: recording ${sources.join(" and ")} for note ${noteId}.`);+ setState({ status: "recording", noteId });+ return "";+ } catch (e) {+ setState({ status: "idle", noteId: null });+ if (e instanceof ModelMissingError) {+ return t("transcription.model-missing", { directory: e.directory });+ }+ getLog().error(`Transcription did not start: ${(e as Error)?.stack ?? e}`);+ return t("transcription.start-failed", { message: (e as Error)?.message ?? String(e) });+ }+}++export async function stopRecording() {+ const session = activeSession;+ if (state.status !== "recording" || !session) {+ return;+ }++ setState({ status: "stopping", noteId: state.noteId });+ activeSession = null;+ try {+ await session.stop();+ } finally {+ setState({ status: "idle", noteId: null });+ }+}++export function getState() {+ return state;+}++/** Where the utterances of a recording for `noteId` go. */+function createSinks(noteId: string): TranscriptSink[] {+ return [ new LogSink(noteId) ];+}++function setState(newState: TranscriptionState) {+ state = newState;+ for (const window of BrowserWindow.getAllWindows()) {+ window.webContents.send("transcription-state", state);+ }+}diff --git a/apps/desktop/src/services/transcription/session.spec.ts b/apps/desktop/src/services/transcription/session.spec.tsnew file mode 100644index 0000000000..c851e61ae9--- /dev/null+++ b/apps/desktop/src/services/transcription/session.spec.ts@@ -0,0 +1,126 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { AudioSource, SamplesListener } from "./capture";+import type { SpeechSegment } from "./engine";+import { RecordingSession, type TranscriptSink, type Utterance } from "./session";++const log = vi.hoisted(() => ({ info: vi.fn(), error: vi.fn() }));+vi.mock("@triliumnext/core", () => ({ getLog: () => log }));+vi.mock("@triliumnext/server/src/services/data_dir.js", () => ({+ default: { TRILIUM_DATA_DIR: "/data" }+}));++/**+ * A chunk the fake segmenter reads as a finished utterance: `id` becomes the transcribed text+ * (`0` transcribes to nothing), `start` the segment's start in samples. One second long.+ */+function utteranceChunk(id: number, start: number) {+ const samples = new Float32Array(16000);+ samples[0] = id;+ samples[1] = start;+ return samples;+}++function createHarness(extraSinks: TranscriptSink[] = []) {+ let clock = 1000;+ let onSamples: SamplesListener = () => {};+ const capture = {+ start: vi.fn(async (listener: SamplesListener) => {+ onSamples = listener;+ return [ "microphone", "system" ] as AudioSource[];+ }),+ stop: vi.fn()+ };+ const flushed: SpeechSegment[][] = [];+ const engine = {+ recognizer: {+ transcribe: vi.fn(async (samples: Float32Array) =>+ samples[0] ? `utterance ${samples[0]}` : "")+ },+ createSegmenter: vi.fn(() => {+ const pending = flushed.shift() ?? [];+ return {+ accept: (samples: Float32Array) => [ { start: samples[1], samples } ],+ flush: () => pending+ };+ })+ };+ const written: Utterance[] = [];+ const sink = {+ write: vi.fn((utterance: Utterance) => {+ written.push(utterance);+ }),+ close: vi.fn()+ };+ const sinks = [ ...extraSinks, sink ];+ const session = new RecordingSession({ capture, engine, sinks, now: () => clock });++ return {+ session, capture, engine, sink, written, flushed,+ /** Delivers `samples` from `source` when the clock reads `at`. */+ deliver(source: AudioSource, samples: Float32Array, at: number) {+ clock = at;+ onSamples(source, samples);+ }+ };+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe("RecordingSession", () => {+ it("labels each source's utterances with their offset from the recording start", async () => {+ const { session, engine, deliver, written } = createHarness();+ await session.start();++ // The microphone's first one-second chunk arrives 2 s in, so it began 1 s in.+ deliver("microphone", utteranceChunk(1, 8000), 3000);+ deliver("system", utteranceChunk(2, 0), 5000);+ deliver("microphone", utteranceChunk(0, 32000), 6000);+ await session.stop();++ expect(engine.createSegmenter).toHaveBeenCalledTimes(2);+ expect(written).toEqual([+ { source: "microphone", offsetMs: 1500, text: "utterance 1" },+ { source: "system", offsetMs: 3000, text: "utterance 2" }+ ]);+ });++ it("transcribes what the segmenters still hold before it closes the sinks", async () => {+ const failingSink: TranscriptSink = {+ write: () => {+ throw new Error("disk full");+ },+ close: () => {+ throw new Error("disk full");+ }+ };+ const { session, capture, deliver, sink, flushed } = createHarness([ failingSink ]);+ flushed.push([ { start: 16000, samples: utteranceChunk(3, 0) } ]);+ await session.start();++ deliver("microphone", utteranceChunk(0, 0), 2000);+ await session.stop();++ expect(capture.stop).toHaveBeenCalledOnce();+ expect(sink.write).toHaveBeenCalledExactlyOnceWith({+ source: "microphone", offsetMs: 1000, text: "utterance 3"+ });+ expect(sink.close).toHaveBeenCalledOnce();+ expect(sink.write.mock.invocationCallOrder[0])+ .toBeLessThan(sink.close.mock.invocationCallOrder[0]);+ expect(log.error).toHaveBeenCalledTimes(2);+ });++ it("logs a failing source instead of throwing into the IPC listener", async () => {+ const { session, engine, deliver } = createHarness();+ engine.createSegmenter.mockImplementationOnce(() => {+ throw new Error("VAD model missing");+ });+ await session.start();++ expect(() => deliver("system", utteranceChunk(1, 0), 2000)).not.toThrow();+ expect(log.error).toHaveBeenCalledWith("Transcription: system failed: VAD model missing");+ });+});diff --git a/apps/desktop/src/services/transcription/session.ts b/apps/desktop/src/services/transcription/session.tsnew file mode 100644index 0000000000..972fc98fd2--- /dev/null+++ b/apps/desktop/src/services/transcription/session.ts@@ -0,0 +1,166 @@+import { getLog } from "@triliumnext/core";++import type { AudioCapture, AudioSource } from "./capture";+import { SAMPLE_RATE, type SpeechEngine, type SpeechSegment, type SpeechSegmenter } from "./engine";++/** One transcribed stretch of speech. */+export interface Utterance {+ source: AudioSource;+ /** Milliseconds from the start of the recording to the start of the utterance. */+ offsetMs: number;+ text: string;+}++/** Receives the utterances of a recording in the order they were spoken per source. */+export interface TranscriptSink {+ write(utterance: Utterance): void | Promise<void>;+ /** Called once after the last utterance. */+ close?(): void | Promise<void>;+}++export interface RecordingSessionOptions {+ capture: AudioCapture;+ engine: SpeechEngine;+ sinks: TranscriptSink[];+ now?: () => number;+}++/**+ * One recording: runs each source of `capture` through its own segmenter, so a pause on one source+ * never cuts an utterance on the other, transcribes the utterances one at a time and hands each+ * to every sink.+ */+export class RecordingSession {+ private readonly pipelines = new Map<AudioSource, SourcePipeline>();+ private queue = Promise.resolve();+ private startedAt = 0;++ constructor(private readonly options: RecordingSessionOptions) {}++ async start() {+ this.startedAt = this.now();+ return await this.options.capture.start((source, samples) => {+ // An exception thrown from an `ipcMain` listener takes down the main process.+ try {+ this.pipelineFor(source, samples).accept(samples);+ } catch (e) {+ getLog().error(`Transcription: ${source} failed: ${(e as Error)?.message ?? e}`);+ }+ });+ }++ /** Stops capturing, then waits until the speech already captured has reached every sink. */+ async stop() {+ this.options.capture.stop();+ for (const pipeline of this.pipelines.values()) {+ pipeline.flush();+ }+ await this.queue;++ for (const sink of this.options.sinks) {+ try {+ await sink.close?.();+ } catch (e) {+ getLog().error(`Transcription: closing a sink failed: ${e}`);+ }+ }+ }++ /** Creates a source's pipeline on its first chunk, which was captured before it arrived. */+ private pipelineFor(source: AudioSource, firstChunk: Float32Array) {+ let pipeline = this.pipelines.get(source);+ if (!pipeline) {+ const chunkMs = firstChunk.length / SAMPLE_RATE * 1000;+ pipeline = new SourcePipeline(+ source,+ this.options.engine.createSegmenter(),+ Math.max(0, this.now() - this.startedAt - chunkMs),+ (offsetMs, samples) => this.enqueue(source, offsetMs, samples)+ );+ this.pipelines.set(source, pipeline);+ }+ return pipeline;+ }++ private enqueue(source: AudioSource, offsetMs: number, samples: Float32Array) {+ this.queue = this.queue.then(async () => {+ const text = await this.options.engine.recognizer.transcribe(samples);+ if (!text) {+ return;+ }++ for (const sink of this.options.sinks) {+ try {+ await sink.write({ source, offsetMs, text });+ } catch (e) {+ getLog().error(`Transcription: a sink failed: ${e}`);+ }+ }+ }).catch((e) => getLog().error(`Transcription failed: ${e}`));+ }++ private now() {+ return (this.options.now ?? Date.now)();+ }+}++/** Logs every utterance, labeled "Me" for the microphone and "Others" for the system audio. */+export class LogSink implements TranscriptSink {+ constructor(private readonly noteId: string) {}++ write({ source, offsetMs, text }: Utterance) {+ const speaker = source === "microphone" ? "Me" : "Others";+ getLog().info(`Transcription [${formatOffset(offsetMs)}] ${speaker}: ${text}`);+ }++ close() {+ getLog().info(`Transcription: recording for note ${this.noteId} stopped.`);+ }+}++export function formatOffset(milliseconds: number) {+ const seconds = Math.max(0, Math.floor(milliseconds / 1000));+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;+}++/** Segments one source and logs its peak level every 5 s, to spot a silent source. */+class SourcePipeline {+ private peak = 0;+ private peakSampleCount = 0;++ constructor(+ private readonly source: AudioSource,+ private readonly segmenter: SpeechSegmenter,+ /** Milliseconds from the start of the recording to the source's first sample. */+ private readonly firstSampleOffsetMs: number,+ private readonly onSegment: (offsetMs: number, samples: Float32Array) => void+ ) {}++ accept(samples: Float32Array) {+ this.trackPeak(samples);+ this.emit(this.segmenter.accept(samples));+ }++ flush() {+ this.emit(this.segmenter.flush());+ }++ private emit(segments: SpeechSegment[]) {+ for (const segment of segments) {+ const offsetMs = this.firstSampleOffsetMs + segment.start / SAMPLE_RATE * 1000;+ this.onSegment(offsetMs, segment.samples);+ }+ }++ private trackPeak(samples: Float32Array) {+ for (const sample of samples) {+ this.peak = Math.max(this.peak, Math.abs(sample));+ }+ this.peakSampleCount += samples.length;+ if (this.peakSampleCount >= 5 * SAMPLE_RATE) {+ getLog().info(`Transcription: ${this.source} peak ${this.peak.toFixed(4)} over 5 s`);+ this.peak = 0;+ this.peakSampleCount = 0;+ }+ }+}diff --git a/apps/desktop/src/sherpa-onnx-node.d.ts b/apps/desktop/src/sherpa-onnx-node.d.tsindex 4811be0795..5f3ad0d8da 100644--- a/apps/desktop/src/sherpa-onnx-node.d.ts+++ b/apps/desktop/src/sherpa-onnx-node.d.ts@@ -15,5 +15,6 @@ declare module "sherpa-onnx-node" {isEmpty(): boolean;front(enableExternalBuffer: boolean): { start: number; samples: Float32Array };pop(): void;+ flush(): void;}}diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex bbb9da28c5..250e4a125c 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -561,5 +561,11 @@"detail": "You will be offered a backup of your current knowledge base first. Nothing is deleted until you choose to create a new knowledge base, restore a backup or sync from another device.\n\nDo not continue if a script or an unfamiliar note prompted you to.","cancel": "Cancel","confirm": "Restart and start over"+ },+ "transcription": {+ "already-recording": "A meeting is already being recorded.",+ "note-not-found": "The meeting note no longer exists.",+ "model-missing": "No speech recognition model was found in {{- directory}}.",+ "start-failed": "The recording could not start: {{- message}}"}}diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.tsindex 9b90d6f744..5e44dce8e1 100644--- a/packages/commons/src/lib/electron_api_interface.ts+++ b/packages/commons/src/lib/electron_api_interface.ts@@ -713,6 +713,41 @@ export interface ElectronDialogApi {confirmStartOver(): Promise<boolean>;}+/** Phase of the meeting transcription; at most one recording runs at a time. */+export type TranscriptionStatus = "idle" | "starting" | "recording" | "stopping";++/** What {@link ElectronTranscriptionApi} reports to every window. */+export interface TranscriptionState {+ status: TranscriptionStatus;+ /** The meeting note the recording belongs to, or `null` when idle. */+ noteId: string | null;+}++/**+ * Meeting transcription, recorded and transcribed on this computer by the main process. The+ * renderer only starts and stops it; the audio never passes through the renderer.+ */+export interface ElectronTranscriptionApi {+ /**+ * Starts recording the microphone and the system audio for the meeting note `noteId`.+ *+ * @returns An empty string once recording runs, or an error message when it cannot start.+ */+ start(noteId: string): Promise<string>;++ /** Stops the recording, once the speech already captured has been transcribed. */+ stop(): Promise<void>;++ getState(): Promise<TranscriptionState>;++ /**+ * Calls `callback` every time the state changes, in any window.+ *+ * @returns A function that removes the listener.+ */+ onStateChanged(callback: (state: TranscriptionState) => void): () => void;+}+/*** The complete surface exposed to the renderer as `window.electronApi` via* `contextBridge`. The renderer must access Electron-only functionality through@@ -757,4 +792,6 @@ export interface ElectronApi {dialog: ElectronDialogApi;/** Choosing a backup to restore during setup, read where it lies rather than uploaded. */restore: ElectronRestoreApi;+ /** Meeting transcription: starting and stopping a recording, and following its state. */+ transcription: ElectronTranscriptionApi;}