Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(meetings): save a live meeting's transcript when the window reloads (#2315)
Joshua474c9bad0b69
diff --git a/src/components/AcceptInvitationModal.tsx b/src/components/AcceptInvitationModal.tsxindex ddf768677..556f8191f 100644--- a/src/components/AcceptInvitationModal.tsx+++ b/src/components/AcceptInvitationModal.tsx@@ -18,6 +18,7 @@ import {import { useAuth } from "../hooks/useAuth";import { signOut } from "../lib/auth";import { syncService } from "../services/SyncService.js";+import { stopRecording } from "../stores/meetingRecordingStore";import { afterWorkspaceJoined } from "../services/membershipActions";import { useToast } from "./ui/useToast";import SignInDialog from "./SignInDialog";@@ -119,6 +120,8 @@ export default function AcceptInvitationModal({ token, onClose, onAccepted }: Pr// new one (the purge never blocks the switch).async function handleSwitchAccount() {if (token) storePendingInvitationToken(token);+ // Signing out takes a live meeting's note out of scope; end it first.+ await stopRecording();await syncService.purgeTeamSpacesForSignOut();await signOut();}diff --git a/src/components/MeetingRecordingMount.tsx b/src/components/MeetingRecordingMount.tsxindex 2cf7cfa25..abc2e87b0 100644--- a/src/components/MeetingRecordingMount.tsx+++ b/src/components/MeetingRecordingMount.tsx@@ -4,12 +4,12 @@ import { useToast } from "./ui/useToast";import {getActiveRecordingSessionId,getMicAnalyser,+ persistLiveTranscript,primeMeetingWorklet,stopRecording,useMeetingRecordingStore,} from "../stores/meetingRecordingStore";import { requestMeetingRecordingAutoEnd } from "../helpers/meetingRecordingSession";-import { serializeTranscriptSegments } from "../utils/transcriptSpeakerState";import logger from "../utils/logger";const EMA_PREV = 0.5;@@ -66,13 +66,7 @@ export default function MeetingRecordingMount(): null {useEffect(() => {if (!isTranscribing) return;- const interval = setInterval(() => {- const { recordingNoteId, segments } = useMeetingRecordingStore.getState();- if (!recordingNoteId || segments.length === 0) return;- window.electronAPI.updateNote(recordingNoteId, {- transcript: serializeTranscriptSegments(segments),- });- }, 30_000);+ const interval = setInterval(() => void persistLiveTranscript(), 30_000);return () => clearInterval(interval);}, [isTranscribing]);diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 04070327f..434f7cb47 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -144,6 +144,7 @@ import {} from "../stores/policyRules";import { usePolicyModeOptions, usePolicySnapshot } from "../hooks/usePolicy";import { usePolicyStore } from "../stores/policyStore";+import { stopRecording } from "../stores/meetingRecordingStore";import { requestSignIn } from "../utils/requestSignIn";import { canManageSystemAudioInApp } from "../utils/systemAudioAccess";import WorkspaceSection from "./settings/WorkspaceSection";@@ -1957,6 +1958,9 @@ export default function SettingsPage({const handleSignOut = useCallback(async () => {setIsSigningOut(true);try {+ // End a live meeting while its note is still in scope: signing out clears+ // the account scope, and anything said after that could not be saved.+ await stopRecording();// Clear account-scoped renderer/session state before ending the session.// Workspace-owned rows remain cached behind their membership boundary.await syncService.purgeTeamSpacesForSignOut();diff --git a/src/stores/meetingRecordingStore.ts b/src/stores/meetingRecordingStore.tsindex a3663c05f..4bf7a83a2 100644--- a/src/stores/meetingRecordingStore.ts+++ b/src/stores/meetingRecordingStore.ts@@ -430,6 +430,9 @@ let recentSystemSpeaker: RecentSystemSpeaker | null = null;let speakerLocks: Map<string, string> = new Map();let pushConfigTimeout: ReturnType<typeof setTimeout> | null = null;let sessionSystemAudioActive = false;+// True while the recording's own note is deleted mid-recording, so a live save+// never writes the transcript back onto its tombstone.+let recordingNoteDeleted = false;export const useMeetingRecordingStore = create<MeetingRecordingState>()(() => ({isRecording: false,@@ -813,6 +816,7 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>speakerLocks = locks;systemPartialSpeakerIdValue = null;sessionSystemAudioActive = false;+ recordingNoteDeleted = false;useMeetingRecordingStore.setState({isRecording: true,@@ -1538,6 +1542,37 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>return true;}+// Writes the live segments to the recording's note, serialized exactly as the+// stop path writes them. Shared by the 30-second crash-safety save and the+// flush before an unload. A no-op once a stop has begun: that+// stop has already written the final transcript (or will write main's, for a+// recording with no segments), and a second write could overwrite it.+export async function persistLiveTranscript(): Promise<void> {+ const { recordingNoteId, segments } = useMeetingRecordingStore.getState();+ if (!isRecordingFlag || recordingNoteDeleted || recordingNoteId == null) return;+ if (segments.length === 0) return;+ try {+ // Posted before the first await: during beforeunload nothing after it is+ // guaranteed to run.+ const result = await window.electronAPI?.updateNote?.(recordingNoteId, {+ transcript: serializeTranscriptSegments(segments),+ });+ if (result && !result.success) {+ logger.error(+ "Failed to persist live meeting transcript",+ { error: result.error, noteId: recordingNoteId },+ "meeting"+ );+ }+ } catch (err) {+ logger.error(+ "Failed to persist live meeting transcript",+ { error: (err as Error).message, noteId: recordingNoteId },+ "meeting"+ );+ }+}+export interface StopRecordingResult {diarizationSessionId: string | null;// True only when this call ended a live recording — false for a no-op stop@@ -1789,6 +1824,36 @@ if (typeof window !== "undefined") {});}+// Registered once at module load, like the diarization listener above: the+// note can be deleted from the sidebar while the recording runs on. A team-note+// delete the server denies revives the same row, and the snapshot pull that+// follows re-syncs it live, so saves resume. A pull never clears deleted_at, so+// one racing a real delete re-syncs the tombstone and the guard holds.+if (typeof window !== "undefined") {+ window.electronAPI?.onNoteDeleted?.(({ id }) => {+ if (isRecordingFlag && id === useMeetingRecordingStore.getState().recordingNoteId) {+ recordingNoteDeleted = true;+ }+ });+ window.electronAPI?.onNoteSynced?.((note) => {+ if (!note.deleted_at && note.id === useMeetingRecordingStore.getState().recordingNoteId) {+ recordingNoteDeleted = false;+ }+ });+}++// A reload (Sign in, SSO completion, the crash screen's Reload) replaces this+// page mid-recording: main's owner-loss teardown ends the session, and this+// module's state goes with the page before stopRecording can save what was said+// since the last 30-second save. beforeunload runs first, for location.reload()+// and main's loadURL/loadFile alike. Never cancel it or return a value: Electron+// treats either as refusing the unload, and main's load then fails.+if (typeof window !== "undefined") {+ window.addEventListener("beforeunload", () => {+ void persistLiveTranscript();+ });+}+// Throttled resize listener — keeps layout reflows during drag from thrashing// React. Registered once at module load; the store outlives any view.if (typeof window !== "undefined") {diff --git a/src/types/electron.ts b/src/types/electron.tsindex 71a3036bc..9c74aef6a 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -1434,7 +1434,7 @@ declare global {updated_by_user_id?: string | null;left_team?: number;}- ) => Promise<{ success: boolean; note?: NoteItem }>;+ ) => Promise<{ success: boolean; note?: NoteItem; error?: string }>;deleteNote: (id: number) => Promise<{ success: boolean }>;exportNote: (noteId: number,diff --git a/test/components/meetingRecordingMountSaver.test.js b/test/components/meetingRecordingMountSaver.test.jsnew file mode 100644index 000000000..40986e22a--- /dev/null+++ b/test/components/meetingRecordingMountSaver.test.js@@ -0,0 +1,127 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const React = require("react");+const { createRoot } = require("react-dom/client");+const {+ createRendererServer,+ installBrowserGlobals,+ installHookDom,+ installMicCaptureGlobals,+} = require("../lib/rendererTestHarness");++// The 30-second crash-safety save lives in the always-mounted Mount, so it+// keeps running whichever view is open. It writes through the store's+// persistLiveTranscript: the same save the unload flush makes.++const NOTE_ID = 11;+const START_ARGS = {+ noteId: NOTE_ID,+ noteTitle: "Standup",+ folderId: null,+ autoEndEligible: true,+};+const TOAST_MOCK = `+ const toast = () => "1";+ const dismiss = () => {};+ export const useToast = () => ({ toast, dismiss });+`;++async function setup(t) {+ let root;+ let store;+ t.after(async () => {+ if (store) await React.act(async () => store.stopRecording());+ if (root) await React.act(async () => root.unmount());+ });+ const listeners = {};+ const capture = (name) => (callback) => {+ listeners[name] = callback;+ return () => {+ if (listeners[name] === callback) listeners[name] = null;+ };+ };+ const noop = () => () => {};+ const writes = [];+ const api = {+ checkSystemAudioAccess: async () => ({+ granted: true,+ status: "granted",+ mode: "native",+ strategy: "native",+ }),+ meetingTranscriptionStart: async () => ({+ success: true,+ systemAudioMode: "native",+ systemAudioStrategy: "native",+ }),+ meetingTranscriptionSetSystemAudioAvailable: async () => ({ success: true }),+ meetingTranscriptionStop: async () => ({ success: true }),+ meetingTranscriptionSend() {},+ updateNote: async (id, patch) => {+ writes.push([id, patch]);+ return { success: true };+ },+ onMeetingTranscriptionSegment: capture("segment"),+ onNoteDeleted: capture("noteDeleted"),+ onMeetingSpeakerIdentified: noop,+ onMeetingSpeakersMerged: noop,+ onMeetingSessionSpeakerConfigUpdated: noop,+ onMeetingTranscriptionError: noop,+ onMeetingTranscriptionFatalError: noop,+ onMeetingSystemAudioSilent: noop,+ onMeetingAutoEndRequested: noop,+ };+ installBrowserGlobals(t, {+ window: { electronAPI: api, setTimeout: (fn, ms) => setTimeout(fn, ms) },+ });+ installMicCaptureGlobals(t);+ const container = installHookDom(t);+ globalThis.document.visibilityState = "visible";+ globalThis.document.hasFocus = () => true;+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-meeting-mount-saver-test-",+ mockModules: { "/ui/useToast": TOAST_MOCK },+ });+ const { default: Mount } = await vite.ssrLoadModule("/components/MeetingRecordingMount.tsx");+ store = await vite.ssrLoadModule("/stores/meetingRecordingStore.ts");+ t.mock.timers.enable({ apis: ["setInterval"] });+ root = createRoot(container);+ await React.act(async () => root.render(React.createElement(Mount)));++ const start = () => React.act(async () => store.startRecording(START_ARGS));+ const say = (text) =>+ React.act(async () =>+ listeners.segment({ text, source: "mic", type: "final", timestamp: Date.now() })+ );+ const deleteNote = (id) => listeners.noteDeleted?.({ id });+ const tick = (ms) => React.act(async () => t.mock.timers.tick(ms));+ const savedTranscripts = () =>+ writes.filter(([, patch]) => typeof patch.transcript === "string");+ return { start, say, deleteNote, tick, writes, savedTranscripts };+}++test("the 30-second save writes the live transcript while a recording runs", async (t) => {+ const { start, say, tick, writes, savedTranscripts } = await setup(t);+ await start();+ await say("halfway through the meeting");+ writes.length = 0;++ await tick(30_000);++ const saved = savedTranscripts();+ assert.equal(saved.length, 1);+ assert.equal(saved[0][0], NOTE_ID);+ assert.match(saved[0][1].transcript, /halfway through the meeting/);+});++test("the 30-second save skips a note deleted mid-recording", async (t) => {+ const { start, say, deleteNote, tick, writes, savedTranscripts } = await setup(t);+ await start();+ await say("said before the delete");+ deleteNote(NOTE_ID);+ writes.length = 0;++ await tick(30_000);++ assert.deepEqual(savedTranscripts(), [], "a deleted note is not written back");+});diff --git a/test/components/meetingRecordingSurvivesViewSwitch.test.js b/test/components/meetingRecordingSurvivesViewSwitch.test.jsnew file mode 100644index 000000000..c92452fd6--- /dev/null+++ b/test/components/meetingRecordingSurvivesViewSwitch.test.js@@ -0,0 +1,295 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const React = require("react");+const { createRoot } = require("react-dom/client");+const {+ createRendererServer,+ installBrowserGlobals,+ installHostDom,+ installMicCaptureGlobals,+} = require("../lib/rendererTestHarness");++// #1685: switching notes or views mid-meeting must not stop the recording or+// lose its transcript. The pipeline lives in the store (#709) and the final+// save runs in the store's stop path (#1494), so whichever view is open when+// the pill's Stop is pressed, the note gets everything that was said.+//+// The shell below mirrors ControlPanel.tsx: MeetingRecordingMount is always+// mounted, and each view renders only while it is the active one. The store,+// Mount and PersonalNotesView are real; NoteEditor is a stub that records its+// mounts, because TipTap needs a real DOM.++const NOTES = {+ 11: {+ id: 11,+ title: "Standup",+ content: "",+ transcript: "",+ folder_id: null,+ space_id: 1,+ note_type: "meeting",+ },+ 12: {+ id: 12,+ title: "Other note",+ content: "",+ transcript: "",+ folder_id: null,+ space_id: 1,+ note_type: "personal",+ },+};++const MOCKS = {+ "/ui/useToast": `+ const toast = () => "1";+ export const useToast = () => ({ toast, dismiss() {} });+ `,+ "/icons": `export const Plus = () => null; export const Sparkles = () => null;`,+ "./NoteEditor": `+ import { useEffect } from "react";+ export default function NoteEditor(props) {+ globalThis.__editorProps = props;+ useEffect(() => {+ globalThis.__editorLog.push(["mount", props.note.id]);+ return () => globalThis.__editorLog.push(["unmount", props.note.id]);+ }, []);+ return null;+ }`,+ "./SpacesTree": `export default () => null;`,+ "/overview/ContainerOverview": `export const ContainerOverview = () => null;`,+ "./NotesStructureIntroDialog": `export default () => null;`,+ "./ActionPicker": `export default () => null;`,+ "./ActionManagerDialog": `export default () => null;`,+ "./AddNotesToFolderDialog": `export default () => null;`,+ "./NotesOnboarding": `export default () => null;`,+ "/hooks/useActionProcessing": `+ export const useActionProcessing = () => ({ state: "idle", actionName: null, runAction() {} });+ `,+ "/stores/actionStore": `export const useActions = () => [];`,+ "/hooks/useNotesOnboarding": `+ export const useNotesOnboarding = () => ({ isComplete: true, complete() {} });+ `,+ "/hooks/useTeamSpacesCapability": `export const useTeamSpacesCapability = () => false;`,+ "/hooks/useAuth": `export const useAuth = () => ({ isSignedIn: false, user: null });`,+ // Just enough of the note store for setActiveNoteId to drive note switches.+ "/stores/noteStore": `+ import { useSyncExternalStore } from "react";+ const state = { activeNoteId: 11 };+ const subscribers = new Set();+ const subscribe = (fn) => {+ subscribers.add(fn);+ return () => subscribers.delete(fn);+ };+ const notes = () => globalThis.__notes;+ export const setActiveNoteId = (id) => {+ state.activeNoteId = id;+ subscribers.forEach((fn) => fn());+ };+ globalThis.__setActiveNoteId = setActiveNoteId;+ export const useActiveNoteId = () => useSyncExternalStore(subscribe, () => state.activeNoteId);+ export const useActiveNote = () =>+ useSyncExternalStore(subscribe, () => notes()[state.activeNoteId] ?? null);+ export const useNotes = () => [];+ export const useSpaces = () => [];+ export const useFolders = () => [];+ export const useActiveFolderId = () => null;+ export const useActiveContext = () => null;+ export const useIsTreeLoading = () => false;+ export const initializeNotes = async () => {};+ export const initializeNotesTree = async () => {};+ export const loadFolders = async () => {};+ export const setActiveContext = () => {};+ export const revealContainer = () => {};+ export const createFolder = async () => ({ success: false });+ export const getNoteFromStore = (id) => notes()[id] ?? null;+ `,+};++async function setup(t) {+ let root;+ let store;+ t.after(async () => {+ if (store) await React.act(async () => store.stopRecording());+ if (root) await React.act(async () => root.unmount());+ for (const key of ["__editorLog", "__editorProps", "__notes", "__setActiveNoteId"]) {+ delete globalThis[key];+ }+ });+ globalThis.__editorLog = [];+ globalThis.__notes = structuredClone(NOTES);++ const calls = { stop: 0, send: [], updateNote: [], trackStops: 0 };+ const listeners = {};+ const capture = (name) => (callback) => {+ listeners[name] = callback;+ return () => {+ if (listeners[name] === callback) listeners[name] = null;+ };+ };+ const api = {+ checkSystemAudioAccess: async () => ({+ granted: true,+ status: "granted",+ mode: "native",+ strategy: "native",+ }),+ meetingTranscriptionStart: async () => ({+ success: true,+ systemAudioMode: "native",+ systemAudioStrategy: "native",+ }),+ meetingTranscriptionSetSystemAudioAvailable: async () => ({ success: true }),+ meetingTranscriptionStop: async () => {+ calls.stop += 1;+ return { success: true };+ },+ meetingTranscriptionSend: (_chunk, source) => calls.send.push(source),+ updateNote: async (id, updates) => {+ calls.updateNote.push([id, updates]);+ return { success: true };+ },+ getNote: async (id) => globalThis.__notes[id] ?? null,+ onMeetingTranscriptionSegment: capture("segment"),+ onMeetingSpeakerIdentified: capture("speaker"),+ onMeetingSpeakersMerged: capture("merged"),+ onMeetingSessionSpeakerConfigUpdated: capture("speakerConfig"),+ onMeetingTranscriptionError: capture("error"),+ onMeetingTranscriptionFatalError: capture("fatal"),+ onMeetingSystemAudioSilent: capture("silent"),+ onMeetingSystemAudioInterrupted: capture("interrupted"),+ onMeetingSystemAudioResumed: capture("resumed"),+ onMeetingAutoEndRequested: capture("autoEnd"),+ onMeetingDiarizationComplete: capture("diarization"),+ };+ installBrowserGlobals(t, {+ window: { electronAPI: api, setTimeout: (fn, ms) => setTimeout(fn, ms) },+ });+ installMicCaptureGlobals(t);+ // The mic track stopping is what "the recording stopped" means in hardware.+ const track = {+ readyState: "live",+ label: "Fake Mic",+ stop: () => (calls.trackStops += 1),+ getSettings: () => ({}),+ };+ const stream = {+ getTracks: () => [track],+ getAudioTracks: () => [track],+ getVideoTracks: () => [],+ };+ globalThis.navigator.mediaDevices.getUserMedia = async () => stream;+ const worklets = [];+ const BaseWorklet = globalThis.AudioWorkletNode;+ globalThis.AudioWorkletNode = class extends BaseWorklet {+ constructor(...args) {+ super(...args);+ worklets.push(this);+ }+ };+ const container = installHostDom(t);+ globalThis.document.visibilityState = "visible";+ globalThis.document.hasFocus = () => true;++ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-meeting-view-switch-test-",+ mockModules: MOCKS,+ });+ const { default: Mount } = await vite.ssrLoadModule("/components/MeetingRecordingMount.tsx");+ const { default: PersonalNotesView } = await vite.ssrLoadModule(+ "/components/notes/PersonalNotesView.tsx"+ );+ store = await vite.ssrLoadModule("/stores/meetingRecordingStore.ts");++ const Home = () => React.createElement("div", null, "home");+ const Shell = ({ view }) =>+ React.createElement(+ React.Fragment,+ null,+ React.createElement(Mount),+ view === "personal-notes" ? React.createElement(PersonalNotesView) : null,+ view === "home" ? React.createElement(Home) : null+ );+ root = createRoot(container);+ const show = (view) => React.act(async () => root.render(React.createElement(Shell, { view })));+ const openNote = (id) => React.act(async () => globalThis.__setActiveNoteId(id));+ const say = (text) =>+ React.act(async () =>+ listeners.segment?.({ text, source: "mic", type: "final", timestamp: Date.now() })+ );+ const micChunk = () => worklets[0].port.onmessage({ data: new ArrayBuffer(16) });+ const isRecording = () => store.useMeetingRecordingStore.getState().isRecording;+ return { store, show, openNote, say, micChunk, isRecording, calls };+}++test("#1685: switching views and notes mid-recording never stops the recording", async (t) => {+ const { store, show, openNote, say, micChunk, isRecording, calls } = await setup(t);+ await show("personal-notes");+ assert.deepEqual(globalThis.__editorLog, [["mount", 11]]);++ // The note's record button (NoteEditor -> onStartRecording).+ await React.act(async () => globalThis.__editorProps.onStartRecording());+ assert.equal(isRecording(), true);+ assert.equal(store.useMeetingRecordingStore.getState().recordingNoteId, 11);+ await say("first words");++ // Note switch: NoteEditor is keyed by note id, so it unmounts and remounts.+ await openNote(12);+ assert.deepEqual(globalThis.__editorLog.slice(-2), [+ ["unmount", 11],+ ["mount", 12],+ ]);+ assert.equal(isRecording(), true, "a note switch keeps recording");++ // Folder or space overview: no active note, so ContainerOverview replaces NoteEditor.+ await openNote(null);+ await openNote(12);+ assert.equal(isRecording(), true, "the overview keeps recording");++ // View switch: the whole notes view unmounts.+ await show("home");+ assert.deepEqual(globalThis.__editorLog.slice(-1), [["unmount", 12]]);+ assert.equal(isRecording(), true, "a view switch keeps recording");+ assert.equal(calls.stop, 0, "no meeting-transcription-stop was sent");+ assert.equal(calls.trackStops, 0, "the mic track was never stopped");++ // Audio keeps reaching main while the notes view is gone.+ const sentBefore = calls.send.length;+ micChunk();+ assert.deepEqual(calls.send.slice(sentBefore), ["mic"]);+ await say("said while on Home");++ // A view with nothing mounted, then back to the recording note.+ await show(null);+ await show("personal-notes");+ await openNote(11);+ assert.equal(globalThis.__editorProps.note.id, 11);+ assert.equal(globalThis.__editorProps.isRecording, true, "returning shows the live recording");+ assert.equal(calls.stop, 0);++ // The floating pill's Stop (MeetingRecordingPill calls stopRecording() with no+ // arguments) while another view is open: the transcript must still reach the note.+ await show("home");+ await React.act(async () => store.stopRecording());+ assert.equal(calls.stop, 1);+ const finalWrite = calls.updateNote+ .filter(([id, updates]) => id === 11 && typeof updates.transcript === "string")+ .at(-1);+ assert.ok(finalWrite, "final transcript persisted with the notes view unmounted");+ assert.match(finalWrite[1].transcript, /first words/);+ assert.match(finalWrite[1].transcript, /said while on Home/);+});++// Control: the counters above are not vacuous, because an explicit Stop registers.+test("#1685 control: the note's Stop button does stop and is counted", async (t) => {+ const { show, isRecording, calls } = await setup(t);+ await show("personal-notes");+ await React.act(async () => globalThis.__editorProps.onStartRecording());+ assert.equal(isRecording(), true);++ await React.act(async () => globalThis.__editorProps.onStopRecording());++ assert.equal(isRecording(), false);+ assert.equal(calls.stop, 1);+ assert.equal(calls.trackStops, 1);+});diff --git a/test/components/signOutEndsMeetingRecording.test.js b/test/components/signOutEndsMeetingRecording.test.jsnew file mode 100644index 000000000..582296e4a--- /dev/null+++ b/test/components/signOutEndsMeetingRecording.test.js@@ -0,0 +1,102 @@+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");+const test = require("node:test");+const vm = require("node:vm");+const ts = require("typescript");++// Signing out clears main's account scope the moment the token is cleared, so+// a live meeting's note is out of reach from then on: neither its later saves+// nor the reload's beforeunload flush can write it. Settings' Sign out and the+// invitation's account switch end the meeting first, and the stop writes the+// final transcript. (Account deletion deletes the note, so it has nothing to save.)+// Exercise the actual callbacks without loading their components.+function extractFunction(relativePath, name) {+ const filename = path.join(__dirname, relativePath);+ const source = ts.createSourceFile(+ filename,+ fs.readFileSync(filename, "utf8"),+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX+ );+ let code;+ function visit(node) {+ if (+ ts.isVariableDeclaration(node) &&+ node.name.getText(source) === name &&+ node.initializer &&+ ts.isCallExpression(node.initializer) &&+ node.initializer.expression.getText(source) === "useCallback"+ ) {+ code = `const ${name} = ${node.initializer.arguments[0].getText(source)};`;+ } else if (ts.isFunctionDeclaration(node) && node.name?.getText(source) === name) {+ code = node.getText(source);+ }+ ts.forEachChild(node, visit);+ }+ visit(source);+ assert.ok(code, `${relativePath} must define ${name}`);+ return ts.transpileModule(code, { compilerOptions: { target: ts.ScriptTarget.ES2022 } })+ .outputText;+}++function createContext(calls) {+ return {+ // Resolves on a later tick, so the order below also proves it is awaited.+ stopRecording: () =>+ new Promise((resolve) => {+ setTimeout(() => {+ calls.push("meeting stopped");+ resolve({ diarizationSessionId: null, stopped: true });+ }, 0);+ }),+ syncService: {+ purgeTeamSpacesForSignOut: async () => {+ calls.push("team spaces purged");+ },+ },+ signOut: async () => {+ calls.push("signed out");+ },+ window: { location: { reload: () => calls.push("reloaded") } },+ setIsSigningOut: () => {},+ logger: { error: (message) => calls.push(`error: ${message}`) },+ showAlertDialog: () => calls.push("alert"),+ t: (key) => key,+ token: "invite-token",+ storePendingInvitationToken: () => calls.push("invitation kept"),+ };+}++test("Settings sign-out ends a live meeting before the account scope is cleared", async () => {+ const calls = [];+ const handleSignOut = vm.runInNewContext(+ `${extractFunction("../../src/components/SettingsPage.tsx", "handleSignOut")}\nhandleSignOut;`,+ createContext(calls)+ );++ await handleSignOut();++ assert.deepEqual(calls, ["meeting stopped", "team spaces purged", "signed out", "reloaded"]);+});++test("switching account from an invitation ends a live meeting before signing out", async () => {+ const calls = [];+ const handleSwitchAccount = vm.runInNewContext(+ `${extractFunction(+ "../../src/components/AcceptInvitationModal.tsx",+ "handleSwitchAccount"+ )}\nhandleSwitchAccount;`,+ createContext(calls)+ );++ await handleSwitchAccount();++ assert.deepEqual(calls, [+ "invitation kept",+ "meeting stopped",+ "team spaces purged",+ "signed out",+ ]);+});diff --git a/test/lib/rendererTestHarness.js b/test/lib/rendererTestHarness.jsindex 1128689b6..9a310733c 100644--- a/test/lib/rendererTestHarness.js+++ b/test/lib/rendererTestHarness.js@@ -95,6 +95,118 @@ function installHookDom(t) {return container;}+// installHookDom plus host elements, for mounting components that render real+// markup (divs, buttons, text) — e.g. a whole view that must unmount and+// remount. Still no layout and no events: React DOM only needs a node tree it+// can insert into, update and remove from. Returns the root container.+function installHostDom(t) {+ installHookDom(t);+ const document = globalThis.document;+ const HTML_NS = "http://www.w3.org/1999/xhtml";+ const createStyle = () => {+ const style = {};+ Object.defineProperties(style, {+ setProperty: { value: (name, value) => (style[name] = value) },+ removeProperty: { value: (name) => delete style[name] },+ });+ return style;+ };++ class HostNode {+ constructor(nodeType, name, namespaceURI = null) {+ this.nodeType = nodeType;+ this.nodeName = name.toUpperCase();+ this.tagName = this.nodeName;+ this.localName = name.toLowerCase();+ this.namespaceURI = namespaceURI;+ this.ownerDocument = document;+ this.childNodes = [];+ this.parentNode = null;+ this.attributes = {};+ this.style = createStyle();+ this.nodeValue = null;+ }++ get firstChild() {+ return this.childNodes[0] ?? null;+ }++ get lastChild() {+ return this.childNodes.at(-1) ?? null;+ }++ get nextSibling() {+ if (!this.parentNode) return null;+ const siblings = this.parentNode.childNodes;+ return siblings[siblings.indexOf(this) + 1] ?? null;+ }++ appendChild(child) {+ return this.insertBefore(child, null);+ }++ insertBefore(child, before) {+ child.parentNode?.removeChild(child);+ const index = before ? this.childNodes.indexOf(before) : -1;+ if (index < 0) this.childNodes.push(child);+ else this.childNodes.splice(index, 0, child);+ child.parentNode = this;+ return child;+ }++ removeChild(child) {+ const index = this.childNodes.indexOf(child);+ if (index >= 0) this.childNodes.splice(index, 1);+ child.parentNode = null;+ return child;+ }++ setAttribute(name, value) {+ this.attributes[name] = String(value);+ }++ removeAttribute(name) {+ delete this.attributes[name];+ }++ getAttribute(name) {+ return this.attributes[name] ?? null;+ }++ hasAttribute(name) {+ return name in this.attributes;+ }++ addEventListener() {}+ removeEventListener() {}+ focus() {}+ blur() {}++ get textContent() {+ if (this.nodeType === 3) return this.nodeValue;+ return this.childNodes.map((child) => child.textContent).join("");+ }++ set textContent(value) {+ for (const child of this.childNodes) child.parentNode = null;+ this.childNodes = [];+ if (value !== "" && value != null) this.appendChild(document.createTextNode(value));+ }+ }++ document.createElement = (tagName) => new HostNode(1, tagName, HTML_NS);+ document.createElementNS = (namespaceURI, tagName) => new HostNode(1, tagName, namespaceURI);+ document.createTextNode = (text) => {+ const node = new HostNode(3, "#text");+ node.nodeValue = String(text);+ return node;+ };+ document.body = document.createElement("body");+ const container = document.createElement("div");+ document.documentElement = container;+ return container;+}+// mockModules maps an import-path suffix (e.g. "/utils/logger") to the ESM// source served in its place.async function createRendererServer(@@ -214,5 +326,6 @@ module.exports = {createRendererServer,installBrowserGlobals,installHookDom,+ installHostDom,installMicCaptureGlobals,};diff --git a/test/stores/meetingRecordingStoreUnloadFlush.test.js b/test/stores/meetingRecordingStoreUnloadFlush.test.jsnew file mode 100644index 000000000..98b50e4db--- /dev/null+++ b/test/stores/meetingRecordingStoreUnloadFlush.test.js@@ -0,0 +1,297 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const {+ createRendererServer,+ installBrowserGlobals,+ installMicCaptureGlobals,+} = require("../lib/rendererTestHarness");++// A window reload mid-recording (Sign in, SSO completion, the crash screen's+// Reload) replaces this renderer: main's owner-loss teardown ends the session+// and the store's module state goes with the page, so stopRecording never+// writes what was said since the last 30-second save. The store writes the+// live transcript on beforeunload instead. Chromium dispatches it before a+// renderer reload and before main's loadURL/loadFile alike, while the page can+// still reach main.++const NOTE_ID = 11;+const START_ARGS = {+ noteId: NOTE_ID,+ noteTitle: "Standup",+ folderId: null,+ autoEndEligible: true,+};++function createElectronAPI({ stopResult = async () => ({ success: true }) } = {}) {+ const noopListener = () => () => {};+ const listeners = {};+ const capture = (name) => (callback) => {+ listeners[name] = callback;+ return () => {+ if (listeners[name] === callback) listeners[name] = null;+ };+ };+ const writes = [];+ const api = {+ checkSystemAudioAccess: async () => ({+ granted: true,+ status: "granted",+ mode: "native",+ strategy: "native",+ }),+ meetingTranscriptionStart: async () => ({+ success: true,+ systemAudioMode: "native",+ systemAudioStrategy: "native",+ }),+ meetingTranscriptionSetSystemAudioAvailable: async () => ({ success: true }),+ meetingTranscriptionStop: () => stopResult(),+ meetingTranscriptionSend: () => {},+ getNote: async () => null,+ updateNote: async (id, patch) => {+ writes.push([id, patch]);+ return { success: true };+ },+ onMeetingTranscriptionSegment: capture("segment"),+ onNoteDeleted: capture("noteDeleted"),+ onNoteSynced: capture("noteSynced"),+ onMeetingSpeakerIdentified: noopListener,+ onMeetingSpeakersMerged: noopListener,+ onMeetingSessionSpeakerConfigUpdated: noopListener,+ onMeetingTranscriptionError: noopListener,+ onMeetingTranscriptionFatalError: noopListener,+ onMeetingSystemAudioSilent: noopListener,+ onMeetingDiarizationComplete: noopListener,+ };+ return { api, listeners, writes };+}++async function loadStore(t, api) {+ const windowListeners = new Map();+ installMicCaptureGlobals(t);+ installBrowserGlobals(t, {+ window: {+ electronAPI: api,+ setTimeout: (fn, ms) => setTimeout(fn, ms),+ addEventListener: (type, listener) => {+ windowListeners.set(type, [...(windowListeners.get(type) ?? []), listener]);+ },+ removeEventListener: (type, listener) => {+ windowListeners.set(+ type,+ (windowListeners.get(type) ?? []).filter((candidate) => candidate !== listener)+ );+ },+ },+ });+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-meeting-unload-flush-test-",+ });+ const store = await vite.ssrLoadModule("/stores/meetingRecordingStore.ts");+ const unloadListeners = () => windowListeners.get("beforeunload") ?? [];+ // Runs the handlers the way the page would, synchronously and to completion.+ const unload = () => {+ const event = {+ type: "beforeunload",+ defaultPrevented: false,+ returnValue: "",+ preventDefault() {+ this.defaultPrevented = true;+ },+ };+ const results = unloadListeners().map((listener) => listener(event));+ return { event, results };+ };+ return { store, unload, unloadListeners, vite };+}++const transcriptWrites = (writes) =>+ writes.filter(([, patch]) => typeof patch.transcript === "string");++const final = (text) => ({ text, source: "mic", type: "final", timestamp: Date.now() });+const deleteNote = (listeners, id) => listeners.noteDeleted?.({ id });+const syncNote = (listeners, note) => listeners.noteSynced?.(note);++// Lets a stop reach its first real await (the audio flush timer).+const settle = async () => {+ for (let i = 0; i < 20; i += 1) await Promise.resolve();+};++test("a reload mid-recording writes the live transcript as the page unloads", async (t) => {+ const { api, listeners, writes } = createElectronAPI();+ const { store, unload } = await loadStore(t, api);+ assert.equal(await store.startRecording(START_ARGS), true);+ listeners.segment(final("said after the last save"));+ writes.length = 0;++ const { event, results } = unload();++ // Checked before any await: nothing after the handler returns is sure to run.+ const flushed = transcriptWrites(writes);+ assert.equal(flushed.length, 1, "the live transcript is written as the window unloads");+ assert.equal(flushed[0][0], NOTE_ID);+ assert.match(flushed[0][1].transcript, /said after the last save/);+ // A cancelled unload fails main's loadURL and prompts on a reload.+ assert.equal(event.defaultPrevented, false);+ assert.equal(event.returnValue, "");+ assert.ok(results.every((result) => result === undefined));++ // Same serialization the stop path writes, so diarization merges either one.+ writes.length = 0;+ await store.stopRecording();+ assert.equal(transcriptWrites(writes).at(-1)[1].transcript, flushed[0][1].transcript);+});++test("the unload listener is registered once, at module load", async (t) => {+ const { api } = createElectronAPI();+ const { store, unloadListeners } = await loadStore(t, api);+ assert.equal(unloadListeners().length, 1);++ assert.equal(await store.startRecording(START_ARGS), true);+ await store.stopRecording();+ assert.equal(await store.startRecording(START_ARGS), true);+ await store.stopRecording();++ assert.equal(unloadListeners().length, 1, "sessions must not stack listeners");+});++test("an unload with nothing to save writes nothing", async (t) => {+ const { api, listeners, writes } = createElectronAPI();+ const { store, unload } = await loadStore(t, api);++ unload();+ assert.deepEqual(transcriptWrites(writes), [], "no recording");++ assert.equal(await store.startRecording(START_ARGS), true);+ unload();+ assert.deepEqual(transcriptWrites(writes), [], "no segments yet");+ await store.stopRecording();++ assert.equal(await store.startRecording({ ...START_ARGS, noteId: null }), true);+ listeners.segment(final("no note to hold this"));+ unload();+ assert.deepEqual(transcriptWrites(writes), [], "no note");+ await store.stopRecording();+});++test("an unload during a stop neither duplicates nor overwrites its final write", async (t) => {+ let releaseStop;+ const stopGate = new Promise((resolve) => {+ releaseStop = resolve;+ });+ const { api, listeners, writes } = createElectronAPI({ stopResult: () => stopGate });+ const { store, unload } = await loadStore(t, api);+ assert.equal(await store.startRecording(START_ARGS), true);+ listeners.segment(final("closing words"));+ writes.length = 0;++ const stopping = store.stopRecording();+ await settle();+ assert.equal(transcriptWrites(writes).length, 1, "the stop wrote its final transcript");++ unload();+ assert.equal(transcriptWrites(writes).length, 1, "the flush stays out of a stop");++ releaseStop({ success: true });+ await stopping;+});++test("a note deleted mid-recording is not written back from its tombstone", async (t) => {+ const { api, listeners, writes } = createElectronAPI();+ const { store, unload } = await loadStore(t, api);+ assert.equal(await store.startRecording(START_ARGS), true);+ listeners.segment(final("said before the delete"));++ deleteNote(listeners, 12);+ writes.length = 0;+ unload();+ assert.equal(transcriptWrites(writes).length, 1, "another note's delete changes nothing");++ deleteNote(listeners, NOTE_ID);+ writes.length = 0;+ unload();+ assert.deepEqual(transcriptWrites(writes), []);+ await store.stopRecording();++ // The guard belongs to that recording, not to every later one.+ assert.equal(await store.startRecording({ ...START_ARGS, noteId: 12 }), true);+ listeners.segment(final("a new meeting"));+ writes.length = 0;+ unload();+ assert.equal(transcriptWrites(writes).length, 1);+ await store.stopRecording();+});++// A team-note delete the server denies (stale admin permissions) revives the+// same row, and the snapshot pull that follows re-syncs it as a live note.+test("a recording note restored after a denied delete is saved again", async (t) => {+ const { api, listeners, writes } = createElectronAPI();+ const { store, unload } = await loadStore(t, api);+ assert.equal(await store.startRecording(START_ARGS), true);+ listeners.segment(final("said before the delete"));+ deleteNote(listeners, NOTE_ID);++ // A pull racing the delete re-syncs the row with its tombstone intact.+ syncNote(listeners, { id: NOTE_ID, deleted_at: "2026-09-23 10:00:00" });+ syncNote(listeners, { id: 12, deleted_at: null });+ writes.length = 0;+ unload();+ assert.deepEqual(transcriptWrites(writes), [], "still a tombstone");++ syncNote(listeners, { id: NOTE_ID, deleted_at: null });+ listeners.segment(final("said after the restore"));+ writes.length = 0;+ unload();+ const flushed = transcriptWrites(writes);+ assert.equal(flushed.length, 1, "the restored note is saved again");+ assert.match(flushed[0][1].transcript, /said after the restore/);+ await store.stopRecording();+});++test("a resumed recording's unload keeps the transcript it resumed from", async (t) => {+ const { api, listeners, writes } = createElectronAPI();+ const { store, unload } = await loadStore(t, api);+ const seedSegments = [+ { id: "seed-1", text: "from the first half", source: "mic", timestamp: 1 },+ ];+ assert.equal(await store.startRecording({ ...START_ARGS, seedSegments }), true);+ listeners.segment(final("from the second half"));+ writes.length = 0;++ unload();++ const [[, { transcript }]] = transcriptWrites(writes);+ assert.match(transcript, /from the first half/, "an unload must not truncate the note");+ assert.match(transcript, /from the second half/);+ await store.stopRecording();+});++// The 30-second saver fires this without awaiting, so a failure must never escape.+for (const [name, updateNote] of [+ [+ "a thrown live save",+ async () => {+ throw new Error("database closed");+ },+ ],+ ["a refused live save", async () => ({ success: false, error: "Note not found" })],+]) {+ test(`${name} is logged, never thrown`, async (t) => {+ const { api, listeners } = createElectronAPI();+ api.updateNote = updateNote;+ const { store, vite } = await loadStore(t, api);+ const { default: logger } = await vite.ssrLoadModule("/utils/logger.ts");+ const logged = t.mock.method(logger, "error", () => {});+ assert.equal(await store.startRecording(START_ARGS), true);+ listeners.segment(final("said as the save failed"));++ await assert.doesNotReject(store.persistLiveTranscript());+ assert.ok(+ logged.mock.calls.some(+ ({ arguments: [message] }) => message === "Failed to persist live meeting transcript"+ ),+ "the failed save is logged"+ );+ await store.stopRecording();+ });+}