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(recording): say when a Restart lost the take on Windows and Linux too

EtienneLescot1b102ddce4ca
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index 95473f902..ace4341ea 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -115,7 +115,6 @@ import { recordingStorageProblem } from "../recording/diskSpaceCheck";
import {
describeSalvagedTake,
nativeMacSalvageTarget,
- removeEmptyNativeMacCapture,
salvageNativeMacCapture,
} from "../recording/nativeMacCaptureSalvage";
import {
@@ -135,6 +134,7 @@ import {
terminateNativeWindowsCapture,
waitForNativeWindowsCaptureStop,
} from "../recording/nativeWindowsCaptureStop";
+import { removeEmptyCaptureOutput } from "../recording/removeEmptyCaptureOutput";
import { patchWebmDurationOnDisk } from "../recording/webm-duration";
import { reindexRecordingOnDisk } from "../recording/webm-seek-index";
import {
@@ -2658,6 +2658,7 @@ export function registerIpcHandlers(
ipcMain.handle(
"start-native-linux-recording",
async (_, request: NativeLinuxRecordingRequest) => {
+ let outputPath: string | null = null;
try {
if (process.platform !== "linux") {
return { success: false, error: "Native Linux capture requires Linux." };
@@ -2673,7 +2674,7 @@ export function registerIpcHandlers(
typeof request?.recordingId === "number" && Number.isFinite(request.recordingId)
? request.recordingId
: Date.now();
- const outputPath = path.join(RECORDINGS_DIR, `${RECORDING_FILE_PREFIX}${recordingId}.mp4`);
+ outputPath = path.join(RECORDINGS_DIR, `${RECORDING_FILE_PREFIX}${recordingId}.mp4`);
const cursorCaptureMode =
normalizeCursorCaptureMode(request?.cursor?.mode) ?? "editable-overlay";
@@ -2742,6 +2743,11 @@ export function registerIpcHandlers(
linuxNativeCaptureSession = null;
linuxNativeCaptureRecordingId = null;
linuxNativeCaptureCursorMode = "editable-overlay";
+ // The helper opens its mp4 on the first frame, before it reports capture
+ // started, so an encoder that failed there leaves it empty.
+ if (outputPath) {
+ await removeEmptyCaptureOutput(outputPath);
+ }
return { success: false, error: String(error) };
}
},
@@ -3071,9 +3077,23 @@ export function registerIpcHandlers(
};
} catch (error) {
console.error("Failed to start native Windows recording:", error);
- nativeWindowsCaptureProcess?.kill();
+ const failedProc = nativeWindowsCaptureProcess;
+ const failedOutputPaths = [
+ nativeWindowsCaptureTargetPath,
+ nativeWindowsCaptureWebcamTargetPath,
+ ];
detachNativeWindowsCaptureOutputDrain();
resetNativeWindowsCaptureState();
+ // Awaited, not just killed: a helper still alive holds its mp4 open, and
+ // the empty one it created could not be removed below.
+ if (failedProc) {
+ await terminateNativeWindowsCapture(failedProc).catch(() => false);
+ }
+ for (const outputPath of failedOutputPaths) {
+ if (outputPath) {
+ await removeEmptyCaptureOutput(outputPath);
+ }
+ }
await stopCursorRecording();
return { success: false, error: String(error) };
}
@@ -3299,7 +3319,7 @@ export function registerIpcHandlers(
nativeMacPauseRanges = [];
nativeMacIsPaused = false;
if (failedOutputPath) {
- await removeEmptyNativeMacCapture(failedOutputPath);
+ await removeEmptyCaptureOutput(failedOutputPath);
}
await stopCursorRecording();
return { success: false, error: error instanceof Error ? error.message : String(error) };
diff --git a/electron/recording/nativeMacCaptureSalvage.test.ts b/electron/recording/nativeMacCaptureSalvage.test.ts
index 18102e482..1cf39180c 100644
--- a/electron/recording/nativeMacCaptureSalvage.test.ts
+++ b/electron/recording/nativeMacCaptureSalvage.test.ts
@@ -7,7 +7,6 @@ import {
describeSalvagedTake,
inspectNativeMacCapture,
nativeMacSalvageTarget,
- removeEmptyNativeMacCapture,
salvageNativeMacCapture,
} from "./nativeMacCaptureSalvage";
@@ -234,30 +233,6 @@ describe("nativeMacSalvageTarget", () => {
});
});
-describe("removeEmptyNativeMacCapture", () => {
- it("deletes the empty file a start that never began leaves", async () => {
- const file = path.join(dir, "empty.mp4");
- await fs.writeFile(file, "");
- await removeEmptyNativeMacCapture(file);
- await expect(fs.stat(file)).rejects.toThrow();
- });
-
- it("never deletes a file with a single byte in it", async () => {
- const file = await take("writer-died-1s-no-moof", 1);
- await removeEmptyNativeMacCapture(file);
- expect(await sizeOf(file)).toBe(1);
- });
-
- it("leaves a directory alone and says nothing when the file is missing", async () => {
- const sub = await fs.mkdtemp(path.join(dir, "sub-"));
- await removeEmptyNativeMacCapture(sub);
- expect((await fs.stat(sub)).isDirectory()).toBe(true);
- await expect(removeEmptyNativeMacCapture(path.join(dir, "missing.mp4"))).resolves.toBe(
- undefined,
- );
- });
-});
-
describe("describeSalvagedTake", () => {
/** Verbatim from the helper, in the disk-full end-to-end run. */
it("keeps the helper's sentence and adds a description that says something", () => {
diff --git a/electron/recording/nativeMacCaptureSalvage.ts b/electron/recording/nativeMacCaptureSalvage.ts
index 6071e1d09..90f3d6dc6 100644
--- a/electron/recording/nativeMacCaptureSalvage.ts
+++ b/electron/recording/nativeMacCaptureSalvage.ts
@@ -509,24 +509,6 @@ export function nativeMacSalvageTarget(
return !result.ok && result.exited && targetPath ? targetPath : null;
}
-/**
- * Deletes the file a failed start left, only while it is still empty.
- *
- * The helper creates its output before the first frame, so a start that never
- * began leaves a 0-byte mp4. Any byte on disk keeps the file: an empty one holds
- * nothing to lose. Never throws.
- */
-export async function removeEmptyNativeMacCapture(filePath: string): Promise<void> {
- try {
- const stats = await fs.stat(filePath);
- if (stats.isFile() && stats.size === 0) {
- await fs.rm(filePath, { force: true });
- }
- } catch {
- // Nothing there, or nothing we may remove: either way nothing is lost.
- }
-}
-
/** NSError descriptions that say nothing a person can act on. */
const GENERIC_ERROR_DESCRIPTIONS = new Set(["The operation could not be completed"]);
diff --git a/electron/recording/removeEmptyCaptureOutput.test.ts b/electron/recording/removeEmptyCaptureOutput.test.ts
new file mode 100644
index 000000000..0f51d122b
--- /dev/null
+++ b/electron/recording/removeEmptyCaptureOutput.test.ts
@@ -0,0 +1,38 @@
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { removeEmptyCaptureOutput } from "./removeEmptyCaptureOutput";
+
+let dir: string;
+
+beforeAll(async () => {
+ dir = await fs.mkdtemp(path.join(os.tmpdir(), "empty-capture-output-"));
+});
+
+afterAll(async () => {
+ await fs.rm(dir, { recursive: true, force: true });
+});
+
+describe("removeEmptyCaptureOutput", () => {
+ it("deletes the empty file a start that never began leaves", async () => {
+ const file = path.join(dir, "empty.mp4");
+ await fs.writeFile(file, "");
+ await removeEmptyCaptureOutput(file);
+ await expect(fs.stat(file)).rejects.toThrow();
+ });
+
+ it("never deletes a file with a single byte in it", async () => {
+ const file = path.join(dir, "one-byte.mp4");
+ await fs.writeFile(file, "x");
+ await removeEmptyCaptureOutput(file);
+ expect((await fs.stat(file)).size).toBe(1);
+ });
+
+ it("leaves a directory alone and says nothing when the file is missing", async () => {
+ const sub = await fs.mkdtemp(path.join(dir, "sub-"));
+ await removeEmptyCaptureOutput(sub);
+ expect((await fs.stat(sub)).isDirectory()).toBe(true);
+ await expect(removeEmptyCaptureOutput(path.join(dir, "missing.mp4"))).resolves.toBe(undefined);
+ });
+});
diff --git a/electron/recording/removeEmptyCaptureOutput.ts b/electron/recording/removeEmptyCaptureOutput.ts
new file mode 100644
index 000000000..7d42e49bf
--- /dev/null
+++ b/electron/recording/removeEmptyCaptureOutput.ts
@@ -0,0 +1,19 @@
+import fs from "node:fs/promises";
+
+/**
+ * Deletes the file a failed native start left, only while it is still empty.
+ *
+ * Every native helper may create its output before the first frame, so a start
+ * that never began can leave a 0-byte mp4. Any byte on disk keeps the file: an
+ * empty one holds nothing to lose. Never throws.
+ */
+export async function removeEmptyCaptureOutput(filePath: string): Promise<void> {
+ try {
+ const stats = await fs.stat(filePath);
+ if (stats.isFile() && stats.size === 0) {
+ await fs.rm(filePath, { force: true });
+ }
+ } catch {
+ // Nothing there, or nothing we may remove: either way nothing is lost.
+ }
+}
diff --git a/src/hooks/useScreenRecorder.restartFailure.test.tsx b/src/hooks/useScreenRecorder.restartFailure.test.tsx
new file mode 100644
index 000000000..63c78d916
--- /dev/null
+++ b/src/hooks/useScreenRecorder.restartFailure.test.tsx
@@ -0,0 +1,228 @@
+// @vitest-environment jsdom
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/contexts/I18nContext", () => ({
+ useScopedT: () => (key: string) => key,
+}));
+
+vi.mock("sonner", () => ({
+ toast: { error: vi.fn(), success: vi.fn(), info: vi.fn(), warning: vi.fn() },
+}));
+
+// 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: () => {
+ const recorder = Object.assign(new EventTarget(), {
+ state: "recording" as RecordingState,
+ stop: () => undefined,
+ });
+ recorder.stop = () => {
+ recorder.state = "inactive";
+ recorder.dispatchEvent(new Event("stop"));
+ };
+ return {
+ recorder,
+ recordedBlobPromise: Promise.resolve(new Blob()),
+ isStreaming: () => true,
+ discard: async () => undefined,
+ };
+ },
+}));
+
+import { toast } from "sonner";
+import { useScreenRecorder } from "./useScreenRecorder";
+
+type ElectronAPI = Window["electronAPI"];
+type RecorderView = { result: { current: ReturnType<typeof useScreenRecorder> } };
+
+const SOURCE = { id: "screen:0:0", name: "Screen 1", display_id: "1", thumbnail: "" };
+
+let api: Record<string, ReturnType<typeof vi.fn>>;
+
+/** The platform is pinned through `getPlatform`, which is what the hook branches on. */
+function stubElectronAPI(platform: "win32" | "linux") {
+ api = {
+ getRecordingPrefs: vi.fn(async () => null),
+ getPlatform: vi.fn(() => platform),
+ getSelectedSource: vi.fn(async () => SOURCE),
+ showCountdownOverlay: vi.fn(async () => true),
+ setCountdownOverlayValue: vi.fn(async () => true),
+ hideCountdownOverlay: vi.fn(async () => true),
+ setRecordingState: vi.fn(),
+ discardCursorTelemetry: vi.fn(),
+ isNativeWindowsCaptureAvailable: vi.fn(async () => ({ success: true, available: true })),
+ startNativeWindowsRecording: vi.fn(async () => ({ success: true, recordingId: 7 })),
+ stopNativeWindowsRecording: vi.fn(async () => ({ success: true, discarded: true })),
+ isNativeLinuxCaptureAvailable: vi.fn(async () => ({ success: true, available: true })),
+ prepareNativeLinuxRecording: vi.fn(async () => ({ success: false })),
+ cancelNativeLinuxPrepare: vi.fn(async () => ({ success: true })),
+ startNativeLinuxRecording: vi.fn(async () => ({ success: true, recordingId: 7 })),
+ stopNativeLinuxRecording: vi.fn(async () => ({ success: true, discarded: true })),
+ };
+ window.electronAPI = api as unknown as ElectronAPI;
+}
+
+/** A Linux machine without the PipeWire helper: the browser pipeline records. */
+function stubBrowserCapture() {
+ stubElectronAPI("linux");
+ api.isNativeLinuxCaptureAvailable.mockResolvedValue({
+ success: true,
+ available: false,
+ reason: "missing-helper",
+ });
+ const videoTrack = {
+ stop: vi.fn(),
+ applyConstraints: vi.fn(async () => undefined),
+ getSettings: () => ({ width: 1920, height: 1080, frameRate: 60 }),
+ };
+ const getUserMedia = vi.fn(async () => ({
+ getTracks: () => [videoTrack],
+ getVideoTracks: () => [videoTrack],
+ getAudioTracks: () => [],
+ }));
+ Object.defineProperty(navigator, "mediaDevices", {
+ configurable: true,
+ value: { getUserMedia },
+ });
+ vi.stubGlobal(
+ "MediaStream",
+ class {
+ private tracks: unknown[] = [];
+ addTrack(track: unknown) {
+ this.tracks.push(track);
+ }
+ getTracks() {
+ return this.tracks;
+ }
+ getAudioTracks() {
+ return [];
+ }
+ },
+ );
+ vi.stubGlobal("MediaRecorder", { isTypeSupported: () => true });
+ return getUserMedia;
+}
+
+/** Runs every pending timer and microtask; `waitFor` would poll the faked timers. */
+async function settle(ms = 0) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(ms);
+ });
+}
+
+/** Through the 3 s countdown into a running take. */
+async function startTake(view: RecorderView) {
+ await settle();
+ await act(async () => {
+ view.result.current.toggleRecording();
+ });
+ await settle(3_500);
+ expect(view.result.current.recording).toBe(true);
+}
+
+async function restart(view: RecorderView) {
+ await act(async () => {
+ await view.result.current.restartRecording();
+ });
+ await settle();
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.mocked(toast.error).mockClear();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ Reflect.deleteProperty(navigator, "mediaDevices");
+});
+
+// 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("useScreenRecorder Restart that does not start a new take", () => {
+ it("says the take was discarded on native Windows", async () => {
+ stubElectronAPI("win32");
+ const view = renderHook(() => useScreenRecorder());
+ await startTake(view);
+
+ api.startNativeWindowsRecording.mockResolvedValue({
+ success: false,
+ error: "Timed out waiting for native Windows capture to start",
+ });
+ await restart(view);
+
+ expect(api.stopNativeWindowsRecording).toHaveBeenCalledWith(true);
+ expect(api.startNativeWindowsRecording).toHaveBeenCalledTimes(2);
+ expect(view.result.current.recording).toBe(false);
+ expect(toast.error).toHaveBeenCalledWith("recording.restartFailed");
+ });
+
+ it("says nothing more on native Windows when the new take starts", async () => {
+ stubElectronAPI("win32");
+ const view = renderHook(() => useScreenRecorder());
+ await startTake(view);
+
+ await restart(view);
+
+ expect(view.result.current.recording).toBe(true);
+ expect(toast.error).not.toHaveBeenCalledWith("recording.restartFailed");
+ });
+
+ it("says the take was discarded on native Linux when the portal picker is dismissed", async () => {
+ stubElectronAPI("linux");
+ const view = renderHook(() => useScreenRecorder());
+ await startTake(view);
+
+ api.startNativeLinuxRecording.mockResolvedValue({
+ success: false,
+ error: "Error: the screen share was cancelled",
+ });
+ await restart(view);
+
+ expect(api.stopNativeLinuxRecording).toHaveBeenCalledWith(true);
+ expect(api.startNativeLinuxRecording).toHaveBeenCalledTimes(2);
+ expect(view.result.current.recording).toBe(false);
+ expect(toast.error).toHaveBeenCalledWith("recording.restartFailed");
+ });
+
+ it("says nothing more on native Linux when the new take starts", async () => {
+ stubElectronAPI("linux");
+ const view = renderHook(() => useScreenRecorder());
+ await startTake(view);
+
+ await restart(view);
+
+ expect(view.result.current.recording).toBe(true);
+ expect(toast.error).not.toHaveBeenCalledWith("recording.restartFailed");
+ });
+
+ it("says the take was discarded on the browser pipeline when capture fails", async () => {
+ const getUserMedia = stubBrowserCapture();
+ const view = renderHook(() => useScreenRecorder());
+ await startTake(view);
+
+ getUserMedia.mockRejectedValue(new Error("Could not start video source"));
+ await restart(view);
+
+ expect(api.discardCursorTelemetry).toHaveBeenCalled();
+ expect(getUserMedia).toHaveBeenCalledTimes(2);
+ expect(view.result.current.recording).toBe(false);
+ expect(toast.error).toHaveBeenCalledWith("recording.restartFailed");
+ });
+
+ it("says nothing more on the browser pipeline when the new take starts", async () => {
+ const getUserMedia = stubBrowserCapture();
+ const view = renderHook(() => useScreenRecorder());
+ await startTake(view);
+
+ await restart(view);
+
+ expect(getUserMedia).toHaveBeenCalledTimes(2);
+ expect(view.result.current.recording).toBe(true);
+ expect(toast.error).not.toHaveBeenCalledWith("recording.restartFailed");
+ });
+});
diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.ts
index cc77e907b..80d721cbb 100644
--- a/src/hooks/useScreenRecorder.ts
+++ b/src/hooks/useScreenRecorder.ts
@@ -2289,6 +2289,24 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
void startRecordCountdown();
};
+ /**
+ * The second half of Restart. The previous take is already gone by now: every
+ * capture path holds one take at a time, so it is discarded before this one is
+ * asked for. A start that did not begin has to say so, or the take is lost
+ * without a word (#995).
+ */
+ const startRecordingAfterRestart = async () => {
+ await startRecording();
+ if (
+ !nativeWindowsRecording.current &&
+ !nativeMacRecording.current &&
+ !nativeLinuxRecording.current &&
+ !screenRecorder.current
+ ) {
+ toast.error(t("recording.restartFailed"));
+ }
+ };
+
const restartRecording = async () => {
if (restarting.current) return;
@@ -2298,7 +2316,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
discardRecordingId.current = activeRecordingId;
try {
await finalizeNativeWindowsRecording(true);
- await startRecording();
+ await startRecordingAfterRestart();
} finally {
restarting.current = false;
}
@@ -2310,10 +2328,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
discardRecordingId.current = activeRecordingId;
try {
await finalizeNativeMacRecording(true);
- await startRecording();
- if (!nativeMacRecording.current) {
- toast.error(t("recording.restartFailed"));
- }
+ await startRecordingAfterRestart();
} finally {
restarting.current = false;
}
@@ -2325,7 +2340,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
discardRecordingId.current = activeRecordingId;
try {
await finalizeNativeLinuxRecording(true);
- await startRecording();
+ await startRecordingAfterRestart();
} finally {
restarting.current = false;
}
@@ -2364,7 +2379,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
await Promise.all(stopPromises);
try {
- await startRecording();
+ await startRecordingAfterRestart();
} finally {
restarting.current = false;
}