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: preserve window drafts and modal focus
Abdurrahman Fakhrulfe4d437b554f
diff --git a/docs/FRONTEND-CONTRACT.md b/docs/FRONTEND-CONTRACT.mdindex a7609842..93e2a278 100644--- a/docs/FRONTEND-CONTRACT.md+++ b/docs/FRONTEND-CONTRACT.md@@ -66,6 +66,10 @@ do not import React frontend components into server infrastructure.clears that state; browser reload does not imply unsaved drafts are durable.- Use the existing feature store/API for durable data. Never persist secrets in localStorage,duplicate a second store, or store sensitive data merely to preserve a visual state.+ Unsubmitted credential form drafts may use the existing exact-window memory store as+ operational input. Clear them on save, discard, confirmed navigation and window close,+ and clear sensitive drafts on sign-out or loss of Owner privilege. They must never+ enter saved layouts, inspector payloads, URLs, logs or preference synchronization.- Drafts need explicit save/discard behaviour and an unsaved-change guard at the relevantclose, route, record and reload boundaries. State from one window/owner cannot bleed into another.- Abort superseded requests and unmounted effects, or ignore results with a sequence/identitydiff --git a/docs/evidence/2026-11-04-final-shell.md b/docs/evidence/2026-11-04-final-shell.mdnew file mode 100644index 00000000..5eac463f--- /dev/null+++ b/docs/evidence/2026-11-04-final-shell.md@@ -0,0 +1,22 @@+# Final shared shell and Settings follow-up, 2026-11-04++Base a2268f2b includes PR #270. The earlier shell evidence remains a dated record of that candidate. This follow-up addresses its SH-07 gap and the mobile focus failure found while testing SH-08. No live service, credential, user file or production browser was changed.++| Finding | Implementation and evidence | Remaining limit |+|---|---|---|+| SH-01 / SH-02 / SH-13 | Actual image-picker components passed 30 synthetic keyboard/invalid-replacement cases across five shells, two themes and 320x844, 390x844, resized 844x390. ArrowRight focused Upload; Enter opened the chooser; invalid replacement disabled Upload. | External fixture used prior compiled CSS; real OS chooser, image decoding and assistive technology were not tested. |+| SH-03 / SH-09 | Existing awaited clipboard result retained manual copy after a rejected write in all ten shell/theme profiles. Keyboard focus stayed within the modal and returned on Escape. Search now has an explicit accessible name. | Real clipboard permissions and touch visibility need physical-device acceptance. |+| SH-04 | Existing image-link load/error/timeout and sequence guard inspected. | Link loading and timeout were not covered by this follow-up fixture. |+| SH-05 / SH-10 | Ten palette controls stayed inside their parent and viewport in 30 shell/theme/size cases. Dialog accessible name was observed at 320px. | Mobile landscape was reached by resizing portrait. Existing CSS foundation; 200% text and larger popover naming were not proven here. |+| SH-06 | Existing rail consumes inherited feature-sidebar width. | Token override and portaled override acceptance were not rerun. |+| SH-07 | Settings section, form visibility, draft fields and pending submission have exact-window ownership. Unsubmitted key/JSON use tagged entries in the existing memory store, never preferences or saved layout. Save/discard/confirmed navigation/close clear credentials. Pending submission prevents form/section/window close. Auth cleanup clears only sensitive entries and retains other drafts; ordered probes cannot restore an older role across logout. | Browser reload does not persist drafts. In-flight server mutation cannot be undone by browser teardown. Physical-device and full authentication journeys remain distinct from unit and fixture evidence. |+| SH-08 | Real overlays contained focus in ten shell/theme profiles. Mobile Shortcuts initially failed; enabling Vaul autofocus corrected immediate focus, Tab/Shift+Tab containment and opener return in both mobile shells/themes. The five-shell/two-theme journey is now wired into mandatory shell-status E2E. | The final exact-SHA mandatory browser result must be recorded by the integration owner. |+| SH-11 | Existing preset failure/retry and promise reset remain in place; earlier registry test passes. | Real failed chunk download/retry was not simulated here. |+| SH-12 | Existing shared Dialog coarse close size retained; explicit Shortcuts close also gets 44px coarse geometry. | Physical touch and title overlap under enlarged text need acceptance. |+| SH-14 | Existing keyboard desktop activation and focused Delete scope remain in place. | Pointer drag, editable/iframe focus and desktop deletion were not rerun here. |++The external actual-component fixture also confirmed Settings draft isolation between two windows, no synthetic credential in localStorage, cancelled old-protocol discovery not replacing newer Models, and one pending provider submission surviving a remount. Its source was changing and CSS came from a prior build, so those receipts are behavioral research, not final-SHA release proof. The external report is final-shell-regression.md with six JSON receipts in the audit work folder.++Portable focused regressions cover window-close cleanup, non-serialization, selective sensitive cleanup retaining Code buffers, original-revision behavior, protocol identity, latest auth probe ordering, logout invalidation and unavailable-probe preservation. The full Settings wrapper regression and mandatory focus journey are part of the integration candidate. TypeScript, targeted lint and the architecture ratchet passed during implementation. Contrast previously passed all 36 presets in both modes and globals. Full local/security/remote results belong to the final integration SHA and are not asserted by this handoff.++The frontend contract now documents operational credential input lifetime. There is no second store, no disk persistence for unsubmitted secrets, no inspector exposure and no per-shell data fork. Revert the incremental commits to roll back; do not weaken guards or scanners to make a gate green.diff --git a/frontend/slices/appshell/features/clipboard/components/clipboard-panel.tsx b/frontend/slices/appshell/features/clipboard/components/clipboard-panel.tsxindex 19fe4040..c3576989 100644--- a/frontend/slices/appshell/features/clipboard/components/clipboard-panel.tsx+++ b/frontend/slices/appshell/features/clipboard/components/clipboard-panel.tsx@@ -33,6 +33,7 @@ export function ClipboardPanel() {autoFocusvalue={q}onChange={(e) => setQ(e.target.value)}+ aria-label="Search clips"placeholder="Search clips…"className="w-full bg-transparent px-4 py-2.5 text-sm outline-none placeholder:text-muted-foreground"/>diff --git a/frontend/slices/appshell/features/shortcut-help/components/shortcut-help-overlay.tsx b/frontend/slices/appshell/features/shortcut-help/components/shortcut-help-overlay.tsxindex f7d81028..39ba46d5 100644--- a/frontend/slices/appshell/features/shortcut-help/components/shortcut-help-overlay.tsx+++ b/frontend/slices/appshell/features/shortcut-help/components/shortcut-help-overlay.tsx@@ -57,7 +57,7 @@ export function ShortcutHelpOverlay() {<Buttontype="button" variant="ghost" aria-label="Close"onClick={() => setShortcutHelpOpen(false)}- className="ml-auto h-auto rounded p-1 font-normal hover:bg-muted"+ className="ml-auto size-8 rounded p-1 font-normal hover:bg-muted [@media(pointer:coarse)]:size-11"><X className="size-3.5" /></Button>diff --git a/frontend/slices/appshell/hooks/use-feature-state.ts b/frontend/slices/appshell/hooks/use-feature-state.tsindex 1c6e5085..3304dd2b 100644--- a/frontend/slices/appshell/hooks/use-feature-state.ts+++ b/frontend/slices/appshell/hooks/use-feature-state.ts@@ -5,7 +5,7 @@ import { shellStore } from "../lib/store-state";import { featureStateKey, readFeatureState, subscribeFeatureState, writeFeatureState } from "../lib/feature-state";/** Per-window UI state shared by desktop, mobile and dashboard mounts. No disk storage. */-export function useFeatureState<T>(windowId: string | undefined, feature: string, initial: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {+export function useFeatureState<T>(windowId: string | undefined, feature: string, initial: T | (() => T), options?: { sensitive?: boolean }): [T, Dispatch<SetStateAction<T>>] {const [fallback, setFallback] = useState(initial);const key = featureStateKey(windowId ?? "", feature);const subscribe = useCallback((notify: () => void) => subscribeFeatureState(key, notify), [key]);@@ -17,7 +17,7 @@ export function useFeatureState<T>(windowId: string | undefined, feature: stringif (!shellStore.getWindow(windowId)) return;const previous = readFeatureState(key, fallback);const result = typeof next === "function" ? (next as (value: T) => T)(previous) : next;- writeFeatureState(key, windowId, result);- }, [key, windowId, fallback]);+ writeFeatureState(key, windowId, result, options?.sensitive === true);+ }, [key, windowId, fallback, options?.sensitive]);return [value, setValue];}diff --git a/frontend/slices/appshell/index.ts b/frontend/slices/appshell/index.tsindex 390fbaa2..07b08946 100644--- a/frontend/slices/appshell/index.ts+++ b/frontend/slices/appshell/index.ts@@ -203,5 +203,6 @@ export type {export { mdToHtml } from "./features/widgets/components/md";export * from "./defaults";+export { clearSensitiveFeatureState } from "./lib/feature-state";export { useFeatureState } from "./hooks/use-feature-state";export type { LayoutMetrics, LayoutConfig } from "./design";diff --git a/frontend/slices/appshell/lib/feature-state.test.ts b/frontend/slices/appshell/lib/feature-state.test.tsindex 501a0bbc..f1ac2e4d 100644--- a/frontend/slices/appshell/lib/feature-state.test.ts+++ b/frontend/slices/appshell/lib/feature-state.test.ts@@ -1,6 +1,6 @@import { afterEach, expect, it } from "vitest";-import { featureStateKey, readFeatureState, writeFeatureState, subscribeFeatureState, pruneFeatureState } from "./feature-state";-import { openWindow, closeWindow } from "./store";+import { featureStateKey, readFeatureState, writeFeatureState, subscribeFeatureState, pruneFeatureState, clearSensitiveFeatureState } from "./feature-state";+import { openWindow, closeWindow, serialize } from "./store";afterEach(() => pruneFeatureState(new Set()));it("preserves a draft across unmount/remount subscriptions and isolates each window", () => {@@ -22,3 +22,31 @@ it("releases state when the owning window closes without affecting another windoexpect(readFeatureState(key, null)).toBeNull();expect(readFeatureState(otherKey, null)).toBe("b"); closeWindow(other);});++it("keeps unsaved credentials in the owning window memory without serializing them", () => {+ const id = openWindow("os-settings", "Settings"), other = openWindow("other-settings", "Other Settings");+ const key = featureStateKey(id, "provider-key"), otherKey = featureStateKey(other, "provider-key");+ const secret = "synthetic-unsubmitted-credential";+ writeFeatureState(key, id, secret, true);+ const stop = subscribeFeatureState(key, () => {}); stop();+ expect(readFeatureState(key, "")).toBe(secret);+ expect(readFeatureState(otherKey, "")).toBe("");+ expect(JSON.stringify(serialize())).not.toContain(secret);+ closeWindow(id);+ expect(readFeatureState(key, "")).toBe("");+ closeWindow(other);+});++it("removes sensitive drafts at the auth boundary while retaining other drafts", () => {+ const id = openWindow("settings", "Settings"), key = featureStateKey(id, "provider-json");+ const other = featureStateKey(id, "code-buffers");+ writeFeatureState(other, id, "unsaved buffer");+ writeFeatureState(key, id, "synthetic private JSON", true);+ writeFeatureState(key, id, "changed private JSON");+ let calls = 0; const off = subscribeFeatureState(key, () => calls++);+ clearSensitiveFeatureState();+ expect(readFeatureState(key, "")).toBe("");+ expect(readFeatureState(other, "")).toBe("unsaved buffer");+ expect(calls).toBe(1);+ off(); closeWindow(id);+});diff --git a/frontend/slices/appshell/lib/feature-state.ts b/frontend/slices/appshell/lib/feature-state.tsindex 9935dff3..b031732e 100644--- a/frontend/slices/appshell/lib/feature-state.ts+++ b/frontend/slices/appshell/lib/feature-state.ts@@ -1,13 +1,15 @@-type Entry = { windowId: string; value: unknown };+type Entry = { windowId: string; value: unknown; sensitive: boolean };const entries = new Map<string, Entry>();const listeners = new Map<string, Set<() => void>>();export const featureStateKey = (windowId: string, feature: string) => JSON.stringify([windowId, feature]);export function readFeatureState<T>(key: string, initial: T): T {return entries.has(key) ? entries.get(key)!.value as T : initial;}-export function writeFeatureState<T>(key: string, windowId: string, value: T) {- if (entries.has(key) && Object.is(entries.get(key)!.value, value)) return;- entries.set(key, { windowId, value });+export function writeFeatureState<T>(key: string, windowId: string, value: T, sensitive = false) {+ const previous = entries.get(key);+ const isSensitive = sensitive || previous?.sensitive === true;+ if (previous && Object.is(previous.value, value) && previous.sensitive === isSensitive) return;+ entries.set(key, { windowId, value, sensitive: isSensitive });listeners.get(key)?.forEach((notify) => notify());}export function subscribeFeatureState(key: string, notify: () => void) {@@ -23,3 +25,12 @@ export function pruneFeatureState(activeWindows: ReadonlySet<string>) {listeners.get(key)?.forEach((notify) => notify());}}++/** Release only sensitive drafts when authentication or privilege is lost. */+export function clearSensitiveFeatureState() {+ for (const [key, entry] of entries) {+ if (!entry.sensitive) continue;+ entries.delete(key);+ listeners.get(key)?.forEach((notify) => notify());+ }+}diff --git a/frontend/slices/appshell/primitives/responsive-dialog-shell.tsx b/frontend/slices/appshell/primitives/responsive-dialog-shell.tsxindex c08abc7f..40b1fb78 100644--- a/frontend/slices/appshell/primitives/responsive-dialog-shell.tsx+++ b/frontend/slices/appshell/primitives/responsive-dialog-shell.tsx@@ -71,7 +71,7 @@ export function ResponsiveDialogShell({const mobileHeight = direction === "bottom" ? design.dialog.drawerHeightClass : "h-full";return (<ResponsiveDialogContext.Provider value={contextValue}>- <Drawer open={open} onOpenChange={onOpenChange} direction={direction} dismissible={dismissible}>+ <Drawer autoFocus open={open} onOpenChange={onOpenChange} direction={direction} dismissible={dismissible}><DrawerContentdata-slot="shell-dialog-surface"data-shell-id={design.id}diff --git a/frontend/slices/auth/lib/session-transition.test.ts b/frontend/slices/auth/lib/session-transition.test.tsnew file mode 100644index 00000000..dd8c39ec--- /dev/null+++ b/frontend/slices/auth/lib/session-transition.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it, vi } from "vitest";+import { createSessionTransition } from "./session-transition";+import type { SessionSnapshot } from "./session-probe";++const owner: SessionSnapshot = { status: "in", role: "owner" };+const viewer: SessionSnapshot = { status: "in", role: "viewer" };++describe("session transition ordering", () => {+ it("clears secrets before publishing a downgrade and ignores an older owner response", () => {+ const order: string[] = [];+ const transition = createSessionTransition(next => order.push(String(next.role)), () => order.push("clear"));+ const oldProbe = transition.beginProbe();+ const newProbe = transition.beginProbe();+ expect(transition.acceptProbe(newProbe, viewer)).toBe(true);+ expect(transition.acceptProbe(oldProbe, owner)).toBe(false);+ expect(order).toEqual(["clear", "viewer"]);+ });++ it("invalidates probes before and during logout, including late replies", () => {+ const publish = vi.fn(), clear = vi.fn();+ const transition = createSessionTransition(publish, clear);+ const before = transition.beginProbe();+ const logout = transition.beginSignOut();+ const during = transition.beginProbe();+ expect(transition.acceptProbe(before, owner)).toBe(false);+ expect(transition.acceptProbe(during, owner)).toBe(false);+ transition.finishSignOut(logout);+ expect(transition.acceptProbe(during, owner)).toBe(false);+ expect(clear).toHaveBeenCalled();+ expect(publish).toHaveBeenCalledExactlyOnceWith({ status: "out", role: null });+ const after = transition.beginProbe();+ expect(transition.acceptProbe(after, owner)).toBe(true);+ });++ it("keeps logout pending until the latest logout finishes", () => {+ const publish = vi.fn();+ const transition = createSessionTransition(publish, () => {});+ const first = transition.beginSignOut(), second = transition.beginSignOut();+ transition.finishSignOut(first);+ expect(transition.acceptProbe(transition.beginProbe(), owner)).toBe(false);+ transition.finishSignOut(second);+ expect(publish).toHaveBeenCalledExactlyOnceWith({ status: "out", role: null });+ });++ it("keeps current state when a probe is unavailable and accepts a later fresh probe", () => {+ const publish = vi.fn(), clear = vi.fn();+ const transition = createSessionTransition(publish, clear);+ expect(transition.acceptProbe(transition.beginProbe(), null)).toBe(false);+ expect(transition.acceptProbe(transition.beginProbe(), owner)).toBe(true);+ expect(publish).toHaveBeenCalledExactlyOnceWith(owner);+ expect(clear).not.toHaveBeenCalled();+ });+});diff --git a/frontend/slices/auth/lib/session-transition.ts b/frontend/slices/auth/lib/session-transition.tsnew file mode 100644index 00000000..4274f790--- /dev/null+++ b/frontend/slices/auth/lib/session-transition.ts@@ -0,0 +1,21 @@+import type { SessionSnapshot } from "./session-probe";++/** Accept only the latest probe and invalidate in-flight probes across logout. */+export function createSessionTransition(publish: (snapshot: SessionSnapshot) => void, clearSensitive: () => void) {+ let generation = 0;+ let signingOut = false;+ const commit = (next: SessionSnapshot) => {+ if (next.status === "out" || (next.status === "in" && next.role !== "owner")) clearSensitive();+ publish(next);+ };+ return {+ beginProbe: () => signingOut ? -1 : ++generation,+ acceptProbe: (id: number, next: SessionSnapshot | null) => {+ if (id !== generation || signingOut || !next) return false;+ commit(next);+ return true;+ },+ beginSignOut: () => { signingOut = true; const id = ++generation; clearSensitive(); return id; },+ finishSignOut: (id: number) => { if (id !== generation || !signingOut) return; ++generation; commit({ status: "out", role: null }); signingOut = false; },+ };+}diff --git a/frontend/slices/auth/lib/use-session.tsx b/frontend/slices/auth/lib/use-session.tsxindex d5fd9b7e..6015e273 100644--- a/frontend/slices/auth/lib/use-session.tsx+++ b/frontend/slices/auth/lib/use-session.tsx@@ -1,10 +1,12 @@"use client";import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from "react";+import { clearSensitiveFeatureState } from "@/features/appshell";import { AUTHED_EVENT } from "@/lib/prefs/use-prefs-sync";import { IS_DEMO } from "@/lib/demo";import type { DeviceRole } from "@/lib/auth/roles";import { probeSession, type SessionSnapshot, type SessionStatus } from "./session-probe";+import { createSessionTransition } from "./session-transition";export type { SessionStatus } from "./session-probe";@@ -34,47 +36,54 @@ export function SessionProvider({role: IS_DEMO || initialStatus !== "in" ? null : (initialRole ?? "viewer"),}));+ const [transition] = useState(() => createSessionTransition(setSnapshot, clearSensitiveFeatureState));+ useEffect(() => {+ if (snapshot.status === "out" || (snapshot.status === "in" && snapshot.role !== "owner")) clearSensitiveFeatureState();+ }, [snapshot.status, snapshot.role]);+const probe = useCallback(() => probeSession(), []);const refresh = useCallback(async () => {+ const id = transition.beginProbe();const next = await probe();// `null` is deliberately NOT signed-out. A deploy/restart can race this// request; preserving the last authoritative snapshot keeps a valid cookie// from being presented as a logout while the service recovers.- if (!next) return;- setSnapshot(next);- if (next.status === "in") window.dispatchEvent(new Event(AUTHED_EVENT));- }, [probe]);+ if (transition.acceptProbe(id, next) && next?.status === "in") window.dispatchEvent(new Event(AUTHED_EVENT));+ }, [probe, transition]);const signOut = useCallback(async () => {+ const id = transition.beginSignOut();try {await fetch("/api/auth/logout", { method: "POST", credentials: "same-origin" });} catch {/* best-effort — clear locally regardless */}- setSnapshot({ status: "out", role: null });- }, []);+ transition.finishSignOut(id);+ }, [transition]);// SSR gives the fast first paint, then the browser immediately reconciles it.// This closes stale HTML/CDN/BFCache windows without reintroducing a loading wall.useEffect(() => {if (IS_DEMO) return;let alive = true;+ const id = transition.beginProbe();void probe().then((next) => {- if (alive && next) setSnapshot(next);+ if (alive) transition.acceptProbe(id, next);});return () => {alive = false;};- }, [probe]);+ }, [probe, transition]);useEffect(() => {if (IS_DEMO) return;let alive = true;const sync = () => {if (document.visibilityState !== "visible") return;+ const id = transition.beginProbe();void probe().then((next) => {- if (alive && next) setSnapshot(next);+ if (alive) transition.acceptProbe(id, next);});};const timer = window.setInterval(sync, 60_000);@@ -90,7 +99,7 @@ export function SessionProvider({window.removeEventListener("online", sync);document.removeEventListener("visibilitychange", sync);};- }, [probe]);+ }, [probe, transition]);const value = useMemo(() => ({ ...snapshot, refresh, signOut }),diff --git a/frontend/slices/os-settings/app.tsx b/frontend/slices/os-settings/app.tsxindex a439668c..0bb295cc 100644--- a/frontend/slices/os-settings/app.tsx+++ b/frontend/slices/os-settings/app.tsx@@ -39,17 +39,21 @@ export default function OsSettings({ winId }: { winId?: string }) {const [draftName] = useFeatureState(winId, "provider-name", "");const [draftUrl] = useFeatureState(winId, "provider-url", "");const [draftModels] = useFeatureState(winId, "provider-models", "");- const draftDirty = Boolean(draftName || draftUrl || draftModels || sensitiveDirty);+ const [draftKey, setDraftKey] = useFeatureState(winId, "provider-key", "", { sensitive: true });+ const [draftJson, setDraftJson] = useFeatureState(winId, "provider-json", "", { sensitive: true });+ const [submitting] = useFeatureState(winId, "provider-submitting", false);+ const hasSensitiveDraft = Boolean(sensitiveDirty || draftKey || draftJson);+ const draftDirty = Boolean(draftName || draftUrl || draftModels || hasSensitiveDraft || submitting);useEffect(() => {if (!draftDirty) return;- if (winId) setCloseGuard(winId, () => window.confirm("Discard the unsaved provider draft?"));+ if (winId) setCloseGuard(winId, () => { if (submitting) { toast("Wait for the provider request to finish before closing Settings."); return false; } return window.confirm("Discard the unsaved provider draft?"); });const beforeUnload = (event: BeforeUnloadEvent) => { event.preventDefault(); };window.addEventListener("beforeunload", beforeUnload);return () => {if (winId) setCloseGuard(winId, null);window.removeEventListener("beforeunload", beforeUnload);};- }, [draftDirty, winId]);+ }, [draftDirty, submitting, winId]);const serverTarget = effectiveServerTarget(tweaks.server);useEffect(() => {@@ -87,10 +91,11 @@ export default function OsSettings({ winId }: { winId?: string }) {);const selectSection = useCallback((next: SectionId | null) => {- if (next !== active && sensitiveDirty && !window.confirm("Discard the unsaved API key or JSON?")) return;- if (next !== active) setSensitiveDirty(false);+ if (next !== active && submitting) return void toast("Wait for the provider request to finish before leaving this section.");+ if (next !== active && hasSensitiveDraft && !window.confirm("Discard the unsaved API key or JSON?")) return;+ if (next !== active) { setDraftKey(""); setDraftJson(""); setSensitiveDirty(false); }setActive(next);- }, [active, sensitiveDirty, setActive]);+ }, [active, hasSensitiveDraft, submitting, setActive, setDraftKey, setDraftJson]);return (<SettingsWindowContext.Provider value={{ winId, setSensitiveDirty }}>diff --git a/frontend/slices/os-settings/components/custom-provider-form.test.tsx b/frontend/slices/os-settings/components/custom-provider-form.test.tsxindex 1b591cd2..0eb3c195 100644--- a/frontend/slices/os-settings/components/custom-provider-form.test.tsx+++ b/frontend/slices/os-settings/components/custom-provider-form.test.tsx@@ -52,6 +52,10 @@ describe("auto-discovery guard", () => {expect(discoveryPairKey("https://host/v1", "sk-1")).not.toBe(discoveryPairKey("https://host/v1", "sk-2"));});+ it("separates protocol discovery for the same URL and key", () => {+ expect(discoveryPairKey("https://host/v1", "sk-1", "openai")).not.toBe(discoveryPairKey("https://host/v1", "sk-1", "anthropic"));+ });+it("claims each pair at most once, so a debounce can never fire twice", () => {const fired = new Set<string>();const pair = discoveryPairKey("https://host/v1", "sk-1");diff --git a/frontend/slices/os-settings/components/custom-provider-form.tsx b/frontend/slices/os-settings/components/custom-provider-form.tsxindex 04557cc1..2c878142 100644--- a/frontend/slices/os-settings/components/custom-provider-form.tsx+++ b/frontend/slices/os-settings/components/custom-provider-form.tsx@@ -13,9 +13,6 @@ export type DiscoveredModel = { id: string; name: string };export type DiscoveryFailure = "invalid-url" | "auth" | "empty";type Reply = { ok?: boolean; models?: DiscoveredModel[]; error?: string };-// Three actionable failures, never one generic "discovery failed": a malformed-// base URL, a rejected key, and a reachable endpoint with no models need-// different fixes. Exported so the messages are testable and stay distinct.export const DISCOVERY_MESSAGES: Record<DiscoveryFailure, string> = {"invalid-url": "That endpoint URL isn’t usable. Use a full https:// base URL (e.g. https://host/v1) that the server can reach.",auth: "That endpoint rejected the API key (401/403). Check the key, then retry Discover.",@@ -44,8 +41,8 @@ export function classifyDiscovery(status: number, body: Reply): DiscoveryFailure/** The baseURL+key pair a discovery run is keyed by, or null until it is usable.* Keyed by the pair so a re-render cannot re-fire it. */-export function discoveryPairKey(baseURL: string, apiKey: string): string | null {- return baseUrlLooksValid(baseURL) && apiKey.trim() ? `${baseURL.trim()}\n${apiKey.trim()}` : null;+export function discoveryPairKey(baseURL: string, apiKey: string, protocol = "openai"): string | null {+ return baseUrlLooksValid(baseURL) && apiKey.trim() ? JSON.stringify([baseURL.trim(), apiKey.trim(), protocol]) : null;}/** Claim the pair BEFORE fetching; false means "this pair already ran". */@@ -61,23 +58,21 @@ export function modelFieldFromDiscovered(list: DiscoveredModel[]): string {return list.map((model) => model.id).join(", ");}-// Add a custom OpenAI-compatible / Anthropic-Messages provider: fields or pasted-// JSON. "Discover models" asks the endpoint's own list API (POST /api/models/discover,-// SSRF-pinned, key only in the body) and PRE-SELECTS every returned id. It also runs-// itself once per baseURL+key pair — debounced, cancellable; the button re-runs it.export function CustomProviderForm({ onAdded }: { onAdded: () => void }) {const { winId, setSensitiveDirty } = useSettingsWindow(), [mode, setMode] = useFeatureState<"fields" | "json">(winId, "provider-mode", "fields");const [name, setName] = useFeatureState(winId, "provider-name", "");const [baseURL, setBaseURL] = useFeatureState(winId, "provider-url", "");- const [key, setKey] = useState("");+ const [key, setKey] = useFeatureState(winId, "provider-key", "", { sensitive: true });const [protocol, setProtocol] = useFeatureState(winId, "provider-protocol", "openai");const [models, setModels] = useFeatureState(winId, "provider-models", "");- const [json, setJson] = useState("");- const [busy, setBusy] = useState(false), [found, setFound] = useState<DiscoveredModel[]>([]);+ const [json, setJson] = useFeatureState(winId, "provider-json", "", { sensitive: true });+ const [busy, setBusy] = useFeatureState(winId, "provider-submitting", false), [found, setFound] = useState<DiscoveredModel[]>([]);const [scanning, setScanning] = useState(false);const [failure, setFailure] = useState<DiscoveryFailure | null>(null);const autoFired = useRef<Set<string>>(new Set()); // pairs already auto-runconst abortRef = useRef<AbortController | null>(null);+ useEffect(() => setSensitiveDirty(Boolean(key || json)), [key, json, setSensitiveDirty]);+ const cancelDiscovery = () => { autoFired.current.clear(); abortRef.current?.abort(); setScanning(false); setFound([]); setFailure(null); };const run = useCallback(async (signal: AbortSignal, target: string, apiKey: string, proto: string) => {if (!baseUrlLooksValid(target) || !apiKey.trim()) {setFailure("invalid-url");@@ -93,6 +88,7 @@ export function CustomProviderForm({ onAdded }: { onAdded: () => void }) {signal,});const body = (await response.json().catch(() => ({}))) as Reply;+ if (signal.aborted) return;const kind = classifyDiscovery(response.status, body);if (kind) {setFound([]);@@ -120,18 +116,21 @@ export function CustomProviderForm({ onAdded }: { onAdded: () => void }) {// Auto-discovery: 700 ms debounce, pair claimed before the fetch, aborted when// the pair changes or the form unmounts. Never on every keystroke, never twice.useEffect(() => {+ abortRef.current?.abort();if (mode !== "fields") return;- const pair = discoveryPairKey(baseURL, key);+ const pair = discoveryPairKey(baseURL, key, protocol);if (!pair || autoFired.current.has(pair)) return;const timer = setTimeout(() => {if (claimDiscovery(autoFired.current, pair)) start(baseURL.trim(), key.trim(), protocol);}, 700);- return () => window.clearTimeout(timer);+ return () => { window.clearTimeout(timer); abortRef.current?.abort(); };}, [baseURL, key, mode, protocol, start]);useEffect(() => () => abortRef.current?.abort(), []);// The route re-validates everything (SSRF, slug, key); this only reports it.async function submit() {+ if (busy) return;+ abortRef.current?.abort(); setScanning(false);setBusy(true);try {const payload = mode === "json"@@ -160,16 +159,16 @@ export function CustomProviderForm({ onAdded }: { onAdded: () => void }) {<div className="space-y-2 rounded-lg border border-border p-3"><div className="flex items-center justify-between text-xs text-muted-foreground"><span>Custom endpoint: OpenAI-compatible or Anthropic Messages</span>- <Button type="button" variant="ghost" className={`${ghost} text-primary`} onClick={() => setMode(mode === "fields" ? "json" : "fields")}>+ <Button type="button" variant="ghost" disabled={busy} className={`${ghost} text-primary`} onClick={() => { cancelDiscovery(); setMode(mode === "fields" ? "json" : "fields"); }}>{mode === "fields" ? "paste JSON" : "use fields"}</Button></div>- <p className="text-xs text-muted-foreground">Unsaved API keys and JSON are cleared when changing shells.</p>+ <p className="text-xs text-muted-foreground">Unsaved credentials stay in this window until you save, discard or close it. Reloading clears them.</p>{mode === "fields" ? (<div className="space-y-2"><div className="flex flex-wrap gap-2"><Input disabled={busy} aria-label="Provider name" placeholder="name (e.g. my-llm)" value={name} onChange={(e) => setName(e.target.value)} className="w-40" />- <Select value={protocol} onValueChange={setProtocol}>+ <Select disabled={busy} value={protocol} onValueChange={(value) => { cancelDiscovery(); setProtocol(value); }}><SelectTrigger aria-label="Endpoint protocol" className="w-52"><SelectValue /></SelectTrigger><SelectContent><SelectItem value="openai">OpenAI /chat/completions</SelectItem>@@ -177,8 +176,8 @@ export function CustomProviderForm({ onAdded }: { onAdded: () => void }) {</SelectContent></Select></div>- <Input disabled={busy} aria-label="Base URL" placeholder="https://host/v1" value={baseURL} onChange={(e) => setBaseURL(e.target.value)} />- <Input disabled={busy} aria-label="API key" type="password" placeholder="API key" value={key} onChange={(e) => { setKey(e.target.value); setSensitiveDirty(Boolean(e.target.value || json)); }} />+ <Input disabled={busy} aria-label="Base URL" placeholder="https://host/v1" value={baseURL} onChange={(e) => { cancelDiscovery(); setBaseURL(e.target.value); }} />+ <Input disabled={busy} aria-label="API key" type="password" placeholder="API key" value={key} onChange={(e) => { cancelDiscovery(); setKey(e.target.value); setSensitiveDirty(Boolean(e.target.value || json)); }} /><div className="flex items-center gap-2"><Input disabled={busy} aria-label="Models" placeholder="models: comma/newline, e.g. minimax-m3, gpt-4o" value={models} onChange={(e) => setModels(e.target.value)} className="flex-1" /><Button type="button" variant="outline" size="sm" className="[@media(pointer:coarse)]:min-h-[44px]" disabled={busy || scanning || !baseURL || !key} onClick={() => start(baseURL, key, protocol)}>@@ -190,12 +189,12 @@ export function CustomProviderForm({ onAdded }: { onAdded: () => void }) {<div className="space-y-1.5"><div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground"><span>{found.length} found · {selectedIds.length} selected</span>- <Button type="button" variant="ghost" size="sm" className={`${ghost} text-primary`} onClick={() => setModels(modelFieldFromDiscovered(found))}>Select all</Button>- <Button type="button" variant="ghost" size="sm" className={ghost} onClick={() => setModels("")}>Clear</Button>+ <Button type="button" variant="ghost" size="sm" disabled={busy} className={`${ghost} text-primary`} onClick={() => setModels(modelFieldFromDiscovered(found))}>Select all</Button>+ <Button type="button" variant="ghost" size="sm" disabled={busy} className={ghost} onClick={() => setModels("")}>Clear</Button></div><div className="flex flex-wrap gap-1.5">{found.map((model) => (- <button key={model.id} type="button" title={model.name} aria-pressed={selectedIds.includes(model.id)}+ <button key={model.id} type="button" disabled={busy} title={model.name} aria-pressed={selectedIds.includes(model.id)}onClick={() => setModels((prev) => toggleModelInList(prev, model.id))}className={`rounded-md border px-2 py-1 font-mono text-xs [@media(pointer:coarse)]:min-h-[44px] ${selectedIds.includes(model.id) ? "border-primary bg-primary/10 text-primary" : "border-border text-muted-foreground"}`}>{model.id}@@ -211,7 +210,7 @@ export function CustomProviderForm({ onAdded }: { onAdded: () => void }) {placeholder={'{\n "name": "ai-hub",\n "baseURL": "https://host/v1",\n "apiKey": "sk-…",\n "protocol": "openai",\n "models": ["minimax-m3", "gpt-4o"]\n}'} />)}<div className="flex justify-end">- <Button type="button" variant="ghost" size="sm" disabled={busy} onClick={() => { setName(""); setBaseURL(""); setKey(""); setModels(""); setJson(""); setFound([]); setFailure(null); setSensitiveDirty(false); }}>Discard</Button>+ <Button type="button" variant="ghost" size="sm" disabled={busy} onClick={() => { abortRef.current?.abort(); setScanning(false); autoFired.current.clear(); setName(""); setBaseURL(""); setKey(""); setModels(""); setJson(""); setFound([]); setFailure(null); setSensitiveDirty(false); }}>Discard</Button><Button size="sm" className="[@media(pointer:coarse)]:min-h-[44px]" disabled={!canSubmit} onClick={submit}>{busy ? "Adding…" : "Add provider"}</Button></div></div>diff --git a/frontend/slices/os-settings/components/provider-manage.tsx b/frontend/slices/os-settings/components/provider-manage.tsxindex 132a0676..7db7fa2e 100644--- a/frontend/slices/os-settings/components/provider-manage.tsx+++ b/frontend/slices/os-settings/components/provider-manage.tsx@@ -1,6 +1,7 @@"use client";-import { useState } from "react";+import { toast, useFeatureState } from "@/features/appshell";+import { useSettingsWindow } from "../lib/window-context";import { Plus } from "lucide-react";import { Button } from "@/components/ui/button";import { SettingsBlock } from "@/features/shell-settings";@@ -20,7 +21,17 @@ export function ProviderManage({selected: string;reload: () => void;}) {- const [showAdd, setShowAdd] = useState(false);+ const { winId, setSensitiveDirty } = useSettingsWindow();+ const [showAdd, setShowAdd] = useFeatureState(winId, "provider-form-open", false);+ const [key, setKey] = useFeatureState(winId, "provider-key", "", { sensitive: true });+ const [json, setJson] = useFeatureState(winId, "provider-json", "", { sensitive: true });+ const [submitting] = useFeatureState(winId, "provider-submitting", false);+ const toggleForm = () => {+ if (showAdd && submitting) return void toast("Wait for the provider request to finish before closing the form.");+ if (showAdd && (key || json) && !window.confirm("Discard the unsaved API key or JSON?")) return;+ if (showAdd) { setKey(""); setJson(""); setSensitiveDirty(false); }+ setShowAdd(!showAdd);+ };return (<><SettingsBlock>@@ -34,7 +45,7 @@ export function ProviderManage({aria-expanded={showAdd}aria-controls="custom-provider-form"className="text-muted-foreground [@media(pointer:coarse)]:min-h-[44px]"- onClick={() => setShowAdd((s) => !s)}+ onClick={toggleForm}><Plus className={`size-3.5 transition-transform ${showAdd ? "rotate-45" : ""}`} />{showAdd ? "Close custom provider form" : "Add custom provider"}diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjsindex ba95fdb8..ed346034 100644--- a/scripts/e2e/release.mjs+++ b/scripts/e2e/release.mjs@@ -14,6 +14,7 @@ import { camoufoxConnectionJourney } from "./camoufox-connection.mjs";import { memoryBackupHistoryJourney } from "./memory-backup-history.mjs";import { aiProviderSwitchJourney } from "./ai-provider-switch.mjs";import { shellNoticesJourney } from "./shell-notices.mjs";+import { settingsDraftJourney } from "./settings-draft.mjs";execFileSync(process.execPath, ["scripts/e2e/socket-authority.mjs"], { stdio: "inherit", timeout: 30000 });execFileSync(process.execPath, ["scripts/e2e/request-bodies.mjs"], { stdio: "inherit", timeout: 60000 });@@ -99,6 +100,7 @@ try {await page.locator('input[type="password"]').fill(fixture.password);await page.getByRole("button", { name: "Unlock", exact: true }).click();await expect(page).toHaveURL(fixture.base + "/integrations");+ await settingsDraftJourney(page, fixture);await agentVaultJourney(page, fixture);await page.goto(fixture.base + "/integrations");await shellNoticesJourney(page, fixture);diff --git a/scripts/e2e/settings-draft.mjs b/scripts/e2e/settings-draft.mjsnew file mode 100644index 00000000..96c6b1e3--- /dev/null+++ b/scripts/e2e/settings-draft.mjs@@ -0,0 +1,100 @@+import { expect } from "@playwright/test";++// Owner Settings journey. All provider mutations and discovery are intercepted:+// the values below are synthetic and never reach a host or external provider.+export async function settingsDraftJourney(page, fixture) {+ const desktop = { width: 1280, height: 900 };+ const phone = { width: 390, height: 844 };+ let releaseSave;+ const saveGate = new Promise(resolve => { releaseSave = resolve; });+ let saveRequests = 0;+ const configRoute = async route => {+ if (route.request().method() !== "POST") return route.continue();+ saveRequests++;+ await saveGate;+ await route.fulfill({ status: 200, json: { slug: "fixture-provider" } }).catch(() => {});+ };+ const discoveryRoute = route => route.fulfill({ status: 200, json: { ok: true, models: [] } });+ await page.route("**/api/config", configRoute);+ await page.route("**/api/models/discover", discoveryRoute);+ try {+ await page.setViewportSize(desktop);+ await page.goto(fixture.base + "/settings?section=ai");+ const open = page.getByRole("button", { name: "Add custom provider", exact: true });+ await expect(open).toBeVisible();+ await open.click();+ const form = page.locator("#custom-provider-form");+ const name = form.getByLabel("Provider name", { exact: true });+ const key = form.getByLabel("API key", { exact: true });+ const url = form.getByLabel("Base URL", { exact: true });+ await name.fill("Fixture provider");+ await key.fill("fixture-only-key");++ // Verify a real surface transition, not merely a resize of the same DOM.+ const oldForm = await form.elementHandle();+ await page.setViewportSize(phone);+ await expect(page.locator('[data-shell="ios"], [data-shell="android"]')).toBeVisible();+ await expect.poll(() => oldForm.evaluate(node => node.isConnected)).toBe(false);+ await expect(name).toHaveValue("Fixture provider");+ await expect(key).toHaveValue("fixture-only-key");+ const mobileForm = await form.elementHandle();+ await page.setViewportSize(desktop);+ await expect(page.locator('[data-window][data-app="os-settings"]')).toBeVisible();+ await expect.poll(() => mobileForm.evaluate(node => node.isConnected)).toBe(false);+ await expect(name).toHaveValue("Fixture provider");+ await expect(key).toHaveValue("fixture-only-key");++ const closeForm = page.getByRole("button", { name: "Close custom provider form", exact: true });+ let choice = "dismiss";+ const dialogHandler = async dialog => {+ expect(dialog.type()).toBe("confirm");+ expect(dialog.message()).toContain("unsaved API key or JSON");+ if (choice === "dismiss") await dialog.dismiss(); else await dialog.accept();+ };+ page.on("dialog", dialogHandler);+ try {+ await closeForm.click();+ await expect(key).toHaveValue("fixture-only-key");+ choice = "accept";+ await closeForm.click();+ await expect(form).toHaveCount(0);+ await open.click();+ await expect(key).toHaveValue("");+ } finally { page.off("dialog", dialogHandler); }++ await url.fill("https://fixture.invalid/v1");+ await key.fill("fixture-only-key");+ await form.getByRole("button", { name: "Add provider", exact: true }).click();+ await expect.poll(() => saveRequests).toBe(1);+ await expect(form.getByRole("button", { name: "Adding…", exact: true })).toBeDisabled();+ const pendingForm = await form.elementHandle();+ await page.setViewportSize(phone);+ await expect(page.locator('[data-shell="ios"], [data-shell="android"]')).toBeVisible();+ await expect.poll(() => pendingForm.evaluate(node => node.isConnected)).toBe(false);+ await expect(form.getByRole("button", { name: "Adding…", exact: true })).toBeDisabled();+ await expect(key).toHaveValue("fixture-only-key");+ const pendingMobile = await form.elementHandle();+ await page.setViewportSize(desktop);+ await expect(page.locator('[data-window][data-app="os-settings"]')).toBeVisible();+ await expect.poll(() => pendingMobile.evaluate(node => node.isConnected)).toBe(false);+ await expect(form.getByRole("button", { name: "Adding…", exact: true })).toBeDisabled();+ await closeForm.click();+ await expect(key).toHaveValue("fixture-only-key");+ await page.getByRole("navigation", { name: "Settings sections" }).getByRole("button", { name: "Appearance", exact: true }).click();+ await expect(form).toBeVisible();+ await page.locator('[data-window][data-app="os-settings"]').getByRole("button", { name: "Close window", exact: true }).click();+ await expect(form).toBeVisible();+ expect(saveRequests).toBe(1);+ releaseSave();+ await expect(open).toBeVisible();+ await open.click();+ await expect(name).toHaveValue("");+ await expect(key).toHaveValue("");+ console.log("PASS Settings draft across responsive remount, discard and pending provider save");+ } finally {+ releaseSave();+ await page.unroute("**/api/config", configRoute);+ await page.unroute("**/api/models/discover", discoveryRoute);+ await page.setViewportSize(desktop);+ }+}diff --git a/scripts/e2e/shell-status.mjs b/scripts/e2e/shell-status.mjsindex db1e7ad7..5e8d4efa 100755--- a/scripts/e2e/shell-status.mjs+++ b/scripts/e2e/shell-status.mjs@@ -34,6 +34,24 @@ try {await expect(host).toBeVisible();await expect(status).toHaveAttribute("data-connection-mode", "mock");assert.equal(await status.evaluate((node) => getComputedStyle(node).position), "static");+ for (const theme of ["light", "dark"]) {+ await page.evaluate(value => { document.documentElement.dataset.theme = value; }, theme);+ const trigger = page.locator("button:visible:not([disabled]), a[href]:visible").first();+ await trigger.focus();+ const opener = await trigger.elementHandle();+ await page.keyboard.press("Control+/");+ const dialog = page.getByRole("dialog", { name: "Keyboard shortcuts", exact: true });+ await expect(dialog).toBeVisible();+ await expect.poll(() => dialog.evaluate(node => node.contains(document.activeElement))).toBe(true);+ for (const key of ["Shift+Tab", "Tab", "Tab", "Shift+Tab"]) {+ await page.keyboard.press(key);+ expect(await dialog.evaluate(node => node.contains(document.activeElement))).toBe(true);+ }+ await page.keyboard.press("Escape");+ await expect(dialog).not.toBeVisible();+ await expect.poll(() => opener.evaluate(node => node === document.activeElement)).toBe(true);+ await opener.dispose();+ }assert.deepEqual(errors, [], `${test.id} browser errors`);await context.close();console.log(`PASS ${test.id}: server status in ${test.placement}`);