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
feat(meetings): Add immediate auto-end restart window (#1898)
Chad Piha0199d72f97e8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 66ed5bd8c..645842dd3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Meetings++- **Meeting recordings stop as soon as the call ends.** The microphone, silence, and meeting-app signals no longer open a 60-second **Keep recording** countdown first, so recordings now end about a minute sooner than before. A microphone release still waits 5 seconds of continued quiet before it counts, so a headset reconnecting or an app that drops the mic on mute cannot cut a live call short. A 30-second card then offers to restart the same note — keeping its transcript, folder, and speaker settings — and restarting holds auto-end off for five minutes. (#1898)+### Data safety- **Deleting one account no longer erases another account's local content.** Account deletion now removes only that account's private notes and folders, preserves workspace-owned spaces and content with former-user attribution cleared, and leaves downloaded models and device settings intact. A separate unchecked option erases all app data from the device when leaving OpenWhispr permanently.diff --git a/preload.js b/preload.jsindex 98ac8924c..91e3508e5 100644--- a/preload.js+++ b/preload.js@@ -1246,7 +1246,14 @@ contextBridge.exposeInMainWorld("electronAPI", {"meeting-auto-end-requested",(callback) => (_event, data) => callback(data)),- meetingAutoEndKeep: (sessionId) => ipcRenderer.invoke("meeting-auto-end-keep", sessionId),+ meetingAutoEndCompleted: (sessionId) =>+ ipcRenderer.invoke("meeting-auto-end-completed", sessionId),+ meetingAutoEndRespond: (sessionId, action) =>+ ipcRenderer.invoke("meeting-auto-end-respond", sessionId, action),+ onMeetingAutoEndRestartRequested: registerListener(+ "meeting-auto-end-restart-requested",+ (callback) => (_event, data) => callback(data)+ ),getMeetingNotificationData: () => ipcRenderer.invoke("get-meeting-notification-data"),meetingNotificationReady: () => ipcRenderer.invoke("meeting-notification-ready"),meetingNotificationRespond: (detectionId, action) =>diff --git a/src/components/MeetingNotificationOverlay.tsx b/src/components/MeetingNotificationOverlay.tsxindex 99a51596d..5ce3bd398 100644--- a/src/components/MeetingNotificationOverlay.tsx+++ b/src/components/MeetingNotificationOverlay.tsx@@ -1,10 +1,11 @@import { useState, useEffect, useCallback } from "react";import { useTranslation } from "react-i18next";-import type { MeetingNotificationData } from "../types/electron";+import type { MeetingAutoEndAction, MeetingNotificationData } from "../types/electron";import { MeetingNotificationCard } from "./MeetingNotificationCard";import {getMeetingNotificationPresentation,initializeMeetingNotificationOverlay,+ shouldRestoreAutoEndCard,subscribeMeetingAutoEndCountdown,} from "./meetingNotificationModel";@@ -43,10 +44,23 @@ export default function MeetingNotificationOverlay() {[data]);- const keepRecording = useCallback(() => {- if (data?.kind !== "auto-end") return;- void window.electronAPI?.meetingAutoEndKeep?.(data.sessionId);- }, [data]);+ const respondToAutoEnd = useCallback(+ async (action: MeetingAutoEndAction) => {+ if (data?.kind !== "auto-end") return;+ setIsVisible(false);+ // Main closes this window when it accepts the response. Anything else —+ // a rejection, a throw, a preload without the method — leaves it open, so+ // put the card back instead of stranding an invisible, unclickable+ // always-on-top overlay.+ try {+ const result = await window.electronAPI?.meetingAutoEndRespond?.(data.sessionId, action);+ if (shouldRestoreAutoEndCard(result)) setIsVisible(true);+ } catch {+ setIsVisible(true);+ }+ },+ [data]+ );const handleMouseEnter = useCallback(() => {setIsHovered(true);@@ -65,7 +79,11 @@ export default function MeetingNotificationOverlay() {? t(presentation.bodyKey, presentation.bodyValues): t(presentation.bodyKey);const handleAction =- presentation.action === "keep" ? keepRecording : () => respond(presentation.action);+ presentation.action === "restart"+ ? () => void respondToAutoEnd("restart")+ : () => respond(presentation.action);+ const handleDismiss =+ data?.kind === "auto-end" ? () => void respondToAutoEnd("dismiss") : () => respond("dismiss");return (<div className="meeting-notification-window w-full h-full bg-transparent p-3">@@ -74,7 +92,7 @@ export default function MeetingNotificationOverlay() {body={body}startLabel={t(presentation.actionKey)}onStart={handleAction}- onDismiss={presentation.dismissible ? () => respond("dismiss") : undefined}+ onDismiss={presentation.dismissible ? handleDismiss : undefined}closeVisible={isHovered}allowTitleWrap={presentation.allowTitleWrap}onMouseEnter={handleMouseEnter}diff --git a/src/components/MeetingRecordingMount.tsx b/src/components/MeetingRecordingMount.tsxindex 8427699d1..4a791365b 100644--- a/src/components/MeetingRecordingMount.tsx+++ b/src/components/MeetingRecordingMount.tsx@@ -5,10 +5,17 @@ import {getActiveRecordingSessionId,getMicAnalyser,primeMeetingWorklet,+ startRecording,stopRecording,useMeetingRecordingStore,} from "../stores/meetingRecordingStore";-import { requestMeetingRecordingAutoEnd } from "../helpers/meetingRecordingSession";+import {+ createMeetingAutoEndRestartContext,+ requestMeetingRecordingAutoEnd,+ runMeetingAutoEndRestart,+ type MeetingAutoEndRestartContext,+} from "../helpers/meetingRecordingSession";+import { parseTranscriptSegments } from "../utils/parseTranscriptSegments";import { serializeTranscriptSegments } from "../utils/transcriptSpeakerState";import logger from "../utils/logger";@@ -31,29 +38,70 @@ export default function MeetingRecordingMount(): null {const micCaptureStatus = useMeetingRecordingStore((s) => s.micCaptureStatus);const wasMicUnavailable = useRef(false);const wasSystemAudioSilent = useRef(false);+ const pendingAutoEndRestart = useRef<MeetingAutoEndRestartContext | null>(null);+ // The auto-end listeners are registered once, so they cannot close over `t`+ // or `toast` directly without pinning the language they mounted with.+ const notifyAutoEnded = useRef<() => void>(() => {});+ const notifyRestartFailed = useRef<() => void>(() => {});++ useEffect(() => {+ notifyAutoEnded.current = () => {+ toast({ title: t("notes.meeting.title"), description: t("notes.meeting.autoEnded") });+ };+ notifyRestartFailed.current = () => {+ toast({+ title: t("notes.meeting.title"),+ description: t("notes.meeting.restartFailed"),+ variant: "destructive",+ });+ };+ }, [toast, t]);useEffect(() => {primeMeetingWorklet();}, []);useEffect(() => {- return window.electronAPI?.onMeetingAutoEndRequested?.((request) => {+ const unsubscribeStop = window.electronAPI?.onMeetingAutoEndRequested?.((request) => {+ const restartContext = createMeetingAutoEndRestartContext(+ request.sessionId,+ getActiveRecordingSessionId(),+ useMeetingRecordingStore.getState()+ );+ if (!restartContext) return;+requestMeetingRecordingAutoEnd(request,- (sessionId) => {- // Toast only when this request actually ends the live session — and- // even if the user's Keep click lost the race with the countdown, so- // they learn the recording ended rather than assuming it was kept.- const endsActiveSession = getActiveRecordingSessionId() === sessionId;- return stopRecording(sessionId).then((result) => {- if (endsActiveSession) {- toast({- title: t("notes.meeting.title"),- description: t("notes.meeting.autoEnded"),- });+ stopRecording,+ (sessionId, stopped) => {+ // Every path that ends the recording without offering a restart card+ // has to say so, or the recording just disappears.+ const abandonRestart = () => {+ if (pendingAutoEndRestart.current?.sessionId === sessionId) {+ pendingAutoEndRestart.current = null;}- return result;- });+ notifyAutoEnded.current();+ };++ const completion = window.electronAPI?.meetingAutoEndCompleted;+ if (!stopped || !completion) {+ abandonRestart();+ return;+ }++ pendingAutoEndRestart.current = restartContext;+ void completion(sessionId)+ .then((result) => {+ if (!result.success) abandonRestart();+ })+ .catch((error) => {+ abandonRestart();+ logger.error(+ "Meeting auto-end completion acknowledgment failed",+ { error: error instanceof Error ? error.message : String(error), sessionId },+ "meeting"+ );+ });},(error, sessionId) => {logger.error(@@ -64,7 +112,48 @@ export default function MeetingRecordingMount(): null {});});- }, [toast, t]);++ const unsubscribeRestart = window.electronAPI?.onMeetingAutoEndRestartRequested?.((request) => {+ const context = pendingAutoEndRestart.current;+ pendingAutoEndRestart.current = null;++ void runMeetingAutoEndRestart(request, context, {+ getActiveSessionId: getActiveRecordingSessionId,+ getLatestSegments: () => useMeetingRecordingStore.getState().segments,+ getNote: (noteId) => window.electronAPI?.getNote?.(noteId) ?? Promise.resolve(null),+ parseSegments: parseTranscriptSegments,+ startRecording,+ })+ .then((outcome) => {+ // Main already closed the card and reported success, so an abort the+ // user is not told about looks exactly like a restart that worked.+ if (outcome.status === "started") return;+ logger.error(+ "Meeting recording restart aborted",+ { reason: outcome.reason, sessionId: request.sessionId },+ "meeting"+ );+ notifyRestartFailed.current();+ })+ .catch((error) => {+ logger.error(+ "Meeting recording restart failed",+ { error: error instanceof Error ? error.message : String(error) },+ "meeting"+ );+ notifyRestartFailed.current();+ });+ });++ return () => {+ unsubscribeStop?.();+ unsubscribeRestart?.();+ };+ }, []);++ useEffect(() => {+ if (isRecording) pendingAutoEndRestart.current = null;+ }, [isRecording]);// Crash-safety net moved out of the notes view: it must keep running when// the user switches views mid-recording.diff --git a/src/components/meetingNotificationModel.ts b/src/components/meetingNotificationModel.tsindex edd10cd2a..78da957fa 100644--- a/src/components/meetingNotificationModel.ts+++ b/src/components/meetingNotificationModel.ts@@ -15,9 +15,9 @@ interface AutoEndPresentation {titleKey: "meetingNotification.autoEnd.title";bodyKey: AutoEndBodyKey;bodyValues: { seconds: number };- actionKey: "meetingNotification.autoEnd.keep";- action: "keep";- dismissible: false;+ actionKey: "meetingNotification.autoEnd.restart";+ action: "restart";+ dismissible: true;allowTitleWrap: true;}@@ -46,9 +46,9 @@ export function getMeetingNotificationPresentation(bodyKey:AUTO_END_BODY_KEYS[data.reason ?? "mic-released"] ?? AUTO_END_BODY_KEYS["mic-released"],bodyValues: { seconds: secondsRemaining },- actionKey: "meetingNotification.autoEnd.keep",- action: "keep",- dismissible: false,+ actionKey: "meetingNotification.autoEnd.restart",+ action: "restart",+ dismissible: true,allowTitleWrap: true,};}@@ -129,6 +129,13 @@ const defaultCountdownClock: CountdownClock = {clearInterval: (timer) => clearInterval(timer),};+// Main closes the notification window when it accepts a response. Anything+// else — a rejected response, or a preload without the method — leaves the+// window alive, so the optimistically hidden card must be restored.+export function shouldRestoreAutoEndCard(result: { success: boolean } | null | undefined): boolean {+ return result?.success !== true;+}+export function getMeetingAutoEndSecondsRemaining(expiresAt: number, now: number): number {return Math.max(0, Math.ceil((expiresAt - now) / 1000));}diff --git a/src/helpers/electronProcessIds.js b/src/helpers/electronProcessIds.jsindex 2703388da..e1c6a75f2 100644--- a/src/helpers/electronProcessIds.js+++ b/src/helpers/electronProcessIds.js@@ -4,7 +4,7 @@ const { getOwnProcessPids } = require("./ownProcessPids");// loopback) are plain child processes, so they never appear in the Electron// process tree — yet the OS attributes their capture to their own pids.// Without excluding them, the app's own system-audio capture reads as an-// external mic user and auto-end can never arm its countdown.+// external mic user and auto-end can never arm its end detection.function collectAudioCaptureHelperPids(managers) {return managers.map((manager) => manager?.process?.pid)diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex eedec23e4..14127980a 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -72,7 +72,7 @@ const { transcribeWithGemini } = require("./geminiTranscription");const AudioStorageManager = require("./audioStorage");const AgentStreamRequestRegistry = require("./agentStreamRequestRegistry");const createMeetingTranscriptionLifecycle = require("./meetingTranscriptionLifecycle");-const { registerMeetingAutoEndKeepHandler } = require("./meetingAutoEndKeep");+const { registerMeetingAutoEndLifecycleHandlers } = require("./meetingAutoEndLifecycle");const liveSpeakerIdentifier = require("./liveSpeakerIdentifier");const { supportsLiveSpeakerIdentification } = require("./liveSpeakerIdPolicy");const MeetingEchoLeakDetector = require("./meetingEchoLeakDetector");@@ -10577,7 +10577,7 @@ class IPCHandlers {}});- registerMeetingAutoEndKeepHandler(ipcMain, () => this.meetingDetectionEngine);+ registerMeetingAutoEndLifecycleHandlers(ipcMain, () => this.meetingDetectionEngine);ipcMain.handle("join-calendar-meeting", async (_event, eventId) => {try {diff --git a/src/helpers/meetingAudioActivityMonitor.js b/src/helpers/meetingAudioActivityMonitor.jsindex 6441a5aa9..e0e6ed7b2 100644--- a/src/helpers/meetingAudioActivityMonitor.js+++ b/src/helpers/meetingAudioActivityMonitor.js@@ -4,11 +4,11 @@ const {MEETING_SYSTEM_ACTIVITY_RMS,} = require("../utils/audioUtils");-// How long a channel stays "active" after its last audible chunk. The system-// tail is longer so gaps between a remote speaker's sentences don't read as-// silence.+// How long a channel stays "active" after its last audible chunk. Both tails sit+// in front of the auto-end dwell, so they are kept short; the system tail only+// has to bridge the pause between a remote speaker's words, not their sentences.const MIC_ACTIVITY_TAIL_MS = 2_000;-const SYSTEM_ACTIVITY_TAIL_MS = 3_000;+const SYSTEM_ACTIVITY_TAIL_MS = 1_000;const CHANNELS = {mic: { threshold: MEETING_MIC_ACTIVITY_RMS, tailMs: MIC_ACTIVITY_TAIL_MS },diff --git a/src/helpers/meetingAutoEndController.js b/src/helpers/meetingAutoEndController.jsindex d40fc7304..6db2012f8 100644--- a/src/helpers/meetingAutoEndController.js+++ b/src/helpers/meetingAutoEndController.js@@ -1,95 +1,92 @@-const COUNTDOWN_MS = 60_000;-// Fallback mode: both channels must stay quiet this long before prompting.+// Fallback mode: both channels must stay quiet this long before stopping.const SILENCE_WINDOW_MS = 60_000;// Fallback mode after the tracked meeting app exits — a much stronger signal.const FAST_SILENCE_MS = 10_000;-// After "Keep recording": no re-prompt sooner than this, even on fresh evidence.-const KEEP_COOLDOWN_MS = 5 * 60_000;+// A mic release must stay uncontradicted this long before it stops a recording.+// The OS reports a release for things that are not the call ending: a device+// flap emits MIC_STOP and MIC_START in one reconcile pass, an app rebuilds its+// input unit when screen share starts, and an app that drops the mic on mute+// looks identical to one that left the call. Without a dwell time each of those+// ends a live recording, and the stop is irreversible. A flap has no gap at all,+// so a few seconds absorbs it while keeping the stop prompt.+const OWNERSHIP_CONFIRM_MS = 5_000;// An external mic hold shorter than this (Siri, a permission prompt, the Sound// settings input meter) is incidental — it must not arm the mic-ignoring// ownership path on what is really an in-person recording.const OWNERSHIP_MIN_ACTIVE_MS = 30_000;// A tick gap longer than this means the machine slept; silence accumulated-// before the gap is stale and must not fire a stop.+// before the gap is stale and must not stop the recording on wake.const TICK_GAP_MS = 5_000;// Two evidence sources decide "the meeting is over"://-// ownership — an external app held the mic and released it. The countdown-// runs only while the SYSTEM channel is also quiet (remote voices still-// playing means the call is live, e.g. an app that releases the mic on-// mute). The mic channel is deliberately ignored here so room noise,-// typing, or talking to a colleague after the call can't mask the end.+// ownership — an external app held the mic and released it. Stop only once the+// release has held for OWNERSHIP_CONFIRM_MS with the SYSTEM channel also+// quiet throughout (remote voices still playing means the call is live, e.g.+// an app that releases the mic on mute). The mic channel is deliberately+// ignored here so room noise after the call cannot mask the end.// fallback — ownership is unreliable, or no external app ever held the mic-// this session (in-person meetings). Both channels quiet for the silence-// window prompts; a tracked meeting app exiting shortens the window.+// this session. Both channels quiet for the silence window stops; a tracked+// meeting app exiting shortens the window.//// Tick-driven and timer-free: every input updates state and re-evaluates; the-// owner calls tick() about once a second. That keeps sleep handling correct — a-// timer due before sleep would fire on wake and stop the recording before any-// gap check could run.-const createMeetingAutoEndController = ({- now = Date.now,- onCountdown,- onCountdownCanceled = () => {},- onCountdownExpired = () => {},- onStop,-}) => {+// owner calls tick() about once a second. This keeps sleep handling correct.+const createMeetingAutoEndController = ({ now = Date.now, onStop }) => {let session = null;let lastSeenAt = null;const isLive = (sessionId) =>session !== null && session.sessionId === sessionId && session.eligible && !session.stopped;- const cancelCountdown = () => {- if (!session?.countdown) return;- session.countdown = null;- onCountdownCanceled(session.sessionId);- };-- // Every entry point observes the clock first, not just tick(): after sleep,- // the owner's monitor tick can deliver an activity change before the- // controller's own tick runs, and that path must not fire a stale countdown.const observeClock = () => {const nowMs = now();const gap = lastSeenAt === null ? 0 : nowMs - lastSeenAt;lastSeenAt = nowMs;if (gap > TICK_GAP_MS && session) {- // Slept through the gap: whatever silence accumulated is stale, and a- // countdown that was running must not fire on wake.session.quietSince = nowMs;session.fastArmAt = null;- cancelCountdown();+ session.ownershipQuietSince = null;+ if (session.externalMicActive) {+ // Ownership observed before sleep is stale. Count it again from wake so+ // a release delivered with the first resumed poll cannot stop at once.+ session.externalMicActiveSince = nowMs;+ } else {+ session.mode = "fallback";+ session.externalMicActiveSince = null;+ }}return nowMs;};- const startCountdown = (reason) => {- const expiresAt = now() + COUNTDOWN_MS;- session.countdown = { expiresAt, reason };- onCountdown({ sessionId: session.sessionId, expiresAt, reason });+ const stop = (reason) => {+ const { sessionId } = session;+ session.stopped = true;+ onStop(sessionId, reason);};const evaluate = () => {if (!session || !session.eligible || session.stopped) return;const nowMs = now();- if (session.countdown) {- if (nowMs >= session.countdown.expiresAt) {- const { reason } = session.countdown;- const { sessionId } = session;- session.countdown = null;- session.stopped = true;- onCountdownExpired(sessionId);- onStop(sessionId, reason);- }+ // A session the user explicitly restarted carries a grace period: they have+ // just told us the meeting is still live, so hold every stop path and keep+ // the quiet clocks reset, so the grace expiring cannot stop instantly.+ if (nowMs < session.suppressUntil) {+ session.quietSince = nowMs;+ session.fastArmAt = null;+ session.ownershipQuietSince = null;return;}- if (session.episodeConsumed || nowMs < session.keptUntil) return;-if (session.mode === "ownership") {- if (!session.externalMicActive && !session.systemActive) startCountdown("mic-released");+ // Any contradicting evidence — the mic coming back, or remote audio+ // resuming — restarts the window rather than merely deferring the stop.+ if (session.externalMicActive || session.systemActive) {+ session.ownershipQuietSince = null;+ return;+ }+ if (session.ownershipQuietSince === null) session.ownershipQuietSince = nowMs;+ if (nowMs - session.ownershipQuietSince >= OWNERSHIP_CONFIRM_MS) stop("mic-released");return;}@@ -98,8 +95,8 @@ const createMeetingAutoEndController = ({const quietStart = fastArmed? Math.max(session.quietSince, session.fastArmAt): session.quietSince;- const window = fastArmed ? FAST_SILENCE_MS : SILENCE_WINDOW_MS;- if (nowMs - quietStart >= window) startCountdown(fastArmed ? "process-exit" : "silence");+ const windowMs = fastArmed ? FAST_SILENCE_MS : SILENCE_WINDOW_MS;+ if (nowMs - quietStart >= windowMs) stop(fastArmed ? "process-exit" : "silence");};const beginSession = ({@@ -109,16 +106,14 @@ const createMeetingAutoEndController = ({externalMicActive,micActive = false,systemActive = false,+ suppressUntil = 0,}) => {- cancelCountdown();const nowMs = now();lastSeenAt = nowMs;const ownership = eligible && reliable && externalMicActive;session = {sessionId,eligible: eligible === true,- // Explicit state, never derived: a reliable-but-inactive report after a- // reliability loss must not jump back into ownership mode.mode: ownership ? "ownership" : "fallback",externalMicActive: ownership,externalMicActiveSince: ownership ? nowMs : null,@@ -126,9 +121,8 @@ const createMeetingAutoEndController = ({systemActive,quietSince: nowMs,fastArmAt: null,- keptUntil: 0,- episodeConsumed: false,- countdown: null,+ ownershipQuietSince: null,+ suppressUntil,stopped: false,};evaluate();@@ -139,22 +133,19 @@ const createMeetingAutoEndController = ({if (!isLive(sessionId)) return;if (!reliable) {- cancelCountdown();session.mode = "fallback";session.externalMicActive = false;session.externalMicActiveSince = null;session.quietSince = nowMs;+ session.fastArmAt = null;evaluate();return;}if (externalMicActive) {- cancelCountdown();if (!session.externalMicActive) session.externalMicActiveSince = nowMs;session.externalMicActive = true;session.mode = "ownership";- // A new call is fresh evidence: reopen the episode after a Keep.- session.episodeConsumed = false;session.fastArmAt = null;evaluate();return;@@ -167,12 +158,6 @@ const createMeetingAutoEndController = ({if (heldMs < OWNERSHIP_MIN_ACTIVE_MS) {session.mode = "fallback";session.quietSince = nowMs;- } else {- // A call that was genuinely rejoined and left again is unambiguous- // evidence; making it wait out the keep cooldown reads as the feature- // silently failing. The cooldown exists for silence-based nags, which- // still honor it.- session.keptUntil = 0;}}evaluate();@@ -187,14 +172,7 @@ const createMeetingAutoEndController = ({session.micActive = micActive;session.systemActive = systemActive;- if (session.mode === "ownership") {- // Only remote audio says the call is live; the mic channel is ignored.- if (systemBecameActive) cancelCountdown();- } else if (micBecameActive || systemBecameActive) {- cancelCountdown();- // Someone spoke — fresh evidence reopens the episode; a process exit- // no longer describes the current situation.- session.episodeConsumed = false;+ if (session.mode === "fallback" && (micBecameActive || systemBecameActive)) {session.fastArmAt = null;}if (!wasQuiet && !micActive && !systemActive) session.quietSince = nowMs;@@ -203,42 +181,13 @@ const createMeetingAutoEndController = ({const handleMeetingProcessExit = ({ sessionId }) => {const nowMs = observeClock();- if (!isLive(sessionId)) return;- if (session.mode !== "fallback" || session.countdown) return;+ if (!isLive(sessionId) || session.mode !== "fallback") return;session.fastArmAt = nowMs;- // The app quitting is fresh evidence, so a kept session can prompt again —- // but never sooner than the keep cooldown.- session.episodeConsumed = false;evaluate();};- const handleCountdownUnavailable = (sessionId) => {- observeClock();- if (!isLive(sessionId) || !session.countdown) return false;- cancelCountdown();- // Do not retry the same episode when the user had no chance to keep it.- session.episodeConsumed = true;- return true;- };-- // Returns false once the countdown has fired: the stop is already in flight,- // so reporting success would tell the user their recording was kept.- // Keep is per episode: prompts resume only on fresh evidence. Renewed audio- // or a process exit (fallback) also wait out the cooldown; a call rejoined- // for at least OWNERSHIP_MIN_ACTIVE_MS and left again re-prompts at once. In- // ownership mode with no further call the session is never prompted again.- const keepRecording = (sessionId) => {- const nowMs = observeClock();- if (!session || session.sessionId !== sessionId || session.stopped) return false;- cancelCountdown();- session.episodeConsumed = true;- session.keptUntil = nowMs + KEEP_COOLDOWN_MS;- return true;- };-const endSession = (sessionId) => {if (!session || session.sessionId !== sessionId) return;- cancelCountdown();session = null;};@@ -252,17 +201,14 @@ const createMeetingAutoEndController = ({handleExternalMicState,handleAudioActivity,handleMeetingProcessExit,- handleCountdownUnavailable,- keepRecording,endSession,tick,};};module.exports = createMeetingAutoEndController;-module.exports.COUNTDOWN_MS = COUNTDOWN_MS;module.exports.SILENCE_WINDOW_MS = SILENCE_WINDOW_MS;module.exports.FAST_SILENCE_MS = FAST_SILENCE_MS;-module.exports.KEEP_COOLDOWN_MS = KEEP_COOLDOWN_MS;module.exports.OWNERSHIP_MIN_ACTIVE_MS = OWNERSHIP_MIN_ACTIVE_MS;+module.exports.OWNERSHIP_CONFIRM_MS = OWNERSHIP_CONFIRM_MS;module.exports.TICK_GAP_MS = TICK_GAP_MS;diff --git a/src/helpers/meetingAutoEndKeep.js b/src/helpers/meetingAutoEndKeep.jsdeleted file mode 100644index af67c884f..000000000--- a/src/helpers/meetingAutoEndKeep.js+++ /dev/null@@ -1,21 +0,0 @@-function keepMeetingRecordingSession(engine, sessionId) {- if (typeof sessionId !== "string" || sessionId.trim().length === 0) {- return { success: false, reason: "invalid-session" };- }- if (engine?.keepRecordingSession(sessionId) !== true) {- return { success: false, reason: "stale-session" };- }- return { success: true };-}--function registerMeetingAutoEndKeepHandler(ipcMain, getMeetingDetectionEngine) {- ipcMain.handle("meeting-auto-end-keep", async (_event, sessionId) => {- try {- return keepMeetingRecordingSession(getMeetingDetectionEngine(), sessionId);- } catch (error) {- return { success: false, error: error.message };- }- });-}--module.exports = { keepMeetingRecordingSession, registerMeetingAutoEndKeepHandler };diff --git a/src/helpers/meetingAutoEndLifecycle.js b/src/helpers/meetingAutoEndLifecycle.jsnew file mode 100644index 000000000..ee220f86c--- /dev/null+++ b/src/helpers/meetingAutoEndLifecycle.js@@ -0,0 +1,62 @@+const isValidSessionId = (sessionId) =>+ typeof sessionId === "string" && sessionId.trim().length > 0;++async function completeMeetingAutoEndSession(engine, sessionId, sender) {+ if (!isValidSessionId(sessionId)) {+ return { success: false, reason: "invalid-session" };+ }+ if ((await engine?.completeAutoEndSession(sessionId, sender)) !== true) {+ return { success: false, reason: "stale-session" };+ }+ return { success: true };+}++function respondToMeetingAutoEndNotification(engine, sessionId, action, sender) {+ if (!isValidSessionId(sessionId)) {+ return { success: false, reason: "invalid-session" };+ }+ if (action !== "restart" && action !== "dismiss") {+ return { success: false, reason: "invalid-action" };+ }+ if (engine?.respondToAutoEndNotification(sessionId, action, sender) !== true) {+ return { success: false, reason: "stale-session" };+ }+ return { success: true };+}++function getErrorMessage(error) {+ return error instanceof Error ? error.message : String(error);+}++function registerMeetingAutoEndLifecycleHandlers(ipcMain, getMeetingDetectionEngine) {+ ipcMain.handle("meeting-auto-end-completed", async (event, sessionId) => {+ try {+ return await completeMeetingAutoEndSession(+ getMeetingDetectionEngine(),+ sessionId,+ event.sender+ );+ } catch (error) {+ return { success: false, error: getErrorMessage(error) };+ }+ });++ ipcMain.handle("meeting-auto-end-respond", async (event, sessionId, action) => {+ try {+ return respondToMeetingAutoEndNotification(+ getMeetingDetectionEngine(),+ sessionId,+ action,+ event.sender+ );+ } catch (error) {+ return { success: false, error: getErrorMessage(error) };+ }+ });+}++module.exports = {+ completeMeetingAutoEndSession,+ respondToMeetingAutoEndNotification,+ registerMeetingAutoEndLifecycleHandlers,+};diff --git a/src/helpers/meetingDetectionEngine.js b/src/helpers/meetingDetectionEngine.jsindex 6540201b6..479ce7318 100644--- a/src/helpers/meetingDetectionEngine.js+++ b/src/helpers/meetingDetectionEngine.js@@ -7,6 +7,16 @@ const { broadcastToWindows } = require("./windowBroadcast");const IMMINENT_THRESHOLD_MS = 5 * 60 * 1000;const AUTO_END_TICK_MS = 1000;+const AUTO_END_RESTART_WINDOW_MS = 30_000;+// Clicking Restart is the user saying the meeting is still live. Honour that for+// a while, or the same silence that just ended the recording ends it again a+// minute later and they have to keep clicking.+const AUTO_END_RESTART_GRACE_MS = 5 * 60_000;+// The grace belongs to the recording the user restarted, which starts within a+// second or two. Main cannot see a restart the renderer drops (its context died+// with a reload, or a manual recording won the race), so an unclaimed grace has+// to lapse rather than wait to be taken by whatever recording starts next.+const AUTO_END_RESTART_CLAIM_MS = 30_000;const PLACEHOLDER_PREFIX = { __detected__: "detected", __manual__: "manual" };@@ -54,6 +64,8 @@ class MeetingDetectionEngine {this._notificationQueue = [];this._postRecordingCooldown = null;this._recordingSession = null;+ this._pendingAutoEnd = null;+ this._autoEndRestartGrace = null;this._now = now;this._setInterval = setInterval;this._clearInterval = clearInterval;@@ -71,26 +83,6 @@ class MeetingDetectionEngine {});this._autoEndController = createAutoEndController({now,- onCountdown: (countdown) => {- debugLogger.info("Meeting auto-end countdown started", countdown, "meeting");- Promise.resolve(this.windowManager.showMeetingAutoEndCountdown?.(countdown)).catch(- (error) => {- debugLogger.error(- "Failed to show meeting auto-end countdown",- { error: error?.message },- "meeting"- );- this.handleAutoEndNotificationUnavailable(countdown.sessionId);- }- );- },- onCountdownCanceled: (sessionId) => {- debugLogger.info("Meeting auto-end countdown canceled", { sessionId }, "meeting");- this.windowManager.dismissMeetingAutoEndCountdown?.(sessionId);- },- onCountdownExpired: (sessionId) => {- this.windowManager.dismissMeetingAutoEndCountdown?.(sessionId);- },onStop: (sessionId, reason) => this._requestRecordingStop(sessionId, reason),});this._bindListeners();@@ -150,15 +142,23 @@ class MeetingDetectionEngine {if (!session || session.sessionId !== sessionId) return;debugLogger.info(- "Meeting auto-end countdown expired, requesting stop",+ "Meeting end detected, requesting automatic stop",{ sessionId, reason },"meeting");const ownerWebContents = session.ownerWebContents;if (!ownerWebContents || ownerWebContents.isDestroyed?.()) return;+ this._clearAutoEndRecovery();+ this._pendingAutoEnd = {+ sessionId,+ reason,+ ownerWebContents,+ expiresAt: null,+ };try {ownerWebContents.send("meeting-auto-end-requested", { sessionId, reason });} catch (error) {+ this._pendingAutoEnd = null;debugLogger.error("Failed to request meeting auto-end from recording renderer",{ error: error?.message, sessionId },@@ -167,6 +167,132 @@ class MeetingDetectionEngine {}}+ // Time-bounded on purpose: the window manager destroys a notification window+ // on paths that cannot notify us (_hideNormalAppSurfaces, a late detection+ // response landing on a replaced card), and this gate holds every meeting+ // prompt. Without the deadline one of those silently kills detection for the+ // rest of the app session.+ _hasLiveAutoEndOffer() {+ const expiresAt = this._pendingAutoEnd?.expiresAt;+ return expiresAt != null && this._now() < expiresAt;+ }++ _clearAutoEndRecovery({ dismiss = true } = {}) {+ const pending = this._pendingAutoEnd;+ this._pendingAutoEnd = null;+ if (dismiss && pending?.expiresAt != null) {+ this.windowManager.dismissMeetingAutoEndNotification?.(pending.sessionId);+ }+ }++ async completeAutoEndSession(sessionId, ownerWebContents) {+ const pending = this._pendingAutoEnd;+ if (+ !pending ||+ pending.sessionId !== sessionId ||+ pending.ownerWebContents !== ownerWebContents ||+ pending.expiresAt !== null ||+ this._recordingSession !== null ||+ ownerWebContents?.isDestroyed?.()+ ) {+ return false;+ }++ const expiresAt = this._now() + AUTO_END_RESTART_WINDOW_MS;+ pending.expiresAt = expiresAt;+ try {+ const shown = await this.windowManager.showMeetingAutoEndNotification?.({+ sessionId,+ reason: pending.reason,+ expiresAt,+ });+ if (this._pendingAutoEnd !== pending) return false;+ // Only an explicit success offers the restart: anything else (a missing+ // window manager method, a load aborted by a replacement) means the card+ // the user would click never appeared.+ if (shown !== true) {+ this._clearAutoEndRecovery({ dismiss: false });+ return false;+ }+ debugLogger.info(+ "Meeting recording auto-ended; restart window shown",+ { sessionId, reason: pending.reason, expiresAt },+ "meeting"+ );+ return true;+ } catch (error) {+ if (this._pendingAutoEnd === pending) {+ this._clearAutoEndRecovery({ dismiss: false });+ }+ debugLogger.error(+ "Failed to show meeting auto-end recovery notification",+ { error: error?.message, sessionId },+ "meeting"+ );+ return false;+ }+ }++ respondToAutoEndNotification(sessionId, action, responderWebContents) {+ if (+ (action !== "restart" && action !== "dismiss") ||+ !this.windowManager.isMeetingNotificationSender?.(responderWebContents)+ ) {+ return false;+ }++ const pending = this._pendingAutoEnd;+ if (!pending || pending.sessionId !== sessionId || pending.expiresAt === null) return false;+ if (this._now() >= pending.expiresAt || this._recordingSession !== null) {+ this._clearAutoEndRecovery();+ this._flushNotificationQueue();+ return false;+ }++ const ownerWebContents = pending.ownerWebContents;+ this._clearAutoEndRecovery();+ if (action === "dismiss") {+ this._flushNotificationQueue();+ return true;+ }++ // A delivered restart deliberately does not flush: the user chose the old+ // meeting, and the recording about to start gates the queue again anyway.+ // One that cannot be delivered starts nothing, so the detections held+ // behind the offer have to go out.+ if (!ownerWebContents || ownerWebContents.isDestroyed?.()) {+ this._flushNotificationQueue();+ return false;+ }++ try {+ ownerWebContents.send("meeting-auto-end-restart-requested", { sessionId });+ const nowMs = this._now();+ this._autoEndRestartGrace = {+ suppressUntil: nowMs + AUTO_END_RESTART_GRACE_MS,+ claimUntil: nowMs + AUTO_END_RESTART_CLAIM_MS,+ };+ return true;+ } catch (error) {+ debugLogger.error(+ "Failed to request meeting recording restart",+ { error: error?.message, sessionId },+ "meeting"+ );+ this._flushNotificationQueue();+ return false;+ }+ }++ // `flushQueued` is false when a replacement notification is already being+ // shown: flushing there would re-enter showMeetingNotification.+ handleAutoEndNotificationClosed(sessionId, { flushQueued = true } = {}) {+ if (this._pendingAutoEnd?.sessionId !== sessionId) return false;+ this._clearAutoEndRecovery({ dismiss: false });+ if (flushQueued) this._flushNotificationQueue();+ return true;+ }+// Hot path — called for every meeting PCM chunk of both channels.recordMeetingAudioChunk(source, buffer) {if (!this._autoEndActive) return;@@ -237,11 +363,15 @@ class MeetingDetectionEngine {"meeting");this._audioActivityMonitor.reset();+ const grace = this._autoEndRestartGrace;+ this._autoEndRestartGrace = null;+ const suppressUntil = grace && this._now() < grace.claimUntil ? grace.suppressUntil : 0;this._autoEndController.beginSession({sessionId,eligible: true,reliable: externalMicState.reliable,externalMicActive: externalMicState.externalMicActive,+ suppressUntil,...this._audioActivityMonitor.getState(),});this._autoEndActive = true;@@ -254,6 +384,7 @@ class MeetingDetectionEngine {ownerWebContents,systemAudioAvailable = false,}) {+ this._clearAutoEndRecovery();if (this._recordingSession) this._deactivateAutoEnd();this._recordingSession = {@@ -329,31 +460,6 @@ class MeetingDetectionEngine {return true;}- keepRecordingSession(sessionId) {- const session = this._recordingSession;- if (!this._autoEndActive || !session || session.sessionId !== sessionId) return false;-- const kept = this._autoEndController.keepRecording(sessionId) === true;- debugLogger.info(- kept ? "Auto-end paused — user kept recording" : "Keep request lost to expired countdown",- { sessionId },- "meeting"- );- return kept;- }-- handleAutoEndNotificationUnavailable(sessionId) {- const suppressed = this._autoEndController.handleCountdownUnavailable(sessionId) === true;- if (suppressed) {- debugLogger.warn(- "Meeting auto-end suppressed because its countdown was unavailable",- { sessionId },- "meeting"- );- }- return suppressed;- }-// Calendar reminders enter the same pipeline as mic detections, so they share// the recording gates, queueing, cooldowns, and the overlay window.handleCalendarReminder(event) {@@ -393,9 +499,14 @@ class MeetingDetectionEngine {// _userRecording is shared with dictation, so a dictation ending mid-meeting// clears it while the recording is still live; the tracked session is the- // gate that cannot be reset from outside. A prompt shown then would replace- // a visible auto-end countdown card and let the countdown run on unseen.- if (this._userRecording || this._postRecordingCooldown || this._recordingSession) {+ // gate that cannot be reset from outside. A prompt shown then could replace+ // the recording UI while the tracked recording is still active.+ if (+ this._userRecording ||+ this._postRecordingCooldown ||+ this._recordingSession ||+ this._hasLiveAutoEndOffer()+ ) {debugLogger.info("Detection queued — user is recording", { detectionId, source }, "meeting");this._notificationQueue.push({ source, key, data });this.activeDetections.set(detectionId, { source, key, data });@@ -657,7 +768,12 @@ class MeetingDetectionEngine {});}- handleNotificationTimeout() {+ handleNotificationTimeout(notification = null) {+ if (notification?.kind === "auto-end") {+ this.handleAutoEndNotificationClosed(notification.sessionId);+ return;+ }+// Expiring unanswered is not a decline, so no dismissal cooldown starts:// the detector's hasPrompted flag already keeps the ongoing call from// re-prompting, while a call starting right after the timeout still@@ -686,6 +802,14 @@ class MeetingDetectionEngine {return;}+ // The post-recording cooldown fires 2.5s after an auto-end stop, while the+ // restart card still has most of its window left. Showing a prompt here+ // would replace that card and silently void the restart offer.+ if (this._hasLiveAutoEndOffer()) {+ debugLogger.info("Holding queued notifications — restart offer live", {}, "meeting");+ return;+ }+debugLogger.info("Flushing notification queue",{ count: this._notificationQueue.length },@@ -765,6 +889,8 @@ class MeetingDetectionEngine {stop() {debugLogger.info("Meeting detection engine stopped", {}, "meeting");+ this._clearAutoEndRecovery();+ this._autoEndRestartGrace = null;this._deactivateAutoEnd();this._recordingSession = null;this.meetingProcessDetector.stop();@@ -780,3 +906,6 @@ class MeetingDetectionEngine {}module.exports = MeetingDetectionEngine;+module.exports.AUTO_END_RESTART_WINDOW_MS = AUTO_END_RESTART_WINDOW_MS;+module.exports.AUTO_END_RESTART_GRACE_MS = AUTO_END_RESTART_GRACE_MS;+module.exports.AUTO_END_RESTART_CLAIM_MS = AUTO_END_RESTART_CLAIM_MS;diff --git a/src/helpers/meetingRecordingSession.ts b/src/helpers/meetingRecordingSession.tsindex 90f0ccbea..58c60095a 100644--- a/src/helpers/meetingRecordingSession.ts+++ b/src/helpers/meetingRecordingSession.ts@@ -1,4 +1,5 @@-import type { NoteItem } from "../types/electron";+import type { StartRecordingArgs, TranscriptSegment } from "../stores/meetingRecordingStore";+import type { MeetingAutoEndRestartRequest, NoteItem } from "../types/electron";export function createMeetingRecordingSessionId(randomUUID: () => string = () => crypto.randomUUID()@@ -15,18 +16,130 @@ export function canStopMeetingRecordingSession(export function requestMeetingRecordingAutoEnd(payload: { sessionId?: unknown } | null | undefined,- stopRecording: (sessionId: string) => unknown,+ stopRecording: (sessionId: string) => Promise<{ stopped: boolean }> | { stopped: boolean },+ // Always called once the stop settles. `stopped` is false when the recording+ // ended without a persisted result — the caller still has to tell the user,+ // because no restart card will be offered for it.+ onStopSettled: (sessionId: string, stopped: boolean) => Promise<unknown> | unknown,onError: (error: unknown, sessionId: string) => void): boolean {const sessionId = payload?.sessionId;if (typeof sessionId !== "string" || sessionId.trim().length === 0) return false;- // A rejected stop means the recording is still running while main already- // considers the countdown expired — surface it instead of swallowing it.- void Promise.resolve(stopRecording(sessionId)).catch((error) => onError(error, sessionId));+ void Promise.resolve(stopRecording(sessionId))+ .then((result) => onStopSettled(sessionId, result.stopped))+ .catch((error) => onError(error, sessionId));return true;}+interface MeetingAutoEndRestartState {+ recordingNoteId: number | null;+ recordingNoteTitle: string | null;+ recordingFolderId: number | null;+ sessionDiarizationEnabled: boolean;+ sessionExpectedCount: number;+ userTouchedStepper: boolean;+ segments: TranscriptSegment[];+}++export interface MeetingAutoEndRestartContext {+ sessionId: string;+ args: StartRecordingArgs;+}++export function createMeetingAutoEndRestartContext(+ sessionId: string,+ activeSessionId: string | null,+ state: MeetingAutoEndRestartState+): MeetingAutoEndRestartContext | null {+ if (activeSessionId !== sessionId) return null;++ return {+ sessionId,+ args: {+ noteId: state.recordingNoteId,+ noteTitle: state.recordingNoteTitle,+ folderId: state.recordingFolderId,+ seedSegments: state.segments,+ diarizationEnabled: state.sessionDiarizationEnabled,+ expectedCount: state.sessionExpectedCount,+ expectedCountIsExplicit: state.userTouchedStepper,+ autoEndEligible: true,+ },+ };+}++type MeetingAutoEndRestartNote = Pick<NoteItem, "transcript" | "deleted_at">;++export type MeetingAutoEndRestartSeed =+ { ok: true; seedSegments: TranscriptSegment[] } | { ok: false; reason: "note-missing" };++// The live segments the renderer holds are the pre-diarization copy: background+// speaker identification writes its enrichment to the note, never back into the+// store. Reseeding from the store would overwrite those labels at the next stop,+// so the note is the source of truth — and reading it is also what catches a+// note deleted during the restart window, which must not be resurrected.+export function resolveMeetingAutoEndRestartSeed(+ noteId: number | null,+ note: MeetingAutoEndRestartNote | null | undefined,+ parseSegments: (transcript: string) => TranscriptSegment[],+ liveSegments: TranscriptSegment[]+): MeetingAutoEndRestartSeed {+ if (noteId == null) return { ok: true, seedSegments: liveSegments };+ if (!note || note.deleted_at) return { ok: false, reason: "note-missing" };+ return { ok: true, seedSegments: note.transcript ? parseSegments(note.transcript) : [] };+}++export interface MeetingAutoEndRestartDeps {+ getActiveSessionId: () => string | null;+ getLatestSegments: () => TranscriptSegment[];+ getNote: (noteId: number) => Promise<MeetingAutoEndRestartNote | null | undefined>;+ parseSegments: (transcript: string) => TranscriptSegment[];+ startRecording: (args: StartRecordingArgs) => Promise<boolean>;+}++export type MeetingAutoEndRestartOutcome =+ | { status: "started" }+ | {+ status: "aborted";+ reason: "no-context" | "already-recording" | "note-missing" | "start-refused";+ };++// Every abort is named rather than swallowed: main closes the card and reports+// success the moment it hands the restart to this renderer, so a drop here is+// invisible to the user unless the caller tells them.+export async function runMeetingAutoEndRestart(+ request: MeetingAutoEndRestartRequest,+ context: MeetingAutoEndRestartContext | null,+ deps: MeetingAutoEndRestartDeps+): Promise<MeetingAutoEndRestartOutcome> {+ if (!context || context.sessionId !== request.sessionId) {+ return { status: "aborted", reason: "no-context" };+ }+ if (deps.getActiveSessionId() !== null) {+ return { status: "aborted", reason: "already-recording" };+ }++ const args: StartRecordingArgs = { ...context.args, seedSegments: deps.getLatestSegments() };+ const note = args.noteId == null ? null : await deps.getNote(args.noteId);+ const seed = resolveMeetingAutoEndRestartSeed(+ args.noteId,+ note,+ deps.parseSegments,+ args.seedSegments ?? []+ );+ if (!seed.ok) return { status: "aborted", reason: "note-missing" };++ // Re-checked after the note read: a manual recording can win the race across+ // that await, and starting here would adopt the auto-ended note under it.+ if (deps.getActiveSessionId() !== null) {+ return { status: "aborted", reason: "already-recording" };+ }++ const started = await deps.startRecording({ ...args, seedSegments: seed.seedSegments });+ return started ? { status: "started" } : { status: "aborted", reason: "start-refused" };+}+export function isMeetingAutoEndEligible(note: Pick<NoteItem, "note_type"> | null | undefined): boolean {diff --git a/src/helpers/windowConfig.js b/src/helpers/windowConfig.jsindex 051e2bc02..0cfa5bbb8 100644--- a/src/helpers/windowConfig.js+++ b/src/helpers/windowConfig.js@@ -273,8 +273,8 @@ const NOTIFICATION_WINDOW_CONFIG = {};const AUTO_END_NOTIFICATION_WINDOW_SIZE = {- width: 620,- height: 116,+ width: 480,+ height: 128,};function getMeetingNotificationWindowSize(promptData) {diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.jsindex df3b423c4..da9b6a70c 100644--- a/src/helpers/windowManager.js+++ b/src/helpers/windowManager.js@@ -68,10 +68,14 @@ class WindowManager {this._agentDictationPillScreenListener = null;this._notificationLoadTimeout = null;this._notificationDismissTimer = new NotificationDismissTimer(() => {+ const notification = this._pendingNotificationData;+ // Dismiss first: an expiring restart offer lets the engine flush the+ // detections it was holding, and a prompt raised from that handler must+ // not be closed by this dismissal.+ this.dismissMeetingNotification();if (this.meetingDetectionEngine) {- this.meetingDetectionEngine.handleNotificationTimeout();+ this.meetingDetectionEngine.handleNotificationTimeout(notification);}- this.dismissMeetingNotification();});this.updateNotificationWindow = null;this._pendingUpdateNotificationData = null;@@ -243,14 +247,13 @@ class WindowManager {// begin with, so on Linux leave the hit-testing alone and move the// countdown alone.const togglesClickThrough = process.platform !== "linux";- // Hovering means the user is reading or about to click — the auto-dismiss- // countdown must not close the card under their pointer.+ const hasFixedExpiry = this._pendingNotificationData?.kind === "auto-end";if (interactive) {if (togglesClickThrough) win.setIgnoreMouseEvents(false);- this._notificationDismissTimer.pause();+ if (!hasFixedExpiry) this._notificationDismissTimer.pause();} else {if (togglesClickThrough) win.setIgnoreMouseEvents(true, { forward: true });- this._notificationDismissTimer.resume();+ if (!hasFixedExpiry) this._notificationDismissTimer.resume();}}@@ -1918,13 +1921,22 @@ class WindowManager {}}- async showMeetingNotification(promptData, { autoDismiss = true } = {}) {+ async showMeetingNotification(promptData, { autoDismiss = true, autoDismissAt = null } = {}) {if (this._onboardingActive) return false;if (this.notificationWindow && !this.notificationWindow.isDestroyed()) {const previousWindow = this.notificationWindow;+ const replacedAutoEndSessionId =+ this._pendingNotificationData?.kind === "auto-end"+ ? this._pendingNotificationData.sessionId+ : null;this.notificationWindow = null;this._pendingNotificationData = null;previousWindow.close();+ if (replacedAutoEndSessionId) {+ this.meetingDetectionEngine?.handleAutoEndNotificationClosed?.(replacedAutoEndSessionId, {+ flushQueued: false,+ });+ }}this._notificationDismissTimer.cancel();if (this._notificationLoadTimeout) {@@ -1951,7 +1963,7 @@ class WindowManager {// after the replacement already took over the reference and the countdown.win.on("closed", () => {if (this.notificationWindow !== win) return;- const unavailableAutoEndSessionId =+ const closedAutoEndSessionId =this._pendingNotificationData?.kind === "auto-end"? this._pendingNotificationData.sessionId: null;@@ -1966,10 +1978,8 @@ class WindowManager {clearTimeout(this._notificationReadyFallback);this._notificationReadyFallback = null;}- if (unavailableAutoEndSessionId) {- this.meetingDetectionEngine?.handleAutoEndNotificationUnavailable?.(- unavailableAutoEndSessionId- );+ if (closedAutoEndSessionId) {+ this.meetingDetectionEngine?.handleAutoEndNotificationClosed?.(closedAutoEndSessionId);}});@@ -2017,8 +2027,9 @@ class WindowManager {await loadPromise;}} catch (error) {- // A load aborted by our own replacement or dismissal is not a failure.- if (this.notificationWindow !== win) return;+ // A load aborted by our own replacement or dismissal is not a failure —+ // but the caller must still learn the notification never appeared.+ if (this.notificationWindow !== win) return false;this.dismissMeetingNotification();throw error;} finally {@@ -2027,7 +2038,7 @@ class WindowManager {this._notificationLoadTimeout = null;}}- if (this.notificationWindow !== win) return;+ if (this.notificationWindow !== win) return false;if (this._onboardingActive) {this.dismissMeetingNotification();return false;@@ -2043,11 +2054,14 @@ class WindowManager {}, 3000);this._notificationReadyFallback = readyFallback;- // The auto-end countdown is owned by its controller — it stays until kept,- // canceled by fresh activity, or expired — so it never auto-dismisses.if (autoDismiss) {- this._notificationDismissTimer.start(getNotificationTimeoutMs(promptData.source));+ this._notificationDismissTimer.start(+ autoDismissAt === null+ ? getNotificationTimeoutMs(promptData.source)+ : Math.max(0, autoDismissAt - Date.now())+ );}+ return true;}// Only the window that loaded the prompt may reveal it: a stale window's late@@ -2085,14 +2099,14 @@ class WindowManager {if (win && !win.isDestroyed()) win.close();}- showMeetingAutoEndCountdown({ sessionId, expiresAt, reason }) {+ showMeetingAutoEndNotification({ sessionId, expiresAt, reason }) {return this.showMeetingNotification({ kind: "auto-end", sessionId, expiresAt, reason },- { autoDismiss: false }+ { autoDismissAt: expiresAt });}- dismissMeetingAutoEndCountdown(sessionId) {+ dismissMeetingAutoEndNotification(sessionId) {if (this._pendingNotificationData?.kind !== "auto-end" ||this._pendingNotificationData.sessionId !== sessionId@@ -2102,6 +2116,11 @@ class WindowManager {this.dismissMeetingNotification();}+ isMeetingNotificationSender(sender) {+ const win = this.notificationWindow;+ return !!win && !win.isDestroyed() && win.webContents === sender;+ }+async showUpdateNotification(info) {if (this._onboardingActive) {this._deferredUpdateNotificationInfo = info;diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 3411ec303..b7658810f 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -3148,6 +3148,7 @@"back": "Zurück","restrictedByOrg": "Die Transkription von Besprechungen ist durch Ihre Organisation eingeschränkt.","autoEnded": "Die Aufnahme wurde nach dem Ende des Meetings automatisch beendet.",+ "restartFailed": "Die Meeting-Aufnahme konnte nicht neu gestartet werden.","systemAudioSilent": {"title": "Noch kein Meeting-Ton erkannt","description": "Bisher hat nur Ihr Mikrofon Ton aufgenommen. Sie sind in einem Videoanruf? Prüfen Sie, ob der Meeting-Ton auf diesem Computer wiedergegeben wird und nicht stummgeschaltet ist. Sie nehmen vor Ort auf? Dann können Sie diesen Hinweis ignorieren – Ihr Mikrofon nimmt den Raum auf."@@ -3842,13 +3843,13 @@"start": "Notizen aufnehmen","join": "Beitreten & transkribieren","autoEnd": {- "title": "Das Meeting könnte beendet sein",+ "title": "Meeting-Aufnahme beendet","body": {- "micReleased": "Keine andere App nutzt Ihr Mikrofon. Die Aufnahme stoppt in {{seconds}} s.",- "silence": "Kein Ton erkannt. Die Aufnahme stoppt in {{seconds}} s.",- "processExit": "Ihre Meeting-App wurde geschlossen. Die Aufnahme stoppt in {{seconds}} s."+ "micReleased": "Keine andere App nutzt Ihr Mikrofon, daher wurde die Aufnahme automatisch beendet. Neustart innerhalb von {{seconds}} s.",+ "silence": "Es wurde kein Ton erkannt, daher wurde die Aufnahme automatisch beendet. Neustart innerhalb von {{seconds}} s.",+ "processExit": "Ihre Meeting-App wurde geschlossen, daher wurde die Aufnahme automatisch beendet. Neustart innerhalb von {{seconds}} s."},- "keep": "Aufnahme fortsetzen"+ "restart": "Aufnahme neu starten"}}}diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex d8dc3c302..f8546a7db 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -3148,6 +3148,7 @@"back": "Back","restrictedByOrg": "Meeting transcription is restricted by your organization.","autoEnded": "Recording stopped automatically after your meeting ended.",+ "restartFailed": "Couldn't restart the meeting recording.","systemAudioSilent": {"title": "No meeting audio detected yet","description": "Only your microphone has picked up sound so far. On a video call? Check that the meeting audio is playing on this computer and isn't muted. Recording in person? You can ignore this — your microphone captures the room."@@ -3842,13 +3843,13 @@"start": "Take notes","join": "Join & transcribe","autoEnd": {- "title": "Meeting may have ended",+ "title": "Meeting recording ended","body": {- "micReleased": "No other app is using your microphone. Recording will stop in {{seconds}}s.",- "silence": "No audio detected. Recording will stop in {{seconds}}s.",- "processExit": "Your meeting app closed. Recording will stop in {{seconds}}s."+ "micReleased": "No other app is using your microphone, so recording stopped automatically. Restart within {{seconds}}s.",+ "silence": "No audio was detected, so recording stopped automatically. Restart within {{seconds}}s.",+ "processExit": "Your meeting app closed, so recording stopped automatically. Restart within {{seconds}}s."},- "keep": "Keep recording"+ "restart": "Restart recording"}}}diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex d1b4f81b4..7abb0982d 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -2985,6 +2985,7 @@"back": "Atrás","restrictedByOrg": "La transcripción de reuniones está restringida por tu organización.","autoEnded": "La grabación se detuvo automáticamente cuando terminó la reunión.",+ "restartFailed": "No se pudo reiniciar la grabación de la reunión.","systemAudioSilent": {"title": "Aún no se detecta el audio de la reunión","description": "Hasta ahora solo tu micrófono ha captado sonido. ¿Estás en una videollamada? Comprueba que el audio de la reunión se reproduce en este equipo y no está silenciado. ¿Estás grabando en persona? Puedes ignorar este aviso: tu micrófono capta la sala."@@ -3842,13 +3843,13 @@"start": "Tomar notas","join": "Unirse y transcribir","autoEnd": {- "title": "Es posible que la reunión haya terminado",+ "title": "La grabación de la reunión terminó","body": {- "micReleased": "Ninguna otra app está usando el micrófono. La grabación se detendrá en {{seconds}}s.",- "silence": "No se detecta audio. La grabación se detendrá en {{seconds}}s.",- "processExit": "La app de reuniones se cerró. La grabación se detendrá en {{seconds}}s."+ "micReleased": "Ninguna otra app está usando el micrófono, así que la grabación se detuvo automáticamente. Reiníciala en {{seconds}} s.",+ "silence": "No se detectó audio, así que la grabación se detuvo automáticamente. Reiníciala en {{seconds}} s.",+ "processExit": "La app de reuniones se cerró, así que la grabación se detuvo automáticamente. Reiníciala en {{seconds}} s."},- "keep": "Seguir grabando"+ "restart": "Reiniciar grabación"}}}diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 2146dcc40..0123d1592 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -3148,6 +3148,7 @@"back": "Retour","restrictedByOrg": "La transcription des réunions est restreinte par votre organisation.","autoEnded": "L'enregistrement s'est arrêté automatiquement à la fin de votre réunion.",+ "restartFailed": "Impossible de redémarrer l'enregistrement de la réunion.","systemAudioSilent": {"title": "Aucun son de réunion détecté pour le moment","description": "Seul votre microphone a capté du son jusqu'à présent. Vous êtes en visioconférence ? Vérifiez que le son de la réunion est diffusé sur cet ordinateur et qu'il n'est pas coupé. Vous enregistrez en présentiel ? Vous pouvez ignorer ce message : votre microphone capte la salle."@@ -3842,13 +3843,13 @@"start": "Prendre des notes","join": "Rejoindre et transcrire","autoEnd": {- "title": "La réunion est peut-être terminée",+ "title": "L’enregistrement de la réunion est terminé","body": {- "micReleased": "Aucune autre app n'utilise votre micro. L'enregistrement s'arrêtera dans {{seconds}}s.",- "silence": "Aucun son détecté. L'enregistrement s'arrêtera dans {{seconds}}s.",- "processExit": "Votre app de réunion s'est fermée. L'enregistrement s'arrêtera dans {{seconds}}s."+ "micReleased": "Aucune autre app n’utilise votre micro, donc l’enregistrement s’est arrêté automatiquement. Redémarrez-le dans les {{seconds}} s.",+ "silence": "Aucun son n’a été détecté, donc l’enregistrement s’est arrêté automatiquement. Redémarrez-le dans les {{seconds}} s.",+ "processExit": "Votre app de réunion s’est fermée, donc l’enregistrement s’est arrêté automatiquement. Redémarrez-le dans les {{seconds}} s."},- "keep": "Continuer l’enregistrement"+ "restart": "Redémarrer l’enregistrement"}}}diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 87f85cff4..15901a645 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -2937,6 +2937,7 @@"back": "Indietro","restrictedByOrg": "La trascrizione delle riunioni è limitata dalla tua organizzazione.","autoEnded": "La registrazione si è interrotta automaticamente al termine della riunione.",+ "restartFailed": "Impossibile riavviare la registrazione della riunione.","systemAudioSilent": {"title": "Nessun audio della riunione rilevato finora","description": "Finora solo il tuo microfono ha captato suoni. Sei in una videochiamata? Verifica che l'audio della riunione venga riprodotto su questo computer e non sia disattivato. Stai registrando di persona? Puoi ignorare questo avviso: il tuo microfono cattura la stanza."@@ -3842,13 +3843,13 @@"start": "Prendi appunti","join": "Partecipa e trascrivi","autoEnd": {- "title": "La riunione potrebbe essere finita",+ "title": "Registrazione della riunione terminata","body": {- "micReleased": "Nessun'altra app sta usando il microfono. La registrazione si fermerà tra {{seconds}}s.",- "silence": "Nessun audio rilevato. La registrazione si fermerà tra {{seconds}}s.",- "processExit": "L'app della riunione è stata chiusa. La registrazione si fermerà tra {{seconds}}s."+ "micReleased": "Nessun’altra app sta usando il microfono, quindi la registrazione si è interrotta automaticamente. Riavviala entro {{seconds}} s.",+ "silence": "Non è stato rilevato audio, quindi la registrazione si è interrotta automaticamente. Riavviala entro {{seconds}} s.",+ "processExit": "L’app della riunione è stata chiusa, quindi la registrazione si è interrotta automaticamente. Riavviala entro {{seconds}} s."},- "keep": "Continua a registrare"+ "restart": "Riavvia registrazione"}}}diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 4531c3e0d..49c829e66 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -2921,6 +2921,7 @@"back": "戻る","restrictedByOrg": "会議の文字起こしは組織によって制限されています。","autoEnded": "会議の終了後、録音は自動的に停止しました。",+ "restartFailed": "会議の録音を再開できませんでした。","systemAudioSilent": {"title": "会議の音声がまだ検出されていません","description": "これまでのところ、音声を拾っているのはマイクのみです。ビデオ会議中の場合は、会議の音声がこのコンピューターで再生されており、ミュートになっていないことを確認してください。対面で録音している場合は、この通知は無視してかまいません。マイクが室内の音を拾います。"@@ -3842,13 +3843,13 @@"start": "メモを取る","join": "参加して文字起こし","autoEnd": {- "title": "会議が終了した可能性があります",+ "title": "会議の録音が終了しました","body": {- "micReleased": "ほかのアプリはマイクを使用していません。録音は{{seconds}}秒後に停止します。",- "silence": "音声が検出されません。録音は{{seconds}}秒後に停止します。",- "processExit": "会議アプリが終了しました。録音は{{seconds}}秒後に停止します。"+ "micReleased": "ほかのアプリがマイクを使用していないため、録音を自動停止しました。{{seconds}}秒以内に再開できます。",+ "silence": "音声が検出されなかったため、録音を自動停止しました。{{seconds}}秒以内に再開できます。",+ "processExit": "会議アプリが終了したため、録音を自動停止しました。{{seconds}}秒以内に再開できます。"},- "keep": "録音を続ける"+ "restart": "録音を再開"}}}diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 2bc2457ae..a6319ddfe 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -2937,6 +2937,7 @@"back": "Voltar","restrictedByOrg": "A transcrição de reuniões está restrita pela sua organização.","autoEnded": "A gravação parou automaticamente após o fim da reunião.",+ "restartFailed": "Não foi possível reiniciar a gravação da reunião.","systemAudioSilent": {"title": "Nenhum áudio da reunião detectado até agora","description": "Até agora, apenas o seu microfone captou som. Está em uma videochamada? Verifique se o áudio da reunião está sendo reproduzido neste computador e não está silenciado. Está gravando presencialmente? Você pode ignorar este aviso: seu microfone capta o ambiente."@@ -3842,13 +3843,13 @@"start": "Fazer anotações","join": "Entrar e transcrever","autoEnd": {- "title": "A reunião pode ter terminado",+ "title": "Gravação da reunião encerrada","body": {- "micReleased": "Nenhum outro app está usando o microfone. A gravação vai parar em {{seconds}}s.",- "silence": "Nenhum áudio detectado. A gravação vai parar em {{seconds}}s.",- "processExit": "Seu app de reunião foi fechado. A gravação vai parar em {{seconds}}s."+ "micReleased": "Nenhum outro app está usando o microfone, então a gravação parou automaticamente. Reinicie em até {{seconds}} s.",+ "silence": "Nenhum áudio foi detectado, então a gravação parou automaticamente. Reinicie em até {{seconds}} s.",+ "processExit": "Seu app de reunião foi fechado, então a gravação parou automaticamente. Reinicie em até {{seconds}} s."},- "keep": "Continuar gravando"+ "restart": "Reiniciar gravação"}}}diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex ee40d31b8..32bfc6cde 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -2959,6 +2959,7 @@"back": "Назад","restrictedByOrg": "Транскрипция встреч ограничена вашей организацией.","autoEnded": "Запись автоматически остановлена после завершения встречи.",+ "restartFailed": "Не удалось возобновить запись встречи.","systemAudioSilent": {"title": "Звук встречи пока не обнаружен","description": "Пока звук поступает только с вашего микрофона. Вы на видеозвонке? Убедитесь, что звук встречи воспроизводится на этом компьютере и не отключён. Записываете встречу вживую? Это предупреждение можно игнорировать — ваш микрофон улавливает звук в помещении."@@ -3872,13 +3873,13 @@"start": "Вести заметки","join": "Присоединиться и вести заметки","autoEnd": {- "title": "Возможно, встреча завершилась",+ "title": "Запись встречи завершена","body": {- "micReleased": "Другие приложения не используют микрофон. Запись остановится через {{seconds}} с.",- "silence": "Звук не обнаружен. Запись остановится через {{seconds}} с.",- "processExit": "Приложение для встреч закрыто. Запись остановится через {{seconds}} с."+ "micReleased": "Другие приложения не используют микрофон, поэтому запись остановлена автоматически. Перезапустите её в течение {{seconds}} с.",+ "silence": "Звук не обнаружен, поэтому запись остановлена автоматически. Перезапустите её в течение {{seconds}} с.",+ "processExit": "Приложение для встреч закрыто, поэтому запись остановлена автоматически. Перезапустите её в течение {{seconds}} с."},- "keep": "Продолжить запись"+ "restart": "Перезапустить запись"}}}diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 0c6f49930..45563ec06 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -2937,6 +2937,7 @@"back": "返回","restrictedByOrg": "会议转录已被您的组织限制。","autoEnded": "会议结束后,录音已自动停止。",+ "restartFailed": "无法重新开始会议录音。","systemAudioSilent": {"title": "尚未检测到会议音频","description": "到目前为止,只有您的麦克风采集到声音。正在进行视频通话?请检查会议音频是否正在此电脑上播放且未被静音。正在进行现场录音?您可以忽略此提示——您的麦克风会采集房间内的声音。"@@ -3842,13 +3843,13 @@"start": "开始记录","join": "加入并转录","autoEnd": {- "title": "会议可能已结束",+ "title": "会议录音已结束","body": {- "micReleased": "没有其他应用在使用麦克风。录音将在 {{seconds}} 秒后停止。",- "silence": "未检测到音频。录音将在 {{seconds}} 秒后停止。",- "processExit": "会议应用已关闭。录音将在 {{seconds}} 秒后停止。"+ "micReleased": "没有其他应用在使用麦克风,因此录音已自动停止。请在 {{seconds}} 秒内重新开始录音。",+ "silence": "未检测到音频,因此录音已自动停止。请在 {{seconds}} 秒内重新开始录音。",+ "processExit": "会议应用已关闭,因此录音已自动停止。请在 {{seconds}} 秒内重新开始录音。"},- "keep": "继续录音"+ "restart": "重新开始录音"}}}diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 9fd63510a..985feb7ac 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -2937,6 +2937,7 @@"back": "返回","restrictedByOrg": "會議轉錄已被您的組織限制。","autoEnded": "會議結束後,錄音已自動停止。",+ "restartFailed": "無法重新開始會議錄音。","systemAudioSilent": {"title": "尚未偵測到會議音訊","description": "到目前為止,只有您的麥克風收到聲音。正在進行視訊通話?請檢查會議音訊是否正在此電腦上播放且未被靜音。正在進行現場錄音?您可以忽略此提示——您的麥克風會收錄房間內的聲音。"@@ -3842,13 +3843,13 @@"start": "開始記錄","join": "加入並轉錄","autoEnd": {- "title": "會議可能已結束",+ "title": "會議錄音已結束","body": {- "micReleased": "沒有其他應用程式在使用麥克風。錄音將在 {{seconds}} 秒後停止。",- "silence": "未偵測到音訊。錄音將在 {{seconds}} 秒後停止。",- "processExit": "會議應用程式已關閉。錄音將在 {{seconds}} 秒後停止。"+ "micReleased": "沒有其他應用程式在使用麥克風,因此錄音已自動停止。請在 {{seconds}} 秒內重新開始錄音。",+ "silence": "未偵測到音訊,因此錄音已自動停止。請在 {{seconds}} 秒內重新開始錄音。",+ "processExit": "會議應用程式已關閉,因此錄音已自動停止。請在 {{seconds}} 秒內重新開始錄音。"},- "keep": "繼續錄音"+ "restart": "重新開始錄音"}}}diff --git a/src/stores/meetingRecordingStore.ts b/src/stores/meetingRecordingStore.tsindex 615609809..d7f29510c 100644--- a/src/stores/meetingRecordingStore.ts+++ b/src/stores/meetingRecordingStore.ts@@ -1448,6 +1448,9 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>export interface StopRecordingResult {diarizationSessionId: string | null;+ // True only when this call ended a live recording — false for a no-op stop+ // (nothing recording, or a scoped stop for a session that is not active).+ stopped: boolean;}export async function stopRecording(expectedSessionId?: string): Promise<StopRecordingResult> {@@ -1465,23 +1468,23 @@ export async function stopRecording(expectedSessionId?: string): Promise<StopRecsystemAudioSilentWarning: false,currentMicLevel: 0,});- return { diarizationSessionId: null };+ return { diarizationSessionId: null, stopped: false };}await meetingRecordingStopBarrier.waitForPendingStop();if (!canStopMeetingRecordingSession(activeRecordingSessionId, expectedSessionId)) {- return { diarizationSessionId: null };+ return { diarizationSessionId: null, stopped: false };}if (!isRecordingFlag) {- return { diarizationSessionId: null };+ return { diarizationSessionId: null, stopped: false };}return meetingRecordingStopBarrier.runStop(async () => {if (!canStopMeetingRecordingSession(activeRecordingSessionId, expectedSessionId)) {- return { diarizationSessionId: null };+ return { diarizationSessionId: null, stopped: false };}if (!isRecordingFlag) {- return { diarizationSessionId: null };+ return { diarizationSessionId: null, stopped: false };}const sessionId = activeRecordingSessionId;@@ -1553,7 +1556,10 @@ export async function stopRecording(expectedSessionId?: string): Promise<StopRec});logger.info("Meeting transcription stopped", {}, "meeting");- return { diarizationSessionId };+ // Reaching here means this call ended a live recording and its transcript+ // was written above, so its note is resumable. A failed main-side teardown+ // is surfaced by reportMeetingError and must not void the restart offer.+ return { diarizationSessionId, stopped: true };});}@@ -1600,6 +1606,7 @@ if (typeof window !== "undefined") {enqueueDiarizationCompletion(async () => {const {diarizationSessionId,+ isRecording,recordingNoteId,segments: liveSegments,} = useMeetingRecordingStore.getState();@@ -1607,6 +1614,7 @@ if (typeof window !== "undefined") {payloadNoteId: data?.noteId,payloadSessionId: data?.sessionId,currentSessionId: diarizationSessionId,+ activeRecordingNoteId: isRecording ? recordingNoteId : null,});if (targetNoteId == null) return;diff --git a/src/types/electron.ts b/src/types/electron.tsindex 8ffbfd71f..702fbd4d4 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -102,6 +102,18 @@ export interface MeetingAutoEndRequest {reason?: MeetingAutoEndReason;}+export type MeetingAutoEndAction = "restart" | "dismiss";++export interface MeetingAutoEndRestartRequest {+ sessionId: string;+}++export interface MeetingAutoEndLifecycleResult {+ success: boolean;+ reason?: "invalid-session" | "invalid-action" | "stale-session";+ error?: string;+}+/*** Proxied-transcription IPC results. `ipcMain.handle` drops custom error props on* rejection, so these handlers resolve with a serialized error instead of throwing.@@ -2793,11 +2805,14 @@ declare global {onMeetingAutoEndRequested?: (callback: (request: MeetingAutoEndRequest) => void) => () => void;- meetingAutoEndKeep?: (sessionId: string) => Promise<{- success: boolean;- reason?: "invalid-session" | "stale-session";- error?: string;- }>;+ meetingAutoEndCompleted?: (sessionId: string) => Promise<MeetingAutoEndLifecycleResult>;+ meetingAutoEndRespond?: (+ sessionId: string,+ action: MeetingAutoEndAction+ ) => Promise<MeetingAutoEndLifecycleResult>;+ onMeetingAutoEndRestartRequested?: (+ callback: (request: MeetingAutoEndRestartRequest) => void+ ) => () => void;getMeetingNotificationData?: () => Promise<MeetingNotificationData | null>;meetingNotificationReady?: () => Promise<void>;meetingNotificationRespond?: (diff --git a/src/utils/diarizationCompletion.ts b/src/utils/diarizationCompletion.tsindex 972b36aa8..08fa65f33 100644--- a/src/utils/diarizationCompletion.ts+++ b/src/utils/diarizationCompletion.ts@@ -14,14 +14,26 @@ export function resolveDiarizationTarget(params: {payloadNoteId?: number | null;payloadSessionId?: string | null;currentSessionId: string | null;+ // The note a *live* recording is writing to, or null when nothing is+ // recording. Not simply the store's recordingNoteId, which outlives the+ // recording that set it.+ activeRecordingNoteId?: number | null;}): DiarizationCompletionPlan {- const { payloadNoteId, payloadSessionId, currentSessionId } = params;+ const { payloadNoteId, payloadSessionId, currentSessionId, activeRecordingNoteId } = params;+ const targetNoteId = payloadNoteId ?? null;+ // Resuming a note starts a recording that resets currentSessionId to null, so+ // "nothing pending" alone no longer means "safe to publish": the result would+ // paint the finished half over the recording that is still appending to the+ // same note, and the editor prefers that overlay to the note's own text.+ const supersededByLiveRecording = targetNoteId !== null && activeRecordingNoteId === targetNoteId;return {- targetNoteId: payloadNoteId ?? null,- // A null current session means nothing newer is pending, so publishing is- // safe and clearing a waiting spinner prevents it from getting stuck.- isCurrentSession: currentSessionId == null || payloadSessionId === currentSessionId,+ targetNoteId,+ // A null current session otherwise means nothing newer is pending, so+ // publishing is safe and clearing a waiting spinner prevents it sticking.+ isCurrentSession:+ !supersededByLiveRecording &&+ (currentSessionId == null || payloadSessionId === currentSessionId),};}diff --git a/test/helpers/meetingAudioActivityMonitor.test.js b/test/helpers/meetingAudioActivityMonitor.test.jsindex 90a506990..ff026f3da 100644--- a/test/helpers/meetingAudioActivityMonitor.test.js+++ b/test/helpers/meetingAudioActivityMonitor.test.js@@ -74,13 +74,20 @@ test("activity ages out after each channel's tail with a single change", () => {monitor.tick(START);assert.deepEqual(changes, [{ micActive: true, systemActive: true }]);- monitor.tick(START + MIC_ACTIVITY_TAIL_MS - 1);+ // Which tail is longer is a tuning decision, so derive the order from the+ // constants: the point is that each channel ages out on its own tail.+ const micFirst = MIC_ACTIVITY_TAIL_MS < SYSTEM_ACTIVITY_TAIL_MS;+ const firstTail = Math.min(MIC_ACTIVITY_TAIL_MS, SYSTEM_ACTIVITY_TAIL_MS);+ const secondTail = Math.max(MIC_ACTIVITY_TAIL_MS, SYSTEM_ACTIVITY_TAIL_MS);+ assert.notEqual(firstTail, secondTail, "the tails must differ for this to be two changes");++ monitor.tick(START + firstTail - 1);assert.equal(changes.length, 1, "still inside both tails");- monitor.tick(START + MIC_ACTIVITY_TAIL_MS);- assert.deepEqual(changes.at(-1), { micActive: false, systemActive: true });+ monitor.tick(START + firstTail);+ assert.deepEqual(changes.at(-1), { micActive: !micFirst, systemActive: micFirst });- monitor.tick(START + SYSTEM_ACTIVITY_TAIL_MS);+ monitor.tick(START + secondTail);assert.deepEqual(changes.at(-1), { micActive: false, systemActive: false });assert.equal(changes.length, 3);});diff --git a/test/helpers/meetingAutoEndController.test.js b/test/helpers/meetingAutoEndController.test.jsindex 7968efee1..d83a8ddfc 100644--- a/test/helpers/meetingAutoEndController.test.js+++ b/test/helpers/meetingAutoEndController.test.js@@ -3,28 +3,21 @@ const assert = require("node:assert/strict");const createMeetingAutoEndController = require("../../src/helpers/meetingAutoEndController");const {- COUNTDOWN_MS,SILENCE_WINDOW_MS,FAST_SILENCE_MS,- KEEP_COOLDOWN_MS,OWNERSHIP_MIN_ACTIVE_MS,+ OWNERSHIP_CONFIRM_MS,TICK_GAP_MS,} = createMeetingAutoEndController;const START_TIME = 1_000_000;const TICK_MS = 1_000;-// The engine ticks the controller about once a second; runFor() mirrors that so-// long spans never look like a sleep gap.const createHarness = () => {let now = START_TIME;- const countdowns = [];- const canceledCountdowns = [];const stops = [];const controller = createMeetingAutoEndController({now: () => now,- onCountdown: (countdown) => countdowns.push(countdown),- onCountdownCanceled: (sessionId) => canceledCountdowns.push(sessionId),onStop: (sessionId, reason) => stops.push({ sessionId, reason }),});@@ -37,18 +30,14 @@ const createHarness = () => {controller.tick();}};- const jump = (ms) => {- now += ms;- };return {controller,- countdowns,- canceledCountdowns,stops,runFor,- jump,- now: () => now,+ jump: (ms) => {+ now += ms;+ },};};@@ -67,494 +56,351 @@ const micAcquired = (controller, sessionId = "s1") =>const audio = (controller, micActive, systemActive, sessionId = "s1") =>controller.handleAudioActivity({ sessionId, micActive, systemActive });-// ---------------------------------------------------------------------------// Ownership mode-// --------------------------------------------------------------------------+test("ownership: a qualifying mic release stops after the confirm window", () => {+ const harness = createHarness();+ beginOwnership(harness.controller);+ harness.runFor(OWNERSHIP_MIN_ACTIVE_MS);-test("ownership: mic release with a quiet system channel starts a mic-released countdown", () => {- const h = createHarness();- beginOwnership(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(harness.controller);+ assert.deepEqual(harness.stops, []);+ harness.runFor(OWNERSHIP_CONFIRM_MS - TICK_MS);+ assert.deepEqual(harness.stops, []);- micReleased(h.controller);-- assert.deepEqual(h.countdowns, [- { sessionId: "s1", expiresAt: h.now() + COUNTDOWN_MS, reason: "mic-released" },- ]);- h.runFor(COUNTDOWN_MS - TICK_MS);- assert.deepEqual(h.stops, []);- h.runFor(TICK_MS);- assert.deepEqual(h.stops, [{ sessionId: "s1", reason: "mic-released" }]);+ harness.runFor(TICK_MS);+ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "mic-released" }]);});-test("ownership: audible system audio defers the countdown until it goes quiet", () => {- const h = createHarness();- beginOwnership(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);- audio(h.controller, false, true);+// A device flap (Bluetooth reconnect, input-device switch, an app rebuilding+// its input unit for screen share) emits MIC_STOP then MIC_START in the same+// reconcile pass, with no time between them.+test("ownership: a mic release immediately followed by a re-acquire keeps recording", () => {+ const harness = createHarness();+ beginOwnership(harness.controller);+ harness.runFor(OWNERSHIP_MIN_ACTIVE_MS);- micReleased(h.controller);- h.runFor(2 * COUNTDOWN_MS);- assert.deepEqual(h.countdowns, [], "remote voices still playing — call is live");+ micReleased(harness.controller);+ micAcquired(harness.controller);- audio(h.controller, false, false);- assert.equal(h.countdowns.length, 1);- assert.equal(h.countdowns[0].reason, "mic-released");+ harness.runFor(4 * OWNERSHIP_CONFIRM_MS);+ assert.deepEqual(harness.stops, []);});-test("ownership: system audio resuming cancels the countdown and quiet restarts it from 60s", () => {- const h = createHarness();- beginOwnership(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);- micReleased(h.controller);- h.runFor(30_000);-- audio(h.controller, false, true);- assert.deepEqual(h.canceledCountdowns, ["s1"]);- h.runFor(COUNTDOWN_MS);- assert.deepEqual(h.stops, []);-- audio(h.controller, false, false);- assert.equal(h.countdowns.length, 2);- assert.equal(h.countdowns[1].expiresAt, h.now() + COUNTDOWN_MS, "full 60s again");-});+test("ownership: remote audio during the confirm window restarts it", () => {+ const harness = createHarness();+ beginOwnership(harness.controller);+ harness.runFor(OWNERSHIP_MIN_ACTIVE_MS);-test("ownership: a re-acquired external mic cancels the countdown and re-arms", () => {- const h = createHarness();- beginOwnership(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);- micReleased(h.controller);- h.runFor(30_000);+ micReleased(harness.controller);+ harness.runFor(OWNERSHIP_CONFIRM_MS - TICK_MS);+ audio(harness.controller, false, true);+ harness.runFor(4 * OWNERSHIP_CONFIRM_MS);+ assert.deepEqual(harness.stops, []);- micAcquired(h.controller);- assert.deepEqual(h.canceledCountdowns, ["s1"]);- h.runFor(2 * COUNTDOWN_MS);- assert.deepEqual(h.stops, []);+ audio(harness.controller, false, false);+ harness.runFor(OWNERSHIP_CONFIRM_MS - TICK_MS);+ assert.deepEqual(harness.stops, []);- micReleased(h.controller);- assert.equal(h.countdowns.length, 2);+ harness.runFor(TICK_MS);+ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "mic-released" }]);});-test("ownership: mic-channel activity does not cancel the countdown", () => {- const h = createHarness();- beginOwnership(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);- micReleased(h.controller);+test("ownership: remote audio defers stopping until the system channel goes quiet", () => {+ const harness = createHarness();+ beginOwnership(harness.controller);+ harness.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ audio(harness.controller, false, true);- audio(h.controller, true, false);- h.runFor(COUNTDOWN_MS);+ micReleased(harness.controller);+ harness.runFor(2 * SILENCE_WINDOW_MS);+ assert.deepEqual(harness.stops, []);- assert.deepEqual(h.canceledCountdowns, []);- assert.deepEqual(h.stops, [{ sessionId: "s1", reason: "mic-released" }]);+ audio(harness.controller, false, false);+ harness.runFor(OWNERSHIP_CONFIRM_MS);+ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "mic-released" }]);});-test("ownership: a hold shorter than the minimum falls back to silence instead of arming", () => {- const h = createHarness();- beginFallback(h.controller);- h.runFor(20_000);- audio(h.controller, true, false);- micAcquired(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS - TICK_MS);-- micReleased(h.controller);- h.runFor(2 * COUNTDOWN_MS);-- assert.deepEqual(h.countdowns, [], "people are still talking in the room");- audio(h.controller, false, false);- h.runFor(SILENCE_WINDOW_MS);- assert.equal(h.countdowns.length, 1);- assert.equal(h.countdowns[0].reason, "silence");-});--test("ownership: a process exit is ignored", () => {- const h = createHarness();- beginOwnership(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+test("ownership: mic-channel activity does not mask a qualifying release", () => {+ const harness = createHarness();+ beginOwnership(harness.controller);+ harness.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ audio(harness.controller, true, false);- h.controller.handleMeetingProcessExit({ sessionId: "s1" });- h.runFor(2 * SILENCE_WINDOW_MS);+ micReleased(harness.controller);+ harness.runFor(OWNERSHIP_CONFIRM_MS);- assert.deepEqual(h.countdowns, []);+ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "mic-released" }]);});-test("ownership: keep suppresses prompts until fresh active ownership, and the cooldown still applies", () => {- const h = createHarness();- beginOwnership(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);- micReleased(h.controller);-- assert.equal(h.controller.keepRecording("s1"), true);- assert.deepEqual(h.canceledCountdowns, ["s1"]);- h.runFor(2 * KEEP_COOLDOWN_MS);- assert.equal(h.countdowns.length, 1, "no further call → never re-prompted");-- micAcquired(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);- micReleased(h.controller);- assert.equal(h.countdowns.length, 2, "a new call is fresh evidence");+test("ownership: a brief external mic hold falls back to the silence window", () => {+ const harness = createHarness();+ beginFallback(harness.controller);+ audio(harness.controller, true, false);+ micAcquired(harness.controller);+ harness.runFor(OWNERSHIP_MIN_ACTIVE_MS - TICK_MS);++ micReleased(harness.controller);+ harness.runFor(SILENCE_WINDOW_MS);+ assert.deepEqual(harness.stops, []);++ audio(harness.controller, false, false);+ harness.runFor(SILENCE_WINDOW_MS - TICK_MS);+ assert.deepEqual(harness.stops, []);+ harness.runFor(TICK_MS);+ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "silence" }]);});-test("ownership: a call rejoined and left again re-prompts at once, even inside the keep cooldown", () => {- const h = createHarness();- beginOwnership(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);- micReleased(h.controller);- h.controller.keepRecording("s1");+test("ownership: process exit is ignored while an app owns the mic", () => {+ const harness = createHarness();+ beginOwnership(harness.controller);+ harness.runFor(OWNERSHIP_MIN_ACTIVE_MS);- h.runFor(60_000);- micAcquired(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);- micReleased(h.controller);-- assert.equal(h.countdowns.length, 2, "unambiguous evidence must not wait out the cooldown");- assert.equal(h.countdowns[1].reason, "mic-released");-});+ harness.controller.handleMeetingProcessExit({ sessionId: "s1" });+ harness.runFor(2 * SILENCE_WINDOW_MS);-test("ownership: a brief rejoin inside the cooldown does not bypass it", () => {- const h = createHarness();- beginOwnership(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);- micReleased(h.controller);- h.controller.keepRecording("s1");- const keptAt = h.now();-- h.runFor(60_000);- micAcquired(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS - TICK_MS);- micReleased(h.controller);- h.runFor(2 * SILENCE_WINDOW_MS);- assert.equal(h.countdowns.length, 1, "an incidental hold is not fresh evidence");-- h.runFor(keptAt + KEEP_COOLDOWN_MS - h.now());- h.runFor(SILENCE_WINDOW_MS);- assert.equal(h.countdowns.length, 2, "after the cooldown, silence prompts as fallback");- assert.equal(h.countdowns[1].reason, "silence");+ assert.deepEqual(harness.stops, []);});-// ---------------------------------------------------------------------------// Fallback mode-// --------------------------------------------------------------------------+test("fallback: both channels staying quiet for 60 seconds stops immediately", () => {+ const harness = createHarness();+ beginFallback(harness.controller);-test("fallback: 60s of both-channel silence prompts with reason silence", () => {- const h = createHarness();- beginFallback(h.controller);+ harness.runFor(SILENCE_WINDOW_MS - TICK_MS);+ assert.deepEqual(harness.stops, []);+ harness.runFor(TICK_MS);- h.runFor(SILENCE_WINDOW_MS - TICK_MS);- assert.deepEqual(h.countdowns, []);- h.runFor(TICK_MS);-- assert.deepEqual(h.countdowns, [- { sessionId: "s1", expiresAt: h.now() + COUNTDOWN_MS, reason: "silence" },- ]);- h.runFor(COUNTDOWN_MS);- assert.deepEqual(h.stops, [{ sessionId: "s1", reason: "silence" }]);-});--test("fallback: activity on either channel resets the window and cancels the countdown", () => {- const h = createHarness();- beginFallback(h.controller);- h.runFor(SILENCE_WINDOW_MS - 5_000);-- audio(h.controller, true, false);- h.runFor(5_000);- audio(h.controller, false, false);- h.runFor(SILENCE_WINDOW_MS - TICK_MS);- assert.deepEqual(h.countdowns, [], "the window restarted when the mic went quiet");- h.runFor(TICK_MS);- assert.equal(h.countdowns.length, 1);-- audio(h.controller, false, true);- assert.deepEqual(h.canceledCountdowns, ["s1"]);- h.runFor(2 * COUNTDOWN_MS);- assert.deepEqual(h.stops, []);+ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "silence" }]);});-test("fallback: process exit with no tracked app left shortens the window to 10s", () => {- const h = createHarness();- beginFallback(h.controller);- h.runFor(20_000);-- h.controller.handleMeetingProcessExit({ sessionId: "s1" });- h.runFor(FAST_SILENCE_MS - TICK_MS);- assert.deepEqual(h.countdowns, []);- h.runFor(TICK_MS);+test("fallback: activity on either channel restarts the silence window", () => {+ const harness = createHarness();+ beginFallback(harness.controller);+ harness.runFor(SILENCE_WINDOW_MS - 5_000);- assert.equal(h.countdowns.length, 1);- assert.equal(h.countdowns[0].reason, "process-exit");-});+ audio(harness.controller, true, false);+ harness.runFor(5_000);+ audio(harness.controller, false, false);+ harness.runFor(SILENCE_WINDOW_MS - TICK_MS);+ assert.deepEqual(harness.stops, []);+ harness.runFor(TICK_MS);-test("fallback: activity after a process exit clears the fast window", () => {- const h = createHarness();- beginFallback(h.controller);- h.controller.handleMeetingProcessExit({ sessionId: "s1" });- h.runFor(5_000);-- audio(h.controller, false, true);- h.runFor(5_000);- audio(h.controller, false, false);- h.runFor(FAST_SILENCE_MS);- assert.deepEqual(h.countdowns, [], "call continued elsewhere — back to the full window");-- h.runFor(SILENCE_WINDOW_MS - FAST_SILENCE_MS);- assert.equal(h.countdowns.length, 1);- assert.equal(h.countdowns[0].reason, "silence");+ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "silence" }]);});-test("fallback: process exit while a countdown is visible is ignored", () => {- const h = createHarness();- beginFallback(h.controller);- h.runFor(SILENCE_WINDOW_MS);- assert.equal(h.countdowns.length, 1);- const { expiresAt } = h.countdowns[0];+test("fallback: process exit shortens the quiet window to 10 seconds", () => {+ const harness = createHarness();+ beginFallback(harness.controller);+ harness.runFor(20_000);- h.controller.handleMeetingProcessExit({ sessionId: "s1" });- h.runFor(COUNTDOWN_MS);+ harness.controller.handleMeetingProcessExit({ sessionId: "s1" });+ harness.runFor(FAST_SILENCE_MS - TICK_MS);+ assert.deepEqual(harness.stops, []);+ harness.runFor(TICK_MS);- assert.equal(h.countdowns.length, 1);- assert.deepEqual(h.stops, [{ sessionId: "s1", reason: "silence" }]);- assert.equal(h.countdowns[0].expiresAt, expiresAt);+ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "process-exit" }]);});-test("fallback: keep is honored until activity resumes and the cooldown passes", () => {- const h = createHarness();- beginFallback(h.controller);- h.runFor(SILENCE_WINDOW_MS);- assert.equal(h.controller.keepRecording("s1"), true);- const keptAt = h.now();-- h.runFor(2 * KEEP_COOLDOWN_MS);- assert.equal(h.countdowns.length, 1, "no fresh evidence → no re-prompt");-- audio(h.controller, true, false);- h.runFor(2_000);- audio(h.controller, false, false);- h.runFor(SILENCE_WINDOW_MS);- assert.equal(h.countdowns.length, 2, "renewed audio then silence reopened the episode");- assert.ok(h.countdowns[1].expiresAt > keptAt + KEEP_COOLDOWN_MS);-});+test("fallback: activity after process exit restores the full silence window", () => {+ const harness = createHarness();+ beginFallback(harness.controller);+ harness.controller.handleMeetingProcessExit({ sessionId: "s1" });+ harness.runFor(5_000);-test("fallback: process exit after keep reopens the episode but fires no earlier than the cooldown", () => {- const h = createHarness();- beginFallback(h.controller);- h.runFor(SILENCE_WINDOW_MS);- h.controller.keepRecording("s1");- const keptAt = h.now();-- h.runFor(60_000);- h.controller.handleMeetingProcessExit({ sessionId: "s1" });- h.runFor(FAST_SILENCE_MS + TICK_MS);- assert.equal(h.countdowns.length, 1, "inside the cooldown");-- h.runFor(keptAt + KEEP_COOLDOWN_MS - h.now());- assert.equal(h.countdowns.length, 2);- assert.equal(h.countdowns[1].reason, "process-exit");+ audio(harness.controller, false, true);+ harness.runFor(5_000);+ audio(harness.controller, false, false);+ harness.runFor(FAST_SILENCE_MS);+ assert.deepEqual(harness.stops, []);++ harness.runFor(SILENCE_WINDOW_MS - FAST_SILENCE_MS);+ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "silence" }]);});-test("fallback: a session that never sees a chunk prompts after the first window", () => {- const h = createHarness();- beginFallback(h.controller);+test("fallback: a session with no chunks still stops after the silence window", () => {+ const harness = createHarness();+ beginFallback(harness.controller);- h.runFor(SILENCE_WINDOW_MS);+ harness.runFor(SILENCE_WINDOW_MS);- assert.equal(h.countdowns.length, 1);- assert.equal(h.countdowns[0].reason, "silence");+ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "silence" }]);});-test("fallback: unreliable ownership behaves as fallback from the start", () => {- const h = createHarness();- beginFallback(h.controller, "s1", { reliable: false });+test("fallback: unreliable ownership uses the silence window from session start", () => {+ const harness = createHarness();+ beginFallback(harness.controller, "s1", { reliable: false });- h.runFor(SILENCE_WINDOW_MS);- assert.equal(h.countdowns.length, 1);-});+ harness.runFor(SILENCE_WINDOW_MS);-// ---------------------------------------------------------------------------// Mode transitions-// --------------------------------------------------------------------------+ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "silence" }]);+});-test("fresh active ownership switches fallback to ownership and cancels a pending fallback countdown", () => {- const h = createHarness();- beginFallback(h.controller);- h.runFor(SILENCE_WINDOW_MS);- assert.equal(h.countdowns.length, 1);+test("mode transitions: fresh ownership switches fallback into ownership mode", () => {+ const harness = createHarness();+ beginFallback(harness.controller);+ harness.runFor(SILENCE_WINDOW_MS - TICK_MS);- micAcquired(h.controller);- assert.deepEqual(h.canceledCountdowns, ["s1"]);- h.runFor(2 * SILENCE_WINDOW_MS);- assert.equal(h.countdowns.length, 1, "silence no longer prompts while an app holds the mic");+ micAcquired(harness.controller);+ harness.runFor(2 * SILENCE_WINDOW_MS);+ assert.deepEqual(harness.stops, []);- micReleased(h.controller);- assert.equal(h.countdowns.length, 2);- assert.equal(h.countdowns[1].reason, "mic-released");+ micReleased(harness.controller);+ harness.runFor(OWNERSHIP_CONFIRM_MS);+ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "mic-released" }]);});-test("reliability loss switches to fallback, dismisses the countdown, and restarts silence from now", () => {- const h = createHarness();- beginOwnership(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);- micReleased(h.controller);- h.runFor(30_000);+test("mode transitions: reliability loss restarts fallback silence from that moment", () => {+ const harness = createHarness();+ beginOwnership(harness.controller);+ harness.runFor(OWNERSHIP_MIN_ACTIVE_MS);- h.controller.handleExternalMicState({+ harness.controller.handleExternalMicState({sessionId: "s1",reliable: false,externalMicActive: false,});- assert.deepEqual(h.canceledCountdowns, ["s1"]);+ harness.runFor(SILENCE_WINDOW_MS - TICK_MS);+ assert.deepEqual(harness.stops, []);+ harness.runFor(TICK_MS);- h.runFor(SILENCE_WINDOW_MS - TICK_MS);- assert.equal(h.countdowns.length, 1);- h.runFor(TICK_MS);- assert.equal(h.countdowns.length, 2);- assert.equal(h.countdowns[1].reason, "silence");+ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "silence" }]);});-test("a reliable-but-inactive report after a reliability loss stays in fallback", () => {- const h = createHarness();- beginOwnership(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);- h.controller.handleExternalMicState({+test("mode transitions: an inactive reliable report after reliability loss stays fallback", () => {+ const harness = createHarness();+ beginOwnership(harness.controller);+ harness.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ harness.controller.handleExternalMicState({sessionId: "s1",reliable: false,externalMicActive: false,});- h.runFor(5_000);-- micReleased(h.controller);- assert.deepEqual(- h.countdowns,- [],- "no observed release → must not start a mic-released countdown"- );-- h.runFor(SILENCE_WINDOW_MS);- assert.equal(h.countdowns.length, 1);- assert.equal(h.countdowns[0].reason, "silence");-});+ harness.runFor(5_000);-// ---------------------------------------------------------------------------// Clock, lifecycle, and guards-// ----------------------------------------------------------------------------test("a tick gap over the sleep threshold discards accumulated silence and cancels a visible countdown without stopping", () => {- const h = createHarness();- beginFallback(h.controller);- h.runFor(SILENCE_WINDOW_MS);- assert.equal(h.countdowns.length, 1);-- h.jump(8 * 60 * 60 * 1000);- h.controller.tick();-- assert.deepEqual(h.stops, []);- assert.deepEqual(h.canceledCountdowns, ["s1"]);- h.runFor(SILENCE_WINDOW_MS - TICK_MS);- assert.equal(h.countdowns.length, 1, "silence restarted from wake");- h.runFor(TICK_MS);- assert.equal(h.countdowns.length, 2);+ micReleased(harness.controller);+ assert.deepEqual(harness.stops, []);+ harness.runFor(SILENCE_WINDOW_MS);++ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "silence" }]);});-test("a gap observed through an activity event instead of tick() is handled the same way", () => {- const h = createHarness();- beginFallback(h.controller);- h.runFor(SILENCE_WINDOW_MS);- h.runFor(30_000);+test("clock: a sleep-sized tick gap discards accumulated silence", () => {+ const harness = createHarness();+ beginFallback(harness.controller);+ harness.runFor(SILENCE_WINDOW_MS - TICK_MS);- h.jump(TICK_GAP_MS + 1);- audio(h.controller, false, false);+ harness.jump(TICK_GAP_MS + 1);+ harness.controller.tick();+ harness.runFor(SILENCE_WINDOW_MS - TICK_MS);+ assert.deepEqual(harness.stops, []);+ harness.runFor(TICK_MS);- assert.deepEqual(h.stops, []);- assert.deepEqual(h.canceledCountdowns, ["s1"]);+ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "silence" }]);});-test("countdown expiry stops exactly once and later inputs are ignored", () => {- const h = createHarness();- beginOwnership(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);- micReleased(h.controller);- h.runFor(COUNTDOWN_MS);- assert.equal(h.stops.length, 1);-- h.runFor(5 * COUNTDOWN_MS);- micAcquired(h.controller);- micReleased(h.controller);- audio(h.controller, true, true);- audio(h.controller, false, false);- h.controller.handleMeetingProcessExit({ sessionId: "s1" });- h.runFor(5 * COUNTDOWN_MS);-- assert.equal(h.stops.length, 1);- assert.equal(h.countdowns.length, 1);+// Every entry point observes the clock, not just tick(): after wake the owner's+// monitor can deliver an activity change before the controller's own tick runs,+// and that path has to discard the pre-sleep silence too.+test("clock: a sleep-sized gap observed through an activity event discards accumulated silence", () => {+ const harness = createHarness();+ beginFallback(harness.controller);+ harness.runFor(SILENCE_WINDOW_MS - TICK_MS);++ harness.jump(TICK_GAP_MS + 1);+ audio(harness.controller, false, false);++ assert.deepEqual(harness.stops, []);+ harness.runFor(SILENCE_WINDOW_MS - TICK_MS);+ assert.deepEqual(harness.stops, []);++ harness.runFor(TICK_MS);+ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "silence" }]);});-test("keep recording after countdown expiry reports failure — the stop is already in flight", () => {- const h = createHarness();- beginOwnership(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);- micReleased(h.controller);- h.runFor(COUNTDOWN_MS);+// endSession drops the session outright, so evidence gathered before it can+// never drive a stop afterwards. Every _deactivateAutoEnd goes through here.+test("ending a session keeps its pending evidence from stopping anything later", () => {+ const harness = createHarness();+ beginOwnership(harness.controller);+ harness.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(harness.controller);- assert.equal(h.controller.keepRecording("s1"), false);+ harness.controller.endSession("s1");+ harness.runFor(OWNERSHIP_CONFIRM_MS + SILENCE_WINDOW_MS);++ assert.deepEqual(harness.stops, []);});-test("ending or replacing a session cancels its countdown", () => {- const h = createHarness();- beginOwnership(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);- micReleased(h.controller);- assert.equal(h.countdowns.length, 1);-- beginOwnership(h.controller, "s2");- assert.deepEqual(h.canceledCountdowns, ["s1"]);- h.runFor(2 * COUNTDOWN_MS);- assert.deepEqual(h.stops, [], "the old countdown never fires for the new session");-- micReleased(h.controller, "s2");- h.controller.endSession("s2");- assert.deepEqual(h.canceledCountdowns, ["s1", "s2"]);- h.runFor(2 * COUNTDOWN_MS);- assert.deepEqual(h.stops, []);+test("ending a session that is not the live one leaves the live one running", () => {+ const harness = createHarness();+ beginOwnership(harness.controller);+ harness.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(harness.controller);++ harness.controller.endSession("s2");+ harness.runFor(OWNERSHIP_CONFIRM_MS);++ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "mic-released" }]);});-test("ending an expired session dismisses nothing and does not stop again", () => {- const h = createHarness();- beginOwnership(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);- micReleased(h.controller);- h.runFor(COUNTDOWN_MS);+test("clock: a mic release observed on wake does not stop immediately", () => {+ const { controller, jump, runFor, stops } = createHarness();+ beginOwnership(controller);+ runFor(OWNERSHIP_MIN_ACTIVE_MS);- h.controller.endSession("s1");- h.runFor(COUNTDOWN_MS);+ jump(TICK_GAP_MS + 1);+ controller.handleExternalMicState({+ sessionId: "s1",+ reliable: true,+ externalMicActive: false,+ });++ assert.deepEqual(stops, []);+ runFor(SILENCE_WINDOW_MS - TICK_MS);+ assert.deepEqual(stops, []);+ runFor(TICK_MS);+ assert.deepEqual(stops, [{ sessionId: "s1", reason: "silence" }]);+});- assert.equal(h.stops.length, 1);- assert.deepEqual(h.canceledCountdowns, []);+test("lifecycle: a stop fires once and later inputs are ignored", () => {+ const harness = createHarness();+ beginOwnership(harness.controller);+ harness.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ micReleased(harness.controller);+ harness.runFor(OWNERSHIP_CONFIRM_MS);++ micAcquired(harness.controller);+ micReleased(harness.controller);+ audio(harness.controller, true, true);+ audio(harness.controller, false, false);+ harness.controller.handleMeetingProcessExit({ sessionId: "s1" });+ harness.runFor(5 * SILENCE_WINDOW_MS);++ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "mic-released" }]);});-test("stale session ids and ineligible sessions ignore all inputs", () => {- const h = createHarness();- beginOwnership(h.controller);- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+test("guards: stale session ids and ineligible sessions ignore inputs", () => {+ const harness = createHarness();+ beginOwnership(harness.controller);+ harness.runFor(OWNERSHIP_MIN_ACTIVE_MS);- micReleased(h.controller, "other");- audio(h.controller, false, false, "other");- h.controller.handleMeetingProcessExit({ sessionId: "other" });- assert.equal(h.controller.keepRecording("other"), false);- h.runFor(2 * SILENCE_WINDOW_MS);- assert.deepEqual(h.countdowns, []);+ micReleased(harness.controller, "other");+ audio(harness.controller, false, false, "other");+ harness.controller.handleMeetingProcessExit({ sessionId: "other" });+ assert.deepEqual(harness.stops, []);- h.controller.beginSession({- sessionId: "s3",+ harness.controller.beginSession({+ sessionId: "s2",eligible: false,reliable: true,externalMicActive: true,});- micReleased(h.controller, "s3");- h.runFor(2 * SILENCE_WINDOW_MS);- assert.deepEqual(h.countdowns, []);+ micReleased(harness.controller, "s2");+ harness.runFor(2 * SILENCE_WINDOW_MS);+ assert.deepEqual(harness.stops, []);});-test("beginSession seeds the initial audio state so an already-audible system channel defers the countdown", () => {- const h = createHarness();- h.controller.beginSession({+test("initial state: an already-audible system channel defers ownership stop", () => {+ const harness = createHarness();+ harness.controller.beginSession({sessionId: "s1",eligible: true,reliable: true,@@ -562,12 +408,12 @@ test("beginSession seeds the initial audio state so an already-audible system chmicActive: false,systemActive: true,});- h.runFor(OWNERSHIP_MIN_ACTIVE_MS);+ harness.runFor(OWNERSHIP_MIN_ACTIVE_MS);- micReleased(h.controller);- h.runFor(COUNTDOWN_MS);- assert.deepEqual(h.countdowns, []);+ micReleased(harness.controller);+ assert.deepEqual(harness.stops, []);- audio(h.controller, false, false);- assert.equal(h.countdowns.length, 1);+ audio(harness.controller, false, false);+ harness.runFor(OWNERSHIP_CONFIRM_MS);+ assert.deepEqual(harness.stops, [{ sessionId: "s1", reason: "mic-released" }]);});diff --git a/test/helpers/meetingAutoEndKeep.test.js b/test/helpers/meetingAutoEndKeep.test.jsdeleted file mode 100644index 13b469a2c..000000000--- a/test/helpers/meetingAutoEndKeep.test.js+++ /dev/null@@ -1,46 +0,0 @@-const test = require("node:test");-const assert = require("node:assert/strict");--const {- keepMeetingRecordingSession,- registerMeetingAutoEndKeepHandler,-} = require("../../src/helpers/meetingAutoEndKeep");--test("keep-recording IPC validation rejects invalid and stale sessions", () => {- const requestedSessions = [];- const engine = {- keepRecordingSession: (sessionId) => {- requestedSessions.push(sessionId);- return sessionId === "meeting-2";- },- };-- assert.deepEqual(keepMeetingRecordingSession(engine, ""), {- success: false,- reason: "invalid-session",- });- assert.deepEqual(keepMeetingRecordingSession(engine, "meeting-1"), {- success: false,- reason: "stale-session",- });- assert.deepEqual(keepMeetingRecordingSession(engine, "meeting-2"), { success: true });- assert.deepEqual(requestedSessions, ["meeting-1", "meeting-2"]);-});--test("main IPC registers Keep and resolves the current engine at invocation time", async () => {- const handlers = new Map();- const ipcMain = {- handle: (channel, handler) => handlers.set(channel, handler),- };- let engine = { keepRecordingSession: () => false };- registerMeetingAutoEndKeepHandler(ipcMain, () => engine);- const handler = handlers.get("meeting-auto-end-keep");-- assert.deepEqual(await handler({}, "meeting-1"), {- success: false,- reason: "stale-session",- });-- engine = { keepRecordingSession: (sessionId) => sessionId === "meeting-2" };- assert.deepEqual(await handler({}, "meeting-2"), { success: true });-});diff --git a/test/helpers/meetingAutoEndLifecycle.test.js b/test/helpers/meetingAutoEndLifecycle.test.jsnew file mode 100644index 000000000..276d53898--- /dev/null+++ b/test/helpers/meetingAutoEndLifecycle.test.js@@ -0,0 +1,113 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const {+ completeMeetingAutoEndSession,+ respondToMeetingAutoEndNotification,+ registerMeetingAutoEndLifecycleHandlers,+} = require("../../src/helpers/meetingAutoEndLifecycle");++test("stop-completion validation rejects invalid, stale, and non-owning sessions", async () => {+ const owner = { id: "owner" };+ const calls = [];+ const engine = {+ completeAutoEndSession: async (sessionId, sender) => {+ calls.push({ sessionId, sender });+ return sessionId === "meeting-2" && sender === owner;+ },+ };++ assert.deepEqual(await completeMeetingAutoEndSession(engine, "", owner), {+ success: false,+ reason: "invalid-session",+ });+ assert.deepEqual(await completeMeetingAutoEndSession(engine, "meeting-1", owner), {+ success: false,+ reason: "stale-session",+ });+ assert.deepEqual(await completeMeetingAutoEndSession(engine, "meeting-2", {}), {+ success: false,+ reason: "stale-session",+ });+ assert.deepEqual(await completeMeetingAutoEndSession(engine, "meeting-2", owner), {+ success: true,+ });+ assert.deepEqual(calls, [+ { sessionId: "meeting-1", sender: owner },+ { sessionId: "meeting-2", sender: {} },+ { sessionId: "meeting-2", sender: owner },+ ]);+});++test("overlay response validation accepts only restart or dismiss for a live offer", () => {+ const overlay = { id: "overlay" };+ const calls = [];+ const engine = {+ respondToAutoEndNotification: (sessionId, action, sender) => {+ calls.push({ sessionId, action, sender });+ return sessionId === "meeting-2" && action === "restart" && sender === overlay;+ },+ };++ assert.deepEqual(respondToMeetingAutoEndNotification(engine, "", "restart", overlay), {+ success: false,+ reason: "invalid-session",+ });+ assert.deepEqual(respondToMeetingAutoEndNotification(engine, "meeting-2", "keep", overlay), {+ success: false,+ reason: "invalid-action",+ });+ assert.deepEqual(respondToMeetingAutoEndNotification(engine, "meeting-1", "dismiss", overlay), {+ success: false,+ reason: "stale-session",+ });+ assert.deepEqual(respondToMeetingAutoEndNotification(engine, "meeting-2", "restart", overlay), {+ success: true,+ });+ assert.deepEqual(calls, [+ { sessionId: "meeting-1", action: "dismiss", sender: overlay },+ { sessionId: "meeting-2", action: "restart", sender: overlay },+ ]);+});++test("main IPC resolves the current engine and scopes both actions to event.sender", async () => {+ const handlers = new Map();+ const ipcMain = {+ handle: (channel, handler) => handlers.set(channel, handler),+ };+ const sender = { id: "renderer" };+ const calls = [];+ let engine = {+ completeAutoEndSession: async () => false,+ respondToAutoEndNotification: () => false,+ };+ registerMeetingAutoEndLifecycleHandlers(ipcMain, () => engine);++ assert.deepEqual(+ await handlers.get("meeting-auto-end-completed")({ sender }, "meeting-1"),+ { success: false, reason: "stale-session" }+ );++ engine = {+ completeAutoEndSession: async (sessionId, eventSender) => {+ calls.push(["completed", sessionId, eventSender]);+ return true;+ },+ respondToAutoEndNotification: (sessionId, action, eventSender) => {+ calls.push(["respond", sessionId, action, eventSender]);+ return true;+ },+ };+ assert.deepEqual(+ await handlers.get("meeting-auto-end-completed")({ sender }, "meeting-2"),+ { success: true }+ );+ assert.deepEqual(+ await handlers.get("meeting-auto-end-respond")({ sender }, "meeting-2", "dismiss"),+ { success: true }+ );+ assert.deepEqual(calls, [+ ["completed", "meeting-2", sender],+ ["respond", "meeting-2", "dismiss", sender],+ ]);+});diff --git a/test/helpers/meetingDetectionEngineAutoEnd.test.js b/test/helpers/meetingDetectionEngineAutoEnd.test.jsindex a1657f51e..3538eb0f0 100644--- a/test/helpers/meetingDetectionEngineAutoEnd.test.js+++ b/test/helpers/meetingDetectionEngineAutoEnd.test.js@@ -17,14 +17,16 @@ const MeetingDetectionEngine = require("../../src/helpers/meetingDetectionEngineconst createMeetingAutoEndController = require("../../src/helpers/meetingAutoEndController");Module._load = originalLoad;-const { COUNTDOWN_MS, SILENCE_WINDOW_MS, FAST_SILENCE_MS, OWNERSHIP_MIN_ACTIVE_MS } =+const { SILENCE_WINDOW_MS, FAST_SILENCE_MS, OWNERSHIP_MIN_ACTIVE_MS, OWNERSHIP_CONFIRM_MS } =createMeetingAutoEndController;const TICK_MS = 1000;+const {+ AUTO_END_RESTART_WINDOW_MS: RESTART_WINDOW_MS,+ AUTO_END_RESTART_GRACE_MS,+ AUTO_END_RESTART_CLAIM_MS,+} = MeetingDetectionEngine;-// Fake clock with a single interval slot: the engine's 1s auto-end ticker.-// advance() steps the clock a second at a time and fires the interval so long-// spans never look like a sleep gap.const createClock = () => {let now = 10_000;const intervals = new Map();@@ -52,7 +54,6 @@ const createClock = () => {};};-// A buffer whose RMS is unmistakably above the activity thresholds.const LOUD_CHUNK = (() => {const buffer = Buffer.alloc(1600);for (let i = 0; i < 800; i += 1) buffer.writeInt16LE(3000, i * 2);@@ -108,7 +109,6 @@ class FakeMeetingProcessDetector extends EventEmitter {return this.detected.map((processKey) => ({ processKey, appName: processKey }));}- // Mirrors the real detector: the ended key is removed before the event fires.endProcess(processKey) {this.detected = this.detected.filter((key) => key !== processKey);this.emit("meeting-process-ended", { processKey, appName: processKey });@@ -119,13 +119,19 @@ function createEngine(windowManagerOverrides = {}) {const clock = createClock();const audioActivityDetector = new FakeAudioActivityDetector();const meetingProcessDetector = new FakeMeetingProcessDetector();- const shownCountdowns = [];- const dismissedCountdowns = [];+ const autoEndNotifications = [];+ const dismissedAutoEndNotifications = [];const shownNotifications = [];+ const overlayWebContents = { kind: "meeting-notification" };const windowManager = {notificationPrefs: {},- showMeetingAutoEndCountdown: (countdown) => shownCountdowns.push(countdown),- dismissMeetingAutoEndCountdown: (sessionId) => dismissedCountdowns.push(sessionId),+ showMeetingAutoEndNotification: async (notification) => {+ autoEndNotifications.push(notification);+ return true;+ },+ dismissMeetingAutoEndNotification: (sessionId) =>+ dismissedAutoEndNotifications.push(sessionId),+ isMeetingNotificationSender: (sender) => sender === overlayWebContents,showMeetingNotification: (notification) => shownNotifications.push(notification),...windowManagerOverrides,};@@ -152,17 +158,30 @@ function createEngine(windowManagerOverrides = {}) {return {audioActivityDetector,- meetingProcessDetector,+ autoEndNotifications,clock,- dismissedCountdowns,+ dismissedAutoEndNotifications,engine,- shownCountdowns,- shownNotifications,+ meetingProcessDetector,micState,+ overlayWebContents,owner,+ shownNotifications,};}+async function triggerOwnershipStop(engineHarness, ownerWebContents) {+ await engineHarness.engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents,+ systemAudioAvailable: true,+ });+ engineHarness.clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ engineHarness.micState(true, false);+ engineHarness.clock.advance(OWNERSHIP_CONFIRM_MS);+}+test("detection prompts retain their existing payload with a detection discriminator", () => {const { engine, shownNotifications } = createEngine();const event = {@@ -208,8 +227,8 @@ test("keeps audio ownership detection running while an eligible recording is actassert.equal(audioActivityDetector.running, false);});-test("keeps the process detector running for an eligible session while processDetection is off", async () => {- const { meetingProcessDetector, engine, owner } = createEngine();+test("keeps the process detector running for eligible auto-end sessions", async () => {+ const { engine, meetingProcessDetector, owner } = createEngine();engine.setPreferences({ processDetection: false });assert.equal(meetingProcessDetector.running, false);@@ -227,334 +246,329 @@ test("keeps the process detector running for an eligible session while processDe});test("does not arm auto-end until system audio capture is confirmed", async () => {- const { clock, engine, micState, owner, shownCountdowns } = createEngine();- const ownerWebContents = owner();+ const harness = createEngine();+ const messages = [];+ const ownerWebContents = harness.owner(messages);- await engine.beginRecordingSession({+ await harness.engine.beginRecordingSession({sessionId: "meeting-1",autoEndEligible: true,ownerWebContents,});- clock.advance(OWNERSHIP_MIN_ACTIVE_MS);- micState(true, false);- clock.advance(2 * COUNTDOWN_MS);-- assert.deepEqual(shownCountdowns, []);+ harness.clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ harness.micState(true, false);+ assert.deepEqual(messages, []);assert.equal(- await engine.setRecordingSystemAudioAvailable("meeting-1", true, owner()),- false,- "a stale renderer must not arm another renderer's recording"- );- assert.equal(- await engine.setRecordingSystemAudioAvailable("meeting-1", true, ownerWebContents),+ await harness.engine.setRecordingSystemAudioAvailable("meeting-1", true, ownerWebContents),true);- clock.advance(OWNERSHIP_MIN_ACTIVE_MS);- micState(true, false);+ harness.clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ harness.micState(true, false);+ harness.clock.advance(OWNERSHIP_CONFIRM_MS);- assert.equal(shownCountdowns.length, 1);- engine.stop();+ assert.deepEqual(messages, [+ {+ channel: "meeting-auto-end-requested",+ payload: { sessionId: "meeting-1", reason: "mic-released" },+ },+ ]);+ harness.engine.stop();});-test("shows and dismisses the countdown from reliable external mic changes", async () => {- const { clock, dismissedCountdowns, engine, micState, owner, shownCountdowns } = createEngine();+test("reliable mic release requests an immediate stop without showing the recovery notice", async () => {+ const harness = createEngine();+ const messages = [];- await engine.beginRecordingSession({- sessionId: "meeting-1",- autoEndEligible: true,- ownerWebContents: owner(),- systemAudioAvailable: true,- });- clock.advance(OWNERSHIP_MIN_ACTIVE_MS);- micState(true, false);- micState(true, true);+ await triggerOwnershipStop(harness, harness.owner(messages));- assert.deepEqual(shownCountdowns, [- { sessionId: "meeting-1", expiresAt: clock.now() + COUNTDOWN_MS, reason: "mic-released" },+ assert.deepEqual(messages, [+ {+ channel: "meeting-auto-end-requested",+ payload: { sessionId: "meeting-1", reason: "mic-released" },+ },]);- assert.deepEqual(dismissedCountdowns, ["meeting-1"]);- engine.stop();+ assert.deepEqual(harness.autoEndNotifications, []);+ harness.engine.stop();});-test("system activity from meeting chunks defers the ownership countdown until quiet", async () => {- const { clock, engine, micState, owner, shownCountdowns } = createEngine();+test("system activity from meeting chunks defers ownership stop until quiet", async () => {+ const harness = createEngine();+ const messages = [];- await engine.beginRecordingSession({+ await harness.engine.beginRecordingSession({sessionId: "meeting-1",autoEndEligible: true,- ownerWebContents: owner(),+ ownerWebContents: harness.owner(messages),systemAudioAvailable: true,});- clock.advance(OWNERSHIP_MIN_ACTIVE_MS);- engine.recordMeetingAudioChunk("system", LOUD_CHUNK);- clock.advance(TICK_MS);-- micState(true, false);- clock.advance(TICK_MS);- assert.deepEqual(shownCountdowns, [], "remote audio still playing");-- // The system channel ages out once no more loud chunks arrive.- clock.advance(5 * TICK_MS);- assert.equal(shownCountdowns.length, 1);- assert.equal(shownCountdowns[0].reason, "mic-released");- engine.stop();-});+ harness.clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ harness.engine.recordMeetingAudioChunk("system", LOUD_CHUNK);+ harness.clock.advance(TICK_MS);-test("meeting audio chunks are ignored before the controller session begins and after it ends", async () => {- const { clock, engine, micState, owner, shownCountdowns } = createEngine();+ harness.micState(true, false);+ harness.clock.advance(TICK_MS);+ assert.deepEqual(messages, []);- // Streaming starts before beginRecordingSession is reached in main.- engine.recordMeetingAudioChunk("system", LOUD_CHUNK);- await engine.beginRecordingSession({- sessionId: "meeting-1",- autoEndEligible: true,- ownerWebContents: owner(),- systemAudioAvailable: true,- });- clock.advance(OWNERSHIP_MIN_ACTIVE_MS);- micState(true, false);- assert.equal(- shownCountdowns.length,- 1,- "the pre-session chunk must not read as live system audio"- );+ // Still inside the confirm window even once the system tail expires.+ harness.clock.advance(OWNERSHIP_CONFIRM_MS - TICK_MS);+ assert.deepEqual(messages, []);- engine.endRecordingSession("meeting-1");- assert.doesNotThrow(() => engine.recordMeetingAudioChunk("mic", LOUD_CHUNK));- clock.advance(2 * SILENCE_WINDOW_MS);- assert.equal(shownCountdowns.length, 1);+ harness.clock.advance(5 * TICK_MS + OWNERSHIP_CONFIRM_MS);+ assert.equal(messages.length, 1);+ assert.equal(messages[0].payload.reason, "mic-released");+ harness.engine.stop();});-test("fallback silence prompts and forwards the reason to the countdown and stop request", async () => {- const { audioActivityDetector, clock, engine, owner, shownCountdowns } = createEngine();+test("fallback silence immediately requests a scoped stop with its reason", async () => {+ const harness = createEngine();const messages = [];- audioActivityDetector.externalMicState = { reliable: true, externalMicActive: false };+ harness.audioActivityDetector.externalMicState = {+ reliable: true,+ externalMicActive: false,+ };- await engine.beginRecordingSession({+ await harness.engine.beginRecordingSession({sessionId: "meeting-1",autoEndEligible: true,- ownerWebContents: owner(messages),+ ownerWebContents: harness.owner(messages),systemAudioAvailable: true,});- clock.advance(SILENCE_WINDOW_MS);+ harness.clock.advance(SILENCE_WINDOW_MS);- assert.equal(shownCountdowns.length, 1);- assert.equal(shownCountdowns[0].reason, "silence");- clock.advance(COUNTDOWN_MS);assert.deepEqual(messages, [{channel: "meeting-auto-end-requested",payload: { sessionId: "meeting-1", reason: "silence" },},]);- engine.stop();+ harness.engine.stop();});-test("meeting-process-ended tightens the silence window only when no tracked app remains", async () => {- const { audioActivityDetector, clock, engine, meetingProcessDetector, owner, shownCountdowns } =- createEngine();- audioActivityDetector.externalMicState = { reliable: false, externalMicActive: false };- meetingProcessDetector.detected = ["zoom", "teams"];+test("only the last tracked meeting process exiting arms the fast stop", async () => {+ const harness = createEngine();+ const messages = [];+ harness.audioActivityDetector.externalMicState = {+ reliable: false,+ externalMicActive: false,+ };+ harness.meetingProcessDetector.detected = ["zoom", "teams"];- await engine.beginRecordingSession({+ await harness.engine.beginRecordingSession({sessionId: "meeting-1",autoEndEligible: true,- ownerWebContents: owner(),+ ownerWebContents: harness.owner(messages),systemAudioAvailable: true,});- meetingProcessDetector.endProcess("teams");- clock.advance(FAST_SILENCE_MS + TICK_MS);- assert.deepEqual(shownCountdowns, [], "Zoom is still running");+ harness.meetingProcessDetector.endProcess("teams");+ harness.clock.advance(FAST_SILENCE_MS + TICK_MS);+ assert.deepEqual(messages, []);- meetingProcessDetector.endProcess("zoom");- clock.advance(FAST_SILENCE_MS);- assert.equal(shownCountdowns.length, 1);- assert.equal(shownCountdowns[0].reason, "process-exit");- engine.stop();+ harness.meetingProcessDetector.endProcess("zoom");+ harness.clock.advance(FAST_SILENCE_MS);+ assert.equal(messages.length, 1);+ assert.equal(messages[0].payload.reason, "process-exit");+ harness.engine.stop();});-test("reliability loss dismisses the countdown and prevents auto-stop", async () => {- const { clock, dismissedCountdowns, engine, micState, owner } = createEngine();+test("the recovery notice appears only after the owning renderer confirms stop completion", async () => {+ const harness = createEngine();const messages = [];+ const ownerWebContents = harness.owner(messages);+ await triggerOwnershipStop(harness, ownerWebContents);- await engine.beginRecordingSession({- sessionId: "meeting-1",- autoEndEligible: true,- ownerWebContents: owner(messages),- systemAudioAvailable: true,- });- clock.advance(OWNERSHIP_MIN_ACTIVE_MS);- micState(true, false);- clock.advance(30_000);-- micState(false, false);- clock.advance(COUNTDOWN_MS);+ assert.deepEqual(harness.autoEndNotifications, []);+ harness.engine.endRecordingSession("meeting-1");- assert.deepEqual(dismissedCountdowns, ["meeting-1"]);- assert.deepEqual(messages, []);- engine.stop();+ assert.equal(+ await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents),+ true+ );+ assert.deepEqual(harness.autoEndNotifications, [+ {+ sessionId: "meeting-1",+ reason: "mic-released",+ expiresAt: harness.clock.now() + RESTART_WINDOW_MS,+ },+ ]);+ harness.engine.stop();});-test("countdown presentation failure keeps the recording active", async () => {- const { clock, engine, micState, owner } = createEngine({- showMeetingAutoEndCountdown: () => Promise.reject(new Error("notification load failed")),- });- const messages = [];+test("stop completion rejects a stale session, wrong owner, or still-live recording", async () => {+ const harness = createEngine();+ const ownerWebContents = harness.owner();+ await triggerOwnershipStop(harness, ownerWebContents);- await engine.beginRecordingSession({- sessionId: "meeting-1",- autoEndEligible: true,- ownerWebContents: owner(messages),- systemAudioAvailable: true,- });- clock.advance(OWNERSHIP_MIN_ACTIVE_MS);- micState(true, false);- await Promise.resolve();- await Promise.resolve();- clock.advance(2 * COUNTDOWN_MS);+ assert.equal(await harness.engine.completeAutoEndSession("other", ownerWebContents), false);+ assert.equal(await harness.engine.completeAutoEndSession("meeting-1", harness.owner()), false);+ assert.equal(await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents), false);- assert.deepEqual(messages, []);- engine.stop();+ harness.engine.endRecordingSession("meeting-1");+ assert.equal(await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents), true);+ harness.engine.stop();});-test("expiry requests one stop from the renderer that owns the current session", async () => {- const { clock, dismissedCountdowns, engine, micState, owner } = createEngine();+test("restart response is owner-scoped, single-use, and dismisses the notice", async () => {+ const harness = createEngine();const messages = [];+ const ownerWebContents = harness.owner(messages);+ await triggerOwnershipStop(harness, ownerWebContents);+ harness.engine.endRecordingSession("meeting-1");+ await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents);- await engine.beginRecordingSession({- sessionId: "meeting-1",- autoEndEligible: true,- ownerWebContents: owner(messages),- systemAudioAvailable: true,+ assert.equal(+ harness.engine.respondToAutoEndNotification(+ "meeting-1",+ "restart",+ harness.overlayWebContents+ ),+ true+ );+ assert.deepEqual(messages.at(-1), {+ channel: "meeting-auto-end-restart-requested",+ payload: { sessionId: "meeting-1" },});- clock.advance(OWNERSHIP_MIN_ACTIVE_MS);- micState(true, false);- clock.advance(3 * COUNTDOWN_MS);-- assert.deepEqual(messages, [- {- channel: "meeting-auto-end-requested",- payload: { sessionId: "meeting-1", reason: "mic-released" },- },- ]);- assert.deepEqual(dismissedCountdowns, ["meeting-1"]);- engine.stop();+ assert.deepEqual(harness.dismissedAutoEndNotifications, ["meeting-1"]);+ assert.equal(+ harness.engine.respondToAutoEndNotification(+ "meeting-1",+ "restart",+ harness.overlayWebContents+ ),+ false+ );+ harness.engine.stop();});-test("replacement cancels the old countdown and stale end requests preserve the new session", async () => {- const { clock, dismissedCountdowns, engine, micState } = createEngine();+test("dismiss response clears the recovery offer without restarting", async () => {+ const harness = createEngine();const messages = [];+ const ownerWebContents = harness.owner(messages);+ await triggerOwnershipStop(harness, ownerWebContents);+ harness.engine.endRecordingSession("meeting-1");+ await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents);- await engine.beginRecordingSession({- sessionId: "meeting-1",- autoEndEligible: true,- ownerWebContents: { isDestroyed: () => false, send: () => messages.push("meeting-1") },- systemAudioAvailable: true,- });- clock.advance(OWNERSHIP_MIN_ACTIVE_MS);- micState(true, false);-- await engine.beginRecordingSession({- sessionId: "meeting-2",- autoEndEligible: true,- ownerWebContents: { isDestroyed: () => false, send: () => messages.push("meeting-2") },- systemAudioAvailable: true,- });- assert.equal(engine.endRecordingSession("meeting-1"), false);- clock.advance(OWNERSHIP_MIN_ACTIVE_MS);- micState(true, false);- clock.advance(2 * COUNTDOWN_MS);-- assert.deepEqual(dismissedCountdowns, ["meeting-1", "meeting-2"]);- assert.deepEqual(messages, ["meeting-2"]);- engine.stop();+ assert.equal(+ harness.engine.respondToAutoEndNotification(+ "meeting-1",+ "dismiss",+ harness.overlayWebContents+ ),+ true+ );+ assert.equal(+ messages.some(({ channel }) => channel === "meeting-auto-end-restart-requested"),+ false+ );+ assert.deepEqual(harness.dismissedAutoEndNotifications, ["meeting-1"]);+ harness.engine.stop();});-test("an ineligible recording does not retain the audio detector", async () => {- const { audioActivityDetector, clock, engine, micState, owner, shownCountdowns } = createEngine();-- engine.setPreferences({ audioDetection: false });- await engine.beginRecordingSession({- sessionId: "personal-1",- autoEndEligible: false,- ownerWebContents: owner(),- });- micState(true, false);- clock.advance(2 * SILENCE_WINDOW_MS);+test("expired, wrong-sender, and invalid auto-end responses are rejected", async () => {+ const harness = createEngine();+ const messages = [];+ const ownerWebContents = harness.owner(messages);+ await triggerOwnershipStop(harness, ownerWebContents);+ harness.engine.endRecordingSession("meeting-1");+ await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents);- assert.equal(audioActivityDetector.running, false);- assert.deepEqual(shownCountdowns, []);- assert.equal(engine.endRecordingSession("personal-1"), true);+ assert.equal(+ harness.engine.respondToAutoEndNotification("meeting-1", "restart", {}),+ false+ );+ assert.equal(+ harness.engine.respondToAutoEndNotification(+ "meeting-1",+ "unknown",+ harness.overlayWebContents+ ),+ false+ );+ harness.clock.advance(RESTART_WINDOW_MS);+ assert.equal(+ harness.engine.respondToAutoEndNotification(+ "meeting-1",+ "restart",+ harness.overlayWebContents+ ),+ false+ );+ assert.equal(+ messages.some(({ channel }) => channel === "meeting-auto-end-restart-requested"),+ false+ );+ assert.deepEqual(harness.dismissedAutoEndNotifications, ["meeting-1"]);+ harness.engine.stop();});-test("keep recording suppresses prompts until fresh ownership evidence, only for the matching session", async () => {- const { clock, dismissedCountdowns, engine, micState, owner, shownCountdowns } = createEngine();+test("starting another recording invalidates an offered restart", async () => {+ const harness = createEngine();+ const firstOwner = harness.owner();+ await triggerOwnershipStop(harness, firstOwner);+ harness.engine.endRecordingSession("meeting-1");+ await harness.engine.completeAutoEndSession("meeting-1", firstOwner);- await engine.beginRecordingSession({- sessionId: "meeting-1",+ await harness.engine.beginRecordingSession({+ sessionId: "meeting-2",autoEndEligible: true,- ownerWebContents: owner(),+ ownerWebContents: harness.owner(),systemAudioAvailable: true,});- clock.advance(OWNERSHIP_MIN_ACTIVE_MS);- micState(true, false);- assert.equal(engine.keepRecordingSession("stale-session"), false);- assert.equal(engine.keepRecordingSession("meeting-1"), true);- assert.deepEqual(dismissedCountdowns, ["meeting-1"]);- clock.advance(2 * COUNTDOWN_MS);- assert.equal(shownCountdowns.length, 1, "no re-prompt without fresh evidence");-- micState(true, true);- clock.advance(OWNERSHIP_MIN_ACTIVE_MS);- micState(true, false);- assert.equal(shownCountdowns.length, 2, "a rejoined-and-left call re-prompts at once");- assert.equal(shownCountdowns[1].reason, "mic-released");- engine.stop();+ assert.deepEqual(harness.dismissedAutoEndNotifications, ["meeting-1"]);+ assert.equal(+ harness.engine.respondToAutoEndNotification(+ "meeting-1",+ "restart",+ harness.overlayWebContents+ ),+ false+ );+ harness.engine.stop();});-test("keep recording after countdown expiry reports a stale session", async () => {- const { clock, engine, micState, owner } = createEngine();-- await engine.beginRecordingSession({- sessionId: "meeting-1",- autoEndEligible: true,- ownerWebContents: owner(),- systemAudioAvailable: true,+test("notification load failure invalidates the completed restart offer", async () => {+ const harness = createEngine({+ showMeetingAutoEndNotification: async () => {+ throw new Error("notification load failed");+ },});- clock.advance(OWNERSHIP_MIN_ACTIVE_MS);- micState(true, false);- clock.advance(COUNTDOWN_MS);+ const ownerWebContents = harness.owner();+ await triggerOwnershipStop(harness, ownerWebContents);+ harness.engine.endRecordingSession("meeting-1");- assert.equal(engine.keepRecordingSession("meeting-1"), false);- engine.stop();+ assert.equal(+ await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents),+ false+ );+ assert.equal(+ harness.engine.respondToAutoEndNotification(+ "meeting-1",+ "restart",+ harness.overlayWebContents+ ),+ false+ );+ harness.engine.stop();});test("a legacy autoEnd preference cannot disable eligible meeting auto-end", async () => {- const { audioActivityDetector, clock, engine, micState, owner, shownCountdowns } = createEngine();- engine.setPreferences({ audioDetection: false, processDetection: false, autoEnd: false });- assert.deepEqual(engine.getPreferences(), {+ const harness = createEngine();+ const messages = [];+ harness.engine.setPreferences({ audioDetection: false, processDetection: false, autoEnd: false });+ assert.deepEqual(harness.engine.getPreferences(), {processDetection: false,audioDetection: false,});- await engine.beginRecordingSession({- sessionId: "meeting-1",- autoEndEligible: true,- ownerWebContents: owner(),- systemAudioAvailable: true,- });- assert.equal(audioActivityDetector.running, true);- assert.equal(clock.activeIntervals(), 1);-- clock.advance(OWNERSHIP_MIN_ACTIVE_MS);- micState(true, false);- assert.equal(shownCountdowns.length, 1);+ await triggerOwnershipStop(harness, harness.owner(messages));- engine.setPreferences({ autoEnd: false });- assert.equal(clock.activeIntervals(), 1);- engine.stop();+ assert.equal(harness.audioActivityDetector.running, true);+ assert.equal(harness.clock.activeIntervals(), 1);+ assert.equal(messages.length, 1);+ harness.engine.setPreferences({ autoEnd: false });+ assert.equal(harness.clock.activeIntervals(), 1);+ harness.engine.stop();});test("the auto-end ticker is cleared on session end and engine stop", async () => {@@ -590,18 +604,11 @@ test("ending with no tracked session allows teardown to proceed", async () => {ownerWebContents: owner(),systemAudioAvailable: true,});- // Quit-path engine stop clears the session while capture may still be live;- // a scoped stop afterwards must not be treated as stale or streams leak.engine.stop();assert.equal(engine.endRecordingSession("meeting-1"), true);});-// The user-recording flag is shared with dictation, so a dictation ending-// mid-meeting clears it while the recording is still live. Without the engine's-// own session as a gate, the next detection would bypass the queue and its-// prompt would replace a visible auto-end countdown card — the countdown then-// runs on invisibly and stops the recording without a chance to keep it.const POST_RECORDING_COOLDOWN_MS = 2500;const nextMeetingReminder = (clock) => ({@@ -610,7 +617,7 @@ const nextMeetingReminder = (clock) => ({start_time: new Date(clock.now() + 60_000).toISOString(),});-test("a detection during a live recording session is queued even after the user-recording flag is cleared", async (t) => {+test("a detection during a live recording remains queued after the shared recording flag clears", async (t) => {t.mock.timers.enable({ apis: ["setTimeout"] });const { clock, engine, owner, shownNotifications } = createEngine();engine.setUserRecording(true);@@ -621,23 +628,19 @@ test("a detection during a live recording session is queued even after the user-systemAudioAvailable: true,});- // A dictation ended mid-meeting: the shared flag clears and its cooldown runs out.engine.setUserRecording(false);t.mock.timers.tick(POST_RECORDING_COOLDOWN_MS);-engine.handleCalendarReminder(nextMeetingReminder(clock));- assert.equal(shownNotifications.length, 0, "no prompt may surface while the recording is live");+ assert.equal(shownNotifications.length, 0);- // The recording ends the way ipcHandlers ends it; the held prompt surfaces then.engine.endRecordingSession("meeting-1");engine.setUserRecording(false);t.mock.timers.tick(POST_RECORDING_COOLDOWN_MS);assert.equal(shownNotifications.length, 1);- assert.equal(shownNotifications[0].detectionId, "calendar:next");engine.stop();});-test("a post-dictation queue flush holds queued detections while the recording session is live", async (t) => {+test("a post-dictation queue flush holds detections while the meeting session is live", async (t) => {t.mock.timers.enable({ apis: ["setTimeout"] });const { clock, engine, owner, shownNotifications } = createEngine();engine.setUserRecording(true);@@ -649,11 +652,9 @@ test("a post-dictation queue flush holds queued detections while the recording s});engine.handleCalendarReminder(nextMeetingReminder(clock));- assert.equal(shownNotifications.length, 0, "queued behind the user-recording gate");-engine.setUserRecording(false);t.mock.timers.tick(POST_RECORDING_COOLDOWN_MS);- assert.equal(shownNotifications.length, 0, "the flush must not surface it mid-recording");+ assert.equal(shownNotifications.length, 0);engine.endRecordingSession("meeting-1");engine.setUserRecording(false);@@ -662,10 +663,6 @@ test("a post-dictation queue flush holds queued detections while the recording sengine.stop();});-// "Take notes" / the meeting hotkey / calendar Join set meeting mode when they-// create the note, and until now only the narrow layout's "Back to notes"-// button ever cleared it. In the wide layout that left every later mic,-// process, and calendar detection suppressed for the rest of the app session.test("a detection-started recording re-enables prompts once its session ends", async (t) => {t.mock.timers.enable({ apis: ["setTimeout"] });const { audioActivityDetector, clock, engine, owner, shownNotifications } = createEngine();@@ -681,17 +678,17 @@ test("a detection-started recording re-enables prompts once its session ends", aengine.endRecordingSession("meeting-1");engine.setUserRecording(false);t.mock.timers.tick(POST_RECORDING_COOLDOWN_MS);-audioActivityDetector.emit("sustained-audio-detected", {durationMs: 2000,detectedAt: clock.now(),});- assert.equal(shownNotifications.length, 1, "the next call must prompt again");++ assert.equal(shownNotifications.length, 1);assert.equal(shownNotifications[0].detectionId, "audio:sustained-audio");engine.stop();});-test("the next meeting's reminder prompts after a detection-started recording ends", async (t) => {+test("the next reminder prompts after a detection-started recording ends", async (t) => {t.mock.timers.enable({ apis: ["setTimeout"] });const { clock, engine, owner, shownNotifications } = createEngine();engine.setMeetingModeActive(true);@@ -706,14 +703,14 @@ test("the next meeting's reminder prompts after a detection-started recording enengine.endRecordingSession("meeting-1");engine.setUserRecording(false);t.mock.timers.tick(POST_RECORDING_COOLDOWN_MS);-engine.handleCalendarReminder(nextMeetingReminder(clock));- assert.equal(shownNotifications.length, 1, "no longer suppressed as meeting-mode noise");++ assert.equal(shownNotifications.length, 1);assert.equal(shownNotifications[0].detectionId, "calendar:next");engine.stop();});-test("meeting mode still suppresses prompts while the detection-started recording is live", async (t) => {+test("meeting mode still suppresses prompts while a detection-started recording is live", async (t) => {t.mock.timers.enable({ apis: ["setTimeout"] });const { audioActivityDetector, clock, engine, owner, shownNotifications } = createEngine();engine.setMeetingModeActive(true);@@ -735,3 +732,356 @@ test("meeting mode still suppresses prompts while the detection-started recordinassert.equal(shownNotifications.length, 0);engine.stop();});++test("an explicit restart grants the new session a grace period before auto-end can fire again", async () => {+ const harness = createEngine();+ const messages = [];+ const ownerWebContents = harness.owner(messages);+ await triggerOwnershipStop(harness, ownerWebContents);+ harness.engine.endRecordingSession("meeting-1");+ await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents);+ assert.equal(+ harness.engine.respondToAutoEndNotification(+ "meeting-1",+ "restart",+ harness.overlayWebContents+ ),+ true+ );++ messages.length = 0;+ harness.audioActivityDetector.externalMicState = {+ reliable: true,+ externalMicActive: false,+ };+ await harness.engine.beginRecordingSession({+ sessionId: "meeting-2",+ autoEndEligible: true,+ ownerWebContents,+ systemAudioAvailable: true,+ });++ // The user just said the meeting is still live; silence alone must not+ // immediately undo that.+ harness.clock.advance(AUTO_END_RESTART_GRACE_MS - TICK_MS);+ assert.deepEqual(messages, []);++ harness.clock.advance(SILENCE_WINDOW_MS + TICK_MS);+ assert.deepEqual(messages, [+ {+ channel: "meeting-auto-end-requested",+ payload: { sessionId: "meeting-2", reason: "silence" },+ },+ ]);+ harness.engine.stop();+});++test("the restart grace is single-use and does not leak into an unrelated later recording", async () => {+ const harness = createEngine();+ const messages = [];+ const ownerWebContents = harness.owner(messages);+ await triggerOwnershipStop(harness, ownerWebContents);+ harness.engine.endRecordingSession("meeting-1");+ await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents);+ harness.engine.respondToAutoEndNotification(+ "meeting-1",+ "restart",+ harness.overlayWebContents+ );++ harness.audioActivityDetector.externalMicState = {+ reliable: true,+ externalMicActive: false,+ };+ await harness.engine.beginRecordingSession({+ sessionId: "meeting-2",+ autoEndEligible: true,+ ownerWebContents,+ systemAudioAvailable: true,+ });+ harness.engine.endRecordingSession("meeting-2");++ messages.length = 0;+ await harness.engine.beginRecordingSession({+ sessionId: "meeting-3",+ autoEndEligible: true,+ ownerWebContents,+ systemAudioAvailable: true,+ });+ harness.clock.advance(SILENCE_WINDOW_MS + TICK_MS);+ assert.deepEqual(messages, [+ {+ channel: "meeting-auto-end-requested",+ payload: { sessionId: "meeting-3", reason: "silence" },+ },+ ]);+ harness.engine.stop();+});++test("a queued detection cannot replace a live restart offer", async () => {+ const harness = createEngine();+ const messages = [];+ const ownerWebContents = harness.owner(messages);+ await triggerOwnershipStop(harness, ownerWebContents);++ // A back-to-back meeting reminder arriving mid-recording is queued, not shown.+ harness.engine.handleCalendarReminder({+ id: "calendar-next",+ summary: "Next call",+ start_time: new Date(harness.clock.now()).toISOString(),+ });+ assert.deepEqual(harness.shownNotifications, []);++ harness.engine.endRecordingSession("meeting-1");+ harness.engine.setUserRecording(false);+ await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents);+ assert.equal(harness.autoEndNotifications.length, 1);++ // What the post-recording cooldown does when it fires 2.5s after the stop.+ harness.engine._flushNotificationQueue();+ assert.deepEqual(harness.shownNotifications, []);+ assert.equal(+ harness.engine.respondToAutoEndNotification(+ "meeting-1",+ "restart",+ harness.overlayWebContents+ ),+ true+ );+ harness.engine.stop();+});++test("a detection queued behind a restart offer is delivered once the offer resolves", async () => {+ const harness = createEngine();+ const messages = [];+ const ownerWebContents = harness.owner(messages);+ await triggerOwnershipStop(harness, ownerWebContents);++ harness.engine.handleCalendarReminder({+ id: "calendar-next",+ summary: "Next call",+ start_time: new Date(harness.clock.now()).toISOString(),+ });+ harness.engine.endRecordingSession("meeting-1");+ harness.engine.setUserRecording(false);+ await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents);+ harness.engine._flushNotificationQueue();+ assert.deepEqual(harness.shownNotifications, []);++ harness.engine.respondToAutoEndNotification(+ "meeting-1",+ "dismiss",+ harness.overlayWebContents+ );++ assert.equal(harness.shownNotifications.length, 1);+ assert.equal(harness.shownNotifications[0].detectionId, "calendar:calendar-next");+ harness.engine.stop();+});++test("a recovery notice that does not report success invalidates the restart offer", async () => {+ const harness = createEngine({ showMeetingAutoEndNotification: async () => undefined });+ const messages = [];+ const ownerWebContents = harness.owner(messages);+ await triggerOwnershipStop(harness, ownerWebContents);+ harness.engine.endRecordingSession("meeting-1");++ assert.equal(await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents), false);+ assert.equal(+ harness.engine.respondToAutoEndNotification(+ "meeting-1",+ "restart",+ harness.overlayWebContents+ ),+ false+ );+ harness.engine.stop();+});++// endRecordingSession returns false only when a *different* session is live —+// the one case where the caller must not tear down shared capture. A stale stop+// arriving after a replacement (the old renderer unwinding) would otherwise+// kill the recording that just took over.+test("a stale end request is refused and leaves the replacement session recording", async () => {+ const harness = createEngine();+ const messages = [];+ const ownerWebContents = harness.owner(messages);++ await harness.engine.beginRecordingSession({+ sessionId: "meeting-1",+ autoEndEligible: true,+ ownerWebContents,+ systemAudioAvailable: true,+ });+ harness.clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ harness.micState(true, false);++ await harness.engine.beginRecordingSession({+ sessionId: "meeting-2",+ autoEndEligible: true,+ ownerWebContents,+ systemAudioAvailable: true,+ });++ assert.equal(harness.engine.endRecordingSession("meeting-1"), false);++ harness.clock.advance(OWNERSHIP_MIN_ACTIVE_MS);+ harness.micState(true, false);+ harness.clock.advance(OWNERSHIP_CONFIRM_MS);++ assert.deepEqual(messages, [+ {+ channel: "meeting-auto-end-requested",+ payload: { sessionId: "meeting-2", reason: "mic-released" },+ },+ ]);+ harness.engine.stop();+});++// The window manager destroys a notification window on paths that cannot tell+// the engine about it (_hideNormalAppSurfaces on re-auth, a late detection+// response landing on a replaced card): dismissMeetingNotification() nulls its+// window reference before close(), so the "closed" handler early-returns, and+// it cancels the dismiss timer, so the timeout handler never runs either. The+// offer therefore has to expire on its own clock, or it gates every meeting+// prompt for the rest of the app session.+test("an offer whose card vanished without notice stops gating the queue once it expires", async () => {+ const harness = createEngine();+ const ownerWebContents = harness.owner([]);+ await triggerOwnershipStop(harness, ownerWebContents);++ harness.engine.handleCalendarReminder({+ id: "calendar-next",+ summary: "Next call",+ start_time: new Date(harness.clock.now()).toISOString(),+ });+ harness.engine.endRecordingSession("meeting-1");+ harness.engine.setUserRecording(false);+ await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents);++ harness.engine._flushNotificationQueue();+ assert.deepEqual(harness.shownNotifications, []);++ harness.clock.advance(RESTART_WINDOW_MS + TICK_MS);+ harness.engine._flushNotificationQueue();+ assert.equal(harness.shownNotifications.length, 1);+ assert.equal(harness.shownNotifications[0].detectionId, "calendar:calendar-next");+ harness.engine.stop();+});++// No setUserRecording here: its 2.5s cooldown is itself a queue gate, and this+// test is about the offer gate alone.+test("an expired offer no longer queues a fresh detection", async () => {+ const harness = createEngine();+ const ownerWebContents = harness.owner([]);+ await triggerOwnershipStop(harness, ownerWebContents);+ harness.engine.endRecordingSession("meeting-1");+ await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents);++ harness.clock.advance(RESTART_WINDOW_MS + TICK_MS);+ harness.engine.handleCalendarReminder({+ id: "calendar-late",+ summary: "Later call",+ start_time: new Date(harness.clock.now()).toISOString(),+ });++ assert.equal(harness.shownNotifications.length, 1);+ assert.equal(harness.shownNotifications[0].detectionId, "calendar:calendar-late");+ harness.engine.stop();+});++// The renderer can drop a restart it accepted (its context died with a reload,+// or a manual recording won the race). Main cannot see that, so the grace it+// banks has to lapse on its own rather than waiting to be claimed by whatever+// recording happens to start next.+test("a restart grace nobody claims in time does not suppress a later recording", async () => {+ const harness = createEngine();+ const messages = [];+ const ownerWebContents = harness.owner(messages);+ await triggerOwnershipStop(harness, ownerWebContents);+ harness.engine.endRecordingSession("meeting-1");+ await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents);+ assert.equal(+ harness.engine.respondToAutoEndNotification("meeting-1", "restart", harness.overlayWebContents),+ true+ );++ // The restart never reaches startRecording; the user opens an unrelated+ // meeting note well after the restart could plausibly have begun.+ harness.clock.advance(AUTO_END_RESTART_CLAIM_MS + TICK_MS);+ harness.audioActivityDetector.externalMicState = { reliable: true, externalMicActive: false };+ messages.length = 0;+ await harness.engine.beginRecordingSession({+ sessionId: "meeting-2",+ autoEndEligible: true,+ ownerWebContents,+ systemAudioAvailable: true,+ });++ harness.clock.advance(SILENCE_WINDOW_MS + TICK_MS);+ assert.deepEqual(messages, [+ {+ channel: "meeting-auto-end-requested",+ payload: { sessionId: "meeting-2", reason: "silence" },+ },+ ]);+ harness.engine.stop();+});++test("a restart claimed inside the claim window still suppresses auto-end", async () => {+ const harness = createEngine();+ const messages = [];+ const ownerWebContents = harness.owner(messages);+ await triggerOwnershipStop(harness, ownerWebContents);+ harness.engine.endRecordingSession("meeting-1");+ await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents);+ harness.engine.respondToAutoEndNotification("meeting-1", "restart", harness.overlayWebContents);++ harness.clock.advance(AUTO_END_RESTART_CLAIM_MS - TICK_MS);+ harness.audioActivityDetector.externalMicState = { reliable: true, externalMicActive: false };+ messages.length = 0;+ await harness.engine.beginRecordingSession({+ sessionId: "meeting-2",+ autoEndEligible: true,+ ownerWebContents,+ systemAudioAvailable: true,+ });++ harness.clock.advance(SILENCE_WINDOW_MS + TICK_MS);+ assert.deepEqual(messages, []);+ harness.engine.stop();+});++// A restart is the one response that deliberately skips the flush, because the+// recording it starts gates the queue again. When it cannot be delivered at+// all, nothing will start, so the detections held behind it have to go out.+test("a restart that cannot reach its renderer releases the detections it was holding", async () => {+ const harness = createEngine();+ let ownerDestroyed = false;+ const ownerWebContents = {+ isDestroyed: () => ownerDestroyed,+ send: () => {},+ };+ await triggerOwnershipStop(harness, ownerWebContents);++ harness.engine.handleCalendarReminder({+ id: "calendar-next",+ summary: "Next call",+ start_time: new Date(harness.clock.now()).toISOString(),+ });+ harness.engine.endRecordingSession("meeting-1");+ harness.engine.setUserRecording(false);+ await harness.engine.completeAutoEndSession("meeting-1", ownerWebContents);+ harness.engine._flushNotificationQueue();+ assert.deepEqual(harness.shownNotifications, []);++ ownerDestroyed = true;+ assert.equal(+ harness.engine.respondToAutoEndNotification("meeting-1", "restart", harness.overlayWebContents),+ false+ );++ assert.equal(harness.shownNotifications.length, 1);+ assert.equal(harness.shownNotifications[0].detectionId, "calendar:calendar-next");+ harness.engine.stop();+});diff --git a/test/helpers/meetingNotificationModel.test.js b/test/helpers/meetingNotificationModel.test.jsindex aafa864ea..d24d12101 100644--- a/test/helpers/meetingNotificationModel.test.js+++ b/test/helpers/meetingNotificationModel.test.js@@ -3,7 +3,7 @@ const assert = require("node:assert/strict");const load = () => import("../../src/components/meetingNotificationModel.ts");-test("auto-end presentation has countdown copy, Keep action, and no dismissal", async () => {+test("auto-end presentation has countdown copy, Restart action, and dismissal", async () => {const { getMeetingNotificationPresentation } = await load();assert.deepEqual(@@ -15,9 +15,9 @@ test("auto-end presentation has countdown copy, Keep action, and no dismissal",titleKey: "meetingNotification.autoEnd.title",bodyKey: "meetingNotification.autoEnd.body.micReleased",bodyValues: { seconds: 30 },- actionKey: "meetingNotification.autoEnd.keep",- action: "keep",- dismissible: false,+ actionKey: "meetingNotification.autoEnd.restart",+ action: "restart",+ dismissible: true,allowTitleWrap: true,});@@ -153,3 +153,18 @@ test("overlay initialization cleanup cancels reveal and invalidates a pending puassert.equal(readyCount, 0);assert.equal(unsubscribeCount, 1);});++// The overlay hides its card optimistically and relies on main closing the+// window. Anything short of an explicit success leaves the window open, so the+// card has to come back or the user is left with an invisible, unclickable+// always-on-top window over their screen.+test("only an explicit success keeps the auto-end card hidden", async () => {+ const { shouldRestoreAutoEndCard } = await load();++ assert.equal(shouldRestoreAutoEndCard({ success: true }), false);+ assert.equal(shouldRestoreAutoEndCard({ success: false, reason: "stale-session" }), true);+ // The IPC method is optional on the preload surface: an older or partially+ // wired bridge resolves undefined, which is not a success.+ assert.equal(shouldRestoreAutoEndCard(undefined), true);+ assert.equal(shouldRestoreAutoEndCard(null), true);+});diff --git a/test/helpers/meetingRecordingSession.test.js b/test/helpers/meetingRecordingSession.test.jsindex 89766c945..9debde283 100644--- a/test/helpers/meetingRecordingSession.test.js+++ b/test/helpers/meetingRecordingSession.test.js@@ -35,24 +35,46 @@ test("accepts legacy stops but rejects an expected ID for another active sessionassert.equal(canStopMeetingRecordingSession(null, "meeting-1"), false);});-test("auto-end stop requests forward only a valid expected session ID", async () => {+test("auto-end stop requests acknowledge only a completed scoped stop", async () => {const { requestMeetingRecordingAutoEnd } = await load();const requestedSessions = [];+ const completedSessions = [];const errors = [];const stopRecording = async (sessionId) => {requestedSessions.push(sessionId);+ return { stopped: sessionId === "meeting-2" };};+ const onStopped = (sessionId, stopped) => completedSessions.push({ sessionId, stopped });const onError = (error, sessionId) => errors.push({ error, sessionId });assert.equal(- requestMeetingRecordingAutoEnd({ sessionId: "meeting-2" }, stopRecording, onError),+ requestMeetingRecordingAutoEnd(+ { sessionId: "meeting-2" },+ stopRecording,+ onStopped,+ onError+ ),true);- assert.equal(requestMeetingRecordingAutoEnd({ sessionId: "" }, stopRecording, onError), false);- assert.equal(requestMeetingRecordingAutoEnd(null, stopRecording, onError), false);+ assert.equal(+ requestMeetingRecordingAutoEnd({ sessionId: "meeting-1" }, stopRecording, onStopped, onError),+ true+ );+ assert.equal(+ requestMeetingRecordingAutoEnd({ sessionId: "" }, stopRecording, onStopped, onError),+ false+ );+ assert.equal(requestMeetingRecordingAutoEnd(null, stopRecording, onStopped, onError), false);+ await Promise.resolve();await Promise.resolve();- assert.deepEqual(requestedSessions, ["meeting-2"]);+ assert.deepEqual(requestedSessions, ["meeting-2", "meeting-1"]);+ // Both settle: the caller must learn about a stop that completed without a+ // persisted result, or an auto-end ends the recording with no feedback.+ assert.deepEqual(completedSessions, [+ { sessionId: "meeting-2", stopped: true },+ { sessionId: "meeting-1", stopped: false },+ ]);assert.deepEqual(errors, []);});@@ -65,8 +87,11 @@ test("a rejected auto-end stop is reported instead of swallowed", async () => {};assert.equal(- requestMeetingRecordingAutoEnd({ sessionId: "meeting-2" }, stopRecording, (error, sessionId) =>- errors.push({ error, sessionId })+ requestMeetingRecordingAutoEnd(+ { sessionId: "meeting-2" },+ stopRecording,+ () => undefined,+ (error, sessionId) => errors.push({ error, sessionId })),true);@@ -76,6 +101,48 @@ test("a rejected auto-end stop is reported instead of swallowed", async () => {assert.deepEqual(errors, [{ error: stopFailure, sessionId: "meeting-2" }]);});+test("restart context preserves note identity and session speaker settings", async () => {+ const { createMeetingAutoEndRestartContext } = await load();+ const seedSegments = [{ id: "segment-1", text: "Hello", source: "mic" }];++ assert.deepEqual(+ createMeetingAutoEndRestartContext("meeting-2", "meeting-2", {+ recordingNoteId: 42,+ recordingNoteTitle: "Planning",+ recordingFolderId: 8,+ sessionDiarizationEnabled: false,+ sessionExpectedCount: 5,+ userTouchedStepper: true,+ segments: seedSegments,+ }),+ {+ sessionId: "meeting-2",+ args: {+ noteId: 42,+ noteTitle: "Planning",+ folderId: 8,+ seedSegments,+ diarizationEnabled: false,+ expectedCount: 5,+ expectedCountIsExplicit: true,+ autoEndEligible: true,+ },+ }+ );+ assert.equal(+ createMeetingAutoEndRestartContext("meeting-1", "meeting-2", {+ recordingNoteId: 42,+ recordingNoteTitle: "Planning",+ recordingFolderId: 8,+ sessionDiarizationEnabled: true,+ sessionExpectedCount: 2,+ userTouchedStepper: false,+ segments: [],+ }),+ null+ );+});+test("only meeting notes are eligible for automatic ending", async () => {const { isMeetingAutoEndEligible } = await load();@@ -327,3 +394,192 @@ test("main-start rejection releases cancellation and replacement after one scopeassert.equal(scopedStopCount, 1);assert.deepEqual(events, ["main-start:meeting-1", "main-stop:meeting-1", "capture:meeting-2"]);});++const parseSegments = (raw) => JSON.parse(raw);++test("restart seeds from the note's persisted transcript, not the stale live segments", async () => {+ const { resolveMeetingAutoEndRestartSeed } = await load();+ const diarized = [{ id: "a", text: "hello", speaker: "Ada" }];+ const stale = [{ id: "a", text: "hello", speaker: null }];++ const result = resolveMeetingAutoEndRestartSeed(+ 7,+ { transcript: JSON.stringify(diarized), deleted_at: null },+ parseSegments,+ stale+ );++ assert.deepEqual(result, { ok: true, seedSegments: diarized });+});++test("restart refuses a note that was deleted during the restart window", async () => {+ const { resolveMeetingAutoEndRestartSeed } = await load();++ assert.deepEqual(+ resolveMeetingAutoEndRestartSeed(+ 7,+ { transcript: "[]", deleted_at: "2026-08-27T00:00:00Z" },+ parseSegments,+ []+ ),+ { ok: false, reason: "note-missing" }+ );+});++test("restart refuses a note that no longer exists", async () => {+ const { resolveMeetingAutoEndRestartSeed } = await load();++ assert.deepEqual(resolveMeetingAutoEndRestartSeed(7, null, parseSegments, []), {+ ok: false,+ reason: "note-missing",+ });+});++test("restart without a note keeps the live segments it captured", async () => {+ const { resolveMeetingAutoEndRestartSeed } = await load();+ const live = [{ id: "a", text: "hello" }];++ assert.deepEqual(resolveMeetingAutoEndRestartSeed(null, null, parseSegments, live), {+ ok: true,+ seedSegments: live,+ });+});++test("restart starts empty when the note has no transcript yet", async () => {+ const { resolveMeetingAutoEndRestartSeed } = await load();++ assert.deepEqual(+ resolveMeetingAutoEndRestartSeed(7, { transcript: "", deleted_at: null }, parseSegments, [+ { id: "a", text: "stale" },+ ]),+ { ok: true, seedSegments: [] }+ );+});++// runMeetingAutoEndRestart owns every abort path, so the component can toast on+// all of them instead of dropping some silently.+function createRestartDeps(overrides = {}) {+ const started = [];+ return {+ started,+ deps: {+ getActiveSessionId: () => null,+ getLatestSegments: () => [],+ getNote: async () => ({ transcript: "[]", deleted_at: null }),+ parseSegments,+ startRecording: async (args) => {+ started.push(args);+ return true;+ },+ ...overrides,+ },+ };+}++const restartContext = (sessionId = "meeting-1", args = {}) => ({+ sessionId,+ args: { noteId: 7, noteTitle: "Standup", folderId: 3, seedSegments: [], ...args },+});++test("a delivered restart starts a recording seeded from the note", async () => {+ const { runMeetingAutoEndRestart } = await load();+ const { deps, started } = createRestartDeps({+ getNote: async () => ({+ transcript: JSON.stringify([{ id: "a", text: "hi" }]),+ deleted_at: null,+ }),+ });++ const outcome = await runMeetingAutoEndRestart(+ { sessionId: "meeting-1" },+ restartContext(),+ deps+ );++ assert.deepEqual(outcome, { status: "started" });+ assert.equal(started.length, 1);+ assert.deepEqual(started[0].seedSegments, [{ id: "a", text: "hi" }]);+ assert.equal(started[0].noteId, 7);+});++test("a restart whose context died reports an abort instead of failing silently", async () => {+ const { runMeetingAutoEndRestart } = await load();+ const { deps, started } = createRestartDeps();++ assert.deepEqual(await runMeetingAutoEndRestart({ sessionId: "meeting-1" }, null, deps), {+ status: "aborted",+ reason: "no-context",+ });+ assert.deepEqual(+ await runMeetingAutoEndRestart({ sessionId: "meeting-9" }, restartContext(), deps),+ { status: "aborted", reason: "no-context" }+ );+ assert.equal(started.length, 0);+});++test("a restart racing an already-live recording aborts before it starts one", async () => {+ const { runMeetingAutoEndRestart } = await load();+ const { deps, started } = createRestartDeps({ getActiveSessionId: () => "meeting-other" });++ assert.deepEqual(+ await runMeetingAutoEndRestart({ sessionId: "meeting-1" }, restartContext(), deps),+ { status: "aborted", reason: "already-recording" }+ );+ assert.equal(started.length, 0);+});++// The note read is awaited, so a manual recording can win the race after the+// first guard passed. Starting anyway would adopt the old note under the user's+// new recording.+test("a recording that starts while the note is being read cancels the restart", async () => {+ const { runMeetingAutoEndRestart } = await load();+ let activeSessionId = null;+ const noteRead = createDeferred();+ const { deps, started } = createRestartDeps({+ getActiveSessionId: () => activeSessionId,+ getNote: () => noteRead.promise,+ });++ const outcome = runMeetingAutoEndRestart({ sessionId: "meeting-1" }, restartContext(), deps);+ activeSessionId = "meeting-manual";+ noteRead.resolve({ transcript: "[]", deleted_at: null });++ assert.deepEqual(await outcome, { status: "aborted", reason: "already-recording" });+ assert.equal(started.length, 0);+});++test("a restart whose note vanished aborts without starting a recording", async () => {+ const { runMeetingAutoEndRestart } = await load();+ const { deps, started } = createRestartDeps({ getNote: async () => null });++ assert.deepEqual(+ await runMeetingAutoEndRestart({ sessionId: "meeting-1" }, restartContext(), deps),+ { status: "aborted", reason: "note-missing" }+ );+ assert.equal(started.length, 0);+});++test("a restart that startRecording refuses reports an abort", async () => {+ const { runMeetingAutoEndRestart } = await load();+ const { deps } = createRestartDeps({ startRecording: async () => false });++ assert.deepEqual(+ await runMeetingAutoEndRestart({ sessionId: "meeting-1" }, restartContext(), deps),+ { status: "aborted", reason: "start-refused" }+ );+});++test("a restart without a note keeps the segments captured at the stop", async () => {+ const { runMeetingAutoEndRestart } = await load();+ const live = [{ id: "a", text: "in person" }];+ const { deps, started } = createRestartDeps({ getLatestSegments: () => live });++ const outcome = await runMeetingAutoEndRestart(+ { sessionId: "meeting-1" },+ restartContext("meeting-1", { noteId: null }),+ deps+ );++ assert.deepEqual(outcome, { status: "started" });+ assert.deepEqual(started[0].seedSegments, live);+});diff --git a/test/helpers/preloadAuthBridge.test.js b/test/helpers/preloadAuthBridge.test.jsindex 362a2f4ed..905c8c703 100644--- a/test/helpers/preloadAuthBridge.test.js+++ b/test/helpers/preloadAuthBridge.test.js@@ -101,12 +101,25 @@ test("meeting auto-end listener strips the event and can unsubscribe", () => {assert.equal(listeners.has("meeting-auto-end-requested"), false);});-test("meeting auto-end keep forwards the recording session ID", async () => {- const { api, invocations } = loadPreloadApi();+test("meeting auto-end lifecycle bridges completion, overlay responses, and restart", async () => {+ const { api, invocations, listeners } = loadPreloadApi();+ const restartPayload = { sessionId: "meeting-2" };+ let receivedRestart;+ const unsubscribe = api.onMeetingAutoEndRestartRequested((request) => {+ receivedRestart = request;+ });- await api.meetingAutoEndKeep("meeting-2");+ await api.meetingAutoEndCompleted("meeting-2");+ await api.meetingAutoEndRespond("meeting-2", "restart");+ listeners.get("meeting-auto-end-restart-requested")?.({ sender: "ipc" }, restartPayload);- assert.deepEqual(invocations, [["meeting-auto-end-keep", "meeting-2"]]);+ assert.deepEqual(invocations, [+ ["meeting-auto-end-completed", "meeting-2"],+ ["meeting-auto-end-respond", "meeting-2", "restart"],+ ]);+ assert.equal(receivedRestart, restartPayload);+ unsubscribe();+ assert.equal(listeners.has("meeting-auto-end-restart-requested"), false);});test("assistant busy state is forwarded to the main-process hotkey guard", async () => {diff --git a/test/helpers/windowConfigMeetingNotification.test.js b/test/helpers/windowConfigMeetingNotification.test.jsindex cb2ee9966..e1a842636 100644--- a/test/helpers/windowConfigMeetingNotification.test.js+++ b/test/helpers/windowConfigMeetingNotification.test.js@@ -20,10 +20,12 @@ test("auto-end uses a larger positioned window while detection keeps its existinassert.deepEqual(detectionSize, { width: 392, height: 92 });assert.deepEqual(autoEndSize, AUTO_END_NOTIFICATION_WINDOW_SIZE);- assert.ok(autoEndSize.width >= 620);- assert.ok(autoEndSize.height >= 116);+ // Wider than a detection prompt because of the countdown copy and the Restart+ // action, but not so wide that a single line runs the width of the screen.+ assert.ok(autoEndSize.width > detectionSize.width);+ assert.ok(autoEndSize.width <= 480);assert.deepEqual(WindowPositionUtil.getNotificationPosition(display, autoEndSize), {- x: 864,+ x: 1004,y: 66,width: autoEndSize.width,height: autoEndSize.height,@@ -42,7 +44,9 @@ test("auto-end dimensions fit every supported localized title, body, and action"(/\p{Script=Han}|\p{Script=Hiragana}|\p{Script=Katakana}/u.test(character) ? 2 : 1),0);- const longestActionColumns = Math.max(...translations.map(({ keep }) => displayColumns(keep)));+ const longestActionColumns = Math.max(+ ...translations.map(({ restart }) => displayColumns(restart))+ );// Reserve the card's outer padding, icon/gaps, and the full non-wrapping action.const actionWidth = longestActionColumns * 6 + 20;diff --git a/test/helpers/windowManagerMeetingNotification.test.js b/test/helpers/windowManagerMeetingNotification.test.jsindex 746c2ba6b..47481cebb 100644--- a/test/helpers/windowManagerMeetingNotification.test.js+++ b/test/helpers/windowManagerMeetingNotification.test.js@@ -25,6 +25,7 @@ class FakeBrowserWindow extends EventEmitter {this.messages = [];this.loadUrlCount = 0;this.showCount = 0;+ this.ignoreMouseEvents = [];this.webContents = {send: (channel, payload) => this.messages.push({ channel, payload }),};@@ -33,7 +34,9 @@ class FakeBrowserWindow extends EventEmitter {setContentProtection() {}- setIgnoreMouseEvents() {}+ setIgnoreMouseEvents(ignore, options) {+ this.ignoreMouseEvents.push({ ignore, options });+ }loadFile() {return this.loadDeferred.promise;@@ -123,6 +126,8 @@ Module._load = function loadWindowManagerWithStubs(request, parent, isMain) {const WindowManager = require("../../src/helpers/windowManager");Module._load = originalLoad;+const notificationWindowFor = (index) => createdWindows[index];+function createNormalWindowManager() {const manager = new WindowManager();manager.setOnboardingActive(false);@@ -352,7 +357,7 @@ test("window creation uses the auto-end dimensions and variant-aware position",const manager = createNormalWindowManager();try {- const showPromise = manager.showMeetingAutoEndCountdown({+ const showPromise = manager.showMeetingAutoEndNotification({sessionId: "meeting-1",expiresAt: 70_000,reason: "silence",@@ -384,14 +389,14 @@ test("window creation uses the auto-end dimensions and variant-aware position",}});-test("unexpected auto-end window closure suppresses that countdown", async () => {+test("unexpected auto-end window closure invalidates that restart offer", async () => {const manager = createNormalWindowManager();- const unavailableSessions = [];+ const closedSessions = [];manager.meetingDetectionEngine = {- handleAutoEndNotificationUnavailable: (sessionId) => unavailableSessions.push(sessionId),+ handleAutoEndNotificationClosed: (sessionId) => closedSessions.push(sessionId),};- const showPromise = manager.showMeetingAutoEndCountdown({+ const showPromise = manager.showMeetingAutoEndNotification({sessionId: "meeting-1",expiresAt: 70_000,reason: "silence",@@ -402,13 +407,42 @@ test("unexpected auto-end window closure suppresses that countdown", async () =>notificationWindow.close();- assert.deepEqual(unavailableSessions, ["meeting-1"]);+ assert.deepEqual(closedSessions, ["meeting-1"]);+});++test("replacing an auto-end notification invalidates its restart offer", async () => {+ const manager = createNormalWindowManager();+ const closedSessions = [];+ manager.meetingDetectionEngine = {+ handleAutoEndNotificationClosed: (sessionId) => closedSessions.push(sessionId),+ };++ const autoEndPromise = manager.showMeetingAutoEndNotification({+ sessionId: "meeting-1",+ expiresAt: Date.now() + 30_000,+ reason: "silence",+ });+ createdWindows[0].loadDeferred.resolve();+ await autoEndPromise;++ const replacementPromise = manager.showMeetingNotification(+ { kind: "detection", detectionId: "calendar:next", source: "calendar" },+ { autoDismiss: false }+ );++ try {+ assert.deepEqual(closedSessions, ["meeting-1"]);+ } finally {+ createdWindows[1].loadDeferred.resolve();+ await replacementPromise;+ manager.dismissMeetingNotification();+ }});test("auto-end notification loading has a fail-safe timeout", async () => {const timers = installFakeTimers();const manager = createNormalWindowManager();- const showPromise = manager.showMeetingAutoEndCountdown({+ const showPromise = manager.showMeetingAutoEndNotification({sessionId: "meeting-1",expiresAt: 70_000,reason: "silence",@@ -430,6 +464,47 @@ test("auto-end notification loading has a fail-safe timeout", async () => {}});+test("auto-end recovery subtracts load time from its expiry and hover cannot extend it", async () => {+ const timers = installFakeTimers();+ const manager = createNormalWindowManager();+ const originalDateNow = Date.now;+ const timedOutNotifications = [];+ let now = 40_000;+ Date.now = () => now;+ manager.meetingDetectionEngine = {+ handleNotificationTimeout: (notification) => timedOutNotifications.push(notification),+ handleAutoEndNotificationClosed: () => undefined,+ };++ const notification = {+ kind: "auto-end",+ sessionId: "meeting-1",+ expiresAt: 70_000,+ reason: "silence",+ };+ const showPromise = manager.showMeetingAutoEndNotification(notification);+ const notificationWindow = createdWindows[0];++ try {+ now = 45_000;+ notificationWindow.loadDeferred.resolve();+ await showPromise;+ assert.equal(timers.pendingDelays().includes(25_000), true);++ manager.setNotificationInteractivity(notificationWindow.webContents, true);+ manager.setNotificationInteractivity(notificationWindow.webContents, false);+ assert.equal(timers.pendingDelays().includes(25_000), true);++ timers.runDelay(25_000);+ assert.deepEqual(timedOutNotifications, [notification]);+ assert.equal(notificationWindow.isDestroyed(), true);+ } finally {+ Date.now = originalDateNow;+ manager.dismissMeetingNotification();+ timers.restore();+ }+});+test("a replaced deferred notification cannot send its payload to the newer window", async () => {const timers = installFakeTimers();const manager = createNormalWindowManager();@@ -546,3 +621,76 @@ test("a stale ready callback cannot show the replacement notification window", atimers.restore();}});++test("an auto-end notification dismissed while loading reports that it was not shown", async () => {+ const manager = createNormalWindowManager();++ const showPromise = manager.showMeetingAutoEndNotification({+ sessionId: "meeting-1",+ expiresAt: Date.now() + 30_000,+ reason: "silence",+ });+ manager.dismissMeetingNotification();+ createdWindows[0].loadDeferred.resolve();++ assert.equal(await showPromise, false);+});++test("an auto-end notification whose load fails after dismissal reports that it was not shown", async () => {+ const manager = createNormalWindowManager();++ const showPromise = manager.showMeetingAutoEndNotification({+ sessionId: "meeting-1",+ expiresAt: Date.now() + 30_000,+ reason: "silence",+ });+ manager.dismissMeetingNotification();+ createdWindows[0].loadDeferred.reject(new Error("load failed"));++ assert.equal(await showPromise, false);+});++// The engine flushes its queued detections when an expiring restart offer+// releases them, so a prompt raised from the timeout handler must outlive the+// dismissal that closes the expired card.+test("a notification raised from the timeout handler survives the dismissal that follows", async () => {+ const timers = installFakeTimers();+ const manager = createNormalWindowManager();+ const originalDateNow = Date.now;+ let now = 40_000;+ Date.now = () => now;+ let replacementPromise = null;+ manager.meetingDetectionEngine = {+ handleNotificationTimeout: () => {+ replacementPromise = manager.showMeetingNotification(+ { kind: "detection", detectionId: "calendar:next", source: "calendar" },+ { autoDismiss: false }+ );+ },+ handleAutoEndNotificationClosed: () => undefined,+ };++ const showPromise = manager.showMeetingAutoEndNotification({+ kind: "auto-end",+ sessionId: "meeting-1",+ expiresAt: 70_000,+ reason: "silence",+ });++ try {+ notificationWindowFor(0).loadDeferred.resolve();+ await showPromise;++ timers.runDelay(30_000);+ notificationWindowFor(1).loadDeferred.resolve();+ await replacementPromise;++ assert.equal(createdWindows.length, 2);+ assert.equal(notificationWindowFor(1).isDestroyed(), false);+ assert.equal(manager.notificationWindow, notificationWindowFor(1));+ } finally {+ Date.now = originalDateNow;+ manager.dismissMeetingNotification();+ timers.restore();+ }+});diff --git a/test/lib/rendererTestHarness.js b/test/lib/rendererTestHarness.jsindex 488486fd7..ae85f03fc 100644--- a/test/lib/rendererTestHarness.js+++ b/test/lib/rendererTestHarness.js@@ -136,4 +136,77 @@ async function createRendererServer(return vite;}-module.exports = { createRendererServer, installBrowserGlobals, installHookDom };+// Minimal Web Audio + capture stubs so the mic pipeline can run under Node.+function installMicCaptureGlobals(t) {+ const track = {+ readyState: "live",+ label: "Fake Mic",+ stop() {},+ getSettings: () => ({}),+ };+ const stream = {+ getTracks: () => [track],+ getAudioTracks: () => [track],+ getVideoTracks: () => [],+ };+ const mediaDevices = {+ getUserMedia: async () => stream,+ enumerateDevices: async () => [],+ addEventListener() {},+ removeEventListener() {},+ };+ const node = () => ({+ connect() {},+ disconnect() {},+ gain: { value: 0 },+ fftSize: 0,+ smoothingTimeConstant: 0,+ });+ class FakeAudioContext {+ constructor() {+ this.state = "running";+ this.audioWorklet = { addModule: async () => {} };+ this.destination = {};+ }+ createMediaStreamSource() {+ return node();+ }+ createGain() {+ return node();+ }+ createAnalyser() {+ return node();+ }+ async resume() {}+ async close() {}+ }+ class FakeAudioWorkletNode {+ constructor() {+ this.port = { onmessage: null, postMessage() {} };+ }+ connect() {}+ disconnect() {}+ }++ const originalNavigator = Object.getOwnPropertyDescriptor(globalThis, "navigator");+ Object.defineProperty(globalThis, "navigator", {+ value: { mediaDevices },+ configurable: true,+ writable: true,+ });+ globalThis.AudioContext = FakeAudioContext;+ globalThis.AudioWorkletNode = FakeAudioWorkletNode;+ t.after(() => {+ if (originalNavigator) Object.defineProperty(globalThis, "navigator", originalNavigator);+ else delete globalThis.navigator;+ delete globalThis.AudioContext;+ delete globalThis.AudioWorkletNode;+ });+}++module.exports = {+ createRendererServer,+ installBrowserGlobals,+ installHookDom,+ installMicCaptureGlobals,+};diff --git a/test/stores/meetingRecordingStoreAutoEndStop.test.js b/test/stores/meetingRecordingStoreAutoEndStop.test.jsnew file mode 100644index 000000000..30c2c2630--- /dev/null+++ b/test/stores/meetingRecordingStoreAutoEndStop.test.js@@ -0,0 +1,132 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const {+ createRendererServer,+ installBrowserGlobals,+ installMicCaptureGlobals,+} = require("../lib/rendererTestHarness");++// `stopped` is what gates the auto-end restart card: true means this call ended+// a live recording, so resuming its note is safe. It must not be conditioned on+// main's teardown result — the transcript is written from the renderer before+// that IPC is even awaited, so a teardown error still leaves a resumable note.++const START_ARGS = {+ noteId: 11,+ noteTitle: "Standup",+ folderId: null,+ autoEndEligible: true,+};++function createElectronAPI({ stopResult }) {+ const noopListener = () => () => {};+ const notes = new Map([[11, { id: 11, transcript: "", deleted_at: null }]]);+ return {+ updatedTranscripts: [],+ 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 () => stopResult(),+ meetingTranscriptionSend: () => {},+ getNote: async (id) => notes.get(id) ?? null,+ updateNote: async () => ({ success: true }),+ onMeetingTranscriptionSegment: noopListener,+ onMeetingSpeakerIdentified: noopListener,+ onMeetingSpeakersMerged: noopListener,+ onMeetingSessionSpeakerConfigUpdated: noopListener,+ onMeetingTranscriptionError: noopListener,+ onMeetingTranscriptionFatalError: noopListener,+ onMeetingSystemAudioSilent: noopListener,+ onMeetingDiarizationComplete: noopListener,+ },+ };+}++async function loadStore(t, api) {+ installMicCaptureGlobals(t);+ installBrowserGlobals(t, {+ window: { electronAPI: api, setTimeout: (fn, ms) => setTimeout(fn, ms) },+ });+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-meeting-auto-end-stop-test-",+ });+ return vite.ssrLoadModule("/stores/meetingRecordingStore.ts");+}++test("a completed stop reports that it ended the recording", async (t) => {+ const { api } = createElectronAPI({ stopResult: () => ({ success: true }) });+ const store = await loadStore(t, api);++ assert.equal(await store.startRecording(START_ARGS), true);+ const result = await store.stopRecording();++ assert.equal(result.stopped, true);+ assert.equal(store.useMeetingRecordingStore.getState().isRecording, false);+});++// The renderer has already run cleanup and written the transcript by the time+// main's result is read, so a teardown failure must not cost the user their+// restart offer.+test("a stop whose main-side teardown fails still reports the recording ended", async (t) => {+ const { api } = createElectronAPI({+ stopResult: () => ({ success: false, error: "audio tap teardown failed" }),+ });+ const store = await loadStore(t, api);++ assert.equal(await store.startRecording(START_ARGS), true);+ const result = await store.stopRecording();++ assert.equal(result.stopped, true);+ assert.equal(store.useMeetingRecordingStore.getState().isRecording, false);+});++test("a stop main already dropped as stale still reports the recording ended", async (t) => {+ const { api } = createElectronAPI({+ stopResult: () => ({ success: false, reason: "stale-session" }),+ });+ const store = await loadStore(t, api);++ assert.equal(await store.startRecording(START_ARGS), true);+ assert.equal((await store.stopRecording()).stopped, true);+});++test("a stop that rejects still reports the recording ended", async (t) => {+ const { api } = createElectronAPI({+ stopResult: () => {+ throw new Error("ipc channel closed");+ },+ });+ const store = await loadStore(t, api);++ assert.equal(await store.startRecording(START_ARGS), true);+ assert.equal((await store.stopRecording()).stopped, true);+});++test("stopping when nothing is recording reports no stop happened", async (t) => {+ const { api } = createElectronAPI({ stopResult: () => ({ success: true }) });+ const store = await loadStore(t, api);++ assert.equal((await store.stopRecording()).stopped, false);+});++test("a scoped stop for another session reports no stop happened", async (t) => {+ const { api } = createElectronAPI({ stopResult: () => ({ success: true }) });+ const store = await loadStore(t, api);++ assert.equal(await store.startRecording(START_ARGS), true);+ const result = await store.stopRecording("some-other-session");++ assert.equal(result.stopped, false);+ assert.equal(store.useMeetingRecordingStore.getState().isRecording, true);+ await store.stopRecording();+});diff --git a/test/stores/meetingRecordingStoreDiarizationPublish.test.js b/test/stores/meetingRecordingStoreDiarizationPublish.test.jsnew file mode 100644index 000000000..733561784--- /dev/null+++ b/test/stores/meetingRecordingStoreDiarizationPublish.test.js@@ -0,0 +1,142 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const {+ createRendererServer,+ installBrowserGlobals,+ installMicCaptureGlobals,+} = require("../lib/rendererTestHarness");++// Delayed diarization is always persisted to the note that owns its session.+// Publishing it to the UI is separate, and must not happen while a recording is+// still appending to that same note: the editor prefers a published overlay to+// the note's own text, so the live half would look like it had vanished.++const NOTE_ID = 11;+const START_ARGS = { noteId: NOTE_ID, noteTitle: "Standup", folderId: null, autoEndEligible: true };++function createElectronAPI() {+ const noopListener = () => () => {};+ const state = { diarizationCallback: null, updatedTranscripts: [] };+ const notes = new Map([[NOTE_ID, { id: NOTE_ID, transcript: "", deleted_at: 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 () => ({ success: true, diarizationSessionId: null }),+ meetingTranscriptionSend: () => {},+ getNote: async (id) => notes.get(id) ?? null,+ updateNote: async (id, patch) => {+ state.updatedTranscripts.push({ id, transcript: patch.transcript });+ const note = notes.get(id);+ if (note) note.transcript = patch.transcript;+ return { success: true };+ },+ saveNoteSpeakerEmbeddings: async () => ({ success: true }),+ onMeetingDiarizationComplete: (callback) => {+ state.diarizationCallback = callback;+ return () => {+ state.diarizationCallback = null;+ };+ },+ onMeetingTranscriptionSegment: noopListener,+ onMeetingSpeakerIdentified: noopListener,+ onMeetingSpeakersMerged: noopListener,+ onMeetingSessionSpeakerConfigUpdated: noopListener,+ onMeetingTranscriptionError: noopListener,+ onMeetingTranscriptionFatalError: noopListener,+ onMeetingSystemAudioSilent: noopListener,+ };+ return { api, state };+}++async function loadStore(t, api) {+ installMicCaptureGlobals(t);+ installBrowserGlobals(t, {+ window: { electronAPI: api, setTimeout: (fn, ms) => setTimeout(fn, ms) },+ });+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-meeting-diarization-publish-test-",+ });+ return vite.ssrLoadModule("/stores/meetingRecordingStore.ts");+}++const ENRICHED = [{ id: "d0", text: "hello there", speaker: "speaker_0", speakerName: "Ada" }];++// The serial queue behind the listener awaits getNote and updateNote.+const settle = async () => {+ for (let i = 0; i < 20; i += 1) await Promise.resolve();+ await new Promise((resolve) => setTimeout(resolve, 0));+ for (let i = 0; i < 20; i += 1) await Promise.resolve();+};++test("a finished session's diarization is not published over the recording that resumed its note", async (t) => {+ const { api, state } = createElectronAPI();+ const store = await loadStore(t, api);+ assert.equal(typeof state.diarizationCallback, "function");++ assert.equal(await store.startRecording(START_ARGS), true);+ state.updatedTranscripts.length = 0;++ state.diarizationCallback({+ noteId: NOTE_ID,+ sessionId: "diar-before-restart",+ segments: ENRICHED,+ });+ await settle();++ assert.equal(+ store.useMeetingRecordingStore.getState().completedDiarization,+ null,+ "the finished half must not paint over the live recording"+ );+ // Suppressing the overlay must not cost the enrichment its write.+ assert.equal(state.updatedTranscripts.length, 1);+ assert.match(state.updatedTranscripts[0].transcript, /Ada/);++ await store.stopRecording();+});++test("the same result publishes normally once the recording has stopped", async (t) => {+ const { api, state } = createElectronAPI();+ const store = await loadStore(t, api);++ assert.equal(await store.startRecording(START_ARGS), true);+ await store.stopRecording();++ state.diarizationCallback({+ noteId: NOTE_ID,+ sessionId: "diar-after-stop",+ segments: ENRICHED,+ });+ await settle();++ const published = store.useMeetingRecordingStore.getState().completedDiarization;+ assert.equal(published?.noteId, NOTE_ID);+ assert.equal(published?.segments.length, 1);+});++test("a live recording on another note does not suppress the publish", async (t) => {+ const { api, state } = createElectronAPI();+ const store = await loadStore(t, api);++ assert.equal(await store.startRecording({ ...START_ARGS, noteId: 99 }), true);++ state.diarizationCallback({+ noteId: NOTE_ID,+ sessionId: "diar-other-note",+ segments: ENRICHED,+ });+ await settle();++ assert.equal(store.useMeetingRecordingStore.getState().completedDiarization?.noteId, NOTE_ID);+ await store.stopRecording();+});diff --git a/test/stores/meetingRecordingStoreSystemAudioSilence.test.js b/test/stores/meetingRecordingStoreSystemAudioSilence.test.jsindex 0f1c5016e..3f6e4873c 100644--- a/test/stores/meetingRecordingStoreSystemAudioSilence.test.js+++ b/test/stores/meetingRecordingStoreSystemAudioSilence.test.js@@ -1,6 +1,10 @@const test = require("node:test");const assert = require("node:assert/strict");-const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");+const {+ createRendererServer,+ installBrowserGlobals,+ installMicCaptureGlobals,+} = require("../lib/rendererTestHarness");// Drives the real startRecording/stopRecording flow through the renderer// harness and pins the meeting-system-audio-silent warning: latched once per@@ -57,74 +61,6 @@ async function loadStore(t, api) {return vite.ssrLoadModule("/stores/meetingRecordingStore.ts");}-// Minimal Web Audio + capture stubs so the mic pipeline can run under Node.-function installMicCaptureGlobals(t) {- const track = {- readyState: "live",- label: "Fake Mic",- stop() {},- getSettings: () => ({}),- };- const stream = {- getTracks: () => [track],- getAudioTracks: () => [track],- getVideoTracks: () => [],- };- const mediaDevices = {- getUserMedia: async () => stream,- enumerateDevices: async () => [],- addEventListener() {},- removeEventListener() {},- };- const node = () => ({- connect() {},- disconnect() {},- gain: { value: 0 },- fftSize: 0,- smoothingTimeConstant: 0,- });- class FakeAudioContext {- constructor() {- this.state = "running";- this.audioWorklet = { addModule: async () => {} };- this.destination = {};- }- createMediaStreamSource() {- return node();- }- createGain() {- return node();- }- createAnalyser() {- return node();- }- async resume() {}- async close() {}- }- class FakeAudioWorkletNode {- constructor() {- this.port = { onmessage: null, postMessage() {} };- }- connect() {}- disconnect() {}- }-- const originalNavigator = Object.getOwnPropertyDescriptor(globalThis, "navigator");- Object.defineProperty(globalThis, "navigator", {- value: { mediaDevices },- configurable: true,- writable: true,- });- globalThis.AudioContext = FakeAudioContext;- globalThis.AudioWorkletNode = FakeAudioWorkletNode;- t.after(() => {- if (originalNavigator) Object.defineProperty(globalThis, "navigator", originalNavigator);- else delete globalThis.navigator;- delete globalThis.AudioContext;- delete globalThis.AudioWorkletNode;- });-}-test("silence event latches the warning once during a system-audio session", async (t) => {const { api, listeners } = createElectronAPI({systemAudioMode: "native",diff --git a/test/utils/diarizationCompletion.test.js b/test/utils/diarizationCompletion.test.jsindex 5d0949cd4..845d0fb5e 100644--- a/test/utils/diarizationCompletion.test.js+++ b/test/utils/diarizationCompletion.test.js@@ -43,6 +43,43 @@ test("payload noteId with no pending session is current", () => {assert.deepEqual(result, { targetNoteId: 1, isCurrentSession: true });});+// A restarted recording resets diarizationSessionId to null, so "no pending+// session" stops meaning "nothing newer is happening". Publishing the finished+// half's snapshot then paints it over the live recording — and the editor+// prefers that overlay, so the note looks truncated and one speaker rename+// writes the truncated copy to disk.+test("a live recording on the target note supersedes a result with no pending session", () => {+ const result = resolveDiarizationTarget({+ payloadNoteId: 1,+ payloadSessionId: "diar-100",+ currentSessionId: null,+ activeRecordingNoteId: 1,+ });+ assert.deepEqual(result, { targetNoteId: 1, isCurrentSession: false });+});++test("a live recording on another note does not supersede the result", () => {+ const result = resolveDiarizationTarget({+ payloadNoteId: 1,+ payloadSessionId: "diar-100",+ currentSessionId: null,+ activeRecordingNoteId: 2,+ });+ assert.deepEqual(result, { targetNoteId: 1, isCurrentSession: true });+});++// recordingNoteId outlives the recording that set it, so the caller passes null+// once the recording stops — otherwise the note could never publish again.+test("a stopped recording no longer supersedes its own note's result", () => {+ const result = resolveDiarizationTarget({+ payloadNoteId: 1,+ payloadSessionId: "diar-100",+ currentSessionId: null,+ activeRecordingNoteId: null,+ });+ assert.deepEqual(result, { targetNoteId: 1, isCurrentSession: true });+});+test("a payload without a noteId is dropped", () => {// Main snapshots the same noteId the renderer passed to// meetingTranscriptionStart, so a missing one means the recording was never