Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(presets): store editor style presets as shareable files

Etienne Lescot9957e6d24904
diff --git a/electron/ai-edition/style-preset-service.test.ts b/electron/ai-edition/style-preset-service.test.ts
new file mode 100644
index 000000000..898beeee3
--- /dev/null
+++ b/electron/ai-edition/style-preset-service.test.ts
@@ -0,0 +1,209 @@
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { StylePresetAppearance } from "../../src/lib/ai-edition/stylePresets";
+import { StylePresetError, StylePresetService } from "./style-preset-service";
+
+const APPEARANCE: StylePresetAppearance = {
+ wallpaper: "#000000",
+ 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,
+ webcamBackgroundMode: "none",
+ webcamWallpaper: "/wallpapers/wallpaper1.jpg",
+ webcamBlurIntensity: 0.5,
+ cursor: { size: 3, smoothing: 0.67, motionBlur: 0.35, clickBounce: 2.5, clipToBounds: false },
+ cursorShow: true,
+ cursorAutoHide: false,
+ cursorTheme: "default",
+};
+
+let root: string;
+let dir: string;
+let service: StylePresetService;
+
+beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "style-presets-"));
+ // Not created up front: the service creates the folder lazily.
+ dir = path.join(root, "OpenScreen Presets");
+ service = new StylePresetService(dir);
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await fs.rm(root, { recursive: true, force: true });
+});
+
+async function expectCode(promise: Promise<unknown>, code: string) {
+ const error = await promise.then(
+ () => null,
+ (e: unknown) => e,
+ );
+ expect(error).toBeInstanceOf(StylePresetError);
+ expect((error as StylePresetError).code).toBe(code);
+}
+
+describe("StylePresetService", () => {
+ it("creates the folder lazily and lists nothing", async () => {
+ expect(await service.list()).toEqual([]);
+ expect((await fs.stat(dir)).isDirectory()).toBe(true);
+ });
+
+ it("creates a preset file named after the preset and lists it", async () => {
+ const created = await service.create(" Studio Look ", APPEARANCE);
+ expect(created).toMatchObject({
+ id: "Studio Look",
+ name: "Studio Look",
+ appearance: APPEARANCE,
+ });
+ expect(Number.isNaN(Date.parse(created.updatedAt))).toBe(false);
+ const raw = JSON.parse(
+ await fs.readFile(path.join(dir, "Studio Look.openscreenpreset"), "utf8"),
+ );
+ expect(raw).toMatchObject({
+ format: "openscreen-style-preset",
+ version: 1,
+ name: "Studio Look",
+ });
+ expect(await service.list()).toEqual([created]);
+ });
+
+ it("lists a dropped-in file, skips corrupt ones, and sorts by name ignoring case", async () => {
+ await service.create("beta", APPEARANCE);
+ await fs.writeFile(
+ path.join(dir, "shared.openscreenpreset"),
+ JSON.stringify({
+ format: "openscreen-style-preset",
+ version: 1,
+ name: "Alpha",
+ appearance: APPEARANCE,
+ }),
+ );
+ await fs.writeFile(path.join(dir, "broken.openscreenpreset"), "{ not json");
+ await fs.writeFile(
+ path.join(dir, "invalid.openscreenpreset"),
+ JSON.stringify({
+ format: "openscreen-style-preset",
+ version: 1,
+ name: "Bad",
+ appearance: {},
+ }),
+ );
+ await fs.writeFile(path.join(dir, "notes.txt"), "ignored");
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+
+ const listed = await service.list();
+
+ expect(listed.map((p) => [p.id, p.name])).toEqual([
+ ["shared", "Alpha"],
+ ["beta", "beta"],
+ ]);
+ expect(warn).toHaveBeenCalledTimes(2);
+ });
+
+ it("refuses a name already used by a file or by a preset, ignoring case", async () => {
+ await service.create("Studio", APPEARANCE);
+ await expectCode(service.create("studio", APPEARANCE), "NAME_TAKEN");
+ await fs.writeFile(
+ path.join(dir, "other-file.openscreenpreset"),
+ JSON.stringify({
+ format: "openscreen-style-preset",
+ version: 1,
+ name: "Shared",
+ appearance: APPEARANCE,
+ }),
+ );
+ await expectCode(service.create("SHARED", APPEARANCE), "NAME_TAKEN");
+ // A corrupt file still occupies its name on disk.
+ await fs.writeFile(path.join(dir, "Corrupt.openscreenpreset"), "nope");
+ vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ await expectCode(service.create("corrupt", APPEARANCE), "NAME_TAKEN");
+ });
+
+ it("rejects an invalid appearance before writing anything", async () => {
+ await expect(
+ service.create("Bad", { ...APPEARANCE, wallpaper: "file:///Users/alice/a.jpg" }),
+ ).rejects.toThrow(TypeError);
+ expect(await fs.readdir(dir).catch(() => [])).toEqual([]);
+ });
+
+ it("renames the file, and refuses a taken name", async () => {
+ const a = await service.create("One", APPEARANCE);
+ await service.create("Two", APPEARANCE);
+ await expectCode(service.rename(a.id, "two"), "NAME_TAKEN");
+
+ const renamed = await service.rename(a.id, "Three");
+ expect(renamed).toMatchObject({ id: "Three", name: "Three" });
+ expect((await fs.readdir(dir)).sort()).toEqual([
+ "Three.openscreenpreset",
+ "Two.openscreenpreset",
+ ]);
+ });
+
+ it("handles a case-only rename without losing the preset", async () => {
+ const created = await service.create("studio", APPEARANCE);
+ const renamed = await service.rename(created.id, "Studio");
+ expect(renamed).toMatchObject({ id: "Studio", name: "Studio", appearance: APPEARANCE });
+ expect(await fs.readdir(dir)).toEqual(["Studio.openscreenpreset"]);
+ });
+
+ it("updates the appearance and keeps the name", async () => {
+ const created = await service.create("Look", APPEARANCE);
+ const updated = await service.update(created.id, { ...APPEARANCE, padding: 10 });
+ expect(updated).toMatchObject({ id: "Look", name: "Look" });
+ expect(updated.appearance.padding).toBe(10);
+ await expectCode(service.update("missing", APPEARANCE), "NOT_FOUND");
+ });
+
+ it("deletes, tolerating a file that is already gone", async () => {
+ const created = await service.create("Gone", APPEARANCE);
+ await service.delete(created.id);
+ await service.delete(created.id);
+ expect(await service.list()).toEqual([]);
+ });
+
+ it("serialises concurrent creates of the same name", async () => {
+ const results = await Promise.allSettled([
+ service.create("Race", APPEARANCE),
+ service.create("race", APPEARANCE),
+ ]);
+ expect(results.map((r) => r.status).sort()).toEqual(["fulfilled", "rejected"]);
+ });
+
+ it("pathFor rejects traversal and separators and stays inside the folder", () => {
+ expect(service.pathFor("Look")).toBe(path.join(path.resolve(dir), "Look.openscreenpreset"));
+ for (const id of [
+ "",
+ ".",
+ "..",
+ "../x",
+ "a/b",
+ "a\\b",
+ "C:evil",
+ `x${String.fromCharCode(0)}y`,
+ ]) {
+ expect(() => service.pathFor(id)).toThrow(StylePresetError);
+ }
+ });
+
+ it("reveals the file when it exists and the folder otherwise", async () => {
+ const created = await service.create("Shown", APPEARANCE);
+ expect(await service.revealTarget(created.id)).toEqual({
+ kind: "file",
+ path: service.pathFor(created.id),
+ });
+ expect(await service.revealTarget("missing")).toEqual({
+ kind: "folder",
+ path: path.resolve(dir),
+ });
+ });
+});
diff --git a/electron/ai-edition/style-preset-service.ts b/electron/ai-edition/style-preset-service.ts
new file mode 100644
index 000000000..31935e8c0
--- /dev/null
+++ b/electron/ai-edition/style-preset-service.ts
@@ -0,0 +1,276 @@
+// StylePresetService — main-process owner of the user's style presets.
+// One `<name>.openscreenpreset` JSON per preset, in a folder the user can see (Documents/
+// OpenScreen Presets in production), so presets can be shared by copying files. The folder
+// is read on every `list`, which is what makes a file dropped into it show up.
+//
+// The directory is injected, like DocumentService's, so this module stays free of any
+// `electron` import. Format and validation live in src/lib/ai-edition/stylePresets.ts.
+
+import { randomUUID } from "node:crypto";
+import fs, { type FileHandle } from "node:fs/promises";
+import path from "node:path";
+import {
+ compareStylePresets,
+ parseStylePresetFile,
+ STYLE_PRESET_FILE_EXTENSION,
+ type StylePreset,
+ type StylePresetAppearance,
+ sanitizeStylePresetName,
+ serializeStylePresetFile,
+ stylePresetFileBaseName,
+} from "../../src/lib/ai-edition/stylePresets";
+
+export type StylePresetErrorCode = "NAME_TAKEN" | "NOT_FOUND" | "INVALID_ID";
+
+export class StylePresetError extends Error {
+ constructor(
+ public readonly code: StylePresetErrorCode,
+ message: string,
+ ) {
+ super(message);
+ this.name = "StylePresetError";
+ }
+}
+
+export interface StylePresetRevealTarget {
+ /** `file` when the preset exists; otherwise the (created) presets folder. */
+ kind: "file" | "folder";
+ path: string;
+}
+
+/**
+ * Local copy of document-service's `renameWithRetry`: Windows fails a rename onto a file an
+ * indexer, antivirus or backup agent holds open for a few milliseconds. Copied rather than
+ * imported because importing document-service drags the whole project schema along.
+ */
+async function renameWithRetry(from: string, to: string): Promise<void> {
+ const RETRYABLE = new Set(["EPERM", "EACCES", "EBUSY"]);
+ for (let attempt = 0; ; attempt++) {
+ try {
+ await fs.rename(from, to);
+ return;
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException)?.code ?? "";
+ if (attempt >= 5 || !RETRYABLE.has(code)) throw error;
+ await new Promise((resolve) => setTimeout(resolve, 10 * 2 ** attempt));
+ }
+ }
+}
+
+function isMissing(error: unknown): boolean {
+ return (error as NodeJS.ErrnoException)?.code === "ENOENT";
+}
+
+export class StylePresetService {
+ private readonly directory: string;
+ /**
+ * Every mutation runs through this one chain. Per instance, not per preset: a rename
+ * touches two files and a create has to see every name already taken, so two concurrent
+ * mutations of DIFFERENT presets can still collide. There is one shared instance in the
+ * main process for the same reason DocumentService has one.
+ */
+ private writeTail: Promise<void> = Promise.resolve();
+
+ constructor(directory: string) {
+ this.directory = path.resolve(directory);
+ }
+
+ get directoryPath(): string {
+ return this.directory;
+ }
+
+ async ensureDirectory(): Promise<void> {
+ await fs.mkdir(this.directory, { recursive: true });
+ }
+
+ /**
+ * The file behind a preset id. The id arrives from the renderer, so it has to be a plain
+ * base name — no separators, no `.`/`..`, no control characters, no `:` (a drive or an
+ * NTFS stream on Windows) — and the path it resolves to must still be in the folder.
+ */
+ pathFor(id: string): string {
+ if (
+ typeof id !== "string" ||
+ id === "" ||
+ id === "." ||
+ id === ".." ||
+ /[/\\:\p{Cc}]/u.test(id)
+ ) {
+ throw new StylePresetError("INVALID_ID", `Invalid style preset id: ${String(id)}`);
+ }
+ const filePath = path.resolve(this.directory, `${id}${STYLE_PRESET_FILE_EXTENSION}`);
+ if (path.dirname(filePath) !== this.directory) {
+ throw new StylePresetError("INVALID_ID", `Invalid style preset id: ${id}`);
+ }
+ return filePath;
+ }
+
+ async list(): Promise<StylePreset[]> {
+ await this.ensureDirectory();
+ return (await this.readEntries()).presets;
+ }
+
+ create(name: string, appearance: StylePresetAppearance): Promise<StylePreset> {
+ return this.serialise(async () => {
+ const cleanName = sanitizeStylePresetName(name);
+ // Validates before anything touches the disk.
+ const json = serializeStylePresetFile({ name: cleanName, appearance });
+ const id = stylePresetFileBaseName(cleanName);
+ await this.ensureDirectory();
+ this.assertNameFree(await this.readEntries(), id, cleanName);
+ await this.writeAtomic(this.pathFor(id), json);
+ return this.read(id);
+ });
+ }
+
+ rename(id: string, name: string): Promise<StylePreset> {
+ return this.serialise(async () => {
+ const current = await this.read(id);
+ const cleanName = sanitizeStylePresetName(name);
+ const nextId = stylePresetFileBaseName(cleanName);
+ this.assertNameFree(await this.readEntries(), nextId, cleanName, id);
+ const json = serializeStylePresetFile({ name: cleanName, appearance: current.appearance });
+ const from = this.pathFor(id);
+ const to = this.pathFor(nextId);
+ if (nextId === id) {
+ await this.writeAtomic(from, json);
+ } else if (nextId.toLowerCase() === id.toLowerCase()) {
+ // A case-only rename. On a case-insensitive disk (macOS, Windows by default) both
+ // names are the SAME file, so "write the new one, delete the old one" would delete
+ // the preset. Rewrite in place, then let rename change the case.
+ await this.writeAtomic(from, json);
+ await renameWithRetry(from, to);
+ } else {
+ await this.writeAtomic(to, json);
+ await fs.unlink(from).catch((error) => {
+ if (!isMissing(error)) throw error;
+ });
+ }
+ return this.read(nextId);
+ });
+ }
+
+ update(id: string, appearance: StylePresetAppearance): Promise<StylePreset> {
+ return this.serialise(async () => {
+ const current = await this.read(id);
+ await this.writeAtomic(
+ this.pathFor(id),
+ serializeStylePresetFile({ name: current.name, appearance }),
+ );
+ return this.read(id);
+ });
+ }
+
+ delete(id: string): Promise<void> {
+ return this.serialise(async () => {
+ await fs.unlink(this.pathFor(id)).catch((error) => {
+ if (!isMissing(error)) throw error;
+ });
+ });
+ }
+
+ /** What "Show in folder" should open. A preset deleted behind the list's back still
+ * opens its folder rather than nothing — `showItemInFolder` is silent on a missing file. */
+ async revealTarget(id: string): Promise<StylePresetRevealTarget> {
+ const filePath = this.pathFor(id);
+ try {
+ await fs.access(filePath);
+ return { kind: "file", path: filePath };
+ } catch {
+ await this.ensureDirectory();
+ return { kind: "folder", path: this.directory };
+ }
+ }
+
+ private async read(id: string): Promise<StylePreset> {
+ const filePath = this.pathFor(id);
+ let raw: string;
+ let mtime: Date;
+ try {
+ [raw, { mtime }] = await Promise.all([fs.readFile(filePath, "utf8"), fs.stat(filePath)]);
+ } catch (error) {
+ if (isMissing(error)) {
+ throw new StylePresetError("NOT_FOUND", `Style preset not found: ${id}`);
+ }
+ throw error;
+ }
+ const file = parseStylePresetFile(JSON.parse(raw));
+ return { id, name: file.name, updatedAt: mtime.toISOString(), appearance: file.appearance };
+ }
+
+ /** Every preset file's id (valid or not — it still occupies its name on disk) and every
+ * preset that parsed. A file that does not is skipped with a warning, never fatal. */
+ private async readEntries(): Promise<{ ids: string[]; presets: StylePreset[] }> {
+ let names: string[];
+ try {
+ names = await fs.readdir(this.directory);
+ } catch (error) {
+ if (isMissing(error)) return { ids: [], presets: [] };
+ throw error;
+ }
+ const ids: string[] = [];
+ const presets: StylePreset[] = [];
+ for (const name of names) {
+ // The temp files of an interrupted write end in `.tmp-…`, so they never match.
+ if (!name.endsWith(STYLE_PRESET_FILE_EXTENSION)) continue;
+ const id = name.slice(0, -STYLE_PRESET_FILE_EXTENSION.length);
+ ids.push(id);
+ try {
+ presets.push(await this.read(id));
+ } catch (error) {
+ console.warn(`[style-presets] skipping ${name}:`, error);
+ }
+ }
+ presets.sort(compareStylePresets);
+ return { ids, presets };
+ }
+
+ /** Taken when the file name is (ignoring case, as macOS and Windows do), or when another
+ * preset already carries the name — a shared file may sit under a different file name. */
+ private assertNameFree(
+ entries: { ids: string[]; presets: StylePreset[] },
+ id: string,
+ name: string,
+ exceptId?: string,
+ ): void {
+ const idKey = id.toLowerCase();
+ const nameKey = name.toLowerCase();
+ const taken =
+ entries.ids.some((other) => other !== exceptId && other.toLowerCase() === idKey) ||
+ entries.presets.some(
+ (preset) => preset.id !== exceptId && preset.name.toLowerCase() === nameKey,
+ );
+ if (taken) {
+ throw new StylePresetError("NAME_TAKEN", `A style preset named "${name}" already exists.`);
+ }
+ }
+
+ private serialise<T>(work: () => Promise<T>): Promise<T> {
+ // Chained on both settlements: one failed mutation must not cancel the next.
+ const run = this.writeTail.then(work, work);
+ this.writeTail = run.then(
+ () => undefined,
+ () => undefined,
+ );
+ return run;
+ }
+
+ /** Temp file + flush + rename, as DocumentService writes projects: a crash or a full disk
+ * mid-write leaves the previous preset intact rather than a truncated one. */
+ private async writeAtomic(filePath: string, contents: string): Promise<void> {
+ const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID()}`;
+ let handle: FileHandle | undefined;
+ try {
+ handle = await fs.open(tempPath, "w");
+ await handle.writeFile(contents, "utf8");
+ await handle.sync();
+ await handle.close();
+ handle = undefined;
+ await renameWithRetry(tempPath, filePath);
+ } catch (error) {
+ await handle?.close().catch(() => undefined);
+ await fs.unlink(tempPath).catch(() => undefined);
+ throw error;
+ }
+ }
+}
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index 2b464240f..17574ffa9 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -42,6 +42,7 @@ import type {
ProjectFileResult,
ProjectPathResult,
} from "../../src/native/contracts";
+import { PRODUCT_NAME } from "../about";
import {
compactSessionNow,
createSession,
@@ -56,6 +57,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 { StylePresetService } from "../ai-edition/style-preset-service";
import { AppSettingsStore } from "../app-settings";
import { isDiagnosticModeEnabled, mainLogBuffer } from "../diagnostics/main-log-buffer";
import { mainT } from "../i18n";
@@ -4589,6 +4591,12 @@ export function registerIpcHandlers(
exportDiagnosticFile(payload),
);
+ // Same one-instance rule: the service serialises its writes per instance. The folder is
+ // in Documents, not userData, because presets are files users are meant to find and share.
+ const stylePresets = new StylePresetService(
+ path.join(app.getPath("documents"), `${PRODUCT_NAME} Presets`),
+ );
+
// One instance each, not one per call. DocumentService serialises saves of a
// project through a per-INSTANCE queue (see its writeProject comment — this
// race destroyed two real project files), so a second instance means a second
@@ -4651,6 +4659,7 @@ export function registerIpcHandlers(
}
},
getAiEditionDocuments: () => aiEditionDocuments,
+ getStylePresets: () => stylePresets,
getAiEditionLlmConfig,
runAiEditionChat: (projectId, sessionId, message, document, sink) =>
runChat(projectId, sessionId, message, getAiEditionLlmConfig(), document, sink, {
diff --git a/electron/ipc/nativeBridge.presets.test.ts b/electron/ipc/nativeBridge.presets.test.ts
new file mode 100644
index 000000000..a04ec169c
--- /dev/null
+++ b/electron/ipc/nativeBridge.presets.test.ts
@@ -0,0 +1,144 @@
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { StylePresetAppearance } from "../../src/lib/ai-edition/stylePresets";
+import type { NativeBridgeResponse } from "../../src/native/contracts";
+import { StylePresetService } from "../ai-edition/style-preset-service";
+import { type NativeBridgeContext, registerNativeBridgeHandlers } from "./nativeBridge";
+
+const electron = vi.hoisted(() => ({
+ handle: vi.fn(),
+ showItemInFolder: vi.fn(),
+ openPath: vi.fn(async () => ""),
+}));
+vi.mock("electron", () => ({
+ app: { getAppPath: () => "", isPackaged: false },
+ ipcMain: { handle: electron.handle, removeHandler: vi.fn() },
+ shell: { showItemInFolder: electron.showItemInFolder, openPath: electron.openPath },
+}));
+// The bridge builds these at registration; none of them is under test here.
+vi.mock("../native-bridge/services/compositorViewService", () => ({
+ CompositorViewService: class {},
+}));
+vi.mock("../native-bridge/services/aiEditionService", () => ({
+ AiEditionService: class {},
+}));
+
+const APPEARANCE: StylePresetAppearance = {
+ wallpaper: "#000000",
+ 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,
+ webcamBackgroundMode: "none",
+ webcamWallpaper: "#ffffff",
+ webcamBlurIntensity: 0.5,
+ cursor: { size: 3, smoothing: 0.67, motionBlur: 0.35, clickBounce: 2.5, clipToBounds: false },
+ cursorShow: true,
+ cursorAutoHide: false,
+ cursorTheme: "default",
+};
+
+let root: string;
+let invoke: (request: unknown) => Promise<NativeBridgeResponse>;
+
+beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "bridge-presets-"));
+ const service = new StylePresetService(root);
+ electron.handle.mockClear();
+ electron.showItemInFolder.mockClear();
+ electron.openPath.mockClear();
+ registerNativeBridgeHandlers({
+ getPlatform: () => "darwin",
+ getAiEditionDocuments: () => ({}),
+ getAiEditionLlmConfig: () => ({}),
+ getStylePresets: () => service,
+ } as unknown as NativeBridgeContext);
+ const handler = electron.handle.mock.calls[0]?.[1] as (
+ event: unknown,
+ request: unknown,
+ ) => Promise<NativeBridgeResponse>;
+ invoke = (request) => handler({ sender: {} }, request);
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await fs.rm(root, { recursive: true, force: true });
+});
+
+describe("native bridge presets domain", () => {
+ it("creates and lists presets", async () => {
+ const created = await invoke({
+ domain: "presets",
+ action: "create",
+ payload: { name: "Studio", appearance: APPEARANCE },
+ });
+ expect(created).toMatchObject({ ok: true, data: { id: "Studio", name: "Studio" } });
+
+ const listed = await invoke({ domain: "presets", action: "list" });
+ expect(listed.ok && listed.data).toEqual([(created as { data: unknown }).data]);
+ });
+
+ it("reports a taken name as NAME_TAKEN", async () => {
+ const create = {
+ domain: "presets",
+ action: "create",
+ payload: { name: "Studio", appearance: APPEARANCE },
+ };
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ await invoke(create);
+ const again = await invoke({ ...create, payload: { name: "STUDIO", appearance: APPEARANCE } });
+ expect(again).toMatchObject({ ok: false, error: { code: "NAME_TAKEN", retryable: false } });
+ });
+
+ it("reports an invalid preset or id as INVALID_REQUEST and a missing one as NOT_FOUND", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ const bad = await invoke({
+ domain: "presets",
+ action: "create",
+ payload: { name: "Bad", appearance: { ...APPEARANCE, wallpaper: "https://x.test/a.png" } },
+ });
+ expect(bad).toMatchObject({ ok: false, error: { code: "INVALID_REQUEST" } });
+
+ const traversal = await invoke({
+ domain: "presets",
+ action: "delete",
+ payload: { id: "../x" },
+ });
+ expect(traversal).toMatchObject({ ok: false, error: { code: "INVALID_REQUEST" } });
+
+ const missing = await invoke({
+ domain: "presets",
+ action: "update",
+ payload: { id: "nope", appearance: APPEARANCE },
+ });
+ expect(missing).toMatchObject({ ok: false, error: { code: "NOT_FOUND" } });
+ });
+
+ it("reveals the preset file, or opens the folder when the file is gone", async () => {
+ await invoke({
+ domain: "presets",
+ action: "create",
+ payload: { name: "Shown", appearance: APPEARANCE },
+ });
+ expect(
+ await invoke({ domain: "presets", action: "reveal", payload: { id: "Shown" } }),
+ ).toMatchObject({
+ ok: true,
+ });
+ expect(electron.showItemInFolder).toHaveBeenCalledWith(
+ path.join(root, "Shown.openscreenpreset"),
+ );
+
+ await invoke({ domain: "presets", action: "reveal", payload: { id: "Gone" } });
+ expect(electron.openPath).toHaveBeenCalledWith(path.resolve(root));
+ });
+});
diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.ts
index 7b01e0b2f..71525feb9 100644
--- a/electron/ipc/nativeBridge.ts
+++ b/electron/ipc/nativeBridge.ts
@@ -1,4 +1,4 @@
-import { ipcMain } from "electron";
+import { ipcMain, shell } from "electron";
import type { AiEditionChatEvent } from "../../src/native/contracts";
import {
NATIVE_BRIDGE_CHANNEL,
@@ -12,6 +12,7 @@ import {
} from "../../src/native/contracts";
import type { ChatEventSink } from "../ai-edition/chat-service";
import type { DocumentService } from "../ai-edition/document-service";
+import { StylePresetError, type StylePresetService } from "../ai-edition/style-preset-service";
import {
type CursorTelemetryLoadResult,
TelemetryCursorAdapter,
@@ -53,6 +54,8 @@ export interface NativeBridgeContext {
*/
getNativeWindowHandle?: (sender: import("electron").WebContents) => Buffer | null;
getAiEditionDocuments: () => DocumentService;
+ /** The one shared style preset service — it serialises writes per instance. */
+ getStylePresets: () => StylePresetService;
getAiEditionLlmConfig: () => import("../ai-edition/llm-config-store").LlmConfigStore;
runAiEditionChat: (
projectId: string,
@@ -646,6 +649,50 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
}
}
+ case "presets": {
+ const action = request.action as string;
+ const presets = context.getStylePresets();
+ switch (request.action) {
+ case "list":
+ return createSuccessResponse(requestId, await presets.list());
+ case "create":
+ return createSuccessResponse(
+ requestId,
+ await presets.create(request.payload.name, request.payload.appearance),
+ );
+ case "rename":
+ return createSuccessResponse(
+ requestId,
+ await presets.rename(request.payload.id, request.payload.name),
+ );
+ case "update":
+ return createSuccessResponse(
+ requestId,
+ await presets.update(request.payload.id, request.payload.appearance),
+ );
+ case "delete":
+ await presets.delete(request.payload.id);
+ return createSuccessResponse(requestId, { success: true });
+ case "reveal": {
+ // The path is built here from the id, never taken from the renderer.
+ const target = await presets.revealTarget(request.payload.id);
+ if (target.kind === "file") {
+ shell.showItemInFolder(target.path);
+ } else {
+ const openError = await shell.openPath(target.path);
+ if (openError) throw new Error(openError);
+ }
+ return createSuccessResponse(requestId, { success: true });
+ }
+ default:
+ return createErrorResponse(
+ requestId,
+ "UNSUPPORTED_ACTION",
+ `Unsupported presets action: ${action}`,
+ );
+ }
+ }
+
default:
return createErrorResponse(
requestId,
@@ -659,6 +706,19 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
// the client to spin on them. The message keeps the reason but drops any
// absolute path — it crosses to the renderer and ends up in UI strings.
console.error(`native bridge ${domain}.${request.action} failed:`, error);
+ // Style preset failures the UI acts on keep their own code: a taken name is a
+ // prompt to pick another, not a crash. A TypeError there is a preset or name that
+ // failed validation, i.e. a bad request.
+ if (error instanceof StylePresetError) {
+ return createErrorResponse(
+ requestId,
+ error.code === "INVALID_ID" ? "INVALID_REQUEST" : error.code,
+ redactPaths(error.message),
+ );
+ }
+ if (domain === "presets" && error instanceof TypeError) {
+ return createErrorResponse(requestId, "INVALID_REQUEST", redactPaths(error.message));
+ }
return createErrorResponse(
requestId,
"INTERNAL_ERROR",
diff --git a/src/lib/ai-edition/stylePresets.test.ts b/src/lib/ai-edition/stylePresets.test.ts
new file mode 100644
index 000000000..7ba0a6492
--- /dev/null
+++ b/src/lib/ai-edition/stylePresets.test.ts
@@ -0,0 +1,188 @@
+import { describe, expect, it } from "vitest";
+import {
+ parseStylePresetAppearance,
+ parseStylePresetFile,
+ parseStylePresetWallpaper,
+ STYLE_PRESET_DATA_URL_MAX_LENGTH,
+ STYLE_PRESET_FORMAT,
+ STYLE_PRESET_FORMAT_VERSION,
+ type StylePresetAppearance,
+ sanitizeStylePresetName,
+ serializeStylePresetFile,
+ stylePresetFileBaseName,
+} from "./stylePresets";
+
+function appearance(overrides: Partial<StylePresetAppearance> = {}): StylePresetAppearance {
+ return {
+ wallpaper: "/wallpapers/wallpaper3.jpg",
+ aspectRatio: "16:9",
+ shadowIntensity: 0.2,
+ showBlur: false,
+ motionBlurAmount: 0.2,
+ borderRadius: 40,
+ padding: 50,
+ webcamLayoutPreset: "picture-in-picture",
+ webcamMaskShape: "circle",
+ webcamMirrored: true,
+ webcamReactiveZoom: true,
+ webcamSizePreset: 25,
+ webcamBackgroundMode: "blur",
+ webcamWallpaper: "#112233",
+ webcamBlurIntensity: 0.5,
+ cursor: { size: 3, smoothing: 0.67, motionBlur: 0.35, clickBounce: 2.5, clipToBounds: false },
+ cursorShow: true,
+ cursorAutoHide: false,
+ cursorTheme: "default",
+ ...overrides,
+ };
+}
+
+describe("parseStylePresetAppearance", () => {
+ it("accepts a complete appearance and drops unknown keys", () => {
+ const parsed = parseStylePresetAppearance({ ...appearance(), cropRegion: { x: 0 } });
+ expect(parsed).toEqual(appearance());
+ expect(parsed).not.toHaveProperty("cropRegion");
+ });
+
+ it("rejects a missing field instead of guessing a factory value", () => {
+ const { padding: _padding, ...rest } = appearance();
+ expect(() => parseStylePresetAppearance(rest)).toThrow(/padding/);
+ });
+
+ it("rejects out-of-range numbers, wrong types and unknown enum values", () => {
+ expect(() => parseStylePresetAppearance(appearance({ padding: 101 }))).toThrow(TypeError);
+ expect(() => parseStylePresetAppearance(appearance({ borderRadius: -1 }))).toThrow(
+ /borderRadius/,
+ );
+ expect(() => parseStylePresetAppearance(appearance({ webcamSizePreset: 5 }))).toThrow(
+ /webcamSizePreset/,
+ );
+ expect(() =>
+ parseStylePresetAppearance({ ...appearance(), shadowIntensity: Number.NaN }),
+ ).toThrow(/shadowIntensity/);
+ expect(() => parseStylePresetAppearance({ ...appearance(), showBlur: "yes" })).toThrow(
+ /showBlur/,
+ );
+ expect(() => parseStylePresetAppearance({ ...appearance(), webcamMaskShape: "star" })).toThrow(
+ /webcamMaskShape/,
+ );
+ expect(() => parseStylePresetAppearance({ ...appearance(), aspectRatio: "wide" })).toThrow(
+ /aspectRatio/,
+ );
+ expect(() =>
+ parseStylePresetAppearance({
+ ...appearance(),
+ cursor: { ...appearance().cursor, size: 11 },
+ }),
+ ).toThrow(/cursor\.size/);
+ });
+
+ it("falls back to the default cursor theme for an id this build does not ship", () => {
+ expect(
+ parseStylePresetAppearance(appearance({ cursorTheme: "theme-from-the-future" })).cursorTheme,
+ ).toBe("default");
+ });
+});
+
+describe("parseStylePresetWallpaper", () => {
+ it.each([
+ "#abc",
+ "#aabbccdd",
+ "rgb(10 20 30)",
+ "oklch(70% 0.1 200)",
+ "linear-gradient(90deg, #000 0%, #fff 100%)",
+ "repeating-conic-gradient(red 0 10deg, blue 10deg 20deg)",
+ "/wallpapers/wallpaper12.jpg",
+ "data:image/png;base64,iVBORw0KGgo=",
+ "data:image/jpeg;base64,/9j/4AAQ",
+ ])("accepts %s", (value) => {
+ expect(parseStylePresetWallpaper(value)).toBe(value);
+ });
+
+ it("normalises a legacy bundled file:// wallpaper to its canonical path", () => {
+ expect(
+ parseStylePresetWallpaper(
+ "file:///Applications/OpenScreen.app/Contents/Resources/wallpapers/wallpaper4.jpg",
+ ),
+ ).toBe("/wallpapers/wallpaper4.jpg");
+ });
+
+ it.each([
+ "file:///Users/alice/Pictures/beach.jpg",
+ "file:///C:/Users/alice/wallpapers/wallpaper1.jpg",
+ "/Users/alice/beach.jpg",
+ "C:\\Users\\alice\\beach.jpg",
+ "https://example.com/bg.png",
+ "http://example.com/bg.png",
+ "red",
+ "linear-gradient(url(file:///etc/passwd), #fff)",
+ "url(x), linear-gradient(#000, #fff)",
+ "data:image/svg+xml;base64,PHN2Zz4=",
+ "data:image/png,notbase64",
+ ])("rejects %s", (value) => {
+ expect(() => parseStylePresetWallpaper(value)).toThrow(TypeError);
+ });
+
+ it("rejects an oversized data URL with a clear message", () => {
+ const big = `data:image/png;base64,${"A".repeat(STYLE_PRESET_DATA_URL_MAX_LENGTH)}`;
+ expect(() => parseStylePresetWallpaper(big, "webcamWallpaper")).toThrow(
+ /webcamWallpaper image is too large/,
+ );
+ });
+});
+
+describe("preset names", () => {
+ it("trims, collapses whitespace and caps the length", () => {
+ expect(sanitizeStylePresetName(" My cool\n preset ")).toBe("My cool preset");
+ expect(Array.from(sanitizeStylePresetName("é".repeat(200)))).toHaveLength(80);
+ });
+
+ it("throws on an empty name", () => {
+ expect(() => sanitizeStylePresetName(" ")).toThrow(TypeError);
+ });
+
+ it("keeps Unicode but strips characters Windows refuses", () => {
+ expect(stylePresetFileBaseName('Démo 日本 <a>:"b"/c\\d|e?f*')).toBe("Démo 日本 abcdef");
+ expect(stylePresetFileBaseName("Trailing dots... ")).toBe("Trailing dots");
+ expect(stylePresetFileBaseName("tab\there")).toBe("tab here");
+ });
+
+ it("never produces a Windows reserved device name", () => {
+ expect(stylePresetFileBaseName("CON")).toBe("CON_");
+ expect(stylePresetFileBaseName("nul")).toBe("nul_");
+ expect(stylePresetFileBaseName("com1")).toBe("com1_");
+ expect(stylePresetFileBaseName("LPT9.txt")).toBe("LPT9.txt_");
+ expect(stylePresetFileBaseName("Console")).toBe("Console");
+ });
+
+ it("falls back to a placeholder when nothing survives stripping", () => {
+ expect(stylePresetFileBaseName("???")).toBe("Preset");
+ });
+});
+
+describe("preset file format", () => {
+ it("round-trips through serialize and parse", () => {
+ const text = serializeStylePresetFile({ name: " Studio ", appearance: appearance() });
+ const parsed = parseStylePresetFile(JSON.parse(text));
+ expect(parsed).toEqual({
+ format: STYLE_PRESET_FORMAT,
+ version: STYLE_PRESET_FORMAT_VERSION,
+ name: "Studio",
+ appearance: appearance(),
+ });
+ });
+
+ it("rejects other formats and future versions", () => {
+ expect(() => parseStylePresetFile({ name: "x", appearance: appearance() })).toThrow(
+ /Not an OpenScreen style preset/,
+ );
+ expect(() =>
+ parseStylePresetFile({
+ format: STYLE_PRESET_FORMAT,
+ version: 2,
+ name: "x",
+ appearance: appearance(),
+ }),
+ ).toThrow(/version 2/);
+ });
+});
diff --git a/src/lib/ai-edition/stylePresets.ts b/src/lib/ai-edition/stylePresets.ts
new file mode 100644
index 000000000..968645fae
--- /dev/null
+++ b/src/lib/ai-edition/stylePresets.ts
@@ -0,0 +1,326 @@
+// Style presets — reusable editor appearance, one JSON file per preset.
+//
+// Imported by the main process (electron/ai-edition/style-preset-service.ts), so this
+// module stays main-process safe: relative imports only, and only TYPE imports from
+// renderer modules (they are erased before anything runs). The renderer half — reading a
+// preset out of the editor settings and patching it back in — is stylePresetsEditor.ts.
+//
+// A preset is the project's LOOK, never its content: nothing here depends on the footage
+// (crop, webcam framing or position, audio gain, captions, timeline). Such a preset can be
+// applied to any project, and shared as a file, without dragging one recording's framing
+// into another.
+
+import type {
+ CursorVisualSettings,
+ WebcamBackgroundMode,
+ WebcamLayoutPreset,
+ WebcamMaskShape,
+ WebcamSizePreset,
+} from "../../components/video-editor/types";
+import { type AspectRatio, isAspectRatio } from "../../utils/aspectRatioUtils";
+import { CURSOR_THEME_IDS, DEFAULT_CURSOR_THEME_ID } from "../cursor/cursorThemes";
+
+export const STYLE_PRESET_FILE_EXTENSION = ".openscreenpreset";
+export const STYLE_PRESET_FORMAT = "openscreen-style-preset";
+export const STYLE_PRESET_FORMAT_VERSION = 1;
+export const STYLE_PRESET_NAME_MAX_LENGTH = 80;
+/** Characters, not bytes: a 15 MB base64 image is ~11 MB decoded, far past any wallpaper. */
+export const STYLE_PRESET_DATA_URL_MAX_LENGTH = 15 * 1024 * 1024;
+/** Colours and gradients are CSS text; anything this long is not one a user typed. */
+const CSS_WALLPAPER_MAX_LENGTH = 10_000;
+
+/** The appearance fields of `EditorSettingsSnapshot`, in the snapshot's own shape. */
+export interface StylePresetAppearance {
+ wallpaper: string;
+ aspectRatio: AspectRatio;
+ shadowIntensity: number;
+ showBlur: boolean;
+ motionBlurAmount: number;
+ borderRadius: number;
+ padding: number;
+ webcamLayoutPreset: WebcamLayoutPreset;
+ webcamMaskShape: WebcamMaskShape;
+ webcamMirrored: boolean;
+ webcamReactiveZoom: boolean;
+ webcamSizePreset: WebcamSizePreset;
+ webcamBackgroundMode: WebcamBackgroundMode;
+ webcamWallpaper: string;
+ webcamBlurIntensity: number;
+ /** `autoHide` is left out: the snapshot's source of truth for it is `cursorAutoHide`. */
+ cursor: Omit<CursorVisualSettings, "autoHide">;
+ cursorShow: boolean;
+ cursorAutoHide: boolean;
+ cursorTheme: string;
+}
+
+export interface StylePreset {
+ /** The file's base name, without the extension. */
+ id: string;
+ name: string;
+ /** ISO timestamp of the file's last modification. */
+ updatedAt: string;
+ appearance: StylePresetAppearance;
+}
+
+export interface StylePresetFile {
+ format: typeof STYLE_PRESET_FORMAT;
+ version: typeof STYLE_PRESET_FORMAT_VERSION;
+ name: string;
+ appearance: StylePresetAppearance;
+}
+
+// Local copies of renderer enums: the modules that own them import through `@/`, which
+// the main process cannot load. `satisfies` keeps each list from naming a value the type
+// does not have; a value ADDED to the type still has to be added here.
+const WEBCAM_LAYOUT_PRESETS = [
+ "picture-in-picture",
+ "vertical-stack",
+ "dual-frame",
+ "no-webcam",
+] as const satisfies readonly WebcamLayoutPreset[];
+const WEBCAM_MASK_SHAPES = [
+ "rectangle",
+ "circle",
+ "square",
+ "rounded",
+] as const satisfies readonly WebcamMaskShape[];
+const WEBCAM_BACKGROUND_MODES = [
+ "none",
+ "transparent",
+ "blur",
+ "custom",
+] as const satisfies readonly WebcamBackgroundMode[];
+
+// Bounds are the editor sliders' (RightPanes.tsx), in stored units. `getEditorSettings`
+// only clamps two of these, so a preset is the stricter gate: a value no slider can
+// produce is a hand-edited file, and it is refused rather than applied.
+const NUMBER_RANGES = {
+ shadowIntensity: [0, 1],
+ motionBlurAmount: [0, 1],
+ borderRadius: [0, 64],
+ padding: [0, 100],
+ webcamSizePreset: [10, 50],
+ webcamBlurIntensity: [0, 1],
+} as const;
+const CURSOR_NUMBER_RANGES = {
+ size: [0.5, 10],
+ smoothing: [0, 1],
+ motionBlur: [0, 1],
+ clickBounce: [0, 5],
+} as const;
+
+type Fields = Record<string, unknown>;
+
+function isRecord(value: unknown): value is Fields {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function readNumber(
+ source: Fields,
+ key: string,
+ [min, max]: readonly [number, number],
+ at = "",
+): number {
+ const value = source[key];
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {
+ throw new TypeError(`Style preset ${at}${key} must be a number between ${min} and ${max}.`);
+ }
+ return value;
+}
+
+function readBoolean(source: Fields, key: string, at = ""): boolean {
+ const value = source[key];
+ if (typeof value !== "boolean") {
+ throw new TypeError(`Style preset ${at}${key} must be true or false.`);
+ }
+ return value;
+}
+
+function readEnum<T extends string>(source: Fields, key: string, allowed: readonly T[]): T {
+ const value = source[key];
+ if (typeof value !== "string" || !(allowed as readonly string[]).includes(value)) {
+ throw new TypeError(`Style preset ${key} must be one of: ${allowed.join(", ")}.`);
+ }
+ return value as T;
+}
+
+const HEX_COLOR_RE = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
+const COLOR_FUNCTION_RE = /^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\(.*\)$/i;
+const GRADIENT_RE = /^(?:repeating-)?(?:linear|radial|conic)-gradient\(.*\)$/i;
+const BUNDLED_WALLPAPER_RE = /^\/wallpapers\/wallpaper\d+\.jpg$/;
+const DATA_URL_RE = /^data:image\/(?:png|jpeg);base64,[A-Za-z0-9+/]+={0,2}$/;
+// Same pattern as projectPersistence.ts: only the known install layouts (packaged
+// resources/[assets/]wallpapers, dev public/wallpapers), so a user's own file under some
+// "wallpapers" folder is not mistaken for a bundled one.
+const LEGACY_FILE_WALLPAPER_RE =
+ /^file:\/\/.*?\/(?:resources\/(?:assets\/)?|public\/)wallpapers\/(wallpaper\d+\.jpg)$/i;
+
+/**
+ * Validates one wallpaper value and returns it in canonical form.
+ *
+ * A preset is a file people pass around, so the wallpaper is the field that could reach
+ * outside it: a `file://` or absolute path names something on the author's disk (or probes
+ * the reader's), and an `http(s)` URL makes applying a preset a network request. Only
+ * self-contained values pass — CSS colours and gradients, the bundled images, and inline
+ * PNG/JPEG data. A CSS value that smuggles a `url(` is refused for the same reason.
+ */
+export function parseStylePresetWallpaper(value: unknown, key = "wallpaper"): string {
+ if (typeof value !== "string") {
+ throw new TypeError(`Style preset ${key} must be a string.`);
+ }
+ if (value.startsWith("data:")) {
+ if (value.length > STYLE_PRESET_DATA_URL_MAX_LENGTH) {
+ throw new TypeError(
+ `Style preset ${key} image is too large (${value.length} characters; the limit is ${STYLE_PRESET_DATA_URL_MAX_LENGTH}).`,
+ );
+ }
+ if (!DATA_URL_RE.test(value)) {
+ throw new TypeError(`Style preset ${key} image must be a base64 PNG or JPEG data URL.`);
+ }
+ return value;
+ }
+ const legacy = LEGACY_FILE_WALLPAPER_RE.exec(value);
+ if (legacy) return `/wallpapers/${legacy[1].toLowerCase()}`;
+ if (BUNDLED_WALLPAPER_RE.test(value)) return value;
+ const trimmed = value.trim();
+ const isCss =
+ HEX_COLOR_RE.test(trimmed) || COLOR_FUNCTION_RE.test(trimmed) || GRADIENT_RE.test(trimmed);
+ if (isCss && trimmed.length <= CSS_WALLPAPER_MAX_LENGTH && !/url\(/i.test(trimmed)) {
+ return trimmed;
+ }
+ throw new TypeError(
+ `Style preset ${key} must be a colour, a gradient, a bundled wallpaper or an embedded PNG/JPEG image.`,
+ );
+}
+
+/**
+ * Strict validation of a preset's appearance.
+ *
+ * Every field is required — format version 1 is only ever written whole by
+ * `serializeStylePresetFile`, so a missing field is a damaged or hand-made file, and
+ * guessing a factory value for it would apply something the author never chose. The one
+ * lenient field is `cursorTheme`: themes come and go between builds, so an id this build
+ * does not ship falls back to the default cursor instead of rejecting a preset that is
+ * otherwise sound (the editor does the same when it renders one). Unknown extra keys are
+ * dropped.
+ */
+export function parseStylePresetAppearance(value: unknown): StylePresetAppearance {
+ if (!isRecord(value)) {
+ throw new TypeError("Style preset appearance must be an object.");
+ }
+ if (!isAspectRatio(value.aspectRatio)) {
+ throw new TypeError('Style preset aspectRatio must be "W:H" or "native".');
+ }
+ const cursor = value.cursor;
+ if (!isRecord(cursor)) {
+ throw new TypeError("Style preset cursor must be an object.");
+ }
+ if (typeof value.cursorTheme !== "string") {
+ throw new TypeError("Style preset cursorTheme must be a string.");
+ }
+ return {
+ wallpaper: parseStylePresetWallpaper(value.wallpaper),
+ aspectRatio: value.aspectRatio,
+ shadowIntensity: readNumber(value, "shadowIntensity", NUMBER_RANGES.shadowIntensity),
+ showBlur: readBoolean(value, "showBlur"),
+ motionBlurAmount: readNumber(value, "motionBlurAmount", NUMBER_RANGES.motionBlurAmount),
+ borderRadius: readNumber(value, "borderRadius", NUMBER_RANGES.borderRadius),
+ padding: readNumber(value, "padding", NUMBER_RANGES.padding),
+ webcamLayoutPreset: readEnum(value, "webcamLayoutPreset", WEBCAM_LAYOUT_PRESETS),
+ webcamMaskShape: readEnum(value, "webcamMaskShape", WEBCAM_MASK_SHAPES),
+ webcamMirrored: readBoolean(value, "webcamMirrored"),
+ webcamReactiveZoom: readBoolean(value, "webcamReactiveZoom"),
+ webcamSizePreset: readNumber(value, "webcamSizePreset", NUMBER_RANGES.webcamSizePreset),
+ webcamBackgroundMode: readEnum(value, "webcamBackgroundMode", WEBCAM_BACKGROUND_MODES),
+ webcamWallpaper: parseStylePresetWallpaper(value.webcamWallpaper, "webcamWallpaper"),
+ webcamBlurIntensity: readNumber(
+ value,
+ "webcamBlurIntensity",
+ NUMBER_RANGES.webcamBlurIntensity,
+ ),
+ cursor: {
+ size: readNumber(cursor, "size", CURSOR_NUMBER_RANGES.size, "cursor."),
+ smoothing: readNumber(cursor, "smoothing", CURSOR_NUMBER_RANGES.smoothing, "cursor."),
+ motionBlur: readNumber(cursor, "motionBlur", CURSOR_NUMBER_RANGES.motionBlur, "cursor."),
+ clickBounce: readNumber(cursor, "clickBounce", CURSOR_NUMBER_RANGES.clickBounce, "cursor."),
+ clipToBounds: readBoolean(cursor, "clipToBounds", "cursor."),
+ },
+ cursorShow: readBoolean(value, "cursorShow"),
+ cursorAutoHide: readBoolean(value, "cursorAutoHide"),
+ cursorTheme: CURSOR_THEME_IDS.has(value.cursorTheme)
+ ? value.cursorTheme
+ : DEFAULT_CURSOR_THEME_ID,
+ };
+}
+
+/** Trims, collapses inner whitespace and caps the length. Throws on an empty result. */
+export function sanitizeStylePresetName(name: string): string {
+ const collapsed = (typeof name === "string" ? name : "").replace(/\s+/g, " ").trim();
+ if (!collapsed) {
+ throw new TypeError("Style preset name must not be empty.");
+ }
+ // By code point, so the cap never splits a surrogate pair in half.
+ return Array.from(collapsed).slice(0, STYLE_PRESET_NAME_MAX_LENGTH).join("").trim();
+}
+
+const WINDOWS_RESERVED_NAME_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
+
+/**
+ * A file base name that is valid on Windows, macOS and Linux alike.
+ *
+ * Unicode stays — a preset called "Démo 日本" is called that on disk too. What goes is
+ * what Windows refuses (`<>:"/\|?*`, control characters, trailing dots and spaces), and a
+ * reserved device name gets a suffix so it no longer is one. The same rules apply on every
+ * platform because the file is meant to travel: a name accepted on macOS must not become
+ * uncopyable on a colleague's PC.
+ */
+export function stylePresetFileBaseName(name: string): string {
+ const stripped = sanitizeStylePresetName(name)
+ .replace(/[<>:"/\\|?*\p{Cc}]/gu, "")
+ .replace(/\s+/g, " ")
+ .trim()
+ .replace(/[. ]+$/, "");
+ const base = stripped || "Preset";
+ return WINDOWS_RESERVED_NAME_RE.test(base) ? `${base}_` : base;
+}
+
+/** List order: by name, ignoring case and accents, then by id so ties are stable. */
+export function compareStylePresets(a: StylePreset, b: StylePreset): number {
+ return (
+ a.name.localeCompare(b.name, undefined, { sensitivity: "base" }) || a.id.localeCompare(b.id)
+ );
+}
+
+export function serializeStylePresetFile(input: {
+ name: string;
+ appearance: StylePresetAppearance;
+}): string {
+ const file: StylePresetFile = {
+ format: STYLE_PRESET_FORMAT,
+ version: STYLE_PRESET_FORMAT_VERSION,
+ name: sanitizeStylePresetName(input.name),
+ appearance: parseStylePresetAppearance(input.appearance),
+ };
+ return `${JSON.stringify(file, null, 2)}\n`;
+}
+
+/** Validates a parsed preset file (the JSON value, not the text). */
+export function parseStylePresetFile(json: unknown): StylePresetFile {
+ if (!isRecord(json) || json.format !== STYLE_PRESET_FORMAT) {
+ throw new TypeError("Not an OpenScreen style preset file.");
+ }
+ if (json.version !== STYLE_PRESET_FORMAT_VERSION) {
+ throw new TypeError(
+ `Unsupported style preset version ${String(json.version)} (this build reads version ${STYLE_PRESET_FORMAT_VERSION}).`,
+ );
+ }
+ if (typeof json.name !== "string") {
+ throw new TypeError("Style preset name must be a string.");
+ }
+ return {
+ format: STYLE_PRESET_FORMAT,
+ version: STYLE_PRESET_FORMAT_VERSION,
+ name: sanitizeStylePresetName(json.name),
+ appearance: parseStylePresetAppearance(json.appearance),
+ };
+}
diff --git a/src/lib/ai-edition/stylePresetsEditor.test.ts b/src/lib/ai-edition/stylePresetsEditor.test.ts
new file mode 100644
index 000000000..338aaa339
--- /dev/null
+++ b/src/lib/ai-edition/stylePresetsEditor.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from "vitest";
+import { createEmptyDocument } from "./schema";
+import {
+ DEFAULT_EDITOR_SETTINGS,
+ type EditorSettingsSnapshot,
+ getEditorSettings,
+ patchEditorSettings,
+} from "./store/editorSettings";
+import { parseStylePresetAppearance } from "./stylePresets";
+import {
+ factoryStylePresetAppearance,
+ stylePresetAppearanceFromSettings,
+ stylePresetPatch,
+} from "./stylePresetsEditor";
+
+const EXCLUDED_KEYS = [
+ "cropRegion",
+ "webcamCropRegion",
+ "webcamCropPan",
+ "webcamPosition",
+ "audioGainDb",
+ "autoFocusAll",
+] as const;
+
+function styledSettings(): EditorSettingsSnapshot {
+ return {
+ ...DEFAULT_EDITOR_SETTINGS,
+ wallpaper: "linear-gradient(90deg, #000, #fff)",
+ aspectRatio: "9:16",
+ shadowIntensity: 0.8,
+ showBlur: true,
+ motionBlurAmount: 0.6,
+ borderRadius: 12,
+ padding: 20,
+ webcamLayoutPreset: "dual-frame",
+ webcamMaskShape: "rounded",
+ webcamMirrored: true,
+ webcamReactiveZoom: false,
+ webcamSizePreset: 40,
+ webcamBackgroundMode: "custom",
+ webcamWallpaper: "#123456",
+ webcamBlurIntensity: 0.9,
+ cursor: { size: 5, smoothing: 0.1, motionBlur: 0.9, clickBounce: 4, clipToBounds: true },
+ cursorShow: false,
+ cursorAutoHide: true,
+ cursorTheme: "default",
+ };
+}
+
+describe("stylePresetsEditor", () => {
+ it("derives a valid factory appearance from the default settings", () => {
+ const factory = factoryStylePresetAppearance();
+ expect(parseStylePresetAppearance(factory)).toEqual(factory);
+ expect(factory.padding).toBe(DEFAULT_EDITOR_SETTINGS.padding);
+ expect(factory).not.toHaveProperty("cropRegion");
+ });
+
+ it("copies the cursor rather than sharing it", () => {
+ const settings = styledSettings();
+ const appearance = stylePresetAppearanceFromSettings(settings);
+ appearance.cursor.size = 9;
+ expect(settings.cursor.size).toBe(5);
+ expect(appearance.cursor).not.toHaveProperty("autoHide");
+ });
+
+ it("round-trips settings -> appearance -> patch without touching excluded fields", () => {
+ const styled = styledSettings();
+ const appearance = stylePresetAppearanceFromSettings(styled);
+
+ // A project with its own footage-dependent state, still on the factory look.
+ const base = patchEditorSettings(createEmptyDocument({ projectId: "proj_a", title: "A" }), {
+ cropRegion: { x: 0.1, y: 0.1, width: 0.5, height: 0.5 },
+ webcamPosition: { cx: 0.2, cy: 0.8 },
+ audioGainDb: 6,
+ autoFocusAll: true,
+ });
+ const before = getEditorSettings(base);
+
+ const after = getEditorSettings(patchEditorSettings(base, stylePresetPatch(appearance)));
+
+ expect(stylePresetAppearanceFromSettings(after)).toEqual(appearance);
+ for (const key of EXCLUDED_KEYS) {
+ expect(after[key]).toEqual(before[key]);
+ }
+ });
+});
diff --git a/src/lib/ai-edition/stylePresetsEditor.ts b/src/lib/ai-edition/stylePresetsEditor.ts
new file mode 100644
index 000000000..13dac8069
--- /dev/null
+++ b/src/lib/ai-edition/stylePresetsEditor.ts
@@ -0,0 +1,86 @@
+// Renderer half of style presets: between the editor settings snapshot and a preset's
+// appearance. The file format and its validation live in stylePresets.ts, which the main
+// process shares.
+
+import {
+ DEFAULT_EDITOR_SETTINGS,
+ type EditorSettingsPatch,
+ type EditorSettingsSnapshot,
+} from "@/lib/ai-edition/store/editorSettings";
+import type { StylePresetAppearance } from "@/lib/ai-edition/stylePresets";
+
+/** The built-in look every new project starts from. Never a file, so never an id on disk
+ * either: file ids are base names, and this one is reserved for the list's first entry. */
+export const FACTORY_STYLE_PRESET_ID = "openscreen-factory";
+
+/** Copies the appearance fields out of a settings snapshot — nothing footage-dependent. */
+export function stylePresetAppearanceFromSettings(
+ settings: EditorSettingsSnapshot,
+): StylePresetAppearance {
+ 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,
+ webcamBackgroundMode: settings.webcamBackgroundMode,
+ webcamWallpaper: settings.webcamWallpaper,
+ webcamBlurIntensity: settings.webcamBlurIntensity,
+ cursor: {
+ size: settings.cursor.size,
+ smoothing: settings.cursor.smoothing,
+ motionBlur: settings.cursor.motionBlur,
+ clickBounce: settings.cursor.clickBounce,
+ clipToBounds: settings.cursor.clipToBounds,
+ },
+ cursorShow: settings.cursorShow,
+ cursorAutoHide: settings.cursorAutoHide,
+ cursorTheme: settings.cursorTheme,
+ };
+}
+
+export function factoryStylePresetAppearance(): StylePresetAppearance {
+ return stylePresetAppearanceFromSettings(DEFAULT_EDITOR_SETTINGS);
+}
+
+/**
+ * The whole preset as ONE settings patch, so `useEditorSettings().set(patch)` applies it as
+ * a single undo step.
+ *
+ * `EditorSettingsPatch` has no top-level `cursorTheme` or `cursorShow`: both travel inside
+ * `cursor` as `theme` and `show`. Auto-hide is written both ways (`cursor.autoHide` and
+ * `cursorAutoHide`) because `nextLegacy` accepts either and they land on the same key.
+ */
+export function stylePresetPatch(appearance: StylePresetAppearance): EditorSettingsPatch {
+ return {
+ wallpaper: appearance.wallpaper,
+ aspectRatio: appearance.aspectRatio,
+ shadowIntensity: appearance.shadowIntensity,
+ showBlur: appearance.showBlur,
+ motionBlurAmount: appearance.motionBlurAmount,
+ borderRadius: appearance.borderRadius,
+ padding: appearance.padding,
+ webcamLayoutPreset: appearance.webcamLayoutPreset,
+ webcamMaskShape: appearance.webcamMaskShape,
+ webcamMirrored: appearance.webcamMirrored,
+ webcamReactiveZoom: appearance.webcamReactiveZoom,
+ webcamSizePreset: appearance.webcamSizePreset,
+ webcamBackgroundMode: appearance.webcamBackgroundMode,
+ webcamWallpaper: appearance.webcamWallpaper,
+ webcamBlurIntensity: appearance.webcamBlurIntensity,
+ cursor: {
+ ...appearance.cursor,
+ theme: appearance.cursorTheme,
+ show: appearance.cursorShow,
+ autoHide: appearance.cursorAutoHide,
+ },
+ cursorAutoHide: appearance.cursorAutoHide,
+ };
+}
diff --git a/src/native/browserShim.presets.test.ts b/src/native/browserShim.presets.test.ts
new file mode 100644
index 000000000..1b7d6d070
--- /dev/null
+++ b/src/native/browserShim.presets.test.ts
@@ -0,0 +1,90 @@
+// @vitest-environment jsdom
+// The shim keeps presets in localStorage, so this needs a DOM.
+import { beforeAll, beforeEach, describe, expect, it } from "vitest";
+import type { StylePresetAppearance } from "@/lib/ai-edition/stylePresets";
+import { installBrowserShims } from "./browserShim";
+import {
+ isStylePresetNameTakenError,
+ NativeBridgeRequestError,
+ nativeBridgeClient,
+} from "./client";
+
+const APPEARANCE: StylePresetAppearance = {
+ wallpaper: "#000000",
+ 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,
+ webcamBackgroundMode: "none",
+ webcamWallpaper: "#ffffff",
+ webcamBlurIntensity: 0.5,
+ cursor: { size: 3, smoothing: 0.67, motionBlur: 0.35, clickBounce: 2.5, clipToBounds: false },
+ cursorShow: true,
+ cursorAutoHide: false,
+ cursorTheme: "default",
+};
+
+const presets = nativeBridgeClient.presets;
+
+beforeAll(() => {
+ window.history.replaceState(null, "", "/?browser");
+ installBrowserShims();
+});
+beforeEach(() => {
+ localStorage.clear();
+});
+
+async function rejection(promise: Promise<unknown>): Promise<unknown> {
+ return promise.then(
+ () => null,
+ (error: unknown) => error,
+ );
+}
+
+describe("browserShim presets", () => {
+ it("creates, lists sorted by name, updates and deletes", async () => {
+ const b = await presets.create(" beta ", APPEARANCE);
+ const a = await presets.create("Alpha", APPEARANCE);
+ expect(b).toMatchObject({ id: "beta", name: "beta" });
+ expect((await presets.list()).map((p) => p.name)).toEqual(["Alpha", "beta"]);
+
+ const updated = await presets.update(a.id, { ...APPEARANCE, padding: 5 });
+ expect(updated.appearance.padding).toBe(5);
+
+ expect(await presets.delete(b.id)).toEqual({ success: true });
+ expect((await presets.list()).map((p) => p.id)).toEqual(["Alpha"]);
+ expect(await presets.reveal(a.id)).toEqual({ success: true });
+ });
+
+ it("rejects a taken name with NAME_TAKEN on create and rename", async () => {
+ const one = await presets.create("One", APPEARANCE);
+ await presets.create("Two", APPEARANCE);
+
+ const onCreate = await rejection(presets.create("one", APPEARANCE));
+ expect(onCreate).toBeInstanceOf(NativeBridgeRequestError);
+ expect(isStylePresetNameTakenError(onCreate)).toBe(true);
+
+ expect(isStylePresetNameTakenError(await rejection(presets.rename(one.id, "TWO")))).toBe(true);
+
+ const renamed = await presets.rename(one.id, "Three");
+ expect(renamed).toMatchObject({ id: "Three", name: "Three" });
+ expect((await presets.list()).map((p) => p.id)).toEqual(["Three", "Two"]);
+ });
+
+ it("reports invalid input and missing presets with the bridge's codes", async () => {
+ const invalid = await rejection(
+ presets.create("Bad", { ...APPEARANCE, wallpaper: "file:///Users/alice/a.jpg" }),
+ );
+ expect(invalid).toMatchObject({ code: "INVALID_REQUEST" });
+ expect(await rejection(presets.update("missing", APPEARANCE))).toMatchObject({
+ code: "NOT_FOUND",
+ });
+ });
+});
diff --git a/src/native/browserShim.ts b/src/native/browserShim.ts
index 73686a113..c157a1927 100644
--- a/src/native/browserShim.ts
+++ b/src/native/browserShim.ts
@@ -5,7 +5,15 @@
import { PROVIDER_DEFINITIONS } from "../../electron/ai-edition/provider-registry";
import { axcutSchemaVersion, migrateRawDocumentToCurrent } from "../lib/ai-edition/schema";
-import { nativeBridgeClient as realClient } from "./client";
+import {
+ compareStylePresets,
+ parseStylePresetAppearance,
+ type StylePreset,
+ type StylePresetAppearance,
+ sanitizeStylePresetName,
+ stylePresetFileBaseName,
+} from "../lib/ai-edition/stylePresets";
+import { NativeBridgeRequestError, nativeBridgeClient as realClient } from "./client";
function detectBrowserMode(): boolean {
if (typeof window === "undefined") return false;
@@ -374,6 +382,59 @@ function createShimBridgeClient() {
}
return m;
};
+ // Style presets: localStorage stands in for the presets folder, keyed by the same file
+ // base name the real service would use, and re-read on every call as `list` re-reads
+ // the folder. Failures reject with the same `NativeBridgeRequestError` codes the real
+ // bridge returns, so the UI's NAME_TAKEN handling can be exercised in browser mode.
+ type ShimPresetRecord = { name: string; updatedAt: string; appearance: StylePresetAppearance };
+ const presetsStorageKey = "browser-shim-style-presets-v1";
+ const readPresets = (): Record<string, ShimPresetRecord> => {
+ try {
+ const parsed = JSON.parse(localStorage.getItem(presetsStorageKey) ?? "{}");
+ return parsed && typeof parsed === "object" ? parsed : {};
+ } catch {
+ return {};
+ }
+ };
+ const writePresets = (records: Record<string, ShimPresetRecord>) => {
+ try {
+ localStorage.setItem(presetsStorageKey, JSON.stringify(records));
+ } catch {
+ // ponytail: localStorage may be full or unavailable; silently skip
+ }
+ };
+ const presetError = (code: "NAME_TAKEN" | "NOT_FOUND" | "INVALID_REQUEST", message: string) =>
+ new NativeBridgeRequestError({ code, message, retryable: false });
+ const toPreset = (id: string, record: ShimPresetRecord): StylePreset => ({ id, ...record });
+ // Same shape as the real bridge: validation TypeErrors become INVALID_REQUEST.
+ const presetCall = async <T>(work: () => T): Promise<T> => {
+ try {
+ return work();
+ } catch (error) {
+ if (error instanceof NativeBridgeRequestError) throw error;
+ throw presetError("INVALID_REQUEST", error instanceof Error ? error.message : String(error));
+ }
+ };
+ const requirePreset = (records: Record<string, ShimPresetRecord>, id: string) => {
+ const record = records[id];
+ if (!record) throw presetError("NOT_FOUND", `Style preset not found: ${id}`);
+ return record;
+ };
+ const assertPresetNameFree = (
+ records: Record<string, ShimPresetRecord>,
+ id: string,
+ name: string,
+ exceptId?: string,
+ ) => {
+ const taken = Object.entries(records).some(
+ ([otherId, record]) =>
+ otherId !== exceptId &&
+ (otherId.toLowerCase() === id.toLowerCase() ||
+ record.name.toLowerCase() === name.toLowerCase()),
+ );
+ if (taken) throw presetError("NAME_TAKEN", `A style preset named "${name}" already exists.`);
+ };
+
const summarize = (s: ShimSession) => ({
id: s.id,
projectId: s.projectId,
@@ -668,6 +729,67 @@ function createShimBridgeClient() {
Promise.resolve({ currentProjectPath: null, currentVideoPath: null }),
loadProjectFile: () => Promise.resolve({ success: false, canceled: true }),
},
+ presets: {
+ list: () =>
+ presetCall(() =>
+ Object.entries(readPresets())
+ .flatMap(([id, record]) => {
+ try {
+ const appearance = parseStylePresetAppearance(record.appearance);
+ return [toPreset(id, { ...record, appearance })];
+ } catch {
+ return [];
+ }
+ })
+ .sort(compareStylePresets),
+ ),
+ create: (name: string, appearance: StylePresetAppearance) =>
+ presetCall(() => {
+ const records = readPresets();
+ const cleanName = sanitizeStylePresetName(name);
+ const id = stylePresetFileBaseName(cleanName);
+ const record = {
+ name: cleanName,
+ updatedAt: new Date().toISOString(),
+ appearance: parseStylePresetAppearance(appearance),
+ };
+ assertPresetNameFree(records, id, cleanName);
+ writePresets({ ...records, [id]: record });
+ return toPreset(id, record);
+ }),
+ rename: (id: string, name: string) =>
+ presetCall(() => {
+ const records = readPresets();
+ const current = requirePreset(records, id);
+ const cleanName = sanitizeStylePresetName(name);
+ const nextId = stylePresetFileBaseName(cleanName);
+ assertPresetNameFree(records, nextId, cleanName, id);
+ const { [id]: _previous, ...rest } = records;
+ const record = { ...current, name: cleanName, updatedAt: new Date().toISOString() };
+ writePresets({ ...rest, [nextId]: record });
+ return toPreset(nextId, record);
+ }),
+ update: (id: string, appearance: StylePresetAppearance) =>
+ presetCall(() => {
+ const records = readPresets();
+ const current = requirePreset(records, id);
+ const record = {
+ ...current,
+ updatedAt: new Date().toISOString(),
+ appearance: parseStylePresetAppearance(appearance),
+ };
+ writePresets({ ...records, [id]: record });
+ return toPreset(id, record);
+ }),
+ delete: (id: string) =>
+ presetCall(() => {
+ const { [id]: _removed, ...rest } = readPresets();
+ writePresets(rest);
+ return { success: true as const };
+ }),
+ // No folder to open in a browser tab.
+ reveal: () => Promise.resolve({ success: true as const }),
+ },
};
}
diff --git a/src/native/client.ts b/src/native/client.ts
index fce40fa6c..5ce7e8493 100644
--- a/src/native/client.ts
+++ b/src/native/client.ts
@@ -17,15 +17,43 @@ import {
type CursorRecordingData,
type CursorTelemetryPoint,
NATIVE_BRIDGE_CHANNEL,
+ type NativeBridgeError,
+ type NativeBridgeErrorCode,
type NativeBridgeRequest,
type NativeBridgeResponse,
type NativePlatform,
type ProjectContext,
type ProjectFileResult,
type ProjectPathResult,
+ type StylePreset,
+ type StylePresetAppearance,
+ type StylePresetDeleteResult,
+ type StylePresetRevealResult,
type SystemCapabilities,
} from "./contracts";
+/**
+ * A failed bridge request, carrying the bridge's error code so a caller can tell one
+ * failure from another without matching on message text — e.g. `NAME_TAKEN` from a style
+ * preset create/rename. Still an `Error` with the same message as before.
+ */
+export class NativeBridgeRequestError extends Error {
+ readonly code: NativeBridgeErrorCode;
+ readonly retryable: boolean;
+
+ constructor(error: NativeBridgeError) {
+ super(error.message);
+ this.name = "NativeBridgeRequestError";
+ this.code = error.code;
+ this.retryable = error.retryable;
+ }
+}
+
+/** True when a style preset create/rename failed because the name is already used. */
+export function isStylePresetNameTakenError(error: unknown): boolean {
+ return error instanceof NativeBridgeRequestError && error.code === "NAME_TAKEN";
+}
+
function createRequestId() {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
@@ -57,7 +85,7 @@ export async function invokeNativeBridge<TData = unknown>(
export async function requireNativeBridgeData<TData>(request: NativeBridgeRequest): Promise<TData> {
const response = await invokeNativeBridge<TData>(request);
if (!response.ok) {
- throw new Error(response.error.message);
+ throw new NativeBridgeRequestError(response.error);
}
return response.data;
@@ -319,4 +347,43 @@ export const nativeBridgeClient = {
payload: input,
}),
},
+ /** Style presets. `create` and `rename` reject with a `NativeBridgeRequestError` whose
+ * `code` is `"NAME_TAKEN"` when the name is in use — see `isStylePresetNameTakenError`. */
+ presets: {
+ list: () =>
+ requireNativeBridgeData<StylePreset[]>({
+ domain: "presets",
+ action: "list",
+ }),
+ create: (name: string, appearance: StylePresetAppearance) =>
+ requireNativeBridgeData<StylePreset>({
+ domain: "presets",
+ action: "create",
+ payload: { name, appearance },
+ }),
+ rename: (id: string, name: string) =>
+ requireNativeBridgeData<StylePreset>({
+ domain: "presets",
+ action: "rename",
+ payload: { id, name },
+ }),
+ update: (id: string, appearance: StylePresetAppearance) =>
+ requireNativeBridgeData<StylePreset>({
+ domain: "presets",
+ action: "update",
+ payload: { id, appearance },
+ }),
+ delete: (id: string) =>
+ requireNativeBridgeData<StylePresetDeleteResult>({
+ domain: "presets",
+ action: "delete",
+ payload: { id },
+ }),
+ reveal: (id: string) =>
+ requireNativeBridgeData<StylePresetRevealResult>({
+ domain: "presets",
+ action: "reveal",
+ payload: { id },
+ }),
+ },
};
diff --git a/src/native/contracts.ts b/src/native/contracts.ts
index 54c1cc775..49687a0dd 100644
--- a/src/native/contracts.ts
+++ b/src/native/contracts.ts
@@ -1,3 +1,5 @@
+import type { StylePreset, StylePresetAppearance } from "../lib/ai-edition/stylePresets";
+
export const NATIVE_BRIDGE_CHANNEL = "native-bridge:invoke";
export const NATIVE_BRIDGE_VERSION = 1;
@@ -364,10 +366,26 @@ export interface AiEditionCaptionTranslateResult {
error?: string;
}
+// ---- Style presets domain -------------------------------------------------
+// One `<name>.openscreenpreset` file per preset in Documents/OpenScreen Presets. The
+// shape and its validation live in src/lib/ai-edition/stylePresets.ts, shared with main.
+
+export type { StylePreset, StylePresetAppearance };
+
+export interface StylePresetDeleteResult {
+ success: true;
+}
+
+export interface StylePresetRevealResult {
+ success: true;
+}
+
export type NativeBridgeErrorCode =
| "INVALID_REQUEST"
| "UNSUPPORTED_ACTION"
| "NOT_FOUND"
+ /** A style preset create/rename collided with an existing name (case-insensitive). */
+ | "NAME_TAKEN"
| "UNAVAILABLE"
| "INTERNAL_ERROR";
@@ -785,6 +803,42 @@ export type NativeBridgeRequest =
params?: CompositorExportGifParams;
};
requestId?: string;
+ }
+ | {
+ domain: "presets";
+ action: "list";
+ payload?: EmptyPayload;
+ requestId?: string;
+ }
+ | {
+ domain: "presets";
+ action: "create";
+ payload: { name: string; appearance: StylePresetAppearance };
+ requestId?: string;
+ }
+ | {
+ domain: "presets";
+ action: "rename";
+ payload: { id: string; name: string };
+ requestId?: string;
+ }
+ | {
+ domain: "presets";
+ action: "update";
+ payload: { id: string; appearance: StylePresetAppearance };
+ requestId?: string;
+ }
+ | {
+ domain: "presets";
+ action: "delete";
+ payload: { id: string };
+ requestId?: string;
+ }
+ | {
+ domain: "presets";
+ action: "reveal";
+ payload: { id: string };
+ requestId?: string;
};
export type NativeBridgeEventName =