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): keep a transcription's audio in development builds
Elian Doranab35a07eab84
diff --git a/apps/desktop/src/services/transcription/audio_recorder.spec.ts b/apps/desktop/src/services/transcription/audio_recorder.spec.tsnew file mode 100644index 0000000000..fc978304e0--- /dev/null+++ b/apps/desktop/src/services/transcription/audio_recorder.spec.ts@@ -0,0 +1,98 @@+import fs from "fs";+import os from "os";+import path from "path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { encodeWavHeader, type RecordingManifest, toPcm16, WavRecorder } from "./audio_recorder";++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" }+}));++const STARTED_AT = Date.parse("2026-10-14T09:30:00.000Z");++let parentDirectory = "";++beforeEach(() => {+ vi.clearAllMocks();+ parentDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "trilium-recordings-"));+});++afterEach(() => {+ fs.rmSync(parentDirectory, { recursive: true, force: true });+});++function readRecording() {+ const [ name ] = fs.readdirSync(parentDirectory);+ const directory = path.join(parentDirectory, name);+ const manifest = JSON.parse(+ fs.readFileSync(path.join(directory, "recording.json"), "utf8")+ ) as RecordingManifest;+ return { name, directory, manifest };+}++describe("WavRecorder", () => {+ it("keeps each source in a WAV file, lined up by the manifest", () => {+ const recorder = new WavRecorder(parentDirectory, "meeting");+ recorder.open(STARTED_AT);+ recorder.write("microphone", new Float32Array([ 0.5, -0.5 ]), 1500);+ recorder.write("system", new Float32Array([ 1 ]), 3000);+ recorder.write("microphone", new Float32Array([ 2, -2 ]), 1500);++ // The header already counts every sample before the recording closes.+ const { name, directory, manifest } = readRecording();+ const microphone = fs.readFileSync(path.join(directory, "microphone.wav"));+ expect(microphone.subarray(0, 44)).toEqual(encodeWavHeader(8));+ expect(microphone.subarray(44)).toEqual(toPcm16(new Float32Array([ 0.5, -0.5, 1, -1 ])));+ recorder.close();++ expect(name).toBe("2026-10-14T09-30-00-000Z_meeting");+ expect(fs.readFileSync(path.join(directory, "system.wav")).length).toBe(46);+ expect(manifest).toEqual({+ noteId: "meeting",+ startedAt: "2026-10-14T09:30:00.000Z",+ sampleRate: 16000,+ sources: {+ microphone: { file: "microphone.wav", firstSampleOffsetMs: 1500 },+ system: { file: "system.wav", firstSampleOffsetMs: 3000 }+ }+ });+ });++ it("stops keeping the audio after a failed write, logging it once", () => {+ const recorder = new WavRecorder(parentDirectory, "meeting");+ recorder.open(STARTED_AT);+ const { directory } = readRecording();+ fs.rmSync(directory, { recursive: true });++ recorder.write("microphone", new Float32Array([ 0.5 ]), 0);+ recorder.write("microphone", new Float32Array([ 0.5 ]), 0);+ recorder.close();++ expect(log.error).toHaveBeenCalledOnce();+ expect(fs.existsSync(directory)).toBe(false);+ });+});++describe("WAV encoding", () => {+ it("describes mono 16-bit PCM at 16 kHz", () => {+ const header = encodeWavHeader(32000);+ expect(header.toString("ascii", 0, 4)).toBe("RIFF");+ expect(header.readUInt32LE(4)).toBe(32036);+ expect(header.toString("ascii", 8, 16)).toBe("WAVEfmt ");+ expect([ header.readUInt16LE(20), header.readUInt16LE(22) ]).toEqual([ 1, 1 ]);+ expect(header.readUInt32LE(24)).toBe(16000);+ expect(header.readUInt32LE(28)).toBe(32000);+ expect([ header.readUInt16LE(32), header.readUInt16LE(34) ]).toEqual([ 2, 16 ]);+ expect(header.toString("ascii", 36, 40)).toBe("data");+ expect(header.readUInt32LE(40)).toBe(32000);+ });++ it("scales samples to the full 16-bit range and clips beyond it", () => {+ const pcm = toPcm16(new Float32Array([ 0, 1, -1, 0.5, 3, -3 ]));+ const values = [ 0, 1, 2, 3, 4, 5 ].map((index) => pcm.readInt16LE(index * 2));+ expect(values).toEqual([ 0, 32767, -32768, 16384, 32767, -32768 ]);+ });+});diff --git a/apps/desktop/src/services/transcription/audio_recorder.ts b/apps/desktop/src/services/transcription/audio_recorder.tsnew file mode 100644index 0000000000..f7b4513eba--- /dev/null+++ b/apps/desktop/src/services/transcription/audio_recorder.ts@@ -0,0 +1,148 @@+import type { TranscriptSource } from "@triliumnext/commons";+import { getLog } from "@triliumnext/core";+import dataDirs from "@triliumnext/server/src/services/data_dir.js";+import fs from "fs";+import path from "path";++import { SAMPLE_RATE } from "./engine";+import type { AudioTap } from "./session";++/** Where development builds keep the audio of each recording, one directory per recording. */+export const RECORDINGS_DIR = path.join(dataDirs.TRILIUM_DATA_DIR, "transcription-recordings");++/** The `recording.json` next to the audio files, which lines the sources up with the transcript. */+export interface RecordingManifest {+ noteId: string;+ /** When the recording started, as an ISO 8601 timestamp, like the transcript's `startedAt`. */+ startedAt: string;+ sampleRate: number;+ sources: Partial<Record<TranscriptSource, {+ file: string;+ /** Milliseconds from `startedAt` to the file's first sample. */+ firstSampleOffsetMs: number;+ }>>;+}++/**+ * Keeps a recording's audio as one mono 16-bit WAV file per source, plus a `recording.json`+ * manifest, in a directory of its own under `parentDirectory`. Each write also updates the WAV+ * header, so the files stay playable if the application quits mid-recording.+ */+export class WavRecorder implements AudioTap {+ private directory: string | null = null;+ private manifest: RecordingManifest | null = null;+ private readonly files = new Map<TranscriptSource, WavFile>();+ private failed = false;++ constructor(private readonly parentDirectory: string, private readonly noteId: string) {}++ open(startedAt: number) {+ const startedAtIso = new Date(startedAt).toISOString();+ const directory = path.join(+ this.parentDirectory,+ `${startedAtIso.replace(/[:.]/g, "-")}_${this.noteId}`+ );+ fs.mkdirSync(directory, { recursive: true });+ this.directory = directory;+ this.manifest = {+ noteId: this.noteId,+ startedAt: startedAtIso,+ sampleRate: SAMPLE_RATE,+ sources: {}+ };+ this.writeManifest();+ getLog().info(`Transcription: keeping the audio in ${directory}`);+ }++ write(source: TranscriptSource, samples: Float32Array, firstSampleOffsetMs: number) {+ const { directory, manifest } = this;+ if (this.failed || !directory || !manifest) {+ return;+ }++ try {+ let file = this.files.get(source);+ if (!file) {+ const fileName = `${source}.wav`;+ file = new WavFile(path.join(directory, fileName));+ this.files.set(source, file);+ manifest.sources[source] = { file: fileName, firstSampleOffsetMs };+ this.writeManifest();+ }+ file.append(samples);+ } catch (e) {+ // Stops for good, so a full disk logs once rather than on every chunk.+ this.failed = true;+ getLog().error(`Transcription: stopped keeping the audio: ${e}`);+ }+ }++ close() {+ for (const file of this.files.values()) {+ file.close();+ }+ this.files.clear();+ }++ private writeManifest() {+ if (this.directory && this.manifest) {+ const manifestPath = path.join(this.directory, "recording.json");+ fs.writeFileSync(manifestPath, JSON.stringify(this.manifest, null, 2));+ }+ }+}++const WAV_HEADER_SIZE = 44;+const BYTES_PER_SAMPLE = 2;++/** A mono 16-bit PCM WAV file at {@link SAMPLE_RATE}, written as samples arrive. */+class WavFile {+ private readonly fd: number;+ private dataSize = 0;++ constructor(filePath: string) {+ this.fd = fs.openSync(filePath, "w");+ fs.writeSync(this.fd, encodeWavHeader(0));+ }++ append(samples: Float32Array) {+ const pcm = toPcm16(samples);+ fs.writeSync(this.fd, pcm, 0, pcm.length, WAV_HEADER_SIZE + this.dataSize);+ this.dataSize += pcm.length;+ fs.writeSync(this.fd, encodeWavHeader(this.dataSize), 0, WAV_HEADER_SIZE, 0);+ }++ close() {+ fs.closeSync(this.fd);+ }+}++/** The 44-byte header of a mono 16-bit PCM WAV file whose samples take `dataSize` bytes. */+export function encodeWavHeader(dataSize: number) {+ const header = Buffer.alloc(WAV_HEADER_SIZE);+ header.write("RIFF", 0, "ascii");+ header.writeUInt32LE(WAV_HEADER_SIZE - 8 + dataSize, 4);+ header.write("WAVE", 8, "ascii");+ header.write("fmt ", 12, "ascii");+ header.writeUInt32LE(16, 16);+ header.writeUInt16LE(1, 20);+ header.writeUInt16LE(1, 22);+ header.writeUInt32LE(SAMPLE_RATE, 24);+ header.writeUInt32LE(SAMPLE_RATE * BYTES_PER_SAMPLE, 28);+ header.writeUInt16LE(BYTES_PER_SAMPLE, 32);+ header.writeUInt16LE(BYTES_PER_SAMPLE * 8, 34);+ header.write("data", 36, "ascii");+ header.writeUInt32LE(dataSize, 40);+ return header;+}++/** Converts samples in [-1, 1] to little-endian 16-bit PCM, clipping any beyond that range. */+export function toPcm16(samples: Float32Array) {+ const pcm = Buffer.alloc(samples.length * BYTES_PER_SAMPLE);+ for (const [ index, sample ] of samples.entries()) {+ const clipped = Math.max(-1, Math.min(1, sample));+ pcm.writeInt16LE(Math.round(clipped < 0 ? clipped * 0x8000 : clipped * 0x7fff),+ index * BYTES_PER_SAMPLE);+ }+ return pcm;+}diff --git a/apps/desktop/src/services/transcription/index.spec.ts b/apps/desktop/src/services/transcription/index.spec.tsindex e46931544f..13048e7c7e 100644--- a/apps/desktop/src/services/transcription/index.spec.ts+++ b/apps/desktop/src/services/transcription/index.spec.ts@@ -32,7 +32,8 @@ vi.mock("electron", () => ({}));vi.mock("@triliumnext/core", () => ({becca: { getNote: (noteId: string) => h.notes.has(noteId) ? { noteId } : null },- getLog: () => ({ info: vi.fn(), error: vi.fn() })+ getLog: () => ({ info: vi.fn(), error: vi.fn() }),+ utils: { isDev: () => false }}));vi.mock("i18next", () => ({t: (key: string, options?: object) => options ? `${key} ${JSON.stringify(options)}` : keydiff --git a/apps/desktop/src/services/transcription/index.ts b/apps/desktop/src/services/transcription/index.tsindex a2432b54b0..ea053c256d 100644--- a/apps/desktop/src/services/transcription/index.ts+++ b/apps/desktop/src/services/transcription/index.ts@@ -1,12 +1,13 @@import type { TranscriptionState } from "@triliumnext/commons";-import { becca, getLog } from "@triliumnext/core";+import { becca, getLog, utils as coreUtils } from "@triliumnext/core";import { BrowserWindow, ipcMain } from "electron";import { t } from "i18next";import { AttachmentSink } from "./attachment_sink";+import { RECORDINGS_DIR, WavRecorder } from "./audio_recorder";import { ElectronAudioCapture } from "./capture";import { loadSherpaEngine, ModelMissingError } from "./engine";-import { RecordingSession, type TranscriptSink } from "./session";+import { type AudioTap, RecordingSession, type TranscriptSink } from "./session";const IDLE: TranscriptionState = { status: "idle", noteId: null, pendingSources: [] };@@ -38,6 +39,7 @@ export async function startRecording(noteId: unknown): Promise<string> {capture: new ElectronAudioCapture(),engine: await loadSherpaEngine(),sinks: createSinks(noteId),+ taps: createTaps(noteId),onPendingChanged: (pendingSources) => setState({ ...state, pendingSources })});const sources = await session.start();@@ -80,6 +82,14 @@ function createSinks(noteId: string): TranscriptSink[] {return [ new AttachmentSink(noteId) ];}+/**+ * What else receives the audio of a recording for `noteId`: development builds keep it, to+ * transcribe it again while the engine is tuned.+ */+function createTaps(noteId: string): AudioTap[] {+ return coreUtils.isDev() ? [ new WavRecorder(RECORDINGS_DIR, noteId) ] : [];+}+function setState(newState: TranscriptionState) {state = newState;for (const window of BrowserWindow.getAllWindows()) {diff --git a/apps/desktop/src/services/transcription/session.spec.ts b/apps/desktop/src/services/transcription/session.spec.tsindex 34666fa002..c8bfa91d00 100644--- a/apps/desktop/src/services/transcription/session.spec.ts+++ b/apps/desktop/src/services/transcription/session.spec.ts@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import type { SamplesListener } from "./capture";import type { SpeechSegment } from "./engine";-import { RecordingSession, type TranscriptSink } from "./session";+import { type AudioTap, RecordingSession, type TranscriptSink } from "./session";const log = vi.hoisted(() => ({ info: vi.fn(), error: vi.fn() }));vi.mock("@triliumnext/core", () => ({ getLog: () => log }));@@ -32,7 +32,7 @@ function speechChunk(speaking: boolean) {return samples;}-function createHarness(extraSinks: TranscriptSink[] = []) {+function createHarness(extraSinks: TranscriptSink[] = [], taps: AudioTap[] = []) {let clock = 1000;let onSamples: SamplesListener = () => {};const capture = {@@ -75,7 +75,7 @@ function createHarness(extraSinks: TranscriptSink[] = []) {const sinks = [ ...extraSinks, sink ];const onPendingChanged = vi.fn();const session = new RecordingSession({- capture, engine, sinks, onPendingChanged, now: () => clock+ capture, engine, sinks, taps, onPendingChanged, now: () => clock});return {@@ -113,6 +113,33 @@ describe("RecordingSession", () => {]);});+ it("hands every captured chunk to the taps, timed like the transcript", async () => {+ const failingTap: AudioTap = {+ write: () => {+ throw new Error("disk full");+ }+ };+ const tap = { open: vi.fn(), write: vi.fn(), close: vi.fn() };+ const { session, deliver, written } = createHarness([], [ failingTap, tap ]);+ await session.start();+ expect(tap.open).toHaveBeenCalledExactlyOnceWith(1000);++ const first = speechChunk(true);+ const second = utteranceChunk(1, 0);+ deliver("microphone", first, 3000);+ deliver("microphone", second, 4000);+ await session.stop();++ expect(tap.write.mock.calls).toEqual([+ [ "microphone", first, 1000 ],+ [ "microphone", second, 1000 ]+ ]);+ expect(tap.close).toHaveBeenCalledOnce();+ expect(written.map((utterance) => utterance.text)).toEqual([ "utterance 1" ]);+ expect(log.error).toHaveBeenCalledWith(+ "Transcription: an audio tap failed on microphone: Error: disk full");+ });+it("transcribes what the segmenters still hold before it closes the sinks", async () => {const failingSink: TranscriptSink = {write: () => {diff --git a/apps/desktop/src/services/transcription/session.ts b/apps/desktop/src/services/transcription/session.tsindex a6e7dacea6..9645f793f0 100644--- a/apps/desktop/src/services/transcription/session.ts+++ b/apps/desktop/src/services/transcription/session.ts@@ -16,10 +16,24 @@ export interface TranscriptSink {close?(): void | Promise<void>;}+/** Receives every source's samples as they are captured, before any segmentation. */+export interface AudioTap {+ /** Called once before capturing starts, as {@link TranscriptSink.open} is. */+ open?(startedAt: number): void | Promise<void>;+ /**+ * @param firstSampleOffsetMs Milliseconds from the start of the recording to the first sample+ * of `source`; the same for every call of one source.+ */+ write(source: TranscriptSource, samples: Float32Array, firstSampleOffsetMs: number): void;+ /** Called once after the last samples. */+ close?(): void | Promise<void>;+}+export interface RecordingSessionOptions {capture: AudioCapture;engine: SpeechEngine;sinks: TranscriptSink[];+ taps?: AudioTap[];/*** Called with the sources whose speech has not reached the sinks yet, either because it is* still being spoken or because it waits to be transcribed, every time that list changes.@@ -45,13 +59,15 @@ export class RecordingSession {async start() {this.startedAt = this.now();- for (const sink of this.options.sinks) {- await sink.open?.(this.startedAt);+ for (const receiver of [ ...this.options.sinks, ...this.options.taps ?? [] ]) {+ await receiver.open?.(this.startedAt);}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);+ const pipeline = this.pipelineFor(source, samples);+ this.tap(source, samples, pipeline.firstSampleOffsetMs);+ pipeline.accept(samples);this.updatePending();} catch (e) {getLog().error(`Transcription: ${source} failed: ${(e as Error)?.message ?? e}`);@@ -66,6 +82,13 @@ export class RecordingSession {pipeline.flush();}this.updatePending();+ for (const tap of this.options.taps ?? []) {+ try {+ await tap.close?.();+ } catch (e) {+ getLog().error(`Transcription: closing an audio tap failed: ${e}`);+ }+ }await this.queue;for (const sink of this.options.sinks) {@@ -77,6 +100,16 @@ export class RecordingSession {}}+ private tap(source: TranscriptSource, samples: Float32Array, firstSampleOffsetMs: number) {+ for (const tap of this.options.taps ?? []) {+ try {+ tap.write(source, samples, firstSampleOffsetMs);+ } catch (e) {+ getLog().error(`Transcription: an audio tap failed on ${source}: ${e}`);+ }+ }+ }+/** Creates a source's pipeline on its first chunk, which was captured before it arrived. */private pipelineFor(source: TranscriptSource, firstChunk: Float32Array) {let pipeline = this.pipelines.get(source);@@ -141,7 +174,7 @@ class SourcePipeline {private readonly source: TranscriptSource,private readonly segmenter: SpeechSegmenter,/** Milliseconds from the start of the recording to the source's first sample. */- private readonly firstSampleOffsetMs: number,+ readonly firstSampleOffsetMs: number,private readonly onSegment: (offsetMs: number, samples: Float32Array) => void) {}