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
fix(transcription): load the capture worklet in packaged builds
Elian Doran96441c11b9a3
diff --git a/.claude/skills/working-with-transcription/SKILL.md b/.claude/skills/working-with-transcription/SKILL.mdindex fb00c3cf7b..e9e1016dff 100644--- a/.claude/skills/working-with-transcription/SKILL.md+++ b/.claude/skills/working-with-transcription/SKILL.md@@ -192,6 +192,7 @@ node $S/capture-check.mjs latest # breaks at chunk boundaries, clippinode $S/capture-test.mjs # the capture worklet vs the old ScriptProcessor, page busynode $S/capture-test.mjs --capture worklet --load all --seconds 30node $S/capture-test.mjs --stereo # a left-only tone must arrive at amplitude 0.25+node $S/capture-test.mjs --fused # on a copy of Electron with the packaged builds' fuses````capture-check.mjs` compares the step between neighbouring samples at each 4096-sample chunk boundary with the steps around it: about 1.0–1.3 is a clean join, about 2 means the capture corrupts the start of chunks, heard as a crackle four times a second. It also counts **dips**, 10 ms windows that fall to near silence between loud stretches and fade back within 40–70 ms, per minute with the worst minute.@@ -211,7 +212,7 @@ node $S/worker-test.mjs latest --source microphone --seconds 60 --speed 8`worker-test.mjs` runs the real `TranscriptionWorker` in Electron: it starts the transcription process on the app's downloads in `apps/desktop/data/resources` (or the Parakeet of `--model`; `--out` writes the utterances), and a hidden page posts a recording's WAV through a `MessageChannelMain` port as the capture page does. It prints the engine's load time, the utterances (with speakers), how long `stop` took and whether the process exited, and the main process's event-loop lag throughout. On two minutes of a meeting's system track: ready after 1.3 s, lag p50 0.1 ms, p99 1.1 ms, max 25 ms. Before the split, speaker labelling alone held the main thread 15–100 ms per utterance. On Windows, Electron launched by it prints nothing and runs into the timeout (unresolved); there, `RecordingSession` and `loadSherpaEngine()` can be driven in plain Node with `node --import tsx` instead, feeding the WAV in 4096-sample chunks, which tests everything but the process boundary.-In development the process loads `transcription_worker.ts` through the `NODE_OPTIONS="--import tsx"` it inherits from `scripts/electron-start.mts`; built, `worker_client.ts` finds `transcription_worker.cjs` beside `main.mjs`. Packaged builds do not ship `sherpa-onnx-node` yet (it is external to every bundle, but not copied or unpacked from the asar).+In development the process loads `transcription_worker.ts` through the `NODE_OPTIONS="--import tsx"` it inherits from `scripts/electron-start.mts`; built, `worker_client.ts` finds `transcription_worker.cjs` beside `main.mjs`. `sherpa-onnx-node` is external to every bundle: `copySherpaOnnx()` in `apps/desktop/scripts/build.ts` copies it and the target's platform package (`sherpa-onnx-win-x64`, …) into `dist/node_modules`, and `forge.config.ts` unpacks the platform package from the asar, since the OS loads its shared libraries. `pnpm --filter @triliumnext/desktop electron-forge:test-packaged` checks a package from outside the repository, where nothing resolves from the workspace.## Findings so far@@ -265,6 +266,7 @@ The same 31-minute Romanian meeting (no reference, judged by reading): int8 is o- **A `MessagePortMain` receives a message whose buffer was transferred as `null`.** The capture page posts each chunk without a transfer list, so it is copied (16 KB).- **The transcription process must not throw from a port listener**: an uncaught exception ends it, and the recording with it. `RecordingSession` catches per chunk.- **`maxSpeechDuration` is not a hard cut**: past it, sherpa lowers the minimum silence to 0.1 s and raises the threshold to 0.9, so a segment ends at the next short gap, typically 1–2 s later.+- **Packaged builds run with different fuses than development.** `GrantFileProtocolExtraPrivileges` is off there, so the capture page, a `file://` page, has an opaque origin and a `blob:` worklet fails to load ("Not allowed to load local resource: blob:null/…"); the worklet loads from a `data:` URL. Check a change to the capture page with `capture-test.mjs --fused`, which flips `FUSES` from `flip-fuses.ts` on a copy of Electron; the plain run cannot show this class of failure.- **The capture window must be `offscreen`**: a hidden window renders no frames without it, and the self-capture that yields system audio times out. `getDisplayMedia()` needs a user gesture, which only `executeJavaScript(…, true)` gives a hidden window.- **Chromium's audio processing is applied during capture**, so the WAV already holds it and no replay can switch it off. The system track runs with echo cancellation, noise suppression and auto gain all off; the microphone keeps echo cancellation, so the meeting played through speakers is not transcribed twice, and its auto gain. Earlier recordings, including the one under "Findings so far", had noise suppression on both tracks and echo cancellation on the system track, so do not compare transcripts across that change.- **A silent system source** usually means the sink's monitor volume is near zero (seen at -66 dB); the per-source peak logged every 5 s shows it.diff --git a/.claude/skills/working-with-transcription/capture-test.mjs b/.claude/skills/working-with-transcription/capture-test.mjsindex 1a5856ed0f..a61d3788b6 100644--- a/.claude/skills/working-with-transcription/capture-test.mjs+++ b/.claude/skills/working-with-transcription/capture-test.mjs@@ -16,15 +16,18 @@// --seconds <n> capture length, default 20// --stereo play the tone on the left channel only// --keep <dir> also write each capture as <dir>/<capture>-<load>.wav+// --fused run a copy of Electron with the fuses of packaged builds+// (flip-fuses.ts), which the npm binary lacks//// Runs Electron the way scripts/electron-start.mts does (Nix-aware) and clears// ELECTRON_RUN_AS_NODE, which a VS Code terminal sets and which turns Electron into plain Node.import { execFileSync } from "node:child_process";import fs from "node:fs";+import { createRequire } from "node:module";import os from "node:os";import path from "node:path";-import { fileURLToPath } from "node:url";+import { fileURLToPath, pathToFileURL } from "node:url";import { parseArgs } from "./recordings.mjs";@@ -46,18 +49,24 @@ run.catch((e) => {});async function launch() {- const { options } = parseArgs(process.argv.slice(2), { flags: [ "stereo" ] });+ const { options } = parseArgs(process.argv.slice(2), { flags: [ "stereo", "fused" ] });const captures = (options.capture ?? "both") === "both" ? [ "worklet", "script" ] : [ options.capture ];const load = options.load ?? "jank";const seconds = Number(options.seconds ?? 20);- const { getElectronPath, getNixLdLibraryPath, isNixOS } = await import(path.join(REPO, "scripts/utils.mts"));+ const { getElectronPath, getNixLdLibraryPath, isNixOS } = await import(pathToFileURL(path.join(REPO, "scripts/utils.mts")).href);const env = { ...process.env, LD_LIBRARY_PATH: isNixOS() ? getNixLdLibraryPath() : process.env.LD_LIBRARY_PATH };delete env.ELECTRON_RUN_AS_NODE;+ // The npm package exports its binary's path; `getElectronPath()` names the command on PATH,+ // which only `pnpm run` provides.+ const electron = isNixOS()+ ? getElectronPath()+ : createRequire(path.join(REPO, "apps/desktop/package.json"))("electron");+ const binary = options.fused ? await getFusedElectron(electron) : electron;console.log(`${seconds} s of a ${TONE_HZ} Hz tone${options.stereo ? " (left channel only)" : ""}, load: ${load}\n`);for (const capture of captures) {const config = { capture, load, seconds, stereo: !!options.stereo, keep: options.keep ?? null };- const output = execFileSync(getElectronPath(), [ SELF, "--no-sandbox" ], {+ const output = execFileSync(binary, [ SELF, "--no-sandbox" ], {env: { ...env, CAPTURE_TEST_CONFIG: JSON.stringify(config) },encoding: "utf8",stdio: [ "ignore", "pipe", "pipe" ],@@ -69,6 +78,10 @@ async function launch() {process.exit(1);}const result = JSON.parse(line.slice("RESULT ".length));+ if (!result.chunks) {+ console.error(`${capture.padEnd(8)} captured nothing\n${output}`);+ process.exit(1);+ }const verdict = result.breaks === 0 ? "clean" : `${result.breaks} break(s)`;console.log(`${capture.padEnd(8)} ${verdict.padEnd(12)} ${result.breaksAtChunkStart} at a chunk start; `+ `captured ${result.capturedSeconds} s in ${result.chunks} chunks; amplitude ${result.amplitude}`@@ -76,6 +89,25 @@ async function launch() {}}+/**+ * Copies Electron's distribution to the temp directory and flips the fuses packaged builds carry+ * on the copy, the way the Flathub build does. Packaged builds differ from development in them:+ * `GrantFileProtocolExtraPrivileges` off, for one, changes what a `file://` page can load.+ */+async function getFusedElectron(electron) {+ const distDir = path.join(path.dirname(createRequire(import.meta.url).resolve("electron/package.json")), "dist");+ const copyDir = path.join(os.tmpdir(), "trilium-fused-electron");+ fs.rmSync(copyDir, { recursive: true, force: true });+ fs.cpSync(distDir, copyDir, { recursive: true, verbatimSymlinks: true });+ const binary = path.join(copyDir, path.relative(distDir, electron));++ const flipFusesScript = path.join(REPO, "apps/desktop/electron-forge/flip-fuses.ts");+ const { FUSES } = await import(pathToFileURL(flipFusesScript).href);+ const { flipFuses } = await import("@electron/fuses");+ await flipFuses(binary, { ...FUSES, resetAdHocDarwinSignature: process.platform === "darwin" });+ return binary;+}+async function runInElectron(config) {const { app, BrowserWindow, ipcMain } = await import("electron");const source = fs.readFileSync(CAPTURE_TS, "utf8");@@ -171,8 +203,8 @@ function buildPage(config, processor) {source.connect(node);node.connect(context.destination);} else {- await context.audioWorklet.addModule(URL.createObjectURL(- new Blob([ PROCESSOR ], { type: "text/javascript" })));+ await context.audioWorklet.addModule(+ "data:text/javascript;charset=utf-8," + encodeURIComponent(PROCESSOR));const node = new AudioWorkletNode(context, "chunk-collector", {numberOfInputs: 1,numberOfOutputs: 0,diff --git a/apps/desktop/src/services/transcription/capture.ts b/apps/desktop/src/services/transcription/capture.tsindex db4135f8e4..8e3f83998f 100644--- a/apps/desktop/src/services/transcription/capture.ts+++ b/apps/desktop/src/services/transcription/capture.ts@@ -227,8 +227,10 @@ const { ipcRenderer } = require("electron");const portReceived = new Promise((resolve) =>ipcRenderer.once("${PORT_CHANNEL}", (e) => resolve(e.ports[0])));const context = new AudioContext({ sampleRate: ${SAMPLE_RATE} });-const processorLoaded = context.audioWorklet.addModule(URL.createObjectURL(- new Blob([ ${JSON.stringify(CAPTURE_PROCESSOR)} ], { type: "text/javascript" })));+// A data: URL, since packaged builds turn off GrantFileProtocolExtraPrivileges, which leaves this+// file:// page an opaque origin that cannot load a blob: worklet.+const processorLoaded = context.audioWorklet.addModule(${JSON.stringify(+ `data:text/javascript;charset=utf-8,${encodeURIComponent(CAPTURE_PROCESSOR)}`)});const flushes = [];