Skip to content

Create polished demo videos without editing skills. Mac/Windows/Linux

fix: harden native capture lifecycle

webadderall31d8db76f766
diff --git a/electron/native/ScreenCaptureKitRecorder.swift b/electron/native/ScreenCaptureKitRecorder.swift
index 7e72b8be..d4c05a3a 100644
--- a/electron/native/ScreenCaptureKitRecorder.swift
+++ b/electron/native/ScreenCaptureKitRecorder.swift
@@ -24,6 +24,11 @@ let writerReadinessPollAttempts = 100
let writerReadinessPollInterval: UInt64 = 10_000_000
final class ScreenCaptureRecorder: NSObject, SCStreamOutput, SCStreamDelegate {
+ private struct CaptureFinalizationResult {
+ let outputResult: Result<String, Error>
+ let interactiveStopParticipated: Bool
+ }
+
private let queue = DispatchQueue(label: "recordly.screencapturekit.video")
private var assetWriter: AVAssetWriter?
private var videoInput: AVAssetWriterInput?
@@ -52,7 +57,8 @@ final class ScreenCaptureRecorder: NSObject, SCStreamOutput, SCStreamDelegate {
private var trackedWindowId: UInt32?
private var windowValidationTask: Task<Void, Never>?
private var isFinalizing = false
- private var finalizationWaiters: [CheckedContinuation<Result<String, Error>, Never>] = []
+ private var interactiveStopParticipated = false
+ private var finalizationWaiters: [CheckedContinuation<CaptureFinalizationResult, Never>] = []
private var inlineAudioInput: AVAssetWriterInput?
private var firstInlineAudioSampleTime: CMTime?
private var capturesSystemAudio = false
@@ -280,7 +286,8 @@ final class ScreenCaptureRecorder: NSObject, SCStreamOutput, SCStreamDelegate {
}
func stopCapture() async throws -> String {
- return try await finalizeCapture()
+ let finalization = await finalizeCapture(interactive: true)
+ return try finalization.outputResult.get()
}
func pauseCapture() async -> Bool {
@@ -383,41 +390,51 @@ final class ScreenCaptureRecorder: NSObject, SCStreamOutput, SCStreamDelegate {
/// Starts one finalization operation after all previously delivered samples on
/// the recorder queue have drained. Manual stop and automatic window-close
/// detection join the same operation instead of racing the asset writers.
- private func finalizeCapture() async throws -> String {
- let result: Result<String, Error> = await withCheckedContinuation { continuation in
+ private func finalizeCapture(interactive: Bool) async -> CaptureFinalizationResult {
+ await withCheckedContinuation { continuation in
queue.async {
if self.isFinalizing {
+ self.interactiveStopParticipated = self.interactiveStopParticipated || interactive
self.finalizationWaiters.append(continuation)
return
}
guard self.isRecording else {
- continuation.resume(returning: .failure(NSError(
- domain: "RecordlyCapture",
- code: 9,
- userInfo: [NSLocalizedDescriptionKey: "No recording in progress"]
- )))
+ continuation.resume(returning: CaptureFinalizationResult(
+ outputResult: .failure(NSError(
+ domain: "RecordlyCapture",
+ code: 9,
+ userInfo: [NSLocalizedDescriptionKey: "No recording in progress"]
+ )),
+ interactiveStopParticipated: interactive
+ ))
return
}
self.isFinalizing = true
+ self.interactiveStopParticipated = interactive
self.isRecording = false
self.windowValidationTask = nil
self.trackedWindowId = nil
self.finalizationWaiters.append(continuation)
Task {
- let finalizationResult: Result<String, Error>
+ let outputResult: Result<String, Error>
do {
- finalizationResult = .success(try await self.finishCapture())
+ outputResult = .success(try await self.finishCapture())
} catch {
- finalizationResult = .failure(error)
+ outputResult = .failure(error)
}
self.queue.async {
+ let finalizationResult = CaptureFinalizationResult(
+ outputResult: outputResult,
+ interactiveStopParticipated: self.interactiveStopParticipated
+ )
let waiters = self.finalizationWaiters
self.finalizationWaiters.removeAll()
self.isFinalizing = false
+ self.interactiveStopParticipated = false
for waiter in waiters {
waiter.resume(returning: finalizationResult)
}
@@ -425,8 +442,6 @@ final class ScreenCaptureRecorder: NSObject, SCStreamOutput, SCStreamDelegate {
}
}
}
-
- return try result.get()
}
private func finishCapture() async throws -> String {
@@ -713,8 +728,12 @@ final class ScreenCaptureRecorder: NSObject, SCStreamOutput, SCStreamDelegate {
if !windowStillAvailable {
print("WINDOW_UNAVAILABLE")
fflush(stdout)
+ let finalization = await self.finalizeCapture(interactive: false)
+ if finalization.interactiveStopParticipated {
+ return
+ }
do {
- let outputPath = try await self.finalizeCapture()
+ let outputPath = try finalization.outputResult.get()
print("Recording stopped. Output path: \(outputPath)")
fflush(stdout)
exit(0)
diff --git a/electron/native/ScreenCaptureKitRecorder.test.ts b/electron/native/ScreenCaptureKitRecorder.test.ts
new file mode 100644
index 00000000..0e269bd4
--- /dev/null
+++ b/electron/native/ScreenCaptureKitRecorder.test.ts
@@ -0,0 +1,25 @@
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+
+const recorderSource = readFileSync(
+ fileURLToPath(new URL("./ScreenCaptureKitRecorder.swift", import.meta.url)),
+ "utf8",
+);
+
+describe("ScreenCaptureKitRecorder finalization coordination", () => {
+ it("marks manual stops as participants in the shared finalization", () => {
+ expect(recorderSource).toContain("finalizeCapture(interactive: true)");
+ expect(recorderSource).toContain("finalization.outputResult.get()");
+ expect(recorderSource).toContain(
+ "self.interactiveStopParticipated = self.interactiveStopParticipated || interactive",
+ );
+ });
+
+ it("does not let automatic window-close exit preempt a joined manual stop", () => {
+ expect(recorderSource).toContain("self.finalizeCapture(interactive: false)");
+ expect(recorderSource).toMatch(
+ /if finalization\.interactiveStopParticipated\s*\{\s*return\s*\}/,
+ );
+ });
+});
diff --git a/src/hooks/useScreenRecorder.test.ts b/src/hooks/useScreenRecorder.test.ts
index d74e884c..1ddceb4e 100644
--- a/src/hooks/useScreenRecorder.test.ts
+++ b/src/hooks/useScreenRecorder.test.ts
@@ -6,6 +6,7 @@ import {
normalizeBrowserMicrophoneProfile,
resolveBrowserCaptureCursorPolicy,
shouldUseNativeWindowsCaptureForSource,
+ stopAndDiscardNativeCapture,
} from "./useScreenRecorder";
type RecordingState = "inactive" | "recording" | "paused";
@@ -173,6 +174,65 @@ describe("shouldUseNativeWindowsCaptureForSource", () => {
});
});
+describe("stopAndDiscardNativeCapture", () => {
+ it("deletes the partial recording after a successful warm-start stop", async () => {
+ const deleteRecordingFile = vi.fn().mockResolvedValue(undefined);
+
+ await expect(
+ stopAndDiscardNativeCapture({
+ stopNativeScreenRecording: vi.fn().mockResolvedValue({
+ success: true,
+ path: "C:\\Recordly\\warm-start.mp4",
+ }),
+ deleteRecordingFile,
+ }),
+ ).resolves.toEqual({
+ stopSucceeded: true,
+ deleteSucceeded: true,
+ path: "C:\\Recordly\\warm-start.mp4",
+ });
+ expect(deleteRecordingFile).toHaveBeenCalledWith("C:\\Recordly\\warm-start.mp4");
+ });
+
+ it("reports an unsuccessful stop without deleting or confirming cleanup", async () => {
+ const deleteRecordingFile = vi.fn();
+
+ await expect(
+ stopAndDiscardNativeCapture({
+ stopNativeScreenRecording: vi.fn().mockResolvedValue({
+ success: false,
+ error: "helper still running",
+ }),
+ deleteRecordingFile,
+ }),
+ ).resolves.toEqual({
+ stopSucceeded: false,
+ deleteSucceeded: false,
+ error: "helper still running",
+ });
+ expect(deleteRecordingFile).not.toHaveBeenCalled();
+ });
+
+ it("keeps the stopped path available when deletion fails so cleanup can retry", async () => {
+ const deleteError = new Error("file locked");
+
+ await expect(
+ stopAndDiscardNativeCapture({
+ stopNativeScreenRecording: vi.fn().mockResolvedValue({
+ success: true,
+ path: "C:\\Recordly\\warm-start.mp4",
+ }),
+ deleteRecordingFile: vi.fn().mockRejectedValue(deleteError),
+ }),
+ ).resolves.toEqual({
+ stopSucceeded: true,
+ deleteSucceeded: false,
+ path: "C:\\Recordly\\warm-start.mp4",
+ error: deleteError,
+ });
+ });
+});
+
function stopRecording(
recorder: ReturnType<typeof createMockMediaRecorder>,
isNativeRecording: boolean,
diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.ts
index 1c2c1acf..a696c4b2 100644
--- a/src/hooks/useScreenRecorder.ts
+++ b/src/hooks/useScreenRecorder.ts
@@ -262,6 +262,63 @@ export function createBrowserRecordingOptions({
return options;
}
+type NativeCaptureStopResult = {
+ success: boolean;
+ path?: string;
+ error?: string;
+ message?: string;
+};
+
+export type DiscardNativeCaptureResult = {
+ stopSucceeded: boolean;
+ deleteSucceeded: boolean;
+ path?: string;
+ error?: unknown;
+};
+
+export async function stopAndDiscardNativeCapture({
+ stopNativeScreenRecording,
+ deleteRecordingFile,
+}: {
+ stopNativeScreenRecording: () => Promise<NativeCaptureStopResult>;
+ deleteRecordingFile: (path: string) => Promise<unknown>;
+}): Promise<DiscardNativeCaptureResult> {
+ let stoppedResult: NativeCaptureStopResult;
+ try {
+ stoppedResult = await stopNativeScreenRecording();
+ } catch (error) {
+ return { stopSucceeded: false, deleteSucceeded: false, error };
+ }
+
+ if (!stoppedResult.success) {
+ return {
+ stopSucceeded: false,
+ deleteSucceeded: false,
+ error: stoppedResult.error ?? stoppedResult.message,
+ };
+ }
+
+ if (!stoppedResult.path) {
+ return { stopSucceeded: true, deleteSucceeded: true };
+ }
+
+ try {
+ await deleteRecordingFile(stoppedResult.path);
+ return {
+ stopSucceeded: true,
+ deleteSucceeded: true,
+ path: stoppedResult.path,
+ };
+ } catch (error) {
+ return {
+ stopSucceeded: true,
+ deleteSucceeded: false,
+ path: stoppedResult.path,
+ error,
+ };
+ }
+}
+
function createMicrophoneTrackSettingsSnapshot(
stream: MediaStream,
): MicrophoneTrackSettingsSnapshot | null {
@@ -344,6 +401,10 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
const recordingSessionTimestamp = useRef<number | null>(null);
const nativeScreenRecording = useRef(false);
const nativeWindowsRecording = useRef(false);
+ const nativeWarmStartActive = useRef(false);
+ const pendingNativeCleanupPath = useRef<string | null>(null);
+ const recordingStartGeneration = useRef(0);
+ const nativeStopRequestInFlight = useRef(false);
const startInFlight = useRef(false);
const hasPromptedForReselect = useRef(false);
const hasShownNativeWindowsFallbackToast = useRef(false);
@@ -1155,10 +1216,74 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
resetRecordingClock,
]);
+ const discardActiveNativeCapture = useCallback(async () => {
+ const pendingPath = pendingNativeCleanupPath.current;
+ if (pendingPath) {
+ try {
+ await window.electronAPI.deleteRecordingFile(pendingPath);
+ pendingNativeCleanupPath.current = null;
+ } catch (error) {
+ console.warn("Failed to delete pending native capture file:", error);
+ }
+ }
+
+ if (!nativeScreenRecording.current) {
+ return pendingNativeCleanupPath.current === null;
+ }
+ if (nativeStopRequestInFlight.current) {
+ return false;
+ }
+
+ nativeStopRequestInFlight.current = true;
+ let result: DiscardNativeCaptureResult;
+ try {
+ result = await stopAndDiscardNativeCapture({
+ stopNativeScreenRecording: () => window.electronAPI.stopNativeScreenRecording(),
+ deleteRecordingFile: (path) => window.electronAPI.deleteRecordingFile(path),
+ });
+ } finally {
+ nativeStopRequestInFlight.current = false;
+ }
+
+ if (result.stopSucceeded) {
+ nativeScreenRecording.current = false;
+ nativeWindowsRecording.current = false;
+ nativeWarmStartActive.current = false;
+ }
+
+ if (!result.deleteSucceeded && result.path) {
+ pendingNativeCleanupPath.current = result.path;
+ }
+
+ if (!result.stopSucceeded || !result.deleteSucceeded) {
+ console.warn("Failed to fully discard native capture:", result.error);
+ return false;
+ }
+
+ return true;
+ }, []);
+
const stopRecording = useRef(() => {
+ recordingStartGeneration.current += 1;
setPaused(false);
+ if (nativeScreenRecording.current && nativeWarmStartActive.current) {
+ setRecording(false);
+ void (async () => {
+ await discardActiveNativeCapture();
+ cleanupCapturedMedia();
+ await Promise.allSettled([
+ stopMicFallbackRecorder(),
+ stopWebcamRecorder(),
+ window.electronAPI?.setRecordingState(false),
+ ]);
+ })();
+ return;
+ }
if (nativeScreenRecording.current) {
- nativeScreenRecording.current = false;
+ if (nativeStopRequestInFlight.current) {
+ return;
+ }
+ nativeStopRequestInFlight.current = true;
setRecording(false);
setFinalizing(true);
@@ -1174,16 +1299,30 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
const micFallbackBlobPromise = stopMicFallbackRecorder();
const webcamPathPromise = stopWebcamRecorder();
const isNativeWindows = nativeWindowsRecording.current;
- nativeWindowsRecording.current = false;
const ipcStopStart = performance.now();
console.log("[PERF:RENDERER] IPC: stopNativeScreenRecording: STARTED");
- const result = await window.electronAPI.stopNativeScreenRecording();
+ let result: NativeCaptureStopResult;
+ try {
+ result = await window.electronAPI.stopNativeScreenRecording();
+ } catch (error) {
+ result = { success: false, error: getErrorMessage(error) };
+ }
+ nativeStopRequestInFlight.current = false;
console.log(
`[PERF:RENDERER] IPC: stopNativeScreenRecording: COMPLETED in ${(performance.now() - ipcStopStart).toFixed(2)}ms`,
);
+ if (result.success) {
+ nativeScreenRecording.current = false;
+ nativeWindowsRecording.current = false;
+ nativeWarmStartActive.current = false;
+ }
- await window.electronAPI?.setRecordingState(false);
+ try {
+ await window.electronAPI?.setRecordingState(false);
+ } catch (stateError) {
+ console.warn("Failed to reset main-process recording state:", stateError);
+ }
if (!result.success || !result.path) {
console.error(
@@ -1393,8 +1532,11 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
const removeRecordingInterruptedListener = window.electronAPI?.onRecordingInterrupted?.(
(state) => {
void (async () => {
+ recordingStartGeneration.current += 1;
setRecording(false);
nativeScreenRecording.current = false;
+ nativeWindowsRecording.current = false;
+ nativeWarmStartActive.current = false;
cleanupCapturedMedia();
await window.electronAPI.setRecordingState(false);
@@ -1425,13 +1567,33 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
);
return () => {
+ recordingStartGeneration.current += 1;
cleanup?.();
removeRecordingStateListener?.();
removeRecordingInterruptedListener?.();
if (nativeScreenRecording.current) {
- nativeScreenRecording.current = false;
- void window.electronAPI.stopNativeScreenRecording();
+ if (nativeWarmStartActive.current) {
+ void discardActiveNativeCapture();
+ } else if (!nativeStopRequestInFlight.current) {
+ nativeStopRequestInFlight.current = true;
+ void window.electronAPI
+ .stopNativeScreenRecording()
+ .then((result) => {
+ if (result.success) {
+ nativeScreenRecording.current = false;
+ nativeWindowsRecording.current = false;
+ }
+ })
+ .catch((error) => {
+ console.warn("Failed to stop native capture during cleanup:", error);
+ })
+ .finally(() => {
+ nativeStopRequestInFlight.current = false;
+ });
+ }
+ } else if (pendingNativeCleanupPath.current) {
+ void discardActiveNativeCapture();
}
const recorder = mediaRecorder.current;
@@ -1442,12 +1604,15 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
cleanupCapturedMedia();
};
- }, [cleanupCapturedMedia, recoverNativeRecordingSession]);
+ }, [cleanupCapturedMedia, discardActiveNativeCapture, recoverNativeRecordingSession]);
const startRecording = async () => {
if (startInFlight.current) {
return;
}
+ const startGeneration = recordingStartGeneration.current + 1;
+ recordingStartGeneration.current = startGeneration;
+ const startWasCancelled = () => recordingStartGeneration.current !== startGeneration;
let hudSourceSelectionActive = false;
const setHudSourceSelectionActive = (active: boolean) => {
@@ -1465,7 +1630,9 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
try {
const preparedStart = await prepareRecordingStart();
- if (!preparedStart) {
+ if (!preparedStart || startWasCancelled()) {
+ cleanupCapturedMedia();
+ await stopWebcamRecorder();
return;
}
@@ -1477,7 +1644,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
setCountdownActive(true);
try {
const result = await window.electronAPI.startCountdown(countdownDelay);
- if (!result.success || result.cancelled) {
+ if (!result.success || result.cancelled || startWasCancelled()) {
cleanupCapturedMedia();
await stopWebcamRecorder();
return;
@@ -1501,6 +1668,15 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
microphoneLabel: micLabel,
},
);
+ if (nativeResult.success && startWasCancelled()) {
+ nativeScreenRecording.current = true;
+ nativeWindowsRecording.current = useNativeWindowsCapture;
+ nativeWarmStartActive.current = shouldWarmStartNativeCapture;
+ await discardActiveNativeCapture();
+ cleanupCapturedMedia();
+ await stopWebcamRecorder();
+ return;
+ }
if (!nativeResult.success) {
if (useNativeWindowsCapture) {
nativeWindowsCaptureStartFailed = true;
@@ -1533,7 +1709,11 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
nativeScreenRecording.current = true;
nativeWindowsRecording.current = useNativeWindowsCapture;
if (shouldWarmStartNativeCapture) {
+ nativeWarmStartActive.current = true;
const pauseResult = await window.electronAPI.pauseNativeScreenRecording();
+ if (startWasCancelled()) {
+ return;
+ }
if (!pauseResult.success) {
throw new Error(
pauseResult.error ??
@@ -1546,16 +1726,14 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
try {
const countdownResult =
await window.electronAPI.startCountdown(countdownDelay);
- if (!countdownResult.success || countdownResult.cancelled) {
- const stoppedResult =
- await window.electronAPI.stopNativeScreenRecording();
- if (stoppedResult.path) {
- await window.electronAPI.deleteRecordingFile(
- stoppedResult.path,
- );
+ if (
+ !countdownResult.success ||
+ countdownResult.cancelled ||
+ startWasCancelled()
+ ) {
+ if (!startWasCancelled()) {
+ await discardActiveNativeCapture();
}
- nativeScreenRecording.current = false;
- nativeWindowsRecording.current = false;
cleanupCapturedMedia();
await stopWebcamRecorder();
return;
@@ -1565,6 +1743,9 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
}
const resumeResult = await window.electronAPI.resumeNativeScreenRecording();
+ if (startWasCancelled()) {
+ return;
+ }
if (!resumeResult.success) {
throw new Error(
resumeResult.error ??
@@ -1572,6 +1753,10 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
"Failed to resume native capture after countdown",
);
}
+ nativeWarmStartActive.current = false;
+ }
+ if (startWasCancelled()) {
+ return;
}
const mainStartedAt = Date.now();
@@ -1647,6 +1832,12 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
);
}
}
+ if (startWasCancelled()) {
+ await stopMicFallbackRecorder();
+ await stopWebcamRecorder();
+ cleanupCapturedMedia();
+ return;
+ }
setRecording(true);
try {
@@ -2018,15 +2209,10 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
: "Failed to start recording",
);
setRecording(false);
+ if (nativeScreenRecording.current) {
+ await discardActiveNativeCapture();
+ }
try {
- if (nativeScreenRecording.current) {
- nativeScreenRecording.current = false;
- nativeWindowsRecording.current = false;
- const stoppedResult = await window.electronAPI.stopNativeScreenRecording();
- if (stoppedResult.path) {
- await window.electronAPI.deleteRecordingFile(stoppedResult.path);
- }
- }
await window.electronAPI?.setRecordingState(false);
} catch (stateError) {
console.warn("Failed to reset main-process recording state:", stateError);
@@ -2134,6 +2320,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
}, [markRecordingResumed, paused, recording, resumeMicFallbackRecorder]);
const cancelRecording = useCallback(() => {
+ recordingStartGeneration.current += 1;
if (!recording) return;
setPaused(false);
markRecordingResumed(Date.now());
@@ -2152,19 +2339,10 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
resolvedWebcamPath.current = null;
if (nativeScreenRecording.current) {
- nativeScreenRecording.current = false;
- nativeWindowsRecording.current = false;
setRecording(false);
window.electronAPI?.setRecordingState(false);
void (async () => {
- try {
- const result = await window.electronAPI.stopNativeScreenRecording();
- if (result?.path) {
- await window.electronAPI.deleteRecordingFile(result.path);
- }
- } catch {
- // Best-effort cleanup
- }
+ await discardActiveNativeCapture();
})();
return;
}
@@ -2178,7 +2356,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
setRecording(false);
window.electronAPI?.setRecordingState(false);
}
- }, [cleanupCapturedMedia, markRecordingResumed, recording]);
+ }, [cleanupCapturedMedia, discardActiveNativeCapture, markRecordingResumed, recording]);
const toggleRecording = async () => {
if (starting || countdownActive || finalizing) {