Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(updater): complete recording startup and failure guards
EtienneLescotb336af66b9e3
diff --git a/electron/auto-updater.test.ts b/electron/auto-updater.test.tsindex 154c06291..50dcbd7af 100644--- a/electron/auto-updater.test.ts+++ b/electron/auto-updater.test.ts@@ -259,20 +259,22 @@ describe("self-update flow", () => {expect(mocks.installWindowsUpdate).not.toHaveBeenCalled();});- it("does not force elevation when the machine install cannot be confirmed", async () => {+ it.each(["HKLM", "HKCU"])("keeps the app open when the %s query fails", async (hive) => {const platform = Object.getOwnPropertyDescriptor(process, "platform");Object.defineProperty(process, "platform", { value: "win32" });vi.mocked(spawnSync)- .mockReturnValueOnce({ status: null } as ReturnType<typeof spawnSync>)- .mockReturnValueOnce({ status: 1 } as ReturnType<typeof spawnSync>)+ .mockReturnValueOnce({ status: hive === "HKLM" ? null : 0 } as ReturnType<typeof spawnSync>)+ .mockReturnValueOnce({ status: hive === "HKCU" ? null : 1 } as ReturnType<typeof spawnSync>).mockReturnValue({ status: null } as ReturnType<typeof spawnSync>);try {- await installSelfUpdate();+ await expect(installSelfUpdate()).rejects.toThrow(+ "Could not confirm the Windows installation type",+ );} finally {if (platform) Object.defineProperty(process, "platform", platform);vi.mocked(spawnSync).mockReturnValue({ status: 1 } as ReturnType<typeof spawnSync>);}- expect(mocks.autoUpdater.quitAndInstall).toHaveBeenCalledWith(true, true);+ expect(mocks.autoUpdater.quitAndInstall).not.toHaveBeenCalled();expect(mocks.installWindowsUpdate).not.toHaveBeenCalled();});});diff --git a/electron/auto-updater.ts b/electron/auto-updater.tsindex a2c108b0a..8b69b4f71 100644--- a/electron/auto-updater.ts+++ b/electron/auto-updater.ts@@ -98,7 +98,8 @@ function nsisInstallStatus(hive: "HKLM" | "HKCU"): number | null {function hasNsisInstall(hive: "HKLM" | "HKCU"): boolean {// Exit 1 is reg's "key not found". Anything else, reg itself failing to run included, counts- // as present, so a doubt keeps the wizard rather than risking the wrong copy.+ // as present, so this selector never treats an uncertain copy as absent. The installer+ // coordinator below refuses failed queries rather than quitting with an unknown target.return nsisInstallStatus(hive) !== 1;}@@ -117,12 +118,17 @@ export function installsSilently(/** Hand over to the installer. Callers MUST have checked `blockedFromInstalling`. */export async function installSelfUpdate(canInstall: () => boolean = () => true): Promise<void> {const autoUpdater = await getUpdater();- const silent = installsSilently();+ let silent = true;if (process.platform === "win32") {const { installWindowsUpdate, assertWindowsUpdateIdle } = await import("./windows-update");// A concurrent check must not fall back to quitting while another UAC is pending.assertWindowsUpdateIdle();- if (silent && nsisInstallStatus("HKLM") === 0) {+ const installed = { HKLM: nsisInstallStatus("HKLM"), HKCU: nsisInstallStatus("HKCU") };+ if (Object.values(installed).some((status) => status !== 0 && status !== 1)) {+ throw new Error("Could not confirm the Windows installation type. Please retry the update.");+ }+ silent = installsSilently("win32", (hive) => installed[hive] === 0);+ if (silent && installed.HKLM === 0) {await installWindowsUpdate(() => autoUpdater.downloadUpdate(), canInstall);return;}diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex 93c514c5e..5249de925 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -1983,7 +1983,7 @@ export function registerIpcHandlers(getSourceSelectorWindow: () => BrowserWindow | null,getNotesWindow: () => BrowserWindow | null,getCountdownOverlayWindow?: () => BrowserWindow | null,- onRecordingStateChange?: (recording: boolean, sourceName: string) => void,+ onRecordingStateChange?: (recording: boolean, sourceName: string, preparing?: boolean) => void,_switchToHud?: () => void,/** The editor holds changes it has not saved (main.ts): an MCP take would close it. */editorHasUnsavedChanges?: () => boolean,@@ -1996,10 +1996,10 @@ export function registerIpcHandlers(* for a client's take to start, and the tray shows it. A native path that called* `onRecordingStateChange` itself left the MCP recorder waiting on a take already running.*/- const setAppRecording = (recording: boolean, sourceName: string, notifyRecorder = true) => {+ const setAppRecording = (recording: boolean, sourceName: string, preparing = false) => {appRecording = recording;- if (notifyRecorder) mcpAppRecorder.recordingChanged(recording);- onRecordingStateChange?.(recording, sourceName);+ if (!preparing) mcpAppRecorder.recordingChanged(recording);+ onRecordingStateChange?.(recording, sourceName, preparing);};const appSettings = new AppSettingsStore(app.getPath("userData"));const broadcastSelectedSource = (source: SelectedSource | null) => {@@ -2907,6 +2907,7 @@ export function registerIpcHandlers(if (isWindowsUpdatePending()) {return { success: false, error: WINDOWS_UPDATE_PENDING_MESSAGE };}+ let startReserved = false;try {if (!isWindowsGraphicsCaptureOsSupported()) {return {@@ -3035,6 +3036,13 @@ export function registerIpcHandlers(outputPath,});+ assertWindowsUpdateIdle();+ if (appRecording || nativeWindowsCaptureProcess) {+ return { success: false, error: "Native Windows capture is already running." };+ }+ // Reserve startup before cursor/helper awaits without reporting a started take.+ startReserved = true;+ setAppRecording(true, selectedSource?.name ?? "Screen", true);await fs.mkdir(RECORDINGS_DIR, { recursive: true });nativeWindowsCaptureOutput = "";nativeWindowsCaptureTargetPath = outputPath;@@ -3133,6 +3141,7 @@ export function registerIpcHandlers(};} catch (error) {console.error("Failed to start native Windows recording:", error);+ if (!startReserved) return { success: false, error: String(error) };const failedProc = nativeWindowsCaptureProcess;const failedOutputPaths = [nativeWindowsCaptureTargetPath,@@ -3151,6 +3160,7 @@ export function registerIpcHandlers(}}await stopCursorRecording();+ setAppRecording(false, selectedSource?.name ?? "Screen");return { success: false, error: String(error) };}},@@ -4170,7 +4180,7 @@ export function registerIpcHandlers(const source = selectedSource || { name: "Screen" };if (recording) {// Claim the take synchronously, before cursor setup yields to an updater.- setAppRecording(recording, source.name, false);+ setAppRecording(recording, source.name, true);if (reserveOnly) return { success: true };}const normalizedCursorCaptureMode =diff --git a/electron/ipc/recordingStateRouting.test.ts b/electron/ipc/recordingStateRouting.test.tsindex 13c7193f1..fa3f85909 100644--- a/electron/ipc/recordingStateRouting.test.ts+++ b/electron/ipc/recordingStateRouting.test.ts@@ -37,7 +37,7 @@ describe("recording state routing", () => {const body = setter.slice(0, setter.indexOf("};"));expect(body).toContain("appRecording = recording");expect(body).toContain("mcpAppRecorder.recordingChanged(recording)");- expect(body).toContain("onRecordingStateChange?.(recording, sourceName)");+ expect(body).toContain("onRecordingStateChange?.(recording, sourceName, preparing)");});it.each(["windows", "mac", "linux"])("a native %s start and stop notify it", (platform) => {diff --git a/electron/main.ts b/electron/main.tsindex 506b45da0..60523105d 100644--- a/electron/main.ts+++ b/electron/main.ts@@ -496,7 +496,9 @@ let updateCheckAbort: AbortController | null = null;* the install, i.e. after a 240 MB download has already competed with the encoder. Every* surface is rebuilt when the flag flips (see `setupApplicationMenu`/`updateTrayMenu`). */function canOfferUpdateCheck(): boolean {- return offersUpdateCheck(getInstallChannel(), { recording: isRecording });+ return offersUpdateCheck(getInstallChannel(), {+ recording: isRecording || recordingStartPending,+ });}/** What the HUD is told at mount, and only the permanent half of the veto. The recording half@@ -664,6 +666,7 @@ function runSaveDiagnostics() {* and on Windows it physically cannot, because the capture helpers spawn from inside the* install directory and NSIS cannot overwrite a running .exe. */let isRecording = false;+let recordingStartPending = false;let backgroundUpdateTimer: ReturnType<typeof setInterval> | null = null;/** The update button, shown by the HUD, the editor and the tray; null hides it. Only a background* check and the downloads it leads to set it: the manual check keeps its own dialogs. */@@ -684,7 +687,7 @@ function setUpdateBadge(badge: UpdateBadge | null, releasePage: string | null =function installBlock(): string | null {return blockedFromInstalling({- recording: isRecording,+ recording: isRecording || recordingStartPending,editorHasUnsavedChanges,inApplicationsFolder:process.platform === "darwin" ? (app.isInApplicationsFolder?.() ?? true) : true,@@ -1510,12 +1513,13 @@ appReady?.then(async () => {() => sourceSelectorWindow,() => notesWindow,() => countdownOverlayWindow,- (recording: boolean, sourceName: string) => {+ (recording: boolean, sourceName: string, preparing = false) => {selectedSourceName = sourceName;- isRecording = recording;+ recordingStartPending = recording && preparing;+ isRecording = recording && !preparing;setDisplaySleepBlocked(recording);if (!tray) createTray();- updateTrayMenu(recording);+ updateTrayMenu(isRecording);// `canOfferUpdateCheck()` now answers "not mid-take" too, and the app/Help menus are// built once at startup — without this they keep offering the check during a take.setupApplicationMenu();diff --git a/src/hooks/recorderHandle.test.ts b/src/hooks/recorderHandle.test.tsindex 91d7154b9..59f731785 100644--- a/src/hooks/recorderHandle.test.ts+++ b/src/hooks/recorderHandle.test.ts@@ -245,6 +245,28 @@ describe("createRecorderHandle", () => {expect(closeRecordingStream).toHaveBeenCalledWith("rec.webm");});+ it("discard waits for a pending open before closing its stream", async () => {+ let finishOpen: ((result: { success: boolean }) => void) | undefined;+ const open = new Promise<{ success: boolean }>((resolve) => {+ finishOpen = resolve;+ });+ const closeRecordingStream = vi.fn(async () => ({ success: true }));+ stubElectronAPI({+ openRecordingStream: vi.fn(() => open),+ appendRecordingChunk: vi.fn(async () => ({ success: true })),+ closeRecordingStream,+ });+ const handle = createRecorderHandle({} as MediaStream, { mimeType: "video/webm" }, "rec.webm");+ const discarded = handle.discard();+ await tick();+ expect(closeRecordingStream).not.toHaveBeenCalled();+ finishOpen?.({ success: true });+ await discarded;+ expect(closeRecordingStream).toHaveBeenCalledWith("rec.webm");+ driver(handle).stop();+ await handle.recordedBlobPromise;+ });+it("discard is a no-op when the stream never opened", async () => {const closeRecordingStream = vi.fn(async () => ({ success: true }));stubElectronAPI({diff --git a/src/hooks/recorderHandle.ts b/src/hooks/recorderHandle.tsindex 6264b9be5..0e4b2df8f 100644--- a/src/hooks/recorderHandle.ts+++ b/src/hooks/recorderHandle.ts@@ -133,6 +133,8 @@ export function createRecorderHandle(}async function discard(): Promise<void> {+ await openPromise.catch(() => undefined);+ await writeChain;if (streamOpened && fileName && api?.closeRecordingStream) {await api.closeRecordingStream(fileName);}diff --git a/src/hooks/useScreenRecorder.restartFailure.test.tsx b/src/hooks/useScreenRecorder.restartFailure.test.tsxindex 990e2745d..00293717c 100644--- a/src/hooks/useScreenRecorder.restartFailure.test.tsx+++ b/src/hooks/useScreenRecorder.restartFailure.test.tsx@@ -182,6 +182,44 @@ describe("browser take start reservation", () => {});expect(view.result.current.recording).toBe(false);expect(api.setRecordingState).toHaveBeenCalledWith(false);+ expect(api.setRecordingState.mock.calls[0]).toEqual([+ true,+ undefined,+ expect.any(String),+ true,+ ]);+ expect(api.setRecordingState.mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(createRecorderHandle).mock.invocationCallOrder[0],+ );+ });++ it("stops and discards a handle retained when later recorder setup fails", async () => {+ stubBrowserCapture();+ const recorder = Object.assign(new EventTarget(), {+ state: "recording" as RecordingState,+ stop: vi.fn(() => {+ recorder.state = "inactive";+ }),+ });+ vi.spyOn(recorder, "addEventListener").mockImplementationOnce(() => {+ throw new Error("later setup failed");+ });+ const failed = {+ recorder: recorder as unknown as MediaRecorder,+ recordedBlobPromise: Promise.resolve(new Blob()),+ isStreaming: () => true,+ discard: vi.fn(async () => undefined),+ };+ vi.mocked(createRecorderHandle).mockReturnValueOnce(failed);+ const view = renderHook(() => useScreenRecorder());+ await settle();+ await act(async () => {+ await view.result.current.startRecordingImmediately();+ });+ expect(recorder.stop).toHaveBeenCalledOnce();+ expect(failed.discard).toHaveBeenCalledOnce();+ expect(api.setRecordingState).toHaveBeenCalledWith(false);+ expect(view.result.current.recording).toBe(false);});});diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.tsindex 65b750fac..8ed63698c 100644--- a/src/hooks/useScreenRecorder.ts+++ b/src/hooks/useScreenRecorder.ts@@ -2161,8 +2161,24 @@ export function useScreenRecorder(): UseScreenRecorderReturn {setElapsedSeconds(0);accumulatedDurationMs.current = 0;segmentStartedAt.current = null;+ const failedRecorders = [screenRecorder.current, webcamRecorder.current];screenRecorder.current = null;webcamRecorder.current = null;+ allowAutoFinalize.current = false;+ for (const failed of failedRecorders) {+ if (!failed) continue;+ try {+ if (failed.recorder.state !== "inactive") failed.recorder.stop();+ } catch (stopError) {+ console.warn("Failed to stop the incomplete recording:", stopError);+ }+ void failed.recordedBlobPromise+ .catch(() => undefined)+ .then(() => failed.discard())+ .catch((discardError) =>+ console.warn("Failed to discard the incomplete recording:", discardError),+ );+ }teardownMedia();} finally {if (browserStartClaimed && !browserRecorderStarted) {diff --git a/src/native/browserShim.test.ts b/src/native/browserShim.test.tsindex 3360d0ddf..6395f2045 100644--- a/src/native/browserShim.test.ts+++ b/src/native/browserShim.test.ts@@ -60,6 +60,13 @@ describe("browserShim addAsset (issue #350)", () => {});describe("browserShim recording settings", () => {+ it("acknowledges recording reservations and releases without a main process", async () => {+ await expect(+ window.electronAPI.setRecordingState(true, undefined, "editable-overlay", true),+ ).resolves.toEqual({ success: true });+ await expect(window.electronAPI.setRecordingState(false)).resolves.toEqual({ success: true });+ });+it("publishes recording settings only after localStorage succeeds", async () => {await window.electronAPI.setRecordingPrefs({ micEnabled: false });const setItem = Storage.prototype.setItem;diff --git a/src/native/browserShim.ts b/src/native/browserShim.tsindex 3b7b704d2..64b70a0d9 100644--- a/src/native/browserShim.ts+++ b/src/native/browserShim.ts@@ -187,6 +187,7 @@ function createShimElectronAPI() {return () => shimSelectedSourceListeners.delete(callback);},getRecordingPrefs: () => Promise.resolve(shimRecordingPrefs),+ setRecordingState: () => Promise.resolve({ success: true as const }),setRecordingPrefs: (patch: Partial<ShimRecordingPrefs>) => {const next = { ...shimRecordingPrefs, ...patch };try {