Skip to content

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

fix(presets): handle persistence failures

Etienne Lescot4b54880582fd
diff --git a/electron/ai-edition/style-preset-service.test.ts b/electron/ai-edition/style-preset-service.test.ts
index 898beeee3..4a7158dca 100644
--- a/electron/ai-edition/style-preset-service.test.ts
+++ b/electron/ai-edition/style-preset-service.test.ts
@@ -129,6 +129,13 @@ describe("StylePresetService", () => {
await expectCode(service.create("corrupt", APPEARANCE), "NAME_TAKEN");
});
+ it("reserves the built-in preset id on create and rename", async () => {
+ await expectCode(service.create("openscreen-factory", APPEARANCE), "NAME_TAKEN");
+ const created = await service.create("Mine", APPEARANCE);
+ await expectCode(service.rename(created.id, "OPENSCREEN-FACTORY"), "NAME_TAKEN");
+ expect((await service.list()).map((preset) => preset.id)).toEqual(["Mine"]);
+ });
+
it("rejects an invalid appearance before writing anything", async () => {
await expect(
service.create("Bad", { ...APPEARANCE, wallpaper: "file:///Users/alice/a.jpg" }),
@@ -156,6 +163,24 @@ describe("StylePresetService", () => {
expect(await fs.readdir(dir)).toEqual(["Studio.openscreenpreset"]);
});
+ it("removes the destination and preserves the source when rename cleanup fails", async () => {
+ const created = await service.create("Source", APPEARANCE);
+ const sourcePath = path.join(dir, "Source.openscreenpreset");
+ const unlink = fs.unlink.bind(fs);
+ vi.spyOn(fs, "unlink").mockImplementation(async (filePath) => {
+ if (filePath === sourcePath) {
+ throw Object.assign(new Error("busy"), { code: "EBUSY" });
+ }
+ return unlink(filePath);
+ });
+
+ await expect(service.rename(created.id, "Destination")).rejects.toMatchObject({
+ code: "EBUSY",
+ });
+ expect((await fs.readdir(dir)).sort()).toEqual(["Source.openscreenpreset"]);
+ expect(await service.list()).toMatchObject([{ id: "Source", name: "Source" }]);
+ });
+
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 });
diff --git a/electron/ai-edition/style-preset-service.ts b/electron/ai-edition/style-preset-service.ts
index 31935e8c0..1ab45083c 100644
--- a/electron/ai-edition/style-preset-service.ts
+++ b/electron/ai-edition/style-preset-service.ts
@@ -11,6 +11,7 @@ import fs, { type FileHandle } from "node:fs/promises";
import path from "node:path";
import {
compareStylePresets,
+ FACTORY_STYLE_PRESET_ID,
parseStylePresetFile,
STYLE_PRESET_FILE_EXTENSION,
type StylePreset,
@@ -116,6 +117,7 @@ export class StylePresetService {
// Validates before anything touches the disk.
const json = serializeStylePresetFile({ name: cleanName, appearance });
const id = stylePresetFileBaseName(cleanName);
+ this.assertNotFactoryId(id, cleanName);
await this.ensureDirectory();
this.assertNameFree(await this.readEntries(), id, cleanName);
await this.writeAtomic(this.pathFor(id), json);
@@ -128,6 +130,7 @@ export class StylePresetService {
const current = await this.read(id);
const cleanName = sanitizeStylePresetName(name);
const nextId = stylePresetFileBaseName(cleanName);
+ this.assertNotFactoryId(nextId, cleanName);
this.assertNameFree(await this.readEntries(), nextId, cleanName, id);
const json = serializeStylePresetFile({ name: cleanName, appearance: current.appearance });
const from = this.pathFor(id);
@@ -142,9 +145,12 @@ export class StylePresetService {
await renameWithRetry(from, to);
} else {
await this.writeAtomic(to, json);
- await fs.unlink(from).catch((error) => {
+ try {
+ await fs.unlink(from);
+ } catch (error) {
+ if (!isMissing(error)) await fs.unlink(to).catch(() => undefined);
if (!isMissing(error)) throw error;
- });
+ }
}
return this.read(nextId);
});
@@ -245,6 +251,12 @@ export class StylePresetService {
}
}
+ private assertNotFactoryId(id: string, name: string): void {
+ if (id.toLowerCase() === FACTORY_STYLE_PRESET_ID) {
+ 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);
diff --git a/src/components/ai-edition/StylePresetsMenu.tsx b/src/components/ai-edition/StylePresetsMenu.tsx
index cc4e8ba25..d646aa6b2 100644
--- a/src/components/ai-edition/StylePresetsMenu.tsx
+++ b/src/components/ai-edition/StylePresetsMenu.tsx
@@ -17,12 +17,12 @@ import { getEditorSettings, patchEditorSettings } from "@/lib/ai-edition/store/e
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import {
+ FACTORY_STYLE_PRESET_ID,
type StylePreset,
type StylePresetAppearance,
sanitizeStylePresetName,
} from "@/lib/ai-edition/stylePresets";
import {
- FACTORY_STYLE_PRESET_ID,
factoryStylePresetAppearance,
stylePresetAppearanceFromSettings,
stylePresetPatch,
@@ -96,7 +96,7 @@ function NameForm({
}: NameFormProps) {
const [name, setName] = useState(initialName);
const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
- if (event.key === "Enter") {
+ if (event.key === "Enter" && !busy) {
event.preventDefault();
onSubmit(name);
}
@@ -106,6 +106,7 @@ function NameForm({
<div className={styles.presetForm}>
<input
type="text"
+ disabled={busy}
autoFocus
value={name}
placeholder={placeholder}
@@ -188,16 +189,16 @@ export function StylePresetsMenu() {
const current = stylePresetAppearanceFromSettings(settings);
const factory = factoryStylePresetAppearance();
- const apply = (appearance: StylePresetAppearance, name: string) => {
+ const apply = async (appearance: StylePresetAppearance, name: string) => {
setOpen(false);
const patch = stylePresetPatch(appearance);
+ if (!(await set(patch))) return;
// The overlay only pushes native params on mount, and each control here pushes its own
// diff; a preset touches all of them at once, so it pushes the whole resulting snapshot.
const doc = useProjectStore.getState().document;
if (doc && isNativeCompositorActive()) {
pushAllNativeParams(getEditorSettings(patchEditorSettings(doc, patch)));
}
- void set(patch);
toast.success(ts("stylePresets.applied", { name }));
};
@@ -323,7 +324,7 @@ export function StylePresetsMenu() {
role="menuitemradio"
aria-checked={active}
className={rowClass(active)}
- onClick={() => apply(preset.appearance, preset.name)}
+ onClick={() => void apply(preset.appearance, preset.name)}
>
<span className={styles.presetCheck} aria-hidden="true">
{active ? <Check size={12} /> : null}
@@ -433,7 +434,7 @@ export function StylePresetsMenu() {
aria-checked={factoryActive}
key={FACTORY_STYLE_PRESET_ID}
className={rowClass(factoryActive)}
- onClick={() => apply(factory, ts("stylePresets.factoryName"))}
+ onClick={() => void apply(factory, ts("stylePresets.factoryName"))}
>
<span className={styles.presetCheck} aria-hidden="true">
{factoryActive ? <Check size={12} /> : null}
diff --git a/src/components/ai-edition/v4/EditorTopBar.stylePresets.test.tsx b/src/components/ai-edition/v4/EditorTopBar.stylePresets.test.tsx
index 5d1106bbe..ed45a138f 100644
--- a/src/components/ai-edition/v4/EditorTopBar.stylePresets.test.tsx
+++ b/src/components/ai-edition/v4/EditorTopBar.stylePresets.test.tsx
@@ -131,7 +131,7 @@ beforeEach(() => {
localStorage.clear();
state.platform = "darwin";
state.settings = DEFAULT_EDITOR_SETTINGS;
- state.set = vi.fn<Fn>(async () => undefined);
+ state.set = vi.fn<Fn>(async () => true);
state.toastSuccess = vi.fn<Fn>();
state.presets.list = vi.fn<Fn>(async () => [WARM]);
state.presets.create = vi.fn<Fn>(async (name) => ({ ...WARM, id: name, name }));
@@ -182,7 +182,16 @@ describe("Presets menu in the editor top bar", () => {
expect(state.set).toHaveBeenCalledTimes(1);
expect(state.set).toHaveBeenCalledWith(stylePresetPatch(WARM.appearance));
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
- expect(state.toastSuccess).toHaveBeenCalledWith("Applied “Warm”");
+ await waitFor(() => expect(state.toastSuccess).toHaveBeenCalledWith("Applied “Warm”"));
+ });
+
+ it("does not report an applied preset when the project save fails", async () => {
+ state.set = vi.fn<Fn>(async () => false);
+ renderPane();
+ await openMenu();
+ fireEvent.click(screen.getByRole("menuitemradio", { name: "Warm" }));
+ await waitFor(() => expect(state.set).toHaveBeenCalledTimes(1));
+ expect(state.toastSuccess).not.toHaveBeenCalled();
});
it("applies the built-in preset from its row", async () => {
@@ -253,6 +262,23 @@ describe("Presets menu in the editor top bar", () => {
expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
});
+ it("blocks repeated Enter submissions while create is busy", async () => {
+ let finishCreate: (() => void) | undefined;
+ state.presets.create = vi.fn<Fn>(
+ () => new Promise<void>((resolve) => (finishCreate = resolve)),
+ );
+ renderPane();
+ await openMenu();
+ fireEvent.click(screen.getByRole("menuitem", { name: "Create new preset…" }));
+ const input = screen.getByRole("textbox", { name: "Preset name" });
+ fireEvent.change(input, { target: { value: "Mine" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+ await waitFor(() => expect(input).toBeDisabled());
+ fireEvent.keyDown(input, { key: "Enter" });
+ expect(state.presets.create).toHaveBeenCalledTimes(1);
+ finishCreate?.();
+ });
+
it("asks for a name instead of saving a blank one", async () => {
renderPane();
await openMenu();
diff --git a/src/lib/ai-edition/store/useEditorSettings.test.ts b/src/lib/ai-edition/store/useEditorSettings.test.ts
index 4122c05bf..157c3c421 100644
--- a/src/lib/ai-edition/store/useEditorSettings.test.ts
+++ b/src/lib/ai-edition/store/useEditorSettings.test.ts
@@ -111,6 +111,13 @@ describe("useEditorSettings drag snapshots", () => {
vi.clearAllMocks();
});
+ it("returns whether a settings edit persisted", async () => {
+ const { result } = renderHook(() => useEditorSettings());
+ await expect(result.current.set({ borderRadius: 10 })).resolves.toBe(true);
+ bridgeMocks.save.mockResolvedValueOnce({ success: false, error: "disk full" });
+ await expect(result.current.set({ borderRadius: 20 })).resolves.toBe(false);
+ });
+
it("does not record a snapshot of the project the user left", async () => {
const { result, rerender } = renderHook(() => useEditorSettings());
diff --git a/src/lib/ai-edition/store/useEditorSettings.ts b/src/lib/ai-edition/store/useEditorSettings.ts
index 49302e52c..facf361c1 100644
--- a/src/lib/ai-edition/store/useEditorSettings.ts
+++ b/src/lib/ai-edition/store/useEditorSettings.ts
@@ -27,7 +27,7 @@ export interface UseEditorSettingsResult {
/** True when there's a project loaded — `set`/`setLive` are no-ops otherwise. */
hasDocument: boolean;
/** Apply a patch, persist to disk. */
- set: (patch: EditorSettingsPatch) => Promise<void>;
+ set: (patch: EditorSettingsPatch) => Promise<boolean>;
/** Apply a patch, no persist. Pair with `commit` on slider release. */
setLive: (patch: EditorSettingsPatch) => void;
/** Force-flush the current document to disk. */
@@ -47,13 +47,13 @@ export function useEditorSettings(): UseEditorSettingsResult {
const set = useCallback(
async (patch: EditorSettingsPatch) => {
const doc = useProjectStore.getState().document;
- if (!doc) return;
+ if (!doc) return false;
const next = patchEditorSettings(doc, patch);
// The optimistic write is not the edit — the save is. Only the one that can
// fail records, and it names `doc` as what Ctrl+Z returns to because by then
// the store already holds `next`.
setDocument(next, { history: false });
- await saveDocument(next, { history: true, historyBase: doc });
+ return saveDocument(next, { history: true, historyBase: doc });
},
[setDocument, saveDocument],
);
diff --git a/src/lib/ai-edition/stylePresets.ts b/src/lib/ai-edition/stylePresets.ts
index 968645fae..1b46ce44d 100644
--- a/src/lib/ai-edition/stylePresets.ts
+++ b/src/lib/ai-edition/stylePresets.ts
@@ -24,6 +24,8 @@ 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;
+/** Reserved for the built-in row; a user preset must never resolve to this file id. */
+export const FACTORY_STYLE_PRESET_ID = "openscreen-factory";
/** 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. */
diff --git a/src/lib/ai-edition/stylePresetsEditor.ts b/src/lib/ai-edition/stylePresetsEditor.ts
index 13dac8069..898c63fab 100644
--- a/src/lib/ai-edition/stylePresetsEditor.ts
+++ b/src/lib/ai-edition/stylePresetsEditor.ts
@@ -9,10 +9,6 @@ import {
} 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,
diff --git a/src/native/browserShim.presets.test.ts b/src/native/browserShim.presets.test.ts
index 1b7d6d070..35172982f 100644
--- a/src/native/browserShim.presets.test.ts
+++ b/src/native/browserShim.presets.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
// The shim keeps presets in localStorage, so this needs a DOM.
-import { beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type { StylePresetAppearance } from "@/lib/ai-edition/stylePresets";
import { installBrowserShims } from "./browserShim";
import {
@@ -78,6 +78,36 @@ describe("browserShim presets", () => {
expect((await presets.list()).map((p) => p.id)).toEqual(["Three", "Two"]);
});
+ it("reserves the built-in preset id on create and rename", async () => {
+ await expect(presets.create("openscreen-factory", APPEARANCE)).rejects.toMatchObject({
+ code: "NAME_TAKEN",
+ });
+ const created = await presets.create("Mine", APPEARANCE);
+ await expect(presets.rename(created.id, "OPENSCREEN-FACTORY")).rejects.toMatchObject({
+ code: "NAME_TAKEN",
+ });
+ });
+
+ it("rejects every mutation when localStorage persistence fails", async () => {
+ const created = await presets.create("Mine", APPEARANCE);
+ const setItem = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
+ throw new DOMException("full", "QuotaExceededError");
+ });
+ try {
+ for (const mutate of [
+ () => presets.create("Other", APPEARANCE),
+ () => presets.rename(created.id, "Renamed"),
+ () => presets.update(created.id, { ...APPEARANCE, padding: 10 }),
+ () => presets.delete(created.id),
+ ]) {
+ await expect(mutate()).rejects.toMatchObject({ code: "INTERNAL_ERROR" });
+ }
+ } finally {
+ setItem.mockRestore();
+ }
+ expect((await presets.list()).map((preset) => preset.id)).toEqual(["Mine"]);
+ });
+
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" }),
diff --git a/src/native/browserShim.ts b/src/native/browserShim.ts
index c157a1927..b115b58e5 100644
--- a/src/native/browserShim.ts
+++ b/src/native/browserShim.ts
@@ -7,6 +7,7 @@ import { PROVIDER_DEFINITIONS } from "../../electron/ai-edition/provider-registr
import { axcutSchemaVersion, migrateRawDocumentToCurrent } from "../lib/ai-edition/schema";
import {
compareStylePresets,
+ FACTORY_STYLE_PRESET_ID,
parseStylePresetAppearance,
type StylePreset,
type StylePresetAppearance,
@@ -400,7 +401,11 @@ function createShimBridgeClient() {
try {
localStorage.setItem(presetsStorageKey, JSON.stringify(records));
} catch {
- // ponytail: localStorage may be full or unavailable; silently skip
+ throw new NativeBridgeRequestError({
+ code: "INTERNAL_ERROR",
+ message: "Failed to persist style presets.",
+ retryable: false,
+ });
}
};
const presetError = (code: "NAME_TAKEN" | "NOT_FOUND" | "INVALID_REQUEST", message: string) =>
@@ -426,6 +431,9 @@ function createShimBridgeClient() {
name: string,
exceptId?: string,
) => {
+ if (id.toLowerCase() === FACTORY_STYLE_PRESET_ID) {
+ throw presetError("NAME_TAKEN", `A style preset named "${name}" already exists.`);
+ }
const taken = Object.entries(records).some(
([otherId, record]) =>
otherId !== exceptId &&