Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

fix: guard workspace save and browser lifecycles

Abdurrahman Fakhrula31a7255128d
diff --git a/docs/evidence/2026-11-04-final-workspace.md b/docs/evidence/2026-11-04-final-workspace.md
new file mode 100644
index 00000000..acbf31fc
--- /dev/null
+++ b/docs/evidence/2026-11-04-final-workspace.md
@@ -0,0 +1,25 @@
+# Final workspace follow-up, 2026-11-04
+
+Scope: isolated workspace branch based on origin/main a2268f2b, including PR #270. No host file writes, real terminal sessions, provider credentials, deployment, full build, or production browser were used. The implementation observations below are not a substitute for interactive acceptance across the five shells, both themes, and real mobile devices.
+
+| Finding | Disposition and remaining evidence |
+| --- | --- |
+| WS-01 | Prior implementation returns write success and vetoes close on failure. Failed-write and retry UI journey remains to be exercised in a browser. |
+| WS-02 | Prior implementation guards all dirty tabs, offers tab confirmation and keeps per-window state. Partial save, focus restoration, and shell remount need interactive proof. |
+| WS-03 | Prior implementation reports storage failure, flushes drafts, warns for session-only uploads, and provides relinking. Reload, decoding and file-picker journey remain unverified. |
+| WS-04 | Prior implementation serializes project writes and reports failure. This follow-up flushes pending project writes before image save, and retains dirty state when edits occur during an image save. Controlled write failure, retry and ordering need mounted UI proof. Browser teardown can still interrupt a request. |
+| WS-05 | Payload identity is used for paging, with a new payload replacing the paged item. Actual shell reuse and same-path reopening remain untested. |
+| WS-06 | Arrows use the focused-window hotkey helper. Editable, iframe and cross-window browser journeys remain untested. |
+| WS-07 | Virtualizer and row use 44px geometry. Actual coarse-pointer and enlarged-text measurement remains untested. |
+| WS-08 | Roving keyboard tab semantics implemented. Close focus restoration and assistive technology behavior remain unverified. |
+| WS-09 | Search uses 16px text, 44px close target and focus style. Focus restoration and physical iOS verification remain untested. |
+| WS-10 | Input request failures halt delivery and report uncertainty without replay. New tests exercise both HTTP and network failure, including queued and later input, using a mocked transport. Real PTY recovery remains untested. |
+| WS-11 | Separator keyboard and pointer cancellation handling implemented. Mobile and assistive technology verification remains untested. |
+| WS-12 | Import requests use sequence identity, initial loading and retry. Delayed-response browser journey remains untested. |
+| WS-13 | Export abort, URL and activity cleanup implemented with generation checks. Actual rendering and download cancellation remain untested. |
+| WSC-01 | Draft baseline now comes from the same storage read as the loaded composition, preventing another tab's intervening write from becoming a false baseline. Unchanged initial composition does not write, including repeated effects. A synthetic hook test reproduces the intervening write and confirms conflict reporting; real mounted cross-tab reload remains untested. |
+| WSC-02 | Sample image actions pass sample bytes, and actions requiring unavailable bytes are hidden. Actual sample rendering and both action paths remain untested. |
+| WSC-03 | Null or throwing export retains the editor and reports an error. This follow-up also avoids marking a later revision clean on async save completion. Mounted canvas failure and retry remain untested. |
+| WSC-04 | Unmount now aborts the current retry/power controller, session fetch receives its signal, late status/transport updates are guarded, and superseded power operations cannot clear a newer busy state. Mocked delayed operation and actual noVNC lifecycle still need interactive proof. |
+
+Validation: targeted draft, relink and media-kind tests passed 28 tests; new terminal delivery tests passed 2; new draft race hook test passed 1. TypeScript, targeted ESLint and architecture checks were run; see final task report for final rerun results. The draft hook test uses a synthetic hook scheduler, not React DOM. Existing tests and source review do not prove the outstanding UI journeys above.
diff --git a/frontend/slices/camoufox-browser/app.tsx b/frontend/slices/camoufox-browser/app.tsx
index 2278940c..c7b6af66 100644
--- a/frontend/slices/camoufox-browser/app.tsx
+++ b/frontend/slices/camoufox-browser/app.tsx
@@ -12,9 +12,9 @@ import { fetchStatus, setPower, waitForViewer, verifyViewerTransport, type Camou
// window manager reflows the framebuffer rather than scaling a desktop thumbnail.
/** The display's VNC password, fetched for this already-authenticated session so
* noVNC does not prompt on every open. Absent = none configured; let noVNC ask. */
-async function viewerSrc(): Promise<string | null> {
+async function viewerSrc(signal: AbortSignal): Promise<string | null> {
try {
- const response = await fetch("/api/v1/camoufox/session", { cache: "no-store" });
+ const response = await fetch("/api/v1/camoufox/session", { cache: "no-store", signal });
if (!response.ok) return null;
const payload = (await response.json()) as {
password?: string | null;
@@ -58,7 +58,7 @@ export default function CamoufoxBrowser() {
// from the power action because it is also the mount path for a session that was
// already up before this window opened.
const connect = useCallback(async (signal: AbortSignal) => {
- const ready = await waitForViewer(signal, 30_000, setStatus);
+ const ready = await waitForViewer(signal, 30_000, (next) => { if (!signal.aborted) setStatus(next); });
if (signal.aborted) return;
if (!ready) {
setError("The browser session started but is not answering. Check its logs on the host.");
@@ -68,10 +68,10 @@ export default function CamoufoxBrowser() {
try { await verifyViewerTransport(signal); }
catch (cause) {
if (!signal.aborted) setError(cause instanceof Error ? cause.message : "The secure viewer is unavailable");
- setSrc(null);
+ if (!signal.aborted) setSrc(null);
return;
}
- const source = await viewerSrc();
+ const source = await viewerSrc(signal);
if (signal.aborted) return;
if (!source) {
setError("Secure browser embedding is unavailable until the split-origin host template is configured.");
@@ -98,7 +98,7 @@ export default function CamoufoxBrowser() {
setStatus({ running: false, enabled: false, installed: true });
}
})();
- return () => controller.abort();
+ return () => { abort.current?.abort(); abort.current = null; };
}, [connect]);
const retryConnection = useCallback(async () => {
@@ -135,7 +135,7 @@ export default function CamoufoxBrowser() {
setError(cause instanceof Error ? cause.message : "Could not change the browser session");
}
} finally {
- setBusy(false);
+ if (abort.current === controller) setBusy(false);
}
}, [connect]);
diff --git a/frontend/slices/image-editor/lib/editor-api.ts b/frontend/slices/image-editor/lib/editor-api.ts
index 5ea3dafb..928afccd 100644
--- a/frontend/slices/image-editor/lib/editor-api.ts
+++ b/frontend/slices/image-editor/lib/editor-api.ts
@@ -1,2 +1,2 @@
/** Imperative handle exposed by ImageEditor without coupling the shell back to its root component. */
-export type EditorApi = { exportPng: () => string | null; markSaved: () => void };
+export type EditorApi = { exportPng: () => string | null; flushProject: () => void; revision: () => number; markSaved: (revision: number) => boolean };
diff --git a/frontend/slices/image-editor/shell.tsx b/frontend/slices/image-editor/shell.tsx
index ea3e9fcd..f2919e30 100644
--- a/frontend/slices/image-editor/shell.tsx
+++ b/frontend/slices/image-editor/shell.tsx
@@ -34,6 +34,7 @@ function DesktopShell({ stage, onSave, onSaveAs, onClose }: { stage: React.React
// when the editor opened blank (no initialImage) so a reload doesn't lose work.
function useAutosave(autoRestore: boolean, saveDoc?: (doc: Doc) => void, ready = true) {
const { doc, exportProject, loadProject } = useEditor();
+ const flushRef = useRef<() => void>(() => {});
useEffect(() => {
if (!autoRestore) return;
const a = loadAutosave();
@@ -48,13 +49,15 @@ function useAutosave(autoRestore: boolean, saveDoc?: (doc: Doc) => void, ready =
if (!ready) return;
let pending = true;
const flush = () => { if (pending) { pending = false; saveDoc(doc); } };
+ flushRef.current = flush;
const t = setTimeout(flush, 800);
window.addEventListener("pagehide", flush);
- return () => { clearTimeout(t); window.removeEventListener("pagehide", flush); flush(); };
+ return () => { clearTimeout(t); window.removeEventListener("pagehide", flush); flush(); flushRef.current = () => {}; };
}
const t = setTimeout(() => saveAutosave(exportProject()), 800);
return () => clearTimeout(t);
}, [doc, exportProject, saveDoc, ready]);
+ return flushRef;
}
// Picks desktop vs mobile layout; both share ONE EditorStage element + provider.
@@ -74,24 +77,27 @@ export type ShellProps = {
export function Shell({ onSave, onSaveAs, onClose, onDirty, onReady, autoRestore, saveDoc, ready, compact, winId, stage }: ShellProps) {
useKeyboard(winId);
- useAutosave(autoRestore, saveDoc, ready);
+ const flushProject = useAutosave(autoRestore, saveDoc, ready);
const autoMobile = useIsMobile();
const mobile = compact ?? autoMobile;
- const { version, canUndo, stageRef, rootRef, docView } = useEditor();
- // Dirty = history moved past the last save. Derived (no effect-driven
- // setState): loadProject/autosave don't push history so opening a file never
- // trips it; api.markSaved() pins savedVersion to the current version.
+ const { version, stageRef, rootRef, docView } = useEditor();
+ // History revisions advance on edits, undo and redo. Conservatively keep the
+ // guard after any revision since save, including undoing back to the first step.
const [savedVersion, setSavedVersion] = useState(0);
- const dirty = canUndo && version > savedVersion;
+ const dirty = version !== savedVersion;
const versionRef = useRef(version);
- useEffect(() => {
- versionRef.current = version;
- });
+ useEffect(() => { versionRef.current = version; }, [version]);
useEffect(() => { onDirty?.(dirty); }, [dirty, onDirty]);
useEffect(() => {
onReady?.({
exportPng: () => { const s = stageRef.current; return s ? stageToDataURL(s, { format: "png", view: docView() }) : null; },
- markSaved: () => setSavedVersion(versionRef.current),
+ flushProject: () => flushProject.current(),
+ revision: () => versionRef.current,
+ markSaved: (revision) => {
+ if (versionRef.current !== revision) return false;
+ setSavedVersion(revision);
+ return true;
+ },
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
diff --git a/frontend/slices/media-studio/app.tsx b/frontend/slices/media-studio/app.tsx
index 806b68db..f4877f94 100644
--- a/frontend/slices/media-studio/app.tsx
+++ b/frontend/slices/media-studio/app.tsx
@@ -19,6 +19,7 @@ export default function MediaStudio({ payload, winId }: AppProps) {
const dirty = useRef(false);
const api = useRef<EditorApi | null>(null);
const closeAfterSave = useRef(false);
+ const pendingRevision = useRef<number | null>(null);
const [docStatus, setDocStatus] = useState<"idle" | "saving" | "saved" | "failed">("idle");
const docStatusRef = useRef(docStatus);
useEffect(() => { docStatusRef.current = docStatus; }, [docStatus]);
@@ -64,33 +65,49 @@ export default function MediaStudio({ payload, winId }: AppProps) {
window.addEventListener("beforeunload", warn);
return () => window.removeEventListener("beforeunload", warn);
}, []);
- const markClean = () => { dirty.current = false; api.current?.markSaved(); };
+ const markClean = (revision: number | null) => {
+ if (revision === null || !api.current?.markSaved(revision)) return false;
+ dirty.current = false;
+ return true;
+ };
const forceClose = () => { if (winId) { setCloseGuard(winId, null); closeWindow(winId); } };
const onSave = (dataUrl: string) => {
+ api.current?.flushProject();
+ const revision = api.current?.revision() ?? null;
const prefs = loadSavePrefs();
if (prefs.remember && prefs.dir) {
saveImageToHost(dataUrl, { dir: prefs.dir, name: autoName(), format: prefs.format, quality: prefs.quality })
- .then((path) => { markClean(); toast(`Saved → ${path}`, { tone: "success" }); })
+ .then((path) => { markClean(revision); toast(`Saved → ${path}`, { tone: "success" }); })
.catch((e) => toast(e instanceof Error ? e.message : "save failed", { tone: "error" }));
} else {
closeAfterSave.current = false;
+ pendingRevision.current = revision;
setPending(dataUrl);
}
};
- const onSaveAs = (dataUrl: string) => { closeAfterSave.current = false; setPending(dataUrl); };
+ const onSaveAs = (dataUrl: string) => { api.current?.flushProject(); closeAfterSave.current = false; pendingRevision.current = api.current?.revision() ?? null; setPending(dataUrl); };
// The prompt's "Save" → render the canvas, open the dialog, close once saved.
const saveThenClose = () => {
let url: string | null = null;
try { url = api.current?.exportPng() ?? null; } catch { /* keep the window open */ }
if (!url) { toast("Could not export image. Try again.", { tone: "error" }); return; }
+ api.current?.flushProject();
setConfirmClose(false);
closeAfterSave.current = true;
+ pendingRevision.current = api.current?.revision() ?? null;
setPending(url);
};
- const onDialogSaved = () => { markClean(); if (closeAfterSave.current) { closeAfterSave.current = false; if (docStatusRef.current === "saving" || docStatusRef.current === "failed") setConfirmClose(true); else forceClose(); } };
+ const onDialogSaved = () => {
+ const clean = markClean(pendingRevision.current);
+ if (closeAfterSave.current) {
+ closeAfterSave.current = false;
+ if (!clean || docStatusRef.current === "saving" || docStatusRef.current === "failed") setConfirmClose(true);
+ else forceClose();
+ }
+ };
const common = {
compact,
diff --git a/frontend/slices/os-terminal/lib/use-pty.test.ts b/frontend/slices/os-terminal/lib/use-pty.test.ts
new file mode 100644
index 00000000..0d5d1671
--- /dev/null
+++ b/frontend/slices/os-terminal/lib/use-pty.test.ts
@@ -0,0 +1,39 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { startPty, type PtyStatus } from "./use-pty";
+
+class Stream {
+ static CLOSED = 2;
+ readyState = 1;
+ onopen: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ addEventListener() {}
+ close() {}
+}
+
+afterEach(() => { vi.unstubAllGlobals(); });
+
+describe("terminal input delivery", () => {
+ it.each(["HTTP failure", "network failure"])("stops without replay after %s", async (failure) => {
+ let rejectInput!: (reason: Error) => void;
+ let resolveInput!: (response: Response) => void;
+ const input = new Promise<Response>((resolve, reject) => { resolveInput = resolve; rejectInput = reject; });
+ const fetchMock = vi.fn((url: string) => {
+ if (url.endsWith("/open")) return Promise.resolve({ ok: true, json: async () => ({ id: "test" }) });
+ if (url.endsWith("/input")) return input;
+ return Promise.resolve({ ok: true });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ vi.stubGlobal("EventSource", Stream);
+ vi.stubGlobal("window", { addEventListener: vi.fn(), removeEventListener: vi.fn() });
+ const statuses: PtyStatus[] = [];
+ const handle = await startPty({ cols: 80, rows: 24, onData: () => {}, onStatus: (s) => statuses.push(s) });
+ handle.write("first");
+ handle.write("queued");
+ if (failure === "HTTP failure") resolveInput({ ok: false } as Response);
+ else rejectInput(new Error("connection lost"));
+ await vi.waitFor(() => expect(statuses.at(-1)).toMatchObject({ kind: "error", message: expect.stringContaining("uncertain") }));
+ handle.write("later");
+ expect(fetchMock.mock.calls.filter(([url]) => url.endsWith("/input"))).toHaveLength(1);
+ handle.dispose();
+ });
+});
diff --git a/frontend/slices/reel-editor/app.tsx b/frontend/slices/reel-editor/app.tsx
index 5f48c3b3..f85de113 100644
--- a/frontend/slices/reel-editor/app.tsx
+++ b/frontend/slices/reel-editor/app.tsx
@@ -28,7 +28,7 @@ const HELLO: AiMessage = {
// Reel editor orchestrator: holds playhead/selection/render state, wires the
// history, drag, keyboard, and AI subsystems to the panels.
export default function ReelEditor({ winId }: AppProps) {
- const { comp, apply, undo, redo, canUndo, canRedo } = useHistory();
+ const { comp, draftBaseline, apply, undo, redo, canUndo, canRedo } = useHistory();
const [playing, setPlaying] = useState(false);
const [sel, setSel] = useState<string | null>("c-intro");
const [zoom, setZoom] = useState(3.2);
@@ -44,7 +44,7 @@ export default function ReelEditor({ winId }: AppProps) {
const [cache] = useState(() => new MediaCache());
const [monitor, setMonitor] = useState(true);
const [layout, setLayout] = useLayout();
- const { savedAt, draftError, sessionMedia } = useDraftAutosave(comp, winId);
+ const { savedAt, draftError, sessionMedia } = useDraftAutosave(comp, draftBaseline, winId);
const [settingsOpen, setSettingsOpen] = useState(false);
const rootRef = useRef<HTMLDivElement>(null);
// Latest-ref mirror of the external frame-store for drag handlers (read
@@ -176,4 +176,4 @@ export default function ReelEditor({ winId }: AppProps) {
</div>
</TooltipProvider>
);
-}
\ No newline at end of file
+}
diff --git a/frontend/slices/reel-editor/lib/draft.ts b/frontend/slices/reel-editor/lib/draft.ts
index 39ef6dba..50bbbfef 100644
--- a/frontend/slices/reel-editor/lib/draft.ts
+++ b/frontend/slices/reel-editor/lib/draft.ts
@@ -8,19 +8,21 @@ import { compositionBoundsError } from "./limits";
const KEY = "reel.draft";
-export function loadDraft(): Composition | null {
- if (typeof window === "undefined") return null;
+export function readDraft(): { comp: Composition | null; snapshot: string | null; available: boolean } {
+ if (typeof window === "undefined") return { comp: null, snapshot: null, available: false };
try {
const raw = localStorage.getItem(KEY);
- if (!raw) return null;
+ if (!raw) return { comp: null, snapshot: raw, available: true };
const c = JSON.parse(raw) as Composition;
- if (!c || !Array.isArray(c.tracks) || !Array.isArray(c.clips) || compositionBoundsError(c)) return null;
- return migrateLayerOrder(c);
+ if (!c || !Array.isArray(c.tracks) || !Array.isArray(c.clips) || compositionBoundsError(c)) return { comp: null, snapshot: raw, available: true };
+ return { comp: migrateLayerOrder(c), snapshot: raw, available: true };
} catch {
- return null;
+ return { comp: null, snapshot: null, available: false };
}
}
+export function loadDraft(): Composition | null { return readDraft().comp; }
+
// Drafts saved before tracks became layers used the old default order
// [video, overlay, text, audio] with start-time z-ordering. Under the new
// top-row-is-front rule that order would paint video OVER text/logo, so flip
diff --git a/frontend/slices/reel-editor/lib/history.ts b/frontend/slices/reel-editor/lib/history.ts
index 92268db2..ac70321a 100644
--- a/frontend/slices/reel-editor/lib/history.ts
+++ b/frontend/slices/reel-editor/lib/history.ts
@@ -5,13 +5,14 @@
import { useCallback, useRef, useState } from "react";
import { type Composition, defaultComposition } from "./mock-timeline";
-import { loadDraft } from "./draft";
+import { readDraft } from "./draft";
const LIMIT = 60;
const COALESCE_MS = 400;
export type HistoryApi = {
comp: Composition;
+ draftBaseline: { snapshot: string | null; available: boolean };
/** Apply a transform. Pass `commit:true` to force a fresh undo step. */
apply: (fn: (c: Composition) => Composition, commit?: boolean) => void;
/** Force the next `apply` to start a new undo step. */
@@ -24,7 +25,8 @@ export type HistoryApi = {
export function useHistory(): HistoryApi {
// Resume the auto-saved draft when one exists (client-only component).
- const [comp, setComp] = useState<Composition>(() => loadDraft() ?? defaultComposition());
+ const [initial] = useState(readDraft);
+ const [comp, setComp] = useState<Composition>(() => initial.comp ?? defaultComposition());
const [past, setPast] = useState<Composition[]>([]);
const [future, setFuture] = useState<Composition[]>([]);
const lastPush = useRef(0);
@@ -70,5 +72,5 @@ export function useHistory(): HistoryApi {
});
}, [comp]);
- return { comp, apply, commit, undo, redo, canUndo: past.length > 0, canRedo: future.length > 0 };
+ return { comp, draftBaseline: initial, apply, commit, undo, redo, canUndo: past.length > 0, canRedo: future.length > 0 };
}
diff --git a/frontend/slices/reel-editor/lib/use-draft-autosave.test.ts b/frontend/slices/reel-editor/lib/use-draft-autosave.test.ts
new file mode 100644
index 00000000..46542703
--- /dev/null
+++ b/frontend/slices/reel-editor/lib/use-draft-autosave.test.ts
@@ -0,0 +1,39 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { defaultComposition } from "./mock-timeline";
+
+const hooks = vi.hoisted(() => ({ refs: [] as Array<{ current: unknown }>, states: [] as unknown[], effects: [] as Array<() => void | (() => void)>, cursor: 0, stateCursor: 0 }));
+vi.mock("react", () => ({
+ useRef: (value: unknown) => hooks.refs[hooks.cursor++] ?? (hooks.refs[hooks.cursor - 1] = { current: value }),
+ useState: (value: unknown) => {
+ const i = hooks.stateCursor++;
+ if (!(i in hooks.states)) hooks.states[i] = value;
+ return [hooks.states[i], (next: unknown) => { hooks.states[i] = next; }];
+ },
+ useEffect: (effect: () => void | (() => void)) => { hooks.effects.push(effect); },
+}));
+vi.mock("@/features/appshell", () => ({ setCloseGuard: vi.fn() }));
+vi.mock("./settings", () => ({ getSettings: () => ({ autosave: true }) }));
+import { useDraftAutosave } from "./use-draft-autosave";
+
+afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });
+
+it("preserves a newer recovery draft written between load and effect", () => {
+ vi.useFakeTimers();
+ hooks.refs = []; hooks.states = [];
+ const original = defaultComposition();
+ const oldRaw = JSON.stringify(original);
+ let stored = JSON.stringify({ ...original, w: 1280 });
+ vi.stubGlobal("localStorage", { getItem: () => stored, setItem: (_key: string, value: string) => { stored = value; } });
+ vi.stubGlobal("window", { addEventListener: vi.fn(), removeEventListener: vi.fn() });
+ const baseline = { snapshot: oldRaw, available: true };
+ const useFixture = (comp: typeof original) => {
+ hooks.cursor = 0; hooks.stateCursor = 0; hooks.effects = [];
+ useDraftAutosave(comp, baseline);
+ return hooks.effects.map((effect) => effect());
+ };
+ useFixture(original);
+ useFixture({ ...original, h: 720 });
+ vi.advanceTimersByTime(800);
+ expect(JSON.parse(stored).w).toBe(1280);
+ expect(hooks.states[1]).toContain("Another tab changed");
+});
diff --git a/frontend/slices/reel-editor/lib/use-draft-autosave.ts b/frontend/slices/reel-editor/lib/use-draft-autosave.ts
index e9ceddf3..c86e3c7b 100644
--- a/frontend/slices/reel-editor/lib/use-draft-autosave.ts
+++ b/frontend/slices/reel-editor/lib/use-draft-autosave.ts
@@ -5,12 +5,11 @@ import type { Composition } from "./mock-timeline";
import { saveDraft } from "./draft";
import { getSettings } from "./settings";
-export function useDraftAutosave(comp: Composition, winId?: string) {
+export function useDraftAutosave(comp: Composition, baseline: { snapshot: string | null; available: boolean }, winId?: string) {
const [savedAt, setSavedAt] = useState<number | null>(null);
const [draftError, setDraftError] = useState<string | null>(null);
- const draftSnapshot = useRef<string | null>(null);
- const snapshotReady = useRef(false);
- const firstDraft = useRef(true);
+ const draftSnapshot = useRef(baseline.snapshot);
+ const initialComp = useRef(comp);
const sessionMedia = comp.clips.some((c) => c.media?.url.startsWith("blob:"));
useEffect(() => {
if (!sessionMedia && !draftError) return;
@@ -21,13 +20,11 @@ export function useDraftAutosave(comp: Composition, winId?: string) {
}, [winId, sessionMedia, draftError]);
useEffect(() => {
if (!getSettings().autosave) return;
- if (firstDraft.current) {
- firstDraft.current = false;
- try { draftSnapshot.current = localStorage.getItem("reel.draft"); snapshotReady.current = true; }
- catch { queueMicrotask(() => setDraftError("Timeline could not be saved in this browser.")); }
+ if (comp === initialComp.current) {
+ if (!baseline.available) queueMicrotask(() => setDraftError("Timeline could not be saved in this browser."));
return;
}
- if (!snapshotReady.current) return;
+ if (!baseline.available) return;
const persist = () => {
try {
if (localStorage.getItem("reel.draft") !== draftSnapshot.current) {
@@ -44,6 +41,6 @@ export function useDraftAutosave(comp: Composition, winId?: string) {
const t = setTimeout(persist, 800);
window.addEventListener("pagehide", persist);
return () => { clearTimeout(t); window.removeEventListener("pagehide", persist); persist(); };
- }, [comp]);
+ }, [comp, baseline.available]);
return { savedAt, draftError, sessionMedia };
}