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): serialize elevation and block new takes

EtienneLescot84cf72c3f8c7
diff --git a/electron/auto-updater.test.ts b/electron/auto-updater.test.ts
index d6059c405..1b1defee1 100644
--- a/electron/auto-updater.test.ts
+++ b/electron/auto-updater.test.ts
@@ -25,11 +25,15 @@ const mocks = vi.hoisted(() => ({
},
app: { isPackaged: true, getVersion: vi.fn(() => "1.9.2") },
installWindowsUpdate: vi.fn(),
+ assertWindowsUpdateIdle: vi.fn(),
}));
vi.mock("electron", () => ({ app: mocks.app }));
vi.mock("electron-updater", () => ({ autoUpdater: mocks.autoUpdater }));
-vi.mock("./windows-update", () => ({ installWindowsUpdate: mocks.installWindowsUpdate }));
+vi.mock("./windows-update", () => ({
+ installWindowsUpdate: mocks.installWindowsUpdate,
+ assertWindowsUpdateIdle: mocks.assertWindowsUpdateIdle,
+}));
// `reg query` finds no install, so the handover below is the same on every platform.
vi.mock("node:child_process", () => ({ spawnSync: vi.fn(() => ({ status: 1 })) }));
@@ -233,6 +237,21 @@ describe("self-update flow", () => {
expect(mocks.installWindowsUpdate).not.toHaveBeenCalled();
});
+ it("does not enter a legacy Windows handoff while another elevation is pending", async () => {
+ const platform = Object.getOwnPropertyDescriptor(process, "platform");
+ Object.defineProperty(process, "platform", { value: "win32" });
+ mocks.assertWindowsUpdateIdle.mockImplementationOnce(() => {
+ throw new Error("A Windows update is pending");
+ });
+ try {
+ await expect(installSelfUpdate()).rejects.toThrow("Windows update is pending");
+ } finally {
+ if (platform) Object.defineProperty(process, "platform", platform);
+ }
+ expect(mocks.autoUpdater.quitAndInstall).not.toHaveBeenCalled();
+ expect(mocks.installWindowsUpdate).not.toHaveBeenCalled();
+ });
+
it("does not force elevation when the machine install cannot be confirmed", async () => {
const platform = Object.getOwnPropertyDescriptor(process, "platform");
Object.defineProperty(process, "platform", { value: "win32" });
diff --git a/electron/auto-updater.ts b/electron/auto-updater.ts
index 6b26e5a51..3b14b3e40 100644
--- a/electron/auto-updater.ts
+++ b/electron/auto-updater.ts
@@ -115,10 +115,14 @@ export function installsSilently(
export async function installSelfUpdate(): Promise<void> {
const autoUpdater = await getUpdater();
const silent = installsSilently();
- if (process.platform === "win32" && silent && nsisInstallStatus("HKLM") === 0) {
- const { installWindowsUpdate } = await import("./windows-update");
- await installWindowsUpdate(() => autoUpdater.downloadUpdate());
- return;
+ 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) {
+ await installWindowsUpdate(() => autoUpdater.downloadUpdate());
+ return;
+ }
}
// isForceRunAfter=true so the app comes back up.
autoUpdater.quitAndInstall(silent, true);
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index 75c3a23df..255fc9c6c 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -162,6 +162,11 @@ import {
} from "../recording-source-settings";
import { getSttManager } from "../stt";
import { createRunnerWindow } from "../windows";
+import {
+ assertWindowsUpdateIdle,
+ isWindowsUpdatePending,
+ WINDOWS_UPDATE_PENDING_MESSAGE,
+} from "../windows-update";
import { getSourcesByType, shouldEnumerateSourceTypesSeparately } from "./desktopSourceTypes";
import { registerNativeBridgeHandlers } from "./nativeBridge";
import { createNativeMacMidCaptureErrorWatch } from "./nativeMacMidCaptureErrorWatch";
@@ -2338,6 +2343,9 @@ export function registerIpcHandlers(
// Asked before every take starts. A disk that fills up mid-take used to be found only
// when the take was saved, and the take was lost with it.
ipcMain.handle("check-recording-storage", async () => {
+ if (isWindowsUpdatePending()) {
+ return { success: false, error: WINDOWS_UPDATE_PENDING_MESSAGE };
+ }
const problem = await recordingStorageProblem(RECORDINGS_DIR);
if (!problem) return { success: true };
if (problem.kind === "unavailable") {
@@ -2514,6 +2522,7 @@ export function registerIpcHandlers(
/** The editor's Record button: over to the HUD, which starts the take by itself. */
function startNewRecording() {
+ assertWindowsUpdateIdle();
_switchToHud?.();
const hudWindow = getMainWindow();
if (hudWindow && !hudWindow.isDestroyed()) {
@@ -2895,6 +2904,9 @@ export function registerIpcHandlers(
ipcMain.handle(
"start-native-windows-recording",
async (_, request: NativeWindowsRecordingRequest) => {
+ if (isWindowsUpdatePending()) {
+ return { success: false, error: WINDOWS_UPDATE_PENDING_MESSAGE };
+ }
try {
if (!isWindowsGraphicsCaptureOsSupported()) {
return {
@@ -3047,6 +3059,7 @@ export function registerIpcHandlers(
pendingCursorRecordingData = null;
}
+ assertWindowsUpdateIdle();
const proc = spawn(helperPath, [JSON.stringify(config)], {
cwd: RECORDINGS_DIR,
stdio: ["pipe", "pipe", "pipe"],
diff --git a/electron/main.ts b/electron/main.ts
index b0a7d38c2..255782c4a 100644
--- a/electron/main.ts
+++ b/electron/main.ts
@@ -88,6 +88,7 @@ import {
createNotesWindow,
createSourceSelectorWindow,
} from "./windows";
+import { isWindowsUpdatePending } from "./windows-update";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -188,6 +189,7 @@ const defaultTrayIcon = getTrayIcon("openscreen.png", trayIconSize);
const recordingTrayIcon = getTrayIcon("rec-button.png", trayIconSize);
function createWindow() {
+ if (isWindowsUpdatePending()) return;
if (mainWindow && !mainWindow.isDestroyed()) {
return;
}
@@ -1476,6 +1478,7 @@ appReady?.then(async () => {
await ensureRecordingsDir();
function switchToHudWrapper() {
+ if (isWindowsUpdatePending()) return;
if (mainWindow) {
isForceClosing = true;
mainWindow.close();
diff --git a/electron/mcp/app-recorder.test.ts b/electron/mcp/app-recorder.test.ts
index 78b76be4e..f552a8426 100644
--- a/electron/mcp/app-recorder.test.ts
+++ b/electron/mcp/app-recorder.test.ts
@@ -2,7 +2,7 @@
// hand, and the editor is a document behind a revision.
import path from "node:path";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import {
type AxcutDocument,
createEmptyDocument,
@@ -113,6 +113,19 @@ async function started(recorder: ReturnType<typeof setup>["recorder"], calls: st
}
describe("an MCP take in the app", () => {
+ it("restores settings and permits retry when the handoff rejects a take", async () => {
+ const startTake = vi.fn().mockImplementationOnce(() => {
+ throw new Error("A Windows update is pending");
+ });
+ const { recorder, calls } = setup({ startTake });
+ await expect(recorder.start(REQUEST)).rejects.toThrow("Windows update is pending");
+ expect(calls).toEqual(["prepare My App", "restore"]);
+ const retry = recorder.start(REQUEST);
+ await vi.waitFor(() => expect(startTake).toHaveBeenCalledTimes(2));
+ recorder.recordingChanged(true);
+ expect((await retry).startedAt).toBeGreaterThan(0);
+ });
+
it("goes through the recording bar, and hands back the project the editor opened", async () => {
const { recorder, calls, editor } = setup();
const starting = recorder.start(REQUEST);
diff --git a/electron/mcp/app-recorder.ts b/electron/mcp/app-recorder.ts
index 6f2134147..586ccd15f 100644
--- a/electron/mcp/app-recorder.ts
+++ b/electron/mcp/app-recorder.ts
@@ -248,7 +248,13 @@ export function createAppRecorder(deps: AppRecorderDeps): AppRecorder {
},
};
current = take;
- deps.startTake();
+ try {
+ deps.startTake();
+ } catch (error) {
+ current = null;
+ take.restore();
+ throw error;
+ }
const startedAt = await within(take.started.promise, timing.startMs);
if (startedAt === null) {
// A take that starts after this is the user's: nothing here waits for it.
diff --git a/electron/windows-update.test.ts b/electron/windows-update.test.ts
index 8514ecf3c..4a0d73c1e 100644
--- a/electron/windows-update.test.ts
+++ b/electron/windows-update.test.ts
@@ -3,10 +3,15 @@ import { EventEmitter } from "node:events";
import path from "node:path";
import { PassThrough } from "node:stream";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { installWindowsUpdate } from "./windows-update";
+
+let installWindowsUpdate: typeof import("./windows-update").installWindowsUpdate;
+let isWindowsUpdatePending: typeof import("./windows-update").isWindowsUpdatePending;
+let assertWindowsUpdateIdle: typeof import("./windows-update").assertWindowsUpdateIdle;
const mocks = vi.hoisted(() => ({
quit: vi.fn(),
+ spawn: vi.fn(),
+ getAllWindows: vi.fn(),
window: {
isEnabled: vi.fn(() => true),
setEnabled: vi.fn(),
@@ -15,16 +20,21 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("electron", () => ({
app: { quit: mocks.quit },
- BrowserWindow: { getAllWindows: () => [mocks.window] },
+ BrowserWindow: { getAllWindows: mocks.getAllWindows },
}));
-vi.mock("node:child_process", () => ({ spawn: vi.fn() }));
+vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));
describe("installWindowsUpdate", () => {
let child: EventEmitter & { stderr: PassThrough; unref: ReturnType<typeof vi.fn> };
let download: ReturnType<typeof vi.fn<() => Promise<string[]>>>;
- beforeEach(() => {
+ beforeEach(async () => {
+ vi.resetModules();
vi.clearAllMocks();
vi.stubGlobal("process", { ...process, resourcesPath: "C:\\OpenScreen\\resources" });
+ ({ installWindowsUpdate, isWindowsUpdatePending, assertWindowsUpdateIdle } = await import(
+ "./windows-update"
+ ));
+ mocks.getAllWindows.mockReturnValue([mocks.window]);
mocks.window.isEnabled.mockReturnValue(true);
mocks.window.isDestroyed.mockReturnValue(false);
child = Object.assign(new EventEmitter(), { stderr: new PassThrough(), unref: vi.fn() });
@@ -33,6 +43,53 @@ describe("installWindowsUpdate", () => {
});
afterEach(() => vi.unstubAllGlobals());
+ it("keeps download interactive, then snapshots current windows for elevation", async () => {
+ let finishDownload: ((paths: string[]) => void) | undefined;
+ download.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finishDownload = resolve;
+ }),
+ );
+ const install = installWindowsUpdate(download);
+ expect(mocks.window.setEnabled).not.toHaveBeenCalled();
+ expect(spawn).not.toHaveBeenCalled();
+ expect(isWindowsUpdatePending()).toBe(true);
+ expect(assertWindowsUpdateIdle).toThrow("Windows update is pending");
+ await expect(installWindowsUpdate(download)).rejects.toThrow("Windows update is pending");
+ expect(download).toHaveBeenCalledOnce();
+ const newWindow = {
+ isEnabled: vi.fn(() => false),
+ setEnabled: vi.fn(),
+ isDestroyed: vi.fn(() => false),
+ };
+ mocks.getAllWindows.mockReturnValue([mocks.window, newWindow]);
+ finishDownload?.(["C:\\update\\installer.exe"]);
+ await vi.waitFor(() => expect(spawn).toHaveBeenCalledOnce());
+ expect(mocks.window.setEnabled.mock.calls).toEqual([[false]]);
+ expect(newWindow.setEnabled.mock.calls).toEqual([[false]]);
+ child.stderr.write("installer.exe could not be launched: 1223\r\n");
+ child.emit("close", 1);
+ await install;
+ expect(mocks.window.setEnabled.mock.calls).toEqual([[false], [true]]);
+ expect(newWindow.setEnabled.mock.calls).toEqual([[false], [false]]);
+ expect(isWindowsUpdatePending()).toBe(false);
+ expect(assertWindowsUpdateIdle).not.toThrow();
+ });
+
+ it("rejects a second elevation without changing the first window snapshot", async () => {
+ const install = installWindowsUpdate(download);
+ await vi.waitFor(() => expect(spawn).toHaveBeenCalledOnce());
+ await expect(installWindowsUpdate(download)).rejects.toThrow("Windows update is pending");
+ expect(spawn).toHaveBeenCalledOnce();
+ expect(mocks.window.setEnabled.mock.calls).toEqual([[false]]);
+ child.stderr.write("installer.exe could not be launched: 1223\r\n");
+ child.emit("close", 1);
+ await install;
+ 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());
@@ -62,6 +119,8 @@ describe("installWindowsUpdate", () => {
await install;
expect(mocks.quit).toHaveBeenCalledOnce();
expect(mocks.window.setEnabled.mock.calls).toEqual([[false]]);
+ expect(isWindowsUpdatePending()).toBe(true);
+ await expect(installWindowsUpdate(download)).rejects.toThrow("Windows update is pending");
});
it("passes the verified installer as a literal without shell interpolation", async () => {
@@ -70,7 +129,13 @@ describe("installWindowsUpdate", () => {
await vi.waitFor(() => expect(spawn).toHaveBeenCalledOnce());
const [executable, args, options] = vi.mocked(spawn).mock.calls[0];
expect(executable).toBe(path.join(process.resourcesPath, "elevate.exe"));
- expect(args).toEqual(["C:\\update\\it's $a`b.exe", "--updated", "/S", "--force-run"]);
+ expect(args).toEqual([
+ "C:\\update\\it's $a`b.exe",
+ "--updated",
+ "/S",
+ "--force-run",
+ "/allusers",
+ ]);
expect(options).toEqual({
detached: true,
stdio: ["ignore", "ignore", "pipe"],
@@ -105,13 +170,15 @@ describe("installWindowsUpdate", () => {
await rejection;
expect(mocks.window.setEnabled.mock.calls).toEqual([[false], [false]]);
expect(mocks.quit).not.toHaveBeenCalled();
+ expect(isWindowsUpdatePending()).toBe(false);
});
it("restores the app if verifying the cached download fails", async () => {
download.mockRejectedValue(new Error("checksum mismatch"));
await expect(installWindowsUpdate(download)).rejects.toThrow("checksum mismatch");
expect(spawn).not.toHaveBeenCalled();
- expect(mocks.window.setEnabled.mock.calls).toEqual([[false], [true]]);
+ expect(mocks.window.setEnabled).not.toHaveBeenCalled();
+ expect(isWindowsUpdatePending()).toBe(false);
});
it("refuses to launch without a verified installer", async () => {
diff --git a/electron/windows-update.ts b/electron/windows-update.ts
index 32aece9b0..7c1982978 100644
--- a/electron/windows-update.ts
+++ b/electron/windows-update.ts
@@ -2,30 +2,55 @@ import { spawn } from "node:child_process";
import path from "node:path";
import { app, BrowserWindow } from "electron";
+let updatePending = false;
+export const WINDOWS_UPDATE_PENDING_MESSAGE =
+ "A Windows update is pending. Try again after the update completes or is cancelled.";
+
+export function isWindowsUpdatePending(): boolean {
+ return updatePending;
+}
+
+export function assertWindowsUpdateIdle(): void {
+ if (updatePending) throw new Error(WINDOWS_UPDATE_PENDING_MESSAGE);
+}
+
/** Elevate the verified per-machine installer before quitting (#1461). The bundled
* helper returns after ShellExecute's UAC decision, without waiting for installation.
* The prompt names the installer itself; no elevated shell or probe is launched. */
export async function installWindowsUpdate(
downloadInstaller: () => Promise<string[]>,
): Promise<void> {
+ assertWindowsUpdateIdle();
+ updatePending = true;
+ let handedOver = false;
+ try {
+ // 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");
+ handedOver = await elevateInstaller(installerPath);
+ } finally {
+ // An accepted handoff remains pending through asynchronous before-quit cleanup.
+ if (!handedOver) updatePending = false;
+ }
+}
+
+async function elevateInstaller(installerPath: string): Promise<boolean> {
const windows = BrowserWindow.getAllWindows().map((window) => ({
window,
enabled: window.isEnabled(),
}));
let handedOver = false;
try {
- // Prevent a new take while elevation is pending, including the gap after accepting it.
+ // Main-process guards also prevent takes and new HUDs outside these windows.
for (const { window } of windows) window.setEnabled(false);
- // The public API reuses and verifies the cached installer.
- const [installerPath] = await downloadInstaller();
- if (!installerPath) throw new Error("No downloaded Windows update installer");
const { exitCode, stderr } = await new Promise<{
exitCode: number | null;
stderr: string;
}>((resolve, reject) => {
const child = spawn(
path.join(process.resourcesPath, "elevate.exe"),
- [installerPath, "--updated", "/S", "--force-run"],
+ // Pin the confirmed machine copy even if an HKCU install appears during UAC.
+ [installerPath, "--updated", "/S", "--force-run", "/allusers"],
{ detached: true, stdio: ["ignore", "ignore", "pipe"], windowsHide: true },
);
let stderr = "";
@@ -38,13 +63,14 @@ export async function installWindowsUpdate(
child.once("close", (exitCode) => resolve({ exitCode, stderr }));
});
// electron-builder's bundled helper exits 1 and prints the Win32 error on failure.
- if (exitCode === 1 && stderr.trimEnd().endsWith(" could not be launched: 1223")) return;
+ if (exitCode === 1 && stderr.trimEnd().endsWith(" could not be launched: 1223")) return false;
if (exitCode !== 0) {
throw new Error(`Windows update elevation failed (${exitCode}): ${stderr.trim()}`);
}
// Preserve normal before-quit cleanup; NSIS is already elevated and waiting for files.
app.quit();
handedOver = true;
+ return true;
} finally {
if (!handedOver) {
for (const { window, enabled } of windows) {