Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(ui): persist workbench window layout across reloads (#799)
Call White1fb68af0d70b
diff --git a/ui/src/apps/registry.tsx b/ui/src/apps/registry.tsxindex 80c861e41..f980077e0 100644--- a/ui/src/apps/registry.tsx+++ b/ui/src/apps/registry.tsx@@ -67,11 +67,12 @@ export const APP_REGISTRY: Record<AppId, AppDefinition> = {accent: '--mint',defaultSize: { width: 820, height: 540 },lockTheme: 'dark',- Component: () => (+ Component: ({ windowId, params }) => (<Suspense fallback={<Loading />}>{/* Each windowed terminal takes a bounded, reused session slot internally so- it gets its own backend session without leaking ids (see AppsTerminalPage). */}- <TerminalBody windowed />+ it gets its own backend session without leaking ids (see AppsTerminalPage).+ windowId + params thread through so the tab layout persists across reloads. */}+ <TerminalBody windowed windowId={windowId} params={params} /></Suspense>),},diff --git a/ui/src/components/apps/AppWindow.tsx b/ui/src/components/apps/AppWindow.tsxindex 408f025db..0d63ca254 100644--- a/ui/src/components/apps/AppWindow.tsx+++ b/ui/src/components/apps/AppWindow.tsx@@ -130,7 +130,12 @@ export const AppWindow: React.FC<{ win: WindowInstance; layerWidth: number; layeGlyph: X,// A dirty editor body can veto the close (confirm) before the exit animation.onClick: () => {- if (wm.confirmClose(win.id)) setExitKind((k) => k ?? 'close');+ // Mark closing so a reload during the ~300ms exit animation doesn't re-persist (and+ // resurrect) this window — it's removed from manager state only at animationEnd.+ if (wm.confirmClose(win.id)) {+ wm.markClosing(win.id);+ setExitKind((k) => k ?? 'close');+ }},label: t('common.close'),},diff --git a/ui/src/components/workbench/AppsTerminalPage.tsx b/ui/src/components/workbench/AppsTerminalPage.tsxindex e040835e3..cc7348acf 100644--- a/ui/src/components/workbench/AppsTerminalPage.tsx+++ b/ui/src/components/workbench/AppsTerminalPage.tsx@@ -5,13 +5,14 @@ import { TerminalTabs } from './TerminalTabs';// The Terminal app. `windowed` fills its AppWindow body; the route adds the page header.// The multi-tab UI + per-tab session/slot lifecycle lives in the reusable TerminalTabs// (so the editor's integrated terminal can mount the same thing later). Design: `iwYIX`.-export const AppsTerminalPage: React.FC<{ windowed?: boolean }> = ({ windowed = false }) => {+// windowId + params thread through for windowed mounts so the tab layout persists across reloads.+export const AppsTerminalPage: React.FC<{ windowed?: boolean; windowId?: string; params?: Record<string, unknown> }> = ({ windowed = false, windowId, params }) => {const { t } = useTranslation();if (windowed) {return (<div className="h-full w-full overflow-hidden bg-surface">- <TerminalTabs windowed />+ <TerminalTabs windowed windowId={windowId} params={params} /></div>);}diff --git a/ui/src/components/workbench/EditorApp.tsx b/ui/src/components/workbench/EditorApp.tsxindex 6f5cbfe63..dde694933 100644--- a/ui/src/components/workbench/EditorApp.tsx+++ b/ui/src/components/workbench/EditorApp.tsx@@ -3,7 +3,8 @@ import { Blocks, Bug, Clock, CodeXml, FilePlus, Files, FileText, FolderOpen, Gitimport { useTranslation } from 'react-i18next';import clsx from 'clsx';-import { useWindowCloseGuard, useWindowManager } from '../../context/WindowManagerContext';+import { useWindowCloseGuard, useWindowManager, useWindowState } from '../../context/WindowManagerContext';+import { MAX_RESTORED_TABS, WINDOW_RESTORE_PARAM } from '../../lib/workbenchPersistence';import { contentUrl, downloadFile, fileMeta, joinPath, parentDir, writeFile, type FsEntry } from '../../lib/filesApi';import { isEditableFile, isEditableMeta, previewOverlayKind, previewRenderKind } from '../../lib/filePreview';import { FileTree } from './FileTree';@@ -22,6 +23,37 @@ const FileEditorPane = lazy(() => import('./FileEditorPane').then((m) => ({ defa// kernel instead — for a raster image / PDF / Office doc, which have no editable text form.type Tab = { id: string; path: string | null; name: string; mtime: number | null; reload?: number; kind?: 'edit' | 'preview' };+// The Editor's persisted snapshot (via useWindowState): the explorer root plus every SAVED tab+// (untitled buffers are dropped — no on-disk file to re-read). Restored by re-reading each file+// from disk for a fresh mtime, so unsaved buffer text / dirty state is deliberately NOT persisted+// (the close-guard already covers loss-of-work at close time).+type EditorRestore = {+ root: string | null;+ tabs: { path: string; name: string; kind?: 'edit' | 'preview' }[];+ activePath: string | null;+};++// Validate a persisted editor snapshot before applying it — the WindowManager stores app state+// opaquely, so a corrupt/hostile localStorage value could carry a non-string root (which would+// crash root.split(...) in the explorer) or malformed tab entries. Returns a sanitized value with+// bad tab entries dropped, or null when the shape is unusable (then the window falls back to its+// normal launch params).+function sanitizeEditorRestore(value: unknown): EditorRestore | null {+ if (!value || typeof value !== 'object') return null;+ const v = value as { root?: unknown; tabs?: unknown; activePath?: unknown };+ const root = typeof v.root === 'string' ? v.root : v.root === null ? null : undefined;+ if (root === undefined) return null; // root must be a string path or null+ // Cap before the flatMap so a corrupt/oversized array can't drive an unbounded fileMeta fan-out.+ const tabs = (Array.isArray(v.tabs) ? v.tabs : []).slice(0, MAX_RESTORED_TABS).flatMap((t): EditorRestore['tabs'] => {+ if (!t || typeof t !== 'object') return [];+ const tb = t as { path?: unknown; name?: unknown; kind?: unknown };+ if (typeof tb.path !== 'string' || typeof tb.name !== 'string') return [];+ const kind = tb.kind === 'preview' ? 'preview' : tb.kind === 'edit' ? 'edit' : undefined;+ return [{ path: tb.path, name: tb.name, kind }];+ });+ return { root, tabs, activePath: typeof v.activePath === 'string' ? v.activePath : null };+}+// A pending file dialog, rendered as the in-window FilePicker overlay.type PickerState = {mode: FilePickerMode;@@ -106,6 +138,10 @@ export const EditorApp: React.FC<{const tabSeq = useRef(0);const untitledSeq = useRef(0);const revealSeq = useRef(0);+ // True while an async session restore is re-reading files from disk: `tabs` is still empty then,+ // so the persistence provider must NOT report that transient empty set (a save landing in the gap+ // would clobber the stored tabs). Cleared as the restored tabs become live — see the mount effect.+ const restorePendingRef = useRef(false);const treeRefreshSeq = useRef(0);// Latest tabs + dirty for async callbacks (reloadTabs) so a reload landing after an in-flight// replace never acts on a stale snapshot and clobbers a buffer the user just edited.@@ -268,6 +304,63 @@ export const EditorApp: React.FC<{// "New File" launched us with a target dir — root the explorer there and start a fresh untitled// buffer (its first save lands in that dir).useEffect(() => {+ // Restore a persisted session (explorer root + saved tabs) when this window was rehydrated on+ // reload — re-reading each file from disk for a fresh mtime, dropping any that vanished. Takes+ // precedence over the launch-file path below; the persisted state fully describes what to open.+ const restore = sanitizeEditorRestore(params?.[WINDOW_RESTORE_PARAM]);+ if (restore && (restore.root != null || restore.tabs.length > 0)) {+ if (restore.root != null) setRoot(restore.root);+ const infos = restore.tabs;+ if (infos.length > 0) {+ restorePendingRef.current = true;+ void (async () => {+ const metas = await Promise.all(+ infos.map(async (info) => {+ try {+ return { info, meta: await fileMeta(info.path), ok: true as const };+ } catch {+ return { info, meta: null, ok: false as const };+ }+ }),+ );+ // Keep only tabs whose file still exists AND still passes the same gate the normal open path+ // applies — an 'edit' tab whose file became a directory / symlink / binary / oversized file+ // is dropped rather than restored as a tab that only errors on read or fails on save.+ // 'preview' tabs keep their lenient handling (FilePreview classifies + degrades on its own).+ const alive = metas.filter((m) => m.ok && m.meta != null && (m.info.kind === 'preview' || isEditableMeta(m.meta)));+ if (alive.length === 0) {+ restorePendingRef.current = false; // nothing restorable — the live empty tab set is now correct+ return; // leave the (already restored) folder open+ }+ // Rebuild in one update to preserve tab order + fresh mtimes; then re-select the saved+ // active tab (falling back to the last if it was among the dropped/vanished files).+ const rebuilt: Tab[] = alive.map((m) => ({ id: `t${++tabSeq.current}`, path: m.info.path, name: m.info.name, mtime: m.meta!.mtime, kind: m.info.kind }));+ // The editor is interactive during the await (root is already set), so the user may have+ // opened / created a tab meanwhile. Merge — restored tabs first, then any tab they opened+ // that a restored one doesn't already cover (dedup saved files by path; untitled buffers+ // have no path, so they always survive) — instead of replacing and discarding their work.+ // Clear the pending flag inside the same update so the provider reports real state exactly+ // when it goes live — no clobber window.+ setTabs((current) => {+ restorePendingRef.current = false;+ const restoredPaths = new Set(rebuilt.map((tb) => tb.path));+ const userOpened = current.filter((tb) => tb.path == null || !restoredPaths.has(tb.path));+ return [...rebuilt, ...userOpened];+ });+ // Re-select the right tab. Keep the user's focused tab if it survived the merge (an+ // untitled buffer, or a file not in the restored set); if it was a saved file the restore+ // deduped away, follow it to the rebuilt tab by path so focus lands on a real tab (not the+ // now-removed id); otherwise select the persisted active tab (fallback last).+ setActive((cur) => {+ const curTab = tabsRef.current.find((tb) => tb.id === cur);+ if (curTab && (curTab.path == null || !rebuilt.some((tb) => tb.path === curTab.path))) return curTab.id;+ const followed = curTab?.path != null ? rebuilt.find((tb) => tb.path === curTab.path) : undefined;+ return (followed ?? rebuilt.find((tb) => tb.path === restore.activePath) ?? rebuilt[rebuilt.length - 1]).id;+ });+ })();+ }+ return;+ }const p = typeof params?.path === 'string' ? params.path : null;if (p) {const name = (typeof params?.filename === 'string' ? params.filename : p.split('/').filter(Boolean).pop()) || p;@@ -296,6 +389,20 @@ export const EditorApp: React.FC<{onDirtyChange?.(anyDirty);}, [anyDirty, onDirtyChange]);+ // Contribute the explorer root + open SAVED tabs (and which is active) to the persisted layout,+ // so a reload re-opens the same folder + files. Untitled buffers have no path, so they're excluded.+ // While an async restore is still in flight, return undefined so buildSnapshot keeps the payload+ // this window was restored WITH, instead of persisting the transient empty tab set.+ useWindowState(windowId, (): EditorRestore | undefined =>+ restorePendingRef.current+ ? undefined+ : {+ root,+ tabs: tabs.filter((tb) => tb.path != null).map((tb) => ({ path: tb.path as string, name: tb.name, kind: tb.kind })),+ activePath: tabs.find((tb) => tb.id === active)?.path ?? null,+ },+ );+// Reflect the active file in the window title, so the Dock + titlebar identify which file this// editor window holds (important when several editor windows are open). Clears to the app title// when nothing is open. setTitle no-ops when unchanged, so this can run on every tab change.diff --git a/ui/src/components/workbench/TerminalTabs.tsx b/ui/src/components/workbench/TerminalTabs.tsxindex f9c52a3b5..a4d290a79 100644--- a/ui/src/components/workbench/TerminalTabs.tsx+++ b/ui/src/components/workbench/TerminalTabs.tsx@@ -4,8 +4,10 @@ import { useTranslation } from 'react-i18next';import clsx from 'clsx';import { useApi } from '../../context/ApiContext';+import { useWindowState } from '../../context/WindowManagerContext';import { apiFetch } from '../../lib/apiFetch';import { acquireTerminalSlot, releaseTerminalSlot } from '../../lib/terminalSlots';+import { MAX_RESTORED_TERMINAL_TABS, WINDOW_RESTORE_PARAM } from '../../lib/workbenchPersistence';import type { TerminalStatus } from './TerminalView';// Lazy so xterm.js stays out of the main bundle until a terminal opens.@@ -31,6 +33,12 @@ function getSessionId(identity: string | null, key?: string): string {type Tab = { key: number; slot: number | null; title?: string };+// The Terminal's persisted snapshot (via useWindowState): just the tab count + any custom titles.+// Windowed terminal sessions are ephemeral by design (slot-based ids, DELETEd on pagehide), so we+// deliberately do NOT persist/reattach session ids — restore re-opens the same number of tabs with+// their names, over fresh shells.+type TerminalRestore = { tabs: { title?: string }[] };+// DELETE a slot-backed terminal session, then release its slot ONLY on a confirmed teardown// (HTTP ok or 404). If the delete failed (expired auth, CSRF/origin rejection, network error, 5xx)// the tmux session may still be alive, so the slot stays reserved — otherwise the next tab could@@ -49,12 +57,26 @@ function deleteTerminalSession(sid: string, slot: number, keepalive = false): vo// - windowed: every tab is an ephemeral, slot-bounded session, disposed on close.// - route (non-windowed): the FIRST tab keeps the persistent localStorage session (so it// reconnects across reloads); extra tabs are slot-bounded like the windowed ones.-export const TerminalTabs: React.FC<{ windowed?: boolean }> = ({ windowed = false }) => {+export const TerminalTabs: React.FC<{ windowed?: boolean; windowId?: string; params?: Record<string, unknown> }> = ({ windowed = false, windowId, params }) => {const { t } = useTranslation();const { getAuthSession } = useApi();const [identity, setIdentity] = useState<string | null | undefined>(undefined); // undefined = resolvingconst tabSeq = useRef(0);- const [tabs, setTabs] = useState<Tab[]>(() => [{ key: ++tabSeq.current, slot: windowed ? acquireTerminalSlot() : null }]);+ // Restore the tab layout (count + custom titles) on reload for a windowed terminal, over fresh+ // slots/shells — the ephemeral session ids are never persisted (a deliberate security property).+ const [tabs, setTabs] = useState<Tab[]>(() => {+ const restore = windowed ? (params?.[WINDOW_RESTORE_PARAM] as TerminalRestore | undefined) : undefined;+ if (restore && Array.isArray(restore.tabs) && restore.tabs.length > 0) {+ // Cap at the backend session capacity before acquiring slots, so a corrupt/oversized array+ // can't open a flood of shells the terminal service can't admit.+ return restore.tabs.slice(0, MAX_RESTORED_TERMINAL_TABS).map((rt) => ({+ key: ++tabSeq.current,+ slot: acquireTerminalSlot(),+ title: typeof rt?.title === 'string' ? rt.title : undefined,+ }));+ }+ return [{ key: ++tabSeq.current, slot: windowed ? acquireTerminalSlot() : null }];+ });const [active, setActive] = useState<number>(() => tabs[0]?.key ?? 0);// Whether sessions actually persist (tmux available) — reported by TerminalView's ready frame.// Drives the tab-bar badge so it never falsely promises persistence for a plain-shell fallback.@@ -74,6 +96,10 @@ export const TerminalTabs: React.FC<{ windowed?: boolean }> = ({ windowed = fals});};+ // Contribute the tab layout (count + custom titles) to the persisted window layout. No-ops for the+ // non-windowed route terminal (windowId undefined), which keeps its own persistent session id.+ useWindowState(windowId, (): TerminalRestore => ({ tabs: tabs.map((tb) => ({ title: tb.title })) }));+useEffect(() => {let cancelled = false;getAuthSession()diff --git a/ui/src/context/WindowManagerContext.tsx b/ui/src/context/WindowManagerContext.tsxindex b56fc08d7..ce6112e70 100644--- a/ui/src/context/WindowManagerContext.tsx+++ b/ui/src/context/WindowManagerContext.tsx@@ -1,6 +1,13 @@import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';import { APP_REGISTRY, type AppId } from '../apps/registry';+import {+ WINDOW_RESTORE_PARAM,+ loadWorkbenchWindows,+ saveWorkbenchWindows,+ stripRestoreParam,+ type PersistedWindow,+} from '../lib/workbenchPersistence';// One open app window. Bounds are in CSS px relative to the window LAYER (the// workbench main area, right of the sidebar). z drives stacking + focus order.@@ -53,6 +60,18 @@ export interface WindowManagerValue {* The getter returns a confirm message when closing would lose work, else null.*/setCloseGuard: (id: string, getMessage: (() => string | null) | null) => void;+ /**+ * Register (or clear, by passing null) a provider a window body uses to contribute its own+ * JSON-able state to the persisted layout (e.g. the Editor's open tabs, the Terminal's tab+ * titles). Read on save; the value comes back through the window's params on the next restore.+ */+ setStateProvider: (id: string, getState: (() => unknown) | null) => void;+ /**+ * Mark a window as closing (its exit animation has started but it's still mounted until+ * animationEnd calls close()). Excludes it from the persisted snapshot so a reload during the+ * ~300ms close animation doesn't write back — and resurrect — a window the user just closed.+ */+ markClosing: (id: string) => void;/** Run a window's close guard (confirm if it has a message); true = may close. */confirmClose: (id: string) => boolean;}@@ -64,21 +83,114 @@ const DEFAULT_SIZE = { width: 760, height: 520 };const CASCADE_STEP = 32;const CASCADE_WRAP = 6;+// Persistence is desktop-only: the window layer is `hidden md:block` and windowed apps open only+// from the desktop-only launcher/Dock, so restoring windows below md would mount invisible bodies+// and a `[]` save from a phone would clobber a real desktop layout. Read live (not frozen at mount)+// so a desktop tab that starts narrow and is widened still restores/saves once it crosses md.+function isDesktopViewport(): boolean {+ return typeof window !== 'undefined' && typeof window.matchMedia === 'function'+ ? window.matchMedia('(min-width: 768px)').matches+ : false;+}+export const WindowManagerProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {- const [windows, setWindows] = useState<WindowInstance[]>([]);const idSeq = useRef(0);const zSeq = useRef(0);const openCount = useRef(0);+ // Whether the persisted layout has been restored yet — set the first time we're on desktop, so a+ // desktop-at-mount restore and a restore-after-widen never both fire.+ const restoredRef = useRef(false);++ // Load the persisted layout and seed the id/z/open sequences past the restored maxima (idempotent)+ // so new windows don't collide with, or open behind, restored ones.+ const loadAndSeed = (): WindowInstance[] => {+ const restored = loadWorkbenchWindows();+ for (const w of restored) {+ const n = Number.parseInt(w.id.slice(4), 10); // strip the validated "win-" prefix+ if (Number.isFinite(n)) idSeq.current = Math.max(idSeq.current, n);+ zSeq.current = Math.max(zSeq.current, w.z);+ }+ openCount.current = Math.max(openCount.current, restored.length);+ return restored;+ };++ // Restore in the lazy initializer when the shell mounts at desktop width, so `windows` never+ // starts empty there (which would let the first debounced save wipe the stored layout). A shell+ // that mounts narrow restores later, on crossing the breakpoint (see the effect below).+ const [windows, setWindows] = useState<WindowInstance[]>(() => {+ if (!isDesktopViewport()) return [];+ restoredRef.current = true;+ return loadAndSeed();+ });++ // Latest windows for the debounced/pagehide save closures (which fire after render).+ const windowsRef = useRef(windows);+ windowsRef.current = windows;+// Per-window close guards: a body (e.g. a dirty editor) registers a getter that// returns a confirm message when closing would lose work. Held in a ref so it// never triggers re-renders.const closeGuards = useRef(new Map<string, () => string | null>());+ // Per-window state providers: a body registers a getter returning its JSON-able snapshot+ // (Editor tabs, Terminal tab titles), read when the layout is saved. Same ref pattern.+ const stateProviders = useRef(new Map<string, () => unknown>());+ // Windows whose close exit animation has started but which are still mounted (removed only at+ // animationEnd). Excluded from the snapshot so a reload mid-animation doesn't re-persist them.+ const closingIds = useRef(new Set<string>());const setCloseGuard = useCallback((id: string, getMessage: (() => string | null) | null) => {if (getMessage) closeGuards.current.set(id, getMessage);else closeGuards.current.delete(id);}, []);+ const setStateProvider = useCallback((id: string, getState: (() => unknown) | null) => {+ if (getState) stateProviders.current.set(id, getState);+ else stateProviders.current.delete(id);+ }, []);++ const markClosing = useCallback((id: string) => {+ closingIds.current.add(id);+ }, []);++ // Snapshot every window plus its body's state (from its provider). A provider that throws+ // contributes no appState rather than failing the whole save. Drop the injected restore payload+ // from params so a re-save keeps only original launch params (no nested stale snapshots).+ const buildSnapshot = useCallback((): PersistedWindow[] =>+ windowsRef.current+ .filter((w) => !closingIds.current.has(w.id))+ .map((w) => {+ let appState: unknown;+ try {+ appState = stateProviders.current.get(w.id)?.();+ } catch {+ appState = undefined;+ }+ // A restored window's lazy body may not have mounted + registered its provider yet. Until+ // it does, carry the payload it was restored WITH (still in params) so a save during that+ // gap doesn't drop the very state we're persisting for.+ if (appState === undefined) appState = w.params?.[WINDOW_RESTORE_PARAM];+ return { ...w, params: stripRestoreParam(w.params), appState };+ }), []);++ // Debounced persistence: coalesce bursts of geometry/z/open-close changes into one write.+ const saveTimer = useRef<number | null>(null);+ const flushSave = useCallback(() => {+ if (saveTimer.current !== null) {+ clearTimeout(saveTimer.current);+ saveTimer.current = null;+ }+ if (!isDesktopViewport()) return; // never persist (incl. clobber with []) from a non-desktop viewport+ saveWorkbenchWindows(buildSnapshot());+ }, [buildSnapshot]);+ const scheduleSave = useCallback(() => {+ if (!isDesktopViewport()) return;+ if (saveTimer.current !== null) clearTimeout(saveTimer.current);+ saveTimer.current = window.setTimeout(() => {+ saveTimer.current = null;+ saveWorkbenchWindows(buildSnapshot());+ }, 400);+ }, [buildSnapshot]);+const confirmClose = useCallback((id: string): boolean => {const message = closeGuards.current.get(id)?.();return !message || window.confirm(message);@@ -128,6 +240,8 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode }> = ({const close = useCallback((id: string) => {closeGuards.current.delete(id);+ stateProviders.current.delete(id);+ closingIds.current.delete(id);setWindows((prev) => prev.filter((w) => w.id !== id));}, []);@@ -170,6 +284,45 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode }> = ({});}, []);+ // If the shell mounted below md (initializer skipped restore), restore the saved layout the first+ // time the viewport crosses to desktop — BEFORE the now-enabled saves could persist an empty list+ // over it. The window list is still empty while narrow (windowed apps open only from the+ // desktop-only launcher), so replacing it here can't discard anything the user opened.+ useEffect(() => {+ if (restoredRef.current) return;+ if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;+ const mql = window.matchMedia('(min-width: 768px)');+ const restoreOnce = () => {+ if (restoredRef.current || !mql.matches) return;+ restoredRef.current = true;+ const restored = loadAndSeed();+ setWindows((cur) => (cur.length ? cur : restored));+ };+ restoreOnce(); // may have crossed to desktop between the initial render and this effect+ mql.addEventListener('change', restoreOnce);+ return () => mql.removeEventListener('change', restoreOnce);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ // Persist on any window-list change (open/close, geometry, z, min/max, title). Body-only state+ // (Editor tabs, Terminal titles) that doesn't touch the window list is captured by the same+ // provider read on the next save this triggers, and — authoritatively — by the pagehide flush.+ // scheduleSave itself no-ops below md, so this stays inert until the viewport is desktop-sized.+ useEffect(() => {+ scheduleSave();+ }, [windows, scheduleSave]);++ // A reload fires pagehide (not React unmount): flush a final synchronous snapshot so the very+ // latest body state (a just-renamed terminal tab, a just-opened editor file) is captured.+ // flushSave no-ops below md, so no phone/narrow viewport ever writes.+ useEffect(() => {+ window.addEventListener('pagehide', flushSave);+ return () => {+ window.removeEventListener('pagehide', flushSave);+ if (saveTimer.current !== null) clearTimeout(saveTimer.current);+ };+ }, [flushSave]);+const focusedId = useMemo(() => {const visible = windows.filter((w) => !w.minimized);if (visible.length === 0) return null;@@ -189,9 +342,11 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode }> = ({setBounds,setTitle,setCloseGuard,+ setStateProvider,+ markClosing,confirmClose,}),- [windows, focusedId, openApp, close, focus, minimize, restore, toggleMaximize, setBounds, setTitle, setCloseGuard, confirmClose],+ [windows, focusedId, openApp, close, focus, minimize, restore, toggleMaximize, setBounds, setTitle, setCloseGuard, setStateProvider, markClosing, confirmClose],);return <WindowManagerContext.Provider value={value}>{children}</WindowManagerContext.Provider>;@@ -216,3 +371,18 @@ export function useWindowCloseGuard(windowId: string | undefined, message: strinreturn () => setCloseGuard(windowId, null);}, [windowId, setCloseGuard]);}++// A window body calls this to contribute its own JSON-able state to the persisted layout, so a+// reload can restore it (Editor open tabs, Terminal tab titles). `getState` may be a fresh closure+// each render — it's held in a ref and read lazily at save time, so it always sees current state+// without re-registering. No-ops for a non-windowed (full-page) mount, where windowId is undefined.+export function useWindowState(windowId: string | undefined, getState: () => unknown): void {+ const { setStateProvider } = useWindowManager();+ const getStateRef = useRef(getState);+ getStateRef.current = getState;+ useEffect(() => {+ if (!windowId) return;+ setStateProvider(windowId, () => getStateRef.current());+ return () => setStateProvider(windowId, null);+ }, [windowId, setStateProvider]);+}diff --git a/ui/src/lib/workbenchPersistence.test.ts b/ui/src/lib/workbenchPersistence.test.tsnew file mode 100644index 000000000..8b5999ac7--- /dev/null+++ b/ui/src/lib/workbenchPersistence.test.ts@@ -0,0 +1,175 @@+import { describe, expect, it } from 'vitest';++import {+ MAX_RESTORED_WINDOWS,+ WINDOW_RESTORE_PARAM,+ parseWorkbenchWindows,+ serializeWorkbenchWindows,+ stripRestoreParam,+ type PersistedWindow,+} from './workbenchPersistence';++const bounds = { x: 120, y: 80, width: 760, height: 520 };++function persisted(overrides: Partial<PersistedWindow> = {}): PersistedWindow {+ return {+ id: 'win-1',+ appId: 'editor',+ bounds,+ z: 1,+ minimized: false,+ maximized: false,+ ...overrides,+ };+}++describe('workbench window persistence — round trip', () => {+ it('serializes and parses a window back to the same rehydratable fields', () => {+ const windows: PersistedWindow[] = [+ persisted({ id: 'win-3', appId: 'terminal', title: 'build', z: 5, minimized: true }),+ ];+ const [w] = parseWorkbenchWindows(serializeWorkbenchWindows(windows));+ expect(w).toMatchObject({ id: 'win-3', appId: 'terminal', title: 'build', z: 5, minimized: true, maximized: false, bounds });+ });++ it('hands a window body its appState back through params under the restore key', () => {+ const appState = { root: '/src', tabs: [{ path: '/src/a.ts', name: 'a.ts' }], activePath: '/src/a.ts' };+ const [w] = parseWorkbenchWindows(serializeWorkbenchWindows([persisted({ appState })]));+ expect(w.params?.[WINDOW_RESTORE_PARAM]).toEqual(appState);+ });++ it('merges appState alongside original launch params without dropping them', () => {+ const raw = serializeWorkbenchWindows([+ persisted({ appId: 'preview', params: { path: '/x.png', name: 'x.png' }, appState: { seen: true } }),+ ]);+ const [w] = parseWorkbenchWindows(raw);+ expect(w.params).toEqual({ path: '/x.png', name: 'x.png', [WINDOW_RESTORE_PARAM]: { seen: true } });+ });++ it('preserves restoreBounds for a maximized window', () => {+ const restoreBounds = { x: 5, y: 6, width: 700, height: 500 };+ const [w] = parseWorkbenchWindows(serializeWorkbenchWindows([persisted({ maximized: true, restoreBounds })]));+ expect(w.restoreBounds).toEqual(restoreBounds);+ });+});++describe('workbench window persistence — corrupt / old data is ignored', () => {+ it('returns [] for invalid JSON', () => {+ expect(parseWorkbenchWindows('{not json')).toEqual([]);+ });++ it('returns [] for null / empty input', () => {+ expect(parseWorkbenchWindows(null)).toEqual([]);+ expect(parseWorkbenchWindows(undefined)).toEqual([]);+ expect(parseWorkbenchWindows('')).toEqual([]);+ });++ it('returns [] for a mismatched schema version', () => {+ expect(parseWorkbenchWindows(JSON.stringify({ version: 2, windows: [persisted()] }))).toEqual([]);+ });++ it('returns [] when windows is not an array', () => {+ expect(parseWorkbenchWindows(JSON.stringify({ version: 1, windows: {} }))).toEqual([]);+ });++ it('drops entries with an unknown appId but keeps valid siblings', () => {+ const raw = JSON.stringify({+ version: 1,+ windows: [persisted({ id: 'win-1', appId: 'ghost-app' }), persisted({ id: 'win-2', appId: 'files' })],+ });+ const result = parseWorkbenchWindows(raw);+ expect(result.map((w) => w.id)).toEqual(['win-2']);+ });++ it('caps the number of restored windows against a corrupt/oversized array', () => {+ const windows = Array.from({ length: MAX_RESTORED_WINDOWS + 25 }, (_, i) => persisted({ id: `win-${i}`, appId: 'files' }));+ expect(parseWorkbenchWindows(serializeWorkbenchWindows(windows))).toHaveLength(MAX_RESTORED_WINDOWS);+ });++ it('rejects ids that are not the generated win-<number> shape', () => {+ // A corrupt id with selector syntax would break `[data-window-id="…"]` queries in the Dock.+ for (const id of ['win-1"]', 'evil', 'win-', 'win-1a', '__proto__']) {+ expect(parseWorkbenchWindows(JSON.stringify({ version: 1, windows: [persisted({ id })] }))).toEqual([]);+ }+ });++ it('rejects id suffixes that are unsafe or lack increment headroom', () => {+ // Beyond MAX_SAFE_INTEGER, and exactly at it (no headroom for ++idSeq) — both dropped.+ expect(parseWorkbenchWindows(JSON.stringify({ version: 1, windows: [persisted({ id: 'win-9007199254740992' })] }))).toEqual([]);+ expect(parseWorkbenchWindows(JSON.stringify({ version: 1, windows: [persisted({ id: 'win-9007199254740991' })] }))).toEqual([]);+ });++ it('rejects unsafe / non-integer z values (they seed the focus counter)', () => {+ for (const z of [Number.MAX_SAFE_INTEGER, 1.5, -1, Number.NaN]) {+ expect(parseWorkbenchWindows(JSON.stringify({ version: 1, windows: [persisted({ z })] }))).toEqual([]);+ }+ expect(parseWorkbenchWindows(serializeWorkbenchWindows([persisted({ z: 7 })]))).toHaveLength(1);+ });++ it('drops duplicate ids so restored windows never collide on key / guard maps', () => {+ const raw = JSON.stringify({+ version: 1,+ windows: [persisted({ id: 'win-1', appId: 'files' }), persisted({ id: 'win-1', appId: 'editor' }), persisted({ id: 'win-2', appId: 'terminal' })],+ });+ // First win-1 wins; the duplicate is dropped; win-2 is kept.+ expect(parseWorkbenchWindows(raw).map((w) => `${w.id}:${w.appId}`)).toEqual(['win-1:files', 'win-2:terminal']);+ });++ it('rejects nonsensical bounds (zero / negative / enormous) while keeping sane ones', () => {+ const bad = [+ { x: 0, y: 0, width: 0, height: 400 },+ { x: 0, y: 0, width: -800, height: 400 },+ { x: 0, y: 0, width: 500, height: 10 }, // below MIN_H+ { x: 0, y: 0, width: 1e9, height: 400 },+ ];+ for (const b of bad) {+ expect(parseWorkbenchWindows(JSON.stringify({ version: 1, windows: [persisted({ bounds: b })] }))).toEqual([]);+ }+ expect(parseWorkbenchWindows(serializeWorkbenchWindows([persisted()]))).toHaveLength(1);+ });++ it('rejects inherited Object keys as appIds (own registry keys only)', () => {+ // A corrupt/hostile blob must not sneak "toString" / "__proto__" through an `in` check —+ // APP_REGISTRY[thatKey] would resolve to a non-app value and crash the window layer.+ for (const appId of ['toString', 'constructor', 'hasOwnProperty', '__proto__']) {+ expect(parseWorkbenchWindows(JSON.stringify({ version: 1, windows: [persisted({ appId })] }))).toEqual([]);+ }+ });++ it('drops entries with malformed bounds or missing fields', () => {+ const raw = JSON.stringify({+ version: 1,+ windows: [+ { id: 'win-1', appId: 'editor', bounds: { x: 'nope', y: 0, width: 1, height: 1 }, z: 1, minimized: false, maximized: false },+ { id: 'win-2', appId: 'editor', z: 1, minimized: false, maximized: false }, // no bounds+ persisted({ id: 'win-3', appId: 'files' }),+ ],+ });+ expect(parseWorkbenchWindows(raw).map((w) => w.id)).toEqual(['win-3']);+ });++ it('does not copy unexpected keys off a stored blob onto the runtime window', () => {+ const raw = JSON.stringify({+ version: 1,+ windows: [{ ...persisted(), evil: 'x', z: 2 }],+ });+ const [w] = parseWorkbenchWindows(raw);+ expect(w).not.toHaveProperty('evil');+ });+});++describe('stripRestoreParam', () => {+ it('removes the injected restore key but keeps real launch params', () => {+ expect(stripRestoreParam({ path: '/a.ts', [WINDOW_RESTORE_PARAM]: { x: 1 } })).toEqual({ path: '/a.ts' });+ });++ it('returns undefined when the restore key was the only entry', () => {+ expect(stripRestoreParam({ [WINDOW_RESTORE_PARAM]: { x: 1 } })).toBeUndefined();+ });++ it('passes through params with no restore key unchanged', () => {+ const p = { path: '/a.ts' };+ expect(stripRestoreParam(p)).toBe(p);+ expect(stripRestoreParam(undefined)).toBeUndefined();+ });+});diff --git a/ui/src/lib/workbenchPersistence.ts b/ui/src/lib/workbenchPersistence.tsnew file mode 100644index 000000000..742365e96--- /dev/null+++ b/ui/src/lib/workbenchPersistence.ts@@ -0,0 +1,191 @@+// Versioned localStorage persistence for the desktop window layer.+//+// The WindowManager holds every open app window in memory (see WindowManagerContext),+// so a browser reload used to lose the whole workbench: which windows were open, their+// geometry / z-order / min-max state, the Editor's folder + file tabs, and the Terminal's+// tab layout. This module serializes that layout to localStorage under a versioned key and+// rebuilds it on the next mount. SPA navigation already survives (the provider lives in the+// AppShell layout route); this covers a real page reload.+//+// Only the geometry lives here directly. Each window body (the Editor, the Terminal) captures+// its own JSON-able snapshot via a state provider (see useWindowState) into `appState`; on+// restore that blob is handed back to the body through its launch params under+// WINDOW_RESTORE_PARAM, so this layer never has to know what any app stores.++import { APP_REGISTRY } from '../apps/registry';+import { MIN_H, MIN_W } from './windowBounds';+import type { WindowBounds, WindowInstance } from '../context/WindowManagerContext';++// Bump the version suffix to invalidate an incompatible on-disk shape — a stored value under+// an older key is simply never read, so old data is ignored silently (not migrated).+export const WORKBENCH_WINDOWS_STORAGE_KEY = 'avibe.workbench.windows.v1';++// The launch-param key under which a restored window's captured body state is handed back to+// its app body (alongside any original launch params). The Editor + Terminal read it on mount+// to re-open their tabs; apps without persisted state ignore it.+export const WINDOW_RESTORE_PARAM = '__avibeRestoredState';++// Sanity caps against a corrupt/oversized stored value — well above any real workbench, but bounded+// so one bad localStorage entry can't spawn thousands of windows / tabs / shells and freeze the UI.+export const MAX_RESTORED_WINDOWS = 40;+export const MAX_RESTORED_TABS = 50;+// Terminals are backend-bounded (the terminal service admits only ~8 sessions by default), so a+// restored terminal window uses a tighter cap than the editor — restoring more would just flood the+// backend with shells it can't admit.+export const MAX_RESTORED_TERMINAL_TABS = 8;+// Largest dimension we accept from storage. Well beyond any real display, but bounded so a corrupt+// entry can't rehydrate an absurdly sized window.+const MAX_DIM = 100_000;++// One window as persisted. Mirrors the rehydratable subset of WindowInstance, plus the body's+// own snapshot in `appState`. This is the on-disk schema — keep it explicit and stable; change+// the storage-key version if it changes incompatibly.+export interface PersistedWindow {+ id: string;+ appId: string;+ title?: string;+ params?: Record<string, unknown>;+ bounds: WindowBounds;+ z: number;+ minimized: boolean;+ maximized: boolean;+ restoreBounds?: WindowBounds;+ appState?: unknown;+}++interface PersistedPayload {+ version: 1;+ windows: PersistedWindow[];+}++function isFiniteNumber(v: unknown): v is number {+ return typeof v === 'number' && Number.isFinite(v);+}++// The id suffix and z-index are seeded into the idSeq/zSeq counters that new windows increment from.+// A restored value must be a non-negative integer with headroom below the safe-integer ceiling, so+// those counters can keep incrementing precisely — a value at/near MAX_SAFE_INTEGER would let the+// next ++ round to a duplicate. Headroom is far larger than any session's window/focus count.+const MAX_SAFE_SEQ = Number.MAX_SAFE_INTEGER - 1_000_000;+function isSaneSeq(v: unknown): v is number {+ return typeof v === 'number' && Number.isInteger(v) && v >= 0 && v <= MAX_SAFE_SEQ;+}++function isBounds(v: unknown): v is WindowBounds {+ if (!v || typeof v !== 'object') return false;+ const b = v as Record<string, unknown>;+ if (!isFiniteNumber(b.x) || !isFiniteNumber(b.y) || !isFiniteNumber(b.width) || !isFiniteNumber(b.height)) return false;+ // Sizes must be within the range real drag/resize can produce (>= the enforced minimum, not+ // absurdly large). Rejects a corrupt entry that would rehydrate a zero/negative/enormous — i.e.+ // invisible or unrecoverable — window. Origin (x/y) may be off-screen; the layer re-clamp on+ // mount pulls the titlebar back into reach, so it needs no bound here.+ return b.width >= MIN_W && b.width <= MAX_DIM && b.height >= MIN_H && b.height <= MAX_DIM;+}++function isPlainObject(v: unknown): v is Record<string, unknown> {+ return !!v && typeof v === 'object' && !Array.isArray(v);+}++// A stored window is usable only if every rehydratable field is well-formed AND its app is still+// registered — a window whose app was removed (or a corrupt entry) is dropped, not restored blank.+function toRuntimeWindow(v: unknown): WindowInstance | null {+ if (!isPlainObject(v)) return null;+ const { id, appId, title, params, bounds, z, minimized, maximized, restoreBounds, appState } = v;+ // Ids are only ever minted as `win-<number>` (see openApp). Enforce that shape AND a sane-sequence+ // suffix so a corrupt id can't break `[data-window-id="…"]` selector queries (the Dock focuses a+ // window that way) or poison the id sequence new windows increment from (a value at/beyond the+ // safe-integer ceiling would let ++idSeq collide with a restored id).+ if (typeof id !== 'string' || !/^win-\d+$/.test(id) || !isSaneSeq(Number(id.slice(4)))) return null;+ // OWN keys only: `in` would accept inherited object keys ("toString", "__proto__") from a corrupt+ // blob, and APP_REGISTRY[thatKey] would then resolve to a non-app value that crashes the layer.+ if (typeof appId !== 'string' || !Object.prototype.hasOwnProperty.call(APP_REGISTRY, appId)) return null;+ // z seeds the focus counter — same sane-sequence bound as the id, so ++zSeq stays precise (a huge+ // z would make newly focused windows share a z and fail to come to the front).+ if (!isBounds(bounds) || !isSaneSeq(z) || typeof minimized !== 'boolean' || typeof maximized !== 'boolean') {+ return null;+ }+ if (restoreBounds !== undefined && !isBounds(restoreBounds)) return null;++ const launchParams = isPlainObject(params) ? params : undefined;+ // Hand the body its captured state back through params, so restore reuses the exact same+ // launch path an app already reads (Editor/Terminal check WINDOW_RESTORE_PARAM on mount).+ const nextParams =+ appState !== undefined ? { ...(launchParams ?? {}), [WINDOW_RESTORE_PARAM]: appState } : launchParams;++ // Rebuild explicitly (never spread the raw stored object) so a corrupt/hostile blob can't+ // smuggle unexpected keys onto the runtime window.+ return {+ id,+ appId: appId as WindowInstance['appId'],+ ...(typeof title === 'string' ? { title } : {}),+ ...(nextParams ? { params: nextParams } : {}),+ bounds: { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height },+ z,+ minimized,+ maximized,+ ...(restoreBounds ? { restoreBounds: { x: restoreBounds.x, y: restoreBounds.y, width: restoreBounds.width, height: restoreBounds.height } } : {}),+ };+}++// Parse a raw stored payload into runtime windows. Pure (no storage access) so it's unit-testable;+// any corruption — invalid JSON, wrong/absent version, non-array, bad entries — yields [] or drops+// just the bad entries, never throws.+export function parseWorkbenchWindows(raw: string | null | undefined): WindowInstance[] {+ if (!raw) return [];+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return [];+ }+ if (!isPlainObject(parsed) || parsed.version !== 1 || !Array.isArray(parsed.windows)) return [];+ const windows: WindowInstance[] = [];+ const seenIds = new Set<string>();+ // Bound the scan + output so a corrupt/oversized array can't build thousands of windows, and drop+ // duplicate ids — two `win-1` entries would collide React keys and the per-id guard/state maps.+ for (const entry of parsed.windows.slice(0, MAX_RESTORED_WINDOWS)) {+ const w = toRuntimeWindow(entry);+ if (w && !seenIds.has(w.id)) {+ seenIds.add(w.id);+ windows.push(w);+ }+ }+ return windows;+}++// Serialize windows to the versioned payload string. Pure; may throw if a body's appState is not+// JSON-serializable (callers wrap this — a bad snapshot must never crash the shell).+export function serializeWorkbenchWindows(windows: PersistedWindow[]): string {+ const payload: PersistedPayload = { version: 1, windows };+ return JSON.stringify(payload);+}++// Remove the injected restore payload from a window's params so a re-save persists only the+// original launch params — the fresh appState replaces it, and re-persisting it would nest a+// stale snapshot inside params on every reload.+export function stripRestoreParam(+ params: Record<string, unknown> | undefined,+): Record<string, unknown> | undefined {+ if (!params || !(WINDOW_RESTORE_PARAM in params)) return params;+ const { [WINDOW_RESTORE_PARAM]: _drop, ...rest } = params;+ return Object.keys(rest).length ? rest : undefined;+}++// Read + parse the persisted layout. Returns [] when storage is unavailable or empty.+export function loadWorkbenchWindows(): WindowInstance[] {+ try {+ return parseWorkbenchWindows(window.localStorage.getItem(WORKBENCH_WINDOWS_STORAGE_KEY));+ } catch {+ return [];+ }+}++// Serialize + write the layout. Silently drops on any failure (storage disabled / quota exceeded /+// a non-serializable snapshot) — persistence is best-effort and must never interrupt the user.+export function saveWorkbenchWindows(windows: PersistedWindow[]): void {+ try {+ window.localStorage.setItem(WORKBENCH_WINDOWS_STORAGE_KEY, serializeWorkbenchWindows(windows));+ } catch {+ // ignore+ }+}