Skip to content

armgit / mso

Public Imported from GitHub
0

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

fix(ui): harden shell controls and picker interactions

Abdurrahman Fakhrul38d7492259ab
diff --git a/components/ui/dialog.tsx b/components/ui/dialog.tsx
index 34dabb9d..49818484 100644
--- a/components/ui/dialog.tsx
+++ b/components/ui/dialog.tsx
@@ -70,7 +70,7 @@ function DialogContent({
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
- className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
+ className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [@media(pointer:coarse)]:top-0 [@media(pointer:coarse)]:right-0 [@media(pointer:coarse)]:grid [@media(pointer:coarse)]:size-11 [@media(pointer:coarse)]:place-items-center [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
@@ -125,7 +125,7 @@ function DialogTitle({
return (
<DialogPrimitive.Title
data-slot="dialog-title"
- className={cn("text-lg leading-none font-semibold", className)}
+ className={cn("text-lg leading-none font-semibold [@media(pointer:coarse)]:pr-8", className)}
{...props}
/>
)
diff --git a/docs/evidence/2026-11-04-frontend-shell.md b/docs/evidence/2026-11-04-frontend-shell.md
new file mode 100644
index 00000000..7b92a41c
--- /dev/null
+++ b/docs/evidence/2026-11-04-frontend-shell.md
@@ -0,0 +1,37 @@
+# Shell and picker audit implementation, 2026-11-04
+
+Source: shell audit SH01–SH14, base 266c24cb. Development worktree only;
+no deployed runtime or authenticated data was changed. Shell, feature and UI-kit
+ownership follows the frontend contract. Browser and device acceptance remains open.
+
+| ID | Before → change | Owner / source | Evidence and remaining limits |
+|---|---|---|---|
+| SH01 | Inactive tabs unreachable → roving arrows and Home/End, unique IDs | Image picker, image-picker-dialog.tsx | Source change; modal/drawer keyboard test needed |
+| SH02 | Hidden chooser inaccessible → native button invokes file input | Image picker, upload-tab.tsx | Source change; keyboard chooser test needed |
+| SH03 | Clipboard reported success on rejection → await result, retain panel and manual copy | AppShell clipboard | Unit test covers reject, missing API and success; browser permission test needed |
+| SH04 | Broken links accepted → error, timeout, request identity and label | Image picker, link-tab.tsx | Source change; browser load, timeout and close test needed |
+| SH05 | Coarse palette clipped → wrap colors and let pills grow | Icon picker, ColorRow.tsx and Toolbar.tsx | Geometry on 320/390/768, 200% zoom and both themes unverified |
+| SH06 | Sidebar fixed width → inherited feature token | AppShell app-chrome.tsx and Settings settings-shell.tsx | Token adoption implemented; five-shell override/portal proof needed |
+| SH07 | Mount-local Settings state → window-scoped section and nonsecret provider fields, discard and close/reload guard | Settings app.tsx, window-context.ts, custom-provider-form.tsx | Partial: API key/JSON remain local and are guarded on section navigation, but a shell remount can discard them without warning; deep-link, isolation and remount journeys unverified |
+| SH08 | Overlays had no modal boundary → existing ResponsiveDialog for Clipboard, Shortcuts and Spotlight | AppShell feature components | Focus containment, opener restoration, stacking and native drawer behavior need browser proof |
+| SH09 | Clipboard actions hover-only → focus-within and coarse visibility | Clipboard panel | Keyboard and touch proof needed |
+| SH10 | Picker dialog unnamed → accessible title | IconPicker.tsx | Drawer and dialog accessible-name proof needed |
+| SH11 | Preset failure blank and rejected promise cached → error, Retry and reset pending on rejection | Settings theme-section.tsx and appearance registry.ts | Registry failure then retry unit test passes; chunk retry in browser unverified |
+| SH12 | Dialog close too small on coarse input → 44px target and title clearance | UI kit dialog.tsx | Measured target, title overlap and both themes unverified |
+| SH13 | Invalid replacement retained old upload → clear selection and preview before validation | Image picker upload-tab.tsx | Type and size replacement browser test needed |
+| SH14 | Native button keyboard click did not open → keyboard click activates; deletion scoped to focused desktop icon | AppShell desktop-icons.tsx | Pointer drag, app/file/link and editable focus behavior need browser proof |
+
+State lifetime: Settings nonsecret fields and section use the exact-window in-memory
+feature store and are cleared with the window. API key and pasted JSON never enter
+that store. A browser reload is not draft persistence. Secrets are component-local.
+
+Verification on this worktree: targeted clipboard, settings section and registry
+tests: 9 passed; changed-file ESLint and typecheck passed. Architecture initially
+failed the file length ratchet, then passed without raising the limit. Contrast:
+36 presets in both modes and globals, zero failures. No full build, preflight,
+security scan, CI, real-device, screen-reader or rendered five-shell checks.
+
+Next integration agent: rerun `umask 077; VITEST_MAX_WORKERS=2 bun run test`
+with targeted picker/overlay tests, `bun run typecheck`, `node scripts/check-architecture.mjs`,
+`node scripts/check-contrast.mjs`, and mandated local/security/remote gates.
+Exercise SH01–14 in the actual five shells and both themes before marking ready.
diff --git a/frontend/slices/appshell/components/layout/app-chrome.tsx b/frontend/slices/appshell/components/layout/app-chrome.tsx
index 72c9905a..2dfec435 100644
--- a/frontend/slices/appshell/components/layout/app-chrome.tsx
+++ b/frontend/slices/appshell/components/layout/app-chrome.tsx
@@ -112,7 +112,7 @@ export function AppSidebar({
compact={pane === "xs" || pane === "sm"}
title={title}
description={description}
- railBase="flex w-56 shrink-0 flex-col border-r border-border bg-sidebar"
+ railBase="flex w-[var(--feature-sidebar-width,14rem)] shrink-0 flex-col border-r border-border bg-sidebar"
railClassName={railClassName}
sheetWidth="w-72 sm:max-w-xs"
sheetClassName={sheetClassName}
diff --git a/frontend/slices/appshell/features/clipboard/components/clipboard-panel.tsx b/frontend/slices/appshell/features/clipboard/components/clipboard-panel.tsx
index 609271c2..19fe4040 100644
--- a/frontend/slices/appshell/features/clipboard/components/clipboard-panel.tsx
+++ b/frontend/slices/appshell/features/clipboard/components/clipboard-panel.tsx
@@ -1,20 +1,28 @@
"use client";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { Pin, Trash2, X } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
+import { ResponsiveDialog } from "../../../primitives/responsive-dialog";
import { clearClips, copyClip, removeClip, setClipboardOpen, togglePinClip, useClips } from "../../../lib/clipboard";
export function ClipboardPanel() {
const clips = useClips();
const [q, setQ] = useState("");
+ const [failedText, setFailedText] = useState<string | null>(null);
+ useEffect(() => {
+ const previous = document.activeElement as HTMLElement | null;
+ return () => { previous?.focus(); };
+ }, []);
const list = clips.filter((c) => c.text.toLowerCase().includes(q.toLowerCase()));
return (
- <div className="absolute inset-0 z-[var(--z-clipboard)] flex items-start justify-center bg-black/20 pt-[16vh]" onClick={() => setClipboardOpen(false)}>
- <div className="glass flex max-h-[60vh] w-full max-w-lg flex-col overflow-hidden rounded-2xl border border-border shadow-2xl" onClick={(e) => e.stopPropagation()}>
+ <ResponsiveDialog open onOpenChange={setClipboardOpen} showCloseButton={false}>
+ <ResponsiveDialog.Header>
+ <ResponsiveDialog.Title>Clipboard history</ResponsiveDialog.Title>
+ </ResponsiveDialog.Header>
+ <ResponsiveDialog.Body className="flex min-h-0 flex-col p-0">
<header className="flex items-center gap-2 border-b border-border px-4 py-2.5">
- <span className="text-xs font-semibold text-muted-foreground">Clipboard history</span>
{clips.length > 0 && (
<Button type="button" variant="ghost" onClick={clearClips} className="ml-auto h-auto p-0 text-xs font-normal text-muted-foreground hover:bg-transparent hover:underline">
Clear unpinned
@@ -29,6 +37,7 @@ export function ClipboardPanel() {
className="w-full bg-transparent px-4 py-2.5 text-sm outline-none placeholder:text-muted-foreground"
/>
<ul className="min-h-0 flex-1 overflow-y-auto border-t border-border p-2">
+ {failedText !== null && <li className="p-2"><p role="alert" className="text-sm text-destructive">Could not copy. Select the text and copy it manually.</p><textarea aria-label="Text to copy manually" readOnly value={failedText} onFocus={(e) => e.currentTarget.select()} className="w-full rounded border border-border bg-background p-2 text-sm text-foreground" /></li>}
{list.length === 0 && (
<li className="px-3 py-4 text-sm text-muted-foreground">
{clips.length === 0 ? "Nothing copied yet. ⌘C anywhere in the OS lands here." : "No matches."}
@@ -39,9 +48,9 @@ export function ClipboardPanel() {
<Button
type="button"
variant="ghost"
- onClick={() => {
- copyClip(c.text);
- setClipboardOpen(false);
+ onClick={async () => {
+ if (await copyClip(c.text)) setClipboardOpen(false);
+ else setFailedText(c.text);
}}
className="h-auto min-w-0 flex-1 justify-start truncate p-2 text-left text-sm font-normal hover:bg-transparent"
>
@@ -50,14 +59,14 @@ export function ClipboardPanel() {
<Button
type="button" variant="ghost" aria-label={c.pinned ? "Unpin" : "Pin"}
onClick={() => togglePinClip(c.id)}
- className={cn("h-auto shrink-0 p-1 font-normal hover:bg-muted", c.pinned ? "text-primary" : "text-muted-foreground opacity-0 group-hover:opacity-100")}
+ className={cn("h-auto shrink-0 p-1 font-normal hover:bg-muted", c.pinned ? "text-primary" : "text-muted-foreground opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 [@media(pointer:coarse)]:opacity-100")}
>
<Pin className="size-3.5" />
</Button>
<Button
type="button" variant="ghost" aria-label="Remove"
onClick={() => removeClip(c.id)}
- className="h-auto shrink-0 p-1 font-normal text-muted-foreground opacity-0 hover:bg-muted group-hover:opacity-100"
+ className="h-auto shrink-0 p-1 font-normal text-muted-foreground opacity-0 hover:bg-muted group-hover:opacity-100 group-focus-within:opacity-100 [@media(pointer:coarse)]:opacity-100"
>
<Trash2 className="size-3.5" />
</Button>
@@ -70,7 +79,7 @@ export function ClipboardPanel() {
<X className="size-3" />
</Button>
</footer>
- </div>
- </div>
+ </ResponsiveDialog.Body>
+ </ResponsiveDialog>
);
}
diff --git a/frontend/slices/appshell/features/desktop-icons/desktop-icons.tsx b/frontend/slices/appshell/features/desktop-icons/desktop-icons.tsx
index 39cd4726..45da32bb 100644
--- a/frontend/slices/appshell/features/desktop-icons/desktop-icons.tsx
+++ b/frontend/slices/appshell/features/desktop-icons/desktop-icons.tsx
@@ -37,7 +37,7 @@ export function DesktopIcons() {
const onKey = (e: KeyboardEvent) => {
if ((e.key === "Delete" || e.key === "Backspace") && getSelected().size) {
const t = e.target as HTMLElement | null;
- if (t && /^(INPUT|TEXTAREA)$/.test(t.tagName)) return;
+ if (!t?.closest("[data-desktop-icon]")) return;
e.preventDefault();
removeIcons([...getSelected()]);
setSelected([]);
@@ -99,6 +99,7 @@ function IconButton({ icon, selected }: { icon: DesktopIcon; selected: boolean }
<>
<button
type="button"
+ data-desktop-icon
style={{ left: icon.x, top: icon.y, width: ICON_W }}
className={cn(
"pointer-events-auto absolute flex touch-none flex-col items-center gap-1 rounded-lg p-1.5 text-center",
@@ -107,6 +108,7 @@ function IconButton({ icon, selected }: { icon: DesktopIcon; selected: boolean }
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
+ onClick={(e) => { if (e.detail === 0) open(); }}
onDoubleClick={open}
onContextMenu={(e) => {
e.stopPropagation();
diff --git a/frontend/slices/appshell/features/search/components/spotlight.tsx b/frontend/slices/appshell/features/search/components/spotlight.tsx
index 2cfb6c7c..2d300d89 100644
--- a/frontend/slices/appshell/features/search/components/spotlight.tsx
+++ b/frontend/slices/appshell/features/search/components/spotlight.tsx
@@ -13,6 +13,7 @@ import { useShellAppearance, useShellSearch, type SearchHit } from "../../../reg
import { matches, type Command } from "../lib";
import { loadRecents, pushRecent } from "../history";
import { ResultList } from "./spotlight-results";
+import { ResponsiveDialog } from "../../../primitives/responsive-dialog";
export function Spotlight() {
const open = useSpotlightOpen();
@@ -128,10 +129,6 @@ function SpotlightPanel() {
const selIdx = Math.min(sel, Math.max(0, results.length - 1));
const close = () => setSpotlightOpen(false);
- const onBackdrop = () => {
- if (!dismissReady.current) return;
- close();
- };
const runAt = (i: number) => {
const cmd = results[i];
if (!cmd) return;
@@ -162,13 +159,9 @@ function SpotlightPanel() {
: `No matches for “${q}”.`;
return (
- <div
- className={cn(
- "absolute inset-0 z-[var(--z-spotlight)] flex items-start justify-center bg-black/20",
- ios ? "pt-[calc(var(--sai-top)_+_0.5rem)]" : "pt-[18vh]",
- )}
- onClick={onBackdrop}
- >
+ <ResponsiveDialog open onOpenChange={(next) => { if (!next && dismissReady.current) close(); }} showCloseButton={false}>
+ <ResponsiveDialog.Header className="sr-only"><ResponsiveDialog.Title>Spotlight search</ResponsiveDialog.Title></ResponsiveDialog.Header>
+ <ResponsiveDialog.Body className="p-0">
<div
className={cn(
"glass w-full overflow-hidden rounded-2xl border border-border text-foreground shadow-2xl",
@@ -182,6 +175,7 @@ function SpotlightPanel() {
{ios && <Search className="size-[15px] shrink-0 text-muted-foreground" />}
<input
ref={inputRef}
+ autoFocus
role="combobox"
aria-label="Spotlight search"
aria-expanded={results.length > 0}
@@ -214,6 +208,7 @@ function SpotlightPanel() {
</p>
)}
</div>
- </div>
+ </ResponsiveDialog.Body>
+ </ResponsiveDialog>
);
}
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.tsx
index 95dd2b8b..f7d81028 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
@@ -3,6 +3,7 @@
import { useEffect, useMemo } from "react";
import { Keyboard, X } from "lucide-react";
import { Button } from "@/components/ui/button";
+import { ResponsiveDialog } from "../../../primitives/responsive-dialog";
import {
setShortcutHelpOpen,
useShortcutHelpOpen,
@@ -15,6 +16,12 @@ export function ShortcutHelpOverlay() {
const open = useShortcutHelpOpen();
const hints = useShortcuts();
+ useEffect(() => {
+ if (!open) return;
+ const previous = document.activeElement as HTMLElement | null;
+ return () => { previous?.focus(); };
+ }, [open]);
+
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === "/") {
@@ -40,11 +47,13 @@ export function ShortcutHelpOverlay() {
if (!open) return null;
return (
- <div className="absolute inset-0 z-[var(--z-shortcut-help)] flex items-center justify-center bg-black/25" onClick={() => setShortcutHelpOpen(false)}>
- <div className="glass max-h-[75vh] w-full max-w-xl overflow-y-auto rounded-2xl border border-border p-5 shadow-2xl" onClick={(e) => e.stopPropagation()}>
+ <ResponsiveDialog open onOpenChange={setShortcutHelpOpen} showCloseButton={false}>
+ <ResponsiveDialog.Header>
+ <ResponsiveDialog.Title>Keyboard shortcuts</ResponsiveDialog.Title>
+ </ResponsiveDialog.Header>
+ <ResponsiveDialog.Body className="overflow-y-auto p-5">
<header className="mb-4 flex items-center gap-2">
<Keyboard className="size-4 text-muted-foreground" />
- <h2 className="text-sm font-semibold">Keyboard shortcuts</h2>
<Button
type="button" variant="ghost" aria-label="Close"
onClick={() => setShortcutHelpOpen(false)}
@@ -68,7 +77,7 @@ export function ShortcutHelpOverlay() {
</section>
))}
</div>
- </div>
- </div>
+ </ResponsiveDialog.Body>
+ </ResponsiveDialog>
);
}
diff --git a/frontend/slices/appshell/lib/clipboard.test.ts b/frontend/slices/appshell/lib/clipboard.test.ts
index 0b2d821b..35d65d6d 100644
--- a/frontend/slices/appshell/lib/clipboard.test.ts
+++ b/frontend/slices/appshell/lib/clipboard.test.ts
@@ -1,5 +1,5 @@
-import { beforeEach, describe, expect, it } from "vitest";
-import { clearClips, listClips, recordClip, removeClip, togglePinClip } from "./clipboard";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { clearClips, copyClip, listClips, recordClip, removeClip, togglePinClip } from "./clipboard";
import { getCommands } from "./commands";
function reset() {
@@ -8,6 +8,18 @@ function reset() {
describe("clipboard history", () => {
beforeEach(reset);
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("records only successful clipboard writes", async () => {
+ const writeText = vi.fn().mockRejectedValueOnce(new Error("denied")).mockResolvedValueOnce(undefined);
+ vi.stubGlobal("navigator", { clipboard: { writeText } });
+ expect(await copyClip("hello")).toBe(false);
+ expect(listClips()).toEqual([]);
+ expect(await copyClip("hello")).toBe(true);
+ expect(listClips().map((c) => c.text)).toEqual(["hello"]);
+ vi.stubGlobal("navigator", {});
+ expect(await copyClip("other")).toBe(false);
+ });
it("records newest-first, dedupes the top, ignores empties", () => {
recordClip("one");
diff --git a/frontend/slices/appshell/lib/clipboard.ts b/frontend/slices/appshell/lib/clipboard.ts
index 5d220f73..f20b0b17 100644
--- a/frontend/slices/appshell/lib/clipboard.ts
+++ b/frontend/slices/appshell/lib/clipboard.ts
@@ -58,14 +58,16 @@ export function recordClip(text: string): void {
}
/** Write an entry back to the system clipboard (and bump its recency). */
-export function copyClip(text: string): void {
+export async function copyClip(text: string): Promise<boolean> {
try {
- void navigator.clipboard?.writeText(text);
+ if (!navigator.clipboard?.writeText) return false;
+ await navigator.clipboard.writeText(text);
} catch {
- /* clipboard API unavailable — history still works */
+ return false;
}
recordClip(text);
toast("Copied to clipboard");
+ return true;
}
export function togglePinClip(id: number): void {
diff --git a/frontend/slices/icon-picker/components/IconPicker.tsx b/frontend/slices/icon-picker/components/IconPicker.tsx
index 414d4d52..fe4158fd 100644
--- a/frontend/slices/icon-picker/components/IconPicker.tsx
+++ b/frontend/slices/icon-picker/components/IconPicker.tsx
@@ -134,6 +134,7 @@ export function IconPickerPopover({
<Popover open={false} onOpenChange={() => {}}>
<PopoverTrigger asChild>{trigger}</PopoverTrigger>
<ResponsiveDialog open={open} onOpenChange={setOpen} size="md">
+ <ResponsiveDialog.Header className="sr-only"><ResponsiveDialog.Title>Choose icon</ResponsiveDialog.Title></ResponsiveDialog.Header>
<ResponsiveDialog.Body className="flex flex-col gap-0 p-3" style={{ height: "min(560px, 88dvh)" }}>
{body}
</ResponsiveDialog.Body>
diff --git a/frontend/slices/icon-picker/components/picker-parts/ColorRow.tsx b/frontend/slices/icon-picker/components/picker-parts/ColorRow.tsx
index 5840b8ab..ae2dcea4 100644
--- a/frontend/slices/icon-picker/components/picker-parts/ColorRow.tsx
+++ b/frontend/slices/icon-picker/components/picker-parts/ColorRow.tsx
@@ -9,7 +9,7 @@ export function ColorRow({
onPick: (hex: string) => void;
}) {
return (
- <div className="mt-2 flex items-center gap-1.5">
+ <div className="mt-2 flex flex-wrap items-center gap-1.5">
<span className="text-[10px] uppercase tracking-wider text-muted-foreground mr-1">Color</span>
{ICON_COLORS.map((c) => {
const isSelected =
diff --git a/frontend/slices/icon-picker/components/picker-parts/Toolbar.tsx b/frontend/slices/icon-picker/components/picker-parts/Toolbar.tsx
index 10517b7f..68916caf 100644
--- a/frontend/slices/icon-picker/components/picker-parts/Toolbar.tsx
+++ b/frontend/slices/icon-picker/components/picker-parts/Toolbar.tsx
@@ -61,7 +61,7 @@ export function VariantPills<T extends string>({
options: ReadonlyArray<{ value: T; label: string; hint?: string }>;
}) {
return (
- <div className="flex h-7 w-full items-center gap-0.5 rounded-md border border-border bg-muted/30 p-0.5">
+ <div className="flex min-h-7 w-full items-center gap-0.5 rounded-md border border-border bg-muted/30 p-0.5">
{options.map((opt) => {
const active = opt.value === value;
return (
diff --git a/frontend/slices/image-picker/components/image-picker-dialog.tsx b/frontend/slices/image-picker/components/image-picker-dialog.tsx
index d7c04a24..447af59d 100644
--- a/frontend/slices/image-picker/components/image-picker-dialog.tsx
+++ b/frontend/slices/image-picker/components/image-picker-dialog.tsx
@@ -28,6 +28,9 @@ interface Props extends ImageSourceProps {
}
export function ImagePickerDialog({ open, onOpenChange, onSelect, onUpload, title = "Choose image", defaultQuery }: Props) {
+ const id = React.useId();
+ const openRef = React.useRef(open);
+ React.useEffect(() => { openRef.current = open; }, [open]);
const [tab, setTab] = React.useState<Tab>(defaultQuery ? "unsplash" : "gallery");
const tabs: { id: Tab; label: string }[] = [
{ id: "gallery", label: "Gallery" },
@@ -35,7 +38,7 @@ export function ImagePickerDialog({ open, onOpenChange, onSelect, onUpload, titl
{ id: "link", label: "Link" },
{ id: "unsplash", label: "Stock" },
];
- const handle = (c: ImageValue) => { onSelect(c); onOpenChange(false); };
+ const handle = (c: ImageValue) => { if (openRef.current) { onSelect(c); onOpenChange(false); } };
return (
<FormDrawer open={open} onOpenChange={onOpenChange} size="lg">
@@ -52,11 +55,21 @@ export function ImagePickerDialog({ open, onOpenChange, onSelect, onUpload, titl
key={t.id}
type="button"
role="tab"
- id={`image-picker-tab-${t.id}`}
+ id={`${id}-tab-${t.id}`}
aria-selected={tab === t.id}
- aria-controls={`image-picker-panel-${t.id}`}
+ aria-controls={`${id}-panel-${t.id}`}
tabIndex={tab === t.id ? 0 : -1}
onClick={() => setTab(t.id)}
+ onKeyDown={(e) => {
+ const index = tabs.findIndex((item) => item.id === t.id);
+ const next = e.key === "Home" ? 0 : e.key === "End" ? tabs.length - 1
+ : e.key === "ArrowRight" ? (index + 1) % tabs.length
+ : e.key === "ArrowLeft" ? (index - 1 + tabs.length) % tabs.length : -1;
+ if (next < 0) return;
+ e.preventDefault();
+ setTab(tabs[next].id);
+ document.getElementById(`${id}-tab-${tabs[next].id}`)?.focus();
+ }}
className={cn(
"rounded-md px-3 py-1 text-xs font-medium transition [@media(pointer:coarse)]:min-h-[44px]",
tab === t.id ? "bg-accent text-foreground" : "text-muted-foreground hover:bg-accent/50",
@@ -68,8 +81,8 @@ export function ImagePickerDialog({ open, onOpenChange, onSelect, onUpload, titl
</div>
<div
role="tabpanel"
- id={`image-picker-panel-${tab}`}
- aria-labelledby={`image-picker-tab-${tab}`}
+ id={`${id}-panel-${tab}`}
+ aria-labelledby={`${id}-tab-${tab}`}
className="flex-1 overflow-y-auto"
>
{tab === "gallery" && <GalleryTab onSelect={handle} />}
diff --git a/frontend/slices/image-picker/components/image-picker/link-tab.tsx b/frontend/slices/image-picker/components/image-picker/link-tab.tsx
index 4f62a86f..ce670335 100644
--- a/frontend/slices/image-picker/components/image-picker/link-tab.tsx
+++ b/frontend/slices/image-picker/components/image-picker/link-tab.tsx
@@ -8,34 +8,48 @@ import type { ImageValue } from "../../types";
const URL_RX = /^https?:\/\/[^\s]+/i;
export function LinkTab({ onSelect }: { onSelect: (c: ImageValue) => void }) {
+ const request = React.useRef(0);
+ React.useEffect(() => () => { request.current++; }, []);
const [url, setUrl] = React.useState("");
const [verifying, setVerifying] = React.useState(false);
const [err, setErr] = React.useState<string | null>(null);
const submit = async () => {
+ if (verifying) return;
const v = url.trim();
if (!URL_RX.test(v)) { setErr("Paste a full https:// image URL"); return; }
+ const current = ++request.current;
setErr(null);
setVerifying(true);
- await new Promise<void>((resolve) => {
+ const valid = await new Promise<boolean>((resolve) => {
const img = new Image();
- img.onload = () => resolve();
- img.onerror = () => resolve();
+ const timer = window.setTimeout(() => finish(false), 10000);
+ const finish = (ok: boolean) => {
+ window.clearTimeout(timer);
+ img.onload = null;
+ img.onerror = null;
+ resolve(ok);
+ };
+ img.onload = () => finish(img.naturalWidth > 0 && img.naturalHeight > 0);
+ img.onerror = () => finish(false);
img.src = v;
});
+ if (current !== request.current) return;
setVerifying(false);
+ if (!valid) { setErr("Could not load this image. Check the URL and try again."); return; }
onSelect({ type: "link", value: v, positionY: 50 });
};
return (
<div className="space-y-3 p-4">
<Input
+ aria-label="Image URL"
placeholder="https://images.example.com/photo.jpg"
value={url}
- onChange={(e) => setUrl(e.target.value)}
+ onChange={(e) => { request.current++; setVerifying(false); setUrl(e.target.value); }}
onKeyDown={(e) => e.key === "Enter" && submit()}
/>
- {err && <p className="text-xs text-destructive">{err}</p>}
+ {err && <p role="alert" className="text-xs text-destructive">{err}</p>}
<Button onClick={submit} disabled={verifying} className="w-full">
{verifying ? "Checking…" : "Add image"}
</Button>
diff --git a/frontend/slices/image-picker/components/image-picker/upload-tab.tsx b/frontend/slices/image-picker/components/image-picker/upload-tab.tsx
index 4c3f4312..da317bc6 100644
--- a/frontend/slices/image-picker/components/image-picker/upload-tab.tsx
+++ b/frontend/slices/image-picker/components/image-picker/upload-tab.tsx
@@ -9,6 +9,7 @@ const MAX = 8 * 1024 * 1024;
const ALLOWED_IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif", "image/avif"]);
export function UploadTab({ onSelect, onUpload }: { onSelect: (c: ImageValue) => void; onUpload: UploadFn }) {
+ const inputRef = React.useRef<HTMLInputElement>(null);
const [file, setFile] = React.useState<File | null>(null);
const [preview, setPreview] = React.useState<string | null>(null);
const [busy, setBusy] = React.useState(false);
@@ -20,6 +21,8 @@ export function UploadTab({ onSelect, onUpload }: { onSelect: (c: ImageValue) =>
const pick = (f: File | undefined) => {
if (!f) return;
+ setFile(null);
+ setPreview(null);
if (!ALLOWED_IMAGE_TYPES.has(f.type)) { setErr("PNG, JPEG, WebP, GIF or AVIF only"); return; }
if (f.size > MAX) { setErr("Max 8 MB"); return; }
setErr(null);
@@ -57,9 +60,10 @@ export function UploadTab({ onSelect, onUpload }: { onSelect: (c: ImageValue) =>
<span>Drag an image or click to choose (≤ 8 MB)</span>
</>
)}
- <input type="file" accept="image/*" className="hidden" onChange={(e) => pick(e.target.files?.[0] ?? undefined)} />
+ <input ref={inputRef} type="file" accept="image/*" className="hidden" onChange={(e) => { pick(e.target.files?.[0] ?? undefined); e.target.value = ""; }} />
</label>
- {err && <p className="text-xs text-destructive">{err}</p>}
+ <Button type="button" variant="outline" onClick={() => inputRef.current?.click()}>Choose file</Button>
+ {err && <p role="alert" className="text-xs text-destructive">{err}</p>}
<Button onClick={apply} disabled={!file || busy} className="w-full">
{busy ? "Uploading…" : "Upload & set image"}
</Button>
diff --git a/frontend/slices/os-settings/app.tsx b/frontend/slices/os-settings/app.tsx
index 09f22be9..c4efa4b5 100644
--- a/frontend/slices/os-settings/app.tsx
+++ b/frontend/slices/os-settings/app.tsx
@@ -10,14 +10,17 @@ import { IS_DEMO } from "@/lib/demo";
import {
useActiveShell,
usePublishInspector,
+ useFeatureState,
+ setCloseGuard,
toast,
} from "@/features/appshell";
import type { SectionId } from "./lib/sections";
import { AboutPageState } from "./components/about-page-state";
import { SettingsShell } from "./components/settings-shell";
+import { SettingsWindowContext } from "./lib/window-context";
// Default export so os-shell can lazy-load it as a window app.
-export default function OsSettings() {
+export default function OsSettings({ winId }: { winId?: string }) {
const params = useSearchParams();
const initial = sectionFromSearch(params.get("section"));
const { tweaks } = useAppearance();
@@ -26,11 +29,26 @@ export default function OsSettings() {
// No shell-specific layout/config lives in this headless app controller.
const { surface } = useActiveShell();
const [model, setModel] = useState("default");
+ const [sensitiveDirty, setSensitiveDirty] = useState(false);
// On mobile we start on the section list (no selection drilled in); desktop
// always shows a selected pane. `null` = list view, an id = detail view.
- const [active, setActive] = useState<SectionId | null>(
+ const [active, setActive] = useFeatureState<SectionId | null>(winId, "settings-section",
initial ?? (surface === "mobile" ? null : "appearance"),
);
+ 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);
+ useEffect(() => {
+ if (!draftDirty) return;
+ if (winId) setCloseGuard(winId, () => 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]);
const serverTarget = effectiveServerTarget(tweaks.server);
useEffect(() => {
@@ -68,8 +86,14 @@ export default function OsSettings() {
);
return (
- <AboutPageState initial={initialAboutPage(initial ?? null, params.get("page"))}>
- <SettingsShell active={active} onSelect={setActive} />
- </AboutPageState>
+ <SettingsWindowContext.Provider value={{ winId, setSensitiveDirty }}>
+ <AboutPageState initial={initialAboutPage(initial ?? null, params.get("page"))}>
+ <SettingsShell active={active} onSelect={(next) => {
+ if (next !== active && sensitiveDirty && !window.confirm("Discard the unsaved API key or JSON?")) return;
+ if (next !== active) setSensitiveDirty(false);
+ setActive(next);
+ }} />
+ </AboutPageState>
+ </SettingsWindowContext.Provider>
);
}
diff --git a/frontend/slices/os-settings/components/custom-provider-form.tsx b/frontend/slices/os-settings/components/custom-provider-form.tsx
index 19e0b327..04557cc1 100644
--- a/frontend/slices/os-settings/components/custom-provider-form.tsx
+++ b/frontend/slices/os-settings/components/custom-provider-form.tsx
@@ -1,12 +1,13 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
-import { toast } from "@/features/appshell";
+import { toast, useFeatureState } from "@/features/appshell";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { parseCustomProviderConfig, parseModelList, toggleModelInList } from "./custom-provider-config";
+import { useSettingsWindow } from "../lib/window-context";
export type DiscoveredModel = { id: string; name: string };
export type DiscoveryFailure = "invalid-url" | "auth" | "empty";
@@ -65,20 +66,18 @@ export function modelFieldFromDiscovered(list: DiscoveredModel[]): string {
// 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 [mode, setMode] = useState<"fields" | "json">("fields");
- const [name, setName] = useState("");
- const [baseURL, setBaseURL] = useState("");
+ 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 [protocol, setProtocol] = useState("openai");
- const [models, setModels] = useState("");
+ const [protocol, setProtocol] = useFeatureState(winId, "provider-protocol", "openai");
+ const [models, setModels] = useFeatureState(winId, "provider-models", "");
const [json, setJson] = useState("");
- const [busy, setBusy] = useState(false);
- const [found, setFound] = useState<DiscoveredModel[]>([]);
+ const [busy, setBusy] = useState(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-run
const abortRef = useRef<AbortController | null>(null);
-
const run = useCallback(async (signal: AbortSignal, target: string, apiKey: string, proto: string) => {
if (!baseUrlLooksValid(target) || !apiKey.trim()) {
setFailure("invalid-url");
@@ -109,7 +108,7 @@ export function CustomProviderForm({ onAdded }: { onAdded: () => void }) {
} finally {
if (!signal.aborted) setScanning(false);
}
- }, []);
+ }, [setModels]);
const start = useCallback((target: string, apiKey: string, proto: string) => {
abortRef.current?.abort(); // one discovery in flight, cancellable
@@ -131,7 +130,6 @@ export function CustomProviderForm({ onAdded }: { onAdded: () => void }) {
}, [baseURL, key, mode, protocol, start]);
useEffect(() => () => abortRef.current?.abort(), []);
-
// The route re-validates everything (SSRF, slug, key); this only reports it.
async function submit() {
setBusy(true);
@@ -146,6 +144,7 @@ export function CustomProviderForm({ onAdded }: { onAdded: () => void }) {
const body = (await response.json().catch(() => ({}))) as { slug?: string; error?: string };
if (!response.ok) return void toast(body.error || "Couldn’t add provider", { tone: "error" });
setName(""); setBaseURL(""); setKey(""); setModels(""); setJson(""); setFound([]); setFailure(null);
+ setSensitiveDirty(false);
autoFired.current.clear(); // a fresh form starts with a fresh budget
toast(`Added ${body.slug ?? "provider"}`);
onAdded();
@@ -157,7 +156,6 @@ export function CustomProviderForm({ onAdded }: { onAdded: () => void }) {
const selectedIds = parseModelList(models);
const canSubmit = !busy && (mode === "json" ? !!json.trim() : !!name && !!baseURL && !!key);
const ghost = "h-auto p-0 text-xs hover:bg-transparent hover:underline [@media(pointer:coarse)]:min-h-[44px]";
-
return (
<div className="space-y-2 rounded-lg border border-border p-3">
<div className="flex items-center justify-between text-xs text-muted-foreground">
@@ -166,6 +164,7 @@ export function CustomProviderForm({ onAdded }: { onAdded: () => void }) {
{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>
{mode === "fields" ? (
<div className="space-y-2">
<div className="flex flex-wrap gap-2">
@@ -179,7 +178,7 @@ export function CustomProviderForm({ onAdded }: { onAdded: () => void }) {
</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)} />
+ <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)); }} />
<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)}>
@@ -208,10 +207,11 @@ export function CustomProviderForm({ onAdded }: { onAdded: () => void }) {
</div>
) : (
<Textarea disabled={busy} rows={7} className="font-mono text-xs" value={json} aria-label="Custom provider JSON"
- onChange={(e) => setJson(e.target.value)}
+ onChange={(e) => { setJson(e.target.value); setSensitiveDirty(Boolean(e.target.value || key)); }}
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 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/settings-shell.tsx b/frontend/slices/os-settings/components/settings-shell.tsx
index bf3f7620..e904eec3 100644
--- a/frontend/slices/os-settings/components/settings-shell.tsx
+++ b/frontend/slices/os-settings/components/settings-shell.tsx
@@ -45,7 +45,7 @@ export function SettingsShell({ active, onSelect }: { active: SectionId | null;
return (
<div className="flex h-full min-h-0 bg-muted/30">
<AppSidebar open={sidebarOpen} onOpenChange={setSidebarOpen} title="Settings sections"
- railClassName={design.id === "windows" ? "w-64 border-r-0 bg-[var(--mica-win,var(--sidebar))]" : "w-56 bg-sidebar/70"}>
+ railClassName={design.id === "windows" ? "border-r-0 bg-[var(--mica-win,var(--sidebar))]" : "bg-sidebar/70"}>
<SettingsSidebar windows={design.id === "windows"} active={desktopActive} onSelect={(id) => { onSelect(id); setSidebarOpen(false); }} />
</AppSidebar>
<AppFrame className="min-w-0 flex-1" toolbar={<div className="hidden border-b border-border p-1 @max-[600px]:block">
diff --git a/frontend/slices/os-settings/components/theme-section.tsx b/frontend/slices/os-settings/components/theme-section.tsx
index 02ef053c..4a5cba33 100644
--- a/frontend/slices/os-settings/components/theme-section.tsx
+++ b/frontend/slices/os-settings/components/theme-section.tsx
@@ -79,12 +79,16 @@ export function ThemeSection() {
const design = useShellDesign();
const mobile = design.mobileNavigation !== "none";
const [groups, setGroups] = useState<PresetGroup[] | null>(null);
+ const [error, setError] = useState(false);
+ const [attempt, setAttempt] = useState(0);
useEffect(() => {
+ let active = true;
loadPresetRegistry()
- .then((reg) => setGroups(groupPresets(reg.items)))
- .catch(() => setGroups([]));
- }, []);
+ .then((reg) => { if (active) setGroups(groupPresets(reg.items)); })
+ .catch(() => { if (active) setError(true); });
+ return () => { active = false; };
+ }, [attempt]);
return (
<div className="space-y-4 sm:space-y-5">
@@ -122,8 +126,12 @@ export function ThemeSection() {
<RotateCcw /> Stock
</Button>
</div>
- {groups === null ? (
+ {error ? (
+ <div role="alert" className="space-y-2 px-1 text-sm">Could not load presets. <Button type="button" variant="outline" size="sm" onClick={() => { setError(false); setGroups(null); setAttempt((n) => n + 1); }}>Retry</Button></div>
+ ) : groups === null ? (
<p className="px-1 text-xs text-muted-foreground">Loading presets…</p>
+ ) : groups.length === 0 ? (
+ <p className="px-1 text-xs text-muted-foreground">No presets available.</p>
) : (
<div className="space-y-3">
{groups.map((group) => (
diff --git a/frontend/slices/os-settings/lib/window-context.ts b/frontend/slices/os-settings/lib/window-context.ts
new file mode 100644
index 00000000..5267af32
--- /dev/null
+++ b/frontend/slices/os-settings/lib/window-context.ts
@@ -0,0 +1,6 @@
+"use client";
+
+import { createContext, useContext } from "react";
+
+export const SettingsWindowContext = createContext<{ winId?: string; setSensitiveDirty: (dirty: boolean) => void }>({ setSensitiveDirty: () => {} });
+export const useSettingsWindow = () => useContext(SettingsWindowContext);
diff --git a/lib/appearance/presets/registry.test.ts b/lib/appearance/presets/registry.test.ts
new file mode 100644
index 00000000..11a7205e
--- /dev/null
+++ b/lib/appearance/presets/registry.test.ts
@@ -0,0 +1,16 @@
+import { afterEach, expect, it, vi } from "vitest";
+
+afterEach(() => {
+ vi.doUnmock("./registry-data.json");
+ vi.resetModules();
+});
+
+it("retries the registry after a failed load", async () => {
+ vi.resetModules();
+ vi.doMock("./registry-data.json", () => { throw new Error("load failed"); });
+ const { loadPresetRegistry } = await import("./registry");
+ await expect(loadPresetRegistry()).rejects.toThrow();
+ vi.doUnmock("./registry-data.json");
+ const registry = await loadPresetRegistry();
+ expect(registry.items.length).toBeGreaterThan(0);
+});
diff --git a/lib/appearance/presets/registry.ts b/lib/appearance/presets/registry.ts
index 515eb9eb..180788fb 100644
--- a/lib/appearance/presets/registry.ts
+++ b/lib/appearance/presets/registry.ts
@@ -17,6 +17,9 @@ export async function loadPresetRegistry(): Promise<PresetRegistry> {
items: data.items.filter((i) => i.cssVars?.light && i.cssVars?.dark),
};
return cache;
+ }).catch((error) => {
+ pending = null;
+ throw error;
});
return pending;
}