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.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
fix(ui): surface refresh and persistence failures
Abdurrahman Fakhrulcc1e5ed887b9
diff --git a/components/external-app-frame.tsx b/components/external-app-frame.tsxindex 60afa47a..5883c404 100644--- a/components/external-app-frame.tsx+++ b/components/external-app-frame.tsx@@ -34,6 +34,7 @@ function ExternalAppFrameContent({ app, frameTitle }: { app: WorkflowEmbed; fram{loading ? <div className="absolute inset-x-0 top-0 z-10 border-b bg-background px-3 py-2 text-xs text-muted-foreground" role="status">{slow ? `Taking longer than expected. Open ${app.title} in a new tab if its login or frame policy blocks embedding.` : `Loading ${app.title}…`}</div> : null}<iframe key={`${revision}:${app.sandbox}`} src={app.url} title={frameTitle ?? `${app.title} application`} sandbox={app.sandbox} referrerPolicy="no-referrer" className="h-full w-full border-0 bg-background" onLoad={() => setLoading(false)} onError={() => { setLoading(true); setSlow(true); }}/></div> : <div className="flex min-h-0 flex-1 items-center justify-center p-6 text-center text-sm text-muted-foreground">{app.reason || `${app.title} opens in a separate tab. Embedded access is not enabled for this provider.`}</div>}+ {app.renderer === "iframe" && !loading && <p role="status" className="shrink-0 border-t px-3 py-2 text-xs text-muted-foreground">If the embedded app is blank or sign-in is blocked, open {app.title} in a new tab.</p>}<p className="shrink-0 border-t px-3 py-1.5 text-xs text-muted-foreground [@media(max-height:520px)]:sr-only">{app.msoSession ? `${app.title} uses your MSO session.` : `${app.title} keeps its own login. Sign in in a new tab, then reload here. If embedding is blocked, use Open ${app.title}.`}</p></div>;}diff --git a/docs/evidence/2026-11-04-frontend-surfaces.md b/docs/evidence/2026-11-04-frontend-surfaces.mdnew file mode 100644index 00000000..83c9391a--- /dev/null+++ b/docs/evidence/2026-11-04-frontend-surfaces.md@@ -0,0 +1,19 @@+# Frontend surfaces handoff++Base: main 266c24cb. Branch: codex/frontend-surfaces-20261104. Draft candidate.++| Audit | Change | Verification still needed |+|---|---|---|+| PX-01/02 | Abort superseded infrastructure reads. Separate loading, empty and errors. Name Refresh and identify stale inventory. | Reverse delayed project and zone responses. Exercise 403, failed verification, retry and provider change. |+| PX-03 | Open. Native manager selection and Composio session identity remain separate. | Define a server-validated owner and connection binding for lookup, creation and cache reuse. Use synthetic owners and multiple connections before enabling it. |+| PX-04/05/06 | Associate Create App labels, expose selected swatches and wrap them. Keep nonsecret fields per window with close and reload guards. | Test label click and keyboard, 320px coarse, 200% text, remount and canceled discard. |+| PX-07 | Show an error when an n8n refresh fails and a prior embed remains. | Force network rejection after initial success, then retry. Verify denial clears the previous embed. |+| PX-08 | Show stale telemetry, last sample time and process failures. Ignore superseded poll results. | Test slow requests, hide/show, disconnect and recovery. |+| PX-09 | Bound Composio tools disclosure height and allow internal scroll. | Test 100 and 500 tools in short and narrow panes, with keyboard and larger text. |+| ST-01 | Write browser storage before publishing state. Show failure in Store confirmation or Create App. | Force quota failure and retry install, uninstall, feature toggle and creation. |+| ST-02 | Publish Skills catalog and discovery from one refresh generation. Serialize writes. | Reverse response order and test concurrent extension events during a mutation. |+| ST-03 | Keep recovery guidance visible when the external frame finishes loading. | Test framing denial, timeout and open-in-new-tab across connected apps and n8n. |++State belongs to the existing browser registry, exact window, or current request. External frames retain their origin and sandbox settings. The UI keeps the existing owner checks.++TypeScript, architecture and changed-file lint are the scoped checks for this candidate. Full local build and browser journeys, security preflight and remote checks are pending for the next agent. Run the repository gates on the committed SHA before promoting the draft. Roll back by reverting this package's commit.diff --git a/frontend/slices/app-store/components/apps-panel.tsx b/frontend/slices/app-store/components/apps-panel.tsxindex f78df4ed..ceea5236 100644--- a/frontend/slices/app-store/components/apps-panel.tsx+++ b/frontend/slices/app-store/components/apps-panel.tsx@@ -118,6 +118,7 @@ export default function AppStore({ systemOnly = false }: { systemOnly?: boolean<Inputvalue={query}onChange={(e) => setQuery(e.target.value)}+ aria-label={isSystem ? `Search ${noun}s` : "Search apps"}placeholder={isSystem ? `Search ${noun}s` : "Search apps"}className={ios ? "h-9 border-0 bg-[var(--fill)] pl-8" : "h-9 pl-8"}/>@@ -128,6 +129,7 @@ export default function AppStore({ systemOnly = false }: { systemOnly?: boolean><ScrollArea className="h-full"><div ref={storeZone} className="p-4 [padding-bottom:calc(1rem+var(--sai-bottom))]">+ {install.error && <p role="alert" className="mb-3 text-sm text-destructive-text">{install.error}</p>}{isSystem ? (<><p className="mb-3 text-xs text-muted-foreground">@@ -136,6 +138,7 @@ export default function AppStore({ systemOnly = false }: { systemOnly?: booleanand Spotlight.</p><div className="grid grid-cols-1 gap-3 @md:grid-cols-2 @4xl:grid-cols-3 @7xl:grid-cols-4">+ {!systemList.length && <p role="status" className="py-6 text-sm text-muted-foreground">No {noun}s match your search.</p>}{systemList.map((e) => (<SystemCardkey={e.id}@@ -180,12 +183,14 @@ export default function AppStore({ systemOnly = false }: { systemOnly?: booleanopen={install.pendingApp !== null}title={install.pendingApp?.title ?? null}onCancel={install.cancelApp}+ error={install.error}onConfirm={install.confirmUninstallApp}/><UninstallConfirmopen={install.pendingSystem !== null}title={install.pendingSystem?.title ?? null}onCancel={install.cancelSystem}+ error={install.error}onConfirm={install.confirmUninstallSystem}/></div>diff --git a/frontend/slices/app-store/components/uninstall-confirm.tsx b/frontend/slices/app-store/components/uninstall-confirm.tsxindex 7b29c55f..0ba13b85 100644--- a/frontend/slices/app-store/components/uninstall-confirm.tsx+++ b/frontend/slices/app-store/components/uninstall-confirm.tsx@@ -14,11 +14,13 @@ export function UninstallConfirm({title,onCancel,onConfirm,+ error,}: {open: boolean;title: string | null;onCancel: () => void;onConfirm: () => void;+ error?: string;}) {return (<FormDrawer open={open} onOpenChange={(next) => !next && onCancel()} size="sm">@@ -28,6 +30,7 @@ export function UninstallConfirm({Your data stays on disk. You can reinstall any time.</FormDrawer.Description></FormDrawer.Header>+ {error && <p role="alert" className="px-4 text-sm text-destructive-text">{error}</p>}<FormDrawer.Footer><Button type="button" variant="ghost" onClick={onCancel}>Canceldiff --git a/frontend/slices/app-store/lib/apps-store.ts b/frontend/slices/app-store/lib/apps-store.tsindex 4cb204a0..90ca3f8c 100644--- a/frontend/slices/app-store/lib/apps-store.ts+++ b/frontend/slices/app-store/lib/apps-store.ts@@ -38,15 +38,12 @@ function snap(): AppRow[] {}function commit(next: AppRow[]) {- rows = next;if (typeof window !== "undefined") {- try {- localStorage.setItem(KEY, JSON.stringify(next));- } catch {- /* quota / private mode */- }+ try { localStorage.setItem(KEY, JSON.stringify(next)); }+ catch { throw new Error("Browser storage could not save this change. Free some space or allow site storage, then try again."); }}- subs.forEach((f) => f());+ rows = next;+ subs.forEach((notify) => notify());}function subscribe(cb: () => void) {diff --git a/frontend/slices/app-store/lib/enabled-store.ts b/frontend/slices/app-store/lib/enabled-store.tsindex c1636acd..4492c5e5 100644--- a/frontend/slices/app-store/lib/enabled-store.ts+++ b/frontend/slices/app-store/lib/enabled-store.ts@@ -32,15 +32,12 @@ function snap(): string[] {}function commit(next: string[]) {- ids = next;if (typeof window !== "undefined") {- try {- localStorage.setItem(KEY, JSON.stringify(next));- } catch {- /* quota / private mode */- }+ try { localStorage.setItem(KEY, JSON.stringify(next)); }+ catch { throw new Error("Browser storage could not save this change. Free some space or allow site storage, then try again."); }}- subs.forEach((f) => f());+ ids = next;+ subs.forEach((notify) => notify());}function subscribe(cb: () => void) {diff --git a/frontend/slices/app-store/lib/use-store-install.ts b/frontend/slices/app-store/lib/use-store-install.tsindex ddb2490c..05919702 100644--- a/frontend/slices/app-store/lib/use-store-install.ts+++ b/frontend/slices/app-store/lib/use-store-install.ts@@ -1,69 +1,41 @@"use client";-import { useCallback, useState } from "react";-import { setInstalled } from "./apps-store";import { setEnabled } from "./enabled-store";import type { CatalogApp } from "./store-catalog";import type { SystemEntry } from "./system-catalog";-// Install/uninstall state machine for the App Store. Touch users have no-// hover affordance, so tapping the "Installed" pill instantly fires uninstall —-// that's the destructive path we gate behind a confirm. Install is instant.-// Returns the toggles cards bind to, the busy id (per-card spinner), the-// pending entries (drive the dialogs), and the confirm callbacks.export function useStoreInstall(off: Set<string>) {const [pendingApp, setPendingApp] = useState<CatalogApp | null>(null);const [pendingSystem, setPendingSystem] = useState<SystemEntry | null>(null);-- const doInstall = useCallback((app: CatalogApp, nextInstalled: boolean) => {- setInstalled({- appId: app.appId,- installed: nextInstalled,- title: app.title,- glyph: app.glyph,- gradient: app.gradient,- runtime: app.runtime,- entry: app.entry,- });+ const [error, setError] = useState("");+ const persist = useCallback((change: () => void) => {+ setError("");+ try { change(); return true; }+ catch (cause) { setError(cause instanceof Error ? cause.message : "The change could not be saved."); return false; }}, []);-- const toggle = useCallback(- (app: CatalogApp) => {- if (app.installed) setPendingApp(app);- else doInstall(app, true);- },- [doInstall],- );-- const toggleSystem = useCallback(- (e: SystemEntry) => {- const currentlyInstalled = !off.has(e.id);- // Confirm before disabling, instant on re-enable (not destructive).- if (currentlyInstalled) setPendingSystem(e);- else setEnabled(e.id, true);- },- [off],- );-+ const doInstall = useCallback((app: CatalogApp, installed: boolean) => persist(() => setInstalled({+ appId: app.appId, installed, title: app.title, glyph: app.glyph,+ gradient: app.gradient, runtime: app.runtime, entry: app.entry,+ })), [persist]);+ const toggle = useCallback((app: CatalogApp) => {+ if (app.installed) setPendingApp(app);+ else doInstall(app, true);+ }, [doInstall]);+ const toggleSystem = useCallback((entry: SystemEntry) => {+ if (!off.has(entry.id)) setPendingSystem(entry);+ else persist(() => setEnabled(entry.id, true));+ }, [off, persist]);const confirmUninstallApp = useCallback(() => {- if (pendingApp) doInstall(pendingApp, false);- setPendingApp(null);+ if (pendingApp && doInstall(pendingApp, false)) setPendingApp(null);}, [doInstall, pendingApp]);-const confirmUninstallSystem = useCallback(() => {- if (pendingSystem) setEnabled(pendingSystem.id, false);- setPendingSystem(null);- }, [pendingSystem]);-+ if (pendingSystem && persist(() => setEnabled(pendingSystem.id, false))) setPendingSystem(null);+ }, [pendingSystem, persist]);return {- pendingApp,- pendingSystem,- toggle,- toggleSystem,- cancelApp: () => setPendingApp(null),- cancelSystem: () => setPendingSystem(null),- confirmUninstallApp,- confirmUninstallSystem,+ error, pendingApp, pendingSystem, toggle, toggleSystem,+ cancelApp: () => { setPendingApp(null); setError(""); },+ cancelSystem: () => { setPendingSystem(null); setError(""); },+ confirmUninstallApp, confirmUninstallSystem,};}diff --git a/frontend/slices/create-app/app.tsx b/frontend/slices/create-app/app.tsxindex 4b337d8d..832d0f1a 100644--- a/frontend/slices/create-app/app.tsx+++ b/frontend/slices/create-app/app.tsx@@ -1,6 +1,6 @@"use client";-import { useMemo, useState } from "react";+import { useEffect, useId, useMemo, useRef, useState } from "react";import { Check, Rocket } from "lucide-react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";@@ -9,7 +9,7 @@ import { Separator } from "@/components/ui/separator";import { Badge } from "@/components/ui/badge";import { ScrollArea } from "@/components/ui/scroll-area";import { GLYPH_KEYS, createApp } from "@/features/app-store";-import { AppFrame, usePublishInspector } from "@/features/appshell";+import { AppFrame, setCloseGuard, useFeatureState, usePublishInspector, type AppProps } from "@/features/appshell";import { cn } from "@/lib/utils";import { IconPreview } from "./components/icon-preview";import { GlyphPicker } from "./components/glyph-picker";@@ -44,17 +44,28 @@ const GRADIENTS = [const slugify = (s: string) =>s.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");-// Create App — author a new os-rr app and persist it via Convex. On create the-// app is installed; the shell's dynamic registry shows it in the dock instantly.-export default function CreateApp() {- const [name, setName] = useState("");- const [runtime, setRuntime] = useState<Runtime>("html");- const [entry, setEntry] = useState(ENTRY.html);- const [gradient, setGradient] = useState(GRADIENTS[0]);- const [glyph, setGlyph] = useState(GLYPH_KEYS[0]);+// Browser-local manifest registration does not install a server runtime.+export default function CreateApp({ winId }: AppProps = {}) {+ const prefix = useId();+ const resetTimer = useRef<ReturnType<typeof setTimeout> | null>(null);+ const [name, setName] = useFeatureState(winId, "create-app:name", "");+ const [runtime, setRuntime] = useFeatureState<Runtime>(winId, "create-app:runtime", "html");+ const [entry, setEntry] = useFeatureState(winId, "create-app:entry", ENTRY.html);+ const [gradient, setGradient] = useFeatureState(winId, "create-app:gradient", GRADIENTS[0]);+ const [glyph, setGlyph] = useFeatureState(winId, "create-app:glyph", GLYPH_KEYS[0]);const [created, setCreated] = useState(false);const [error, setError] = useState<string | null>(null);+ const dirty = !created && Boolean(name || runtime !== "html" || entry !== ENTRY.html || gradient !== GRADIENTS[0] || glyph !== GLYPH_KEYS[0]);+ useEffect(() => {+ const confirm = () => !dirty || window.confirm("Discard unsaved app details?");+ if (winId) setCloseGuard(winId, dirty ? confirm : null);+ const unload = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = ""; };+ if (dirty) window.addEventListener("beforeunload", unload);+ return () => { if (winId) setCloseGuard(winId, null); window.removeEventListener("beforeunload", unload); };+ }, [dirty, winId]);+ useEffect(() => () => { if (resetTimer.current) clearTimeout(resetTimer.current); }, []);+const slug = useMemo(() => slugify(name) || "untitled", [name]);const manifest = useMemo(() =>@@ -77,7 +88,7 @@ export default function CreateApp() {{subject: name.trim() || "New app",props: [- { label: "Name", value: name.trim() || "—" },+ { label: "Name", value: name.trim() || "Not named" },{ label: "Slug", value: slug },{ label: "Runtime", value: runtime },{ label: "Entry", value: entry },@@ -94,11 +105,8 @@ export default function CreateApp() {try {createApp({ appId: slug, title: name, glyph, gradient, runtime, entry });setCreated(true);- setTimeout(() => {- setName("");- pickRuntime("html");- setGradient(GRADIENTS[0]);- setGlyph(GLYPH_KEYS[0]);+ setName(""); pickRuntime("html"); setGradient(GRADIENTS[0]); setGlyph(GLYPH_KEYS[0]);+ resetTimer.current = setTimeout(() => {setCreated(false);}, 1800);} catch (e) {@@ -125,16 +133,16 @@ export default function CreateApp() {<div className="grid grid-cols-1 gap-5 @xl:grid-cols-2 @xl:gap-x-8"><div className="space-y-5">- <Field label="Name">- <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="My App" autoFocus />+ <Field label="Name" htmlFor={`${prefix}-name`}>+ <Input id={`${prefix}-name`} value={name} onChange={(e) => setName(e.target.value)} placeholder="My App" autoFocus /></Field><Field label="Runtime"><Segmented options={RUNTIMES} value={runtime} onChange={pickRuntime} className="w-full" /></Field>- <Field label="Entry point">- <Input value={entry} onChange={(e) => setEntry(e.target.value)} className="font-mono text-xs" />+ <Field label="Entry point" htmlFor={`${prefix}-entry`}>+ <Input id={`${prefix}-entry`} value={entry} onChange={(e) => setEntry(e.target.value)} className="font-mono text-xs" /></Field><Field label="Glyph">@@ -142,7 +150,7 @@ export default function CreateApp() {</Field><Field label="Accent">- <div className="flex gap-2">+ <div className="flex flex-wrap gap-[var(--feature-gap,.5rem)]">{GRADIENTS.map((g, i) => (<Buttonkey={g}@@ -150,6 +158,7 @@ export default function CreateApp() {variant="ghost"size="icon"aria-label={`Accent ${i + 1}`}+ aria-pressed={gradient === g}onClick={() => setGradient(g)}style={{ background: g }}className={cn(@@ -181,7 +190,7 @@ export default function CreateApp() {)}</Button>- {error && <p className="text-center text-xs text-destructive">{error}</p>}+ {error && <p role="alert" className="text-center text-xs text-destructive-text">{error}</p>}{created && (<div className="flex justify-center">diff --git a/frontend/slices/create-app/components/field.tsx b/frontend/slices/create-app/components/field.tsxindex 6c4935d9..a5ad2f8a 100644--- a/frontend/slices/create-app/components/field.tsx+++ b/frontend/slices/create-app/components/field.tsx@@ -1,17 +1,9 @@"use client";--// Labeled form row shared by the Create App form.-export function Field({- label,- children,-}: {- label: string;- children: React.ReactNode;-}) {- return (- <div className="space-y-1.5">- <label className="text-xs font-medium text-muted-foreground">{label}</label>- {children}- </div>- );+import { useId, type ReactNode } from "react";+export function Field({ label, htmlFor, children }: { label: string; htmlFor?: string; children: ReactNode }) {+ const labelId = useId();+ return <div className="space-y-1.5" role="group" aria-labelledby={labelId}>+ <label id={labelId} htmlFor={htmlFor} className="text-xs font-medium text-muted-foreground">{label}</label>+ {children}+ </div>;}diff --git a/frontend/slices/create-app/components/glyph-picker.tsx b/frontend/slices/create-app/components/glyph-picker.tsxindex 132d110c..22e256d2 100644--- a/frontend/slices/create-app/components/glyph-picker.tsx+++ b/frontend/slices/create-app/components/glyph-picker.tsx@@ -23,6 +23,7 @@ export function GlyphPicker({variant="ghost"size="icon"aria-label={`glyph ${key}`}+ aria-pressed={value === key}onClick={() => onChange(key)}className={cn("grid size-9 place-items-center rounded-md p-0 ring-offset-2 ring-offset-background transition",diff --git a/frontend/slices/extensions/skill-panel.tsx b/frontend/slices/extensions/skill-panel.tsxindex d4cee67c..212e2d2a 100644--- a/frontend/slices/extensions/skill-panel.tsx+++ b/frontend/slices/extensions/skill-panel.tsx@@ -1,5 +1,5 @@"use client";-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import type { SkillMarketSnapshot, SkillMarketRow } from "@/lib/contracts/skill-market";@@ -9,33 +9,47 @@ export function SkillStorePanel() { return <ExtensionAccess><OwnerSkillPanel /><function OwnerSkillPanel() {const [market, setMarket] = useState<SkillMarketSnapshot | null>(null);const [existing, setExisting] = useState<ExistingSkill[]>([]), [partial, setPartial] = useState(false);- const [query, setQuery] = useState(""), [busy, setBusy] = useState(false), [error, setError] = useState("");- const reload = useCallback(async (signal?: AbortSignal) => {- setBusy(true); setError("");+ const [query, setQuery] = useState(""), [loading, setLoading] = useState(false), [error, setError] = useState("");+ const [saving, setSaving] = useState(false);+ const busy = loading || saving;+ const controller = useRef<AbortController | null>(null), generation = useRef(0), writing = useRef(false);+ const source = useRef(Symbol("skill-market"));+ const reload = useCallback(async () => {+ controller.current?.abort();+ const request = new AbortController(); controller.current = request;+ const epoch = ++generation.current;+ const current = () => !request.signal.aborted && generation.current === epoch;+ setLoading(true); setError("");try {- const response = await fetch("/api/v1/skill-market", { cache: "no-store", signal });- const data = await response.json(); if (!response.ok) throw new Error(data.error || "Skill market failed");- setMarket(data);- const installed = await fetch("/api/skills", { cache: "no-store", signal });- const skills = await installed.json(); if (!installed.ok) throw new Error(skills.error || "Skill discovery failed");- setExisting(skills.skills ?? []); setPartial(Boolean(skills.scan?.truncated));- } catch (cause) { if (!signal?.aborted) setError(cause instanceof Error ? cause.message : "Skill catalog failed"); }- finally { if (!signal?.aborted) setBusy(false); }+ const [response, installed] = await Promise.all([+ fetch("/api/v1/skill-market", { cache: "no-store", signal: request.signal }),+ fetch("/api/skills", { cache: "no-store", signal: request.signal }),+ ]);+ const [data, skills] = await Promise.all([response.json(), installed.json()]);+ if (!response.ok || !installed.ok) throw new Error(!response.ok ? data.error || "Skill market failed" : skills.error || "Skill discovery failed");+ if (!current()) return;+ setMarket(data); setExisting(skills.skills ?? []); setPartial(Boolean(skills.scan?.truncated));+ } catch (cause) { if (current()) setError(cause instanceof Error ? cause.message : "Skill catalog failed"); }+ finally { if (current()) setLoading(false); }}, []);useEffect(() => {- const controller = new AbortController(); const timer = window.setTimeout(() => { void reload(controller.signal); }, 0);- const changed = () => { void reload(controller.signal); }; window.addEventListener("mso:extensions-changed", changed);- return () => { window.clearTimeout(timer); controller.abort(); window.removeEventListener("mso:extensions-changed", changed); };+ const timer = window.setTimeout(() => { void reload(); }, 0);+ const changed = (event: Event) => { if ((event as CustomEvent).detail?.source !== source.current) void reload(); };+ window.addEventListener("mso:extensions-changed", changed);+ return () => { clearTimeout(timer); controller.current?.abort(); window.removeEventListener("mso:extensions-changed", changed); };}, [reload]);async function change(action: "install" | "remove", row: SkillMarketRow) {+ if (writing.current || busy) return;if (!window.confirm(`${action === "remove" ? "Remove" : "Install"} ${row.title} ${action === "remove" ? "from" : "on"} this VPS? Only this managed skill directory will change.`)) return;- setBusy(true); setError("");+ writing.current = true; setSaving(true); setError("");+ controller.current?.abort(); generation.current++;try {const response = await fetch("/api/v1/skill-market", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action, id: row.id, revision: row.revision }) });const data = await response.json(); if (!response.ok) throw new Error(data.error || "Skill operation failed");- setMarket(data); window.dispatchEvent(new Event("mso:extensions-changed"));+ await reload();+ window.dispatchEvent(new CustomEvent("mso:extensions-changed", { detail: { source: source.current } }));} catch (cause) { setError(cause instanceof Error ? cause.message : "Skill operation failed"); }- finally { setBusy(false); }+ finally { writing.current = false; setSaving(false); }}const q = query.trim().toLowerCase();return <div className="min-w-0 space-y-4">diff --git a/frontend/slices/infrastructure/app.tsx b/frontend/slices/infrastructure/app.tsxindex fb09f16b..d1dbbe5e 100644--- a/frontend/slices/infrastructure/app.tsx+++ b/frontend/slices/infrastructure/app.tsx@@ -1,75 +1,13 @@"use client";-import { useCallback, useEffect, useMemo, useState } from "react";+import { useMemo } from "react";import { CheckCircle2, Cloud, Loader2, RefreshCw, Save, ServerCog, ShieldCheck, TriangleAlert } from "lucide-react";import { Button } from "@/components/ui/button";import type { InfrastructureFeatureId } from "./index";--type Field = { key: string; label: string; secret: boolean; required: boolean; placeholder?: string; description: string };-type Provider = { id: string; title: string; description: string; configured: boolean; missing: string[]; values: Record<string, string>; fields: Field[] };-type Doctor = { id: string; ok: boolean | null; detail: string };--type RemoteItem = { id: string; name: string };--async function json<T>(url: string, init?: RequestInit): Promise<T> {- const res = await fetch(url, { ...init, headers: { "content-type": "application/json", ...(init?.headers ?? {}) } });- const body = await res.json().catch(() => ({})) as T & { error?: string };- if (!res.ok) throw new Error(body.error ?? `HTTP ${res.status}`);- return body;-}+import { useProvider } from "./lib/use-provider";export function InfrastructureProviderApp({ provider }: { provider: InfrastructureFeatureId }) {- const [meta, setMeta] = useState<Provider | null>(null);- const [form, setForm] = useState<Record<string, string>>({});- const [doctor, setDoctor] = useState<Doctor | null>(null);- const [items, setItems] = useState<RemoteItem[]>([]);- const [busy, setBusy] = useState(false);- const [error, setError] = useState("");-- const refresh = useCallback(async () => {- try {- const data = await json<{ providers: Provider[] }>("/api/v1/infra/providers");- setError("");- const row = data.providers.find((entry) => entry.id === provider) ?? null;- setMeta(row);- if (row) setForm((current) => Object.fromEntries(row.fields.map((field) => [field.key, current[field.key] ?? (field.secret ? "" : row.values[field.key] ?? "")])))- if (row?.configured) {- const resource = provider === "dokploy"- ? await json<{ projects: Array<{ projectId: string; name: string }> }>("/api/v1/infra/dokploy/projects").then((r) => r.projects.map((p) => ({ id: p.projectId, name: p.name })))- : await json<{ zones: RemoteItem[] }>("/api/v1/infra/cloudflare/zones").then((r) => r.zones);- setItems(resource);- } else setItems([]);- } catch (e) { setError(e instanceof Error ? e.message : "Failed to read provider"); }- }, [provider]);-- useEffect(() => {- const timer = window.setTimeout(() => { void refresh(); }, 0);- return () => window.clearTimeout(timer);- }, [refresh]);-- const save = async () => {- if (!meta) return;- setBusy(true); setError("");- try {- const values = Object.fromEntries(Object.entries(form).filter(([, value]) => value.trim()));- await json("/api/v1/infra/providers", { method: "POST", body: JSON.stringify({ id: provider, values }) });- const checked = await json<{ results: Doctor[] }>("/api/v1/infra/providers/doctor", { method: "POST", body: JSON.stringify({ id: provider }) });- setDoctor(checked.results[0] ?? null);- setForm((current) => ({ ...current, ...(meta.fields.filter((field) => field.secret).reduce((acc, field) => ({ ...acc, [field.key]: "" }), {}) as Record<string, string>) }));- await refresh();- } catch (e) { setError(e instanceof Error ? e.message : "Failed to save provider"); }- finally { setBusy(false); }- };-- const verify = async () => {- setBusy(true); setError("");- try {- const checked = await json<{ results: Doctor[] }>("/api/v1/infra/providers/doctor", { method: "POST", body: JSON.stringify({ id: provider }) });- setDoctor(checked.results[0] ?? null);- await refresh();- } catch (e) { setError(e instanceof Error ? e.message : "Provider verification failed"); }- finally { setBusy(false); }- };+ const { meta, form, setForm, doctor, items, loading, loaded, busy, error, refresh, save, verify } = useProvider(provider);const Icon = provider === "dokploy" ? ServerCog : Cloud;const remoteLabel = provider === "dokploy" ? "Projects" : "Zones";@@ -82,7 +20,7 @@ export function InfrastructureProviderApp({ provider }: { provider: Infrastructu<div className="grid size-8 place-items-center rounded-lg bg-[color:var(--inset)]"><Icon className="size-4.5" /></div><div className="min-w-0"><h2 className="truncate text-sm font-semibold">{meta?.title ?? (provider === "dokploy" ? "Dokploy" : "Cloudflare")}</h2><p className="truncate text-[11px] text-[color:var(--text-dim)]">{summary}</p></div></div>- <div className="flex w-full items-center gap-2 @min-[480px]:w-auto"><Button size="sm" variant="outline" className="flex-1 @min-[480px]:flex-none" onClick={() => void verify()} disabled={busy || !meta?.configured}><ShieldCheck className="size-3.5" /> Verify</Button><Button size="sm" className="flex-1 @min-[480px]:flex-none" onClick={() => void save()} disabled={busy || !meta}>{busy ? <Loader2 className="size-3.5 animate-spin" /> : <Save className="size-3.5" />} Save</Button></div>+ <div className="flex w-full items-center gap-2 @min-[480px]:w-auto"><Button size="sm" variant="outline" className="flex-1 @min-[480px]:flex-none" onClick={() => void verify()} disabled={busy || loading || !meta?.configured}><ShieldCheck className="size-3.5" /> Verify</Button><Button size="sm" className="flex-1 @min-[480px]:flex-none" onClick={() => void save()} disabled={busy || loading || !meta}>{busy ? <Loader2 className="size-3.5 animate-spin" /> : <Save className="size-3.5" />} Save</Button></div></header><div className="min-h-0 flex-1 overflow-y-auto p-4">@@ -93,12 +31,14 @@ export function InfrastructureProviderApp({ provider }: { provider: Infrastructu{meta?.fields.map((field) => <label key={field.key} className="block"><span className="mb-1 flex items-center justify-between text-xs font-medium"><span>{field.label}{field.required ? " *" : ""}</span>{meta.values[field.key] && <span className="text-[10px] font-normal text-[color:var(--text-dim)]">current: {meta.values[field.key]}</span>}</span><input type={field.secret ? "password" : "text"} autoComplete="off" value={form[field.key] ?? ""} placeholder={field.secret && meta.values[field.key] ? "Leave blank to keep current secret" : field.placeholder ?? ""} onChange={(e) => setForm((current) => ({ ...current, [field.key]: e.target.value }))} className="h-9 w-full rounded-lg border border-[color:var(--separator)] bg-[color:var(--inset)] px-3 text-xs outline-none focus:border-[color:var(--accent)]" /><span className="mt-1 block text-[10px] leading-4 text-[color:var(--text-faint)]">{field.description}</span></label>)}</div>{doctor && <div className={`mt-4 flex items-start gap-2 rounded-lg border p-3 text-xs ${doctor.ok ? "border-emerald-500/30 bg-emerald-500/5" : "border-amber-500/30 bg-amber-500/5"}`}>{doctor.ok ? <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-emerald-500" /> : <TriangleAlert className="mt-0.5 size-4 shrink-0 text-amber-500" />}<span>{doctor.detail}</span></div>}- {error && <div className="mt-4 flex items-start gap-2 rounded-lg border border-red-500/30 bg-red-500/5 p-3 text-xs"><TriangleAlert className="mt-0.5 size-4 shrink-0 text-red-500" /><span>{error}</span></div>}+ {error && <div role="alert" className="mt-4 flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-xs text-destructive-text"><TriangleAlert className="mt-0.5 size-4 shrink-0 text-red-500" /><span>{error}</span></div>}</section><section className="rounded-xl border border-[color:var(--separator)] bg-[color:var(--surface)] p-4">- <div className="mb-3 flex items-center justify-between"><div><h3 className="text-xs font-semibold uppercase tracking-[0.12em] text-[color:var(--text-dim)]">{remoteLabel}</h3><p className="mt-1 text-[10px] text-[color:var(--text-faint)]">Live read from the configured provider.</p></div><Button size="sm" variant="ghost" onClick={() => void refresh()}><RefreshCw className="size-3.5" /></Button></div>- {!meta?.configured ? <p className="rounded-lg bg-[color:var(--inset)] p-3 text-xs text-[color:var(--text-dim)]">Configure the required fields first.</p> : items.length ? <div className="space-y-1.5">{items.map((item) => <div key={item.id} className="flex items-center justify-between gap-3 rounded-lg bg-[color:var(--inset)] px-3 py-2"><span className="truncate text-xs font-medium">{item.name}</span><code className="max-w-[45%] truncate text-[10px] text-[color:var(--text-faint)]">{item.id}</code></div>)}</div> : <p className="rounded-lg bg-[color:var(--inset)] p-3 text-xs text-[color:var(--text-dim)]">No {remoteLabel.toLowerCase()} returned.</p>}+ <div className="mb-3 flex items-center justify-between"><div><h3 className="text-xs font-semibold uppercase tracking-[0.12em] text-[color:var(--text-dim)]">{remoteLabel}</h3><p className="mt-1 text-[10px] text-[color:var(--text-faint)]">Live read from the configured provider.</p></div><Button size="sm" variant="ghost" aria-label="Refresh inventory" title="Refresh inventory" disabled={loading || busy} onClick={() => void refresh()}><RefreshCw className="size-3.5" /></Button></div>+ {loading && <p role="status" className="mb-3 text-xs text-muted-foreground">{loaded ? "Refreshing inventory…" : "Loading provider inventory…"}</p>}+ {error && loaded && <p role="status" className="mb-3 text-xs text-muted-foreground">Showing the last loaded inventory.</p>}+ {!meta ? <p className="text-xs text-muted-foreground">{error ? "Provider inventory is unavailable. Retry using Refresh inventory." : "Loading connection details…"}</p> : !meta.configured ? <p className="rounded-lg bg-[color:var(--inset)] p-3 text-xs text-[color:var(--text-dim)]">Configure the required fields first.</p> : items.length ? <div className="space-y-1.5">{items.map((item) => <div key={item.id} className="flex items-center justify-between gap-3 rounded-lg bg-[color:var(--inset)] px-3 py-2"><span className="truncate text-xs font-medium">{item.name}</span><code className="max-w-[45%] truncate text-[10px] text-[color:var(--text-faint)]">{item.id}</code></div>)}</div> : loading ? null : error && !loaded ? <p className="text-xs text-muted-foreground">Inventory could not be loaded. Use Refresh inventory to retry.</p> : <p className="rounded-lg bg-[color:var(--inset)] p-3 text-xs text-[color:var(--text-dim)]">No {remoteLabel.toLowerCase()} returned.</p>}<div className="mt-4 rounded-lg border border-[color:var(--separator)] p-3 text-[10px] leading-4 text-[color:var(--text-dim)]">MSO Agent uses the same provider state through bounded tools. Secrets stay server-side and are never included in model tool arguments.</div></section></div>diff --git a/frontend/slices/infrastructure/lib/use-provider.ts b/frontend/slices/infrastructure/lib/use-provider.tsnew file mode 100644index 00000000..0bcccc75--- /dev/null+++ b/frontend/slices/infrastructure/lib/use-provider.ts@@ -0,0 +1,67 @@+"use client";+import { useCallback, useEffect, useRef, useState } from "react";+import type { InfrastructureFeatureId } from "../index";+export type ProviderField = { key: string; label: string; secret: boolean; required: boolean; placeholder?: string; description: string };+export type Provider = { id: string; title: string; description: string; configured: boolean; missing: string[]; values: Record<string, string>; fields: ProviderField[] };+type Doctor = { id: string; ok: boolean | null; detail: string };+type Item = { id: string; name: string };+async function json<T>(url: string, signal: AbortSignal, init?: RequestInit): Promise<T> {+ const response = await fetch(url, { ...init, signal, headers: { "content-type": "application/json", ...init?.headers } });+ const body = await response.json().catch(() => ({})) as T & { error?: string };+ if (!response.ok) throw new Error(body.error ?? `HTTP ${response.status}`);+ return body;+}+export function useProvider(provider: InfrastructureFeatureId) {+ const [meta, setMeta] = useState<Provider | null>(null);+ const [form, setForm] = useState<Record<string, string>>({});+ const [doctor, setDoctor] = useState<Doctor | null>(null);+ const [items, setItems] = useState<Item[]>([]);+ const [loading, setLoading] = useState(true), [loaded, setLoaded] = useState(false);+ const [busy, setBusy] = useState(false), [error, setError] = useState("");+ const request = useRef<AbortController | null>(null), operation = useRef<AbortController | null>(null);+ const refresh = useCallback(async () => {+ request.current?.abort();+ const controller = new AbortController(); request.current = controller;+ setLoading(true); setError("");+ try {+ const data = await json<{ providers: Provider[] }>("/api/v1/infra/providers", controller.signal);+ if (controller.signal.aborted) return;+ const row = data.providers.find(entry => entry.id === provider) ?? null;+ if (!row) throw new Error("Provider configuration is unavailable.");+ setMeta(row);+ setForm(current => Object.fromEntries(row.fields.map(field => [field.key, current[field.key] ?? (field.secret ? "" : row.values[field.key] ?? "")])));+ const next = !row.configured ? [] : provider === "dokploy"+ ? (await json<{ projects: { projectId: string; name: string }[] }>("/api/v1/infra/dokploy/projects", controller.signal)).projects.map(item => ({ id: item.projectId, name: item.name }))+ : (await json<{ zones: Item[] }>("/api/v1/infra/cloudflare/zones", controller.signal)).zones;+ if (controller.signal.aborted) return;+ setItems(next); setLoaded(true);+ } catch (cause) {+ if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : "Provider refresh failed.");+ } finally { if (!controller.signal.aborted) setLoading(false); }+ }, [provider]);+ useEffect(() => {+ const timer = window.setTimeout(() => { setMeta(null); setForm({}); setDoctor(null); setItems([]); setLoaded(false); void refresh(); }, 0);+ return () => { clearTimeout(timer); request.current?.abort(); operation.current?.abort(); operation.current = null; };+ }, [refresh]);+ const mutate = async (saveValues: boolean) => {+ if (!meta || operation.current) return;+ const controller = new AbortController(); operation.current = controller;+ setBusy(true); setError("");+ try {+ if (saveValues) {+ const values = Object.fromEntries(Object.entries(form).filter(([, value]) => value.trim()));+ await json("/api/v1/infra/providers", controller.signal, { method: "POST", body: JSON.stringify({ id: provider, values }) });+ if (controller.signal.aborted) return;+ setForm(current => ({ ...current, ...Object.fromEntries(meta.fields.filter(field => field.secret).map(field => [field.key, ""])) }));+ }+ const result = await json<{ results: Doctor[] }>("/api/v1/infra/providers/doctor", controller.signal, { method: "POST", body: JSON.stringify({ id: provider }) });+ if (controller.signal.aborted) return;+ setDoctor(result.results[0] ?? null); await refresh();+ } catch (cause) {+ if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : "Provider action failed.");+ } finally {+ if (operation.current === controller) { operation.current = null; if (!controller.signal.aborted) setBusy(false); }+ }+ };+ return { meta, form, setForm, doctor, items, loading, loaded, busy, error, refresh, save: () => mutate(true), verify: () => mutate(false) };+}diff --git a/frontend/slices/integrations/composio-session-panel.tsx b/frontend/slices/integrations/composio-session-panel.tsxindex 94ffb0d1..e5f6ed2f 100644--- a/frontend/slices/integrations/composio-session-panel.tsx+++ b/frontend/slices/integrations/composio-session-panel.tsx@@ -86,7 +86,7 @@ export function ComposioSessionPanel() {if (kind === undefined) return null;if (kind === "connect") {return (- <details className="shrink-0 border-b p-3" aria-label="Composio Connect"><summary className="cursor-pointer text-sm">Composio Connect tools</summary>+ <details className="max-h-[40%] shrink-0 overflow-auto border-b p-[var(--feature-padding,.75rem)]" aria-label="Composio Connect"><summary className="cursor-pointer text-sm">Composio Connect tools</summary><div className="flex flex-wrap items-center gap-3"><p className="text-sm">Composio Connect</p><Button variant="secondary" disabled={busy} onClick={() => void loadTools()}>List tools</Button>@@ -95,7 +95,7 @@ export function ComposioSessionPanel() {Connect tools run under the Composio Connect account and cannot create a per-user agent session.</p>{tools && (- <ul className="mt-2 text-sm">{tools.map(tool => <li key={tool.name}>{tool.name}</li>)}</ul>+ tools.length ? <ul className="mt-2 break-words text-sm">{tools.map(tool => <li key={tool.name}>{tool.name}</li>)}</ul> : <p role="status" className="mt-2 text-sm text-muted-foreground">No tools returned.</p>)}{status && <p role="status" className="mt-2 text-sm text-muted-foreground">{status}</p>}</details>@@ -104,7 +104,7 @@ export function ComposioSessionPanel() {if (kind === null) return null;return (- <details className="shrink-0 border-b p-3" aria-label="Composio agent session"><summary className="cursor-pointer text-sm">Composio agent session</summary>+ <details className="max-h-[40%] shrink-0 overflow-auto border-b p-[var(--feature-padding,.75rem)]" aria-label="Composio agent session"><summary className="cursor-pointer text-sm">Composio agent session</summary><div className="flex flex-wrap items-center gap-3"><Button variant="secondary" disabled={busy} onClick={() => void create(false)}>Create agent session</Button>{mcpUrl && <Button variant="ghost" disabled={busy} onClick={() => void create(true)}>Refresh session</Button>}diff --git a/frontend/slices/n8n/app.tsx b/frontend/slices/n8n/app.tsxindex 8436e824..f0b2546e 100644--- a/frontend/slices/n8n/app.tsx+++ b/frontend/slices/n8n/app.tsx@@ -21,6 +21,7 @@ export default function N8nApp(_: AppProps) {request.current?.abort();const controller = new AbortController();request.current = controller;+ setLoading(true);try {const response = await fetch("/api/v1/workflow-embeds", { cache: "no-store", signal: controller.signal });if (controller.signal.aborted) return;@@ -67,7 +68,11 @@ export default function N8nApp(_: AppProps) {return <div data-slot="n8n-feature" className="@container h-full min-h-0 min-w-0"><AppFrame safeArea={false} className="h-full min-w-0" toolbar={toolbar}>- {loading && !n8n ? <div role="status" className="grid h-full place-items-center p-[var(--feature-padding,1.5rem)] text-sm text-muted-foreground">Loading n8n workspace…</div> : n8n ? <N8nEmbedPanel app={n8n}/> : <div className="grid h-full min-h-0 place-items-center overflow-y-auto p-6">+ {loading && !n8n ? <div role="status" className="grid h-full place-items-center p-[var(--feature-padding,1.5rem)] text-sm text-muted-foreground">Loading n8n workspace…</div> : n8n ? <div className="flex h-full min-h-0 flex-col">+ {message && <p role="alert" className="shrink-0 border-b p-3 text-sm text-destructive-text">Refresh failed. Showing the last loaded surface. {message}</p>}+ {loading && <p role="status" className="shrink-0 border-b px-3 py-2 text-xs text-muted-foreground">Refreshing n8n surface…</p>}+ <div className="min-h-0 flex-1"><N8nEmbedPanel app={n8n}/></div>+ </div> : <div className="grid h-full min-h-0 place-items-center overflow-y-auto p-6"><div className="w-full max-w-2xl rounded-2xl border bg-card p-5 shadow-sm"><div className="flex items-start gap-3"><div className="grid size-10 shrink-0 place-items-center rounded-xl border bg-muted/40"><Boxes className="size-5 text-muted-foreground"/></div>diff --git a/frontend/slices/system-monitor/app.tsx b/frontend/slices/system-monitor/app.tsxindex d287699a..0fd03376 100644--- a/frontend/slices/system-monitor/app.tsx+++ b/frontend/slices/system-monitor/app.tsx@@ -22,7 +22,7 @@ export default function SystemMonitor() {const api = useOsApi();const { isMobile } = useResponsive();const [tab, setTab] = useState<MonitorTab>("overview");- const { stats, procs, cpuSeries, netSeries, gpu, error, refresh } = useStatsHistory(tab === "overview");+ const { stats, procs, cpuSeries, netSeries, gpu, error, processError, lastUpdated, refresh } = useStatsHistory(tab === "overview");usePublishInspector("system-monitor", {subject: tab === "overview" ? "VPS host" : tab === "services" ? "systemd services" : "package updates",@@ -64,19 +64,21 @@ export default function SystemMonitor() {</div></header>}>- {tab === "overview" ? <Overview stats={stats} procs={procs} cpuSeries={cpuSeries} netSeries={netSeries} gpu={api.mode === "mock" ? gpu : undefined} error={error} refresh={refresh} /> : null}+ {tab === "overview" ? <Overview stats={stats} procs={procs} cpuSeries={cpuSeries} netSeries={netSeries} gpu={api.mode === "mock" ? gpu : undefined} error={error} processError={processError} lastUpdated={lastUpdated} refresh={refresh} /> : null}{tab === "services" ? <ServicesPanel /> : null}{tab === "updates" ? <PackageUpdatesPanel /> : null}</AppFrame>);}-function Overview({ stats, procs, cpuSeries, netSeries, gpu, error, refresh }: Omit<ReturnType<typeof useStatsHistory>, "gpu"> & { gpu?: number }) {+function Overview({ stats, procs, cpuSeries, netSeries, gpu, error, processError, lastUpdated, refresh }: Omit<ReturnType<typeof useStatsHistory>, "gpu"> & { gpu?: number }) {if (!stats && error) return <div className="flex h-full flex-col items-center justify-center gap-3 p-6 text-center"><AlertCircle className="size-6 text-destructive" /><p className="max-w-xs text-xs text-muted-foreground">{error}</p><Button variant="outline" size="sm" onClick={refresh}><RotateCw className="size-3.5" /> Retry</Button></div>;if (!stats) return <div className="flex h-full items-center justify-center gap-2 text-xs text-[color:var(--text-faint)]"><Loader2 className="size-4 animate-spin" /> Reading host telemetry…</div>;const lastNet = netSeries[netSeries.length - 1] ?? 0;return (<div className="space-y-3.5 p-4" style={MONITOR_VARS as React.CSSProperties}>+ {error && <div role="alert" className="flex flex-wrap items-center gap-2 rounded-lg border border-destructive/30 p-3 text-xs text-destructive-text"><span className="min-w-0 flex-1">Telemetry refresh failed. Showing the last sample{lastUpdated ? ` from ${new Date(lastUpdated).toLocaleTimeString()}` : ""}. {error}</span><Button size="sm" variant="outline" onClick={refresh}>Retry</Button></div>}+ {processError && <p role="status" className="text-xs text-destructive-text">Process list may be out of date. {processError}</p>}<GaugeGrid stats={stats} gpu={gpu} /><div className="grid grid-cols-2 gap-3 @max-[440px]:grid-cols-1"><GlassPanel title="CPU load" right={fmtPct(stats.cpu.pct)}><Sparkline data={cpuSeries} accent={"--mon-cpu" as MonitorVar} max={100} /></GlassPanel>diff --git a/frontend/slices/system-monitor/lib/use-stats-history.ts b/frontend/slices/system-monitor/lib/use-stats-history.tsindex afe2f324..8d666831 100644--- a/frontend/slices/system-monitor/lib/use-stats-history.ts+++ b/frontend/slices/system-monitor/lib/use-stats-history.ts@@ -16,6 +16,8 @@ export type StatsHistory = {/** Last poll error message — null while healthy. The UI surfaces this as a* retry tile instead of an eternal spinner. */error: string | null;+ processError: string | null;+ lastUpdated: number | null;refresh: () => void; // manual one-shot re-poll};@@ -30,6 +32,9 @@ export function useStatsHistory(enabled = true): StatsHistory {const [netSeries, setNet] = useState<number[]>(() => Array(SPAN).fill(0));const [gpu, setGpu] = useState(18);const [error, setError] = useState<string | null>(null);+ const [processError, setProcessError] = useState<string | null>(null);+ const [lastUpdated, setLastUpdated] = useState<number | null>(null);+ const generation = useRef(0);const gpuRef = useRef(18);const aliveRef = useRef(true);@@ -37,11 +42,13 @@ export function useStatsHistory(enabled = true): StatsHistory {// Failures land on `.catch` so an interval-driven failure doesn't pollute the// console with unhandled-rejection lines every POLL_MS ms.const pull = useCallback(() => {+ const epoch = ++generation.current;+ const current = () => aliveRef.current && generation.current === epoch;api.sys.stats().then((s) => {- if (!aliveRef.current) return;- setStats(s);+ if (!current()) return;+ setStats(s); setLastUpdated(Date.now());setError(null);setCpu((a) => [...a.slice(1), clampPct(s.cpu.pct)]);const net = s.net ? s.net.rx + s.net.tx : 0;@@ -50,11 +57,11 @@ export function useStatsHistory(enabled = true): StatsHistory {setGpu(gpuRef.current);api.sys.processes()- .then((p) => aliveRef.current && setProcs(p))- .catch(() => {});+ .then((p) => { if (current()) { setProcs(p); setProcessError(null); } })+ .catch((cause) => { if (current()) setProcessError(cause instanceof Error ? cause.message : "Process refresh failed"); });}).catch((e) => {- if (!aliveRef.current) return;+ if (!current()) return;setError(e instanceof Error ? e.message : String(e));});}, [api]);@@ -83,5 +90,5 @@ export function useStatsHistory(enabled = true): StatsHistory {};}, [pull, enabled]);- return { stats, procs, cpuSeries, netSeries, gpu, error, refresh: pull };+ return { stats, procs, cpuSeries, netSeries, gpu, error, processError, lastUpdated, refresh: pull };}