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(frontend): allow relinking recovered media

Abdurrahman Fakhrul155f511e5f6a
diff --git a/docs/evidence/2026-11-04-frontend-workspace.md b/docs/evidence/2026-11-04-frontend-workspace.md
index 5e5182f1..e03a8759 100644
--- a/docs/evidence/2026-11-04-frontend-workspace.md
+++ b/docs/evidence/2026-11-04-frontend-workspace.md
@@ -6,8 +6,8 @@ Base: origin/main 266c24cb. Changes are local to the isolated workspace worktree
| --- | --- |
| WS-01 | Implemented explicit write result; failed Save and Close remains open with an error. Needs browser rejection/retry journey. |
| WS-02 | Implemented per-window working-set state, all-tab dirty guard, save-all, and tab close confirmation. Browser shell remount, partial save and focus return need verification. |
-| WS-03 | Partial: reports storage failure, flushes pending draft, warns about session-only uploads and guards exit. Asset relink or durable asset persistence is not implemented, and actual reload/media recovery needs testing. |
-| WS-04 | Partial: serialized host writes, status, and retry. Pending changes flush on unmount/pagehide and incomplete saves warn on exit; browser teardown may interrupt the request, so verify failure, close/reload and out-of-order requests. |
+| WS-03 | Reports storage failure, flushes pending draft, hides saved status for session-only uploads, warns and guards exit, and offers a file chooser to relink each restored upload. Actual reload/media recovery needs browser testing; assets remain session-only and must be relinked after each reload. |
+| WS-04 | Serialized host writes, status, retry and a close veto on incomplete save, with explicit discard. Pending changes flush on unmount/pagehide; browser teardown may interrupt requests, so verify failure, close/reload and out-of-order requests. |
| WS-05 | Payload identity resets paging, including reopening the same path; needs shell reuse journey. |
| WS-06 | Scoped arrows to focused window; needs editable, iframe and cross-window journey. |
| WS-07 | Unified fixed 44px list geometry and virtualizer; large text and touch geometry need browser measurement. |
@@ -23,3 +23,5 @@ Base: origin/main 266c24cb. Changes are local to the isolated workspace worktree
| WSC-04 | Deferred: not in confirmed scope; retry/power lifecycle was not changed. |
Validation with umask 077: targeted ESLint passed on changed source paths; TypeScript noEmit passed after final changes; architecture check and git diff --check passed; draft and media kinds tests passed 25/25, including a new quota failure check. Initial architecture check detected 48 files over 220; extracting draft lifecycle restored the ratchet to 47. No full build, full preflight, security scan, browser journeys, device testing, CI, or production runtime was run, by task direction. Targeted tests do not prove the untested behaviors listed above.
+
+Follow-up: targeted draft and relink tests passed 22/22, including unrelated-asset preservation and incompatible MIME rejection; TypeScript, architecture and diff checks passed. Browser file chooser, actual decoding, reload, and rejected project-write journeys remain untested.
diff --git a/frontend/slices/media-studio/app.tsx b/frontend/slices/media-studio/app.tsx
index f60a9208..806b68db 100644
--- a/frontend/slices/media-studio/app.tsx
+++ b/frontend/slices/media-studio/app.tsx
@@ -26,6 +26,7 @@ export default function MediaStudio({ payload, winId }: AppProps) {
const docQueue = useRef<Promise<void>>(Promise.resolve());
const saveDoc = useCallback((doc: NonNullable<typeof latestDoc.current>) => {
latestDoc.current = doc;
+ docStatusRef.current = "saving";
setDocStatus("saving");
docQueue.current = docQueue.current.catch(() => {}).then(async () => {
const response = await fetch("/api/v1/fs/write", {
@@ -33,8 +34,8 @@ export default function MediaStudio({ payload, winId }: AppProps) {
body: JSON.stringify({ path: p?.path, content: JSON.stringify(doc) }),
});
if (!response.ok) throw new Error("Save failed");
- }).then(() => { if (latestDoc.current === doc) setDocStatus("saved"); })
- .catch(() => { if (latestDoc.current === doc) setDocStatus("failed"); });
+ }).then(() => { if (latestDoc.current === doc) { docStatusRef.current = "saved"; setDocStatus("saved"); } })
+ .catch(() => { if (latestDoc.current === doc) { docStatusRef.current = "failed"; setDocStatus("failed"); } });
}, [p?.path]);
// Container-first responsiveness: the editor reflows off its PANE width (a
// 390px desktop window gets the compact layout, not just phones).
@@ -47,7 +48,7 @@ export default function MediaStudio({ payload, winId }: AppProps) {
useEffect(() => {
if (!winId) return;
setCloseGuard(winId, () => {
- if (!dirty.current) return docStatusRef.current === "saving" || docStatusRef.current === "failed" ? window.confirm("Project save is incomplete. Close anyway?") : true;
+ if (!dirty.current && docStatusRef.current !== "saving" && docStatusRef.current !== "failed") return true;
setConfirmClose(true);
return false;
});
@@ -89,7 +90,7 @@ export default function MediaStudio({ payload, winId }: AppProps) {
setPending(url);
};
- const onDialogSaved = () => { markClean(); if (closeAfterSave.current) { closeAfterSave.current = false; forceClose(); } };
+ const onDialogSaved = () => { markClean(); if (closeAfterSave.current) { closeAfterSave.current = false; if (docStatusRef.current === "saving" || docStatusRef.current === "failed") setConfirmClose(true); else forceClose(); } };
const common = {
compact,
@@ -130,12 +131,12 @@ export default function MediaStudio({ payload, winId }: AppProps) {
<FormDrawer open={confirmClose} onOpenChange={(o) => !o && setConfirmClose(false)} variant="alert" size="sm">
<FormDrawer.Header>
<FormDrawer.Title>Save changes before closing?</FormDrawer.Title>
- <FormDrawer.Description>Your image has unsaved edits. They’ll be lost if you don’t save.</FormDrawer.Description>
+ <FormDrawer.Description>{docStatus === "failed" ? "The project could not be saved. Retry or explicitly discard the unsaved project changes." : docStatus === "saving" ? "The project is still saving. Wait for it to finish or explicitly discard the unsaved project changes." : "Your image has unsaved edits. They’ll be lost if you don’t save."}</FormDrawer.Description>
</FormDrawer.Header>
<FormDrawer.Footer>
<Button variant="ghost" onClick={() => setConfirmClose(false)}>Cancel</Button>
<Button variant="ghost" className="text-destructive" onClick={() => { setConfirmClose(false); forceClose(); }}>Don’t Save</Button>
- <Button onClick={saveThenClose}>Save</Button>
+ {docStatus === "failed" ? <Button onClick={() => latestDoc.current && saveDoc(latestDoc.current)}>Retry project save</Button> : <Button disabled={docStatus === "saving"} onClick={saveThenClose}>Save image</Button>}
</FormDrawer.Footer>
</FormDrawer>
</>
diff --git a/frontend/slices/reel-editor/app.tsx b/frontend/slices/reel-editor/app.tsx
index 33be78a1..5f48c3b3 100644
--- a/frontend/slices/reel-editor/app.tsx
+++ b/frontend/slices/reel-editor/app.tsx
@@ -16,6 +16,7 @@ import { ReelPanes } from "./components/reel-panes";
import { useLayout } from "./lib/use-layout";
import { type AiMessage } from "./components/ai-panel";
import { RenderOverlay } from "./components/render-overlay";
+import { AssetRecovery } from "./components/asset-recovery";
import { useExport } from "./lib/use-export";
import { useReelInspector } from "./lib/use-reel-inspector";
import { useContainer, useIsMobile } from "./lib/host";
@@ -98,11 +99,8 @@ export default function ReelEditor({ winId }: AppProps) {
onMouseDown={() => rootRef.current?.focus({ preventScroll: true })}
className="@container relative flex h-full flex-col bg-background text-foreground outline-none"
>
- {(draftError || sessionMedia) && (
- <div role="status" className="shrink-0 bg-warning/15 px-3 py-2 text-sm text-foreground">
- {draftError ?? "Uploaded media is available only in this session. Keep the original files to restore the project."}
- </div>
- )}
+ {draftError && <div role="alert" className="shrink-0 bg-warning/15 px-3 py-2 text-sm">{draftError}</div>}
+ <AssetRecovery comp={comp} apply={apply} />
<ReelChrome
comp={comp}
mode={mode}
@@ -111,7 +109,7 @@ export default function ReelEditor({ winId }: AppProps) {
canUndo={canUndo}
canRedo={canRedo}
layout={layout}
- savedAt={savedAt}
+ savedAt={sessionMedia ? null : savedAt}
compact={compact}
addMedia={addMedia}
ratio={ratio}
diff --git a/frontend/slices/reel-editor/components/asset-recovery.tsx b/frontend/slices/reel-editor/components/asset-recovery.tsx
new file mode 100644
index 00000000..bb29dc5c
--- /dev/null
+++ b/frontend/slices/reel-editor/components/asset-recovery.tsx
@@ -0,0 +1,61 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import type { Composition, MediaType } from "../lib/mock-timeline";
+import { probeMedia } from "../lib/media-cache";
+import { acceptsRelinkType, replaceMedia } from "../lib/relink-media";
+
+export function AssetRecovery({ comp, apply }: {
+ comp: Composition;
+ apply: (fn: (c: Composition) => Composition, commit?: boolean) => void;
+}) {
+ // Blob URLs restored from a previous page cannot be decoded in this page.
+ const [missing, setMissing] = useState(() => new Set(comp.clips.flatMap((c) =>
+ c.media?.url.startsWith("blob:") ? [c.media.url] : [])));
+ const [error, setError] = useState<string | null>(null);
+ const owned = useRef<string[]>([]);
+ const alive = useRef(true);
+ useEffect(() => { const urls = owned.current; alive.current = true; return () => { alive.current = false; urls.forEach((url) => URL.revokeObjectURL(url)); }; }, []);
+ const assets = Array.from(new Map(comp.clips.flatMap((c) =>
+ c.media?.url.startsWith("blob:") ? [[c.media.url, { url: c.media.url, name: c.name, type: c.media.type }] as const] : [])).values());
+
+ async function relink(oldUrl: string, type: MediaType, file: File) {
+ if (!acceptsRelinkType(type, file.type)) {
+ setError("Choose a file of the same media type.");
+ return;
+ }
+ const url = URL.createObjectURL(file);
+ try {
+ const metadata = await probeMedia(url, type);
+ if (!alive.current) { URL.revokeObjectURL(url); return; }
+ owned.current.push(url);
+ apply((current) => replaceMedia(current, oldUrl, { url, type, ...metadata }), true);
+ setMissing((current) => { const next = new Set(current); next.delete(oldUrl); return next; });
+ setError(null);
+ } catch {
+ URL.revokeObjectURL(url);
+ if (alive.current) setError("Could not read that file. Choose a compatible original and try again.");
+ }
+ }
+
+ if (!assets.length) return null;
+ return (
+ <section aria-label="Uploaded media recovery" className="max-h-40 shrink-0 overflow-y-auto border-b bg-warning/15 px-3 py-2 text-sm">
+ <p>Uploaded media is available only in this session. Keep the original files and relink them after reopening.</p>
+ {assets.map((asset) => (
+ <div key={asset.url} className="flex flex-wrap items-center gap-2">
+ <span>{asset.name}: {missing.has(asset.url) ? "Needs relinking" : "Session only"}</span>
+ <label className="flex flex-wrap items-center gap-2">
+ Relink {asset.name}
+ <input className="max-w-full rounded border text-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary" type="file" accept={asset.type + "/*"} onChange={(e) => {
+ const file = e.currentTarget.files?.[0];
+ if (file) void relink(asset.url, asset.type, file);
+ e.currentTarget.value = "";
+ }} />
+ </label>
+ </div>
+ ))}
+ {error && <p role="alert">{error}</p>}
+ </section>
+ );
+}
diff --git a/frontend/slices/reel-editor/lib/relink-media.test.ts b/frontend/slices/reel-editor/lib/relink-media.test.ts
new file mode 100644
index 00000000..e06952e7
--- /dev/null
+++ b/frontend/slices/reel-editor/lib/relink-media.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+import { defaultComposition } from "./mock-timeline";
+import { acceptsRelinkType, replaceMedia } from "./relink-media";
+
+describe("replaceMedia", () => {
+ it("updates all clips sharing the missing asset while preserving timing and other clips", () => {
+ const base = defaultComposition();
+ const original = { url: "blob:old", type: "video" as const, natW: 10, natH: 10 };
+ const comp = { ...base, clips: base.clips.map((clip, index) => index < 2 ? { ...clip, media: original } : clip) };
+ const replacement = { ...original, url: "blob:new" };
+ const result = replaceMedia(comp, "blob:old", replacement);
+ expect(result.clips[0].media).toEqual(replacement);
+ expect(result.clips[1].media).toEqual(replacement);
+ expect(result.clips[0].start).toBe(comp.clips[0].start);
+ expect(result.clips[2]).toBe(comp.clips[2]);
+ expect(comp.clips[0].media).toBe(original);
+ });
+ it("leaves unrelated media untouched if the old URL is absent", () => {
+ const comp = defaultComposition();
+ const result = replaceMedia(comp, "blob:missing", { url: "blob:new", type: "image", natW: 1, natH: 1 });
+ expect(result.clips).toEqual(comp.clips);
+ });
+});
+
+it("rejects a file of a different media type", () => {
+ expect(acceptsRelinkType("video", "image/png")).toBe(false);
+ expect(acceptsRelinkType("video", "video/webm")).toBe(true);
+});
diff --git a/frontend/slices/reel-editor/lib/relink-media.ts b/frontend/slices/reel-editor/lib/relink-media.ts
new file mode 100644
index 00000000..b3978838
--- /dev/null
+++ b/frontend/slices/reel-editor/lib/relink-media.ts
@@ -0,0 +1,13 @@
+import type { Composition, MediaRef, MediaType } from "./mock-timeline";
+
+/** Replace references to one recovered asset without changing timeline edits. */
+export function replaceMedia(comp: Composition, oldUrl: string, media: MediaRef): Composition {
+ return {
+ ...comp,
+ clips: comp.clips.map((clip) => clip.media?.url === oldUrl ? { ...clip, media } : clip),
+ };
+}
+
+export function acceptsRelinkType(type: MediaType, mime: string): boolean {
+ return !mime || mime.startsWith(type + "/");
+}