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
feat(settings): persist recording setup and project appearance defaults
超超超超超级喜欢你的达妮娅f9405130cbcb
diff --git a/electron/ai-edition/document-service.defaults.test.ts b/electron/ai-edition/document-service.defaults.test.tsnew file mode 100644index 000000000..ddd7d208d--- /dev/null+++ b/electron/ai-edition/document-service.defaults.test.ts@@ -0,0 +1,51 @@+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { getEditorSettings } from "../../src/lib/ai-edition/store/editorSettings";+import { DEFAULT_PROJECT_APPEARANCE } from "../../src/lib/projectDefaults";+import { DocumentService } from "./document-service";++const dirs: string[] = [];+function temp() {+ const root = mkdtempSync(path.join(os.tmpdir(), "openscreen-default-doc-"));+ dirs.push(root);+ return root;+}+afterEach(() => {+ for (const root of dirs.splice(0)) rmSync(root, { recursive: true, force: true });+});++describe("DocumentService project appearance defaults", () => {+ it("materializes the current defaults before the new project's first write", async () => {+ const root = temp();+ const projects = path.join(root, "projects");+ const service = new DocumentService(projects, path.join(root, "media"), undefined, () => ({+ ...DEFAULT_PROJECT_APPEARANCE,+ wallpaper: "#123456",+ padding: 22,+ }));+ const created = await service.createProject("New recording or CLI project");+ const onDisk = JSON.parse(+ readFileSync(path.join(projects, `${created.project.id}.openscreen`), "utf8"),+ );+ expect(getEditorSettings(onDisk)).toMatchObject({ wallpaper: "#123456", padding: 22 });+ expect(onDisk.assets).toEqual([]);+ expect(onDisk.annotations).toEqual([]);+ });++ it("never reapplies changed defaults while opening an existing project", async () => {+ const root = temp();+ let padding = 11;+ const service = new DocumentService(+ path.join(root, "projects"),+ path.join(root, "media"),+ undefined,+ () => ({ ...DEFAULT_PROJECT_APPEARANCE, padding }),+ );+ const created = await service.createProject("Existing");+ padding = 44;+ const reopened = await service.getProject(created.project.id);+ expect(getEditorSettings(reopened).padding).toBe(11);+ });+});diff --git a/electron/ai-edition/document-service.ts b/electron/ai-edition/document-service.tsindex e78a9c48e..75d6fb1ab 100644--- a/electron/ai-edition/document-service.ts+++ b/electron/ai-edition/document-service.ts@@ -21,6 +21,10 @@ import {documentSchema,migrateRawDocumentToCurrent,} from "../../src/lib/ai-edition/schema";+import {+ applyProjectAppearanceDefaults,+ type ProjectAppearanceDefaults,+} from "../../src/lib/projectDefaults";import { ensureDocumentExtensions } from "../media/extensionClip";import { relinkProjectMedia } from "../media/projectMediaRelinker";@@ -165,15 +169,18 @@ export class DocumentService {* `electron` import. Optional so the tests and the CLI construct it as they always did.*/private readonly onProjectRead?: (document: AxcutDocument) => void;+ private readonly loadProjectDefaults?: () => ProjectAppearanceDefaults;constructor(projectsRoot: string,mediaRegistryDir: string,onProjectRead?: (document: AxcutDocument) => void,+ loadProjectDefaults?: () => ProjectAppearanceDefaults,) {this.projectsRoot = projectsRoot;this.mediaRegistryDir = mediaRegistryDir;this.onProjectRead = onProjectRead;+ this.loadProjectDefaults = loadProjectDefaults;}async ensureProjectsDir(): Promise<void> {@@ -299,10 +306,13 @@ export class DocumentService {async createProject(title: string): Promise<AxcutDocument> {await this.ensureProjectsDir();const projectId = createId("proj");- const doc = createEmptyDocument({+ const empty = createEmptyDocument({projectId,title: title?.trim() || "Untitled Project",});+ const doc = this.loadProjectDefaults+ ? applyProjectAppearanceDefaults(empty, this.loadProjectDefaults())+ : empty;await this.writeProject(doc);return doc;}diff --git a/electron/app-settings.test.ts b/electron/app-settings.test.tsnew file mode 100644index 000000000..2370c9b34--- /dev/null+++ b/electron/app-settings.test.ts@@ -0,0 +1,83 @@+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { DEFAULT_PROJECT_APPEARANCE } from "../src/lib/projectDefaults";+import { AppSettingsStore, DEFAULT_RECORDING_PREFERENCES } from "./app-settings";++const dirs: string[] = [];+const temp = () => {+ const dir = mkdtempSync(path.join(os.tmpdir(), "openscreen-app-settings-"));+ dirs.push(dir);+ return dir;+};+afterEach(() => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++describe("app settings store", () => {+ it("uses defaults for absent fields and preserves unknown keys", () => {+ const dir = temp();+ const file = path.join(dir, "recording-settings.json");+ writeFileSync(file, JSON.stringify({ future: { keep: true } }));+ const store = new AppSettingsStore(dir);+ expect(store.getSnapshot().recording).toEqual(DEFAULT_RECORDING_PREFERENCES);+ store.setRecordingPreferences({ micEnabled: true, camDeviceName: "Camera A" });+ expect(JSON.parse(readFileSync(file, "utf8"))).toMatchObject({+ future: { keep: true },+ micEnabled: true,+ camDeviceName: "Camera A",+ });+ });++ it("uses validated defaults for absent, corrupt, and invalid fields", () => {+ const dir = temp();+ const file = path.join(dir, "recording-settings.json");+ const store = new AppSettingsStore(dir);+ expect(store.getSnapshot().recording).toEqual(DEFAULT_RECORDING_PREFERENCES);+ for (const raw of ["{broken", "[]", JSON.stringify({ micEnabled: "yes" })]) {+ writeFileSync(file, raw);+ expect(store.getSnapshot().recording.micEnabled).toBe(false);+ }+ });++ it("stores and resets versioned appearance and recording setup", () => {+ const dir = temp();+ const store = new AppSettingsStore(dir);+ const custom = { ...DEFAULT_PROJECT_APPEARANCE, wallpaper: "#010203", padding: 7 };+ expect(store.setAppearanceDefaults(custom).appearance).toMatchObject({ custom: true });+ store.setLastSource({+ platform: "win32",+ kind: "screen",+ id: "screen:1",+ name: "Display",+ displayId: "1",+ });+ store.setRecordingPreferences({ micEnabled: true, micDeviceId: "mic" });+ expect(store.resetRecordingSetup()).toMatchObject({+ recording: DEFAULT_RECORDING_PREFERENCES,+ lastSource: null,+ });+ expect(store.resetAppearanceDefaults().appearance).toEqual({+ version: 1,+ custom: false,+ defaults: DEFAULT_PROJECT_APPEARANCE,+ });+ expect(+ JSON.parse(readFileSync(path.join(dir, "recording-settings.json"), "utf8")),+ ).toMatchObject({+ projectAppearance: { version: 1, defaults: null },+ });+ });++ it("rejects invalid or failed writes without changing the published durable value", () => {+ const dir = temp();+ const store = new AppSettingsStore(dir);+ store.setRecordingPreferences({ micEnabled: true });+ expect(() => store.setRecordingPreferences({ micEnabled: "yes" as never })).toThrow(TypeError);+ expect(store.getSnapshot().recording.micEnabled).toBe(true);+ const missing = new AppSettingsStore(path.join(dir, "missing"));+ expect(() => missing.setRecordingPreferences({ micEnabled: true })).toThrow();+ expect(missing.getSnapshot().recording.micEnabled).toBe(false);+ });+});diff --git a/electron/app-settings.ts b/electron/app-settings.tsnew file mode 100644index 000000000..64b31704d--- /dev/null+++ b/electron/app-settings.ts@@ -0,0 +1,214 @@+import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";+import path from "node:path";+import {+ DEFAULT_PROJECT_APPEARANCE,+ type ProjectAppearanceDefaults,+ parseProjectAppearanceDefaults,+} from "../src/lib/projectDefaults";+import type { CursorCaptureMode } from "../src/lib/recordingSession";++export interface RecordingPreferences {+ micEnabled: boolean;+ micDeviceId: string | null;+ micDeviceName: string | null;+ camEnabled: boolean;+ camDeviceId: string | null;+ camDeviceName: string | null;+ systemAudioEnabled: boolean;+ cursorCaptureMode: CursorCaptureMode;+}++export const DEFAULT_RECORDING_PREFERENCES: RecordingPreferences = {+ micEnabled: false,+ micDeviceId: null,+ micDeviceName: null,+ camEnabled: false,+ camDeviceId: null,+ camDeviceName: null,+ systemAudioEnabled: false,+ cursorCaptureMode: "editable-overlay",+};++export interface RecordingSourceDescriptor {+ platform: NodeJS.Platform;+ kind: "screen" | "window";+ id: string;+ name: string;+ displayId: string | null;+}++export interface AppSettingsSnapshot {+ recording: RecordingPreferences;+ lastSource: RecordingSourceDescriptor | null;+ appearance: {+ version: 1;+ custom: boolean;+ defaults: ProjectAppearanceDefaults;+ };+}++type RawSettings = Record<string, unknown>;++function readRaw(userData: string): RawSettings {+ try {+ const value: unknown = JSON.parse(+ readFileSync(path.join(userData, "recording-settings.json"), "utf8"),+ );+ return value !== null && typeof value === "object" && !Array.isArray(value)+ ? (value as RawSettings)+ : {};+ } catch {+ return {};+ }+}++function atomicWrite(userData: string, value: RawSettings): void {+ const destination = path.join(userData, "recording-settings.json");+ const temporary = `${destination}.${process.pid}.${Date.now()}.tmp`;+ try {+ writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, "utf8");+ renameSync(temporary, destination);+ } finally {+ rmSync(temporary, { force: true });+ }+}++const bool = (value: unknown, fallback: boolean) => (typeof value === "boolean" ? value : fallback);+const nullableString = (value: unknown, fallback: string | null) =>+ value === null || typeof value === "string" ? value : fallback;++function parseRecording(raw: RawSettings): RecordingPreferences {+ return {+ micEnabled: bool(raw.micEnabled, DEFAULT_RECORDING_PREFERENCES.micEnabled),+ micDeviceId: nullableString(raw.micDeviceId, DEFAULT_RECORDING_PREFERENCES.micDeviceId),+ micDeviceName: nullableString(raw.micDeviceName, DEFAULT_RECORDING_PREFERENCES.micDeviceName),+ camEnabled: bool(raw.camEnabled, DEFAULT_RECORDING_PREFERENCES.camEnabled),+ camDeviceId: nullableString(raw.camDeviceId, DEFAULT_RECORDING_PREFERENCES.camDeviceId),+ camDeviceName: nullableString(raw.camDeviceName, DEFAULT_RECORDING_PREFERENCES.camDeviceName),+ systemAudioEnabled: bool(+ raw.systemAudioEnabled,+ DEFAULT_RECORDING_PREFERENCES.systemAudioEnabled,+ ),+ cursorCaptureMode:+ raw.cursorCaptureMode === "system" || raw.cursorCaptureMode === "editable-overlay"+ ? raw.cursorCaptureMode+ : DEFAULT_RECORDING_PREFERENCES.cursorCaptureMode,+ };+}++function parseSource(value: unknown): RecordingSourceDescriptor | null {+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;+ const candidate = value as Record<string, unknown>;+ if (+ (candidate.platform !== "win32" &&+ candidate.platform !== "darwin" &&+ candidate.platform !== "linux") ||+ (candidate.kind !== "screen" && candidate.kind !== "window") ||+ typeof candidate.id !== "string" ||+ candidate.id.length === 0 ||+ typeof candidate.name !== "string" ||+ candidate.name.length === 0 ||+ !(candidate.displayId === null || typeof candidate.displayId === "string")+ ) {+ return null;+ }+ return candidate as unknown as RecordingSourceDescriptor;+}++function parseAppearance(raw: RawSettings): AppSettingsSnapshot["appearance"] {+ const value = raw.projectAppearance;+ if (!value || typeof value !== "object" || Array.isArray(value)) {+ return { version: 1, custom: false, defaults: DEFAULT_PROJECT_APPEARANCE };+ }+ const candidate = value as Record<string, unknown>;+ if (candidate.version !== 1 || candidate.defaults === null) {+ return { version: 1, custom: false, defaults: DEFAULT_PROJECT_APPEARANCE };+ }+ try {+ return {+ version: 1,+ custom: true,+ defaults: parseProjectAppearanceDefaults(candidate.defaults),+ };+ } catch {+ return { version: 1, custom: false, defaults: DEFAULT_PROJECT_APPEARANCE };+ }+}++function validateRecordingPatch(patch: Partial<RecordingPreferences>): void {+ const allowed = new Set(Object.keys(DEFAULT_RECORDING_PREFERENCES));+ for (const [key, value] of Object.entries(patch)) {+ if (!allowed.has(key)) throw new TypeError(`unknown recording preference: ${key}`);+ if (value === undefined) continue;+ if (key.endsWith("Enabled") && typeof value !== "boolean") {+ throw new TypeError(`${key} must be a boolean`);+ }+ if (+ (key.endsWith("DeviceId") || key.endsWith("DeviceName")) &&+ value !== null &&+ typeof value !== "string"+ ) {+ throw new TypeError(`${key} must be a string or null`);+ }+ if (key === "cursorCaptureMode" && value !== "system" && value !== "editable-overlay") {+ throw new TypeError("cursorCaptureMode is invalid");+ }+ }+}++export class AppSettingsStore {+ constructor(private readonly userData: string) {}++ getSnapshot(): AppSettingsSnapshot {+ const raw = readRaw(this.userData);+ return {+ recording: parseRecording(raw),+ lastSource: parseSource(raw.lastSource),+ appearance: parseAppearance(raw),+ };+ }++ setRecordingPreferences(patch: Partial<RecordingPreferences>): AppSettingsSnapshot {+ validateRecordingPatch(patch);+ const raw = readRaw(this.userData);+ const current = parseRecording(raw);+ const next = Object.fromEntries(+ Object.entries(patch).filter(([, value]) => value !== undefined),+ ) as Partial<RecordingPreferences>;+ atomicWrite(this.userData, { ...raw, ...current, ...next });+ return this.getSnapshot();+ }++ setLastSource(source: RecordingSourceDescriptor | null): AppSettingsSnapshot {+ if (source !== null && !parseSource(source)) throw new TypeError("last source is invalid");+ const raw = readRaw(this.userData);+ atomicWrite(this.userData, { ...raw, lastSource: source });+ return this.getSnapshot();+ }++ setAppearanceDefaults(defaults: ProjectAppearanceDefaults): AppSettingsSnapshot {+ const parsed = parseProjectAppearanceDefaults(defaults);+ const raw = readRaw(this.userData);+ atomicWrite(this.userData, {+ ...raw,+ projectAppearance: { version: 1, defaults: parsed },+ });+ return this.getSnapshot();+ }++ resetAppearanceDefaults(): AppSettingsSnapshot {+ const raw = readRaw(this.userData);+ atomicWrite(this.userData, { ...raw, projectAppearance: { version: 1, defaults: null } });+ return this.getSnapshot();+ }++ resetRecordingSetup(): AppSettingsSnapshot {+ const raw = readRaw(this.userData);+ atomicWrite(this.userData, {+ ...raw,+ ...DEFAULT_RECORDING_PREFERENCES,+ lastSource: null,+ });+ return this.getSnapshot();+ }+}diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.tsindex d742d2d09..4d1484c1c 100644--- a/electron/electron-env.d.ts+++ b/electron/electron-env.d.ts@@ -51,13 +51,24 @@ interface Window {opened: boolean;reason?: string;}>;- selectSource: (source: ProcessedDesktopSource) => Promise<ProcessedDesktopSource | null>;+ selectSource: (+ source: ProcessedDesktopSource,+ options?: { persist?: boolean },+ ) => Promise<ProcessedDesktopSource | null>;getSelectedSource: () => Promise<ProcessedDesktopSource | null>;- onSelectedSourceChanged: (callback: (source: ProcessedDesktopSource) => void) => () => void;+ onSelectedSourceChanged: (+ callback: (source: ProcessedDesktopSource | null) => void,+ ) => () => void;getRecordingPrefs: () => Promise<import("./ipc/handlers").RecordingPrefs>;setRecordingPrefs: (prefs: Partial<import("./ipc/handlers").RecordingPrefs>,) => Promise<import("./ipc/handlers").RecordingPrefs>;+ getAppSettings: () => Promise<import("./app-settings").AppSettingsSnapshot>;+ setProjectAppearanceDefaults: (+ defaults: import("../src/lib/projectDefaults").ProjectAppearanceDefaults,+ ) => Promise<import("./app-settings").AppSettingsSnapshot>;+ resetProjectAppearanceDefaults: () => Promise<import("./app-settings").AppSettingsSnapshot>;+ resetRecordingSetup: () => Promise<import("./app-settings").AppSettingsSnapshot>;onRecordingPrefsChanged: (callback: (prefs: import("./ipc/handlers").RecordingPrefs) => void,) => () => void;diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex b3ae42364..e3a02808b 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -56,6 +56,7 @@ import {import type { CursorTelemetryReader } from "../ai-edition/deep-agent/service";import { DocumentService } from "../ai-edition/document-service";import { LlmConfigStore } from "../ai-edition/llm-config-store";+import { AppSettingsStore } from "../app-settings";import { isDiagnosticModeEnabled, mainLogBuffer } from "../diagnostics/main-log-buffer";import { mainT } from "../i18n";import { getInstallChannel } from "../install-channel";@@ -103,6 +104,15 @@ import {} from "../recording/nativeWindowsCaptureStop";import { patchWebmDurationOnDisk } from "../recording/webm-duration";import { reindexRecordingOnDisk } from "../recording/webm-seek-index";+import {+ describeRecordingSource,+ enumerationIncludesSourceKind,+ mergeEnumeratedSources,+ resolveRecordingSource,+ restoreRecordingSourceAfterEnumeration,+ shouldEnumerateRecordingSources,+ shouldPersistSelectedSource,+} from "../recording-source-settings";import { registerNativeBridgeHandlers } from "./nativeBridge";import { createNativeMacMidCaptureErrorWatch } from "./nativeMacMidCaptureErrorWatch";import { registerRecordingPrefsHandlers } from "./recordingPrefs";@@ -595,13 +605,12 @@ let lastEnumeratedSources = new Map<string, DesktopCapturerSource>();let currentProjectPath: string | null = null;let currentRecordingSession: RecordingSession | null = null;-// single source of truth for the mic/camera/system-audio/cursor+// Durable source of truth for the mic/camera/system-audio/cursor/source// choices a user makes in the editor's Rec-mode stage, so the HUD window's// useScreenRecorder (a separate renderer, own process, own React tree) picks// up those choices instead of silently reverting to its own defaults when-// startNewRecording() switches windows. Mirrors the selectedSource pattern-// above (in-memory, broadcast on change). Auto-zoom is the one durable choice;-// the device selections remain session preferences, not project content.+// startNewRecording() switches windows. Persisted in AppSettingsStore and+// broadcast on change; not project content.export interface RecordingPrefs {micEnabled: boolean;micDeviceId: string | null;@@ -619,6 +628,8 @@ export interface RecordingPrefs {micDeviceName: string | null;camEnabled: boolean;camDeviceId: string | null;+ /** Camera label paired with the preferred id for restart-safe resolution. */+ camDeviceName: string | null;systemAudioEnabled: boolean;cursorCaptureMode: CursorCaptureMode;}@@ -628,6 +639,7 @@ const defaultRecordingPrefs: RecordingPrefs = {micDeviceName: null,camEnabled: false,camDeviceId: null,+ camDeviceName: null,systemAudioEnabled: false,cursorCaptureMode: "editable-overlay",};@@ -1837,6 +1849,17 @@ export function registerIpcHandlers(onRecordingStateChange?: (recording: boolean, sourceName: string) => void,_switchToHud?: () => void,) {+ const appSettings = new AppSettingsStore(app.getPath("userData"));+ const broadcastSelectedSource = (source: SelectedSource | null) => {+ for (const window of BrowserWindow.getAllWindows()) {+ if (!window.isDestroyed()) {+ window.webContents.send("selected-source-changed", source);+ }+ }+ };+ const sameSelectedSource = (left: SelectedSource | null, right: SelectedSource | null) =>+ left?.id === right?.id && left?.name === right?.name && left?.display_id === right?.display_id;+async function requestScreenAccess() {if (process.platform !== "darwin") {return { success: true, granted: true, status: "granted" };@@ -1917,7 +1940,39 @@ export function registerIpcHandlers(`[get-sources] returned ${sources.length} source(s) in ${Date.now() - startedAt}ms (types=${(opts?.types ?? []).join(",")})`,);}- lastEnumeratedSources = new Map(sources.map((source) => [source.id, source]));+ lastEnumeratedSources = mergeEnumeratedSources(lastEnumeratedSources, sources, opts?.types);+ const previousSelectedSource = selectedSource;+ const currentLive = selectedSource?.id+ ? sources.find((source) => source.id === selectedSource?.id)+ : null;+ if (currentLive) {+ selectedSource = {+ id: currentLive.id,+ name: currentLive.name,+ display_id: currentLive.display_id,+ };+ selectedDesktopSource = currentLive;+ } else if (enumerationIncludesSourceKind(opts?.types, selectedSource?.id)) {+ selectedSource = null;+ selectedDesktopSource = null;+ const restored = resolveRecordingSource(+ appSettings.getSnapshot().lastSource,+ process.platform,+ sources,+ { waylandPortal: process.platform === "linux" && Boolean(findPipeWireCursorHelperPath()) },+ );+ if (restored) {+ selectedSource = {+ id: restored.id,+ name: restored.name,+ display_id: restored.display_id,+ };+ selectedDesktopSource = lastEnumeratedSources.get(restored.id) ?? null;+ }+ }+ if (!sameSelectedSource(previousSelectedSource, selectedSource)) {+ broadcastSelectedSource(selectedSource);+ }return sources.map((source) => ({id: source.id,name: source.name,@@ -1927,42 +1982,128 @@ export function registerIpcHandlers(}));});- ipcMain.handle("select-source", async (_, source: SelectedSource) => {- selectedSource = source;- // 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;+ 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);+ }+ }+ broadcastSelectedSource(selectedSource);+ const sourceSelectorWin = getSourceSelectorWindow();+ if (sourceSelectorWin) {+ sourceSelectorWin.close();+ }+ return selectedSource;+ },+ );- 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;+ ipcMain.handle("get-selected-source", async () => {+ const previousSelectedSource = selectedSource;+ if (process.platform === "linux" && findPipeWireCursorHelperPath()) {+ selectedSource = null;+ selectedDesktopSource = null;+ if (!sameSelectedSource(previousSelectedSource, null)) {+ broadcastSelectedSource(null);}+ return null;+ }+ const lastSource = appSettings.getSnapshot().lastSource;+ const liveSelected =+ selectedSource?.id != null+ ? {+ id: selectedSource.id,+ name: selectedSource.name,+ display_id: selectedSource.display_id ?? "",+ }+ : null;+ if (!shouldEnumerateRecordingSources(liveSelected, lastSource)) {+ return selectedSource;}- const mainWin = getMainWindow();- if (mainWin && !mainWin.isDestroyed()) {- mainWin.webContents.send("selected-source-changed", selectedSource);+ const sources = await withDeadline(+ desktopCapturer.getSources({+ types: ["screen", "window"],+ thumbnailSize: { width: 0, height: 0 },+ fetchWindowIcons: false,+ }),+ GET_SOURCES_TIMEOUT_MS,+ `Desktop source restoration did not return within ${GET_SOURCES_TIMEOUT_MS}ms.`,+ );+ const decision = restoreRecordingSourceAfterEnumeration({+ selectedBefore: liveSelected,+ selectedAfter:+ selectedSource?.id != null+ ? {+ id: selectedSource.id,+ name: selectedSource.name,+ display_id: selectedSource.display_id ?? "",+ }+ : null,+ lastSourceBefore: lastSource,+ lastSourceAfter: appSettings.getSnapshot().lastSource,+ platform: process.platform,+ sources,+ });+ if (!decision.apply) {+ return selectedSource;}- const sourceSelectorWin = getSourceSelectorWindow();- if (sourceSelectorWin) {- sourceSelectorWin.close();+ lastEnumeratedSources = new Map(sources.map((source) => [source.id, source]));+ const restored = decision.restored;+ selectedDesktopSource = restored ? (lastEnumeratedSources.get(restored.id) ?? null) : null;+ selectedSource = restored+ ? { id: restored.id, name: restored.name, display_id: restored.display_id }+ : null;+ if (!sameSelectedSource(previousSelectedSource, selectedSource)) {+ broadcastSelectedSource(selectedSource);}return selectedSource;});- ipcMain.handle("get-selected-source", () => {- return selectedSource;- });-- registerRecordingPrefsHandlers(defaultRecordingPrefs, getMainWindow);+ registerRecordingPrefsHandlers(+ defaultRecordingPrefs,+ getMainWindow,+ () => {+ selectedSource = null;+ selectedDesktopSource = null;+ broadcastSelectedSource(null);+ },+ () => BrowserWindow.getAllWindows(),+ );ipcMain.handle("request-camera-access", async () => {if (process.platform !== "darwin") {@@ -4467,6 +4608,7 @@ export function registerIpcHandlers(path.join(app.getPath("userData"), "projects"),RECORDINGS_DIR,approveDocumentMedia,+ () => appSettings.getSnapshot().appearance.defaults,);// LlmConfigStore is single-instance for a duller reason — its constructor doesdiff --git a/electron/ipc/recordingPrefs.test.ts b/electron/ipc/recordingPrefs.test.tsindex aaa08b190..a6d978b85 100644--- a/electron/ipc/recordingPrefs.test.ts+++ b/electron/ipc/recordingPrefs.test.ts@@ -1,10 +1,14 @@+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import os from "node:os";+import path from "node:path";import type { BrowserWindow } from "electron";-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { RecordingPrefs } from "./handlers";import { registerRecordingPrefsHandlers } from "./recordingPrefs";-const electron = vi.hoisted(() => ({ handle: vi.fn() }));+const electron = vi.hoisted(() => ({ getPath: vi.fn(), handle: vi.fn() }));vi.mock("electron", () => ({+ app: { getPath: electron.getPath },ipcMain: { handle: electron.handle },}));@@ -14,17 +18,25 @@ const defaults: RecordingPrefs = {micDeviceName: null,camEnabled: false,camDeviceId: null,+ camDeviceName: null,systemAudioEnabled: false,cursorCaptureMode: "editable-overlay",};-+let dir: string;beforeEach(() => {+ dir = mkdtempSync(path.join(os.tmpdir(), "openscreen-recording-ipc-"));+ electron.getPath.mockReturnValue(dir);electron.handle.mockClear();});+afterEach(() => rmSync(dir, { recursive: true, force: true }));-function start(getWindow: () => BrowserWindow | null = () => null) {+function start(+ getWindow: () => BrowserWindow | null = () => null,+ onResetSource: () => void = () => undefined,+ getAppWindows?: () => BrowserWindow[],+) {electron.handle.mockClear();- registerRecordingPrefsHandlers(defaults, getWindow);+ registerRecordingPrefsHandlers(defaults, getWindow, onResetSource, getAppWindows);const get = electron.handle.mock.calls.find(([name]) => name === "get-recording-prefs",)?.[1] as () => RecordingPrefs;@@ -32,28 +44,97 @@ function start(getWindow: () => BrowserWindow | null = () => null) {_event: unknown,prefs: Partial<RecordingPrefs>,) => RecordingPrefs;- return { get, set: (prefs: Partial<RecordingPrefs>) => set(undefined, prefs) };+ const reset = electron.handle.mock.calls.find(+ ([name]) => name === "reset-recording-setup",+ )?.[1] as (_event: unknown) => { recording: RecordingPrefs; lastSource: null };+ return {+ get,+ set: (prefs: Partial<RecordingPrefs>) => set(undefined, prefs),+ reset: () => reset(undefined),+ };}describe("recording preferences IPC", () => {- it("returns defaults and updates session preferences", () => {- const session = start();- expect(session.get()).toEqual(defaults);- const updated = session.set({ micEnabled: true, micDeviceId: "test-mic" });- expect(updated.micEnabled).toBe(true);- expect(updated.micDeviceId).toBe("test-mic");- expect(session.get().micEnabled).toBe(true);+ it("restores toggles and device preferences on restart", () => {+ const first = start();+ expect(first.get().micEnabled).toBe(false);+ expect(first.get().camDeviceName).toBeNull();+ expect(first.set({ camDeviceName: "Camera A" }).camDeviceName).toBe("Camera A");+ first.set({ micEnabled: true, micDeviceId: "temporary-device" });+ const disk = JSON.parse(readFileSync(path.join(dir, "recording-settings.json"), "utf8"));+ expect(disk).toMatchObject({+ camDeviceName: "Camera A",+ micEnabled: true,+ micDeviceId: "temporary-device",+ });+ const restarted = start();+ expect(restarted.get()).toEqual({+ ...defaults,+ camDeviceName: "Camera A",+ micEnabled: true,+ micDeviceId: "temporary-device",+ });+ restarted.set({ camDeviceName: "Camera B" });+ expect(start().get().camDeviceName).toBe("Camera B");});- it("broadcasts changes to main window and tolerates an absent or destroyed window", () => {+ it("broadcasts saved values to every live application window", () => {+ const firstSend = vi.fn();+ const secondSend = vi.fn();+ const destroyedSend = vi.fn();+ const first = {+ isDestroyed: () => false,+ webContents: { send: firstSend },+ } as unknown as BrowserWindow;+ const second = {+ isDestroyed: () => false,+ webContents: { send: secondSend },+ } as unknown as BrowserWindow;+ const destroyed = {+ isDestroyed: () => true,+ webContents: { send: destroyedSend },+ } as unknown as BrowserWindow;+ const session = start(+ () => first,+ undefined,+ () => [first, second, first, destroyed],+ );+ const updated = session.set({ micEnabled: true });+ expect(firstSend).toHaveBeenCalledWith("recording-prefs-changed", updated);+ expect(secondSend).toHaveBeenCalledWith("recording-prefs-changed", updated);+ expect(firstSend).toHaveBeenCalledTimes(1);+ expect(destroyedSend).not.toHaveBeenCalled();+ });++ it("publishes the reset snapshot and runs the source reset callback", () => {const send = vi.fn();- const isDestroyed = vi.fn(() => false);- const window = { isDestroyed, webContents: { send } } as unknown as BrowserWindow;- const session = start(() => window);- const updated = session.set({ camEnabled: true });- expect(send).toHaveBeenCalledWith("recording-prefs-changed", updated);- isDestroyed.mockReturnValue(true);+ const window = {+ isDestroyed: () => false,+ webContents: { send },+ } as unknown as BrowserWindow;+ const onResetSource = vi.fn();+ const session = start(() => window, onResetSource);+ session.set({ micEnabled: true, camEnabled: true, systemAudioEnabled: true });+ send.mockClear();++ const snapshot = session.reset();+ expect(snapshot.recording).toEqual(defaults);+ expect(snapshot.lastSource).toBeNull();+ expect(onResetSource).toHaveBeenCalledTimes(1);+ expect(send).toHaveBeenCalledWith("recording-prefs-changed", defaults);+ });++ it("does not publish an invalid or failed preference write", () => {+ const session = start();+ expect(() => session.set({ micEnabled: null } as unknown as Partial<RecordingPrefs>)).toThrow(+ TypeError,+ );+ expect(session.get().micEnabled).toBe(false);session.set({ micEnabled: true });- expect(send).toHaveBeenCalledTimes(1);+ session.set({ micEnabled: undefined, camEnabled: true });+ expect(session.get().micEnabled).toBe(true);+ rmSync(dir, { recursive: true, force: true });+ expect(() => session.set({ micEnabled: false })).toThrow();+ expect(session.get().micEnabled).toBe(true);});});diff --git a/electron/ipc/recordingPrefs.ts b/electron/ipc/recordingPrefs.tsindex 65516201d..b80b03430 100644--- a/electron/ipc/recordingPrefs.ts+++ b/electron/ipc/recordingPrefs.ts@@ -1,24 +1,48 @@-import type { BrowserWindow } from "electron";-import { ipcMain } from "electron";+import { app, type BrowserWindow, ipcMain } from "electron";+import type { ProjectAppearanceDefaults } from "../../src/lib/projectDefaults";+import { AppSettingsStore } from "../app-settings";import type { RecordingPrefs } from "./handlers";-/** Shared session preferences. */+/** Shared durable recording preferences. Persist before publishing any new snapshot. */export function registerRecordingPrefsHandlers(defaults: RecordingPrefs,getMainWindow: () => BrowserWindow | null,+ onResetSource: () => void = () => undefined,+ getAppWindows: () => BrowserWindow[] = () => {+ const mainWindow = getMainWindow();+ return mainWindow ? [mainWindow] : [];+ },): void {- let recordingPrefs = { ...defaults };+ const userData = app.getPath("userData");+ const settings = new AppSettingsStore(userData);+ let recordingPrefs = { ...defaults, ...settings.getSnapshot().recording };+ const publish = () => {+ for (const window of new Set(getAppWindows())) {+ if (!window.isDestroyed()) {+ window.webContents.send("recording-prefs-changed", recordingPrefs);+ }+ }+ };ipcMain.handle("get-recording-prefs", () => recordingPrefs);ipcMain.handle("set-recording-prefs", (_, prefs: Partial<RecordingPrefs>) => {- recordingPrefs = {- ...recordingPrefs,- ...prefs,- };- const mainWin = getMainWindow();- if (mainWin && !mainWin.isDestroyed()) {- mainWin.webContents.send("recording-prefs-changed", recordingPrefs);- }+ // Persist every validated field first. A failed save must leave both the+ // durable value and the main-process published snapshot unchanged.+ recordingPrefs = settings.setRecordingPreferences(prefs).recording;+ publish();return recordingPrefs;});++ ipcMain.handle("get-app-settings", () => settings.getSnapshot());+ ipcMain.handle("set-project-appearance-defaults", (_, value: ProjectAppearanceDefaults) =>+ settings.setAppearanceDefaults(value),+ );+ ipcMain.handle("reset-project-appearance-defaults", () => settings.resetAppearanceDefaults());+ ipcMain.handle("reset-recording-setup", () => {+ const snapshot = settings.resetRecordingSetup();+ recordingPrefs = snapshot.recording;+ onResetSource();+ publish();+ return snapshot;+ });}diff --git a/electron/preload.ts b/electron/preload.tsindex 6b29edd87..35699839e 100644--- a/electron/preload.ts+++ b/electron/preload.ts@@ -2,10 +2,12 @@ import { contextBridge, ipcRenderer, webUtils } from "electron";import type { NativeLinuxRecordingRequest } from "../src/lib/nativeLinuxRecording";import type { NativeMacRecordingRequest } from "../src/lib/nativeMacRecording";import type { NativeWindowsRecordingRequest } from "../src/lib/nativeWindowsRecording";+import type { ProjectAppearanceDefaults } from "../src/lib/projectDefaults";import type { RecordingSession, StoreRecordedSessionInput } from "../src/lib/recordingSession";import type { ShortcutBinding } from "../src/lib/shortcuts";import type { AiEditionChatEvent } from "../src/native/contracts";import { NATIVE_BRIDGE_CHANNEL, type NativeBridgeRequest } from "../src/native/contracts";+import type { AppSettingsSnapshot } from "./app-settings";import type { RecordingPrefs } from "./ipc/handlers";import type {SttStatusEvent,@@ -122,8 +124,8 @@ contextBridge.exposeInMainWorld("electronAPI", {openNotes: () => {return ipcRenderer.invoke("open-notes");},- selectSource: (source: ProcessedDesktopSource) => {- return ipcRenderer.invoke("select-source", source);+ selectSource: (source: ProcessedDesktopSource, options?: { persist?: boolean }) => {+ return ipcRenderer.invoke("select-source", source, options);},getSelectedSource: () => {return ipcRenderer.invoke("get-selected-source");@@ -134,13 +136,20 @@ contextBridge.exposeInMainWorld("electronAPI", {setRecordingPrefs: (prefs: Partial<RecordingPrefs>) => {return ipcRenderer.invoke("set-recording-prefs", prefs);},+ getAppSettings: () => ipcRenderer.invoke("get-app-settings") as Promise<AppSettingsSnapshot>,+ setProjectAppearanceDefaults: (defaults: ProjectAppearanceDefaults) =>+ ipcRenderer.invoke("set-project-appearance-defaults", defaults) as Promise<AppSettingsSnapshot>,+ resetProjectAppearanceDefaults: () =>+ ipcRenderer.invoke("reset-project-appearance-defaults") as Promise<AppSettingsSnapshot>,+ resetRecordingSetup: () =>+ ipcRenderer.invoke("reset-recording-setup") as Promise<AppSettingsSnapshot>,onRecordingPrefsChanged: (callback: (prefs: RecordingPrefs) => void) => {const listener = (_event: unknown, prefs: RecordingPrefs) => callback(prefs);ipcRenderer.on("recording-prefs-changed", listener);return () => ipcRenderer.removeListener("recording-prefs-changed", listener);},- onSelectedSourceChanged: (callback: (source: ProcessedDesktopSource) => void) => {- const listener = (_event: unknown, source: ProcessedDesktopSource) => callback(source);+ onSelectedSourceChanged: (callback: (source: ProcessedDesktopSource | null) => void) => {+ const listener = (_event: unknown, source: ProcessedDesktopSource | null) => callback(source);ipcRenderer.on("selected-source-changed", listener);return () => ipcRenderer.removeListener("selected-source-changed", listener);},diff --git a/electron/recording-source-settings.test.ts b/electron/recording-source-settings.test.tsnew file mode 100644index 000000000..f56a684fa--- /dev/null+++ b/electron/recording-source-settings.test.ts@@ -0,0 +1,141 @@+import { describe, expect, it } from "vitest";+import {+ describeRecordingSource,+ enumerationIncludesSourceKind,+ mergeEnumeratedSources,+ resolveCurrentRecordingSource,+ resolveRecordingSource,+ restoreRecordingSourceAfterEnumeration,+ shouldEnumerateRecordingSources,+ shouldPersistSelectedSource,+} from "./recording-source-settings";++const display = { id: "screen:1:0", name: "Display 1", display_id: "stable-1" };++describe("recording source settings", () => {+ it("restores a display by stable display id from the fresh list", () => {+ const descriptor = describeRecordingSource("win32", display);+ expect(+ resolveRecordingSource(descriptor, "win32", [+ { ...display, id: "screen:new-id", name: "Renamed display" },+ ]),+ ).toMatchObject({ id: "screen:new-id", display_id: "stable-1" });+ });++ it("uses an exact display identity fallback and refuses missing or ambiguous matches", () => {+ const descriptor = describeRecordingSource("win32", display);+ expect(resolveRecordingSource(descriptor, "win32", [display])).toEqual(display);+ expect(resolveRecordingSource(descriptor, "darwin", [display])).toBeNull();+ expect(resolveRecordingSource(descriptor, "win32", [])).toBeNull();+ expect(+ resolveRecordingSource(descriptor, "win32", [{ ...display }, { ...display, id: "screen:2" }]),+ ).toEqual(display);+ expect(+ resolveRecordingSource(descriptor, "win32", [{ ...display }, { ...display }]),+ ).toBeNull();+ });++ it("requires both live id and name for windows and never guesses by title", () => {+ const saved = describeRecordingSource("win32", {+ id: "window:42",+ name: "Notes",+ display_id: "",+ });+ expect(+ resolveRecordingSource(saved, "win32", [{ id: "window:99", name: "Notes", display_id: "" }]),+ ).toBeNull();+ expect(+ resolveRecordingSource(saved, "win32", [{ id: "window:42", name: "Notes", display_id: "" }]),+ ).toMatchObject({ id: "window:42" });+ });++ it("keeps a live window when only its title changed", () => {+ const selected = { id: "window:42", name: "Notes", display_id: "" };+ const renamed = { id: "window:42", name: "Notes — saved", display_id: "" };+ expect(resolveCurrentRecordingSource(selected, null, "win32", [renamed])).toEqual(renamed);+ expect(+ resolveRecordingSource(describeRecordingSource("win32", selected), "win32", [renamed]),+ ).toBeNull();+ });++ it("persists interactive source picks and skips CLI ones", () => {+ expect(shouldPersistSelectedSource()).toBe(true);+ expect(shouldPersistSelectedSource({ persist: true })).toBe(true);+ expect(shouldPersistSelectedSource({ persist: false })).toBe(false);+ });++ it("does not resurrect a persisted source after reset during enumeration", () => {+ const persisted = describeRecordingSource("win32", display);+ let selected: { id: string; name: string; display_id: string } | null = null;+ let lastSource: ReturnType<typeof describeRecordingSource> | null = persisted;+ const selectedBefore = selected;+ const lastSourceBefore = lastSource;+ lastSource = null;+ selected = null;+ const decision = restoreRecordingSourceAfterEnumeration({+ selectedBefore,+ selectedAfter: selected,+ lastSourceBefore,+ lastSourceAfter: lastSource,+ platform: "win32",+ sources: [display],+ });+ expect(decision.apply).toBe(false);+ expect(decision.restored).toBeNull();+ expect(selected).toBeNull();+ expect(+ restoreRecordingSourceAfterEnumeration({+ selectedBefore: null,+ selectedAfter: null,+ lastSourceBefore: persisted,+ lastSourceAfter: persisted,+ platform: "win32",+ sources: [display],+ }).restored,+ ).toEqual(display);+ });++ it("enumerates only when a live or persisted source exists", () => {+ expect(shouldEnumerateRecordingSources(null, null)).toBe(false);+ expect(+ shouldEnumerateRecordingSources({ id: "window:1", name: "A", display_id: "" }, null),+ ).toBe(true);+ expect(shouldEnumerateRecordingSources(null, describeRecordingSource("win32", display))).toBe(+ true,+ );+ });++ it("does not treat a screen-only enum as proof a window is gone", () => {+ expect(enumerationIncludesSourceKind(["screen"], "window:42")).toBe(false);+ expect(enumerationIncludesSourceKind(["window"], "window:42")).toBe(true);+ expect(enumerationIncludesSourceKind(["screen", "window"], "window:42")).toBe(true);+ expect(enumerationIncludesSourceKind(undefined, "window:42")).toBe(true);+ expect(enumerationIncludesSourceKind(["screen"], null)).toBe(true);+ });++ it("keeps the other kind in the enumeration cache across a partial list", () => {+ const screen = { id: "screen:1:0", name: "Display 1" };+ const windowSource = { id: "window:42", name: "Notes" };+ const previous = new Map([+ [screen.id, screen],+ [windowSource.id, windowSource],+ ]);+ const merged = mergeEnumeratedSources(+ previous,+ [{ ...screen, name: "Display 1 HDR" }],+ ["screen"],+ );+ expect(merged.get(windowSource.id)).toEqual(windowSource);+ expect(merged.get(screen.id)).toMatchObject({ name: "Display 1 HDR" });+ });++ it("never restores a source when the Wayland portal owns selection", () => {+ const descriptor = describeRecordingSource("linux", display);+ expect(+ resolveRecordingSource(descriptor, "linux", [display], { waylandPortal: true }),+ ).toBeNull();+ expect(+ resolveRecordingSource(descriptor, "linux", [display], { waylandPortal: false }),+ ).toEqual(display);+ });+});diff --git a/electron/recording-source-settings.ts b/electron/recording-source-settings.tsnew file mode 100644index 000000000..d8d89425b--- /dev/null+++ b/electron/recording-source-settings.ts@@ -0,0 +1,182 @@+import type { RecordingSourceDescriptor } from "./app-settings";++export interface LiveRecordingSource {+ id: string;+ name: string;+ display_id: string;+}++export function recordingSourceKindFromId(id: string): RecordingSourceDescriptor["kind"] {+ return id.startsWith("window:") ? "window" : "screen";+}++export function describeRecordingSource(+ platform: NodeJS.Platform,+ source: LiveRecordingSource,+): RecordingSourceDescriptor {+ return {+ platform,+ kind: recordingSourceKindFromId(source.id),+ id: source.id,+ name: source.name,+ displayId: source.display_id || null,+ };+}++/**+ * A screen-only (or window-only) enumeration cannot prove a source of the+ * other kind is gone. Clearing the live pick in that case is a false negative.+ */+export function enumerationIncludesSourceKind(+ requestedTypes: readonly string[] | undefined,+ sourceId: string | null | undefined,+): boolean {+ if (!sourceId) return true;+ const types = requestedTypes && requestedTypes.length > 0 ? requestedTypes : ["screen", "window"];+ return types.includes(recordingSourceKindFromId(sourceId));+}++export function mergeEnumeratedSources<T extends { id: string }>(+ previous: ReadonlyMap<string, T>,+ next: readonly T[],+ requestedTypes: readonly string[] | undefined,+): Map<string, T> {+ const types = requestedTypes && requestedTypes.length > 0 ? requestedTypes : ["screen", "window"];+ const merged = new Map(previous);+ for (const id of [...merged.keys()]) {+ if (types.includes(recordingSourceKindFromId(id))) {+ merged.delete(id);+ }+ }+ for (const source of next) {+ merged.set(source.id, source);+ }+ return merged;+}++/** HUD/RecStage persist the pick; CLI capture must not overwrite that default. */+export function shouldPersistSelectedSource(options?: { persist?: boolean }): boolean {+ return options?.persist !== false;+}++export function sameRecordingSourceDescriptor(+ left: RecordingSourceDescriptor | null | undefined,+ right: RecordingSourceDescriptor | null | undefined,+): boolean {+ if (left == null && right == null) return true;+ if (left == null || right == null) return false;+ return (+ left.platform === right.platform &&+ left.kind === right.kind &&+ left.id === right.id &&+ left.name === right.name &&+ left.displayId === right.displayId+ );+}++/**+ * Drop a restore result when the live selection or the persisted descriptor+ * changed while enumeration was in flight. This includes reset: both sides can+ * still be null while lastSource went from A to empty.+ */+export function shouldCommitRestoredRecordingSource(options: {+ selectedBeforeId?: string | null;+ selectedAfterId?: string | null;+ lastSourceBefore: RecordingSourceDescriptor | null | undefined;+ lastSourceAfter: RecordingSourceDescriptor | null | undefined;+}): boolean {+ return (+ (options.selectedBeforeId ?? null) === (options.selectedAfterId ?? null) &&+ sameRecordingSourceDescriptor(options.lastSourceBefore, options.lastSourceAfter)+ );+}++export function restoreRecordingSourceAfterEnumeration(options: {+ selectedBefore: LiveRecordingSource | null | undefined;+ selectedAfter: LiveRecordingSource | null | undefined;+ lastSourceBefore: RecordingSourceDescriptor | null | undefined;+ lastSourceAfter: RecordingSourceDescriptor | null | undefined;+ platform: NodeJS.Platform;+ sources: readonly LiveRecordingSource[];+}): { apply: boolean; restored: LiveRecordingSource | null } {+ if (+ !shouldCommitRestoredRecordingSource({+ selectedBeforeId: options.selectedBefore?.id,+ selectedAfterId: options.selectedAfter?.id,+ lastSourceBefore: options.lastSourceBefore,+ lastSourceAfter: options.lastSourceAfter,+ })+ ) {+ return { apply: false, restored: null };+ }+ return {+ apply: true,+ restored: resolveCurrentRecordingSource(+ options.selectedBefore,+ options.lastSourceBefore,+ options.platform,+ options.sources,+ ),+ };+}++/** True when restoration or liveness checking has a source to look up. */+export function shouldEnumerateRecordingSources(+ selected: LiveRecordingSource | null | undefined,+ lastSource: RecordingSourceDescriptor | null | undefined,+): boolean {+ return Boolean(selected?.id || lastSource);+}++/**+ * In-memory selections stay bound to the live id: a browser tab or document title+ * can change without the window going away. Disk restore stays strict.+ */+export function resolveLiveRecordingSource(+ selected: LiveRecordingSource,+ sources: readonly LiveRecordingSource[],+): LiveRecordingSource | null {+ const exact = sources.filter((source) => source.id === selected.id);+ return exact.length === 1 ? exact[0] : null;+}++export function resolveCurrentRecordingSource(+ selected: LiveRecordingSource | null | undefined,+ lastSource: RecordingSourceDescriptor | null | undefined,+ platform: NodeJS.Platform,+ sources: readonly LiveRecordingSource[],+ options: { waylandPortal?: boolean } = {},+): LiveRecordingSource | null {+ if (selected?.id) {+ return resolveLiveRecordingSource(selected, sources);+ }+ return resolveRecordingSource(lastSource ?? null, platform, sources, options);+}++/** Resolves a stored logical descriptor only to an item from a fresh enumeration. */+export function resolveRecordingSource(+ descriptor: RecordingSourceDescriptor | null,+ platform: NodeJS.Platform,+ sources: readonly LiveRecordingSource[],+ options: { waylandPortal?: boolean } = {},+): LiveRecordingSource | null {+ if (!descriptor || descriptor.platform !== platform || options.waylandPortal) return null;+ const kindMatches = sources.filter(+ (source) => (source.id.startsWith("window:") ? "window" : "screen") === descriptor.kind,+ );+ if (descriptor.kind === "window") {+ const exact = kindMatches.filter(+ (source) => source.id === descriptor.id && source.name === descriptor.name,+ );+ return exact.length === 1 ? exact[0] : null;+ }++ if (descriptor.displayId) {+ const stable = kindMatches.filter((source) => source.display_id === descriptor.displayId);+ if (stable.length === 1) return stable[0];+ }+ const exact = kindMatches.filter(+ (source) => source.id === descriptor.id && source.name === descriptor.name,+ );+ return exact.length === 1 ? exact[0] : null;+}diff --git a/src/App.tsx b/src/App.tsxindex aa7619d26..163632f11 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -35,6 +35,11 @@ const ProviderSettingsDialog = lazy(() =>default: module.ProviderSettingsDialog,})),);+const AppSettingsDialog = lazy(() =>+ import("./components/ai-edition/AppSettings").then((module) => ({+ default: module.AppSettingsDialog,+ })),+);export default function App() {const [windowType, setWindowType] = useState(@@ -146,6 +151,7 @@ export default function App() {<VideoEditorEntry /><ShortcutsConfigDialog /><ProviderSettingsDialog />+ <AppSettingsDialog /></Suspense></EditorDialogsProvider></ShortcutsProvider>diff --git a/src/cli/CliRecordRunner.tsx b/src/cli/CliRecordRunner.tsxindex f588caa4c..a3c232472 100644--- a/src/cli/CliRecordRunner.tsx+++ b/src/cli/CliRecordRunner.tsx@@ -120,6 +120,10 @@ export function CliRecordRunner() {setMicrophoneDeviceName,setSystemAudioEnabled,setCursorCaptureMode,+ setWebcamEnabled,+ setWebcamDeviceId,+ setWebcamDeviceName,+ recordingPrefsLoaded,} = recorder;// Keep latest values in refs for the stop/finish effects.@@ -137,9 +141,11 @@ export function CliRecordRunner() {};// Bootstrap: pick source, configure recorder, start.+ // Wait for persisted GUI prefs to land first, then overwrite every field+ // from the CLI request so a previous HUD session cannot enable mic/webcam.// biome-ignore lint/correctness/useExhaustiveDependencies: intentional run-once bootstrap; startedRef guards re-entryuseEffect(() => {- if (startedRef.current) return;+ if (startedRef.current || !recordingPrefsLoaded) return;startedRef.current = true;void (async () => {@@ -157,18 +163,24 @@ export function CliRecordRunner() {requestRef.current = request;const source = await pickSource(request);- await window.electronAPI.selectSource(source);+ await window.electronAPI.selectSource(source, { persist: false });window.electronAPI.cliLog("info", `Recording source: ${source.name}`);+ setMicrophoneEnabled(Boolean(request.mic));if (request.mic) {const mic = await resolveMicDeviceId(request.micDevice);- setMicrophoneEnabled(true);setMicrophoneDeviceId(mic.deviceId);setMicrophoneDeviceName(mic.deviceName);if (mic.deviceName) {window.electronAPI.cliLog("info", `Microphone: ${mic.deviceName}`);}+ } else {+ setMicrophoneDeviceId(undefined);+ setMicrophoneDeviceName(undefined);}+ await setWebcamEnabled(false);+ setWebcamDeviceId(undefined);+ setWebcamDeviceName(undefined);setSystemAudioEnabled(request.systemAudio);setCursorCaptureMode(request.cursorMode);setStatus("Starting recording…");@@ -177,7 +189,7 @@ export function CliRecordRunner() {await fail(error);}})();- }, []);+ }, [recordingPrefsLoaded]);// The setters above land on the *next* render; start only once they have.const configuredRef = useRef(false);@@ -185,10 +197,11 @@ export function CliRecordRunner() {useEffect(() => {const request = requestReady;if (!request || configuredRef.current || phaseRef.current !== "init") return;- const micReady = !request.mic || recorder.microphoneEnabled;+ const micReady = recorder.microphoneEnabled === Boolean(request.mic);+ const webcamReady = !recorder.webcamEnabled;const systemAudioReady = recorder.systemAudioEnabled === request.systemAudio;const cursorReady = recorder.cursorCaptureMode === request.cursorMode;- if (!micReady || !systemAudioReady || !cursorReady) return;+ if (!micReady || !webcamReady || !systemAudioReady || !cursorReady) return;configuredRef.current = true;phaseRef.current = "recording";@@ -214,6 +227,7 @@ export function CliRecordRunner() {}, [requestReady,recorder.microphoneEnabled,+ recorder.webcamEnabled,recorder.systemAudioEnabled,recorder.cursorCaptureMode,]);diff --git a/src/components/ai-edition/AppSettings.test.tsx b/src/components/ai-edition/AppSettings.test.tsxnew file mode 100644index 000000000..505a8afb1--- /dev/null+++ b/src/components/ai-edition/AppSettings.test.tsx@@ -0,0 +1,186 @@+// @vitest-environment jsdom+import "@testing-library/jest-dom";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { EditorDialogsProvider, useEditorDialogActions } from "@/contexts/EditorDialogsContext";+import { createEmptyDocument } from "@/lib/ai-edition/schema";+import { DEFAULT_PROJECT_APPEARANCE } from "@/lib/projectDefaults";+import { AppSettingsDialog } from "./AppSettings";++const project = vi.hoisted(() => ({+ document: null as ReturnType<typeof createEmptyDocument> | null,+}));+vi.mock("@/lib/ai-edition/store/projectStore", () => ({+ useProjectStore: (selector: (state: typeof project) => unknown) => selector(project),+}));+const microphoneHook = vi.hoisted(() => ({+ enabled: [] as boolean[],+}));+vi.mock("@/hooks/useMicrophoneDevices", () => ({+ useMicrophoneDevices: (enabled: boolean) => {+ microphoneHook.enabled.push(enabled);+ return {+ devices: [{ deviceId: "mic-live", label: "Live microphone", groupId: "g" }],+ selectedDeviceId: "mic-live",+ setSelectedDeviceId: vi.fn(),+ };+ },+}));+vi.mock("@/hooks/useCameraDevices", () => ({+ useCameraDevices: () => ({+ devices: [{ deviceId: "cam-live", label: "Live camera", groupId: "g" }],+ selectedDeviceId: "cam-live",+ setSelectedDeviceId: vi.fn(),+ }),+}));+vi.mock("@/contexts/I18nContext", () => ({+ useScopedT: () => (key: string, vars?: Record<string, string>) =>+ vars ? `${key}:${Object.values(vars).join(":")}` : key,+}));++const recording = {+ micEnabled: false,+ micDeviceId: null,+ micDeviceName: null,+ camEnabled: false,+ camDeviceId: null,+ camDeviceName: null,+ systemAudioEnabled: false,+ cursorCaptureMode: "editable-overlay" as const,+};+const snapshot = {+ recording,+ lastSource: null,+ appearance: { version: 1 as const, custom: false, defaults: DEFAULT_PROJECT_APPEARANCE },+};++function OpenSettings() {+ const { openDialog, closeDialog } = useEditorDialogActions();+ return (+ <>+ <button type="button" onClick={() => openDialog("settings")}>+ open settings+ </button>+ <button type="button" onClick={closeDialog}>+ close settings+ </button>+ </>+ );+}++function renderSettings() {+ render(+ <EditorDialogsProvider>+ <OpenSettings />+ <AppSettingsDialog />+ </EditorDialogsProvider>,+ );+ fireEvent.click(screen.getByText("open settings"));+}++describe("AppSettings", () => {+ beforeEach(() => {+ microphoneHook.enabled = [];+ project.document = createEmptyDocument({ projectId: "proj_settings", title: "Settings" });+ window.electronAPI = {+ getAppSettings: vi.fn(async () => snapshot),+ setRecordingPrefs: vi.fn(async (value) => ({ ...recording, ...value })),+ setProjectAppearanceDefaults: vi.fn(async (defaults) => ({+ ...snapshot,+ appearance: { version: 1 as const, custom: true, defaults },+ })),+ resetProjectAppearanceDefaults: vi.fn(async () => snapshot),+ resetRecordingSetup: vi.fn(async () => snapshot),+ } as unknown as typeof window.electronAPI;+ });++ it("does not enable microphone enumeration until the microphone is on", async () => {+ renderSettings();+ await screen.findByTestId("app-settings-dialog");+ expect(microphoneHook.enabled.at(-1)).toBe(false);+ fireEvent.click(screen.getByLabelText("appSettings.microphone"));+ expect(microphoneHook.enabled.at(-1)).toBe(true);+ });++ it("loads settings and saves edited recording toggles", async () => {+ renderSettings();+ expect(await screen.findByTestId("app-settings-dialog")).toBeInTheDocument();+ fireEvent.click(screen.getByLabelText("appSettings.systemAudio"));+ fireEvent.click(screen.getByText("appSettings.saveRecording"));+ await waitFor(() =>+ expect(window.electronAPI.setRecordingPrefs).toHaveBeenCalledWith(+ expect.objectContaining({ systemAudioEnabled: true }),+ ),+ );+ expect(await screen.findByRole("status")).toHaveTextContent("appSettings.saved");+ });++ it("shows a failed save and never reports Saved", async () => {+ vi.mocked(window.electronAPI.setRecordingPrefs).mockRejectedValueOnce(new Error("disk full"));+ renderSettings();+ await screen.findByTestId("app-settings-dialog");+ fireEvent.click(screen.getByText("appSettings.saveRecording"));+ expect(await screen.findByRole("alert")).toHaveTextContent("disk full");+ expect(screen.queryByRole("status")).not.toBeInTheDocument();+ });++ it("shows a load failure without rendering stale settings", async () => {+ vi.mocked(window.electronAPI.getAppSettings).mockRejectedValueOnce(new Error("read failed"));+ renderSettings();+ expect(await screen.findByRole("alert")).toHaveTextContent("read failed");+ expect(screen.queryByText("appSettings.saveRecording")).not.toBeInTheDocument();+ });++ it("does not let a stale save overwrite a newer local edit", async () => {+ let finishSave!: (value: typeof recording) => void;+ vi.mocked(window.electronAPI.setRecordingPrefs).mockImplementation(+ () =>+ new Promise((resolve) => {+ finishSave = resolve;+ }),+ );+ renderSettings();+ await screen.findByTestId("app-settings-dialog");+ fireEvent.click(screen.getByLabelText("appSettings.systemAudio"));+ fireEvent.click(screen.getByText("appSettings.saveRecording"));+ fireEvent.click(screen.getByLabelText("appSettings.systemAudio"));+ expect(screen.getByLabelText("appSettings.systemAudio")).not.toBeChecked();+ finishSave({ ...recording, systemAudioEnabled: true });+ await waitFor(() =>+ expect(window.electronAPI.setRecordingPrefs).toHaveBeenCalledWith(+ expect.objectContaining({ systemAudioEnabled: true }),+ ),+ );+ expect(screen.getByLabelText("appSettings.systemAudio")).not.toBeChecked();+ expect(screen.queryByRole("status")).not.toBeInTheDocument();+ });++ it("clears loaded settings when a later open fails to load", async () => {+ vi.mocked(window.electronAPI.getAppSettings)+ .mockResolvedValueOnce(snapshot)+ .mockRejectedValueOnce(new Error("read failed"));+ renderSettings();+ await screen.findByText("appSettings.saveRecording");+ fireEvent.click(screen.getByText("close settings"));+ fireEvent.click(screen.getByText("open settings"));+ expect(await screen.findByRole("alert")).toHaveTextContent("read failed");+ expect(screen.queryByText("appSettings.saveRecording")).not.toBeInTheDocument();+ });++ it("copies the current look and exposes both reset actions", async () => {+ renderSettings();+ await screen.findByTestId("app-settings-dialog");+ fireEvent.click(screen.getByText("appSettings.useCurrentAppearance"));+ await waitFor(() =>+ expect(window.electronAPI.setProjectAppearanceDefaults).toHaveBeenCalledWith(+ expect.objectContaining({ padding: 50, aspectRatio: "16:9" }),+ ),+ );+ fireEvent.click(screen.getByText("appSettings.resetAppearance"));+ await waitFor(() =>+ expect(window.electronAPI.resetProjectAppearanceDefaults).toHaveBeenCalled(),+ );+ fireEvent.click(screen.getByText("appSettings.resetRecording"));+ await waitFor(() => expect(window.electronAPI.resetRecordingSetup).toHaveBeenCalled());+ });+});diff --git a/src/components/ai-edition/AppSettings.tsx b/src/components/ai-edition/AppSettings.tsxnew file mode 100644index 000000000..6cc9121b6--- /dev/null+++ b/src/components/ai-edition/AppSettings.tsx@@ -0,0 +1,294 @@+import { Camera, Loader2, Mic, Monitor, MousePointer2, RotateCcw, Save } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { useEditorDialogActions, useEditorDialogSection } from "@/contexts/EditorDialogsContext";+import { useScopedT } from "@/contexts/I18nContext";+import { useCameraDevices } from "@/hooks/useCameraDevices";+import { useMicrophoneDevices } from "@/hooks/useMicrophoneDevices";+import { getEditorSettings } from "@/lib/ai-edition/store/editorSettings";+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";+import { projectAppearanceFromEditorSettings } from "@/lib/projectDefaults";+import type { AppSettingsSnapshot, RecordingPreferences } from "../../../electron/app-settings";+import { ModalShell } from "./Modals";+import styles from "./NewEditorShell.module.css";++type Status = "idle" | "loading" | "saving" | "saved" | "error";++function AppSettings({ open, onClose }: { open: boolean; onClose: () => void }) {+ const t = useScopedT("editor");+ const document = useProjectStore((state) => state.document);+ const [snapshot, setSnapshot] = useState<AppSettingsSnapshot | null>(null);+ const [recording, setRecording] = useState<RecordingPreferences | null>(null);+ const [status, setStatus] = useState<Status>("idle");+ const [error, setError] = useState<string | null>(null);+ const generationRef = useRef(0);++ useEffect(() => {+ if (!open) {+ generationRef.current += 1;+ return;+ }+ const generation = ++generationRef.current;+ setStatus("loading");+ setError(null);+ setSnapshot(null);+ setRecording(null);+ void window.electronAPI+ .getAppSettings()+ .then((value) => {+ if (generation !== generationRef.current) return;+ setSnapshot(value);+ setRecording(value.recording);+ setStatus("idle");+ })+ .catch((cause) => {+ if (generation !== generationRef.current) return;+ setError(cause instanceof Error ? cause.message : String(cause));+ setStatus("error");+ });+ }, [open]);++ const microphones = useMicrophoneDevices(+ open && Boolean(recording?.micEnabled),+ recording?.micDeviceId ?? undefined,+ recording?.micDeviceName ?? undefined,+ );+ const cameras = useCameraDevices(+ open,+ recording?.camDeviceId ?? undefined,+ recording?.camDeviceName ?? undefined,+ );++ const run = async (work: () => Promise<AppSettingsSnapshot>) => {+ const generation = ++generationRef.current;+ setStatus("saving");+ setError(null);+ try {+ const next = await work();+ if (generation !== generationRef.current) return;+ setSnapshot(next);+ setRecording(next.recording);+ setStatus("saved");+ } catch (cause) {+ if (generation !== generationRef.current) return;+ setError(cause instanceof Error ? cause.message : String(cause));+ setStatus("error");+ }+ };++ const saveRecording = () => {+ if (!recording) return;+ void run(async () => {+ const saved = await window.electronAPI.setRecordingPrefs(recording);+ const next = await window.electronAPI.getAppSettings();+ return { ...next, recording: saved };+ });+ };+ const editRecording = (patch: Partial<RecordingPreferences>) => {+ generationRef.current += 1;+ setRecording((current) => (current ? { ...current, ...patch } : current));+ setStatus("idle");+ setError(null);+ };++ return (+ <ModalShell+ open={open}+ onClose={onClose}+ title={t("appSettings.title")}+ subtitle={t("appSettings.subtitle")}+ wide+ >+ <div data-testid="app-settings-dialog" style={{ display: "grid", gap: 20 }}>+ {status === "loading" ? (+ <div className={styles.emptyState}>+ <Loader2 size={18} className="animate-spin" /> {t("appSettings.loading")}+ </div>+ ) : recording && snapshot ? (+ <>+ <section style={{ display: "grid", gap: 10 }}>+ <h3>+ <Monitor size={16} /> {t("appSettings.recordingTitle")}+ </h3>+ <SettingToggle+ label={t("appSettings.systemAudio")}+ checked={recording.systemAudioEnabled}+ onChange={(value) => editRecording({ systemAudioEnabled: value })}+ />+ <SettingToggle+ label={t("appSettings.microphone")}+ checked={recording.micEnabled}+ onChange={(value) => editRecording({ micEnabled: value })}+ />+ <label className={styles.field}>+ <span>+ <Mic size={14} /> {t("appSettings.microphoneDevice")}+ </span>+ <select+ value={microphones.selectedDeviceId}+ onChange={(event) => {+ const device = microphones.devices.find(+ (item) => item.deviceId === event.target.value,+ );+ if (!device) return;+ microphones.setSelectedDeviceId(device.deviceId);+ editRecording({+ micDeviceId: device.deviceId,+ micDeviceName: device.label,+ });+ }}+ >+ {microphones.devices.map((device) => (+ <option key={device.deviceId} value={device.deviceId}>+ {device.label}+ </option>+ ))}+ </select>+ </label>+ <SettingToggle+ label={t("appSettings.camera")}+ checked={recording.camEnabled}+ onChange={(value) => editRecording({ camEnabled: value })}+ />+ <label className={styles.field}>+ <span>+ <Camera size={14} /> {t("appSettings.cameraDevice")}+ </span>+ <select+ value={cameras.selectedDeviceId}+ onChange={(event) => {+ const device = cameras.devices.find(+ (item) => item.deviceId === event.target.value,+ );+ if (!device) return;+ cameras.setSelectedDeviceId(device.deviceId);+ editRecording({+ camDeviceId: device.deviceId,+ camDeviceName: device.label,+ });+ }}+ >+ {cameras.devices.map((device) => (+ <option key={device.deviceId} value={device.deviceId}>+ {device.label}+ </option>+ ))}+ </select>+ </label>+ <SettingToggle+ label={t("appSettings.editableCursor")}+ checked={recording.cursorCaptureMode === "editable-overlay"}+ onChange={(value) =>+ editRecording({+ cursorCaptureMode: value ? "editable-overlay" : "system",+ })+ }+ />+ <p>+ {t("appSettings.lastSource", {+ source: snapshot.lastSource?.name ?? t("appSettings.noSource"),+ })}+ </p>+ <div className={styles.actions}>+ <button+ type="button"+ className={`${styles.btn} ${styles.btnPrimary}`}+ onClick={saveRecording}+ disabled={status === "saving"}+ >+ <Save size={14} /> {t("appSettings.saveRecording")}+ </button>+ <button+ type="button"+ className={styles.btn}+ onClick={() => void run(() => window.electronAPI.resetRecordingSetup())}+ disabled={status === "saving"}+ >+ <RotateCcw size={14} /> {t("appSettings.resetRecording")}+ </button>+ </div>+ </section>+ <section style={{ display: "grid", gap: 10 }}>+ <h3>+ <MousePointer2 size={16} /> {t("appSettings.appearanceTitle")}+ </h3>+ <p>+ {snapshot.appearance.custom+ ? t("appSettings.customAppearance")+ : t("appSettings.factoryAppearance")}+ </p>+ <p data-testid="appearance-defaults-summary">+ {t("appSettings.appearanceSummary", {+ aspect: snapshot.appearance.defaults.aspectRatio,+ padding: snapshot.appearance.defaults.padding,+ radius: snapshot.appearance.defaults.borderRadius,+ cursor: snapshot.appearance.defaults.cursorTheme,+ camera: snapshot.appearance.defaults.webcamLayoutPreset,+ })}+ </p>+ <div className={styles.actions}>+ <button+ type="button"+ className={`${styles.btn} ${styles.btnPrimary}`}+ disabled={!document || status === "saving"}+ onClick={() => {+ if (!document) return;+ const defaults = projectAppearanceFromEditorSettings(+ getEditorSettings(document),+ );+ void run(() => window.electronAPI.setProjectAppearanceDefaults(defaults));+ }}+ >+ {t("appSettings.useCurrentAppearance")}+ </button>+ <button+ type="button"+ className={styles.btn}+ onClick={() =>+ void run(() => window.electronAPI.resetProjectAppearanceDefaults())+ }+ disabled={status === "saving"}+ >+ <RotateCcw size={14} /> {t("appSettings.resetAppearance")}+ </button>+ </div>+ </section>+ </>+ ) : null}+ {status === "saved" ? <p role="status">{t("appSettings.saved")}</p> : null}+ {error ? <p role="alert">{t("appSettings.saveFailed", { error })}</p> : null}+ </div>+ </ModalShell>+ );+}++function SettingToggle({+ label,+ checked,+ disabled,+ onChange,+}: {+ label: string;+ checked: boolean;+ disabled?: boolean;+ onChange: (value: boolean) => void;+}) {+ return (+ <label+ style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}+ >+ <span>{label}</span>+ <input+ type="checkbox"+ checked={checked}+ disabled={disabled}+ onChange={(event) => onChange(event.target.checked)}+ />+ </label>+ );+}++export function AppSettingsDialog() {+ const section = useEditorDialogSection();+ const { closeDialog } = useEditorDialogActions();+ return <AppSettings open={section === "settings"} onClose={closeDialog} />;+}diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsxindex fabfc3acb..596ea0c67 100644--- a/src/components/ai-edition/NewEditorShell.tsx+++ b/src/components/ai-edition/NewEditorShell.tsx@@ -1547,6 +1547,7 @@ export function NewEditorShell() {save: () => void handleSave(),export: handleExport,openSettings: handleOpenSettings,+ openAppSettings: () => openDialog("settings"),renameProject: handleRenameProject,toggleChat: () => setChatOpen((v) => !v),openProviderSettings: () => openDialog("providers"),diff --git a/src/components/ai-edition/ProviderSettings.test.tsx b/src/components/ai-edition/ProviderSettings.test.tsxindex 6f20c3ebc..63508dd53 100644--- a/src/components/ai-edition/ProviderSettings.test.tsx+++ b/src/components/ai-edition/ProviderSettings.test.tsx@@ -54,6 +54,7 @@ function TopBar({ mode }: { mode: EditorMode }) {save: noop,export: noop,openSettings: noop,+ openAppSettings: noop,renameProject: noop,toggleChat: noop,openProviderSettings: () => openDialog("providers"),diff --git a/src/components/ai-edition/v4/EditorTopBar.test.tsx b/src/components/ai-edition/v4/EditorTopBar.test.tsxindex 087c3cc38..f904d88ec 100644--- a/src/components/ai-edition/v4/EditorTopBar.test.tsx+++ b/src/components/ai-edition/v4/EditorTopBar.test.tsx@@ -19,15 +19,16 @@ import { EditorTopBar } from "./EditorTopBar";const noop = () => {};-function renderTopBar(projectTitle: string | null) {+function renderTopBar(projectTitle: string | null, mode: "media" | "edit" | "rec" = "edit") {const onRename = vi.fn();const onShowAbout = vi.fn();const onCheckForUpdates = vi.fn();const onOpenSettings = vi.fn();+ const onOpenAppSettings = vi.fn();const onOpenProviderSettings = vi.fn();render(<EditorTopBar- mode="edit"+ mode={mode}onModeChange={noop}projectTitle={projectTitle}dirty={false}@@ -39,6 +40,7 @@ function renderTopBar(projectTitle: string | null) {save: noop,export: noop,openSettings: onOpenSettings,+ openAppSettings: onOpenAppSettings,renameProject: onRename,toggleChat: noop,openProviderSettings: onOpenProviderSettings,@@ -47,7 +49,14 @@ function renderTopBar(projectTitle: string | null) {}}/>,);- return { onRename, onShowAbout, onCheckForUpdates, onOpenSettings, onOpenProviderSettings };+ return {+ onRename,+ onShowAbout,+ onCheckForUpdates,+ onOpenSettings,+ onOpenAppSettings,+ onOpenProviderSettings,+ };}/** The menu reads two separate channels, and they answer different questions: `getAppInfo` for@@ -163,17 +172,25 @@ describe("AppMenu", () => {expect(trigger.getAttribute("style") ?? "").not.toMatch(/all\s*:\s*unset/);});- it("opens on click and offers shortcuts, AI settings and about", () => {+ it("opens on click and offers app settings, shortcuts, AI settings and about", () => {renderTopBar("Demo Project");fireEvent.click(screen.getByRole("button", { name: /OpenScreen/ }));expect(screen.getByRole("menu")).toBeInTheDocument();// Exact names: the translator echoes keys, and both settings rows are labelled with a// `…title` key, so a /title/ match would hit two items and pin neither.expect(screen.getByRole("menuitem", { name: "title" })).toBeInTheDocument();+ expect(screen.getByRole("menuitem", { name: "appSettings.title" })).toBeInTheDocument();expect(screen.getByRole("menuitem", { name: "providerSettings.title" })).toBeInTheDocument();expect(screen.getByRole("menuitem", { name: /actions\.about/ })).toBeInTheDocument();});+ it.each(["media", "edit", "rec"] as const)("opens app settings from %s mode", (mode) => {+ const { onOpenAppSettings } = renderTopBar("Demo Project", mode);+ fireEvent.click(screen.getByRole("button", { name: /OpenScreen/ }));+ fireEvent.click(screen.getByRole("menuitem", { name: "appSettings.title" }));+ expect(onOpenAppSettings).toHaveBeenCalledTimes(1);+ });+// Issue #420: the AI dialog used to be openable only from the chat panel, which mounts in// Edit mode with the panel expanded. The row is unconditional here — its dialog is mounted// in App.tsx, above every mode — so the menu does not lie in Media and Rec.diff --git a/src/components/ai-edition/v4/EditorTopBar.tsx b/src/components/ai-edition/v4/EditorTopBar.tsxindex 0fa4ce90e..ea00e541d 100644--- a/src/components/ai-edition/v4/EditorTopBar.tsx+++ b/src/components/ai-edition/v4/EditorTopBar.tsx@@ -10,6 +10,7 @@ import {PanelLeft,RefreshCw,Save,+ Settings,Sparkles,Sun,} from "lucide-react";@@ -28,6 +29,7 @@ export interface TopBarActions {save: () => void;export: () => void;openSettings: () => void;+ openAppSettings: () => void;renameProject: (title: string) => void;toggleChat: () => void;openProviderSettings: () => void;@@ -397,6 +399,15 @@ function AppMenu({ actions }: { actions: TopBarActions }) {</button>{open ? (<div ref={menuRef} className={styles.appMenu} role="menu" onKeyDown={onMenuKeyDown}>+ <button+ type="button"+ role="menuitem"+ className={styles.appMenuRow}+ onClick={run(actions.openAppSettings)}+ >+ <Settings size={15} />+ {tEditor("appSettings.title")}+ </button><buttontype="button"role="menuitem"diff --git a/src/components/ai-edition/v4/RecStage.test.tsx b/src/components/ai-edition/v4/RecStage.test.tsxindex f2b0f0146..610751fb9 100644--- a/src/components/ai-edition/v4/RecStage.test.tsx+++ b/src/components/ai-edition/v4/RecStage.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdomimport "@testing-library/jest-dom";-import { cleanup, render, screen, waitFor } from "@testing-library/react";+import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { RecStage } from "./RecStage";@@ -8,13 +8,22 @@ vi.mock("@/contexts/I18nContext", () => ({useScopedT: () => (key: string) => key,}));-vi.mock("@/hooks/useMicrophoneDevices", () => ({- useMicrophoneDevices: () => ({- devices: [],+const microphoneHook = vi.hoisted(() => ({+ call: vi.fn(),+ value: {+ devices: [] as Array<{ deviceId: string; label: string; groupId: string }>,selectedDeviceId: "default",setSelectedDeviceId: vi.fn(),isLoading: false,- }),+ isReady: true,+ error: null as string | null,+ },+}));+vi.mock("@/hooks/useMicrophoneDevices", () => ({+ useMicrophoneDevices: (...args: unknown[]) => {+ microphoneHook.call(...args);+ return microphoneHook.value;+ },}));vi.mock("@/hooks/useCameraDevices", () => ({@@ -27,38 +36,80 @@ vi.mock("@/hooks/useCameraDevices", () => ({}),}));+const audioMeter = vi.hoisted(() => ({ call: vi.fn() }));vi.mock("@/hooks/useAudioLevelMeter", () => ({- useAudioLevelMeter: () => ({ level: 0 }),+ useAudioLevelMeter: (options: unknown) => {+ audioMeter.call(options);+ return { level: 0 };+ },}));+const cameraPreview = vi.hoisted(() => ({ call: vi.fn() }));vi.mock("@/hooks/useCameraPreviewStream", () => ({- useCameraPreviewStream: () => ({ stream: null, error: null }),+ useCameraPreviewStream: (options: unknown) => {+ cameraPreview.call(options);+ return { stream: null, error: null };+ },}));vi.mock("@/hooks/usePortalOwnsSource", () => ({usePortalOwnsSource: () => false,}));-function stubRecordingPrefs(prefs: Record<string, unknown> = {}) {+type RecordingPrefs = Awaited<ReturnType<Window["electronAPI"]["getRecordingPrefs"]>>;+type SelectedSource = Awaited<ReturnType<Window["electronAPI"]["getSelectedSource"]>>;+let recordingPrefsListeners: Array<(prefs: RecordingPrefs) => void> = [];+let selectedSourceListeners: Array<(source: SelectedSource) => void> = [];++function stubRecordingPrefs(+ prefs: Record<string, unknown> = {},+ selectedSource: SelectedSource = null,+) {const getRecordingPrefs = vi.fn(async () => prefs);const setRecordingPrefs = vi.fn(async () => undefined);(window as unknown as { electronAPI?: unknown }).electronAPI = {getRecordingPrefs,setRecordingPrefs,- getSelectedSource: vi.fn(async () => null),+ getSelectedSource: vi.fn(async () => selectedSource),+ onRecordingPrefsChanged: vi.fn((callback: (next: RecordingPrefs) => void) => {+ recordingPrefsListeners.push(callback);+ return () => {+ recordingPrefsListeners = recordingPrefsListeners.filter(+ (listener) => listener !== callback,+ );+ };+ }),+ onSelectedSourceChanged: vi.fn((callback: (next: SelectedSource) => void) => {+ selectedSourceListeners.push(callback);+ return () => {+ selectedSourceListeners = selectedSourceListeners.filter(+ (listener) => listener !== callback,+ );+ };+ }),};return { getRecordingPrefs, setRecordingPrefs };}function renderRecStage() {const onStartRecording = vi.fn();- render(<RecStage onStartRecording={onStartRecording} />);- return { onStartRecording };+ const view = render(<RecStage onStartRecording={onStartRecording} />);+ return { onStartRecording, ...view };}describe("RecStage controls", () => {beforeEach(() => {vi.clearAllMocks();+ recordingPrefsListeners = [];+ selectedSourceListeners = [];+ microphoneHook.value = {+ devices: [],+ selectedDeviceId: "default",+ setSelectedDeviceId: vi.fn(),+ isLoading: false,+ isReady: true,+ error: null,+ };});afterEach(() => {@@ -77,4 +128,148 @@ describe("RecStage controls", () => {});expect(screen.queryByTestId("rec-auto-zoom-button")).toBeNull();});++ it("waits for microphone discovery before starting the meter and normalizes default", async () => {+ stubRecordingPrefs({+ micEnabled: true,+ micDeviceId: "saved-id",+ micDeviceName: "Saved microphone",+ });+ microphoneHook.value = {+ ...microphoneHook.value,+ isLoading: true,+ isReady: false,+ };+ const { rerender, onStartRecording } = renderRecStage();+ await waitFor(() =>+ expect(microphoneHook.call).toHaveBeenCalledWith(true, "saved-id", "Saved microphone"),+ );+ expect(audioMeter.call).toHaveBeenLastCalledWith({ enabled: false, deviceId: undefined });++ microphoneHook.value = {+ ...microphoneHook.value,+ devices: [{ deviceId: "default", label: "System default", groupId: "g" }],+ selectedDeviceId: "default",+ isLoading: false,+ isReady: true,+ };+ rerender(<RecStage onStartRecording={onStartRecording} />);+ expect(audioMeter.call).toHaveBeenLastCalledWith({ enabled: true, deviceId: undefined });+ });++ it("shows explicit empty and error states instead of an empty microphone select", async () => {+ stubRecordingPrefs({ micEnabled: true });+ microphoneHook.value = { ...microphoneHook.value, devices: [], error: null };+ const { rerender, onStartRecording } = renderRecStage();+ expect(await screen.findByText("rec.noMicrophoneFound")).toBeInTheDocument();+ expect(screen.queryByRole("combobox")).not.toBeInTheDocument();++ microphoneHook.value = {+ ...microphoneHook.value,+ devices: [],+ error: "enumeration failed",+ };+ rerender(<RecStage onStartRecording={onStartRecording} />);+ expect(screen.getByText("rec.microphoneUnavailable")).toHaveAttribute(+ "title",+ "enumeration failed",+ );+ });++ it("ties microphone discovery to the toggle so off then on requests a retry", async () => {+ stubRecordingPrefs({ micEnabled: true });+ renderRecStage();+ await screen.findByText("rec.noMicrophoneFound");+ const row = screen.getByText("rec.microphone").closest("div");+ if (!row?.parentElement) throw new Error("microphone row is missing");+ const toggle = within(row.parentElement).getByRole("button", { name: "rec.on" });+ microphoneHook.call.mockClear();+ fireEvent.click(toggle);+ await waitFor(() =>+ expect(microphoneHook.call).toHaveBeenLastCalledWith(false, undefined, undefined),+ );+ fireEvent.click(within(row.parentElement).getByRole("button", { name: "rec.off" }));+ await waitFor(() =>+ expect(microphoneHook.call).toHaveBeenLastCalledWith(true, undefined, undefined),+ );+ });++ it("applies reset events and ignores older initial preference and source reads", async () => {+ let resolvePrefs: ((value: RecordingPrefs) => void) | undefined;+ let resolveSource: ((value: SelectedSource) => void) | undefined;+ const initialPrefs = new Promise<RecordingPrefs>((resolve) => {+ resolvePrefs = resolve;+ });+ const initialSource = new Promise<SelectedSource>((resolve) => {+ resolveSource = resolve;+ });+ (window as unknown as { electronAPI?: unknown }).electronAPI = {+ getRecordingPrefs: vi.fn(() => initialPrefs),+ setRecordingPrefs: vi.fn(async () => undefined),+ getSelectedSource: vi.fn(() => initialSource),+ onRecordingPrefsChanged: vi.fn((callback: (next: RecordingPrefs) => void) => {+ recordingPrefsListeners.push(callback);+ return () => {+ recordingPrefsListeners = recordingPrefsListeners.filter(+ (listener) => listener !== callback,+ );+ };+ }),+ onSelectedSourceChanged: vi.fn((callback: (next: SelectedSource) => void) => {+ selectedSourceListeners.push(callback);+ return () => {+ selectedSourceListeners = selectedSourceListeners.filter(+ (listener) => listener !== callback,+ );+ };+ }),+ };+ const { unmount } = renderRecStage();+ await waitFor(() => {+ expect(recordingPrefsListeners).toHaveLength(1);+ expect(selectedSourceListeners).toHaveLength(1);+ });++ const resetPrefs: RecordingPrefs = {+ micEnabled: false,+ micDeviceId: null,+ micDeviceName: null,+ camEnabled: false,+ camDeviceId: null,+ camDeviceName: null,+ systemAudioEnabled: false,+ cursorCaptureMode: "editable-overlay",+ };+ act(() => {+ recordingPrefsListeners.forEach((listener) => listener(resetPrefs));+ selectedSourceListeners.forEach((listener) => listener(null));+ });+ await act(async () => {+ resolvePrefs?.({+ ...resetPrefs,+ micEnabled: true,+ camEnabled: true,+ systemAudioEnabled: true,+ });+ resolveSource?.({+ id: "screen:stale",+ name: "Stale source",+ display_id: "1",+ thumbnail: null,+ appIcon: null,+ });+ });++ await waitFor(() =>+ expect(microphoneHook.call).toHaveBeenLastCalledWith(false, undefined, undefined),+ );+ expect(audioMeter.call).toHaveBeenLastCalledWith({ enabled: false, deviceId: undefined });+ expect(cameraPreview.call).toHaveBeenLastCalledWith({ enabled: false, deviceId: undefined });+ expect(screen.getByRole("button", { name: "rec.selectSource" })).toBeInTheDocument();+ expect(screen.queryByText("Stale source")).not.toBeInTheDocument();++ unmount();+ expect(recordingPrefsListeners).toEqual([]);+ expect(selectedSourceListeners).toEqual([]);+ });});diff --git a/src/components/ai-edition/v4/RecStage.tsx b/src/components/ai-edition/v4/RecStage.tsxindex 23a39d0db..883360716 100644--- a/src/components/ai-edition/v4/RecStage.tsx+++ b/src/components/ai-edition/v4/RecStage.tsx@@ -26,6 +26,7 @@ interface RecordingPrefsState {micDeviceName: string | null;camEnabled: boolean;camDeviceId: string | null;+ camDeviceName: string | null;systemAudioEnabled: boolean;cursorCaptureMode: "editable-overlay" | "system";}@@ -36,10 +37,18 @@ const DEFAULT_PREFS: RecordingPrefsState = {micDeviceName: null,camEnabled: false,camDeviceId: null,+ camDeviceName: null,systemAudioEnabled: false,cursorCaptureMode: "editable-overlay",};+function normalizedRecordingPrefs(prefs: Partial<RecordingPrefsState>): RecordingPrefsState {+ return {+ ...DEFAULT_PREFS,+ ...prefs,+ };+}+/*** Rec-mode stage. The real capture pipeline lives in the standalone recorder* HUD window (`electronAPI.startNewRecording`); this stage is a pre-flight@@ -64,14 +73,16 @@ export function RecStage({const [prefs, setPrefsState] = useState<RecordingPrefsState>(DEFAULT_PREFS);useEffect(() => {let cancelled = false;+ let receivedNewerSnapshot = false;+ const unsubscribe = window.electronAPI?.onRecordingPrefsChanged?.((next) => {+ receivedNewerSnapshot = true;+ if (!cancelled) setPrefsState(normalizedRecordingPrefs(next));+ });void window.electronAPI?.getRecordingPrefs?.().then((p) => {- if (!cancelled && p) {- setPrefsState({- ...DEFAULT_PREFS,- ...p,- } as RecordingPrefsState);+ if (!cancelled && !receivedNewerSnapshot && p) {+ setPrefsState(normalizedRecordingPrefs(p));}}).catch((err) => {@@ -81,6 +92,7 @@ export function RecStage({});return () => {cancelled = true;+ unsubscribe?.();};}, []);const updatePrefs = (patch: Partial<RecordingPrefsState>) => {@@ -93,8 +105,16 @@ export function RecStage({});};- const micDevices = useMicrophoneDevices(true);- const camDevices = useCameraDevices(true);+ const micDevices = useMicrophoneDevices(+ prefs.micEnabled,+ prefs.micDeviceId ?? undefined,+ prefs.micDeviceName ?? undefined,+ );+ const camDevices = useCameraDevices(+ true,+ prefs.camDeviceId ?? undefined,+ prefs.camDeviceName ?? undefined,+ );// Seed the device hooks' local "selected" state from the persisted prefs// once devices are enumerated, so the dropdown reflects the last real@@ -113,12 +133,15 @@ export function RecStage({// Live proof the selected devices actually work — a level meter for mic,// a real <video> feed for camera — instead of just toggling a pref flag.const { level: micLevel } = useAudioLevelMeter({- enabled: prefs.micEnabled,- deviceId: prefs.micDeviceId ?? undefined,+ enabled: prefs.micEnabled && micDevices.isReady && micDevices.devices.length > 0,+ deviceId:+ micDevices.selectedDeviceId && micDevices.selectedDeviceId !== "default"+ ? micDevices.selectedDeviceId+ : undefined,});const { stream: cameraStream, error: cameraError } = useCameraPreviewStream({enabled: prefs.camEnabled,- deviceId: prefs.camDeviceId ?? undefined,+ deviceId: camDevices.selectedDeviceId || undefined,});const cameraVideoRef = useRef<HTMLVideoElement | null>(null);useEffect(() => {@@ -128,12 +151,24 @@ export function RecStage({// ── capture source (screen/window) ──────────────────────────────const [source, setSource] = useState<ProcessedDesktopSource | null>(null);useEffect(() => {+ let cancelled = false;+ let receivedNewerSource = false;+ const unsubscribe = window.electronAPI?.onSelectedSourceChanged?.((next) => {+ receivedNewerSource = true;+ if (!cancelled) setSource(next);+ });void window.electronAPI?.getSelectedSource?.()- .then((s) => setSource(s ?? null))+ .then((next) => {+ if (!cancelled && !receivedNewerSource) setSource(next ?? null);+ }).catch((err) => {console.warn("[rec-stage] failed to read the selected source:", err);});+ return () => {+ cancelled = true;+ unsubscribe?.();+ };}, []);const [sourceModalOpen, setSourceModalOpen] = useState(false);const [sourceTab, setSourceTab] = useState<"screen" | "window">("screen");@@ -155,7 +190,7 @@ export function RecStage({};const chooseSource = async (candidate: ProcessedDesktopSource) => {const result = await window.electronAPI?.selectSource?.(candidate);- setSource(result ?? candidate);+ setSource(result ?? null);setSourceModalOpen(false);};const screenSources = sources.filter((s) => s.id.startsWith("screen:"));@@ -169,7 +204,7 @@ export function RecStage({const portalOwnsSource = usePortalOwnsSource();const sourceLabel = portalOwnsSource? t("rec.systemPicker")- : (source?.name ?? t("rec.entireScreen"));+ : (source?.name ?? t("rec.selectSource"));return (<div className={styles.recStage}>@@ -274,15 +309,21 @@ export function RecStage({</div><div className={styles.recRowControl}>{prefs.micEnabled ? (- micDevices.isLoading ? (+ micDevices.isLoading || !micDevices.isReady ? (<span className={styles.recRowMuted}><Loader2 size={13} className="animate-spin" />{t("rec.loading")}</span>+ ) : micDevices.error ? (+ <span className={styles.recRowMuted} title={micDevices.error}>+ {t("rec.microphoneUnavailable")}+ </span>+ ) : micDevices.devices.length === 0 ? (+ <span className={styles.recRowMuted}>{t("rec.noMicrophoneFound")}</span>) : (<selectclassName={styles.recSelect}- value={prefs.micDeviceId ?? micDevices.selectedDeviceId}+ value={micDevices.selectedDeviceId}onChange={(e) => {const deviceId = e.target.value;micDevices.setSelectedDeviceId(deviceId);@@ -332,10 +373,15 @@ export function RecStage({) : (<selectclassName={styles.recSelect}- value={prefs.camDeviceId ?? camDevices.selectedDeviceId}+ value={camDevices.selectedDeviceId}onChange={(e) => {- camDevices.setSelectedDeviceId(e.target.value);- updatePrefs({ camDeviceId: e.target.value });+ const deviceId = e.target.value;+ camDevices.setSelectedDeviceId(deviceId);+ updatePrefs({+ camDeviceId: deviceId,+ camDeviceName:+ camDevices.devices.find((d) => d.deviceId === deviceId)?.label ?? null,+ });}}>{camDevices.devices.map((d) => (diff --git a/src/components/launch/HudDeviceSettings.tsx b/src/components/launch/HudDeviceSettings.tsxindex 4b40206d7..63d14bb7f 100644--- a/src/components/launch/HudDeviceSettings.tsx+++ b/src/components/launch/HudDeviceSettings.tsx@@ -124,7 +124,7 @@ export const HudDeviceSettings = memo(function HudDeviceSettings({const hasCamera = cameraDevices.length > 0 && !cameraError && !cameraLoading;const { level } = useAudioLevelMeter({enabled: micDevices.length > 0,- deviceId: activeMicId,+ deviceId: activeMicId && activeMicId !== "default" ? activeMicId : undefined,});const { stream, error: previewError } = useCameraPreviewStream({enabled: hasCamera,diff --git a/src/components/launch/LaunchWindow.test.tsx b/src/components/launch/LaunchWindow.test.tsxindex 201cbfd8d..856c608b6 100644--- a/src/components/launch/LaunchWindow.test.tsx+++ b/src/components/launch/LaunchWindow.test.tsx@@ -63,6 +63,7 @@ const recorderState = vi.hoisted(() => ({setCursorCaptureMode: vi.fn(),softwareEncoderFallbackNoticeVisible: false,dismissSoftwareEncoderFallbackNotice: vi.fn(),+ recordingPrefsLoaded: true,},}));@@ -83,21 +84,31 @@ vi.mock("../../hooks/useMicrophoneDevices", () => ({devices: micDevicesState.value,selectedDeviceId: "default",setSelectedDeviceId: vi.fn(),+ isReady: true,}),}));+const cameraDevicesState = vi.hoisted(() => ({+ isReady: true,+}));+vi.mock("../../hooks/useCameraDevices", () => ({useCameraDevices: () => ({devices: [],selectedDeviceId: "",setSelectedDeviceId: vi.fn(),isLoading: false,+ isReady: cameraDevicesState.isReady,error: null,}),}));+const audioLevelMeter = vi.hoisted(() => ({ call: vi.fn() }));vi.mock("../../hooks/useAudioLevelMeter", () => ({- useAudioLevelMeter: () => ({ level: 0 }),+ useAudioLevelMeter: (options: unknown) => {+ audioLevelMeter.call(options);+ return { level: 0 };+ },}));vi.mock("../../hooks/useCameraPreviewStream", () => ({@@ -290,8 +301,10 @@ function emitSourceSelectorClosed() {function resetLaunchMocks() {vi.stubGlobal("ResizeObserver", StubResizeObserver);- recorderState.value.toggleRecording.mockClear();+ recorderState.value.toggleRecording = vi.fn();recorderState.value.cursorCaptureMode = "editable-overlay";+ recorderState.value.systemAudioEnabled = false;+ recorderState.value.setSystemAudioEnabled.mockClear();recorderState.value.setCursorCaptureMode.mockClear();recorderState.value.softwareEncoderFallbackNoticeVisible = false;recorderState.value.dismissSoftwareEncoderFallbackNotice.mockClear();@@ -302,7 +315,10 @@ function resetLaunchMocks() {recorderState.value.setMicrophoneDeviceId.mockClear();recorderState.value.webcamEnabled = false;recorderState.value.setWebcamEnabled.mockClear();+ recorderState.value.recordingPrefsLoaded = true;+ cameraDevicesState.isReady = true;micDevicesState.value = [];+ audioLevelMeter.call.mockClear();hudCursorListeners = [];selectedSourceChangedListeners = [];sourceSelectorClosedListeners = [];@@ -499,6 +515,81 @@ describe("LaunchWindow record button", () => {expect(window.electronAPI.openSourceSelector).not.toHaveBeenCalled();});+ it("does not wait for the camera list when the webcam is off", async () => {+ cameraDevicesState.isReady = false;+ recorderState.value.webcamEnabled = false;+ stubElectronAPI(vi.fn(async () => displayOneSource));++ renderLaunchWindow();++ const recordButton = await screen.findByTestId("launch-record-button");+ await waitFor(() => {+ expect(recordButton).toHaveAttribute("title", "Display 1");+ });++ fireEvent.click(recordButton);++ await waitFor(() => {+ expect(recorderState.value.toggleRecording).toHaveBeenCalledTimes(1);+ });+ });++ it("does not start recording twice while waiting for device prefs", async () => {+ recorderState.value.recordingPrefsLoaded = false;+ stubElectronAPI(vi.fn(async () => displayOneSource));++ const view = renderLaunchWindow();+ const recordButton = await screen.findByTestId("launch-record-button");+ await waitFor(() => {+ expect(recordButton).toHaveAttribute("title", "Display 1");+ });++ fireEvent.click(recordButton);+ fireEvent.click(recordButton);+ expect(recorderState.value.toggleRecording).not.toHaveBeenCalled();++ recorderState.value.recordingPrefsLoaded = true;+ view.rerender(+ <TooltipProvider>+ <LaunchWindow />+ </TooltipProvider>,+ );++ await waitFor(() => {+ expect(recorderState.value.toggleRecording).toHaveBeenCalledTimes(1);+ });+ });++ it("starts with the latest record callback after prefs finish loading", async () => {+ const firstToggle = vi.fn();+ const secondToggle = vi.fn();+ recorderState.value.toggleRecording = firstToggle;+ recorderState.value.recordingPrefsLoaded = false;+ stubElectronAPI(vi.fn(async () => displayOneSource));++ const view = renderLaunchWindow();+ const recordButton = await screen.findByTestId("launch-record-button");+ await waitFor(() => {+ expect(recordButton).toHaveAttribute("title", "Display 1");+ });++ fireEvent.click(recordButton);+ expect(firstToggle).not.toHaveBeenCalled();++ recorderState.value.toggleRecording = secondToggle;+ recorderState.value.recordingPrefsLoaded = true;+ view.rerender(+ <TooltipProvider>+ <LaunchWindow />+ </TooltipProvider>,+ );++ await waitFor(() => {+ expect(secondToggle).toHaveBeenCalledTimes(1);+ });+ expect(firstToggle).not.toHaveBeenCalled();+ });+// The #385 regression, and #266 before it. A HUD that has gone click-through// receives no pointer event of any kind, so every DOM route back — pointerenter,// pointerdown, pointermove — is unreachable by construction. This test therefore@@ -1067,6 +1158,109 @@ describe("LaunchWindow device buttons", () => {expect(recorderState.value.setMicrophoneEnabled).toHaveBeenCalledWith(false);});+ it("persists turning system audio on", async () => {+ renderLaunchWindow();++ fireEvent.click(await screen.findByTestId("launch-system-audio-button"));++ expect(recorderState.value.setSystemAudioEnabled).toHaveBeenCalledWith(true);+ expect(window.electronAPI.setRecordingPrefs).toHaveBeenCalledWith({ systemAudioEnabled: true });+ });++ it("persists turning system audio off", async () => {+ recorderState.value.systemAudioEnabled = true;++ renderLaunchWindow();++ fireEvent.click(await screen.findByTestId("launch-system-audio-button"));++ expect(recorderState.value.setSystemAudioEnabled).toHaveBeenCalledWith(false);+ expect(window.electronAPI.setRecordingPrefs).toHaveBeenCalledWith({+ systemAudioEnabled: false,+ });+ });++ it("persists turning the microphone on", async () => {+ renderLaunchWindow();++ fireEvent.click(await screen.findByTestId("launch-microphone-button"));++ expect(recorderState.value.setMicrophoneEnabled).toHaveBeenCalledWith(true);+ expect(window.electronAPI.setRecordingPrefs).toHaveBeenCalledWith({ micEnabled: true });+ });++ it("persists turning the microphone off", async () => {+ recorderState.value.microphoneEnabled = true;++ renderLaunchWindow();++ fireEvent.click(await screen.findByTestId("launch-microphone-button"));++ expect(recorderState.value.setMicrophoneEnabled).toHaveBeenCalledWith(false);+ expect(window.electronAPI.setRecordingPrefs).toHaveBeenCalledWith({ micEnabled: false });+ });++ it("persists switching to the system cursor", async () => {+ renderLaunchWindow();++ fireEvent.click(await screen.findByTestId("launch-cursor-mode-button"));++ expect(recorderState.value.setCursorCaptureMode).toHaveBeenCalledWith("system");+ expect(window.electronAPI.setRecordingPrefs).toHaveBeenCalledWith({+ cursorCaptureMode: "system",+ });+ });++ it("persists switching to the editable cursor", async () => {+ recorderState.value.cursorCaptureMode = "system";++ renderLaunchWindow();++ fireEvent.click(await screen.findByTestId("launch-cursor-mode-button"));++ expect(recorderState.value.setCursorCaptureMode).toHaveBeenCalledWith("editable-overlay");+ expect(window.electronAPI.setRecordingPrefs).toHaveBeenCalledWith({+ cursorCaptureMode: "editable-overlay",+ });+ });++ it("does not mutate toggles or preferences while recording", async () => {+ recorderState.value.recording = true;+ renderLaunchWindow();++ const systemAudioButton = await screen.findByTestId("launch-system-audio-button");+ const microphoneButton = await screen.findByTestId("launch-microphone-button");+ const cursorButton = await screen.findByTestId("launch-cursor-mode-button");++ expect(systemAudioButton).toBeDisabled();+ expect(microphoneButton).toBeDisabled();+ expect(cursorButton).toBeDisabled();+ fireEvent.click(systemAudioButton);+ fireEvent.click(microphoneButton);+ fireEvent.click(cursorButton);++ expect(recorderState.value.setSystemAudioEnabled).not.toHaveBeenCalled();+ expect(recorderState.value.setMicrophoneEnabled).not.toHaveBeenCalled();+ expect(recorderState.value.setCursorCaptureMode).not.toHaveBeenCalled();+ expect(window.electronAPI.setRecordingPrefs).not.toHaveBeenCalled();+ });++ it("keeps a local toggle change when preference persistence fails", async () => {+ const error = new Error("preference store unavailable");+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);+ vi.mocked(window.electronAPI.setRecordingPrefs).mockRejectedValue(error);++ renderLaunchWindow();+ fireEvent.click(await screen.findByTestId("launch-system-audio-button"));++ expect(recorderState.value.setSystemAudioEnabled).toHaveBeenCalledWith(true);+ await waitFor(() => {+ expect(warnSpy).toHaveBeenCalledWith("Failed to persist the device preference:", error);+ });++ warnSpy.mockRestore();+ });+it("turns the camera on with a single click, without opening anything", async () => {renderLaunchWindow();@@ -1135,6 +1329,17 @@ describe("LaunchWindow device settings", () => {expect(recorderState.value.setMicrophoneEnabled).not.toHaveBeenCalled();});+ it("uses an unconstrained meter request for the default microphone pseudo-device", async () => {+ micDevicesState.value = [{ deviceId: "default", label: "System default", groupId: "g" }];+ renderLaunchWindow();+ fireEvent.click(await screen.findByTestId("launch-device-settings-button"));+ await screen.findByTestId("hud-device-settings");+ expect(audioLevelMeter.call).toHaveBeenLastCalledWith({+ enabled: true,+ deviceId: undefined,+ });+ });+// The gear is disabled while recording, but a panel that was already open stays mounted —// and the main process refuses the check for the length of a take. Offering the button then// would give the user a click that does nothing at all: no dialog, no error, no feedback.diff --git a/src/components/launch/LaunchWindow.tsx b/src/components/launch/LaunchWindow.tsxindex c8f989755..e5a2e5ff7 100644--- a/src/components/launch/LaunchWindow.tsx+++ b/src/components/launch/LaunchWindow.tsx@@ -4,7 +4,11 @@ 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 MicrophoneDevice, useMicrophoneDevices } from "../../hooks/useMicrophoneDevices";+import {+ isPlaceholderMicrophoneLabel,+ type MicrophoneDevice,+ useMicrophoneDevices,+} from "../../hooks/useMicrophoneDevices";import { usePortalOwnsSource } from "../../hooks/usePortalOwnsSource";import { useScreenRecorder } from "../../hooks/useScreenRecorder";import { requestCameraAccess } from "../../lib/requestCameraAccess";@@ -106,11 +110,13 @@ export function LaunchWindow() {setWebcamEnabled,webcamDeviceId,setWebcamDeviceId,+ webcamDeviceName,setWebcamDeviceName,cursorCaptureMode,setCursorCaptureMode,softwareEncoderFallbackNoticeVisible,dismissSoftwareEncoderFallbackNotice,+ recordingPrefsLoaded,} = useScreenRecorder();// Choosing a device and switching one on are deliberately separate concerns.@@ -168,14 +174,16 @@ export function LaunchWindow() {selectedDeviceId: selectedCameraId,setSelectedDeviceId: setSelectedCameraId,isLoading: isCameraDevicesLoading,+ isReady: cameraDevicesReady,error: cameraDevicesError,- } = useCameraDevices(true, webcamDeviceId);+ } = useCameraDevices(true, webcamDeviceId, webcamDeviceName);// 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 {devices: micDevices,selectedDeviceId: selectedMicId,setSelectedDeviceId: setSelectedMicId,+ isReady: micDevicesReady,} = useMicrophoneDevices(microphoneEnabled || isDeviceSettingsOpen,microphoneDeviceId,@@ -185,9 +193,15 @@ export function LaunchWindow() {useEffect(() => {if (selectedMicId && selectedMicId !== "default") {setMicrophoneDeviceId(selectedMicId);- setMicrophoneDeviceName(micDevices.find((d) => d.deviceId === selectedMicId)?.label);+ const liveLabel = micDevices.find((d) => d.deviceId === selectedMicId)?.label;+ if (liveLabel && !isPlaceholderMicrophoneLabel(liveLabel, selectedMicId)) {+ setMicrophoneDeviceName(liveLabel);+ }+ } else if (micDevicesReady) {+ setMicrophoneDeviceId(undefined);+ setMicrophoneDeviceName(undefined);}- }, [selectedMicId, micDevices, setMicrophoneDeviceId, setMicrophoneDeviceName]);+ }, [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@@ -199,8 +213,17 @@ export function LaunchWindow() {if (selectedCameraId) {setWebcamDeviceId(selectedCameraId);setWebcamDeviceName(selectedCameraLabel);+ } else if (cameraDevicesReady) {+ setWebcamDeviceId(undefined);+ setWebcamDeviceName(undefined);}- }, [selectedCameraId, selectedCameraLabel, setWebcamDeviceId, setWebcamDeviceName]);+ }, [+ selectedCameraId,+ selectedCameraLabel,+ cameraDevicesReady,+ setWebcamDeviceId,+ setWebcamDeviceName,+ ]);useEffect(() => {let cancelled = false;@@ -597,6 +620,58 @@ export function LaunchWindow() {},[defaultSourceName],);+ const deviceReadinessRef = useRef({+ recordingPrefsLoaded,+ cameraDevicesReady,+ micDevicesReady,+ microphoneEnabled,+ webcamEnabled,+ });+ const toggleRecordingRef = useRef(toggleRecording);+ const startWhenDevicesReadyInFlight = useRef<Promise<void> | null>(null);+ useLayoutEffect(() => {+ deviceReadinessRef.current = {+ recordingPrefsLoaded,+ cameraDevicesReady,+ micDevicesReady,+ microphoneEnabled,+ webcamEnabled,+ };+ toggleRecordingRef.current = toggleRecording;+ }, [+ recordingPrefsLoaded,+ cameraDevicesReady,+ micDevicesReady,+ microphoneEnabled,+ webcamEnabled,+ toggleRecording,+ ]);+ const startWhenDevicesReady = useCallback(() => {+ if (startWhenDevicesReadyInFlight.current) {+ return startWhenDevicesReadyInFlight.current;+ }+ const pending = (async () => {+ try {+ for (let attempt = 0; attempt < 100; attempt++) {+ const ready = deviceReadinessRef.current;+ if (+ ready.recordingPrefsLoaded &&+ (!ready.webcamEnabled || ready.cameraDevicesReady) &&+ (!ready.microphoneEnabled || ready.micDevicesReady)+ ) {+ toggleRecordingRef.current();+ return;+ }+ await new Promise((resolve) => setTimeout(resolve, 25));+ }+ console.warn("Recording did not start because device preferences could not be resolved.");+ } finally {+ startWhenDevicesReadyInFlight.current = null;+ }+ })();+ startWhenDevicesReadyInFlight.current = pending;+ return pending;+ }, []);// The main process pushes every change through `onSelectedSourceChanged`, so// this only needs one read to seed the initial value (plus one on focus, in@@ -637,7 +712,7 @@ export function LaunchWindow() {}recordAfterSourceSelectionRef.current = false;- toggleRecording();+ void startWhenDevicesReady();});const cleanupSelectorClosed = window.electronAPI?.onSourceSelectorClosed?.(() => {recordAfterSourceSelectionRef.current = false;@@ -647,7 +722,7 @@ export function LaunchWindow() {cleanupSourceChanged?.();cleanupSelectorClosed?.();};- }, [applySelectedSource, recording, toggleRecording]);+ }, [applySelectedSource, recording, startWhenDevicesReady]);const openSourceSelector = useCallback(async () => {if (window.electronAPI) {@@ -685,7 +760,7 @@ export function LaunchWindow() {// all. Honouring the refusal starts the recording instead,// whatever the local state has caught up to.if (result.reason === "portal-owns-selection" && !recording) {- toggleRecording();+ void startWhenDevicesReady();}}).catch(() => {@@ -694,9 +769,16 @@ export function LaunchWindow() {return;}- toggleRecording();+ void startWhenDevicesReady();},- [hasSelectedSource, portalOwnsSource, openSourceSelector, recording, saving, toggleRecording],+ [+ hasSelectedSource,+ portalOwnsSource,+ openSourceSelector,+ recording,+ saving,+ startWhenDevicesReady,+ ],);const handleRecordClick = useCallback(() => handleRecordButtonClick(), [handleRecordButtonClick]);@@ -753,36 +835,23 @@ export function LaunchWindow() {});}, [closePopovers]);- const toggleSystemAudio = useCallback(() => {- if (controlsLocked) return;- setSystemAudioEnabled(!systemAudioEnabled);- }, [controlsLocked, setSystemAudioEnabled, systemAudioEnabled]);-- const toggleCursorMode = useCallback(() => {- if (controlsLocked) return;- setCursorCaptureMode(cursorCaptureMode === "editable-overlay" ? "system" : "editable-overlay");- }, [controlsLocked, cursorCaptureMode, setCursorCaptureMode]);-- const toggleMicrophone = useCallback(() => {- if (controlsLocked) return;- setMicrophoneEnabled(!microphoneEnabled);- }, [controlsLocked, microphoneEnabled, setMicrophoneEnabled]);-/**- * Write a camera choice back to the main-process recording prefs.+ * Write a recording preference back to the main-process session store.*- * The HUD used to be a reader of that SSOT and never a writer, while being- * destroyed and rebuilt for every recording — so a camera picked here lived- * exactly as long as one take, and the editor's Rec stage kept showing the- * previous device. Best-effort on purpose: failing to persist a preference- * must not stop a recording.+ * The HUD is destroyed and rebuilt for every recording, so toggles and device+ * choices need to share the same best-effort persistence path. Failing to+ * persist a preference must not stop a recording.*/const persistRecordingPrefs = useCallback((patch: {camEnabled?: boolean;camDeviceId?: string;+ camDeviceName?: string;+ micEnabled?: boolean;micDeviceId?: string;micDeviceName?: string;+ systemAudioEnabled?: boolean;+ cursorCaptureMode?: "editable-overlay" | "system";}) => {void window.electronAPI?.setRecordingPrefs?.(patch).catch((error) => {console.warn("Failed to persist the device preference:", error);@@ -791,6 +860,27 @@ export function LaunchWindow() {[],);+ const toggleSystemAudio = useCallback(() => {+ if (controlsLocked) return;+ const next = !systemAudioEnabled;+ setSystemAudioEnabled(next);+ persistRecordingPrefs({ systemAudioEnabled: next });+ }, [controlsLocked, persistRecordingPrefs, setSystemAudioEnabled, systemAudioEnabled]);++ const toggleCursorMode = useCallback(() => {+ if (controlsLocked) return;+ const next = cursorCaptureMode === "editable-overlay" ? "system" : "editable-overlay";+ setCursorCaptureMode(next);+ persistRecordingPrefs({ cursorCaptureMode: next });+ }, [controlsLocked, cursorCaptureMode, persistRecordingPrefs, setCursorCaptureMode]);++ const toggleMicrophone = useCallback(() => {+ if (controlsLocked) return;+ const next = !microphoneEnabled;+ setMicrophoneEnabled(next);+ persistRecordingPrefs({ micEnabled: next });+ }, [controlsLocked, microphoneEnabled, persistRecordingPrefs, setMicrophoneEnabled]);+const toggleWebcam = useCallback(() => {if (controlsLocked) return;const next = !webcamEnabled;@@ -817,7 +907,7 @@ export function LaunchWindow() {setSelectedCameraId(device.deviceId);setWebcamDeviceId(device.deviceId);setWebcamDeviceName(device.label);- persistRecordingPrefs({ camDeviceId: device.deviceId });+ persistRecordingPrefs({ camDeviceId: device.deviceId, camDeviceName: device.label });},[persistRecordingPrefs, setSelectedCameraId, setWebcamDeviceId, setWebcamDeviceName],);diff --git a/src/contexts/EditorDialogsContext.tsx b/src/contexts/EditorDialogsContext.tsxindex e38c8844f..340534f21 100644--- a/src/contexts/EditorDialogsContext.tsx+++ b/src/contexts/EditorDialogsContext.tsx@@ -22,7 +22,7 @@ import { createContext, type ReactNode, useContext, useMemo, useState } from "re// global shortcuts, which was only ever half an answer — this context knows about its own// dialogs and about no others (#434). `isModalOpen` (lib/ai-edition/modalGuard) is where that// question is asked now.-export type EditorDialogSection = "providers";+export type EditorDialogSection = "providers" | "settings";interface EditorDialogsActions {openDialog: (section: EditorDialogSection) => void;diff --git a/src/hooks/useCameraDevices.test.ts b/src/hooks/useCameraDevices.test.tsindex a622ba78d..91b1b802b 100644--- a/src/hooks/useCameraDevices.test.ts+++ b/src/hooks/useCameraDevices.test.ts@@ -97,6 +97,19 @@ describe("useCameraDevices", () => {// settled on the first device. Losing the user's camera at that point is what// made a HUD rebuilt for a new recording revert to a virtual camera that emits// nothing, while the native helper was told to capture it by name.+ it("clears the live selection when the remembered camera is reset", async () => {+ const { result, rerender } = renderHook<+ ReturnType<typeof useCameraDevices>,+ { preferred?: string }+ >(({ preferred }) => useCameraDevices(true, preferred), {+ initialProps: { preferred: "cam2" },+ });+ await waitFor(() => expect(result.current.selectedDeviceId).toBe("cam2"));++ rerender({});+ await waitFor(() => expect(result.current.selectedDeviceId).toBe(""));+ });+it("should adopt the restored device when it arrives after enumeration", async () => {const { result, rerender } = renderHook(({ preferred }: { preferred?: string }) => useCameraDevices(true, preferred),@@ -122,6 +135,20 @@ describe("useCameraDevices", () => {});});+ it("resolves a stale id by a unique saved camera label", async () => {+ const { result } = renderHook(() => useCameraDevices(true, "stale-id", "Camera 2"));+ await waitFor(() => expect(result.current.selectedDeviceId).toBe("cam2"));+ });++ it("does not guess when a saved camera label is ambiguous", async () => {+ mockEnumerateDevices.mockResolvedValueOnce([+ { kind: "videoinput", deviceId: "cam1", label: "Same camera", groupId: "g1" },+ { kind: "videoinput", deviceId: "cam2", label: "Same camera", groupId: "g2" },+ ]);+ const { result } = renderHook(() => useCameraDevices(true, "stale-id", "Same camera"));+ await waitFor(() => expect(result.current.selectedDeviceId).toBe("cam1"));+ });+/*** The HUD feeds this hook's own output back in: `LaunchWindow` writes* `selectedDeviceId` into the recorder's `webcamDeviceId`, and hands that same@@ -163,6 +190,31 @@ describe("useCameraDevices", () => {expect(result.current.selectedDeviceId).toBe("cam2");});+ it("clears readiness while a later devicechange is still loading", async () => {+ const { result } = renderHook(() => useCameraDevices(true));+ await waitFor(() => expect(result.current.isReady).toBe(true));++ let resolveNewest: ((devices: typeof mockDevices) => void) | undefined;+ mockEnumerateDevices.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveNewest = resolve;+ }),+ );+ const devicechangeHandler = (+ navigator.mediaDevices.addEventListener as ReturnType<typeof vi.fn>+ ).mock.calls[0]?.[1] as (() => void) | undefined;+ if (!devicechangeHandler) throw new Error("devicechange listener was not registered");++ act(() => {+ void devicechangeHandler();+ });+ expect(result.current.isReady).toBe(false);++ await act(async () => resolveNewest?.(mockDevices));+ await waitFor(() => expect(result.current.isReady).toBe(true));+ });+it("should fall back to first available device when selected device is unplugged", async () => {const { result } = renderHook(() => useCameraDevices(true));diff --git a/src/hooks/useCameraDevices.ts b/src/hooks/useCameraDevices.tsindex 0466cc40c..72ef7eee1 100644--- a/src/hooks/useCameraDevices.ts+++ b/src/hooks/useCameraDevices.ts@@ -15,11 +15,16 @@ export interface CameraDevice {* only the *name* reached the native helper, so the preview showed the chosen* camera while the recording captured the other one.*/-export function useCameraDevices(enabled: boolean = false, preferredDeviceId?: string) {+export function useCameraDevices(+ enabled: boolean = false,+ preferredDeviceId?: string,+ preferredDeviceName?: string,+) {const [devices, setDevices] = useState<CameraDevice[]>([]);const [selectedDeviceId, setSelectedDeviceId] = useState<string>("");const [isLoading, setIsLoading] = useState(false);const [error, setError] = useState<string | null>(null);+ const [isReady, setIsReady] = useState(!enabled);// `loadDevices` runs long after the render that scheduled it — on a// `devicechange` that may arrive at any moment — so it reads these two// through refs rather than closing over them.@@ -31,16 +36,24 @@ export function useCameraDevices(enabled: boolean = false, preferredDeviceId?: s// the first enumeration reads them.const selectedDeviceIdRef = useRef(selectedDeviceId);const preferredDeviceIdRef = useRef(preferredDeviceId);+ const preferredDeviceNameRef = useRef(preferredDeviceName);+ const hadPreferenceRef = useRef(false);useEffect(() => {selectedDeviceIdRef.current = selectedDeviceId;preferredDeviceIdRef.current = preferredDeviceId;- }, [selectedDeviceId, preferredDeviceId]);+ preferredDeviceNameRef.current = preferredDeviceName;+ }, [selectedDeviceId, preferredDeviceId, preferredDeviceName]);useEffect(() => {if (!enabled) return;+ setIsReady(false);let mounted = true;+ let latestLoad = 0;const loadDevices = async () => {+ const loadToken = ++latestLoad;+ const isCurrent = () => mounted && loadToken === latestLoad;+ setIsReady(false);try {setIsLoading(true);setError(null);@@ -56,24 +69,28 @@ export function useCameraDevices(enabled: boolean = false, preferredDeviceId?: sgroupId: device.groupId,}));- if (mounted) {- setDevices(videoInputs);- const currentId = selectedDeviceIdRef.current;- const stillAvailable = videoInputs.some((d) => d.deviceId === currentId);- if (!currentId || !stillAvailable) {- const preferredId = preferredDeviceIdRef.current;- const preferred = preferredId- ? videoInputs.find((d) => d.deviceId === preferredId)- : undefined;- setSelectedDeviceId(preferred?.deviceId ?? videoInputs[0]?.deviceId ?? "");- }- setIsLoading(false);+ if (!isCurrent()) return;+ setDevices(videoInputs);+ const currentId = selectedDeviceIdRef.current;+ const stillAvailable = videoInputs.some((d) => d.deviceId === currentId);+ if (!currentId || !stillAvailable) {+ const preferredId = preferredDeviceIdRef.current;+ const preferredName = preferredDeviceNameRef.current;+ const labelMatches = preferredName+ ? videoInputs.filter((d) => d.label === preferredName)+ : [];+ const preferred =+ (preferredId ? videoInputs.find((d) => d.deviceId === preferredId) : undefined) ??+ (labelMatches.length === 1 ? labelMatches[0] : undefined);+ setSelectedDeviceId(preferred?.deviceId ?? videoInputs[0]?.deviceId ?? "");}+ setIsLoading(false);+ setIsReady(true);} catch (err) {- if (mounted) {- setError(err instanceof Error ? err.message : "Failed to load cameras");- setIsLoading(false);- }+ if (!isCurrent()) return;+ setError(err instanceof Error ? err.message : "Failed to load cameras");+ setIsLoading(false);+ setIsReady(true);}};@@ -91,11 +108,26 @@ export function useCameraDevices(enabled: boolean = false, preferredDeviceId?: s// first device. Adopting it here is what makes the two async sources converge// on the same camera instead of racing.useEffect(() => {- if (!enabled || !preferredDeviceId) return;- if (preferredDeviceId === selectedDeviceId) return;- if (!devices.some((d) => d.deviceId === preferredDeviceId)) return;- setSelectedDeviceId(preferredDeviceId);- }, [enabled, preferredDeviceId, devices, selectedDeviceId]);+ if (!enabled) return;+ const hasPreference = Boolean(preferredDeviceId || preferredDeviceName);+ if (!hasPreference) {+ if (hadPreferenceRef.current) {+ hadPreferenceRef.current = false;+ setSelectedDeviceId("");+ }+ return;+ }+ hadPreferenceRef.current = true;+ const byId = preferredDeviceId+ ? devices.find((device) => device.deviceId === preferredDeviceId)+ : undefined;+ const byLabel = preferredDeviceName+ ? devices.filter((device) => device.label === preferredDeviceName)+ : [];+ const preferred = byId ?? (byLabel.length === 1 ? byLabel[0] : undefined);+ if (!preferred || preferred.deviceId === selectedDeviceId) return;+ setSelectedDeviceId(preferred.deviceId);+ }, [enabled, preferredDeviceId, preferredDeviceName, devices, selectedDeviceId]);// The selected entry itself, so callers can react to "which camera is chosen"// without depending on the identity of `devices`. `loadDevices` rebuilds that@@ -105,6 +137,24 @@ export function useCameraDevices(enabled: boolean = false, preferredDeviceId?: s// settling. Depending on this object's fields instead makes the write-back// fire only when the chosen camera really changed.const selectedDevice = devices.find((d) => d.deviceId === selectedDeviceId);+ const preferredById = preferredDeviceId+ ? devices.find((device) => device.deviceId === preferredDeviceId)+ : undefined;+ const preferredByLabel = preferredDeviceName+ ? devices.filter((device) => device.label === preferredDeviceName)+ : [];+ const resolvedPreference =+ preferredById ?? (preferredByLabel.length === 1 ? preferredByLabel[0] : undefined);+ const selectionReady =+ isReady && (!resolvedPreference || resolvedPreference.deviceId === selectedDeviceId);- return { devices, selectedDevice, selectedDeviceId, setSelectedDeviceId, isLoading, error };+ return {+ devices,+ selectedDevice,+ selectedDeviceId,+ setSelectedDeviceId,+ isLoading,+ isReady: selectionReady,+ error,+ };}diff --git a/src/hooks/useMicrophoneDevices.test.ts b/src/hooks/useMicrophoneDevices.test.tsindex 17c8eefb9..e1f6ff258 100644--- a/src/hooks/useMicrophoneDevices.test.ts+++ b/src/hooks/useMicrophoneDevices.test.ts@@ -1,7 +1,7 @@// @vitest-environment jsdom-import { renderHook, waitFor } from "@testing-library/react";+import { act, renderHook, waitFor } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";-import { useMicrophoneDevices } from "./useMicrophoneDevices";+import { isPlaceholderMicrophoneLabel, useMicrophoneDevices } from "./useMicrophoneDevices";const DEVICES = [{ kind: "audioinput", deviceId: "mic-a", label: "Realtek Array Microphone", groupId: "g1" },@@ -10,26 +10,49 @@ const DEVICES = [];const enumerateDevices = vi.fn(async () => DEVICES);+const getUserMedia = vi.fn(async () => ({ getTracks: () => [{ stop: vi.fn() }] }));+const addEventListener = vi.fn();+const removeEventListener = vi.fn();Object.defineProperty(global.navigator, "mediaDevices", {value: {enumerateDevices,- getUserMedia: vi.fn(async () => ({ getTracks: () => [{ stop: vi.fn() }] })),- addEventListener: vi.fn(),- removeEventListener: vi.fn(),+ getUserMedia,+ addEventListener,+ removeEventListener,},configurable: true,});describe("useMicrophoneDevices", () => {+ it("recognizes the synthetic label used when permission hid the real name", () => {+ expect(isPlaceholderMicrophoneLabel("Microphone mic-hidd", "mic-hidden")).toBe(true);+ expect(isPlaceholderMicrophoneLabel("Realtek Array Microphone", "mic-a")).toBe(false);+ });+beforeEach(() => {vi.clearAllMocks();enumerateDevices.mockResolvedValue(DEVICES);+ getUserMedia.mockResolvedValue({ getTracks: () => [{ stop: vi.fn() }] });});it("falls back to the first input when nothing is remembered", async () => {const { result } = renderHook(() => useMicrophoneDevices(true));await waitFor(() => expect(result.current.selectedDeviceId).toBe("mic-a"));+ expect(getUserMedia).not.toHaveBeenCalled();+ });++ it("clears the live selection when the remembered microphone is reset", async () => {+ const { result, rerender } = renderHook<+ ReturnType<typeof useMicrophoneDevices>,+ { preferredId?: string; preferredName?: string }+ >(({ preferredId, preferredName }) => useMicrophoneDevices(true, preferredId, preferredName), {+ initialProps: { preferredId: "mic-b", preferredName: "Microphone (Logitech PRO X)" },+ });+ await waitFor(() => expect(result.current.selectedDeviceId).toBe("mic-b"));++ rerender({});+ await waitFor(() => expect(result.current.selectedDeviceId).toBe("default"));});it("prefers the remembered microphone over the first input", async () => {@@ -56,4 +79,141 @@ describe("useMicrophoneDevices", () => {);await waitFor(() => expect(result.current.selectedDeviceId).toBe("mic-a"));});++ it("does not guess when a saved microphone label matches more than one device", async () => {+ enumerateDevices.mockResolvedValueOnce([+ { kind: "audioinput", deviceId: "mic-a", label: "USB microphone", groupId: "g1" },+ { kind: "audioinput", deviceId: "mic-b", label: "USB microphone", groupId: "g2" },+ ]);+ const { result } = renderHook(() => useMicrophoneDevices(true, "stale-id", "USB microphone"));+ await waitFor(() => expect(result.current.selectedDeviceId).toBe("mic-a"));+ });++ it("probes only when labels are hidden, re-enumerates, and always stops the probe", async () => {+ const stop = vi.fn();+ enumerateDevices+ .mockResolvedValueOnce([{ kind: "audioinput", deviceId: "mic-a", label: "", groupId: "g1" }])+ .mockResolvedValueOnce(DEVICES);+ getUserMedia.mockResolvedValueOnce({ getTracks: () => [{ stop }] });++ const { result } = renderHook(() => useMicrophoneDevices(true));+ await waitFor(() => expect(result.current.devices[0]?.label).toBe("Realtek Array Microphone"));+ expect(getUserMedia).toHaveBeenCalledTimes(1);+ expect(enumerateDevices).toHaveBeenCalledTimes(2);+ expect(stop).toHaveBeenCalledTimes(1);+ });++ it("keeps the first live list when the label probe is rejected", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);+ enumerateDevices.mockResolvedValueOnce([+ { kind: "audioinput", deviceId: "mic-hidden", label: "", groupId: "g1" },+ ]);+ getUserMedia.mockRejectedValueOnce(new Error("probe busy"));++ const { result } = renderHook(() => useMicrophoneDevices(true));+ await waitFor(() => expect(result.current.isReady).toBe(true));+ expect(result.current.devices).toEqual([+ { deviceId: "mic-hidden", label: "Microphone mic-hidd", groupId: "g1" },+ ]);+ expect(result.current.error).toBeNull();+ warn.mockRestore();+ });++ it("stops the probe and keeps the first list when the label refresh fails", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);+ const stop = vi.fn();+ enumerateDevices+ .mockResolvedValueOnce([+ { kind: "audioinput", deviceId: "mic-hidden", label: "", groupId: "g1" },+ ])+ .mockRejectedValueOnce(new Error("refresh failed"));+ getUserMedia.mockResolvedValueOnce({ getTracks: () => [{ stop }] });++ const { result } = renderHook(() => useMicrophoneDevices(true));+ await waitFor(() => expect(result.current.isReady).toBe(true));+ expect(result.current.devices).toHaveLength(1);+ expect(stop).toHaveBeenCalledTimes(1);+ warn.mockRestore();+ });++ it("binds readiness to the current enable generation and retries after off then on", async () => {+ const error = vi.spyOn(console, "error").mockImplementation(() => undefined);+ let resolveRetry: ((devices: typeof DEVICES) => void) | undefined;+ enumerateDevices.mockRejectedValueOnce(new Error("transient enumeration failure"));+ enumerateDevices.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveRetry = resolve;+ }),+ );+ const { result, rerender } = renderHook(+ ({ enabled }: { enabled: boolean }) => useMicrophoneDevices(enabled, "mic-b"),+ { initialProps: { enabled: true } },+ );+ await waitFor(() => expect(result.current.error).toBe("transient enumeration failure"));+ expect(result.current.devices).toEqual([]);++ rerender({ enabled: false });+ expect(result.current.isReady).toBe(true);+ await act(async () => rerender({ enabled: true }));+ expect(result.current.isReady).toBe(false);+ await act(async () => resolveRetry?.(DEVICES));+ await waitFor(() => expect(result.current.selectedDeviceId).toBe("mic-b"));+ expect(result.current.isReady).toBe(true);+ expect(enumerateDevices).toHaveBeenCalledTimes(2);+ error.mockRestore();+ });++ it("keeps an older devicechange result stale until the newest load completes", async () => {+ const { result } = renderHook(() => useMicrophoneDevices(true));+ await waitFor(() => expect(result.current.isReady).toBe(true));+ expect(result.current.devices[0]?.deviceId).toBe("mic-a");++ let resolveOlder: ((devices: typeof DEVICES) => void) | undefined;+ let resolveNewest: ((devices: typeof DEVICES) => void) | undefined;+ enumerateDevices+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveOlder = resolve;+ }),+ )+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveNewest = resolve;+ }),+ );+ const onDeviceChange = addEventListener.mock.calls.find(+ ([name]) => name === "devicechange",+ )?.[1] as (() => void) | undefined;+ if (!onDeviceChange) throw new Error("devicechange listener was not registered");++ act(() => {+ void onDeviceChange();+ });+ act(() => {+ void onDeviceChange();+ });+ await waitFor(() => expect(enumerateDevices).toHaveBeenCalledTimes(3));+ expect(result.current.isReady).toBe(false);++ await act(async () =>+ resolveOlder?.([+ { kind: "audioinput", deviceId: "mic-old", label: "Older", groupId: "g-old" },+ ]),+ );+ expect(result.current.isReady).toBe(false);+ expect(result.current.devices[0]?.deviceId).toBe("mic-a");++ await act(async () =>+ resolveNewest?.([+ { kind: "audioinput", deviceId: "mic-new", label: "Newest", groupId: "g-new" },+ ]),+ );+ await waitFor(() => expect(result.current.isReady).toBe(true));+ expect(result.current.devices).toEqual([+ { deviceId: "mic-new", label: "Newest", groupId: "g-new" },+ ]);+ });});diff --git a/src/hooks/useMicrophoneDevices.ts b/src/hooks/useMicrophoneDevices.tsindex 55f059351..a7fe24de1 100644--- a/src/hooks/useMicrophoneDevices.ts+++ b/src/hooks/useMicrophoneDevices.ts@@ -6,17 +6,45 @@ export interface MicrophoneDevice {groupId: string;}+export function isPlaceholderMicrophoneLabel(label: string, deviceId: string): boolean {+ return label === `Microphone ${deviceId.slice(0, 8)}`;+}++function microphoneDevices(devices: readonly MediaDeviceInfo[]): MicrophoneDevice[] {+ return devices+ .filter((device) => device.kind === "audioinput")+ .map((device) => ({+ deviceId: device.deviceId,+ label: device.label || `Microphone ${device.deviceId.slice(0, 8)}`,+ groupId: device.groupId,+ }));+}++function resolvePreferredDevice(+ devices: readonly MicrophoneDevice[],+ preferredDeviceId?: string,+ preferredDeviceName?: string,+): MicrophoneDevice | undefined {+ const byId = preferredDeviceId+ ? devices.find((device) => device.deviceId === preferredDeviceId)+ : undefined;+ if (byId) return byId;+ const byLabel = preferredDeviceName+ ? devices.filter((device) => device.label === preferredDeviceName)+ : [];+ return byLabel.length === 1 ? byLabel[0] : undefined;+}+/**- * @param preferredDeviceId The microphone the session already settled on —- * normally the one restored from the recording prefs. It outranks "first in the- * list", which is the OS enumeration order and has nothing to do with what the- * user chose. The HUD window is destroyed and rebuilt for every recording, so- * without this its pick reverted on each take.- * @param preferredDeviceName The same choice by label, tried when the id finds- * nothing. Chromium's device ids are per-origin salted, so the id a previous- * window persisted can name nothing in this one while the microphone is sitting- * right there in the list — and falling through to the first input would then- * discard a choice that was perfectly resolvable.+ * Enumerates live microphone inputs and resolves a stored preference by exact id,+ * then unique label, then the first live input.+ *+ * Enumeration happens before any permission probe. Chromium exposes labels after+ * permission has already been granted, which is the common restart path and needs+ * no temporary stream. If labels are still hidden, a short probe unlocks them and+ * the list is read once more. The first enumeration remains usable when that probe+ * or the second enumeration fails, and every acquired probe stream is stopped in+ * `finally`.*/export function useMicrophoneDevices(enabled: boolean = true,@@ -27,16 +55,14 @@ export function useMicrophoneDevices(const [selectedDeviceId, setSelectedDeviceId] = useState<string>("default");const [isLoading, setIsLoading] = useState(false);const [error, setError] = useState<string | null>(null);- // Read through a ref rather than a dependency: `selectedDeviceId` is written by- // this very effect, so depending on it re-ran the whole load — a second- // getUserMedia() permission stream acquired and torn down on every open.+ // The enabled value identifies the load generation. When false→true renders,+ // the prior disabled "ready" state cannot briefly start a competing meter.+ const [readyGeneration, setReadyGeneration] = useState<boolean | null>(enabled ? null : false);+const selectedDeviceIdRef = useRef(selectedDeviceId);const preferredDeviceIdRef = useRef(preferredDeviceId);const preferredDeviceNameRef = useRef(preferredDeviceName);- // Synchronised in an effect rather than during render: React may discard a- // render without committing it, and a ref written there keeps the value- // anyway, which would resolve the selection against a device the committed- // tree never agreed on.+ const hadPreferenceRef = useRef(false);useEffect(() => {selectedDeviceIdRef.current = selectedDeviceId;preferredDeviceIdRef.current = preferredDeviceId;@@ -45,79 +71,112 @@ export function useMicrophoneDevices(useEffect(() => {if (!enabled) {+ setIsLoading(false);+ setReadyGeneration(false);return;}let mounted = true;-+ let latestLoad = 0;const loadDevices = async () => {+ if (!mounted) return;+ const loadToken = ++latestLoad;+ const isCurrent = () => mounted && loadToken === latestLoad;+ setIsLoading(true);+ setReadyGeneration(null);+ setError(null);+ let probeStream: MediaStream | null = null;try {- setIsLoading(true);- setError(null);-- // Request permission first to get actual device labels- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });-- const allDevices = await navigator.mediaDevices.enumerateDevices();- const audioInputs = allDevices- .filter((device) => device.kind === "audioinput")- .map((device) => ({- deviceId: device.deviceId,- label: device.label || `Microphone ${device.deviceId.slice(0, 8)}`,- groupId: device.groupId,- }));-- // Stop the permission stream- stream.getTracks().forEach((track) => track.stop());-- if (mounted) {- setDevices(audioInputs);- const currentId = selectedDeviceIdRef.current;- const stillAvailable = audioInputs.some((d) => d.deviceId === currentId);- if ((currentId === "default" || !stillAvailable) && audioInputs.length > 0) {- const preferredId = preferredDeviceIdRef.current;- const preferredName = preferredDeviceNameRef.current;- // By id, then by label, then whatever is first. Always an entry- // from THIS list, so the id and the label the caller ends up- // sending to the native helper describe the same device — the- // pairing that #387 and #404 were both about.- const preferred =- (preferredId ? audioInputs.find((d) => d.deviceId === preferredId) : undefined) ??- (preferredName ? audioInputs.find((d) => d.label === preferredName) : undefined);- setSelectedDeviceId(preferred?.deviceId ?? audioInputs[0].deviceId);+ const firstEnumeration = await navigator.mediaDevices.enumerateDevices();+ if (!isCurrent()) return;+ let inputs = microphoneDevices(firstEnumeration);+ const labelsHidden = firstEnumeration.some(+ (device) => device.kind === "audioinput" && !device.label,+ );+ if (labelsHidden) {+ try {+ probeStream = await navigator.mediaDevices.getUserMedia({ audio: true });+ if (!isCurrent()) return;+ try {+ inputs = microphoneDevices(await navigator.mediaDevices.enumerateDevices());+ } catch (secondEnumerationError) {+ if (isCurrent())+ console.warn(+ "Could not refresh microphone labels after permission probe:",+ secondEnumerationError,+ );+ }+ } catch (probeError) {+ if (isCurrent()) console.warn("Could not unlock microphone labels:", probeError);}- setIsLoading(false);}- } catch (err) {- if (mounted) {- const errorMessage =- err instanceof Error ? err.message : "Failed to enumerate audio devices";- setError(errorMessage);++ if (!isCurrent()) return;+ setDevices(inputs);+ const currentId = selectedDeviceIdRef.current;+ const stillAvailable = inputs.some((device) => device.deviceId === currentId);+ if (currentId === "default" || !stillAvailable) {+ const preferred = resolvePreferredDevice(+ inputs,+ preferredDeviceIdRef.current,+ preferredDeviceNameRef.current,+ );+ setSelectedDeviceId(preferred?.deviceId ?? inputs[0]?.deviceId ?? "default");+ }+ } catch (cause) {+ if (!isCurrent()) return;+ setDevices([]);+ setSelectedDeviceId("default");+ setError(cause instanceof Error ? cause.message : "Failed to enumerate audio devices");+ console.error("Error loading microphone devices:", cause);+ } finally {+ probeStream?.getTracks().forEach((track) => track.stop());+ if (isCurrent()) {setIsLoading(false);- console.error("Error loading microphone devices:", err);+ setReadyGeneration(true);}}};- loadDevices();-- const handleDeviceChange = () => {- loadDevices();- };-- navigator.mediaDevices.addEventListener("devicechange", handleDeviceChange);-+ void loadDevices();+ navigator.mediaDevices.addEventListener("devicechange", loadDevices);return () => {mounted = false;- navigator.mediaDevices.removeEventListener("devicechange", handleDeviceChange);+ navigator.mediaDevices.removeEventListener("devicechange", loadDevices);};}, [enabled]);+ useEffect(() => {+ if (!enabled) return;+ const hasPreference = Boolean(preferredDeviceId || preferredDeviceName);+ if (!hasPreference) {+ if (hadPreferenceRef.current) {+ hadPreferenceRef.current = false;+ setSelectedDeviceId("default");+ }+ return;+ }+ hadPreferenceRef.current = true;+ const preferred = resolvePreferredDevice(devices, preferredDeviceId, preferredDeviceName);+ if (!preferred || preferred.deviceId === selectedDeviceId) return;+ setSelectedDeviceId(preferred.deviceId);+ }, [enabled, preferredDeviceId, preferredDeviceName, devices, selectedDeviceId]);++ const resolvedPreference = resolvePreferredDevice(+ devices,+ preferredDeviceId,+ preferredDeviceName,+ );+ const generationReady = enabled ? readyGeneration === true : readyGeneration === false;+ const selectionReady =+ generationReady && (!resolvedPreference || resolvedPreference.deviceId === selectedDeviceId);+return {devices,selectedDeviceId,setSelectedDeviceId,isLoading,+ isReady: selectionReady,error,};}diff --git a/src/hooks/useScreenRecorder.prefsRace.test.tsx b/src/hooks/useScreenRecorder.prefsRace.test.tsxnew file mode 100644index 000000000..d12f56f72--- /dev/null+++ b/src/hooks/useScreenRecorder.prefsRace.test.tsx@@ -0,0 +1,68 @@+// @vitest-environment jsdom+import { act, renderHook } from "@testing-library/react";+import { afterEach, 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 { useScreenRecorder } from "./useScreenRecorder";++type ElectronAPI = Window["electronAPI"];+type RecordingPrefs = Awaited<ReturnType<ElectronAPI["getRecordingPrefs"]>>;++const SOURCE = { id: "screen:0:0", name: "Screen 1", display_id: "1", thumbnail: "" };++function prefs(micEnabled: boolean): RecordingPrefs {+ return {+ micEnabled,+ micDeviceId: null,+ micDeviceName: null,+ camEnabled: false,+ camDeviceId: null,+ camDeviceName: null,+ systemAudioEnabled: false,+ cursorCaptureMode: "editable-overlay",+ };+}++describe("useScreenRecorder prefs snapshot/event race", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("does not let the initial read overwrite a newer live snapshot", async () => {+ let resolveInitial!: (value: RecordingPrefs) => void;+ const initial = new Promise<RecordingPrefs>((resolve) => {+ resolveInitial = resolve;+ });+ let onChange: ((next: RecordingPrefs) => void) | undefined;+ window.electronAPI = {+ getRecordingPrefs: vi.fn(() => initial),+ onRecordingPrefsChanged: vi.fn((callback: (next: RecordingPrefs) => void) => {+ onChange = callback;+ return () => {+ onChange = undefined;+ };+ }),+ getPlatform: vi.fn(() => "win32"),+ getSelectedSource: vi.fn(async () => SOURCE),+ } as unknown as ElectronAPI;++ const view = renderHook(() => useScreenRecorder());+ expect(onChange).toBeTypeOf("function");+ act(() => {+ onChange?.(prefs(true));+ });+ expect(view.result.current.microphoneEnabled).toBe(true);+ await act(async () => {+ resolveInitial(prefs(false));+ await initial;+ });+ expect(view.result.current.microphoneEnabled).toBe(true);+ });+});diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.tsindex 13c010883..00083bdfc 100644--- a/src/hooks/useScreenRecorder.ts+++ b/src/hooks/useScreenRecorder.ts@@ -108,6 +108,7 @@ type UseScreenRecorderReturn = {setCursorCaptureMode: (mode: CursorCaptureMode) => void;softwareEncoderFallbackNoticeVisible: boolean;dismissSoftwareEncoderFallbackNotice: (dontShowAgain?: boolean) => void;+ recordingPrefsLoaded: boolean;};type NativeWindowsRecordingHandle = {@@ -158,6 +159,17 @@ type NativeLinuxRecordingHandle = {* video in the camera's place. Rounding loses nothing: one frame at 60 fps is* 16.7 ms.*/+export function isRecoverableWebcamConstraintError(+ error: unknown,+ savedDeviceName?: string,+): boolean {+ if (!savedDeviceName) return false;+ return (+ error instanceof DOMException &&+ ["OverconstrainedError", "NotFoundError", "DevicesNotFoundError"].includes(error.name)+ );+}+export function webcamOffsetMsFrom(webcamRecorder: RecorderHandle | null,webcamStartedAtMs: number | null,@@ -244,38 +256,62 @@ export function useScreenRecorder(): UseScreenRecorderReturn {const [cursorCaptureMode, setCursorCaptureMode] = useState<CursorCaptureMode>("editable-overlay");const [softwareEncoderFallbackNoticeVisible, setSoftwareEncoderFallbackNoticeVisible] =useState(false);+ const [recordingPrefsLoaded, setRecordingPrefsLoaded] = useState(false);// Seed from the main-process recording-prefs SSOT on mount, so choices// made in the editor's Rec-mode stage (a different renderer window) carry// over instead of this hook silently reverting to its own hardcoded// defaults every time startNewRecording() switches to the HUD window.+ // Reset and later saves arrive on the same channel; applying every field+ // (including null devices) is what clears a live HUD after reset.useEffect(() => {let cancelled = false;+ let receivedNewerSnapshot = false;+ const applyPrefs = (prefs: {+ micEnabled: boolean;+ micDeviceId?: string | null;+ micDeviceName?: string | null;+ camEnabled: boolean;+ camDeviceId?: string | null;+ camDeviceName?: string | null;+ systemAudioEnabled: boolean;+ cursorCaptureMode: CursorCaptureMode;+ }) => {+ if (cancelled) return;+ setMicrophoneEnabled(prefs.micEnabled);+ setMicrophoneDeviceId(prefs.micDeviceId ?? undefined);+ setMicrophoneDeviceName(prefs.micDeviceName ?? undefined);+ setWebcamEnabledState(prefs.camEnabled);+ setWebcamDeviceId(prefs.camDeviceId ?? undefined);+ setWebcamDeviceName(prefs.camDeviceName ?? undefined);+ setSystemAudioEnabled(prefs.systemAudioEnabled);+ setCursorCaptureMode(prefs.cursorCaptureMode);+ setRecordingPrefsLoaded(true);+ };+ const stop = window.electronAPI?.onRecordingPrefsChanged?.((prefs) => {+ receivedNewerSnapshot = true;+ applyPrefs(prefs);+ });void window.electronAPI?.getRecordingPrefs?.().then((prefs) => {- if (cancelled || !prefs) return;- setMicrophoneEnabled(prefs.micEnabled);- if (prefs.micDeviceId) setMicrophoneDeviceId(prefs.micDeviceId);- // The name matters as much as the id: the native Windows helper picks- // the microphone by NAME, and falls back to the Windows default- // endpoint when it is empty. Seeding only the id left an auto-started- // recording racing this window's own device enumeration for it, and- // losing (getopenscreen/openscreen#404).- if (prefs.micDeviceName) setMicrophoneDeviceName(prefs.micDeviceName);- setWebcamEnabledState(prefs.camEnabled);- if (prefs.camDeviceId) setWebcamDeviceId(prefs.camDeviceId);- setSystemAudioEnabled(prefs.systemAudioEnabled);- setCursorCaptureMode(prefs.cursorCaptureMode);+ if (cancelled || receivedNewerSnapshot) return;+ if (!prefs) {+ setRecordingPrefsLoaded(true);+ return;+ }+ applyPrefs(prefs);}).catch((err) => {// Bare ipcRenderer.invoke — rejects if the main handler throws. Falling// back to this hook's own defaults is acceptable; an unhandled rejection// on every HUD mount is not.console.warn("Failed to seed the recording prefs:", err);+ if (!cancelled && !receivedNewerSnapshot) setRecordingPrefsLoaded(true);});return () => {cancelled = true;+ stop?.();};}, []);@@ -460,6 +496,10 @@ export function useScreenRecorder(): UseScreenRecorderReturn {webcamStream.current = stream;webcamReady.current = true;} catch (cameraError) {+ if (isRecoverableWebcamConstraintError(cameraError, webcamDeviceName)) {+ console.warn("Waiting to resolve the restored camera identity:", cameraError);+ return;+ }if (!cancelled) {console.warn("Failed to get webcam access:", cameraError);setWebcamEnabledState(false);@@ -490,7 +530,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {webcamStream.current = null;}};- }, [webcamEnabled, webcamDeviceId, t]);+ }, [webcamEnabled, webcamDeviceId, webcamDeviceName, t]);const finalizeRecording = useCallback((@@ -2352,5 +2392,6 @@ export function useScreenRecorder(): UseScreenRecorderReturn {setCursorCaptureMode,softwareEncoderFallbackNoticeVisible,dismissSoftwareEncoderFallbackNotice,+ recordingPrefsLoaded,};}diff --git a/src/hooks/webcamConstraint.test.ts b/src/hooks/webcamConstraint.test.tsnew file mode 100644index 000000000..75651d873--- /dev/null+++ b/src/hooks/webcamConstraint.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from "vitest";+import { isRecoverableWebcamConstraintError } from "./useScreenRecorder";++describe("isRecoverableWebcamConstraintError", () => {+ it("waits when a saved camera name can still resolve a stale id", () => {+ expect(+ isRecoverableWebcamConstraintError(+ new DOMException("exact id gone", "OverconstrainedError"),+ "Camera 2",+ ),+ ).toBe(true);+ expect(+ isRecoverableWebcamConstraintError(new DOMException("missing", "NotFoundError"), "Camera 2"),+ ).toBe(true);+ });++ it("does not wait when there is no saved name or the error is not a constraint", () => {+ expect(+ isRecoverableWebcamConstraintError(+ new DOMException("exact id gone", "OverconstrainedError"),+ undefined,+ ),+ ).toBe(false);+ expect(+ isRecoverableWebcamConstraintError(+ new DOMException("blocked", "NotAllowedError"),+ "Camera 2",+ ),+ ).toBe(false);+ });+});diff --git a/src/i18n/locales/ar/editor.json b/src/i18n/locales/ar/editor.jsonindex dcef44624..f6148a84c 100644--- a/src/i18n/locales/ar/editor.json+++ b/src/i18n/locales/ar/editor.json@@ -105,6 +105,7 @@},"rec": {"source": "المصدر",+ "selectSource": "اختيار المصدر","systemPicker": "سيسألك النظام عمّا تريد مشاركته","systemAudio": "صوت النظام","microphone": "الميكروفون",@@ -113,6 +114,8 @@"on": "تشغيل","off": "إيقاف","loading": "جارٍ التحميل...",+ "noMicrophoneFound": "لم يتم العثور على ميكروفون",+ "microphoneUnavailable": "الميكروفون غير متاح","noCameraFound": "لم يتم العثور على كاميرا","cameraAccessError": "تعذّر الوصول إلى هذه الكاميرا","startingCamera": "جارٍ تشغيل الكاميرا...",@@ -367,6 +370,30 @@"noImage": "لا توجد صورة","noArrowData": "لا توجد بيانات سهم"},+ "appSettings": {+ "title": "الإعدادات",+ "subtitle": "اختر إعداد التسجيل والمظهر المستخدم للمشاريع الجديدة.",+ "loading": "جارٍ تحميل الإعدادات…",+ "recordingTitle": "إعداد التسجيل",+ "systemAudio": "صوت النظام",+ "microphone": "الميكروفون",+ "microphoneDevice": "جهاز الميكروفون",+ "camera": "الكاميرا",+ "cameraDevice": "جهاز الكاميرا",+ "editableCursor": "مؤشر قابل للتحرير",+ "lastSource": "آخر مصدر: {{source}}",+ "noSource": "لم يتم تحديد مصدر",+ "saveRecording": "حفظ إعداد التسجيل",+ "resetRecording": "إعادة ضبط إعداد التسجيل",+ "appearanceTitle": "مظهر المشروع الجديد",+ "customAppearance": "تم حفظ إعدادات مظهر مخصصة.",+ "factoryAppearance": "إعدادات المظهر الافتراضية للمصنع نشطة.",+ "useCurrentAppearance": "استخدام المظهر الحالي كإعداد افتراضي",+ "resetAppearance": "إعادة ضبط إعدادات المظهر",+ "saved": "تم الحفظ",+ "saveFailed": "تعذر حفظ الإعدادات: {{error}}",+ "appearanceSummary": "{{aspect}}، حشوة {{padding}}٪، نصف قطر {{radius}}، المؤشر {{cursor}}، الكاميرا {{camera}}"+ },"providerSettings": {"title": "إعدادات الذكاء الاصطناعي","subtitle": "اختر مزوّدًا. تُحفظ بيانات الاعتماد في سلسلة مفاتيح النظام (safeStorage).",diff --git a/src/i18n/locales/en/editor.json b/src/i18n/locales/en/editor.jsonindex a75b70055..ad3d98b64 100644--- a/src/i18n/locales/en/editor.json+++ b/src/i18n/locales/en/editor.json@@ -105,6 +105,7 @@},"rec": {"source": "Source",+ "selectSource": "Select source","systemPicker": "Your system will ask what to share","systemAudio": "System audio","microphone": "Microphone",@@ -113,6 +114,8 @@"on": "On","off": "Off","loading": "Loading…",+ "noMicrophoneFound": "No microphone found",+ "microphoneUnavailable": "Microphone unavailable","noCameraFound": "No camera found","cameraAccessError": "Couldn't access this camera","startingCamera": "Starting camera…",@@ -367,6 +370,30 @@"noImage": "No image","noArrowData": "No arrow data"},+ "appSettings": {+ "title": "Settings",+ "subtitle": "Choose the recording setup and the appearance used by new projects.",+ "loading": "Loading settings…",+ "recordingTitle": "Recording setup",+ "systemAudio": "System audio",+ "microphone": "Microphone",+ "microphoneDevice": "Microphone device",+ "camera": "Camera",+ "cameraDevice": "Camera device",+ "editableCursor": "Editable cursor",+ "lastSource": "Last source: {{source}}",+ "noSource": "No source selected",+ "saveRecording": "Save recording setup",+ "resetRecording": "Reset recording setup",+ "appearanceTitle": "New-project appearance",+ "customAppearance": "Custom appearance defaults are saved.",+ "factoryAppearance": "Factory appearance defaults are active.",+ "useCurrentAppearance": "Use current appearance as defaults",+ "resetAppearance": "Reset appearance defaults",+ "saved": "Saved",+ "saveFailed": "Could not save settings: {{error}}",+ "appearanceSummary": "{{aspect}}, {{padding}}% padding, radius {{radius}}, cursor {{cursor}}, camera {{camera}}"+ },"providerSettings": {"title": "AI settings","subtitle": "Choose a provider. Credentials are stored in the OS keychain (safeStorage).",diff --git a/src/i18n/locales/es/editor.json b/src/i18n/locales/es/editor.jsonindex 9487e6b70..f104d05a4 100644--- a/src/i18n/locales/es/editor.json+++ b/src/i18n/locales/es/editor.json@@ -105,6 +105,7 @@},"rec": {"source": "Fuente",+ "selectSource": "Seleccionar fuente","systemPicker": "El sistema te preguntará qué compartir","systemAudio": "Audio del sistema","microphone": "Micrófono",@@ -113,6 +114,8 @@"on": "Activado","off": "Desactivado","loading": "Cargando…",+ "noMicrophoneFound": "No se encontró micrófono",+ "microphoneUnavailable": "Micrófono no disponible","noCameraFound": "No se encontró cámara","cameraAccessError": "No se pudo acceder a esta cámara","startingCamera": "Iniciando cámara…",@@ -367,6 +370,30 @@"noImage": "Sin imagen","noArrowData": "Sin datos de flecha"},+ "appSettings": {+ "title": "Ajustes",+ "subtitle": "Elige la configuración de grabación y la apariencia de los proyectos nuevos.",+ "loading": "Cargando ajustes…",+ "recordingTitle": "Configuración de grabación",+ "systemAudio": "Audio del sistema",+ "microphone": "Micrófono",+ "microphoneDevice": "Dispositivo de micrófono",+ "camera": "Cámara",+ "cameraDevice": "Dispositivo de cámara",+ "editableCursor": "Cursor editable",+ "lastSource": "Última fuente: {{source}}",+ "noSource": "Ninguna fuente seleccionada",+ "saveRecording": "Guardar configuración de grabación",+ "resetRecording": "Restablecer configuración de grabación",+ "appearanceTitle": "Apariencia de proyectos nuevos",+ "customAppearance": "Se guardaron valores de apariencia personalizados.",+ "factoryAppearance": "Están activos los valores de apariencia de fábrica.",+ "useCurrentAppearance": "Usar la apariencia actual como predeterminada",+ "resetAppearance": "Restablecer apariencia",+ "saved": "Guardado",+ "saveFailed": "No se pudieron guardar los ajustes: {{error}}",+ "appearanceSummary": "{{aspect}}, relleno {{padding}} %, radio {{radius}}, cursor {{cursor}}, cámara {{camera}}"+ },"providerSettings": {"title": "Ajustes de IA","subtitle": "Elige un proveedor. Las credenciales se guardan en el llavero del sistema (safeStorage).",diff --git a/src/i18n/locales/fr/editor.json b/src/i18n/locales/fr/editor.jsonindex cf0de68ee..8d408657a 100644--- a/src/i18n/locales/fr/editor.json+++ b/src/i18n/locales/fr/editor.json@@ -105,6 +105,7 @@},"rec": {"source": "Source",+ "selectSource": "Sélectionner une source","systemPicker": "Le système vous demandera quoi partager","systemAudio": "Audio système","microphone": "Microphone",@@ -113,6 +114,8 @@"on": "Activé","off": "Désactivé","loading": "Chargement…",+ "noMicrophoneFound": "Aucun microphone trouvé",+ "microphoneUnavailable": "Microphone indisponible","noCameraFound": "Aucune caméra trouvée","cameraAccessError": "Impossible d'accéder à cette caméra","startingCamera": "Démarrage de la caméra…",@@ -367,6 +370,30 @@"noImage": "Aucune image","noArrowData": "Aucune donnée de flèche"},+ "appSettings": {+ "title": "Paramètres",+ "subtitle": "Choisissez la configuration d’enregistrement et l’apparence des nouveaux projets.",+ "loading": "Chargement des paramètres…",+ "recordingTitle": "Configuration d’enregistrement",+ "systemAudio": "Audio système",+ "microphone": "Microphone",+ "microphoneDevice": "Périphérique microphone",+ "camera": "Caméra",+ "cameraDevice": "Périphérique caméra",+ "editableCursor": "Curseur modifiable",+ "lastSource": "Dernière source : {{source}}",+ "noSource": "Aucune source sélectionnée",+ "saveRecording": "Enregistrer la configuration",+ "resetRecording": "Réinitialiser la configuration",+ "appearanceTitle": "Apparence des nouveaux projets",+ "customAppearance": "Des valeurs d’apparence personnalisées sont enregistrées.",+ "factoryAppearance": "Les valeurs d’apparence d’usine sont actives.",+ "useCurrentAppearance": "Utiliser l’apparence actuelle par défaut",+ "resetAppearance": "Réinitialiser l’apparence",+ "saved": "Enregistré",+ "saveFailed": "Impossible d’enregistrer les paramètres : {{error}}",+ "appearanceSummary": "{{aspect}}, marge {{padding}} %, rayon {{radius}}, curseur {{cursor}}, caméra {{camera}}"+ },"providerSettings": {"title": "Paramètres IA","subtitle": "Choisissez un fournisseur. Les identifiants sont stockés dans le trousseau du système (safeStorage).",diff --git a/src/i18n/locales/it/editor.json b/src/i18n/locales/it/editor.jsonindex 9f3b35aa4..43f649b3a 100644--- a/src/i18n/locales/it/editor.json+++ b/src/i18n/locales/it/editor.json@@ -105,6 +105,7 @@},"rec": {"source": "Sorgente",+ "selectSource": "Seleziona sorgente","systemPicker": "Il sistema ti chiederà cosa condividere","systemAudio": "Audio di sistema","microphone": "Microfono",@@ -113,6 +114,8 @@"on": "Attivo","off": "Disattivo","loading": "Caricamento…",+ "noMicrophoneFound": "Nessun microfono trovato",+ "microphoneUnavailable": "Microfono non disponibile","noCameraFound": "Nessuna fotocamera trovata","cameraAccessError": "Impossibile accedere a questa fotocamera","startingCamera": "Avvio fotocamera…",@@ -367,6 +370,30 @@"noImage": "Nessuna immagine","noArrowData": "Nessun dato freccia"},+ "appSettings": {+ "title": "Impostazioni",+ "subtitle": "Scegli la configurazione di registrazione e l’aspetto dei nuovi progetti.",+ "loading": "Caricamento impostazioni…",+ "recordingTitle": "Configurazione registrazione",+ "systemAudio": "Audio di sistema",+ "microphone": "Microfono",+ "microphoneDevice": "Dispositivo microfono",+ "camera": "Fotocamera",+ "cameraDevice": "Dispositivo fotocamera",+ "editableCursor": "Cursore modificabile",+ "lastSource": "Ultima sorgente: {{source}}",+ "noSource": "Nessuna sorgente selezionata",+ "saveRecording": "Salva configurazione registrazione",+ "resetRecording": "Ripristina configurazione registrazione",+ "appearanceTitle": "Aspetto dei nuovi progetti",+ "customAppearance": "Sono salvate impostazioni aspetto personalizzate.",+ "factoryAppearance": "Sono attive le impostazioni aspetto di fabbrica.",+ "useCurrentAppearance": "Usa l’aspetto corrente come predefinito",+ "resetAppearance": "Ripristina aspetto",+ "saved": "Salvato",+ "saveFailed": "Impossibile salvare le impostazioni: {{error}}",+ "appearanceSummary": "{{aspect}}, spaziatura {{padding}}%, raggio {{radius}}, cursore {{cursor}}, fotocamera {{camera}}"+ },"providerSettings": {"title": "Impostazioni IA","subtitle": "Scegli un provider. Le credenziali sono salvate nel portachiavi del sistema (safeStorage).",diff --git a/src/i18n/locales/ja-JP/editor.json b/src/i18n/locales/ja-JP/editor.jsonindex ca82e702f..7365b191c 100644--- a/src/i18n/locales/ja-JP/editor.json+++ b/src/i18n/locales/ja-JP/editor.json@@ -105,6 +105,7 @@},"rec": {"source": "ソース",+ "selectSource": "ソースを選択","systemPicker": "共有する対象はシステムが確認します","systemAudio": "システム音声","microphone": "マイク",@@ -113,6 +114,8 @@"on": "オン","off": "オフ","loading": "読み込み中…",+ "noMicrophoneFound": "マイクが見つかりません",+ "microphoneUnavailable": "マイクを使用できません","noCameraFound": "カメラが見つかりません","cameraAccessError": "このカメラにアクセスできませんでした","startingCamera": "カメラを起動中…",@@ -367,6 +370,30 @@"noImage": "画像なし","noArrowData": "矢印データなし"},+ "appSettings": {+ "title": "設定",+ "subtitle": "録画設定と新規プロジェクトで使う外観を選択します。",+ "loading": "設定を読み込み中…",+ "recordingTitle": "録画設定",+ "systemAudio": "システム音声",+ "microphone": "マイク",+ "microphoneDevice": "マイクデバイス",+ "camera": "カメラ",+ "cameraDevice": "カメラデバイス",+ "editableCursor": "編集可能なカーソル",+ "lastSource": "最後のソース: {{source}}",+ "noSource": "ソース未選択",+ "saveRecording": "録画設定を保存",+ "resetRecording": "録画設定をリセット",+ "appearanceTitle": "新規プロジェクトの外観",+ "customAppearance": "カスタム外観の既定値が保存されています。",+ "factoryAppearance": "工場出荷時の外観が有効です。",+ "useCurrentAppearance": "現在の外観を既定値として使用",+ "resetAppearance": "外観をリセット",+ "saved": "保存しました",+ "saveFailed": "設定を保存できませんでした: {{error}}",+ "appearanceSummary": "{{aspect}}、余白 {{padding}}%、角丸 {{radius}}、カーソル {{cursor}}、カメラ {{camera}}"+ },"providerSettings": {"title": "AI 設定","subtitle": "プロバイダーを選択してください。認証情報は OS のキーチェーン(safeStorage)に保存されます。",diff --git a/src/i18n/locales/ko-KR/editor.json b/src/i18n/locales/ko-KR/editor.jsonindex d65edaa60..3e81b1a79 100644--- a/src/i18n/locales/ko-KR/editor.json+++ b/src/i18n/locales/ko-KR/editor.json@@ -105,6 +105,7 @@},"rec": {"source": "소스",+ "selectSource": "소스 선택","systemPicker": "공유할 대상을 시스템이 묻습니다","systemAudio": "시스템 오디오","microphone": "마이크",@@ -113,6 +114,8 @@"on": "켜짐","off": "꺼짐","loading": "로딩 중…",+ "noMicrophoneFound": "마이크를 찾을 수 없음",+ "microphoneUnavailable": "마이크를 사용할 수 없음","noCameraFound": "카메라를 찾을 수 없음","cameraAccessError": "이 카메라에 액세스할 수 없습니다","startingCamera": "카메라 시작 중…",@@ -367,6 +370,30 @@"noImage": "이미지 없음","noArrowData": "화살표 데이터 없음"},+ "appSettings": {+ "title": "설정",+ "subtitle": "녹화 설정과 새 프로젝트에 사용할 모양을 선택하세요.",+ "loading": "설정 불러오는 중…",+ "recordingTitle": "녹화 설정",+ "systemAudio": "시스템 오디오",+ "microphone": "마이크",+ "microphoneDevice": "마이크 장치",+ "camera": "카메라",+ "cameraDevice": "카메라 장치",+ "editableCursor": "편집 가능한 커서",+ "lastSource": "마지막 소스: {{source}}",+ "noSource": "선택한 소스 없음",+ "saveRecording": "녹화 설정 저장",+ "resetRecording": "녹화 설정 초기화",+ "appearanceTitle": "새 프로젝트 모양",+ "customAppearance": "사용자 지정 모양 기본값이 저장되었습니다.",+ "factoryAppearance": "기본 모양 설정이 적용 중입니다.",+ "useCurrentAppearance": "현재 모양을 기본값으로 사용",+ "resetAppearance": "모양 초기화",+ "saved": "저장됨",+ "saveFailed": "설정을 저장할 수 없습니다: {{error}}",+ "appearanceSummary": "{{aspect}}, 여백 {{padding}}%, 반경 {{radius}}, 커서 {{cursor}}, 카메라 {{camera}}"+ },"providerSettings": {"title": "AI 설정","subtitle": "공급자를 선택하세요. 자격 증명은 OS 키체인(safeStorage)에 저장됩니다.",diff --git a/src/i18n/locales/pt-BR/editor.json b/src/i18n/locales/pt-BR/editor.jsonindex e913b61dc..88c173f88 100644--- a/src/i18n/locales/pt-BR/editor.json+++ b/src/i18n/locales/pt-BR/editor.json@@ -105,6 +105,7 @@},"rec": {"source": "Fonte",+ "selectSource": "Selecionar fonte","systemPicker": "O sistema perguntará o que compartilhar","systemAudio": "Áudio do sistema","microphone": "Microfone",@@ -113,6 +114,8 @@"on": "Ativado","off": "Desativado","loading": "Carregando…",+ "noMicrophoneFound": "Nenhum microfone encontrado",+ "microphoneUnavailable": "Microfone indisponível","noCameraFound": "Nenhuma câmera encontrada","cameraAccessError": "Não foi possível acessar esta câmera","startingCamera": "Iniciando câmera…",@@ -367,6 +370,30 @@"noImage": "Sem imagem","noArrowData": "Sem dados de seta"},+ "appSettings": {+ "title": "Configurações",+ "subtitle": "Escolha a configuração de gravação e a aparência dos novos projetos.",+ "loading": "Carregando configurações…",+ "recordingTitle": "Configuração de gravação",+ "systemAudio": "Áudio do sistema",+ "microphone": "Microfone",+ "microphoneDevice": "Dispositivo de microfone",+ "camera": "Câmera",+ "cameraDevice": "Dispositivo de câmera",+ "editableCursor": "Cursor editável",+ "lastSource": "Última fonte: {{source}}",+ "noSource": "Nenhuma fonte selecionada",+ "saveRecording": "Salvar configuração de gravação",+ "resetRecording": "Redefinir configuração de gravação",+ "appearanceTitle": "Aparência de novos projetos",+ "customAppearance": "Padrões de aparência personalizados estão salvos.",+ "factoryAppearance": "Os padrões de aparência de fábrica estão ativos.",+ "useCurrentAppearance": "Usar aparência atual como padrão",+ "resetAppearance": "Redefinir aparência",+ "saved": "Salvo",+ "saveFailed": "Não foi possível salvar as configurações: {{error}}",+ "appearanceSummary": "{{aspect}}, preenchimento {{padding}}%, raio {{radius}}, cursor {{cursor}}, câmera {{camera}}"+ },"providerSettings": {"title": "Configurações de IA","subtitle": "Escolha um provedor. As credenciais são armazenadas no chaveiro do sistema (safeStorage).",diff --git a/src/i18n/locales/ru/editor.json b/src/i18n/locales/ru/editor.jsonindex d0f663c41..007324376 100644--- a/src/i18n/locales/ru/editor.json+++ b/src/i18n/locales/ru/editor.json@@ -105,6 +105,7 @@},"rec": {"source": "Источник",+ "selectSource": "Выбрать источник","systemPicker": "Система спросит, чем поделиться","systemAudio": "Системный звук","microphone": "Микрофон",@@ -113,6 +114,8 @@"on": "Вкл","off": "Выкл","loading": "Загрузка…",+ "noMicrophoneFound": "Микрофон не найден",+ "microphoneUnavailable": "Микрофон недоступен","noCameraFound": "Камера не найдена","cameraAccessError": "Не удалось получить доступ к этой камере","startingCamera": "Запуск камеры…",@@ -367,6 +370,30 @@"noImage": "Нет изображения","noArrowData": "Нет данных стрелки"},+ "appSettings": {+ "title": "Настройки",+ "subtitle": "Выберите параметры записи и оформление новых проектов.",+ "loading": "Загрузка настроек…",+ "recordingTitle": "Параметры записи",+ "systemAudio": "Системный звук",+ "microphone": "Микрофон",+ "microphoneDevice": "Устройство микрофона",+ "camera": "Камера",+ "cameraDevice": "Устройство камеры",+ "editableCursor": "Редактируемый курсор",+ "lastSource": "Последний источник: {{source}}",+ "noSource": "Источник не выбран",+ "saveRecording": "Сохранить параметры записи",+ "resetRecording": "Сбросить параметры записи",+ "appearanceTitle": "Оформление новых проектов",+ "customAppearance": "Пользовательские параметры оформления сохранены.",+ "factoryAppearance": "Используются заводские параметры оформления.",+ "useCurrentAppearance": "Использовать текущее оформление по умолчанию",+ "resetAppearance": "Сбросить оформление",+ "saved": "Сохранено",+ "saveFailed": "Не удалось сохранить настройки: {{error}}",+ "appearanceSummary": "{{aspect}}, отступ {{padding}}%, радиус {{radius}}, курсор {{cursor}}, камера {{camera}}"+ },"providerSettings": {"title": "Настройки ИИ","subtitle": "Выберите провайдера. Учётные данные хранятся в связке ключей ОС (safeStorage).",diff --git a/src/i18n/locales/tr/editor.json b/src/i18n/locales/tr/editor.jsonindex b30bc78d6..07fa34852 100644--- a/src/i18n/locales/tr/editor.json+++ b/src/i18n/locales/tr/editor.json@@ -105,6 +105,7 @@},"rec": {"source": "Kaynak",+ "selectSource": "Kaynak seç","systemPicker": "Sisteminiz neyi paylaşacağınızı soracak","systemAudio": "Sistem sesi","microphone": "Mikrofon",@@ -113,6 +114,8 @@"on": "Açık","off": "Kapalı","loading": "Yükleniyor…",+ "noMicrophoneFound": "Mikrofon bulunamadı",+ "microphoneUnavailable": "Mikrofon kullanılamıyor","noCameraFound": "Kamera bulunamadı","cameraAccessError": "Bu kameraya erişilemedi","startingCamera": "Kamera başlatılıyor…",@@ -367,6 +370,30 @@"noImage": "Görsel yok","noArrowData": "Ok verisi yok"},+ "appSettings": {+ "title": "Ayarlar",+ "subtitle": "Kayıt kurulumunu ve yeni projelerde kullanılacak görünümü seçin.",+ "loading": "Ayarlar yükleniyor…",+ "recordingTitle": "Kayıt kurulumu",+ "systemAudio": "Sistem sesi",+ "microphone": "Mikrofon",+ "microphoneDevice": "Mikrofon aygıtı",+ "camera": "Kamera",+ "cameraDevice": "Kamera aygıtı",+ "editableCursor": "Düzenlenebilir imleç",+ "lastSource": "Son kaynak: {{source}}",+ "noSource": "Kaynak seçilmedi",+ "saveRecording": "Kayıt kurulumunu kaydet",+ "resetRecording": "Kayıt kurulumunu sıfırla",+ "appearanceTitle": "Yeni proje görünümü",+ "customAppearance": "Özel görünüm varsayılanları kaydedildi.",+ "factoryAppearance": "Fabrika görünüm varsayılanları etkin.",+ "useCurrentAppearance": "Geçerli görünümü varsayılan olarak kullan",+ "resetAppearance": "Görünümü sıfırla",+ "saved": "Kaydedildi",+ "saveFailed": "Ayarlar kaydedilemedi: {{error}}",+ "appearanceSummary": "{{aspect}}, dolgu %{{padding}}, yarıçap {{radius}}, imleç {{cursor}}, kamera {{camera}}"+ },"providerSettings": {"title": "Yapay zekâ ayarları","subtitle": "Bir sağlayıcı seçin. Kimlik bilgileri işletim sisteminin anahtar zincirinde (safeStorage) saklanır.",diff --git a/src/i18n/locales/vi/editor.json b/src/i18n/locales/vi/editor.jsonindex 60db3e563..87cd729cd 100644--- a/src/i18n/locales/vi/editor.json+++ b/src/i18n/locales/vi/editor.json@@ -105,6 +105,7 @@},"rec": {"source": "Nguồn",+ "selectSource": "Chọn nguồn","systemPicker": "Hệ thống sẽ hỏi bạn muốn chia sẻ gì","systemAudio": "Âm thanh hệ thống","microphone": "Micro",@@ -113,6 +114,8 @@"on": "Bật","off": "Tắt","loading": "Đang tải…",+ "noMicrophoneFound": "Không tìm thấy micrô",+ "microphoneUnavailable": "Micrô không khả dụng","noCameraFound": "Không tìm thấy máy ảnh","cameraAccessError": "Không thể truy cập máy ảnh này","startingCamera": "Đang khởi động máy ảnh…",@@ -367,6 +370,30 @@"noImage": "Không có hình ảnh","noArrowData": "Không có dữ liệu mũi tên"},+ "appSettings": {+ "title": "Cài đặt",+ "subtitle": "Chọn thiết lập ghi và giao diện dùng cho dự án mới.",+ "loading": "Đang tải cài đặt…",+ "recordingTitle": "Thiết lập ghi",+ "systemAudio": "Âm thanh hệ thống",+ "microphone": "Micrô",+ "microphoneDevice": "Thiết bị micrô",+ "camera": "Camera",+ "cameraDevice": "Thiết bị camera",+ "editableCursor": "Con trỏ có thể chỉnh sửa",+ "lastSource": "Nguồn gần nhất: {{source}}",+ "noSource": "Chưa chọn nguồn",+ "saveRecording": "Lưu thiết lập ghi",+ "resetRecording": "Đặt lại thiết lập ghi",+ "appearanceTitle": "Giao diện dự án mới",+ "customAppearance": "Đã lưu mặc định giao diện tùy chỉnh.",+ "factoryAppearance": "Đang dùng mặc định giao diện ban đầu.",+ "useCurrentAppearance": "Dùng giao diện hiện tại làm mặc định",+ "resetAppearance": "Đặt lại giao diện",+ "saved": "Đã lưu",+ "saveFailed": "Không thể lưu cài đặt: {{error}}",+ "appearanceSummary": "{{aspect}}, khoảng đệm {{padding}}%, bán kính {{radius}}, con trỏ {{cursor}}, camera {{camera}}"+ },"providerSettings": {"title": "Cài đặt AI","subtitle": "Chọn một nhà cung cấp. Thông tin đăng nhập được lưu trong kho khóa của hệ điều hành (safeStorage).",diff --git a/src/i18n/locales/zh-CN/editor.json b/src/i18n/locales/zh-CN/editor.jsonindex 15fb5cf09..5cf9e4feb 100644--- a/src/i18n/locales/zh-CN/editor.json+++ b/src/i18n/locales/zh-CN/editor.json@@ -105,6 +105,7 @@},"rec": {"source": "来源",+ "selectSource": "选择来源","systemPicker": "系统将询问要共享的内容","systemAudio": "系统音频","microphone": "麦克风",@@ -113,6 +114,8 @@"on": "开","off": "关","loading": "加载中…",+ "noMicrophoneFound": "未找到麦克风",+ "microphoneUnavailable": "麦克风不可用","noCameraFound": "未找到摄像头","cameraAccessError": "无法访问该摄像头","startingCamera": "正在启动摄像头…",@@ -367,6 +370,30 @@"noImage": "无图片","noArrowData": "无箭头数据"},+ "appSettings": {+ "title": "设置",+ "subtitle": "选择录制配置和新项目使用的外观。",+ "loading": "正在加载设置…",+ "recordingTitle": "录制配置",+ "systemAudio": "系统音频",+ "microphone": "麦克风",+ "microphoneDevice": "麦克风设备",+ "camera": "摄像头",+ "cameraDevice": "摄像头设备",+ "editableCursor": "可编辑光标",+ "lastSource": "上次来源:{{source}}",+ "noSource": "未选择来源",+ "saveRecording": "保存录制配置",+ "resetRecording": "重置录制配置",+ "appearanceTitle": "新项目外观",+ "customAppearance": "已保存自定义外观默认值。",+ "factoryAppearance": "当前使用出厂外观默认值。",+ "useCurrentAppearance": "将当前外观设为默认值",+ "resetAppearance": "重置外观默认值",+ "saved": "已保存",+ "saveFailed": "无法保存设置:{{error}}",+ "appearanceSummary": "{{aspect}},边距 {{padding}}%,圆角 {{radius}},光标 {{cursor}},摄像头 {{camera}}"+ },"providerSettings": {"title": "AI 设置","subtitle": "选择一个提供商。凭据存储在系统钥匙串(safeStorage)中。",diff --git a/src/i18n/locales/zh-TW/editor.json b/src/i18n/locales/zh-TW/editor.jsonindex 62f162592..4d2cd591e 100644--- a/src/i18n/locales/zh-TW/editor.json+++ b/src/i18n/locales/zh-TW/editor.json@@ -105,6 +105,7 @@},"rec": {"source": "來源",+ "selectSource": "選擇來源","systemPicker": "系統將詢問要分享的內容","systemAudio": "系統音訊","microphone": "麥克風",@@ -113,6 +114,8 @@"on": "開","off": "關","loading": "載入中…",+ "noMicrophoneFound": "找不到麥克風",+ "microphoneUnavailable": "麥克風無法使用","noCameraFound": "找不到攝影機","cameraAccessError": "無法存取此攝影機","startingCamera": "正在啟動攝影機…",@@ -367,6 +370,30 @@"noImage": "沒有圖片","noArrowData": "沒有箭頭資料"},+ "appSettings": {+ "title": "設定",+ "subtitle": "選擇錄製配置和新專案使用的外觀。",+ "loading": "正在載入設定…",+ "recordingTitle": "錄製配置",+ "systemAudio": "系統音訊",+ "microphone": "麥克風",+ "microphoneDevice": "麥克風裝置",+ "camera": "攝影機",+ "cameraDevice": "攝影機裝置",+ "editableCursor": "可編輯游標",+ "lastSource": "上次來源:{{source}}",+ "noSource": "未選擇來源",+ "saveRecording": "儲存錄製配置",+ "resetRecording": "重設錄製配置",+ "appearanceTitle": "新專案外觀",+ "customAppearance": "已儲存自訂外觀預設值。",+ "factoryAppearance": "目前使用原廠外觀預設值。",+ "useCurrentAppearance": "將目前外觀設為預設值",+ "resetAppearance": "重設外觀預設值",+ "saved": "已儲存",+ "saveFailed": "無法儲存設定:{{error}}",+ "appearanceSummary": "{{aspect}},邊距 {{padding}}%,圓角 {{radius}},游標 {{cursor}},攝影機 {{camera}}"+ },"providerSettings": {"title": "AI 設定","subtitle": "選擇一個供應商。憑證會儲存在系統金鑰鏈(safeStorage)中。",diff --git a/src/lib/ai-edition/store/editorSettings.ts b/src/lib/ai-edition/store/editorSettings.tsindex 079a0b7d1..5f2b28bca 100644--- a/src/lib/ai-edition/store/editorSettings.ts+++ b/src/lib/ai-edition/store/editorSettings.ts@@ -12,19 +12,7 @@ import {type CropRegion,type CursorVisualSettings,DEFAULT_CROP_REGION,- DEFAULT_CURSOR_CLICK_BOUNCE,- DEFAULT_CURSOR_CLIP_TO_BOUNDS,- DEFAULT_CURSOR_MOTION_BLUR,- DEFAULT_CURSOR_SIZE,- DEFAULT_CURSOR_SMOOTHING,- DEFAULT_WEBCAM_BACKGROUND_MODE,- DEFAULT_WEBCAM_BLUR_INTENSITY,- DEFAULT_WEBCAM_LAYOUT_PRESET,- DEFAULT_WEBCAM_MASK_SHAPE,- DEFAULT_WEBCAM_MIRRORED,DEFAULT_WEBCAM_POSITION,- DEFAULT_WEBCAM_REACTIVE_ZOOM,- DEFAULT_WEBCAM_SIZE_PRESET,isWebcamBackgroundMode,type WebcamBackgroundMode,type WebcamLayoutPreset,@@ -32,8 +20,7 @@ import {type WebcamPosition,type WebcamSizePreset,} from "@/components/video-editor/types";-import { DEFAULT_CURSOR_THEME_ID } from "@/lib/cursor/cursorThemes";-import { DEFAULT_WALLPAPER } from "@/lib/wallpaper";+import { DEFAULT_PROJECT_APPEARANCE } from "@/lib/projectDefaults";import type { AspectRatio } from "@/utils/aspectRatioUtils";import { clamp01 } from "@/utils/math";import type { AxcutDocument } from "../schema";@@ -114,43 +101,16 @@ export interface EditorSettingsSnapshot {}export const DEFAULT_EDITOR_SETTINGS: EditorSettingsSnapshot = {- wallpaper: DEFAULT_WALLPAPER,- aspectRatio: "16:9",// Opinionated by default: the wallpaper and the padding were already on, but// with square corners and no shadow the recording read as a rectangle pasted// onto the background rather than a window floating above it (#271 reported// the symptom and blamed the padding). These three are the rest of that look;// shipping the background without them was shipping half a composition.- shadowIntensity: 0.2,- showBlur: false,- motionBlurAmount: 0.2,- borderRadius: 40,- padding: 50,+ ...DEFAULT_PROJECT_APPEARANCE,cropRegion: DEFAULT_CROP_REGION,- webcamLayoutPreset: DEFAULT_WEBCAM_LAYOUT_PRESET,- webcamMaskShape: DEFAULT_WEBCAM_MASK_SHAPE,- webcamMirrored: DEFAULT_WEBCAM_MIRRORED,- webcamReactiveZoom: DEFAULT_WEBCAM_REACTIVE_ZOOM,- webcamSizePreset: DEFAULT_WEBCAM_SIZE_PRESET,- webcamPosition: DEFAULT_WEBCAM_POSITION,webcamCropRegion: DEFAULT_CROP_REGION,webcamCropPan: DEFAULT_CROP_PAN,audioGainDb: 0,- webcamBackgroundMode: DEFAULT_WEBCAM_BACKGROUND_MODE,- webcamWallpaper: DEFAULT_WALLPAPER,- webcamBlurIntensity: DEFAULT_WEBCAM_BLUR_INTENSITY,- cursor: {- size: DEFAULT_CURSOR_SIZE,- smoothing: DEFAULT_CURSOR_SMOOTHING,- motionBlur: DEFAULT_CURSOR_MOTION_BLUR,- clickBounce: DEFAULT_CURSOR_CLICK_BOUNCE,- clipToBounds: DEFAULT_CURSOR_CLIP_TO_BOUNDS,- autoHide: false,- },- cursorShow: true,- cursorAutoHide: false,- cursorTheme: DEFAULT_CURSOR_THEME_ID,- autoFocusAll: false,};interface LegacyShape {diff --git a/src/lib/projectDefaults.test.ts b/src/lib/projectDefaults.test.tsnew file mode 100644index 000000000..d333e3194--- /dev/null+++ b/src/lib/projectDefaults.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from "vitest";+import { createEmptyDocument } from "@/lib/ai-edition/schema";+import { DEFAULT_EDITOR_SETTINGS } from "@/lib/ai-edition/store/editorSettings";+import {+ applyProjectAppearanceDefaults,+ DEFAULT_PROJECT_APPEARANCE,+ parseProjectAppearanceDefaults,+ projectAppearanceFromEditorSettings,+} from "./projectDefaults";++describe("project appearance defaults", () => {+ it("copies the appearance allowlist without media, crop, timing, or identity", () => {+ const source = {+ ...DEFAULT_EDITOR_SETTINGS,+ wallpaper: "#123456",+ padding: 12,+ cropRegion: { x: 0.2, y: 0.2, width: 0.5, height: 0.5 },+ audioGainDb: 9,+ };+ const defaults = projectAppearanceFromEditorSettings(source);+ expect(defaults).toMatchObject({ wallpaper: "#123456", padding: 12 });+ expect(defaults).not.toHaveProperty("cropRegion");+ expect(defaults).not.toHaveProperty("audioGainDb");+ expect(defaults).not.toHaveProperty("assets");+ });++ it("defaults a stored appearance that predates cursor auto-hide", () => {+ const { cursorAutoHide: _cursorAutoHide, cursor, ...rest } = DEFAULT_PROJECT_APPEARANCE;+ const { autoHide: _autoHide, ...legacyCursor } = cursor;+ expect(+ parseProjectAppearanceDefaults({+ ...rest,+ cursor: legacyCursor,+ }),+ ).toMatchObject({+ cursorAutoHide: false,+ cursor: { ...legacyCursor, autoHide: false },+ });+ });++ it("validates the complete payload and rejects partial or unsafe values", () => {+ expect(parseProjectAppearanceDefaults(DEFAULT_PROJECT_APPEARANCE)).toEqual(+ DEFAULT_PROJECT_APPEARANCE,+ );+ expect(() => parseProjectAppearanceDefaults({ padding: 10 })).toThrow(TypeError);+ expect(() =>+ parseProjectAppearanceDefaults({ ...DEFAULT_PROJECT_APPEARANCE, padding: 101 }),+ ).toThrow(TypeError);+ });++ it("materializes the allowlist into a new document without changing its identity", () => {+ const empty = createEmptyDocument({ projectId: "proj_defaults", title: "Defaults" });+ const next = applyProjectAppearanceDefaults(empty, {+ ...DEFAULT_PROJECT_APPEARANCE,+ wallpaper: "#abcdef",+ padding: 18,+ });+ expect(next.project).toEqual(empty.project);+ expect(next.assets).toEqual([]);+ expect(next.timeline).toEqual(empty.timeline);+ expect(next.legacyEditor).toMatchObject({ wallpaper: "#abcdef", padding: 18 });+ });+});diff --git a/src/lib/projectDefaults.ts b/src/lib/projectDefaults.tsnew file mode 100644index 000000000..237e7f741--- /dev/null+++ b/src/lib/projectDefaults.ts@@ -0,0 +1,205 @@+import type { AxcutDocument } from "./ai-edition/schema";++export interface ProjectAppearanceDefaults {+ wallpaper: string;+ aspectRatio: `${number}:${number}` | "native";+ shadowIntensity: number;+ showBlur: boolean;+ motionBlurAmount: number;+ borderRadius: number;+ padding: number;+ webcamLayoutPreset: "picture-in-picture" | "vertical-stack" | "dual-frame" | "no-webcam";+ webcamMaskShape: "rectangle" | "circle" | "square" | "rounded";+ webcamMirrored: boolean;+ webcamReactiveZoom: boolean;+ webcamSizePreset: number;+ webcamPosition: { cx: number; cy: number } | null;+ webcamBackgroundMode: "none" | "transparent" | "blur" | "custom";+ webcamWallpaper: string;+ webcamBlurIntensity: number;+ cursor: {+ size: number;+ smoothing: number;+ motionBlur: number;+ clickBounce: number;+ clipToBounds: boolean;+ autoHide: boolean;+ };+ cursorShow: boolean;+ cursorAutoHide: boolean;+ cursorTheme: string;+ autoFocusAll: boolean;+}++/** Structural input accepted from the editor settings reader without coupling this+ * main-process-safe serializer to renderer-only modules or path aliases.+ * `cursor.autoHide` is optional on the editor snapshot (#104); the stored+ * appearance defaults always materialize it as a boolean. */+export type ProjectAppearanceSource = Omit<ProjectAppearanceDefaults, "cursor"> & {+ cursor: Omit<ProjectAppearanceDefaults["cursor"], "autoHide"> & { autoHide?: boolean };+};++export const DEFAULT_PROJECT_APPEARANCE: ProjectAppearanceDefaults = {+ wallpaper: "/wallpapers/wallpaper1.jpg",+ aspectRatio: "16:9",+ shadowIntensity: 0.2,+ showBlur: false,+ motionBlurAmount: 0.2,+ borderRadius: 40,+ padding: 50,+ webcamLayoutPreset: "picture-in-picture",+ webcamMaskShape: "rectangle",+ webcamMirrored: false,+ webcamReactiveZoom: true,+ webcamSizePreset: 25,+ webcamPosition: null,+ webcamBackgroundMode: "none",+ webcamWallpaper: "/wallpapers/wallpaper1.jpg",+ webcamBlurIntensity: 0.5,+ cursor: {+ size: 3,+ smoothing: 0.67,+ motionBlur: 0.35,+ clickBounce: 2.5,+ clipToBounds: false,+ autoHide: false,+ },+ cursorShow: true,+ cursorAutoHide: false,+ cursorTheme: "default",+ autoFocusAll: false,+};++const LAYOUTS = new Set(["picture-in-picture", "vertical-stack", "dual-frame", "no-webcam"]);+const MASK_SHAPES = new Set(["rectangle", "circle", "square", "rounded"]);+const BACKGROUND_MODES = new Set(["none", "transparent", "blur", "custom"]);++function finite(value: unknown, min: number, max: number): value is number {+ return typeof value === "number" && Number.isFinite(value) && value >= min && value <= max;+}++function isAspectRatio(value: unknown): value is string {+ if (value === "native") return true;+ if (typeof value !== "string") return false;+ const match = /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(value);+ return Boolean(match && Number(match[1]) > 0 && Number(match[2]) > 0);+}++function position(value: unknown): value is ProjectAppearanceDefaults["webcamPosition"] {+ if (value === null) return true;+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;+ const candidate = value as Record<string, unknown>;+ return finite(candidate.cx, 0, 1) && finite(candidate.cy, 0, 1);+}++function cursor(value: unknown): value is ProjectAppearanceDefaults["cursor"] {+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;+ const candidate = value as Record<string, unknown>;+ return (+ finite(candidate.size, 0.1, 20) &&+ finite(candidate.smoothing, 0, 1) &&+ finite(candidate.motionBlur, 0, 1) &&+ finite(candidate.clickBounce, 0, 10) &&+ typeof candidate.clipToBounds === "boolean" &&+ (candidate.autoHide === undefined || typeof candidate.autoHide === "boolean")+ );+}++export function projectAppearanceFromEditorSettings(+ settings: ProjectAppearanceSource,+): ProjectAppearanceDefaults {+ return {+ wallpaper: settings.wallpaper,+ aspectRatio: settings.aspectRatio,+ shadowIntensity: settings.shadowIntensity,+ showBlur: settings.showBlur,+ motionBlurAmount: settings.motionBlurAmount,+ borderRadius: settings.borderRadius,+ padding: settings.padding,+ webcamLayoutPreset: settings.webcamLayoutPreset,+ webcamMaskShape: settings.webcamMaskShape,+ webcamMirrored: settings.webcamMirrored,+ webcamReactiveZoom: settings.webcamReactiveZoom,+ webcamSizePreset: settings.webcamSizePreset,+ webcamPosition: settings.webcamPosition ? { ...settings.webcamPosition } : null,+ webcamBackgroundMode: settings.webcamBackgroundMode,+ webcamWallpaper: settings.webcamWallpaper,+ webcamBlurIntensity: settings.webcamBlurIntensity,+ cursor: { ...settings.cursor, autoHide: settings.cursor.autoHide === true },+ cursorShow: settings.cursorShow,+ cursorAutoHide: settings.cursorAutoHide === true || settings.cursor.autoHide === true,+ cursorTheme: settings.cursorTheme,+ autoFocusAll: settings.autoFocusAll,+ };+}++export function parseProjectAppearanceDefaults(value: unknown): ProjectAppearanceDefaults {+ if (!value || typeof value !== "object" || Array.isArray(value)) {+ throw new TypeError("project appearance defaults must be an object");+ }+ const candidate = value as Record<string, unknown>;+ if (+ typeof candidate.wallpaper !== "string" ||+ !isAspectRatio(candidate.aspectRatio) ||+ !finite(candidate.shadowIntensity, 0, 1) ||+ typeof candidate.showBlur !== "boolean" ||+ !finite(candidate.motionBlurAmount, 0, 1) ||+ !finite(candidate.borderRadius, 0, 500) ||+ !finite(candidate.padding, 0, 100) ||+ !LAYOUTS.has(candidate.webcamLayoutPreset as string) ||+ !MASK_SHAPES.has(candidate.webcamMaskShape as string) ||+ typeof candidate.webcamMirrored !== "boolean" ||+ typeof candidate.webcamReactiveZoom !== "boolean" ||+ !finite(candidate.webcamSizePreset, 10, 50) ||+ !position(candidate.webcamPosition) ||+ !BACKGROUND_MODES.has(candidate.webcamBackgroundMode as string) ||+ typeof candidate.webcamWallpaper !== "string" ||+ !finite(candidate.webcamBlurIntensity, 0, 1) ||+ !cursor(candidate.cursor) ||+ typeof candidate.cursorShow !== "boolean" ||+ typeof candidate.cursorTheme !== "string" ||+ candidate.cursorTheme.length === 0 ||+ typeof candidate.autoFocusAll !== "boolean"+ ) {+ throw new TypeError("project appearance defaults are invalid");+ }+ return projectAppearanceFromEditorSettings(candidate as unknown as ProjectAppearanceSource);+}++export function applyProjectAppearanceDefaults(+ document: AxcutDocument,+ defaults: ProjectAppearanceDefaults,+): AxcutDocument {+ const parsed = parseProjectAppearanceDefaults(defaults);+ return {+ ...document,+ legacyEditor: {+ ...(document.legacyEditor ?? {}),+ wallpaper: parsed.wallpaper,+ aspectRatio: parsed.aspectRatio,+ shadowIntensity: parsed.shadowIntensity,+ showBlur: parsed.showBlur,+ motionBlurAmount: parsed.motionBlurAmount,+ borderRadius: parsed.borderRadius,+ padding: parsed.padding,+ webcamLayoutPreset: parsed.webcamLayoutPreset,+ webcamMaskShape: parsed.webcamMaskShape,+ webcamMirrored: parsed.webcamMirrored,+ webcamReactiveZoom: parsed.webcamReactiveZoom,+ webcamSizePreset: parsed.webcamSizePreset,+ webcamPosition: parsed.webcamPosition,+ webcamBackgroundMode: parsed.webcamBackgroundMode,+ webcamWallpaper: parsed.webcamWallpaper,+ webcamBlurIntensity: parsed.webcamBlurIntensity,+ cursorSize: parsed.cursor.size,+ cursorSmoothing: parsed.cursor.smoothing,+ cursorMotionBlur: parsed.cursor.motionBlur,+ cursorClickBounce: parsed.cursor.clickBounce,+ cursorClipToBounds: parsed.cursor.clipToBounds,+ cursorShow: parsed.cursorShow,+ cursorAutoHide: parsed.cursorAutoHide,+ cursorTheme: parsed.cursorTheme,+ autoFocusAll: parsed.autoFocusAll,+ },+ };+}diff --git a/src/lib/userPreferences.test.ts b/src/lib/userPreferences.test.tsindex ca66c53d5..6bf436f60 100644--- a/src/lib/userPreferences.test.ts+++ b/src/lib/userPreferences.test.ts@@ -1,4 +1,5 @@import { beforeEach, describe, expect, it } from "vitest";+import { DEFAULT_PROJECT_APPEARANCE } from "./projectDefaults";import {DEFAULT_PREFS,getProjectFolder,@@ -133,4 +134,10 @@ describe("user preferences", () => {expect(loadUserPreferences().hideSoftwareEncoderFallbackNotice).toBe(false);});++ it("keeps dormant padding and aspect values compatible without overriding project defaults", () => {+ saveUserPreferences({ padding: 3, aspectRatio: "1:1" });+ expect(loadUserPreferences()).toMatchObject({ padding: 3, aspectRatio: "1:1" });+ expect(DEFAULT_PROJECT_APPEARANCE).toMatchObject({ padding: 50, aspectRatio: "16:9" });+ });});diff --git a/src/lib/userPreferences.ts b/src/lib/userPreferences.tsindex f98fb422d..90be5916e 100644--- a/src/lib/userPreferences.ts+++ b/src/lib/userPreferences.ts@@ -8,9 +8,9 @@ import { type AspectRatio, isAspectRatio } from "@/utils/aspectRatioUtils";const PREFS_KEY = "openscreen_user_preferences";export interface UserPreferences {- /** Default padding % */+ /** @deprecated Dormant compatibility field. New-project appearance uses recording-settings.json. */padding: number;- /** Default aspect ratio */+ /** @deprecated Dormant compatibility field. New-project appearance uses recording-settings.json. */aspectRatio: AspectRatio;/** Default export quality */exportQuality: ExportQuality;@@ -61,6 +61,8 @@ export function loadUserPreferences(): UserPreferences {if (!raw || typeof raw !== "object") return { ...DEFAULT_PREFS };return {+ // Kept readable for compatibility with older builds. These values are never+ // migrated into or consulted by the canonical project-appearance store.padding:typeof raw.padding === "number" &&Number.isFinite(raw.padding) &&diff --git a/src/native/browserShim.test.ts b/src/native/browserShim.test.tsindex 07f5966b8..c2d849baf 100644--- a/src/native/browserShim.test.ts+++ b/src/native/browserShim.test.ts@@ -2,6 +2,7 @@// The shim persists projects to localStorage, so this needs a DOM.import { beforeAll, beforeEach, describe, expect, it } from "vitest";import type { AxcutDocument } from "@/lib/ai-edition/schema";+import { DEFAULT_PROJECT_APPEARANCE } from "@/lib/projectDefaults";import { installBrowserShims } from "./browserShim";import { nativeBridgeClient } from "./client";@@ -58,3 +59,81 @@ describe("browserShim addAsset (issue #350)", () => {expect(doc.project.primaryAssetId).toBe(asset?.id);});});++describe("browserShim app settings", () => {+ it("materializes versioned appearance defaults into a new browser project", async () => {+ await window.electronAPI.setProjectAppearanceDefaults({+ ...DEFAULT_PROJECT_APPEARANCE,+ wallpaper: "#abcdef",+ padding: 9,+ });+ const created = await nativeBridgeClient.aiEdition.create("Defaults");+ expect(asDoc(created.document).legacyEditor).toMatchObject({+ wallpaper: "#abcdef",+ padding: 9,+ });+ });++ it("publishes recording settings only after localStorage succeeds", async () => {+ await window.electronAPI.resetRecordingSetup();+ const setItem = Storage.prototype.setItem;+ Storage.prototype.setItem = () => {+ throw new Error("storage unavailable");+ };+ try {+ await expect(window.electronAPI.setRecordingPrefs({ micEnabled: true })).rejects.toThrow(+ "storage unavailable",+ );+ expect((await window.electronAPI.getRecordingPrefs()).micEnabled).toBe(false);+ } finally {+ Storage.prototype.setItem = setItem;+ }+ });++ it("notifies recording and source subscribers on changes and reset", async () => {+ const prefsEvents: boolean[] = [];+ const sourceEvents: Array<string | null> = [];+ const stopPrefs = window.electronAPI.onRecordingPrefsChanged((prefs) =>+ prefsEvents.push(prefs.micEnabled),+ );+ const stopSource = window.electronAPI.onSelectedSourceChanged((source) =>+ sourceEvents.push(source?.id ?? null),+ );++ await window.electronAPI.setRecordingPrefs({ micEnabled: true });+ const source = (await window.electronAPI.getSources({ types: ["screen"] }))[0];+ await window.electronAPI.selectSource(source);+ await window.electronAPI.resetRecordingSetup();++ expect(prefsEvents).toEqual([true, false]);+ expect(sourceEvents).toEqual([source.id, null]);+ stopPrefs();+ stopSource();+ await window.electronAPI.setRecordingPrefs({ micEnabled: true });+ expect(prefsEvents).toEqual([true, false]);+ });++ it("persists the selected source unless persist is false, and reset clears it", async () => {+ const source = (await window.electronAPI.getSources({ types: ["screen"] }))[0];+ await window.electronAPI.selectSource(source, { persist: false });+ expect(localStorage.getItem("browser-shim-selected-source")).toBeNull();+ expect((await window.electronAPI.getAppSettings()).lastSource).toMatchObject({+ id: source.id,+ name: source.name,+ });++ await window.electronAPI.selectSource(source);+ expect(+ JSON.parse(localStorage.getItem("browser-shim-selected-source") ?? "null"),+ ).toMatchObject({ id: source.id });+ expect((await window.electronAPI.getAppSettings()).lastSource).toMatchObject({+ id: source.id,+ name: source.name,+ kind: "screen",+ });++ await window.electronAPI.resetRecordingSetup();+ expect(localStorage.getItem("browser-shim-selected-source")).toBeNull();+ expect((await window.electronAPI.getAppSettings()).lastSource).toBeNull();+ });+});diff --git a/src/native/browserShim.ts b/src/native/browserShim.tsindex c9e5d395b..15a806935 100644--- a/src/native/browserShim.ts+++ b/src/native/browserShim.ts@@ -4,7 +4,18 @@// rapid iteration without the Electron window overhead.import { PROVIDER_DEFINITIONS } from "../../electron/ai-edition/provider-registry";-import { axcutSchemaVersion, migrateRawDocumentToCurrent } from "../lib/ai-edition/schema";+import { describeRecordingSource } from "../../electron/recording-source-settings";+import {+ type AxcutDocument,+ axcutSchemaVersion,+ migrateRawDocumentToCurrent,+} from "../lib/ai-edition/schema";+import {+ applyProjectAppearanceDefaults,+ DEFAULT_PROJECT_APPEARANCE,+ type ProjectAppearanceDefaults,+ parseProjectAppearanceDefaults,+} from "../lib/projectDefaults";import { nativeBridgeClient as realClient } from "./client";function detectBrowserMode(): boolean {@@ -37,6 +48,7 @@ const SHIM_SOURCES: ShimDesktopSource[] = [{ id: "window:100", name: "OpenScreen", display_id: "", thumbnail: null, appIcon: null },{ id: "window:101", name: "Terminal", display_id: "", thumbnail: null, appIcon: null },];+const selectedSourceStorageKey = "browser-shim-selected-source";let shimSelectedSource: ShimDesktopSource | null = null;type ShimRecordingPrefs = {@@ -45,6 +57,7 @@ type ShimRecordingPrefs = {micDeviceName: string | null;camEnabled: boolean;camDeviceId: string | null;+ camDeviceName: string | null;systemAudioEnabled: boolean;cursorCaptureMode: "editable-overlay" | "system";};@@ -55,9 +68,24 @@ let shimRecordingPrefs: ShimRecordingPrefs = {micDeviceName: null,camEnabled: false,camDeviceId: null,+ camDeviceName: null,systemAudioEnabled: false,cursorCaptureMode: "editable-overlay",};+const shimRecordingPrefsListeners = new Set<(prefs: ShimRecordingPrefs) => void>();+const shimSelectedSourceListeners = new Set<(source: ShimDesktopSource | null) => void>();+function persistShimSelectedSource(source: ShimDesktopSource | null) {+ try {+ if (source) {+ localStorage.setItem(selectedSourceStorageKey, JSON.stringify(source));+ return;+ }+ localStorage.removeItem(selectedSourceStorageKey);+ } catch {+ // ponytail: corrupt/unavailable localStorage — keep the in-memory pick.+ }+}+(() => {try {const raw = localStorage.getItem(recordingPrefsStorageKey);@@ -65,8 +93,53 @@ let shimRecordingPrefs: ShimRecordingPrefs = {} catch {// ponytail: corrupt/unavailable localStorage — start fresh.}+ try {+ const raw = localStorage.getItem(selectedSourceStorageKey);+ if (!raw) return;+ const parsed = JSON.parse(raw) as ShimDesktopSource;+ if (parsed && typeof parsed.id === "string" && typeof parsed.name === "string") {+ shimSelectedSource = parsed;+ }+ } catch {+ // ponytail: corrupt/unavailable localStorage — start with no source.+ }+})();++const appearanceStorageKey = "browser-shim-project-appearance-v1";+let shimAppearanceDefaults: ProjectAppearanceDefaults = DEFAULT_PROJECT_APPEARANCE;+let shimHasCustomAppearance = false;+(() => {+ try {+ const raw = localStorage.getItem(appearanceStorageKey);+ if (!raw) return;+ const parsed = JSON.parse(raw) as { version?: unknown; defaults?: unknown };+ if (parsed.version === 1 && parsed.defaults) {+ shimAppearanceDefaults = parseProjectAppearanceDefaults(parsed.defaults);+ shimHasCustomAppearance = true;+ }+ } catch {+ // Corrupt/unavailable localStorage starts from canonical factory appearance.+ }})();+function shimAppSettingsSnapshot() {+ return {+ recording: shimRecordingPrefs,+ lastSource: shimSelectedSource+ ? describeRecordingSource(process.platform, {+ id: shimSelectedSource.id,+ name: shimSelectedSource.name,+ display_id: shimSelectedSource.display_id,+ })+ : null,+ appearance: {+ version: 1 as const,+ custom: shimHasCustomAppearance,+ defaults: shimAppearanceDefaults,+ },+ };+}+// ponytail: real file dialogs/ffmpeg probing aren't available in a plain// browser tab, but a hidden <input type="file"> + blob URL gets us a real,// playable video without any native bridge — NewEditorShell/toFileUrl@@ -134,23 +207,66 @@ function createShimElectronAPI() {// No installer in browser mode, so nothing may ever be checked.canCheckForUpdatesNow: () => Promise.resolve(false),getSources: () => Promise.resolve(SHIM_SOURCES),- selectSource: (source: ShimDesktopSource) => {+ selectSource: (source: ShimDesktopSource, options?: { persist?: boolean }) => {shimSelectedSource = source;+ if (options?.persist !== false) persistShimSelectedSource(source);+ shimSelectedSourceListeners.forEach((listener) => listener(source));return Promise.resolve(source);},getSelectedSource: () => Promise.resolve(shimSelectedSource),- onSelectedSourceChanged: () => () => undefined,+ onSelectedSourceChanged: (callback: (source: ShimDesktopSource | null) => void) => {+ shimSelectedSourceListeners.add(callback);+ return () => shimSelectedSourceListeners.delete(callback);+ },getRecordingPrefs: () => Promise.resolve(shimRecordingPrefs),setRecordingPrefs: (patch: Partial<ShimRecordingPrefs>) => {- shimRecordingPrefs = { ...shimRecordingPrefs, ...patch };+ const next = { ...shimRecordingPrefs, ...patch };try {- localStorage.setItem(recordingPrefsStorageKey, JSON.stringify(shimRecordingPrefs));- } catch {- // ponytail: localStorage may be full or unavailable; silently skip+ localStorage.setItem(recordingPrefsStorageKey, JSON.stringify(next));+ } catch (error) {+ return Promise.reject(error);}+ shimRecordingPrefs = next;+ shimRecordingPrefsListeners.forEach((listener) => listener(next));return Promise.resolve(shimRecordingPrefs);},- onRecordingPrefsChanged: () => () => undefined,+ onRecordingPrefsChanged: (callback: (prefs: ShimRecordingPrefs) => void) => {+ shimRecordingPrefsListeners.add(callback);+ return () => shimRecordingPrefsListeners.delete(callback);+ },+ getAppSettings: () => Promise.resolve(shimAppSettingsSnapshot()),+ setProjectAppearanceDefaults: (defaults: ProjectAppearanceDefaults) => {+ const next = parseProjectAppearanceDefaults(defaults);+ localStorage.setItem(appearanceStorageKey, JSON.stringify({ version: 1, defaults: next }));+ shimAppearanceDefaults = next;+ shimHasCustomAppearance = true;+ return Promise.resolve(shimAppSettingsSnapshot());+ },+ resetProjectAppearanceDefaults: () => {+ localStorage.setItem(appearanceStorageKey, JSON.stringify({ version: 1, defaults: null }));+ shimAppearanceDefaults = DEFAULT_PROJECT_APPEARANCE;+ shimHasCustomAppearance = false;+ return Promise.resolve(shimAppSettingsSnapshot());+ },+ resetRecordingSetup: () => {+ const next: ShimRecordingPrefs = {+ micEnabled: false,+ micDeviceId: null,+ micDeviceName: null,+ camEnabled: false,+ camDeviceId: null,+ camDeviceName: null,+ systemAudioEnabled: false,+ cursorCaptureMode: "editable-overlay",+ };+ localStorage.setItem(recordingPrefsStorageKey, JSON.stringify(next));+ shimRecordingPrefs = next;+ shimSelectedSource = null;+ persistShimSelectedSource(null);+ shimRecordingPrefsListeners.forEach((listener) => listener(next));+ shimSelectedSourceListeners.forEach((listener) => listener(null));+ return Promise.resolve(shimAppSettingsSnapshot());+ },// ponytail: the chat panel subscribes to this on mount, unconditionally.// Without a stub the whole editor tree throws before it paints, so every// browser-shim test fails at boot, not just the chat ones. Nothing streams@@ -361,7 +477,7 @@ function createShimBridgeClient() {);},create: (title?: string) => {- const doc: ShimDocument = {+ const empty: ShimDocument = {// Mint at the current schema version so the renderer's// `documentSchema.parse` (a pure validator, no migration) accepts// the returned document. Must never be a literal: this value has to@@ -389,6 +505,10 @@ function createShimBridgeClient() {audioTracks: [],legacyEditor: null,};+ const doc = applyProjectAppearanceDefaults(+ empty as unknown as AxcutDocument,+ shimAppearanceDefaults,+ ) as unknown as ShimDocument;documentsByProject[doc.project.id] = doc;projectOrder.unshift(doc.project.id);saveProjectsState();diff --git a/technical-documentation/testing/images/recording-defaults-reset-windows.png b/technical-documentation/testing/images/recording-defaults-reset-windows.pngnew file mode 100644index 000000000..0833302acBinary files /dev/null and b/technical-documentation/testing/images/recording-defaults-reset-windows.png differdiff --git a/technical-documentation/testing/manual-e2e-checklist.md b/technical-documentation/testing/manual-e2e-checklist.mdindex 0c4a4cdb4..d298c5df1 100644--- a/technical-documentation/testing/manual-e2e-checklist.md+++ b/technical-documentation/testing/manual-e2e-checklist.md@@ -623,5 +623,7 @@ The mask comes from the native compositor (ONNX Runtime + the vendored selfie-se| | | | | || 2026-09-05 | Windows single-frame decoder ownership follow-up; source SHA-256 `FAF87561...87117`, bundled addon `94bc16d7...43a2c`, app.asar `8063a377...96f04` | Windows 11 build 26340; packaged Electron 41.2.1 | Scoped pass: nonzero AV1 seek and cross-clip playback | Fresh package, unique profile, no addon override; all 15 packaged native files hash-match staging (the existing packaging filter excludes standalone `ffmpeg.exe`). Native keyboard opened Studio after HUD pointer targeting failed; Studio seek/play/close used native input. AV1 at timeline 1.500 s/source 0.400 s rendered red `[255,24,0,255]` with a retained screenshot. During native playback from the first H.264 clip, read-only CDP samples observed blue followed by third-clip green `[0,216,0,255]` at 1.571 s; native logs confirm the malformed AV1 and following H.264 sources. PID 35472 exited 0 through window Close. An earlier sandboxed launch failed during Chromium GPU startup and is excluded from this pass. Limits: synthetic media, two native playback attempts in one successful session, no repeated stability or reporter-file claim; capture/webcam/tray/export not run. Exact-endpoint 4.540 s and one subsequent seek showed first-clip blue after native free-run wrapped: unchanged clip-identity synchronization paths, outside this resource/preflight follow-up; endpoint correctness is not claimed. Historical A/B rows remain separate. || 2026-09-11 | dev build (`npm run dev`) of `fix/582-antialias-decimation`, base `fbe461e9`, final commit `8d97f799`. The 96 and 192 kHz A/B ran the helper from a clean `npm run build:native:win` of the tree `8d97f799` carries; the 384 kHz A/B and the 48 kHz app run used helpers built with the same command from earlier revisions of this branch, whose helper sources differ from `8d97f799` only in comments and whitespace. The A/B's pre-fix helper was built from `fbe461e9` in a separate worktree. No binary hash is given; build from the commit SHA. | Windows 11 Pro 26340, 2560×1600 @ 150% (as read after the runs) | Scoped pass — no defect; the 96, 192 and 384 kHz (factors 2, 4 and 8) A/B ran and the alias is gone | **Anti-alias decimation (#582) slice.** **48 kHz path, in the app, with real OS input against the click-through HUD:** source picker → Entire screen → Share; system audio on (helper launched with `system: { enabled: true }`); record with countdown; **pause at 00:32** (timer yellow, control switches to resume) and **resume** (red at 00:36); stop → editor opens with the take; playback of the saved recording runs, playhead advancing through 0:04.6 and 0:11.6. Recorded stream `aac, 48000 Hz, 2 ch, 192000 bit/s`, 38.38 s. The endpoint ran at 48 kHz, so nothing decimated on this pass: the 1 kHz reference measured **-26.97 dBFS**, and the 4 kHz and 12 kHz alias bins were empty (-128 and -125 dBFS). The 20 kHz probe component is absent (-136 dBFS), and an AAC encode alone removes it too: the same tone encoded to AAC 192 kbps by ffmpeg, with no capture involved, reads -131 dBFS at 20 kHz against -13.99 dBFS at 1 kHz — so a 20 kHz probe cannot test the capture path. **Decimation path, A/B'd against the pre-fix build at three rates:** a USB DAC was made the default render endpoint and its *shared-mode* format set to 96000, 192000 and 384000 Hz in turn, so loopback reports that rate, the encoder target stays 48000, and the factor is 2, 4 and 8; the helper's own `audio-format` event confirmed the rate in every run. The helper was driven the way the app drives it (config JSON argument, `stop` on stdin), not through the app UI. Fold-bin readings, before → after, for 96 / 192 / 384 kHz: a 36 kHz tone (folds onto 12 kHz) **-22.25 → at most -115.32**, **-23.90 → at most -138.02**, **-24.28 → at most -111.54 dBFS**; a 42 kHz tone (folds onto 6 kHz) **-28.20 → at most -137.14**, **-30.40 → at most -135.09**, **-30.96 → at most -117.25 dBFS**. The after readings bound what the recordings hold and sit near each recording's floor; they are not the filter's leakage, which the design puts at -123 to -155 dBFS at these points. The 1 kHz reference reads -13.98 or -13.99 dBFS in every recording; each pre-fix recording shows its alias only in its own fold bin; every pre-fix reading matches the box average's frequency response to within 0.08 dB; the 384 kHz runs were repeated and agree to 0.01 dB. AAC track length is not used as evidence about the filter's delay or about frame accounting (tracks are whole 1024-sample AAC frames, and repeat runs of the same helper differ by up to six); that output frame counts do not drift is asserted by the helper's suite. Beyond these recordings the behaviour is covered by that suite (95 assertions, including a real-`AudioMixer` case) plus eleven mutation counter-proofs and a control that must stay green. **Check the Advanced tab's format list, and every endpoint, before concluding a machine cannot run this** — a device's current format is not its capability. **Not run:** microphone, webcam, tray menu, export, and every non-Windows platform. A/V sync was not eyeballed: against the output timeline this change puts a decimated stream 39 + 1/factor output frames late (0.81–0.82 ms at a 48 kHz output; the filter's own group delay is 40·factor source frames), below what watching can resolve, so it is asserted numerically in the suite instead. |+| 2026-09-12 | dev build, `fix/509-hud-session-prefs` @ `fbe461e9` plus uncommitted issue-509 patch | Windows 11 | Partial — Settings persistence only | Playwright drove two separate real Electron processes against one isolated userData profile. Recording toggles/device identity and versioned new-project appearance survived a full process restart; a project created before restart and another created after restart both materialized the chosen appearance on their first write. One test passed. This is scripted CDP state/UI evidence and does not count as OS-input capture proof. Native computer-use was unavailable, so source picker interaction, physical microphone/camera, record→edit, missing-source UI behavior, reset through visible controls, tray, export, macOS and Linux were skipped. |+| 2026-09-13 | source-built 1.11.0 integration, settings synchronization repair included | Windows 11, isolated profile | Partial — recording defaults pass | Real OS input verified recording preferences across restart, reset while RecStage remained mounted (previews stop and active source clears), factory defaults on new-project first write, unchanged existing projects and missing-source recovery. The test used the combined tree before PR splitting; it is not a second hardware pass on the split commit. See [recording-defaults-windows.md](recording-defaults-windows.md) for the screenshot, build context and exclusions. No STT, HUD pointer/tray, precise AV sync, other-platform or release-promotion claim. || 2026-09-13 | `6862a380` + microphone USB-label resolver patch; rebuilt release helpers | macOS 26.6.2, Apple Silicon, Shure MV7 | Partial | Real desktop HUD: selected explicit `Shure MV7 (14ed:1012)`, microphone on, system audio/camera off; started/stopped capture and reached saved editor (16.1 s). Logs confirm the rebuilt helper path and decorated label. Raw AAC is non-silent (mean -37.4 dBFS, peak -13.3 dBFS). Separately, the resolver matched the decorated label to the real AVFoundation MV7 ID. Default input was also MV7, so audio alone does not prove non-default routing. Listening, mixed/system audio, export, non-default-input recording and other platforms were not run; this is not full acceptance. |diff --git a/technical-documentation/testing/recording-defaults-windows.md b/technical-documentation/testing/recording-defaults-windows.mdnew file mode 100644index 000000000..63260a862--- /dev/null+++ b/technical-documentation/testing/recording-defaults-windows.md@@ -0,0 +1,17 @@+# Recording defaults: Windows validation++The settings implementation was tested on Windows 11 in a source-built OpenScreen 1.11.0 with an isolated profile on 2026-09-13. The tested integration included the settings changes and the GIF/workbench changes that were subsequently split into separate PRs. This record is not a claim that the split PR was run through a second complete hardware pass.++- Screen, system audio, microphone, webcam and combined recording opened in the editor. Playback, seeking and trimming were exercised with real OS input.+- Recording preferences survived a full process restart. An explicitly selected microphone was restored; the camera used the default device, so explicit camera-ID persistence is not claimed by this pass.+- Reset recording setup, with the recording page already mounted, immediately turned system audio, microphone and camera off, stopped both device previews and cleared the active source. This retest followed the fix for stale recording-page state.+- Resetting appearance defaults left six existing project files unchanged. A new project created through the UI used the factory wallpaper, shadow, padding, motion blur and cursor defaults on its first write.+- A selected test window was closed before restarting the app. The recording page remained unselected after source validation rather than selecting a different window. The durable descriptor was retained for future matching.++The screenshot shows the recording page after reset. No microphone/camera preview, device identity, private media or filesystem path is visible.++++The final synchronization repair passed targeted Vitest tests for recording preferences, RecStage, browser-shim events and LaunchWindow, both application/test TypeScript checks, scoped Biome checks, i18n validation and `npm run build-vite`.++Not covered: STT (helper absent), HUD pointer hit-testing, tray behavior, precise audiovisual synchronization, exhaustive editor operations, macOS/Linux hardware testing or release packaging. This is a scoped Windows result, not release promotion approval. Earlier failed attempts remain separate historical records.diff --git a/tests/e2e/settings-defaults.spec.ts b/tests/e2e/settings-defaults.spec.tsnew file mode 100644index 000000000..316e0dc2c--- /dev/null+++ b/tests/e2e/settings-defaults.spec.ts@@ -0,0 +1,118 @@+import { once } from "node:events";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { _electron as electron, expect, test } from "@playwright/test";+import { DEFAULT_PROJECT_APPEARANCE } from "../../src/lib/projectDefaults";++const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), "../..");+const MAIN_JS = path.join(ROOT, "dist-electron/main.js");+type ElectronApplication = Awaited<ReturnType<typeof electron.launch>>;+type ProjectResult = {+ success: boolean;+ document: { project: { id: string }; legacyEditor: Record<string, unknown> };+};++async function launch(userData: string, temp: string) {+ return electron.launch({+ args: [+ MAIN_JS,+ "--no-sandbox",+ "--enable-unsafe-swiftshader",+ "--lang=en-US",+ `--user-data-dir=${userData}`,+ ],+ env: {+ ...process.env,+ ELECTRON_USER_DATA_DIR: userData,+ TMPDIR: temp,+ TMP: temp,+ TEMP: temp,+ HEADLESS: process.env["HEADLESS"] ?? "true",+ },+ });+}++async function close(app: ElectronApplication) {+ const process = app.process();+ await Promise.race([app.close(), new Promise<void>((resolve) => setTimeout(resolve, 5_000))]);+ if (process.exitCode === null && process.signalCode === null) {+ process.kill("SIGKILL");+ await Promise.race([+ once(process, "close"),+ new Promise<void>((resolve) => setTimeout(resolve, 5_000)),+ ]);+ }+}++test("recording setup and new-project appearance survive a real Electron restart", async () => {+ const userData = fs.mkdtempSync(path.join(os.tmpdir(), "openscreen-settings-e2e-"));+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), "openscreen-settings-e2e-tmp-"));+ let app: ElectronApplication | null = null;+ try {+ app = await launch(userData, temp);+ const firstWindow = await app.firstWindow({ timeout: 60_000 });+ const custom = { ...DEFAULT_PROJECT_APPEARANCE, wallpaper: "#123456", padding: 17 };+ await firstWindow.evaluate(async (defaults) => {+ await window.electronAPI.setRecordingPrefs({+ micEnabled: true,+ micDeviceId: "persisted-mic",+ micDeviceName: "Persisted microphone",+ systemAudioEnabled: true,+ });+ await window.electronAPI.setProjectAppearanceDefaults(defaults);+ }, custom);+ const existing = await firstWindow.evaluate(() =>+ window.electronAPI.invokeNativeBridge<ProjectResult>({+ domain: "aiEdition",+ action: "document.create",+ payload: { title: "Before restart" },+ }),+ );+ expect(existing.ok).toBe(true);+ if (!existing.ok) throw new Error(existing.error.message);+ const existingId = existing.data?.document.project.id;+ expect(existing.data?.document.legacyEditor).toMatchObject({+ wallpaper: "#123456",+ padding: 17,+ });+ await close(app);+ app = null;++ app = await launch(userData, temp);+ const restartedWindow = await app.firstWindow({ timeout: 60_000 });+ const restored = await restartedWindow.evaluate(() => window.electronAPI.getAppSettings());+ expect(restored.recording).toMatchObject({+ micEnabled: true,+ micDeviceId: "persisted-mic",+ micDeviceName: "Persisted microphone",+ systemAudioEnabled: true,+ });+ expect(restored.appearance).toMatchObject({ custom: true, defaults: custom });++ const after = await restartedWindow.evaluate(async (oldId) => {+ const oldProject = await window.electronAPI.invokeNativeBridge<ProjectResult>({+ domain: "aiEdition",+ action: "document.get",+ payload: { projectId: oldId },+ });+ const fresh = await window.electronAPI.invokeNativeBridge<ProjectResult>({+ domain: "aiEdition",+ action: "document.create",+ payload: { title: "After restart" },+ });+ return { oldProject, fresh };+ }, existingId);+ expect(after.oldProject.ok).toBe(true);+ expect(after.fresh.ok).toBe(true);+ if (!after.oldProject.ok) throw new Error(after.oldProject.error.message);+ if (!after.fresh.ok) throw new Error(after.fresh.error.message);+ expect(after.oldProject.data.document.legacyEditor).toMatchObject({ padding: 17 });+ expect(after.fresh.data.document.legacyEditor).toMatchObject({ padding: 17 });+ } finally {+ if (app) await close(app);+ for (const directory of [userData, temp])+ fs.rmSync(directory, { recursive: true, force: true });+ }+});