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(macos): keep a timed-out helper out of the next take, and say why a take ended
Etienne Lescot186dd5a7189b
diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.tsindex 0fce60828..838ef6e77 100644--- a/electron/electron-env.d.ts+++ b/electron/electron-env.d.ts@@ -319,6 +319,8 @@ interface Window {success: boolean;session?: RecordingSession | null;canceled?: boolean;+ /** Why this recording ended before it was stopped, when it did. */+ warning?: string;}>;findRecordingCamera: (videoPath: string) => Promise<{success: boolean;diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex 3cd452afb..d270e8b77 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -83,6 +83,7 @@ import { toHelperRect } from "../native-bridge/helperCoordinates";import { scoreDeviceNameMatch } from "../recording/deviceNameMatching";import {type NativeMacCaptureExit,+ nativeMacDiscardTargets,sendNativeMacStopCommand,waitForNativeMacCaptureStop,} from "../recording/nativeMacCaptureStop";@@ -775,6 +776,18 @@ let nativeMacIsPaused = false;* point at which its output has been read in full.*/const nativeMacCaptureExits = new WeakMap<ChildProcessWithoutNullStreams, NativeMacCaptureExit>();+/**+ * Each macOS helper's own output. The shared `nativeMacCaptureOutput` belongs to+ * the current take; a helper whose stop timed out keeps talking after the next+ * take has started, and its late `recording-stopped` must not settle that take.+ */+const nativeMacCaptureOutputs = new WeakMap<ChildProcessWithoutNullStreams, string>();+/**+ * Why the last macOS take ended before it was stopped, keyed by the file it was+ * kept in. Handed to whatever opens that recording next — the editor or the CLI —+ * because the HUD that ran the stop closes as the editor opens.+ */+let nativeMacRecordingWarning: { screenVideoPath: string; message: string } | null = null;/** True while stop-native-mac-recording runs: the take is ending on purpose. */let nativeMacStopInFlight = false;// Global frame of the region captured by the SCK helper (see getSelectedSourceBounds).@@ -1511,14 +1524,22 @@ function attachNativeMacCaptureOutputDrain();const drain = (chunk: Buffer) => {const text = chunk.toString();- nativeMacCaptureOutput += text;+ nativeMacCaptureOutputs.set(proc, (nativeMacCaptureOutputs.get(proc) ?? "") + text);+ // Only the current take's helper feeds the shared buffer and event bus that the+ // start wait, the microphone check and the diagnostics bundle read.+ const isCurrent = nativeMacCaptureProcess === proc;+ if (isCurrent) {+ nativeMacCaptureOutput += text;+ }lineBuffer += text;const lines = lineBuffer.split(/\r?\n/);lineBuffer = lines.pop() ?? "";for (const line of lines) {const event = tryParseNativeHelperEvent(line.trim());if (event) {- dispatchNativeMacHelperEvent(event);+ if (isCurrent) {+ dispatchNativeMacHelperEvent(event);+ }watchLiveTake(event);}}@@ -2787,6 +2808,7 @@ export function registerIpcHandlers(nativeMacPauseRanges = [];nativeMacIsPaused = false;nativeMacStopInFlight = false;+ nativeMacRecordingWarning = null;activeMacCaptureBounds = null;const cursorStartTimeMs = Date.now();@@ -3174,7 +3196,7 @@ export function registerIpcHandlers(const stopResultPromise = waitForNativeMacCaptureStop({proc,targetPath: preferredPath,- readOutput: () => nativeMacCaptureOutput,+ readOutput: () => nativeMacCaptureOutputs.get(proc) ?? "",readExit: () => nativeMacCaptureExits.get(proc) ?? null,});sendNativeMacStopCommand(proc);@@ -3187,15 +3209,11 @@ export function registerIpcHandlers(}if (discard) {pendingCursorRecordingData = null;- // Discarding does not wait on the stop having worked: a take thrown away- // after its writer died used to stay behind as an orphan .mp4.- const discardedPath = stopResult.ok ? stopResult.screenVideoPath : preferredPath;- if (discardedPath) {- await Promise.all([- fs.rm(discardedPath, { force: true }),- fs.rm(`${discardedPath}.cursor.json`, { force: true }),- ]);- }+ await Promise.all(+ nativeMacDiscardTargets(stopResult, preferredPath).map((target) =>+ fs.rm(target, { force: true }),+ ),+ );if (!stopResult.ok) {console.warn("[native-sck] discarded a take whose stop did not complete", {reason: stopResult.reason,@@ -3210,11 +3228,14 @@ export function registerIpcHandlers(reason: stopResult.reason,message: stopResult.message,helperExited: stopResult.exited,- output: nativeMacCaptureOutput.trim(),+ output: (nativeMacCaptureOutputs.get(proc) ?? "").trim(),});return { success: false, error: stopResult.message };}const screenVideoPath = stopResult.screenVideoPath;+ nativeMacRecordingWarning = stopResult.warning+ ? { screenVideoPath, message: stopResult.warning }+ : null;if (stopResult.warning) {console.warn("[native-sck] the take ended before it was stopped; its recording was kept", {warning: stopResult.warning,@@ -4254,9 +4275,14 @@ export function registerIpcHandlers(});ipcMain.handle("get-current-recording-session", () => {- return currentRecordingSession- ? { success: true, session: currentRecordingSession }- : { success: false };+ if (!currentRecordingSession) {+ return { success: false };+ }+ const warning =+ nativeMacRecordingWarning?.screenVideoPath === currentRecordingSession.screenVideoPath+ ? nativeMacRecordingWarning.message+ : undefined;+ return { success: true, session: currentRecordingSession, ...(warning ? { warning } : {}) };});// returns the webcam path (if any) for a given screen video bydiff --git a/electron/recording/nativeMacCaptureStop.test.ts b/electron/recording/nativeMacCaptureStop.test.tsindex 83150de1e..9855b7c2d 100644--- a/electron/recording/nativeMacCaptureStop.test.ts+++ b/electron/recording/nativeMacCaptureStop.test.ts@@ -4,6 +4,7 @@ import { PassThrough, Writable } from "node:stream";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {type NativeMacCaptureExit,+ nativeMacDiscardTargets,readNativeMacHelperEvents,readNativeMacStopOutcome,sendNativeMacStopCommand,@@ -17,12 +18,19 @@ function line(event: Record<string, unknown>) {return `${JSON.stringify(event)}\n`;}+// The messages as the Swift helper really prints them: the interruption embeds the+// writer's NSError, and a stream the system stopped reports its NSError alone.+const WRITER_DIED_MESSAGE =+ 'Recording stopped: the video file could not be written (video append: Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSLocalizedFailureReason=An unknown error occurred (-16364)}).';+const CAPTURE_STOPPED_MESSAGE =+ 'Error Domain=com.apple.ScreenCaptureKit.SCStreamErrorDomain Code=-3815 "The stream was stopped by the system." UserInfo={NSLocalizedDescription=The stream was stopped by the system.}';+const started = line({ event: "recording-started", width: 3840, height: 2160 });const stopped = line({ event: "recording-stopped", screenPath: TARGET });const writerDied = line({event: "error",code: "writer-failed-during-capture",- message: "Recording stopped: the video file could not be written (video append: -11800).",+ message: WRITER_DIED_MESSAGE,});const writerFailed = line({event: "error",@@ -32,7 +40,7 @@ const writerFailed = line({const captureStopped = line({event: "error",code: "capture-stopped-with-error",- message: "The display was disconnected.",+ message: CAPTURE_STOPPED_MESSAGE,});/**@@ -131,8 +139,7 @@ describe("readNativeMacStopOutcome", () => {expect(readNativeMacStopOutcome(started + captureStopped + stopped, null, TARGET)).toEqual({ok: true,screenVideoPath: TARGET,- warning:- "Recording ended early (The display was disconnected). The part recorded until then was saved.",+ warning: `Recording ended early (${CAPTURE_STOPPED_MESSAGE}). The part recorded until then was saved.`,});});@@ -140,7 +147,7 @@ describe("readNativeMacStopOutcome", () => {expect(readNativeMacStopOutcome(started + writerDied + writerFailed, null, TARGET)).toEqual({ok: false,reason: "helper-failed",- message: "Recording stopped: the video file could not be written (video append: -11800).",+ message: WRITER_DIED_MESSAGE,exited: false,});});@@ -164,7 +171,7 @@ describe("readNativeMacStopOutcome", () => {).toEqual({ok: false,reason: "helper-failed",- message: "Recording stopped: the video file could not be written (video append: -11800).",+ message: WRITER_DIED_MESSAGE,exited: true,});});@@ -206,7 +213,7 @@ describe("waitForNativeMacCaptureStop", () => {await expect(pending).resolves.toMatchObject({ok: false,- message: "Recording stopped: the video file could not be written (video append: -11800).",+ message: WRITER_DIED_MESSAGE,exited: true,});});@@ -288,3 +295,40 @@ describe("sendNativeMacStopCommand", () => {expect(sendNativeMacStopCommand(asProc(helper))).toBe(false);});});++describe("nativeMacDiscardTargets", () => {+ it("removes the file the helper finalized", () => {+ expect(nativeMacDiscardTargets({ ok: true, screenVideoPath: "/rec/a.mp4" }, TARGET)).toEqual([+ "/rec/a.mp4",+ "/rec/a.mp4.cursor.json",+ ]);+ });++ /** The orphan: a take thrown away after its writer died. */+ it("removes the requested file when the stop failed", () => {+ expect(+ nativeMacDiscardTargets(+ { ok: false, reason: "helper-failed", message: WRITER_DIED_MESSAGE, exited: true },+ TARGET,+ ),+ ).toEqual([TARGET, `${TARGET}.cursor.json`]);+ });++ it("removes the requested file when the stop timed out", () => {+ expect(+ nativeMacDiscardTargets(+ { ok: false, reason: "stop-timeout", message: "timed out", exited: false },+ TARGET,+ ),+ ).toEqual([TARGET, `${TARGET}.cursor.json`]);+ });++ it("has nothing to remove when no file was ever requested", () => {+ expect(+ nativeMacDiscardTargets(+ { ok: false, reason: "helper-failed", message: "x", exited: true },+ null,+ ),+ ).toEqual([]);+ });+});diff --git a/electron/recording/nativeMacCaptureStop.ts b/electron/recording/nativeMacCaptureStop.tsindex b07e5135d..42e665f47 100644--- a/electron/recording/nativeMacCaptureStop.ts+++ b/electron/recording/nativeMacCaptureStop.ts@@ -178,9 +178,11 @@ export function readNativeMacStopOutcome(return null;}- // A helper that exits 0 without a word finalized the file it was asked for —- // unless it had already said the take ended, in which case exit 0 only means- // its command pipe closed.+ // Exit 0 with no terminal word is the command loop reaching stdin EOF without a+ // `stop` — nothing in the app closes that pipe, and `stop()` always reports+ // before its exit(0). It keeps the meaning the stop wait gave it before this+ // module (the requested file), except after an interruption, when nothing+ // finalized that file.if (exit.code === 0 && !exit.signal && targetPath && !interruption) {return { ok: true, screenVideoPath: targetPath };}@@ -224,9 +226,9 @@ export function waitForNativeMacCaptureStop(options: {exited: true,};- // The helper may already be gone: killed, crashed, or exited after stopping- // itself. Node never re-emits `close`, so waiting for one would burn the whole- // timeout on a recorder that has nothing left to say.+ // The helper may already be gone: killed or crashed. (One that stopped itself+ // stays alive until it is sent `stop`.) Node never re-emits `close`, so waiting+ // for one would burn the whole timeout on a recorder that has nothing left to say.const alreadyExited = readExit();if (alreadyExited) {return Promise.resolve(settleFromExit(alreadyExited));@@ -287,3 +289,16 @@ export function sendNativeMacStopCommand(proc: ChildProcessWithoutNullStreams):proc.stdin.write("stop\n");return true;}++/**+ * The files a discarded take leaves behind, whatever its stop returned: a take+ * thrown away after its writer died used to stay on disk as an orphan .mp4,+ * because removing it depended on the stop having worked.+ */+export function nativeMacDiscardTargets(+ result: NativeMacCaptureStopResult,+ targetPath: string | null,+): string[] {+ const screenVideoPath = result.ok ? result.screenVideoPath : targetPath;+ return screenVideoPath ? [screenVideoPath, `${screenVideoPath}.cursor.json`] : [];+}diff --git a/src/cli/CliRecordRunner.tsx b/src/cli/CliRecordRunner.tsxindex e19c451f9..f588caa4c 100644--- a/src/cli/CliRecordRunner.tsx+++ b/src/cli/CliRecordRunner.tsx@@ -284,6 +284,9 @@ export function CliRecordRunner() {cursorDataPath: `${session.screenVideoPath}.cursor.json`,durationMs,...(request?.projectOut ? { projectData: buildDefaultProject(session) } : {}),+ // The take ended before it was stopped but was kept: a script must be+ // able to tell that apart from a clean run.+ ...(sessionResult.warning ? { warnings: [sessionResult.warning] } : {}),});} catch (error) {await fail(error);diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsxindex 681a88031..fabfc3acb 100644--- a/src/components/ai-edition/NewEditorShell.tsx+++ b/src/components/ai-edition/NewEditorShell.tsx@@ -380,7 +380,7 @@ export function NewEditorShell() {void (async () => {if (!window.electronAPI) return;try {- if (await importPendingRecording()) {+ if (await importPendingRecording((warning) => toast.warning(warning))) {toast.success("Recording added to a new project");return;}diff --git a/src/components/ai-edition/recordingImport.test.ts b/src/components/ai-edition/recordingImport.test.tsindex 123c954af..9bc7c5557 100644--- a/src/components/ai-edition/recordingImport.test.ts+++ b/src/components/ai-edition/recordingImport.test.ts@@ -55,6 +55,7 @@ const realActions = {function stubElectronApi(screenVideoPath: string | null,cursorCaptureMode: "editable-overlay" | "system" = "editable-overlay",+ warning?: string,) {let session: {screenVideoPath: string;@@ -63,7 +64,7 @@ function stubElectronApi(} | null = screenVideoPath ? { screenVideoPath, createdAt: 0, cursorCaptureMode } : null;const api = {getCurrentRecordingSession: vi.fn(async () =>- session ? { success: true, session } : { success: false },+ session ? { success: true, session, ...(warning ? { warning } : {}) } : { success: false },),setCurrentRecordingSession: vi.fn(async (next: typeof session) => {session = next;@@ -93,6 +94,33 @@ describe("importPendingRecording", () => {expect(createProject).not.toHaveBeenCalled();});+ // The HUD that stopped a take which ended on its own closes as the editor opens,+ // so the editor has to be the one that says the recording was cut short.+ it("hands over why the take ended early once the import succeeded", async () => {+ stubElectronApi(+ "/recordings/recording-1.mp4",+ "editable-overlay",+ "Recording ended early (stream stopped). The part recorded until then was saved.",+ );+ const onWarning = vi.fn();++ await expect(importPendingRecording(onWarning)).resolves.toBe(true);++ expect(onWarning).toHaveBeenCalledTimes(1);+ expect(onWarning).toHaveBeenCalledWith(+ "Recording ended early (stream stopped). The part recorded until then was saved.",+ );+ });++ it("says nothing about a take that was stopped normally", async () => {+ stubElectronApi("/recordings/recording-1.mp4");+ const onWarning = vi.fn();++ await importPendingRecording(onWarning);++ expect(onWarning).not.toHaveBeenCalled();+ });+it("imports the recording into a new project and consumes the hand-off", async () => {const api = stubElectronApi("C:\\recordings\\recording-1.mp4");diff --git a/src/components/ai-edition/recordingImport.ts b/src/components/ai-edition/recordingImport.tsindex 975a4a144..39b0923bd 100644--- a/src/components/ai-edition/recordingImport.ts+++ b/src/components/ai-edition/recordingImport.ts@@ -297,7 +297,14 @@ export async function maybeSaveFreshRecordingAutoZooms(* reopening the most recent project. Throws if the import itself fails, leaving* the session in place so a later mount can retry it.*/-export async function importPendingRecording(): Promise<boolean> {+export async function importPendingRecording(+ /**+ * Called once the import succeeded, with why the take ended before it was+ * stopped when it did. The HUD that ran the stop closes as the editor opens, so+ * the editor is the only window left to say it.+ */+ onWarning?: (message: string) => void,+): Promise<boolean> {const api = window.electronAPI;if (!api) return false;@@ -305,6 +312,7 @@ export async function importPendingRecording(): Promise<boolean> {const screenPath = result.success ? result.session?.screenVideoPath : undefined;if (!screenPath) return false;const cursorCaptureMode = result.success ? result.session?.cursorCaptureMode : undefined;+ const warning = result.success ? result.warning : undefined;const label = screenPath.split(/[\\/]/).pop() || "Recording";await useProjectStore.getState().createProject(`Recording ${new Date().toLocaleString()}`);@@ -348,5 +356,8 @@ export async function importPendingRecording(): Promise<boolean> {if (latest) {await maybeSaveFreshRecordingAutoZooms(latest);}+ if (warning) {+ onWarning?.(warning);+ }return true;}diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.tsindex 68a50d2c1..8960548b2 100644--- a/src/hooks/useScreenRecorder.ts+++ b/src/hooks/useScreenRecorder.ts@@ -767,9 +767,6 @@ export function useScreenRecorder(): UseScreenRecorderReturn {clearNativeRecordingState();return true;}- if (result.warning) {- toast.warning(result.warning);- }if (webcamResult.asset && result.path) {const attachResult = await window.electronAPI.attachNativeMacWebcamRecording({