Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(updater): recheck readiness and reserve browser starts

EtienneLescot0f006a23d747
diff --git a/electron/auto-updater.test.ts b/electron/auto-updater.test.ts
index 1b1defee1..154c06291 100644
--- a/electron/auto-updater.test.ts
+++ b/electron/auto-updater.test.ts
@@ -56,6 +56,12 @@ describe("blockedFromInstalling", () => {
}
});
+ it("blocks a Windows handoff with unsaved editor changes", () => {
+ expect(blockedFromInstalling(state({ platform: "win32", editorHasUnsavedChanges: true }))).toBe(
+ "unsaved-changes",
+ );
+ });
+
// App Translocation: a quarantined app runs from a read-only image where Squirrel cannot
// replace the bundle. Pinned per-platform because CI is Linux-only and an unpinned branch
// would be green here and wrong on the one platform it applies to.
@@ -194,6 +200,7 @@ describe("self-update flow", () => {
it("waits for the Windows installer without quitting before the UAC decision", async () => {
const platform = Object.getOwnPropertyDescriptor(process, "platform");
+ const canInstall = vi.fn(() => true);
let finish: (() => void) | undefined;
mocks.installWindowsUpdate.mockImplementation(async (download: () => Promise<string[]>) => {
await download();
@@ -209,12 +216,12 @@ describe("self-update flow", () => {
Object.defineProperty(process, "platform", { value: "win32" });
try {
let settled = false;
- const install = installSelfUpdate().then(() => {
+ const install = installSelfUpdate(canInstall).then(() => {
settled = true;
});
await vi.waitFor(() => expect(mocks.autoUpdater.downloadUpdate).toHaveBeenCalledOnce());
expect(settled).toBe(false);
- expect(mocks.installWindowsUpdate).toHaveBeenCalledWith(expect.any(Function));
+ expect(mocks.installWindowsUpdate).toHaveBeenCalledWith(expect.any(Function), canInstall);
expect(mocks.autoUpdater.quitAndInstall).not.toHaveBeenCalled();
finish?.();
await install;
diff --git a/electron/auto-updater.ts b/electron/auto-updater.ts
index 3b14b3e40..a2c108b0a 100644
--- a/electron/auto-updater.ts
+++ b/electron/auto-updater.ts
@@ -23,6 +23,8 @@ export type UpdateOutcome =
* all" because these are transient — the answer changes as the user works. */
export interface InstallReadiness {
recording: boolean;
+ /** A Windows handoff cannot wait on the editor's close prompt with input disabled. */
+ editorHasUnsavedChanges?: boolean;
/** macOS only. Gatekeeper runs a quarantined app from a read-only image (App Translocation),
* where Squirrel cannot replace the bundle; worse, an app can BECOME translocated after an
* update and then never update again. */
@@ -33,6 +35,7 @@ export interface InstallReadiness {
/** Pure so the veto can be tested without an updater, a Mac, or a recording. */
export function blockedFromInstalling(state: InstallReadiness): string | null {
if (state.recording) return "recording";
+ if (state.platform === "win32" && state.editorHasUnsavedChanges) return "unsaved-changes";
if (state.platform === "darwin" && !state.inApplicationsFolder) return "not-in-applications";
return null;
}
@@ -112,7 +115,7 @@ export function installsSilently(
}
/** Hand over to the installer. Callers MUST have checked `blockedFromInstalling`. */
-export async function installSelfUpdate(): Promise<void> {
+export async function installSelfUpdate(canInstall: () => boolean = () => true): Promise<void> {
const autoUpdater = await getUpdater();
const silent = installsSilently();
if (process.platform === "win32") {
@@ -120,10 +123,11 @@ export async function installSelfUpdate(): Promise<void> {
// A concurrent check must not fall back to quitting while another UAC is pending.
assertWindowsUpdateIdle();
if (silent && nsisInstallStatus("HKLM") === 0) {
- await installWindowsUpdate(() => autoUpdater.downloadUpdate());
+ await installWindowsUpdate(() => autoUpdater.downloadUpdate(), canInstall);
return;
}
}
+ if (!canInstall()) return;
// isForceRunAfter=true so the app comes back up.
autoUpdater.quitAndInstall(silent, true);
}
diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.ts
index b85d616ce..4cf2dbacf 100644
--- a/electron/electron-env.d.ts
+++ b/electron/electron-env.d.ts
@@ -149,7 +149,8 @@ interface Window {
recording: boolean,
recordingId?: number,
cursorCaptureMode?: import("../src/lib/recordingSession").CursorCaptureMode,
- ) => Promise<void>;
+ reserveOnly?: boolean,
+ ) => Promise<{ success: boolean; error?: string }>;
isNativeWindowsCaptureAvailable: () => Promise<{
success: boolean;
available: boolean;
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index 255fc9c6c..93c514c5e 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -1996,9 +1996,9 @@ 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) => {
+ const setAppRecording = (recording: boolean, sourceName: string, notifyRecorder = true) => {
appRecording = recording;
- mcpAppRecorder.recordingChanged(recording);
+ if (notifyRecorder) mcpAppRecorder.recordingChanged(recording);
onRecordingStateChange?.(recording, sourceName);
};
const appSettings = new AppSettingsStore(app.getPath("userData"));
@@ -4157,7 +4157,22 @@ export function registerIpcHandlers(
ipcMain.handle(
"set-recording-state",
- async (_, recording: boolean, recordingId?: number, cursorCaptureMode?: CursorCaptureMode) => {
+ async (
+ _,
+ recording: boolean,
+ recordingId?: number,
+ cursorCaptureMode?: CursorCaptureMode,
+ reserveOnly?: boolean,
+ ) => {
+ if (recording && isWindowsUpdatePending()) {
+ return { success: false, error: WINDOWS_UPDATE_PENDING_MESSAGE };
+ }
+ const source = selectedSource || { name: "Screen" };
+ if (recording) {
+ // Claim the take synchronously, before cursor setup yields to an updater.
+ setAppRecording(recording, source.name, false);
+ if (reserveOnly) return { success: true };
+ }
const normalizedCursorCaptureMode =
normalizeCursorCaptureMode(cursorCaptureMode) ?? "editable-overlay";
if (recording && normalizedCursorCaptureMode === "editable-overlay") {
@@ -4166,8 +4181,8 @@ export function registerIpcHandlers(
await stopCursorRecording();
}
- const source = selectedSource || { name: "Screen" };
setAppRecording(recording, source.name);
+ return { success: true };
},
);
diff --git a/electron/main.ts b/electron/main.ts
index 255782c4a..506b45da0 100644
--- a/electron/main.ts
+++ b/electron/main.ts
@@ -685,6 +685,7 @@ function setUpdateBadge(badge: UpdateBadge | null, releasePage: string | null =
function installBlock(): string | null {
return blockedFromInstalling({
recording: isRecording,
+ editorHasUnsavedChanges,
inApplicationsFolder:
process.platform === "darwin" ? (app.isInApplicationsFolder?.() ?? true) : true,
platform: process.platform,
@@ -695,13 +696,25 @@ async function showBlockedInstall(blocked: string) {
await showMessageBox({
type: "info",
title: PRODUCT_NAME,
- message: mainT(
- "common",
- blocked === "recording" ? "updates.blockedRecording" : "updates.blockedLocation",
- ),
+ message:
+ blocked === "unsaved-changes"
+ ? mainT("dialogs", "unsavedChanges.message")
+ : mainT(
+ "common",
+ blocked === "recording" ? "updates.blockedRecording" : "updates.blockedLocation",
+ ),
});
}
+async function installWhenReady() {
+ let blocked: string | null = null;
+ await installSelfUpdate(() => {
+ blocked = installBlock();
+ return blocked === null;
+ });
+ if (blocked) await showBlockedInstall(blocked);
+}
+
let usagePingEnabled = true;
/** Hidden where the ping never runs anyway: a dev build, or DO_NOT_TRACK set. */
@@ -743,7 +756,7 @@ async function downloadAndInstall(latestVersion: string) {
});
return restart.response;
},
- install: installSelfUpdate,
+ install: installWhenReady,
});
if (result.status === "failed") {
await showMessageBox({
@@ -832,7 +845,7 @@ async function applyUpdate() {
const blocked = installBlock();
if (blocked) await showBlockedInstall(blocked);
else if (badge.state === "available") await downloadAndInstall(badge.version);
- else await installSelfUpdate();
+ else await installWhenReady();
} finally {
applyUpdateInFlight = false;
}
diff --git a/electron/preload.ts b/electron/preload.ts
index 4e96cdb76..021932a33 100644
--- a/electron/preload.ts
+++ b/electron/preload.ts
@@ -241,8 +241,15 @@ contextBridge.exposeInMainWorld("electronAPI", {
recording: boolean,
recordingId?: number,
cursorCaptureMode?: import("../src/lib/recordingSession").CursorCaptureMode,
+ reserveOnly?: boolean,
) => {
- return ipcRenderer.invoke("set-recording-state", recording, recordingId, cursorCaptureMode);
+ return ipcRenderer.invoke(
+ "set-recording-state",
+ recording,
+ recordingId,
+ cursorCaptureMode,
+ reserveOnly,
+ );
},
isNativeWindowsCaptureAvailable: () => {
return ipcRenderer.invoke("is-native-windows-capture-available");
diff --git a/electron/windows-update.test.ts b/electron/windows-update.test.ts
index 4a0d73c1e..3474eff29 100644
--- a/electron/windows-update.test.ts
+++ b/electron/windows-update.test.ts
@@ -90,6 +90,39 @@ describe("installWindowsUpdate", () => {
expect(isWindowsUpdatePending()).toBe(false);
});
+ it("checks edits made during download before disabling windows or elevating", async () => {
+ let finishDownload: ((paths: string[]) => void) | undefined;
+ download.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finishDownload = resolve;
+ }),
+ );
+ let unsaved = false;
+ const canInstall = vi.fn(() => !unsaved);
+ const install = installWindowsUpdate(download, canInstall);
+ expect(canInstall).not.toHaveBeenCalled();
+ unsaved = true;
+ finishDownload?.(["installer.exe"]);
+ await install;
+ expect(canInstall).toHaveBeenCalledOnce();
+ expect(spawn).not.toHaveBeenCalled();
+ expect(mocks.window.setEnabled).not.toHaveBeenCalled();
+ expect(isWindowsUpdatePending()).toBe(false);
+ });
+
+ it("handles stderr pipe errors and still uses the helper outcome", async () => {
+ const install = installWindowsUpdate(download);
+ await vi.waitFor(() => expect(spawn).toHaveBeenCalledOnce());
+ expect(() => child.stderr.emit("error", new Error("pipe failed"))).not.toThrow();
+ child.stderr.write("installer.exe could not be launched: 1223\r\n");
+ child.emit("close", 1);
+ await install;
+ expect(mocks.quit).not.toHaveBeenCalled();
+ expect(mocks.window.setEnabled.mock.calls).toEqual([[false], [true]]);
+ expect(isWindowsUpdatePending()).toBe(false);
+ });
+
it("retains the app and controls after No, and permits retry", async () => {
const install = installWindowsUpdate(download);
await vi.waitFor(() => expect(spawn).toHaveBeenCalledOnce());
diff --git a/electron/windows-update.ts b/electron/windows-update.ts
index 7c1982978..458aba03f 100644
--- a/electron/windows-update.ts
+++ b/electron/windows-update.ts
@@ -19,6 +19,7 @@ export function assertWindowsUpdateIdle(): void {
* The prompt names the installer itself; no elevated shell or probe is launched. */
export async function installWindowsUpdate(
downloadInstaller: () => Promise<string[]>,
+ canInstall: () => boolean = () => true,
): Promise<void> {
assertWindowsUpdateIdle();
updatePending = true;
@@ -27,6 +28,8 @@ export async function installWindowsUpdate(
// A missing cache can require a network download: keep the windows interactive.
const [installerPath] = await downloadInstaller();
if (!installerPath) throw new Error("No downloaded Windows update installer");
+ // No await between this late readiness check and disabling the current windows.
+ if (!canInstall()) return;
handedOver = await elevateInstaller(installerPath);
} finally {
// An accepted handoff remains pending through asynchronous before-quit cleanup.
@@ -58,6 +61,9 @@ async function elevateInstaller(installerPath: string): Promise<boolean> {
child.stderr.on("data", (chunk: string) => {
stderr += chunk;
});
+ child.stderr.on("error", () => {
+ // The helper's close result remains authoritative if its stderr pipe fails.
+ });
child.once("error", reject);
// Wait for close so the helper's error output has drained too; do not unref it.
child.once("close", (exitCode) => resolve({ exitCode, stderr }));
diff --git a/src/hooks/useScreenRecorder.restartFailure.test.tsx b/src/hooks/useScreenRecorder.restartFailure.test.tsx
index 63c78d916..990e2745d 100644
--- a/src/hooks/useScreenRecorder.restartFailure.test.tsx
+++ b/src/hooks/useScreenRecorder.restartFailure.test.tsx
@@ -13,7 +13,7 @@ vi.mock("sonner", () => ({
// The browser pipeline's MediaRecorder, cut down to what Restart touches: a stop that
// fires "stop", and a take already streamed to disk.
vi.mock("./recorderHandle", () => ({
- createRecorderHandle: () => {
+ createRecorderHandle: vi.fn(() => {
const recorder = Object.assign(new EventTarget(), {
state: "recording" as RecordingState,
stop: () => undefined,
@@ -28,10 +28,11 @@ vi.mock("./recorderHandle", () => ({
isStreaming: () => true,
discard: async () => undefined,
};
- },
+ }),
}));
import { toast } from "sonner";
+import { createRecorderHandle } from "./recorderHandle";
import { useScreenRecorder } from "./useScreenRecorder";
type ElectronAPI = Window["electronAPI"];
@@ -50,7 +51,7 @@ function stubElectronAPI(platform: "win32" | "linux") {
showCountdownOverlay: vi.fn(async () => true),
setCountdownOverlayValue: vi.fn(async () => true),
hideCountdownOverlay: vi.fn(async () => true),
- setRecordingState: vi.fn(),
+ setRecordingState: vi.fn(async () => ({ success: true })),
discardCursorTelemetry: vi.fn(),
isNativeWindowsCaptureAvailable: vi.fn(async () => ({ success: true, available: true })),
startNativeWindowsRecording: vi.fn(async () => ({ success: true, recordingId: 7 })),
@@ -84,7 +85,7 @@ function stubBrowserCapture() {
}));
Object.defineProperty(navigator, "mediaDevices", {
configurable: true,
- value: { getUserMedia },
+ value: { getUserMedia, getDisplayMedia: getUserMedia },
});
vi.stubGlobal(
"MediaStream",
@@ -132,6 +133,7 @@ async function restart(view: RecorderView) {
beforeEach(() => {
vi.useFakeTimers();
vi.mocked(toast.error).mockClear();
+ vi.mocked(createRecorderHandle).mockClear();
});
afterEach(() => {
@@ -143,6 +145,46 @@ afterEach(() => {
// Restart discards the take before the next one is asked for. When that one does not
// start, the take is gone and the user has to be told (#995).
+describe("browser take start reservation", () => {
+ it("does not construct a recorder when the main process refuses a queued Windows take", async () => {
+ const capture = stubBrowserCapture();
+ api.getPlatform.mockReturnValue("win32");
+ api.isNativeWindowsCaptureAvailable.mockResolvedValue({
+ success: true,
+ available: false,
+ reason: "missing-helper",
+ });
+ api.setRecordingState.mockResolvedValue({
+ success: false,
+ error: "A Windows update is pending",
+ });
+ const view = renderHook(() => useScreenRecorder());
+ await settle();
+ await act(async () => {
+ await view.result.current.startRecordingImmediately();
+ });
+ expect(view.result.current.recording).toBe(false);
+ expect(createRecorderHandle).not.toHaveBeenCalled();
+ expect(toast.error).toHaveBeenCalledWith("A Windows update is pending");
+ const stream = await capture.mock.results[0].value;
+ expect(stream.getTracks()[0].stop).toHaveBeenCalled();
+ });
+
+ it("releases the claim when recorder construction fails", async () => {
+ stubBrowserCapture();
+ vi.mocked(createRecorderHandle).mockImplementationOnce(() => {
+ throw new Error("recorder failed");
+ });
+ const view = renderHook(() => useScreenRecorder());
+ await settle();
+ await act(async () => {
+ await view.result.current.startRecordingImmediately();
+ });
+ expect(view.result.current.recording).toBe(false);
+ expect(api.setRecordingState).toHaveBeenCalledWith(false);
+ });
+});
+
describe("useScreenRecorder Restart that does not start a new take", () => {
it("says the take was discarded on native Windows", async () => {
stubElectronAPI("win32");
diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.ts
index 3ec0a4ac4..65b750fac 100644
--- a/src/hooks/useScreenRecorder.ts
+++ b/src/hooks/useScreenRecorder.ts
@@ -1813,6 +1813,8 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
) => {
const platform = window.electronAPI.getPlatform();
const browserCursorCaptureMode = effectiveBrowserCursorMode(platform, cursorCaptureMode);
+ let browserStartClaimed = false;
+ let browserRecorderStarted = false;
try {
if (!isCountdownRunActive(countdownRunToken)) {
@@ -2072,6 +2074,20 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
return;
}
+ // Reserve the take before constructing MediaRecorder. Start cursor sampling below
+ // as before, so this handshake does not shift the cursor/video time origin.
+ const claim = await window.electronAPI.setRecordingState(
+ true,
+ undefined,
+ browserCursorCaptureMode,
+ true,
+ );
+ if (!claim.success) throw new Error(claim.error ?? "The recording could not start.");
+ browserStartClaimed = true;
+ if (!isCountdownRunActive(countdownRunToken)) {
+ teardownMedia();
+ return;
+ }
recordingId.current = Date.now();
const activeRecordingId = recordingId.current;
screenRecorder.current = createRecorderHandle(
@@ -2110,6 +2126,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
setRecording(true);
setPaused(false);
setElapsedSeconds(0);
+ browserRecorderStarted = true;
window.electronAPI?.setRecordingState(true, recordingId.current, browserCursorCaptureMode);
const activeScreenRecorder = screenRecorder.current;
@@ -2147,6 +2164,12 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
screenRecorder.current = null;
webcamRecorder.current = null;
teardownMedia();
+ } finally {
+ if (browserStartClaimed && !browserRecorderStarted) {
+ await window.electronAPI.setRecordingState(false).catch((error) => {
+ console.warn("Failed to release the recording start:", error);
+ });
+ }
}
};