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(settings): stop camera pref ping-pong and stale select-source writes

超超超超超级喜欢你的达妮娅9bdf5d05bfee
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index e3a02808b..3d6e267af 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -117,6 +117,11 @@ import { registerNativeBridgeHandlers } from "./nativeBridge";
import { createNativeMacMidCaptureErrorWatch } from "./nativeMacMidCaptureErrorWatch";
import { registerRecordingPrefsHandlers } from "./recordingPrefs";
import { RecordingStreamRegistry, registerRecordingStreamHandlers } from "./recordingStream";
+import {
+ resetSelectSource,
+ type SelectSourceContext,
+ selectSourceWithOwnership,
+} from "./selectSourceOwnership";
const PROJECT_FILE_EXTENSION = "openscreen";
export const SHORTCUTS_FILE = path.join(app.getPath("userData"), "shortcuts.json");
@@ -602,6 +607,7 @@ type AttachNativeMacWebcamRecordingInput = {
let selectedSource: SelectedSource | null = null;
let selectedDesktopSource: DesktopCapturerSource | null = null;
let lastEnumeratedSources = new Map<string, DesktopCapturerSource>();
+const selectSourceGeneration = { value: 0 };
let currentProjectPath: string | null = null;
let currentRecordingSession: RecordingSession | null = null;
@@ -1982,54 +1988,49 @@ export function registerIpcHandlers(
}));
});
+ const selectSourceContext: SelectSourceContext<DesktopCapturerSource> = {
+ generation: selectSourceGeneration,
+ getSelected: () => ({ source: selectedSource, live: selectedDesktopSource }),
+ setSelected: (source, live) => {
+ selectedSource = source;
+ selectedDesktopSource = live;
+ },
+ getCached: (id) => lastEnumeratedSources.get(id) ?? null,
+ replaceCache: (sources) => {
+ lastEnumeratedSources = new Map(sources.map((candidate) => [candidate.id, candidate]));
+ },
+ };
+
ipcMain.handle(
"select-source",
async (_, source: SelectedSource, options?: { persist?: boolean }) => {
- // Reuse the exact source object returned during enumeration to avoid
- // Windows window-source id mismatches across separate getSources() calls.
- selectedDesktopSource =
- typeof source.id === "string" ? (lastEnumeratedSources.get(source.id) ?? null) : null;
-
- if (!selectedDesktopSource && typeof source.id === "string") {
- try {
- const sources = await desktopCapturer.getSources({
- types: ["screen", "window"],
- thumbnailSize: { width: 0, height: 0 },
- fetchWindowIcons: true,
- });
- lastEnumeratedSources = new Map(sources.map((candidate) => [candidate.id, candidate]));
- selectedDesktopSource = lastEnumeratedSources.get(source.id) ?? null;
- } catch {
- selectedDesktopSource = null;
- }
- }
- if (!selectedDesktopSource) {
- selectedSource = null;
- broadcastSelectedSource(null);
- return null;
- }
- selectedSource = {
- id: selectedDesktopSource.id,
- name: selectedDesktopSource.name,
- display_id: selectedDesktopSource.display_id,
- };
- // Persist only a descriptor built from the freshly enumerated live object.
- // A failed write must not keep the picker open after a valid live pick.
- if (shouldPersistSelectedSource(options)) {
- try {
- appSettings.setLastSource(
- describeRecordingSource(process.platform, selectedSource as Required<SelectedSource>),
- );
- } catch (error) {
- console.warn("Failed to persist the selected recording source:", error);
+ const next = await selectSourceWithOwnership(
+ selectSourceContext,
+ { id: source.id, name: source.name, display_id: source.display_id },
+ options,
+ {
+ getSources: () =>
+ desktopCapturer.getSources({
+ types: ["screen", "window"],
+ thumbnailSize: { width: 0, height: 0 },
+ fetchWindowIcons: true,
+ }),
+ persist: (live) => {
+ appSettings.setLastSource(
+ describeRecordingSource(process.platform, live as Required<SelectedSource>),
+ );
+ },
+ broadcast: broadcastSelectedSource,
+ shouldPersist: shouldPersistSelectedSource,
+ },
+ );
+ if (next) {
+ const sourceSelectorWin = getSourceSelectorWindow();
+ if (sourceSelectorWin) {
+ sourceSelectorWin.close();
}
}
- broadcastSelectedSource(selectedSource);
- const sourceSelectorWin = getSourceSelectorWindow();
- if (sourceSelectorWin) {
- sourceSelectorWin.close();
- }
- return selectedSource;
+ return next;
},
);
@@ -2098,9 +2099,7 @@ export function registerIpcHandlers(
defaultRecordingPrefs,
getMainWindow,
() => {
- selectedSource = null;
- selectedDesktopSource = null;
- broadcastSelectedSource(null);
+ resetSelectSource(selectSourceContext, broadcastSelectedSource);
},
() => BrowserWindow.getAllWindows(),
);
diff --git a/electron/ipc/selectSourceOwnership.test.ts b/electron/ipc/selectSourceOwnership.test.ts
new file mode 100644
index 000000000..88d839af2
--- /dev/null
+++ b/electron/ipc/selectSourceOwnership.test.ts
@@ -0,0 +1,120 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ resetSelectSource,
+ type SelectSourceContext,
+ selectSourceWithOwnership,
+} from "./selectSourceOwnership";
+
+type Live = { id: string; name: string; display_id: string };
+
+function createContext() {
+ let selected: {
+ source: { name: string; id?: string; display_id?: string } | null;
+ live: Live | null;
+ } = {
+ source: null,
+ live: null,
+ };
+ let cache = new Map<string, Live>();
+ const ctx: SelectSourceContext<Live> = {
+ generation: { value: 0 },
+ getSelected: () => selected,
+ setSelected: (source, live) => {
+ selected = { source, live };
+ },
+ getCached: (id) => cache.get(id) ?? null,
+ replaceCache: (sources) => {
+ cache = new Map(sources.map((source) => [source.id, source]));
+ },
+ };
+ return {
+ ctx,
+ get selected() {
+ return selected;
+ },
+ seedCache(source: Live) {
+ cache.set(source.id, source);
+ },
+ };
+}
+
+const sourceA: Live = { id: "screen:a", name: "Display A", display_id: "1" };
+const sourceB: Live = { id: "screen:b", name: "Display B", display_id: "2" };
+
+describe("selectSourceWithOwnership", () => {
+ it("does not restore A after reset while A is still enumerating", async () => {
+ const harness = createContext();
+ let resolveA!: (sources: Live[]) => void;
+ const persist = vi.fn();
+ const broadcast = vi.fn();
+ const pendingA = selectSourceWithOwnership(
+ harness.ctx,
+ sourceA,
+ { persist: true },
+ {
+ getSources: () =>
+ new Promise<Live[]>((resolve) => {
+ resolveA = resolve;
+ }),
+ persist,
+ broadcast,
+ shouldPersist: () => true,
+ },
+ );
+
+ resetSelectSource(harness.ctx, broadcast);
+ expect(harness.selected.source).toBeNull();
+
+ resolveA([sourceA, sourceB]);
+ await pendingA;
+
+ expect(harness.selected.source).toBeNull();
+ expect(persist).not.toHaveBeenCalled();
+ expect(broadcast).toHaveBeenLastCalledWith(null);
+ });
+
+ it("keeps B when a slower A enumeration finishes later", async () => {
+ const harness = createContext();
+ harness.seedCache(sourceB);
+ let resolveA!: (sources: Live[]) => void;
+ const persist = vi.fn();
+ const broadcast = vi.fn();
+
+ const pendingA = selectSourceWithOwnership(
+ harness.ctx,
+ sourceA,
+ { persist: true },
+ {
+ getSources: () =>
+ new Promise<Live[]>((resolve) => {
+ resolveA = resolve;
+ }),
+ persist,
+ broadcast,
+ shouldPersist: () => true,
+ },
+ );
+
+ await selectSourceWithOwnership(
+ harness.ctx,
+ sourceB,
+ { persist: true },
+ {
+ getSources: async () => [sourceA, sourceB],
+ persist,
+ broadcast,
+ shouldPersist: () => true,
+ },
+ );
+ expect(harness.selected.source).toMatchObject({ id: "screen:b" });
+ expect(persist).toHaveBeenCalledTimes(1);
+ expect(persist.mock.calls[0]?.[0]).toMatchObject({ id: "screen:b" });
+
+ resolveA([sourceA, sourceB]);
+ await pendingA;
+
+ expect(harness.selected.source).toMatchObject({ id: "screen:b" });
+ expect(persist).toHaveBeenCalledTimes(1);
+ expect(broadcast).toHaveBeenLastCalledWith(expect.objectContaining({ id: "screen:b" }));
+ });
+});
diff --git a/electron/ipc/selectSourceOwnership.ts b/electron/ipc/selectSourceOwnership.ts
new file mode 100644
index 000000000..7a3339f84
--- /dev/null
+++ b/electron/ipc/selectSourceOwnership.ts
@@ -0,0 +1,88 @@
+export type SelectedSourceSnapshot = {
+ name: string;
+ id?: string;
+ display_id?: string;
+};
+
+export type SelectSourceContext<TLive extends { id: string; name: string; display_id: string }> = {
+ generation: { value: number };
+ getSelected: () => { source: SelectedSourceSnapshot | null; live: TLive | null };
+ setSelected: (source: SelectedSourceSnapshot | null, live: TLive | null) => void;
+ getCached: (id: string) => TLive | null;
+ replaceCache: (sources: TLive[]) => void;
+};
+
+export type SelectSourceDeps<TLive extends { id: string; name: string; display_id: string }> = {
+ getSources: () => Promise<TLive[]>;
+ persist: (source: SelectedSourceSnapshot) => void;
+ broadcast: (source: SelectedSourceSnapshot | null) => void;
+ shouldPersist: (options?: { persist?: boolean }) => boolean;
+};
+
+export function bumpSelectSourceGeneration(generation: { value: number }): number {
+ generation.value += 1;
+ return generation.value;
+}
+
+export function resetSelectSource<TLive extends { id: string; name: string; display_id: string }>(
+ ctx: SelectSourceContext<TLive>,
+ broadcast: (source: SelectedSourceSnapshot | null) => void,
+): void {
+ bumpSelectSourceGeneration(ctx.generation);
+ ctx.setSelected(null, null);
+ broadcast(null);
+}
+
+export async function selectSourceWithOwnership<
+ TLive extends { id: string; name: string; display_id: string },
+>(
+ ctx: SelectSourceContext<TLive>,
+ source: { id?: string; name: string; display_id?: string },
+ options: { persist?: boolean } | undefined,
+ deps: SelectSourceDeps<TLive>,
+): Promise<SelectedSourceSnapshot | null> {
+ const generation = bumpSelectSourceGeneration(ctx.generation);
+ let live: TLive | null = typeof source.id === "string" ? ctx.getCached(source.id) : null;
+
+ if (!live && typeof source.id === "string") {
+ try {
+ const sources = await deps.getSources();
+ if (generation !== ctx.generation.value) {
+ return ctx.getSelected().source;
+ }
+ ctx.replaceCache(sources);
+ live = ctx.getCached(source.id);
+ } catch {
+ if (generation !== ctx.generation.value) {
+ return ctx.getSelected().source;
+ }
+ live = null;
+ }
+ }
+
+ if (generation !== ctx.generation.value) {
+ return ctx.getSelected().source;
+ }
+
+ if (!live) {
+ ctx.setSelected(null, null);
+ deps.broadcast(null);
+ return null;
+ }
+
+ const next: SelectedSourceSnapshot = {
+ id: live.id,
+ name: live.name,
+ display_id: live.display_id,
+ };
+ ctx.setSelected(next, live);
+ if (deps.shouldPersist(options)) {
+ try {
+ deps.persist(next);
+ } catch (error) {
+ console.warn("Failed to persist the selected recording source:", error);
+ }
+ }
+ deps.broadcast(next);
+ return next;
+}
diff --git a/src/cli/CliRecordRunner.cameraIsolation.test.tsx b/src/cli/CliRecordRunner.cameraIsolation.test.tsx
new file mode 100644
index 000000000..ea64b299c
--- /dev/null
+++ b/src/cli/CliRecordRunner.cameraIsolation.test.tsx
@@ -0,0 +1,81 @@
+// @vitest-environment jsdom
+import { render, waitFor } from "@testing-library/react";
+import { afterEach, beforeAll, 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() },
+}));
+
+import { CliRecordRunner } from "./CliRecordRunner";
+
+const persistedPrefs = {
+ micEnabled: false,
+ micDeviceId: null,
+ micDeviceName: null,
+ camEnabled: true,
+ camDeviceId: "cam1",
+ camDeviceName: "Camera 1",
+ systemAudioEnabled: false,
+ cursorCaptureMode: "editable-overlay" as const,
+};
+
+describe("CliRecordRunner camera isolation", () => {
+ const getUserMedia = vi.fn(async () => ({
+ getTracks: () => [],
+ getVideoTracks: () => [],
+ }));
+
+ beforeAll(() => {
+ window.history.replaceState(null, "", "/?windowType=cli-record");
+ Object.defineProperty(global.navigator, "mediaDevices", {
+ configurable: true,
+ value: {
+ enumerateDevices: vi.fn(async () => []),
+ getUserMedia,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ },
+ });
+ });
+
+ beforeEach(() => {
+ getUserMedia.mockClear();
+ window.electronAPI = {
+ getRecordingPrefs: vi.fn(async () => persistedPrefs),
+ onRecordingPrefsChanged: vi.fn(() => () => undefined),
+ getPlatform: vi.fn(() => "win32"),
+ getSelectedSource: vi.fn(async () => null),
+ cliGetRequest: vi.fn(
+ () =>
+ new Promise(() => {
+ /* source/request stay pending */
+ }),
+ ),
+ cliLog: vi.fn(),
+ cliDone: vi.fn(async () => undefined),
+ onCliStopRecording: vi.fn(() => () => undefined),
+ getCurrentRecordingSession: vi.fn(async () => ({ success: false, session: null })),
+ getSources: vi.fn(
+ () =>
+ new Promise(() => {
+ /* enumeration pending */
+ }),
+ ),
+ selectSource: vi.fn(),
+ } as unknown as typeof window.electronAPI;
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("does not acquire webcam from GUI prefs while CLI source enumeration is pending", async () => {
+ render(<CliRecordRunner />);
+ await waitFor(() => expect(window.electronAPI.getRecordingPrefs).toHaveBeenCalled());
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(getUserMedia).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/components/ai-edition/AppSettings.test.tsx b/src/components/ai-edition/AppSettings.test.tsx
index 63c80fbdb..e2d6d08da 100644
--- a/src/components/ai-edition/AppSettings.test.tsx
+++ b/src/components/ai-edition/AppSettings.test.tsx
@@ -212,6 +212,24 @@ describe("AppSettings", () => {
expect(window.electronAPI.setRecordingPrefs).not.toHaveBeenCalled();
});
+ it("keeps an unsaved recording draft when appearance is saved", async () => {
+ vi.mocked(window.electronAPI.setProjectAppearanceDefaults).mockImplementation(
+ async (defaults) => ({
+ recording,
+ lastSource: null,
+ appearance: { version: 1 as const, custom: true, defaults },
+ }),
+ );
+ renderSettings();
+ await screen.findByTestId("app-settings-dialog");
+ fireEvent.click(screen.getByLabelText("appSettings.systemAudio"));
+ expect(screen.getByLabelText("appSettings.systemAudio")).toBeChecked();
+ fireEvent.click(screen.getByText("appSettings.useCurrentAppearance"));
+ await waitFor(() => expect(window.electronAPI.setProjectAppearanceDefaults).toHaveBeenCalled());
+ expect(screen.getByLabelText("appSettings.systemAudio")).toBeChecked();
+ expect(window.electronAPI.setRecordingPrefs).not.toHaveBeenCalled();
+ });
+
it("copies the current look and exposes both reset actions", async () => {
renderSettings();
await screen.findByTestId("app-settings-dialog");
diff --git a/src/components/ai-edition/AppSettings.tsx b/src/components/ai-edition/AppSettings.tsx
index 46a016c83..87ecdac62 100644
--- a/src/components/ai-edition/AppSettings.tsx
+++ b/src/components/ai-edition/AppSettings.tsx
@@ -58,7 +58,11 @@ function AppSettings({ open, onClose }: { open: boolean; onClose: () => void })
recording?.camDeviceName ?? undefined,
);
- const run = async (work: () => Promise<AppSettingsSnapshot>) => {
+ const run = async (
+ work: () => Promise<AppSettingsSnapshot>,
+ options: { replaceRecording?: boolean } = {},
+ ) => {
+ const replaceRecording = options.replaceRecording !== false;
const generation = ++generationRef.current;
setStatus("saving");
setError(null);
@@ -66,7 +70,9 @@ function AppSettings({ open, onClose }: { open: boolean; onClose: () => void })
const next = await work();
if (generation !== generationRef.current) return;
setSnapshot(next);
- setRecording(next.recording);
+ if (replaceRecording) {
+ setRecording(next.recording);
+ }
setStatus("saved");
} catch (cause) {
if (generation !== generationRef.current) return;
@@ -256,7 +262,9 @@ function AppSettings({ open, onClose }: { open: boolean; onClose: () => void })
const defaults = projectAppearanceFromEditorSettings(
getEditorSettings(document),
);
- void run(() => window.electronAPI.setProjectAppearanceDefaults(defaults));
+ void run(() => window.electronAPI.setProjectAppearanceDefaults(defaults), {
+ replaceRecording: false,
+ });
}}
>
{t("appSettings.useCurrentAppearance")}
@@ -265,7 +273,9 @@ function AppSettings({ open, onClose }: { open: boolean; onClose: () => void })
type="button"
className={styles.btn}
onClick={() =>
- void run(() => window.electronAPI.resetProjectAppearanceDefaults())
+ void run(() => window.electronAPI.resetProjectAppearanceDefaults(), {
+ replaceRecording: false,
+ })
}
disabled={status === "saving"}
>
diff --git a/src/components/launch/LaunchWindow.tsx b/src/components/launch/LaunchWindow.tsx
index f8fe67052..60fe9be18 100644
--- a/src/components/launch/LaunchWindow.tsx
+++ b/src/components/launch/LaunchWindow.tsx
@@ -3,7 +3,8 @@ import { useI18n, useScopedT } from "@/contexts/I18nContext";
import { getAvailableLocales, getLocaleName } from "@/i18n/loader";
import { loadUserPreferences, saveUserPreferences } from "@/lib/userPreferences";
import { nativeBridgeClient } from "@/native";
-import { type CameraDevice, useCameraDevices } from "../../hooks/useCameraDevices";
+import { type CameraDevice } from "../../hooks/useCameraDevices";
+import { useCameraHudSync } from "../../hooks/useCameraHudSync";
import {
isPlaceholderMicrophoneLabel,
type MicrophoneDevice,
@@ -167,16 +168,22 @@ export function LaunchWindow() {
// Passing `webcamDeviceId` as the preferred device is what keeps the pick the
// user made in the editor's Rec stage: this window is destroyed and rebuilt
// for every recording, so the enumeration default would otherwise revert the
- // camera to whatever the OS lists first on each take.
+ // camera to whatever the OS lists first on each take. Write-back waits for
+ // persisted prefs so an enumeration default cannot overwrite a late cam2.
const {
devices: cameraDevices,
- selectedDevice: selectedCamera,
selectedDeviceId: selectedCameraId,
setSelectedDeviceId: setSelectedCameraId,
isLoading: isCameraDevicesLoading,
isReady: cameraDevicesReady,
error: cameraDevicesError,
- } = useCameraDevices(true, webcamDeviceId, webcamDeviceName);
+ } = useCameraHudSync({
+ webcamDeviceId,
+ webcamDeviceName,
+ recordingPrefsLoaded,
+ setWebcamDeviceId,
+ setWebcamDeviceName,
+ });
// The microphone list stays lazy: enumerating it asks for mic permission,
// which would light the OS "in use" indicator just for opening the HUD.
const {
@@ -203,28 +210,6 @@ export function LaunchWindow() {
}
}, [selectedMicId, micDevices, micDevicesReady, setMicrophoneDeviceId, setMicrophoneDeviceName]);
- // Keyed on the chosen device's own fields, never on the `cameraDevices` array.
- // That array is rebuilt on every `devicechange`, and mirroring the selection
- // back on each rebuild put this effect in a tug-of-war with the preference
- // adoption inside `useCameraDevices`: the two wrote each other's value on
- // every commit and the HUD spun without ever settling.
- const selectedCameraLabel = selectedCamera?.label;
- useEffect(() => {
- if (selectedCameraId) {
- setWebcamDeviceId(selectedCameraId);
- setWebcamDeviceName(selectedCameraLabel);
- } else if (cameraDevicesReady) {
- setWebcamDeviceId(undefined);
- setWebcamDeviceName(undefined);
- }
- }, [
- selectedCameraId,
- selectedCameraLabel,
- cameraDevicesReady,
- setWebcamDeviceId,
- setWebcamDeviceName,
- ]);
-
useEffect(() => {
let cancelled = false;
nativeBridgeClient.system
diff --git a/src/hooks/useCameraHudSync.test.tsx b/src/hooks/useCameraHudSync.test.tsx
new file mode 100644
index 000000000..3fcff1aab
--- /dev/null
+++ b/src/hooks/useCameraHudSync.test.tsx
@@ -0,0 +1,85 @@
+// @vitest-environment jsdom
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { useState } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { useCameraHudSync } from "./useCameraHudSync";
+
+const mockDevices = [
+ { kind: "videoinput", deviceId: "cam1", label: "Camera 1", groupId: "group1" },
+ { kind: "videoinput", deviceId: "cam2", label: "Camera 2", groupId: "group1" },
+];
+
+const mockEnumerateDevices = vi.fn().mockResolvedValue(mockDevices);
+
+Object.defineProperty(global.navigator, "mediaDevices", {
+ value: {
+ enumerateDevices: mockEnumerateDevices,
+ getUserMedia: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ },
+ configurable: true,
+});
+
+function useRecorderBackedCameraSync() {
+ const [webcamDeviceId, setWebcamDeviceId] = useState<string | undefined>(undefined);
+ const [webcamDeviceName, setWebcamDeviceName] = useState<string | undefined>(undefined);
+ const [recordingPrefsLoaded, setRecordingPrefsLoaded] = useState(false);
+ const camera = useCameraHudSync({
+ webcamDeviceId,
+ webcamDeviceName,
+ recordingPrefsLoaded,
+ setWebcamDeviceId,
+ setWebcamDeviceName,
+ });
+ return {
+ camera,
+ webcamDeviceId,
+ webcamDeviceName,
+ recordingPrefsLoaded,
+ setRecordingPrefsLoaded,
+ applyPersistedCamera: (id: string, name: string) => {
+ setWebcamDeviceId(id);
+ setWebcamDeviceName(name);
+ setRecordingPrefsLoaded(true);
+ },
+ };
+}
+
+describe("useCameraHudSync", () => {
+ beforeEach(() => {
+ mockEnumerateDevices.mockResolvedValue(mockDevices);
+ });
+
+ it("keeps enumeration cam1 off the recorder until persisted cam2 arrives, then settles", async () => {
+ let renders = 0;
+ const { result } = renderHook(() => {
+ renders += 1;
+ return useRecorderBackedCameraSync();
+ });
+
+ await waitFor(() => {
+ expect(result.current.camera.selectedDeviceId).toBe("cam1");
+ });
+ expect(result.current.webcamDeviceId).toBeUndefined();
+ expect(result.current.recordingPrefsLoaded).toBe(false);
+
+ act(() => {
+ result.current.applyPersistedCamera("cam2", "Camera 2");
+ });
+
+ await waitFor(() => {
+ expect(result.current.camera.selectedDeviceId).toBe("cam2");
+ expect(result.current.webcamDeviceId).toBe("cam2");
+ expect(result.current.camera.isReady).toBe(true);
+ });
+
+ const settled = renders;
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+ expect(result.current.camera.selectedDeviceId).toBe("cam2");
+ expect(result.current.webcamDeviceId).toBe("cam2");
+ expect(renders - settled).toBeLessThanOrEqual(2);
+ });
+});
diff --git a/src/hooks/useCameraHudSync.ts b/src/hooks/useCameraHudSync.ts
new file mode 100644
index 000000000..c3e45354b
--- /dev/null
+++ b/src/hooks/useCameraHudSync.ts
@@ -0,0 +1,44 @@
+import { useEffect } from "react";
+import { useCameraDevices } from "./useCameraDevices";
+
+/**
+ * HUD camera list plus write-back into recorder prefs.
+ *
+ * Enumeration often finishes before persisted prefs arrive. Writing the
+ * first enumerated camera back immediately would overwrite a late cam2
+ * preference with cam1. Write-back waits until prefs are loaded and the
+ * hook is ready, and is a no-op when the ids already match.
+ */
+export function useCameraHudSync(options: {
+ webcamDeviceId: string | undefined;
+ webcamDeviceName: string | undefined;
+ recordingPrefsLoaded: boolean;
+ setWebcamDeviceId: (deviceId: string | undefined) => void;
+ setWebcamDeviceName: (deviceName: string | undefined) => void;
+}) {
+ const camera = useCameraDevices(true, options.webcamDeviceId, options.webcamDeviceName);
+ const selectedCameraLabel = camera.selectedDevice?.label;
+ const selectedCameraId = camera.selectedDeviceId;
+
+ useEffect(() => {
+ if (!options.recordingPrefsLoaded || !camera.isReady) return;
+ if (selectedCameraId === (options.webcamDeviceId ?? "")) return;
+ if (selectedCameraId) {
+ options.setWebcamDeviceId(selectedCameraId);
+ options.setWebcamDeviceName(selectedCameraLabel);
+ return;
+ }
+ options.setWebcamDeviceId(undefined);
+ options.setWebcamDeviceName(undefined);
+ }, [
+ options.recordingPrefsLoaded,
+ camera.isReady,
+ selectedCameraId,
+ selectedCameraLabel,
+ options.webcamDeviceId,
+ options.setWebcamDeviceId,
+ options.setWebcamDeviceName,
+ ]);
+
+ return camera;
+}
diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.ts
index 00083bdfc..445850c2e 100644
--- a/src/hooks/useScreenRecorder.ts
+++ b/src/hooks/useScreenRecorder.ts
@@ -281,9 +281,14 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
setMicrophoneEnabled(prefs.micEnabled);
setMicrophoneDeviceId(prefs.micDeviceId ?? undefined);
setMicrophoneDeviceName(prefs.micDeviceName ?? undefined);
- setWebcamEnabledState(prefs.camEnabled);
- setWebcamDeviceId(prefs.camDeviceId ?? undefined);
- setWebcamDeviceName(prefs.camDeviceName ?? undefined);
+ const isCliRecord =
+ typeof window !== "undefined" &&
+ new URLSearchParams(window.location.search).get("windowType") === "cli-record";
+ if (!isCliRecord) {
+ setWebcamEnabledState(prefs.camEnabled);
+ setWebcamDeviceId(prefs.camDeviceId ?? undefined);
+ setWebcamDeviceName(prefs.camDeviceName ?? undefined);
+ }
setSystemAudioEnabled(prefs.systemAudioEnabled);
setCursorCaptureMode(prefs.cursorCaptureMode);
setRecordingPrefsLoaded(true);