High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: clean up of the dashboard
Luigi Agostieca0f9bdad36
diff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.goindex e5a8cfe4..d640d920 100644--- a/cmd/pinchtab/cmd_dashboard.go+++ b/cmd/pinchtab/cmd_dashboard.go@@ -36,6 +36,7 @@ func runDashboard(cfg *config.RuntimeConfig) {if dashPort == "" {dashPort = "9870"}+ startedAt := time.Now()slog.Info("🦀 PinchTab", "port", dashPort)@@ -51,6 +52,7 @@ func runDashboard(cfg *config.RuntimeConfig) {orch.ApplyRuntimeConfig(cfg)orch.SetProfileManager(profMgr)dash.SetInstanceLister(orch)+ configAPI := dashboard.NewConfigAPI(cfg, orch, profMgr, orch, version, startedAt)// Wire up instance events to SSE broadcastorch.OnEvent(func(evt orchestrator.InstanceEvent) {@@ -63,6 +65,7 @@ func runDashboard(cfg *config.RuntimeConfig) {mux := http.NewServeMux()dash.RegisterHandlers(mux)+ configAPI.RegisterHandlers(mux)profMgr.RegisterHandlers(mux)// Strategy-based routing: if a known strategy is configured, let it handle@@ -134,9 +137,7 @@ func runDashboard(cfg *config.RuntimeConfig) {})})- mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {- web.JSON(w, 200, map[string]string{"status": "ok", "mode": "dashboard"})- })+ mux.HandleFunc("GET /health", configAPI.HandleHealth)mux.HandleFunc("GET /metrics", func(w http.ResponseWriter, r *http.Request) {web.JSON(w, 200, map[string]any{"metrics": handlers.SnapshotMetrics()})diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsxindex 3f389ca7..97f9fc2b 100644--- a/dashboard/src/App.tsx+++ b/dashboard/src/App.tsx@@ -8,19 +8,17 @@ import {} from "react-router-dom";import { useAppStore } from "./stores/useAppStore";import { NavBar } from "./components/molecules";-import { DebugPanel } from "./components/atoms";-import {- MonitoringPage,- ProfilesPage,- AgentsPage,- SettingsPage,-} from "./pages";+import { MonitoringPage, ProfilesPage, SettingsPage } from "./pages";import * as api from "./services/api";function AppContent() {const { setInstances, setProfiles, setAgents, setServerInfo } = useAppStore();const location = useLocation();+ useEffect(() => {+ document.documentElement.setAttribute("data-site-mode", "agent");+ }, []);+// Log navigation for debugginguseEffect(() => {console.log("📍 Navigation:", location.pathname);@@ -73,18 +71,20 @@ function AppContent() {}, [setInstances, setProfiles, setAgents]);return (- <div className="flex h-screen flex-col bg-bg-app">+ <div className="dashboard-shell flex h-screen flex-col bg-bg-app"><NavBar />- <main className="flex-1 overflow-hidden">+ <main className="dashboard-grid flex-1 overflow-hidden"><Routes><Route path="/" element={<Navigate to="/monitoring" replace />} /><Route path="/monitoring" element={<MonitoringPage />} /><Route path="/profiles" element={<ProfilesPage />} />- <Route path="/agents" element={<AgentsPage />} />+ <Route+ path="/agents"+ element={<Navigate to="/monitoring" replace />}+ /><Route path="/settings" element={<SettingsPage />} /></Routes></main>- <DebugPanel /></div>);}diff --git a/dashboard/src/components/atoms/Badge.test.tsx b/dashboard/src/components/atoms/Badge.test.tsxindex 17e33b93..7dc20f50 100644--- a/dashboard/src/components/atoms/Badge.test.tsx+++ b/dashboard/src/components/atoms/Badge.test.tsx@@ -11,7 +11,12 @@ describe("Badge", () => {it("applies default variant styles", () => {render(<Badge>Default</Badge>);const badge = screen.getByText("Default");- expect(badge).toHaveClass("bg-bg-elevated", "text-text-secondary");+ expect(badge).toHaveClass(+ "border",+ "border-border-subtle",+ "bg-white/[0.03]",+ "text-text-secondary",+ );});it("applies success variant styles", () => {@@ -44,9 +49,9 @@ describe("Badge", () => {expect(badge).toHaveClass("inline-flex","items-center",- "rounded",- "text-xs",- "font-medium",+ "rounded-sm",+ "font-semibold",+ "uppercase",);});});diff --git a/dashboard/src/components/atoms/Badge.tsx b/dashboard/src/components/atoms/Badge.tsxindex d56cf0de..ca5287a8 100644--- a/dashboard/src/components/atoms/Badge.tsx+++ b/dashboard/src/components/atoms/Badge.tsx@@ -6,17 +6,17 @@ interface Props {}const variants: Record<Variant, string> = {- default: "bg-bg-elevated text-text-secondary",- success: "bg-success/15 text-success",- warning: "bg-warning/15 text-warning",- danger: "bg-destructive/15 text-destructive",- info: "bg-info/15 text-info",+ default: "border border-border-subtle bg-white/[0.03] text-text-secondary",+ success: "border border-success/35 bg-success/15 text-success",+ warning: "border border-warning/35 bg-warning/15 text-warning",+ danger: "border border-destructive/35 bg-destructive/10 text-destructive",+ info: "border border-info/35 bg-info/10 text-info",};export default function Badge({ variant = "default", children }: Props) {return (<span- className={`inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium ${variants[variant]}`}+ className={`inline-flex items-center rounded-sm px-2 py-1 text-[0.68rem] font-semibold uppercase tracking-[0.08em] ${variants[variant]}`}>{children}</span>diff --git a/dashboard/src/components/atoms/Button.tsx b/dashboard/src/components/atoms/Button.tsxindex 7b53a189..96a07ccf 100644--- a/dashboard/src/components/atoms/Button.tsx+++ b/dashboard/src/components/atoms/Button.tsx@@ -11,23 +11,25 @@ interface Props extends ButtonHTMLAttributes<HTMLButtonElement> {}const base =- "inline-flex items-center justify-center gap-1.5 rounded font-medium transition-all duration-150 disabled:cursor-not-allowed disabled:opacity-40";+ "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-sm font-semibold transition-all duration-150 active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-50";const variants: Record<Variant, string> = {default:- "border border-border-default bg-bg-elevated text-text-secondary hover:bg-bg-hover hover:text-text-primary",- primary: "bg-primary text-white hover:bg-primary-hover",+ "border border-border-subtle bg-white/5 text-text-primary hover:border-border-default hover:bg-white/[0.08]",+ primary:+ "bg-primary text-white shadow-[0_0_24px_rgb(var(--brand-accent-rgb)/0.18)] hover:bg-primary-hover",secondary:- "border border-border-subtle bg-transparent text-text-muted hover:bg-bg-elevated hover:text-text-secondary",- danger: "bg-destructive text-white hover:bg-destructive/80",+ "border border-border-subtle bg-transparent text-text-secondary hover:border-border-default hover:bg-bg-hover hover:text-text-primary",+ danger:+ "border border-destructive/30 bg-destructive/10 text-destructive hover:bg-destructive/15",ghost:- "bg-transparent text-text-muted hover:bg-bg-elevated hover:text-text-secondary",+ "bg-transparent text-text-secondary hover:bg-bg-hover hover:text-text-primary",};const sizes: Record<Size, string> = {- sm: "px-2 py-1 text-xs",- md: "px-3 py-1.5 text-sm",- lg: "px-4 py-2 text-base",+ sm: "px-3 py-1.5 text-xs",+ md: "px-3.5 py-2 text-sm",+ lg: "px-5 py-2.5 text-base",};// Spinner sizes match button text sizesdiff --git a/dashboard/src/components/atoms/Card.tsx b/dashboard/src/components/atoms/Card.tsxindex 437cfdd2..ce5f8e53 100644--- a/dashboard/src/components/atoms/Card.tsx+++ b/dashboard/src/components/atoms/Card.tsx@@ -14,13 +14,9 @@ export default function Card({}: Props) {return (<div- className={`rounded-lg border bg-bg-surface ${- selected ? "border-primary" : "border-border-subtle"- } ${- hover- ? "cursor-pointer transition-all duration-150 hover:border-border-default hover:bg-bg-elevated"- : ""- } ${className}`}+ className={`dashboard-panel ${+ selected ? "dashboard-panel-selected border-primary" : ""+ } ${hover ? "dashboard-panel-hover cursor-pointer" : ""} ${className}`}{...props}>{children}diff --git a/dashboard/src/components/atoms/EmptyState.tsx b/dashboard/src/components/atoms/EmptyState.tsxindex 0d55bb3a..dfbe977e 100644--- a/dashboard/src/components/atoms/EmptyState.tsx+++ b/dashboard/src/components/atoms/EmptyState.tsx@@ -13,10 +13,15 @@ export default function EmptyState({}: Props) {return (<div className="flex flex-col items-center justify-center py-16 text-center">- <div className="mb-3 text-5xl">{icon}</div>- <div className="text-text-secondary">{title}</div>+ <div className="mb-3 flex h-[4.5rem] w-[4.5rem] items-center justify-center rounded-full border border-border-subtle bg-primary/[0.08] text-4xl shadow-[0_0_30px_rgb(var(--brand-accent-rgb)/0.08)]">+ {icon}+ </div>+ <div className="dashboard-section-label mb-2">Dashboard</div>+ <div className="text-lg font-semibold text-text-primary">{title}</div>{description && (- <div className="mt-1 text-sm text-text-muted">{description}</div>+ <div className="mt-1 max-w-md text-sm leading-6 text-text-muted">+ {description}+ </div>)}{action && <div className="mt-4">{action}</div>}</div>diff --git a/dashboard/src/components/atoms/Input.tsx b/dashboard/src/components/atoms/Input.tsxindex 968ccb2f..86cb7037 100644--- a/dashboard/src/components/atoms/Input.tsx+++ b/dashboard/src/components/atoms/Input.tsx@@ -9,11 +9,15 @@ interface Props extends InputHTMLAttributes<HTMLInputElement> {const Input = forwardRef<HTMLInputElement, Props>(({ label, hint, className = "", ...props }, ref) => {return (- <div className="flex flex-col gap-1">- {label && <label className="text-xs text-text-muted">{label}</label>}+ <div className="flex flex-col gap-1.5">+ {label && (+ <label className="dashboard-section-title text-[0.68rem]">+ {label}+ </label>+ )}<inputref={ref}- className={`rounded border border-border-default bg-bg-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-primary focus:outline-none ${className}`}+ className={`rounded-sm border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.72)] px-3 py-2 text-sm text-text-primary placeholder:text-text-muted transition-all duration-150 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 ${className}`}{...props}/>{hint && <span className="text-xs text-text-muted">{hint}</span>}diff --git a/dashboard/src/components/atoms/Modal.tsx b/dashboard/src/components/atoms/Modal.tsxindex 70bbaeb3..a99c64a7 100644--- a/dashboard/src/components/atoms/Modal.tsx+++ b/dashboard/src/components/atoms/Modal.tsx@@ -36,20 +36,21 @@ export default function Modal({return (<div- className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 backdrop-blur-sm"onClick={onClose}><div- className={`max-h-[90vh] overflow-y-auto rounded-lg border border-border-subtle bg-bg-surface p-5 shadow-xl ${+ className={`dashboard-panel max-h-[90vh] overflow-y-auto p-5 ${wide ? "w-full max-w-lg" : "w-full max-w-sm"}`}onClick={(e) => e.stopPropagation()}>- <h3 className="mb-4 text-lg font-semibold text-text-primary">- {title}- </h3>+ <div className="mb-4 border-b border-border-subtle pb-4">+ <div className="dashboard-section-label mb-2">Dashboard</div>+ <h3 className="text-lg font-semibold text-text-primary">{title}</h3>+ </div><div className="text-sm text-text-secondary">{children}</div>- <div className="mt-5 flex justify-end gap-2">+ <div className="mt-5 flex justify-end gap-2 border-t border-border-subtle pt-4">{actions ?? (<Button variant="secondary" onClick={onClose}>Closediff --git a/dashboard/src/components/atoms/Toolbar.tsx b/dashboard/src/components/atoms/Toolbar.tsxindex 5ef3832b..b14c1486 100644--- a/dashboard/src/components/atoms/Toolbar.tsx+++ b/dashboard/src/components/atoms/Toolbar.tsx@@ -1,3 +1,5 @@+import Button from "./Button";+interface ToolbarAction {key: string;label: string;@@ -11,26 +13,23 @@ interface Props {children?: React.ReactNode;}-const actionBtn =- "inline-flex cursor-pointer items-center gap-1.5 whitespace-nowrap rounded border border-border-subtle bg-bg-elevated px-3 py-1.5 text-xs font-medium text-text-secondary transition-all duration-150 hover:not-disabled:border-border-default hover:not-disabled:bg-bg-hover hover:not-disabled:text-text-primary disabled:cursor-not-allowed disabled:opacity-40";--const primaryBtn =- "border-primary/50 bg-primary/10 text-primary hover:not-disabled:border-primary hover:not-disabled:bg-primary/20";-export default function Toolbar({ actions, children }: Props) {return (- <div className="flex items-center gap-2 border-b border-border-subtle bg-bg-surface px-4 py-2">- {actions?.map((a) => (- <button- key={a.key}- className={`${actionBtn} ${a.variant === "primary" ? primaryBtn : ""}`}- onClick={a.onClick}- disabled={a.disabled}- >- {a.label}- </button>- ))}+ <div className="flex items-center gap-2 border-b border-border-subtle bg-bg-surface/95 px-4 py-3 backdrop-blur">{children}+ <div className="ml-auto flex items-center gap-2">+ {actions?.map((a) => (+ <Button+ key={a.key}+ onClick={a.onClick}+ disabled={a.disabled}+ variant={a.variant === "primary" ? "primary" : "secondary"}+ size="md"+ >+ {a.label}+ </Button>+ ))}+ </div></div>);}diff --git a/dashboard/src/components/molecules/ActivityLine.tsx b/dashboard/src/components/molecules/ActivityLine.tsxindex 319126c1..1b876b80 100644--- a/dashboard/src/components/molecules/ActivityLine.tsx+++ b/dashboard/src/components/molecules/ActivityLine.tsx@@ -31,18 +31,20 @@ function formatTime(ts: string): string {export default function ActivityLine({ event }: Props) {return (- <div className="flex items-center gap-3 border-b border-border-subtle px-4 py-2 text-sm">+ <div className="flex items-center gap-3 border-b border-border-subtle/70 px-4 py-3 text-sm transition-colors hover:bg-white/[0.02]"><span className="text-lg">{typeIcons[event.type] || "📝"}</span>- <span className="w-16 shrink-0 font-mono text-xs text-text-muted">+ <span className="dashboard-mono w-[4.5rem] shrink-0 text-xs text-text-muted">{formatTime(event.timestamp)}</span><Badge variant={typeColors[event.type] || "default"}>{event.method}</Badge>- <span className="min-w-0 flex-1 truncate font-mono text-text-secondary">+ <span className="dashboard-mono min-w-0 flex-1 truncate text-text-secondary">{event.path}</span>- <span className="shrink-0 text-xs text-text-muted">{event.agentId}</span>+ <span className="dashboard-mono shrink-0 text-xs text-text-muted">+ {event.agentId}+ </span></div>);}diff --git a/dashboard/src/components/molecules/AgentItem.tsx b/dashboard/src/components/molecules/AgentItem.tsxindex 49e5dc3a..d2668045 100644--- a/dashboard/src/components/molecules/AgentItem.tsx+++ b/dashboard/src/components/molecules/AgentItem.tsx@@ -19,21 +19,21 @@ function timeAgo(date: string): string {export default function AgentItem({ agent, selected, onClick }: Props) {return (<button- className={`flex w-full items-center gap-3 rounded-lg px-3 py-2 text-left transition-all duration-150 ${+ className={`flex w-full items-center gap-3 px-3 py-3 text-left ${selected- ? "bg-primary/10 border border-primary"- : "border border-transparent hover:bg-bg-elevated"+ ? "dashboard-panel dashboard-panel-selected border-primary"+ : "dashboard-panel dashboard-panel-hover"}`}onClick={onClick}>- <div className="flex h-9 w-9 items-center justify-center rounded-full bg-bg-elevated text-lg">+ <div className="flex h-10 w-10 items-center justify-center rounded-full border border-border-subtle bg-primary/10 text-lg shadow-[0_0_20px_rgb(var(--brand-accent-rgb)/0.08)]">🤖</div><div className="min-w-0 flex-1"><div className="truncate font-medium text-text-primary">{agent.name || agent.id}</div>- <div className="text-xs text-text-muted">+ <div className="dashboard-mono text-xs text-text-muted">{timeAgo(agent.lastActivity || agent.connectedAt)}</div></div>diff --git a/dashboard/src/components/molecules/InstanceCard.tsx b/dashboard/src/components/molecules/InstanceCard.tsxindex a081ccb8..3baf7a85 100644--- a/dashboard/src/components/molecules/InstanceCard.tsx+++ b/dashboard/src/components/molecules/InstanceCard.tsx@@ -34,9 +34,11 @@ export default function InstanceCard({ instance, onOpen, onStop }: Props) {</Badge></div>- <div className="mb-3 rounded bg-bg-elevated px-2 py-1.5 text-xs">- <span className="text-text-muted">Uptime:</span>{" "}- <span className="text-text-secondary">+ <div className="mb-3 rounded-sm border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.4)] px-3 py-2 text-xs">+ <span className="dashboard-section-title mr-2 text-[0.68rem]">+ Uptime+ </span>+ <span className="dashboard-mono text-text-secondary">{formatUptime(instance.startTime)}</span></div>diff --git a/dashboard/src/components/molecules/InstanceListItem.tsx b/dashboard/src/components/molecules/InstanceListItem.tsxindex 3649798d..d4d42f70 100644--- a/dashboard/src/components/molecules/InstanceListItem.tsx+++ b/dashboard/src/components/molecules/InstanceListItem.tsx@@ -33,10 +33,10 @@ export default function InstanceListItem({return (<buttononClick={onClick}- className={`mb-1 flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left transition-all ${+ className={`mb-2 flex w-full items-center gap-3 px-3 py-3 text-left ${selected- ? "bg-primary/10 border border-primary"- : "border border-transparent hover:bg-bg-elevated"+ ? "dashboard-panel dashboard-panel-selected border-primary"+ : "dashboard-panel dashboard-panel-hover"}`}><div className={`h-2 w-2 rounded-full ${statusColor}`} />@@ -44,7 +44,7 @@ export default function InstanceListItem({<div className="truncate text-sm font-medium text-text-primary">{instance.profileName}</div>- <div className="text-xs text-text-muted">+ <div className="dashboard-mono text-xs text-text-muted">:{instance.port} · {tabCount} tabs{memoryMB !== undefined && ` · ${memoryMB.toFixed(0)}MB`}</div>diff --git a/dashboard/src/components/molecules/NavBar.css b/dashboard/src/components/molecules/NavBar.cssindex 3f713fbc..d2f7f871 100644--- a/dashboard/src/components/molecules/NavBar.css+++ b/dashboard/src/components/molecules/NavBar.css@@ -16,13 +16,13 @@.navbar-tab.active::after {content: "";position: absolute;- bottom: 0;- left: 8px;- right: 8px;+ bottom: 6px;+ left: 12px;+ right: 12px;height: 2px;background: var(--color-primary);- border-radius: 1px;+ border-radius: 9999px;box-shadow:- 0 0 0 1px color-mix(in srgb, var(--color-primary) 38%, transparent),- 0 0 12px color-mix(in srgb, var(--color-primary) 18%, transparent);+ 0 0 0 1px color-mix(in srgb, var(--color-primary) 28%, transparent),+ 0 0 18px color-mix(in srgb, var(--color-primary) 24%, transparent);}diff --git a/dashboard/src/components/molecules/NavBar.tsx b/dashboard/src/components/molecules/NavBar.tsxindex 6d367a02..d3b9df01 100644--- a/dashboard/src/components/molecules/NavBar.tsx+++ b/dashboard/src/components/molecules/NavBar.tsx@@ -11,7 +11,6 @@ interface Tab {const tabs: Tab[] = [{ id: "monitoring", path: "/monitoring", label: "Monitoring" },- { id: "agents", path: "/agents", label: "Agents" },{ id: "profiles", path: "/profiles", label: "Profiles" },{ id: "settings", path: "/settings", label: "Settings" },];@@ -58,9 +57,9 @@ export default function NavBar({ onRefresh }: NavBarProps) {}, [onRefresh, handleRefresh]);return (- <header className="sticky top-0 z-50 border-b border-border-subtle bg-bg-app">- <div className="flex h-[52px] items-center gap-0 px-4">- <span className="min-w-32 text-sm font-semibold tracking-wide text-text-primary">+ <header className="sticky top-0 z-50 border-b border-border-subtle bg-bg-app/95 backdrop-blur">+ <div className="flex h-[60px] items-center gap-0 px-4 sm:px-5">+ <span className="min-w-32 text-sm font-semibold tracking-[0.2em] text-text-primary uppercase">PinchTab</span>@@ -71,8 +70,10 @@ export default function NavBar({ onRefresh }: NavBarProps) {key={tab.id}to={tab.path}className={({ isActive }) =>- `navbar-tab relative cursor-pointer border-none bg-transparent px-3.5 py-3.5 text-sm font-medium leading-none whitespace-nowrap transition-colors duration-150 hover:text-text-primary focus-visible:rounded focus-visible:shadow-[0_0_0_2px_var(--primary)/25] focus-visible:outline-none ${- isActive ? "active text-text-primary" : "text-text-secondary"+ `navbar-tab relative cursor-pointer rounded-sm border border-transparent bg-transparent px-3.5 py-2.5 text-sm font-medium leading-none whitespace-nowrap transition-all duration-150 hover:border-border-subtle hover:bg-bg-hover/70 hover:text-text-primary focus-visible:rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30 ${+ isActive+ ? "active border-primary/20 bg-primary/10 text-text-primary"+ : "text-text-secondary"}`}title={`${tab.label} (⌘${i + 1})`}@@ -84,16 +85,37 @@ export default function NavBar({ onRefresh }: NavBarProps) {<div className="ml-auto flex items-center gap-1.5">{serverInfo && (- <div className="mr-2 flex items-center gap-1.5 rounded-full bg-success/10 px-2.5 py-1">- <div className="h-1.5 w-1.5 rounded-full bg-success animate-pulse" />- <span className="text-[10px] font-bold text-success uppercase tracking-wider">- Running+ <div+ className={`mr-2 flex items-center gap-1.5 rounded-full px-2.5 py-1 ${+ serverInfo.restartRequired+ ? "border border-warning/25 bg-warning/10"+ : "border border-success/20 bg-success/10"+ }`}+ title={+ serverInfo.restartRequired+ ? serverInfo.restartReasons?.join(", ") || "Restart required"+ : "Server running"+ }+ >+ <div+ className={`h-1.5 w-1.5 rounded-full ${+ serverInfo.restartRequired+ ? "bg-warning"+ : "bg-success animate-pulse"+ }`}+ />+ <span+ className={`text-[10px] font-bold uppercase tracking-wider ${+ serverInfo.restartRequired ? "text-warning" : "text-success"+ }`}+ >+ {serverInfo.restartRequired ? "Restart Required" : "Running"}</span></div>)}{onRefresh && (<button- className={`navbar-icon-btn flex h-8 w-8 cursor-pointer items-center justify-center rounded-md border border-transparent bg-transparent text-base text-text-muted transition-all duration-150 hover:border-border-subtle hover:bg-bg-elevated hover:text-text-secondary focus-visible:shadow-[0_0_0_2px_var(--primary)/25] focus-visible:outline-none ${+ className={`navbar-icon-btn flex h-8 w-8 cursor-pointer items-center justify-center rounded-sm border border-transparent bg-transparent text-base text-text-muted transition-all duration-150 hover:border-border-subtle hover:bg-bg-hover hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30 ${refreshing ? "spinning" : ""}`}onClick={handleRefresh}@@ -104,7 +126,7 @@ export default function NavBar({ onRefresh }: NavBarProps) {)}{/* Mobile menu button */}<button- className="flex h-8 w-8 cursor-pointer items-center justify-center rounded-md border border-transparent bg-transparent text-lg text-text-muted transition-all duration-150 hover:border-border-subtle hover:bg-bg-elevated hover:text-text-secondary sm:hidden"+ className="flex h-8 w-8 cursor-pointer items-center justify-center rounded-sm border border-transparent bg-transparent text-lg text-text-muted transition-all duration-150 hover:border-border-subtle hover:bg-bg-hover hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30 sm:hidden"onClick={() => setMobileMenuOpen(!mobileMenuOpen)}aria-label="Toggle menu">@@ -123,7 +145,7 @@ export default function NavBar({ onRefresh }: NavBarProps) {className={({ isActive }) =>`px-4 py-3 text-sm font-medium transition-colors duration-150 ${isActive- ? "bg-bg-elevated text-text-primary"+ ? "bg-primary/10 text-text-primary": "text-text-secondary hover:bg-bg-elevated hover:text-text-primary"}`}diff --git a/dashboard/src/components/molecules/ProfileCard.tsx b/dashboard/src/components/molecules/ProfileCard.tsxindex 0ad26ec3..3001e1ec 100644--- a/dashboard/src/components/molecules/ProfileCard.tsx+++ b/dashboard/src/components/molecules/ProfileCard.tsx@@ -11,9 +11,9 @@ interface Props {function InfoRow({ label, value }: { label: string; value: string }) {return (- <div className="flex justify-between text-xs">- <span className="text-text-muted">{label}</span>- <span className="text-text-secondary">{value}</span>+ <div className="flex items-center justify-between gap-3 text-xs">+ <span className="dashboard-section-title text-[0.68rem]">{label}</span>+ <span className="dashboard-mono text-text-secondary">{value}</span></div>);}@@ -33,7 +33,7 @@ export default function ProfileCard({return (<Card hover className="flex flex-col">{/* Header */}- <div className="flex items-center justify-between border-b border-border-subtle p-3">+ <div className="flex items-center justify-between border-b border-border-subtle bg-black/10 px-4 py-3"><span className="truncate font-medium text-text-primary">{profile.name}</span>@@ -47,13 +47,15 @@ export default function ProfileCard({</div>{/* Body */}- <div className="flex flex-1 flex-col gap-1.5 p-3">+ <div className="flex flex-1 flex-col gap-2 px-4 py-4"><InfoRow label="Size" value={sizeText} /><InfoRow label="Account" value={accountText} />{profile.useWhen && (- <div className="mt-1">- <div className="text-xs text-text-muted">Use when</div>- <div className="mt-0.5 line-clamp-2 text-xs text-text-secondary">+ <div className="mt-2 rounded-sm border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.4)] p-3">+ <div className="dashboard-section-title text-[0.68rem]">+ Use when+ </div>+ <div className="mt-1 line-clamp-2 text-xs leading-5 text-text-secondary">{profile.useWhen}</div></div>@@ -64,7 +66,7 @@ export default function ProfileCard({</div>{/* Actions */}- <div className="flex justify-end gap-2 border-t border-border-subtle p-3">+ <div className="flex justify-end gap-2 border-t border-border-subtle bg-black/10 px-4 py-3">{onDetails && (<Button size="sm" variant="ghost" onClick={onDetails}>Detailsdiff --git a/dashboard/src/components/molecules/ProfileDetailsModal.tsx b/dashboard/src/components/molecules/ProfileDetailsModal.tsxindex 2213f1c4..9ae95de6 100644--- a/dashboard/src/components/molecules/ProfileDetailsModal.tsx+++ b/dashboard/src/components/molecules/ProfileDetailsModal.tsx@@ -2,12 +2,7 @@ import { useState, useEffect, useCallback } from "react";import { Modal, Button, Input } from "../atoms";import ScreencastTile from "./ScreencastTile";import TabItem from "./TabItem";-import type {- Profile,- Instance,- InstanceTab,- Agent,-} from "../../generated/types";+import type { Profile, Instance, InstanceTab } from "../../generated/types";import * as api from "../../services/api";interface Props {@@ -40,7 +35,6 @@ export default function ProfileDetailsModal({const [name, setName] = useState("");const [useWhen, setUseWhen] = useState("");const [tabs, setTabs] = useState<InstanceTab[]>([]);- const [agents, setAgents] = useState<Agent[]>([]);const [logs] = useState(""); // TODO: fetch from /instances/{id}/logsconst [copyFeedback, setCopyFeedback] = useState("");@@ -59,20 +53,16 @@ export default function ProfileDetailsModal({if (!instance?.id) return;try {- const [allTabs, agentsData] = await Promise.all([- api.fetchAllTabs().catch(() => []),- api.fetchAgents().catch(() => []),- ]);+ const allTabs = await api.fetchAllTabs().catch(() => []);// Filter tabs for this instanceconst instanceTabs = Array.isArray(allTabs)? allTabs.filter((t) => t.instanceId === instance.id): [];setTabs(instanceTabs);- setAgents(agentsData.filter((a) => a.name === profile?.name));} catch (e) {console.error("Failed to load live data", e);}- }, [instance, profile?.name]);+ }, [instance]);useEffect(() => {if (activeTab === "live" || activeTab === "logs") {@@ -294,19 +284,11 @@ export default function ProfileDetailsModal({{/* Agents */}<div><h4 className="mb-2 text-xs font-semibold uppercase tracking-wide text-text-muted">- Agents ({agents.length})+ Agents</h4>- {agents.length === 0 ? (- <p className="text-sm text-text-muted">No agents connected.</p>- ) : (- <div className="space-y-1">- {agents.map((agent) => (- <div key={agent.id} className="text-sm text-text-secondary">- {agent.id}- </div>- ))}- </div>- )}+ <p className="text-sm text-text-muted">+ Agent registry is not exposed by the current backend.+ </p></div>{/* Logs placeholder */}diff --git a/dashboard/src/components/molecules/ServerSummary.tsx b/dashboard/src/components/molecules/ServerSummary.tsxindex 7eedc110..31f45635 100644--- a/dashboard/src/components/molecules/ServerSummary.tsx+++ b/dashboard/src/components/molecules/ServerSummary.tsx@@ -22,30 +22,31 @@ export default function ServerSummary() {return (<div className="flex flex-col gap-4">- <Card className="p-3 flex flex-col gap-3 bg-bg-surface/50">- <div className="mb-1 border-b border-border-subtle pb-2">- <h2 className="text-[10px] font-bold tracking-widest text-text-muted uppercase">+ <Card className="flex flex-col gap-4 p-4">+ <div className="border-b border-border-subtle pb-3">+ <div className="dashboard-section-label mb-2">Settings</div>+ <h2 className="text-[0.72rem] font-bold tracking-[0.18em] text-text-muted uppercase">Server Information</h2>- <p className="text-[9px] text-text-muted italic opacity-70">+ <p className="mt-1 text-[0.7rem] text-text-muted italic opacity-70">Technical details for current session</p></div>- <div className="flex flex-col gap-0.5">- <label className="text-[10px] font-semibold text-text-muted uppercase tracking-tight">+ <div className="flex flex-col gap-1">+ <label className="dashboard-section-title text-[0.68rem]">Version</label>- <div className="text-sm font-mono text-text-secondary">+ <div className="dashboard-mono text-sm text-text-secondary">{serverInfo.version}</div></div>- <div className="flex flex-col gap-0.5">- <label className="text-[10px] font-semibold text-text-muted uppercase tracking-tight">+ <div className="flex flex-col gap-1">+ <label className="dashboard-section-title text-[0.68rem]">Uptime</label>- <div className="text-sm text-text-secondary">+ <div className="dashboard-mono text-sm text-text-secondary">{uptimeStr(serverInfo.uptime)}</div></div>diff --git a/dashboard/src/components/molecules/TabItem.test.tsx b/dashboard/src/components/molecules/TabItem.test.tsxindex 93185bb6..b8c8bcda 100644--- a/dashboard/src/components/molecules/TabItem.test.tsx+++ b/dashboard/src/components/molecules/TabItem.test.tsx@@ -36,18 +36,18 @@ describe("TabItem", () => {render(<TabItem tab={mockTab} compact />);expect(screen.getByText("Example Page")).toBeInTheDocument();- // Compact wraps in a border-b div+ // Compact renders as a flat bordered rowconst titleEl = screen.getByText("Example Page");- const outerDiv = titleEl.closest(".border-b");+ const outerDiv = titleEl.closest(".rounded-sm");expect(outerDiv).toBeInTheDocument();});- it("renders card variant by default", () => {+ it("renders flat row variant by default", () => {render(<TabItem tab={mockTab} />);- // Default uses Card component which has rounded class+ // Default renders as a bordered row, not a nested card shellconst titleEl = screen.getByText("Example Page");- const card = titleEl.closest(".rounded-lg");- expect(card).toBeInTheDocument();+ const row = titleEl.closest(".rounded-md");+ expect(row).toBeInTheDocument();});});diff --git a/dashboard/src/components/molecules/TabItem.tsx b/dashboard/src/components/molecules/TabItem.tsxindex 4ea4e010..2ba9912e 100644--- a/dashboard/src/components/molecules/TabItem.tsx+++ b/dashboard/src/components/molecules/TabItem.tsx@@ -1,5 +1,4 @@import { useState } from "react";-import { Card } from "../atoms";import type { InstanceTab } from "../../generated/types";interface Props {@@ -34,10 +33,10 @@ export default function TabItem({ tab, compact }: Props) {if (compact) {return (- <div className="border-b border-border-subtle py-2">+ <div className="rounded-sm border border-border-subtle/70 bg-white/[0.02] px-3 py-2"><div className="flex items-center gap-2 overflow-hidden">{idBadge}- <div className="text-text-muted/30">|</div>+ <div className="text-text-dim">/</div><div className="truncate text-sm font-medium text-text-primary">{tab.title || "Untitled"}</div>@@ -50,10 +49,10 @@ export default function TabItem({ tab, compact }: Props) {}return (- <Card className="p-3">+ <div className="rounded-md border border-border-subtle/80 bg-white/[0.02] px-3 py-2.5 transition-colors hover:border-border-default hover:bg-white/[0.03]"><div className="flex items-center gap-2 overflow-hidden">{idBadge}- <div className="text-text-muted/30">|</div>+ <div className="text-text-dim">/</div><div className="truncate text-sm font-medium text-text-primary">{tab.title || "Untitled"}</div>@@ -61,6 +60,6 @@ export default function TabItem({ tab, compact }: Props) {<div className="mt-1 truncate text-xs text-text-muted opacity-80">{tab.url}</div>- </Card>+ </div>);}diff --git a/dashboard/src/components/molecules/TabsChart.tsx b/dashboard/src/components/molecules/TabsChart.tsxindex 9e77cf83..c08408ee 100644--- a/dashboard/src/components/molecules/TabsChart.tsx+++ b/dashboard/src/components/molecules/TabsChart.tsx@@ -24,14 +24,14 @@ interface Props {// Colors for different instancesconst COLORS = [- "#f97316", // orange (primary)- "#3b82f6", // blue- "#22c55e", // green- "#eab308", // yellow- "#ef4444", // red- "#8b5cf6", // purple- "#ec4899", // pink- "#14b8a6", // teal+ "#60a5fa",+ "#93c5fd",+ "#38bdf8",+ "#22c55e",+ "#fbbf24",+ "#ef4444",+ "#818cf8",+ "#2dd4bf",];function formatTime(timestamp: number): string {@@ -41,6 +41,14 @@ function formatTime(timestamp: number): string {});}+function formatMetricValue(value: number, maximumFractionDigits = 0): string {+ if (!Number.isFinite(value)) return "0";++ return new Intl.NumberFormat("en-US", {+ maximumFractionDigits,+ }).format(value);+}+export default function TabsChart({data,memoryData,@@ -103,7 +111,7 @@ export default function TabsChart({// Show empty state if no data or too few points to render meaningfullyif (mergedData.length < 2) {return (- <div className="flex h-50 items-center justify-center rounded-lg border border-border-subtle bg-bg-surface text-sm text-text-muted">+ <div className="dashboard-panel flex h-56 items-center justify-center text-sm text-text-muted">{mergedData.length === 0? "Collecting data...": "Waiting for more data..."}@@ -115,128 +123,164 @@ export default function TabsChart({const hasServer = serverData && serverData.length > 0;return (- <div className="rounded-lg border border-border-subtle bg-bg-surface">- <ResponsiveContainer width="100%" height={200}>- <LineChart- data={mergedData}- margin={{- top: 16,- right: hasMemory || hasServer ? 50 : 16,- bottom: 8,- left: 8,- }}- >- <XAxis- dataKey="timestamp"- tickFormatter={formatTime}- stroke="#666"- fontSize={11}- tickLine={false}- axisLine={false}- />- <YAxis- yAxisId="tabs"- stroke="#666"- fontSize={11}- allowDecimals={false}- domain={[0, "auto"]}- tickLine={false}- axisLine={false}- width={30}- />- {(hasMemory || hasServer) && (+ <div className="dashboard-panel overflow-hidden">+ <div className="flex items-center justify-between border-b border-border-subtle px-4 py-3">+ <div>+ <div className="dashboard-section-label">Monitoring</div>+ <div className="mt-1 text-sm font-semibold text-text-primary">+ Live telemetry+ </div>+ </div>+ <div className="flex flex-wrap gap-1.5">+ <span className="rounded-sm border border-border-subtle bg-white/[0.03] px-2 py-1 text-[0.68rem] font-semibold uppercase tracking-[0.08em] text-text-secondary">+ Tabs+ </span>+ {hasMemory && (+ <span className="rounded-sm border border-info/35 bg-info/10 px-2 py-1 text-[0.68rem] font-semibold uppercase tracking-[0.08em] text-info">+ Memory+ </span>+ )}+ {hasServer && (+ <span className="rounded-sm border border-primary/35 bg-primary/10 px-2 py-1 text-[0.68rem] font-semibold uppercase tracking-[0.08em] text-primary">+ Heap+ </span>+ )}+ </div>+ </div>+ <div className="px-2 py-3">+ <ResponsiveContainer width="100%" height={220}>+ <LineChart+ data={mergedData}+ margin={{+ top: 16,+ right: hasMemory || hasServer ? 50 : 16,+ bottom: 8,+ left: 8,+ }}+ >+ <XAxis+ dataKey="timestamp"+ tickFormatter={formatTime}+ stroke="#64748b"+ fontSize={11}+ tickLine={false}+ axisLine={false}+ /><YAxis- yAxisId="memory"- orientation="right"- stroke="#888"+ yAxisId="tabs"+ stroke="#64748b"fontSize={11}allowDecimals={false}domain={[0, "auto"]}tickLine={false}axisLine={false}- width={40}- tickFormatter={(v) => `${v}MB`}+ width={30}+ tickFormatter={(value) => formatMetricValue(Number(value))}/>- )}- <Tooltip- contentStyle={{- background: "#1a1a1a",- border: "1px solid #333",- borderRadius: "6px",- fontSize: "12px",- }}- labelFormatter={(label) => formatTime(label as number)}- formatter={(value, name) => {- const nameStr = String(name);- if (nameStr === "goHeapMB") {- return [`${value}MB`, "Server Heap"];- }- const isMemory = nameStr.endsWith("_mem");- const instId = isMemory ? nameStr.replace("_mem", "") : nameStr;- const inst = instances.find((i) => i.id === instId);- const label = inst?.profileName || instId;- return [- isMemory ? `${value}MB` : value,- isMemory ? `${label} (mem)` : `${label} (tabs)`,- ];- }}- />- {/* Tab count lines (solid) */}- {instances.map((inst) => (- <Line- key={inst.id}- yAxisId="tabs"- type="monotone"- dataKey={inst.id}- name={inst.id}- stroke={instanceColors[inst.id]}- strokeWidth={selectedInstanceId === inst.id ? 3 : 1.5}- strokeOpacity={- selectedInstanceId && selectedInstanceId !== inst.id ? 0.3 : 1- }- dot={false}- activeDot={{- r: 4,- onClick: () => onSelectInstance(inst.id),- style: { cursor: "pointer" },+ {(hasMemory || hasServer) && (+ <YAxis+ yAxisId="memory"+ orientation="right"+ stroke="#94a3b8"+ fontSize={11}+ allowDecimals={false}+ domain={[0, "auto"]}+ tickLine={false}+ axisLine={false}+ width={40}+ tickFormatter={(value) =>+ `${formatMetricValue(Number(value), 1)}MB`+ }+ />+ )}+ <Tooltip+ contentStyle={{+ background: "rgb(20 23 32 / 0.94)",+ border: "1px solid rgb(255 255 255 / 0.12)",+ borderRadius: "12px",+ boxShadow: "0 18px 36px rgb(0 0 0 / 0.28)",+ fontSize: "12px",+ color: "#e2e8f0",+ }}+ labelFormatter={(label) => formatTime(label as number)}+ formatter={(value, name) => {+ const numericValue = Number(value);+ const nameStr = String(name);+ if (nameStr === "goHeapMB") {+ return [+ `${formatMetricValue(numericValue, 1)}MB`,+ "Server Heap",+ ];+ }+ const isMemory = nameStr.endsWith("_mem");+ const instId = isMemory ? nameStr.replace("_mem", "") : nameStr;+ const inst = instances.find((i) => i.id === instId);+ const label = inst?.profileName || instId;+ return [+ isMemory+ ? `${formatMetricValue(numericValue, 1)}MB`+ : formatMetricValue(numericValue),+ isMemory ? `${label} (mem)` : `${label} (tabs)`,+ ];}}/>- ))}- {/* Memory lines (dashed) */}- {hasMemory &&- instances.map((inst) => (+ {/* Tab count lines (solid) */}+ {instances.map((inst) => (<Line- key={`${inst.id}_mem`}- yAxisId="memory"+ key={inst.id}+ yAxisId="tabs"type="monotone"- dataKey={`${inst.id}_mem`}- name={`${inst.id}_mem`}+ dataKey={inst.id}+ name={inst.id}stroke={instanceColors[inst.id]}- strokeWidth={selectedInstanceId === inst.id ? 2 : 1}+ strokeWidth={selectedInstanceId === inst.id ? 3 : 1.5}strokeOpacity={- selectedInstanceId && selectedInstanceId !== inst.id- ? 0.2- : 0.6+ selectedInstanceId && selectedInstanceId !== inst.id ? 0.3 : 1}- strokeDasharray="4 2"dot={false}+ activeDot={{+ r: 4,+ onClick: () => onSelectInstance(inst.id),+ style: { cursor: "pointer" },+ }}/>))}- {/* Server heap line (dotted, gray) */}- {hasServer && (- <Line- yAxisId="memory"- type="monotone"- dataKey="goHeapMB"- name="goHeapMB"- stroke="#888"- strokeWidth={1.5}- strokeDasharray="2 2"- dot={false}- />- )}- </LineChart>- </ResponsiveContainer>+ {/* Memory lines (dashed) */}+ {hasMemory &&+ instances.map((inst) => (+ <Line+ key={`${inst.id}_mem`}+ yAxisId="memory"+ type="monotone"+ dataKey={`${inst.id}_mem`}+ name={`${inst.id}_mem`}+ stroke={instanceColors[inst.id]}+ strokeWidth={selectedInstanceId === inst.id ? 2 : 1}+ strokeOpacity={+ selectedInstanceId && selectedInstanceId !== inst.id+ ? 0.2+ : 0.6+ }+ strokeDasharray="4 2"+ dot={false}+ />+ ))}+ {/* Server heap line (dotted, gray) */}+ {hasServer && (+ <Line+ yAxisId="memory"+ type="monotone"+ dataKey="goHeapMB"+ name="goHeapMB"+ stroke="#94a3b8"+ strokeWidth={1.5}+ strokeDasharray="2 2"+ dot={false}+ />+ )}+ </LineChart>+ </ResponsiveContainer>+ </div></div>);}diff --git a/dashboard/src/components/molecules/TabsChart2.test.tsx b/dashboard/src/components/molecules/TabsChart2.test.tsxnew file mode 100644index 00000000..1e8f0d4e--- /dev/null+++ b/dashboard/src/components/molecules/TabsChart2.test.tsx@@ -0,0 +1,45 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import TabsChart2 from "./TabsChart2";+import type { TabDataPoint } from "../../stores/useAppStore";++const mockInstances = [+ { id: "inst_1", profileName: "profile-1" },+ { id: "inst_2", profileName: "profile-2" },+];++const mockData: TabDataPoint[] = [+ { timestamp: Date.now() - 60000, inst_1: 3, inst_2: 5 },+ { timestamp: Date.now() - 30000, inst_1: 4, inst_2: 6 },+ { timestamp: Date.now(), inst_1: 5, inst_2: 4 },+];++describe("TabsChart2", () => {+ it('shows "Collecting data..." when no data exists', () => {+ render(+ <TabsChart2+ data={[]}+ instances={[]}+ selectedInstanceId={null}+ onSelectInstance={() => {}}+ />,+ );++ expect(screen.getByText("Collecting data...")).toBeInTheDocument();+ });++ it("renders the terminal chart shell when data exists", () => {+ render(+ <TabsChart2+ data={mockData}+ instances={mockInstances}+ selectedInstanceId={null}+ onSelectInstance={() => {}}+ />,+ );++ expect(screen.getByTestId("terminal-tabs-chart")).toBeInTheDocument();+ expect(screen.getByText("Terminal telemetry")).toBeInTheDocument();+ expect(screen.getByText("Tabs")).toBeInTheDocument();+ });+});diff --git a/dashboard/src/components/molecules/TabsChart2.tsx b/dashboard/src/components/molecules/TabsChart2.tsxnew file mode 100644index 00000000..112bbfec--- /dev/null+++ b/dashboard/src/components/molecules/TabsChart2.tsx@@ -0,0 +1,370 @@+import { useMemo } from "react";+import type {+ MemoryDataPoint,+ ServerDataPoint,+ TabDataPoint,+} from "../../stores/useAppStore";++interface Props {+ data: TabDataPoint[];+ memoryData?: MemoryDataPoint[];+ serverData?: ServerDataPoint[];+ instances: { id: string; profileName: string }[];+ selectedInstanceId: string | null;+ onSelectInstance: (id: string) => void;+}++interface SeriesDefinition {+ id: string;+ key: string;+ label: string;+ color: string;+ selectable: boolean;+ selected: boolean;+}++interface TrackDefinition {+ id: string;+ title: string;+ suffix: string;+ rows: number;+ series: SeriesDefinition[];+ data: Record<string, number>[];+}++const COLORS = [+ "#60a5fa",+ "#93c5fd",+ "#38bdf8",+ "#22c55e",+ "#fbbf24",+ "#ef4444",+ "#818cf8",+ "#2dd4bf",+];++function formatTime(timestamp: number): string {+ return new Date(timestamp).toLocaleTimeString("en-GB", {+ hour: "2-digit",+ minute: "2-digit",+ });+}++function formatMetricValue(value: number, maximumFractionDigits = 0): string {+ if (!Number.isFinite(value)) return "0";++ return new Intl.NumberFormat("en-US", {+ maximumFractionDigits,+ }).format(value);+}++function formatValue(value: number, suffix: string): string {+ return suffix+ ? `${formatMetricValue(value, 1)}${suffix}`+ : formatMetricValue(value);+}++function clampCellCount(value: number, maxValue: number, rows: number): number {+ if (value <= 0 || maxValue <= 0) return 0;+ return Math.max(1, Math.min(rows, Math.round((value / maxValue) * rows)));+}++function TerminalTrack({+ track,+ selectedInstanceId,+ onSelectInstance,+}: {+ track: TrackDefinition;+ selectedInstanceId: string | null;+ onSelectInstance: (id: string) => void;+}) {+ const cell = 4;+ const gap = 3;+ const rowStride = cell + gap;+ const colInset = 3;+ const topInset = 10;+ const bottomInset = 20;+ const rightInset = 8;+ const columns = track.data.length;+ const seriesCount = Math.max(track.series.length, 1);+ const groupWidth = Math.max(12, seriesCount * (cell + 2) + 8);+ const width = colInset + columns * groupWidth + rightInset;+ const height = topInset + track.rows * rowStride + bottomInset;+ const maxValue = Math.max(+ 1,+ ...track.data.flatMap((point) =>+ track.series.map((series) => point[series.key] ?? 0),+ ),+ );+ const labelStep = Math.max(1, Math.ceil(columns / 6));++ return (+ <div className="rounded-md border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.55)] px-3 py-3">+ <div className="mb-3 flex items-center justify-between">+ <div className="dashboard-section-title">{track.title}</div>+ <div className="dashboard-mono text-[0.68rem] text-text-muted">+ max {formatValue(maxValue, track.suffix)}+ </div>+ </div>++ <div className="overflow-x-auto">+ <svg+ width={width}+ height={height}+ viewBox={`0 0 ${width} ${height}`}+ className="block min-w-full"+ role="img"+ aria-label={`${track.title} terminal chart`}+ >+ {track.data.map((point, pointIndex) => {+ const groupX = colInset + pointIndex * groupWidth;++ return track.series.map((series, seriesIndex) => {+ const value = point[series.key] ?? 0;+ const lit = clampCellCount(value, maxValue, track.rows);+ const x = groupX + seriesIndex * (cell + 2);+ const dimmed =+ selectedInstanceId &&+ series.selectable &&+ selectedInstanceId !== series.id;++ return (+ <g key={`${track.id}-${series.key}-${point.timestamp}`}>+ {Array.from({ length: track.rows }).map((_, rowIndex) => {+ const y =+ topInset + (track.rows - 1 - rowIndex) * rowStride;+ const active = rowIndex < lit;++ return (+ <rect+ key={`${track.id}-${series.key}-${pointIndex}-${rowIndex}`}+ x={x}+ y={y}+ width={cell}+ height={cell}+ rx={0.8}+ fill={active ? series.color : "rgb(255 255 255 / 0.07)"}+ opacity={active ? (dimmed ? 0.3 : 0.92) : 1}+ >+ <title>+ {`${series.label} ${formatValue(value, track.suffix)} at ${formatTime(point.timestamp)}`}+ </title>+ </rect>+ );+ })}+ </g>+ );+ });+ })}++ {track.data.map(+ (point, pointIndex) =>+ (pointIndex % labelStep === 0 || pointIndex === columns - 1) && (+ <text+ key={`${track.id}-label-${point.timestamp}`}+ x={colInset + pointIndex * groupWidth}+ y={height - 4}+ fill="#64748b"+ fontSize="10"+ fontFamily="JetBrains Mono, monospace"+ >+ {formatTime(point.timestamp)}+ </text>+ ),+ )}+ </svg>+ </div>++ <div className="mt-3 flex flex-wrap gap-1.5">+ {track.series.map((series) => {+ const active = selectedInstanceId === series.id;+ return (+ <button+ key={`${track.id}-${series.key}-legend`}+ type="button"+ onClick={() => series.selectable && onSelectInstance(series.id)}+ className={`inline-flex items-center gap-2 rounded-sm border px-2 py-1 text-[0.68rem] font-semibold uppercase tracking-[0.08em] transition-all ${+ series.selectable+ ? active+ ? "border-primary/35 bg-primary/10 text-primary"+ : "border-border-subtle bg-white/[0.03] text-text-secondary hover:border-border-default hover:text-text-primary"+ : "cursor-default border-border-subtle bg-white/[0.03] text-text-secondary"+ }`}+ >+ <span+ className="h-2 w-2 rounded-[2px]"+ style={{ backgroundColor: series.color }}+ aria-hidden="true"+ />+ {series.label}+ </button>+ );+ })}+ </div>+ </div>+ );+}++export default function TabsChart2({+ data,+ memoryData,+ serverData,+ instances,+ selectedInstanceId,+ onSelectInstance,+}: Props) {+ const mergedData = useMemo(() => {+ const memByTime = new Map((memoryData || []).map((m) => [m.timestamp, m]));+ const serverByTime = new Map(+ (serverData || []).map((s) => [s.timestamp, s]),+ );++ const baseData =+ data.length > 0+ ? data+ : (serverData || []).map((s) => ({ timestamp: s.timestamp }));++ return baseData.map((d) => {+ const merged: Record<string, number> = { timestamp: d.timestamp };++ for (const [key, val] of Object.entries(d)) {+ if (key !== "timestamp") {+ merged[key] = val as number;+ }+ }++ const mem = memByTime.get(d.timestamp);+ if (mem) {+ for (const [key, val] of Object.entries(mem)) {+ if (key !== "timestamp") {+ merged[`${key}_mem`] = val;+ }+ }+ }++ const srv = serverByTime.get(d.timestamp);+ if (srv) {+ merged.goHeapMB = srv.goHeapMB;+ }++ return merged;+ });+ }, [data, memoryData, serverData]);++ const hasMemory = Boolean(memoryData && memoryData.length > 0);+ const hasServer = Boolean(serverData && serverData.length > 0);++ const tracks = useMemo<TrackDefinition[]>(() => {+ const tabSeries: SeriesDefinition[] = instances.map((instance, index) => ({+ id: instance.id,+ key: instance.id,+ label: instance.profileName,+ color: COLORS[index % COLORS.length],+ selectable: true,+ selected: selectedInstanceId === instance.id,+ }));++ const memorySeries: SeriesDefinition[] = hasMemory+ ? instances.map((instance, index) => ({+ id: instance.id,+ key: `${instance.id}_mem`,+ label: instance.profileName,+ color: COLORS[index % COLORS.length],+ selectable: true,+ selected: selectedInstanceId === instance.id,+ }))+ : [];++ const nextTracks: TrackDefinition[] = [];++ if (tabSeries.length > 0) {+ nextTracks.push({+ id: "tabs",+ title: "Tabs",+ suffix: "",+ rows: 10,+ series: tabSeries,+ data: mergedData,+ });+ }++ if (memorySeries.length > 0) {+ nextTracks.push({+ id: "memory",+ title: "Memory",+ suffix: "MB",+ rows: 8,+ series: memorySeries,+ data: mergedData,+ });+ }++ if (hasServer) {+ nextTracks.push({+ id: "server",+ title: "Heap",+ suffix: "MB",+ rows: 6,+ series: [+ {+ id: "goHeapMB",+ key: "goHeapMB",+ label: "Server Heap",+ color: "#cbd5e1",+ selectable: false,+ selected: false,+ },+ ],+ data: mergedData,+ });+ }++ return nextTracks;+ }, [hasMemory, hasServer, instances, mergedData, selectedInstanceId]);++ if (mergedData.length < 2) {+ return (+ <div className="dashboard-panel flex h-56 items-center justify-center text-sm text-text-muted">+ {mergedData.length === 0+ ? "Collecting data..."+ : "Waiting for more data..."}+ </div>+ );+ }++ return (+ <div+ className="dashboard-panel overflow-hidden"+ data-testid="terminal-tabs-chart"+ >+ <div className="flex items-center justify-between border-b border-border-subtle px-4 py-3">+ <div>+ <div className="dashboard-section-label">Monitoring</div>+ <div className="mt-1 text-sm font-semibold text-text-primary">+ Terminal telemetry+ </div>+ </div>+ <div className="dashboard-mono text-[0.72rem] uppercase tracking-[0.12em] text-text-muted">+ {mergedData.length} samples+ </div>+ </div>++ <div className="flex flex-col gap-3 p-3">+ {tracks.length === 0 ? (+ <div className="rounded-md border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.55)] px-4 py-6 text-sm text-text-muted">+ No terminal tracks available.+ </div>+ ) : (+ tracks.map((track) => (+ <TerminalTrack+ key={track.id}+ track={track}+ selectedInstanceId={selectedInstanceId}+ onSelectInstance={onSelectInstance}+ />+ ))+ )}+ </div>+ </div>+ );+}diff --git a/dashboard/src/components/molecules/index.ts b/dashboard/src/components/molecules/index.tsindex dbdc66e9..d0a012d4 100644--- a/dashboard/src/components/molecules/index.ts+++ b/dashboard/src/components/molecules/index.ts@@ -8,4 +8,5 @@ export { default as TabItem } from "./TabItem";export { default as AgentItem } from "./AgentItem";export { default as ActivityLine } from "./ActivityLine";export { default as TabsChart } from "./TabsChart";+export { default as TabsChart2 } from "./TabsChart2";export { default as ServerSummary } from "./ServerSummary";diff --git a/dashboard/src/index.css b/dashboard/src/index.cssindex 1c2f5af8..6b71a104 100644--- a/dashboard/src/index.css+++ b/dashboard/src/index.css@@ -1,94 +1,222 @@+@import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap");@import "tailwindcss";@theme {- --font-sans: "Geist", ui-sans-serif, system-ui, sans-serif;- --font-mono: "Geist Mono", ui-monospace, monospace;+ --font-sans:+ "Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",+ sans-serif;+ --font-mono:+ "JetBrains Mono", "Fira Code", "Cascadia Code", ui-monospace, monospace;- /* Colors - matching Poseidon dark theme */- --color-bg-app: #0a0a0a;- --color-bg-surface: #111111;- --color-bg-elevated: #1a1a1a;- --color-bg-hover: #222222;-- --color-border-subtle: #222222;- --color-border-default: #333333;-- --color-text-primary: #fafafa;- --color-text-secondary: #a1a1a1;- --color-text-muted: #666666;-- --color-primary: #f97316; /* Orange - Pinchtab brand */- --color-primary-hover: #fb923c;+ --color-bg-app: #0f1117;+ --color-bg-surface: #1a1d27;+ --color-bg-elevated: #222633;+ --color-bg-hover: #222633;+ --color-border-subtle: #ffffff1a;+ --color-border-default: #3b82f62e;+ --color-text-primary: #e2e8f0;+ --color-text-secondary: #94a3b8;+ --color-text-muted: #64748b;+ --color-primary: #60a5fa;+ --color-primary-hover: #93c5fd;--color-success: #22c55e;- --color-warning: #eab308;+ --color-warning: #fbbf24;--color-destructive: #ef4444;- --color-info: #3b82f6;+ --color-info: #93c5fd;- /* Spacing */--spacing-page: 1rem;}-/* Geist font - load via CDN */-@font-face {- font-family: "Geist";- src: url("https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/geist-sans/Geist-Regular.woff2")- format("woff2");- font-weight: 400;- font-style: normal;- font-display: swap;-}--@font-face {- font-family: "Geist";- src: url("https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/geist-sans/Geist-Medium.woff2")- format("woff2");- font-weight: 500;- font-style: normal;- font-display: swap;-}--@font-face {- font-family: "Geist";- src: url("https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/geist-sans/Geist-SemiBold.woff2")- format("woff2");- font-weight: 600;- font-style: normal;- font-display: swap;+:root,+html[data-site-mode="agent"] {+ --brand-bg-rgb: 15 17 23;+ --brand-surface-rgb: 26 29 39;+ --brand-surface-hover-rgb: 34 38 51;+ --brand-surface-code-rgb: 20 23 32;+ --brand-border-rgb: 59 130 246;+ --brand-border-subtle-rgb: 255 255 255;+ --brand-text-rgb: 226 232 240;+ --brand-text-muted-rgb: 148 163 184;+ --brand-text-dim-rgb: 100 116 139;+ --brand-accent-rgb: 96 165 250;+ --brand-accent-light-rgb: 147 197 253;+ --brand-accent-dark-rgb: 37 99 235;+ --brand-accent-contrast-rgb: 255 255 255;+ --theme-glow-rgb: 96 165 250;+ --selection-bg-rgb: 59 130 246;+ --panel-shadow:+ 0 0 0 1px rgb(var(--brand-border-rgb) / 0.03), 0 24px 50px rgb(0 0 0 / 0.26);+ color-scheme: dark;}-@font-face {- font-family: "Geist Mono";- src: url("https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/geist-mono/GeistMono-Regular.woff2")- format("woff2");- font-weight: 400;- font-style: normal;- font-display: swap;+* {+ box-sizing: border-box;}html {- color-scheme: dark;+ scroll-behavior: smooth;}body {margin: 0;+ min-height: 100vh;+ background-color: rgb(var(--brand-bg-rgb));+ background-image: none;+ color: rgb(var(--brand-text-rgb));font-family: var(--font-sans);- background: var(--color-bg-app);- color: var(--color-text-primary);+ line-height: 1.6;-webkit-font-smoothing: antialiased;+ -moz-osx-font-smoothing: grayscale;+}++#root {+ min-height: 100vh;+}++::selection {+ background-color: rgb(var(--selection-bg-rgb) / 0.95);+ color: #000;+}++::-moz-selection {+ background-color: rgb(var(--selection-bg-rgb) / 0.95);+ color: #000;+}++a {+ color: inherit;+ text-decoration: none;+ transition: color 0.2s ease;+}++a:not([class]) {+ color: rgb(var(--brand-accent-rgb));+}++a:not([class]):hover {+ color: rgb(var(--brand-accent-light-rgb));+}++h1,+h2,+h3,+h4,+h5,+h6 {+ font-family: var(--font-sans);+ font-weight: 700;+ letter-spacing: -0.02em;+ line-height: 1.1;+}++code {+ border-radius: 4px;+ background-color: rgb(var(--brand-accent-rgb) / 0.1);+ color: rgb(var(--brand-accent-light-rgb));+ font-family: var(--font-mono);+ font-size: 0.85em;+ padding: 2px 6px;+}++pre {+ overflow-x: auto;+ border: 1px solid rgb(var(--brand-border-subtle-rgb) / 0.12);+ border-radius: 16px;+ background-color: rgb(var(--brand-surface-code-rgb));+ color: rgb(var(--brand-text-rgb));+ padding: 1.5rem;+ font-size: 0.85rem;+ line-height: 1.8;}-/* Scrollbar */::-webkit-scrollbar {width: 8px;height: 8px;}+::-webkit-scrollbar-track {background: transparent;}+::-webkit-scrollbar-thumb {- background: var(--color-border-default);- border-radius: 4px;+ border-radius: 9999px;+ background: rgb(var(--brand-surface-hover-rgb));}+::-webkit-scrollbar-thumb:hover {- background: var(--color-text-muted);+ background: rgb(var(--brand-text-dim-rgb) / 0.9);+}++@layer utilities {+ .dashboard-shell {+ background-color: rgb(var(--brand-bg-rgb));+ color: rgb(var(--brand-text-rgb));+ }++ .dashboard-panel {+ border: 1px solid rgb(var(--brand-border-subtle-rgb) / 0.1);+ border-radius: 16px;+ background: linear-gradient(+ 180deg,+ rgb(var(--brand-surface-rgb) / 0.98),+ rgb(var(--brand-surface-rgb) / 0.9)+ );+ box-shadow: var(--panel-shadow);+ }++ .dashboard-panel-hover {+ transition:+ background-color 0.18s ease,+ border-color 0.18s ease,+ transform 0.18s ease,+ box-shadow 0.18s ease;+ }++ .dashboard-panel-hover:hover {+ border-color: rgb(var(--brand-border-rgb) / 0.18);+ background: rgb(var(--brand-surface-hover-rgb));+ box-shadow:+ 0 0 0 1px rgb(var(--brand-border-rgb) / 0.06),+ 0 24px 50px rgb(0 0 0 / 0.3);+ }++ .dashboard-panel-selected {+ border-color: rgb(var(--brand-border-rgb) / 0.32);+ background: linear-gradient(+ 180deg,+ rgb(var(--brand-accent-rgb) / 0.12),+ rgb(var(--brand-surface-hover-rgb) / 0.96)+ );+ box-shadow:+ 0 0 0 1px rgb(var(--brand-border-rgb) / 0.08),+ 0 0 36px rgb(var(--brand-accent-rgb) / 0.08);+ }++ .dashboard-section-label {+ color: rgb(var(--brand-accent-rgb));+ font-size: 0.72rem;+ font-weight: 600;+ letter-spacing: 0.14em;+ text-transform: uppercase;+ }++ .dashboard-section-title {+ color: rgb(var(--brand-text-dim-rgb));+ font-size: 0.72rem;+ font-weight: 600;+ letter-spacing: 0.14em;+ text-transform: uppercase;+ }++ .dashboard-mono {+ font-family: var(--font-mono);+ }++ .dashboard-grid {+ background-image:+ linear-gradient(rgb(255 255 255 / 0.025) 1px, transparent 1px),+ linear-gradient(90deg, rgb(255 255 255 / 0.025) 1px, transparent 1px);+ background-position: center;+ background-size: 18px 18px;+ }}diff --git a/dashboard/src/pages/AgentsPage.tsx b/dashboard/src/pages/AgentsPage.tsxindex 6c7890ee..6bc68130 100644--- a/dashboard/src/pages/AgentsPage.tsx+++ b/dashboard/src/pages/AgentsPage.tsx@@ -1,8 +1,6 @@-import { useEffect } from "react";import { useAppStore } from "../stores/useAppStore";import { EmptyState } from "../components/atoms";import { AgentItem, ActivityLine } from "../components/molecules";-import * as api from "../services/api";const filters = [{ key: "all", label: "All" },@@ -17,29 +15,10 @@ export default function AgentsPage() {selectedAgentId,events,eventFilter,- setAgents,setSelectedAgentId,setEventFilter,} = useAppStore();- const loadAgents = async () => {- try {- const data = await api.fetchAgents();- setAgents(data);- } catch (e) {- console.error("Failed to load agents", e);- }- };-- // Agents are loaded via SSE init event — only load if empty- // Load once on mount if empty — intentionally omitting deps to avoid refetch loops- useEffect(() => {- if (agents.length === 0) {- loadAgents();- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-const filteredEvents = events.filter((e) => {if (selectedAgentId && e.agentId !== selectedAgentId) return false;if (eventFilter === "all") return true;@@ -79,27 +58,24 @@ export default function AgentsPage() {</div>{/* Desktop: Agents sidebar */}- <div className="hidden w-64 shrink-0 border-r border-border-subtle bg-bg-surface sm:block">- <div className="border-b border-border-subtle p-3">+ <div className="hidden w-72 shrink-0 border-r border-border-subtle bg-bg-surface sm:block">+ <div className="border-b border-border-subtle px-4 py-3">+ <div className="dashboard-section-label mb-1">Agents</div><h2 className="text-sm font-semibold text-text-secondary">Agents</h2></div><div className="p-2">{agents.length === 0 ? (<div className="py-8 text-center text-sm text-text-muted"><div className="mb-2 text-2xl">🦀</div>- No agents connected yet- <div className="mt-1 text-xs">- Make an API call with{" "}- <code className="text-primary">X-Agent-Id</code> header- </div>+ No agent activity observed yet</div>) : (<div className="flex flex-col gap-1"><button- className={`rounded-lg px-3 py-2 text-left text-sm transition-all ${+ className={`rounded-sm px-3 py-2 text-left text-sm transition-all ${!selectedAgentId- ? "bg-primary/10 text-primary"- : "text-text-muted hover:bg-bg-elevated"+ ? "border border-primary/30 bg-primary/10 text-primary"+ : "border border-transparent text-text-muted hover:bg-bg-elevated"}`}onClick={() => setSelectedAgentId(null)}>@@ -120,18 +96,21 @@ export default function AgentsPage() {{/* Activity feed */}<div className="flex flex-1 flex-col overflow-hidden">- <div className="flex items-center justify-between border-b border-border-subtle bg-bg-surface px-4 py-2">- <h2 className="text-sm font-semibold text-text-secondary">- Activity Feed- </h2>+ <div className="flex items-center justify-between border-b border-border-subtle bg-bg-surface px-4 py-3">+ <div>+ <div className="dashboard-section-label mb-1">Feed</div>+ <h2 className="text-sm font-semibold text-text-secondary">+ Activity Feed+ </h2>+ </div><div className="flex gap-1">{filters.map((f) => (<buttonkey={f.key}- className={`rounded px-2 py-1 text-xs font-medium transition-all ${+ className={`rounded-sm border px-2.5 py-1.5 text-xs font-semibold uppercase tracking-[0.08em] transition-all ${eventFilter === f.key- ? "bg-primary/10 text-primary"- : "text-text-muted hover:bg-bg-elevated hover:text-text-secondary"+ ? "border-primary/30 bg-primary/10 text-primary"+ : "border-transparent text-text-muted hover:border-border-subtle hover:bg-bg-elevated hover:text-text-secondary"}`}onClick={() => setEventFilter(f.key)}>diff --git a/dashboard/src/pages/MonitoringPage.tsx b/dashboard/src/pages/MonitoringPage.tsxindex e76e05ec..3143b7a4 100644--- a/dashboard/src/pages/MonitoringPage.tsx+++ b/dashboard/src/pages/MonitoringPage.tsx@@ -210,8 +210,9 @@ export default function MonitoringPage() {{instances.length > 0 && (<div className="flex flex-1 gap-4 overflow-hidden">{/* Instance list */}- <div className="w-64 shrink-0 overflow-auto rounded-lg border border-border-subtle bg-bg-surface">- <div className="border-b border-border-subtle p-3">+ <div className="dashboard-panel w-64 shrink-0 overflow-auto">+ <div className="border-b border-border-subtle px-4 py-3">+ <div className="dashboard-section-label mb-1">Monitoring</div><h3 className="text-sm font-semibold text-text-secondary">Instances ({instances.length})</h3>@@ -233,15 +234,18 @@ export default function MonitoringPage() {</div>{/* Selected instance details */}- <div className="flex flex-1 flex-col overflow-hidden rounded-lg border border-border-subtle bg-bg-surface">+ <div className="dashboard-panel flex flex-1 flex-col overflow-hidden">{selectedInstance ? (<>- <div className="flex items-center justify-between border-b border-border-subtle p-3">+ <div className="flex items-center justify-between border-b border-border-subtle px-4 py-3"><div>+ <div className="dashboard-section-title mb-1">+ Active instance+ </div><h3 className="text-sm font-semibold text-text-primary">{selectedInstance.profileName}</h3>- <div className="text-xs text-text-muted">+ <div className="dashboard-mono text-xs text-text-muted">Port {selectedInstance.port} ·{" "}{selectedInstance.headless ? "Headless" : "Headed"}</div>diff --git a/dashboard/src/pages/ProfilesPage.tsx b/dashboard/src/pages/ProfilesPage.tsxindex 705ce1d5..d1615708 100644--- a/dashboard/src/pages/ProfilesPage.tsx+++ b/dashboard/src/pages/ProfilesPage.tsx@@ -3,7 +3,7 @@ import { useAppStore } from "../stores/useAppStore";import { Toolbar, EmptyState, Button, Modal, Input } from "../components/atoms";import { ProfileCard, ProfileDetailsModal } from "../components/molecules";import * as api from "../services/api";-import type { Profile } from "../generated/types";+import type { LaunchInstanceRequest, Profile } from "../generated/types";export default function ProfilesPage() {const {@@ -24,7 +24,7 @@ export default function ProfilesPage() {const [createSource, setCreateSource] = useState("");// Launch form- const [launchPort, setLaunchPort] = useState("9868");+ const [launchPort, setLaunchPort] = useState("");const [launchHeadless, setLaunchHeadless] = useState(false);const [launchError, setLaunchError] = useState("");const [launchLoading, setLaunchLoading] = useState(false);@@ -72,16 +72,16 @@ export default function ProfilesPage() {setLaunchError("");setLaunchLoading(true);try {- const payload = {+ const payload: LaunchInstanceRequest = {name: showLaunch,- port: launchPort || undefined,- mode: launchHeadless ? "" : "headed",+ port: launchPort.trim() || undefined,+ mode: launchHeadless ? undefined : "headed",};console.log("Launching instance:", payload);const result = await api.launchInstance(payload);console.log("Launch result:", result);setShowLaunch(null);- setLaunchPort("9868");+ setLaunchPort("");setLaunchHeadless(false);// Refresh instances listconst updated = await api.fetchInstances();@@ -137,9 +137,13 @@ export default function ProfilesPage() {if (!showLaunch) return "";const profile = profiles.find((p) => p.name === showLaunch);const profileId = profile?.id || showLaunch;- const mode = launchHeadless ? "headless" : "headed";- const port = launchPort || "auto";- return `curl -X POST http://localhost:9867/instances/start -H "Content-Type: application/json" -d '{"profileId":"${profileId}","mode":"${mode}","port":"${port}"}'`;+ const payload: LaunchInstanceRequest = {+ profileId,+ mode: launchHeadless ? undefined : "headed",+ port: launchPort.trim() || undefined,+ };++ return `curl -X POST http://localhost:9867/instances/start -H "Content-Type: application/json" -d '${JSON.stringify(payload)}'`;}, [showLaunch, launchHeadless, launchPort, profiles]);const handleCopyCommand = async () => {@@ -159,13 +163,13 @@ export default function ProfilesPage() {<div className="flex h-full flex-col"><Toolbaractions={[+ { key: "refresh", label: "Refresh", onClick: loadProfiles },{key: "new",- label: "+ New Profile",+ label: "New Profile",onClick: () => setShowCreate(true),variant: "primary",},- { key: "refresh", label: "Refresh", onClick: loadProfiles },]}/>@@ -178,10 +182,10 @@ export default function ProfilesPage() {) : profiles.length === 0 ? (<EmptyStatetitle="No profiles yet"- description="Click + New Profile to create one"+ description="Click New Profile to create one"action={<Button variant="primary" onClick={() => setShowCreate(true)}>- + New Profile+ New Profile</Button>}/>@@ -283,10 +287,14 @@ export default function ProfilesPage() {)}<Inputlabel="Port"- placeholder="e.g. 9868"+ placeholder="Auto-select from configured range"value={launchPort}onChange={(e) => setLaunchPort(e.target.value)}/>+ <p className="-mt-2 text-xs text-text-muted">+ Leave blank to auto-select a free port from the configured instance+ port range.+ </p><label className="flex items-center gap-2 text-sm text-text-secondary"><inputtype="checkbox"diff --git a/dashboard/src/pages/SettingsPage.tsx b/dashboard/src/pages/SettingsPage.tsxindex f4b80d9a..60b940a9 100644--- a/dashboard/src/pages/SettingsPage.tsx+++ b/dashboard/src/pages/SettingsPage.tsx@@ -1,292 +1,1048 @@-import { useState, useMemo } from "react";+import { useEffect, useMemo, useState } from "react";import { useAppStore } from "../stores/useAppStore";import { Button, Card } from "../components/atoms";-import { ServerSummary } from "../components/molecules";-import type { Settings } from "../types";+import * as api from "../services/api";+import type {+ BackendConfig,+ BackendConfigState,+ LocalDashboardSettings,+} from "../types";++type SectionId =+ | "dashboard"+ | "defaults"+ | "orchestration"+ | "security"+ | "profiles"+ | "network"+ | "browser"+ | "timeouts";++const sections: Array<{+ id: SectionId;+ label: string;+ description: string;+}> = [+ {+ id: "dashboard",+ label: "Dashboard",+ description: "Local monitoring and screencast preferences.",+ },+ {+ id: "defaults",+ label: "Instance Defaults",+ description: "How new managed browser instances launch.",+ },+ {+ id: "orchestration",+ label: "Orchestration",+ description: "Routing strategy, port range, and allocation policy.",+ },+ {+ id: "security",+ label: "Security",+ description: "Sensitive endpoint gates and access controls.",+ },+ {+ id: "profiles",+ label: "Profiles",+ description: "Shared profile storage and default profile behavior.",+ },+ {+ id: "network",+ label: "Network & Attach",+ description: "Server binding, auth, and attach policy.",+ },+ {+ id: "browser",+ label: "Browser Runtime",+ description: "Chrome binary, version, flags, and extensions.",+ },+ {+ id: "timeouts",+ label: "Timeouts",+ description: "Action, navigation, shutdown, and wait timing.",+ },+];++const fieldClass =+ "w-full rounded-sm border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.72)] px-3 py-2 text-sm text-text-primary placeholder:text-text-muted transition-all duration-150 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20";++const selectClass =+ "rounded-sm border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.72)] px-3 py-2 text-sm text-text-primary transition-all duration-150 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20";++function csvToList(value: string): string[] {+ return value+ .split(",")+ .map((item) => item.trim())+ .filter(Boolean);+}++function listToCsv(value: string[]): string {+ return value.join(", ");+}++function SectionCard({+ title,+ description,+ children,+}: {+ title: string;+ description: string;+ children: React.ReactNode;+}) {+ return (+ <Card className="p-5">+ <div className="mb-5 border-b border-border-subtle pb-4">+ <div className="dashboard-section-label mb-2">Settings</div>+ <h3 className="text-lg font-semibold text-text-primary">{title}</h3>+ <p className="mt-2 max-w-2xl text-sm leading-6 text-text-muted">+ {description}+ </p>+ </div>+ <div className="space-y-4">{children}</div>+ </Card>+ );+}++function SettingRow({+ label,+ description,+ children,+}: {+ label: string;+ description: string;+ children: React.ReactNode;+}) {+ return (+ <div className="flex flex-col gap-3 rounded-sm border border-border-subtle bg-black/10 p-4 lg:flex-row lg:items-center lg:justify-between">+ <div className="max-w-xl">+ <div className="text-sm font-medium text-text-primary">{label}</div>+ <p className="mt-1 text-xs leading-5 text-text-muted">{description}</p>+ </div>+ <div className="w-full max-w-md">{children}</div>+ </div>+ );+}export default function SettingsPage() {- const {- settings,- setSettings,- // serverInfo- } = useAppStore();- const [local, setLocal] = useState<Settings>(settings);-- // Check if settings have changed- const hasChanges = useMemo(- () => JSON.stringify(local) !== JSON.stringify(settings),- [local, settings],+ const { settings, setSettings, serverInfo, setServerInfo } = useAppStore();+ const [activeSection, setActiveSection] = useState<SectionId>("dashboard");+ const [localSettings, setLocalSettings] =+ useState<LocalDashboardSettings>(settings);+ const [backendState, setBackendState] = useState<BackendConfigState | null>(+ null,);+ const [backendConfig, setBackendConfig] = useState<BackendConfig | null>(+ null,+ );+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState("");+ const [notice, setNotice] = useState("");++ useEffect(() => {+ setLocalSettings(settings);+ }, [settings]);++ useEffect(() => {+ const load = async () => {+ setLoading(true);+ setError("");+ try {+ const [configState, health] = await Promise.all([+ api.fetchBackendConfig(),+ api.fetchHealth().catch(() => null),+ ]);+ setBackendState(configState);+ setBackendConfig(configState.config);+ if (health) {+ setServerInfo(health);+ }+ } catch (e) {+ const message =+ e instanceof Error ? e.message : "Failed to load settings";+ setError(message);+ } finally {+ setLoading(false);+ }+ };+ load();+ }, [setServerInfo]);++ const hasDashboardChanges = useMemo(+ () => JSON.stringify(localSettings) !== JSON.stringify(settings),+ [localSettings, settings],+ );++ const hasBackendChanges = useMemo(+ () =>+ Boolean(+ backendConfig &&+ backendState &&+ JSON.stringify(backendConfig) !== JSON.stringify(backendState.config),+ ),+ [backendConfig, backendState],+ );++ const hasChanges = hasDashboardChanges || hasBackendChanges;+ const restartRequired =+ backendState?.restartRequired || serverInfo?.restartRequired || false;+ const restartReasons =+ backendState?.restartReasons || serverInfo?.restartReasons || [];+ const sensitiveEndpointsEnabled = backendConfig+ ? Object.values(backendConfig.security).some(Boolean)+ : false;+ const apiTokenMissing = backendConfig+ ? backendConfig.server.token.trim() === ""+ : false;++ const updateBackendSection = <K extends keyof BackendConfig>(+ section: K,+ patch: Partial<BackendConfig[K]>,+ ) => {+ setBackendConfig((current) =>+ current+ ? {+ ...current,+ [section]: { ...current[section], ...patch },+ }+ : current,+ );+ };- const handleSave = () => {- // Settings are persisted to localStorage via setSettings- setSettings(local);+ const handleReset = () => {+ if (backendState) {+ setBackendConfig(backendState.config);+ }+ setLocalSettings(settings);+ setError("");+ setNotice("");};- const handleReset = () => setLocal(settings);+ const handleSave = async () => {+ if (!hasChanges || !backendConfig) return;++ setSaving(true);+ setError("");+ setNotice("");++ try {+ if (hasDashboardChanges) {+ setSettings(localSettings);+ }++ if (hasBackendChanges) {+ const saved = await api.saveBackendConfig(backendConfig);+ setBackendState(saved);+ setBackendConfig(saved.config);+ setNotice(+ saved.restartRequired+ ? "Backend config saved. Dynamic changes were applied where possible. Restart advised for server-level changes."+ : "Backend config saved. Dynamic changes were applied where possible.",+ );+ }++ const health = await api.fetchHealth().catch(() => null);+ if (health) {+ setServerInfo(health);+ }++ if (!hasBackendChanges) {+ setNotice("Dashboard preferences saved in this browser.");+ }+ } catch (e) {+ const message =+ e instanceof Error ? e.message : "Failed to save settings";+ setError(message);+ } finally {+ setSaving(false);+ }+ };return (<div className="flex h-full flex-col overflow-hidden">- <div className="sticky top-0 z-10 border-b border-border-subtle bg-bg-surface px-4 py-2">- <div className="flex w-full items-center justify-end gap-2">- <Button- variant="secondary"- onClick={handleReset}- disabled={!hasChanges}- >- Reset- </Button>- <Button variant="primary" onClick={handleSave} disabled={!hasChanges}>- Apply Settings- </Button>+ <div className="sticky top-0 z-10 border-b border-border-subtle bg-bg-surface/95 px-4 py-3 backdrop-blur">+ <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">+ <div>+ <div className="dashboard-mono text-sm text-text-secondary">+ Server Version: {serverInfo?.version || "Unknown version"}+ </div>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ {restartRequired && (+ <div className="rounded-sm border border-warning/25 bg-warning/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.08em] text-warning">+ Restart required+ </div>+ )}+ <Button+ variant="secondary"+ onClick={handleReset}+ disabled={!hasChanges || saving}+ >+ Reset+ </Button>+ <Button+ variant="primary"+ onClick={handleSave}+ disabled={!hasChanges || saving || !backendConfig}+ >+ {saving ? "Saving..." : "Save"}+ </Button>+ </div></div>+ {(error || notice || restartReasons.length > 0) && (+ <div className="mt-3 flex flex-col gap-2">+ {error && (+ <div className="rounded-sm border border-destructive/35 bg-destructive/10 px-3 py-2 text-sm text-destructive">+ {error}+ </div>+ )}+ {notice && (+ <div className="rounded-sm border border-primary/30 bg-primary/10 px-3 py-2 text-sm text-primary">+ {notice}+ </div>+ )}+ {restartRequired && restartReasons.length > 0 && (+ <div className="rounded-sm border border-warning/25 bg-warning/10 px-3 py-2 text-sm text-warning">+ Restart needed for: {restartReasons.join(", ")}.+ </div>+ )}+ </div>+ )}</div>- <div className="flex w-full flex-1 overflow-hidden p-6 gap-8">- {/* Sidebar Info */}- <aside className="w-64 shrink-0 overflow-y-auto">- <ServerSummary />+ <div className="flex flex-1 flex-col gap-6 overflow-hidden p-4 lg:flex-row lg:p-6">+ <aside className="flex w-full shrink-0 flex-col gap-4 overflow-y-auto lg:w-72">+ <Card className="p-3">+ <div className="dashboard-section-label mb-3">Sections</div>+ <div className="flex flex-col gap-1.5">+ {sections.map((section) => (+ <button+ key={section.id}+ type="button"+ className={`rounded-sm border px-3 py-2.5 text-left transition-all ${+ activeSection === section.id+ ? "border-primary/30 bg-primary/10 text-text-primary"+ : "border-transparent text-text-secondary hover:border-border-subtle hover:bg-bg-elevated hover:text-text-primary"+ }`}+ onClick={() => setActiveSection(section.id)}+ >+ <div className="text-sm font-medium">{section.label}</div>+ <div className="mt-1 text-xs leading-5 text-text-muted">+ {section.description}+ </div>+ </button>+ ))}+ </div>+ </Card></aside>- {/* Settings Content */}- <div className="flex-1 space-y-6 overflow-y-auto pr-2">- {/* Policies & Strategy */}- {/* {serverInfo && (- <Card className="p-4">- <h3 className="mb-4 text-sm font-semibold text-text-primary">- ⚖️ Policies & Strategy- </h3>- <div className="grid grid-cols-3 gap-6">- <div className="space-y-1">- <label className="text-[10px] font-semibold text-text-muted uppercase tracking-tight">- Allocation Strategy- </label>- <div className="flex">- <span className="rounded bg-primary/10 px-2 py-0.5 text-xs font-bold text-primary uppercase">- {serverInfo.strategy || "none"}- </span>- </div>- </div>- <div className="space-y-1">- <label className="text-[10px] font-semibold text-text-muted uppercase tracking-tight">- Selection Policy- </label>- <div className="text-sm text-text-secondary italic">- {serverInfo.allocationPolicy || "fcfs"}- </div>- </div>- <div className="space-y-1">- <label className="text-[10px] font-semibold text-text-muted uppercase tracking-tight">- Tab Eviction- </label>- <div className="text-sm text-text-secondary italic">- {serverInfo.tabEvictionPolicy || "reject"}- </div>- </div>- </div>+ <div className="flex-1 overflow-y-auto pr-1">+ {loading || !backendConfig ? (+ <Card className="p-6">+ <div className="text-sm text-text-muted">Loading settings…</div></Card>- )} */}-- {/* Screencast */}- <Card className="p-4">- <h3 className="mb-4 text-sm font-semibold text-text-primary">- 📺 Screencast- </h3>- <div className="space-y-4">- <div className="flex items-center justify-between">- <label className="text-sm text-text-secondary">- Frame Rate- </label>- <div className="flex items-center gap-2">- <input- type="range"- min={1}- max={15}- value={local.screencast.fps}- onChange={(e) =>- setLocal({- ...local,- screencast: {- ...local.screencast,- fps: +e.target.value,- },- })- }- className="w-32"- />- <span className="w-12 text-right text-sm text-text-muted">- {local.screencast.fps} fps- </span>- </div>- </div>- <div className="flex items-center justify-between">- <label className="text-sm text-text-secondary">Quality</label>- <div className="flex items-center gap-2">- <input- type="range"- min={10}- max={80}- value={local.screencast.quality}- onChange={(e) =>- setLocal({- ...local,- screencast: {- ...local.screencast,- quality: +e.target.value,- },- })- }- className="w-32"- />- <span className="w-12 text-right text-sm text-text-muted">- {local.screencast.quality}%- </span>- </div>- </div>- <div className="flex items-center justify-between">- <label className="text-sm text-text-secondary">Max Width</label>- <select- value={local.screencast.maxWidth}- onChange={(e) =>- setLocal({- ...local,- screencast: {- ...local.screencast,- maxWidth: +e.target.value,- },- })- }- className="rounded border border-border-default bg-bg-elevated px-2 py-1 text-sm text-text-primary"+ ) : (+ <>+ {activeSection === "dashboard" && (+ <SectionCard+ title="Dashboard Preferences"+ description="These controls affect this dashboard UI only. They are stored locally in your browser and do not require a backend restart."+ >+ <SettingRow+ label="Screencast frame rate"+ description="Controls how often live previews request new frames."+ >+ <div className="flex items-center gap-3">+ <input+ type="range"+ min={1}+ max={15}+ value={localSettings.screencast.fps}+ onChange={(e) =>+ setLocalSettings({+ ...localSettings,+ screencast: {+ ...localSettings.screencast,+ fps: Number(e.target.value),+ },+ })+ }+ className="w-full"+ />+ <span className="dashboard-mono w-16 text-right text-sm text-text-secondary">+ {localSettings.screencast.fps} fps+ </span>+ </div>+ </SettingRow>+ <SettingRow+ label="Screencast quality"+ description="JPEG quality for tab preview streams."+ >+ <div className="flex items-center gap-3">+ <input+ type="range"+ min={10}+ max={80}+ value={localSettings.screencast.quality}+ onChange={(e) =>+ setLocalSettings({+ ...localSettings,+ screencast: {+ ...localSettings.screencast,+ quality: Number(e.target.value),+ },+ })+ }+ className="w-full"+ />+ <span className="dashboard-mono w-16 text-right text-sm text-text-secondary">+ {localSettings.screencast.quality}%+ </span>+ </div>+ </SettingRow>+ <SettingRow+ label="Screencast width"+ description="Maximum preview width for live tiles."+ >+ <select+ value={localSettings.screencast.maxWidth}+ onChange={(e) =>+ setLocalSettings({+ ...localSettings,+ screencast: {+ ...localSettings.screencast,+ maxWidth: Number(e.target.value),+ },+ })+ }+ className={selectClass}+ >+ {[400, 600, 800, 1024, 1280].map((width) => (+ <option key={width} value={width}>+ {width}px+ </option>+ ))}+ </select>+ </SettingRow>+ <SettingRow+ label="Memory metrics"+ description="Enable per-tab heap collection in the dashboard. Useful for debugging, but heavier."+ >+ <label className="flex items-center justify-end gap-3 text-sm text-text-secondary">+ <input+ type="checkbox"+ checked={localSettings.monitoring.memoryMetrics}+ onChange={(e) =>+ setLocalSettings({+ ...localSettings,+ monitoring: {+ ...localSettings.monitoring,+ memoryMetrics: e.target.checked,+ },+ })+ }+ className="h-4 w-4"+ />+ Enable+ </label>+ </SettingRow>+ <SettingRow+ label="Polling interval"+ description="How frequently the dashboard asks the backend for fresh metrics."+ >+ <div className="flex items-center gap-3">+ <input+ type="range"+ min={5}+ max={120}+ step={5}+ value={localSettings.monitoring.pollInterval}+ onChange={(e) =>+ setLocalSettings({+ ...localSettings,+ monitoring: {+ ...localSettings.monitoring,+ pollInterval: Number(e.target.value),+ },+ })+ }+ className="w-full"+ />+ <span className="dashboard-mono w-16 text-right text-sm text-text-secondary">+ {localSettings.monitoring.pollInterval}s+ </span>+ </div>+ </SettingRow>+ </SectionCard>+ )}++ {activeSection === "defaults" && (+ <SectionCard+ title="Instance Defaults"+ description="These values are written to config and used for new managed instances. Existing running instances keep their current runtime.">- {[400, 600, 800, 1024, 1280].map((w) => (- <option key={w} value={w}>- {w}px- </option>+ <SettingRow+ label="Mode"+ description="Default browser mode for new launches."+ >+ <select+ value={backendConfig.instanceDefaults.mode}+ onChange={(e) =>+ updateBackendSection("instanceDefaults", {+ mode: e.target+ .value as BackendConfig["instanceDefaults"]["mode"],+ })+ }+ className={selectClass}+ >+ <option value="headless">Headless</option>+ <option value="headed">Headed</option>+ </select>+ </SettingRow>+ <SettingRow+ label="Stealth level"+ description="Fingerprint hardening profile for new instances."+ >+ <select+ value={backendConfig.instanceDefaults.stealthLevel}+ onChange={(e) =>+ updateBackendSection("instanceDefaults", {+ stealthLevel: e.target+ .value as BackendConfig["instanceDefaults"]["stealthLevel"],+ })+ }+ className={selectClass}+ >+ <option value="light">Light</option>+ <option value="medium">Medium</option>+ <option value="full">Full</option>+ </select>+ </SettingRow>+ <SettingRow+ label="Tab eviction policy"+ description="How PinchTab behaves when a managed instance reaches its tab limit."+ >+ <select+ value={backendConfig.instanceDefaults.tabEvictionPolicy}+ onChange={(e) =>+ updateBackendSection("instanceDefaults", {+ tabEvictionPolicy: e.target+ .value as BackendConfig["instanceDefaults"]["tabEvictionPolicy"],+ })+ }+ className={selectClass}+ >+ <option value="reject">Reject new tabs</option>+ <option value="close_oldest">Close oldest</option>+ <option value="close_lru">+ Close least recently used+ </option>+ </select>+ </SettingRow>+ <SettingRow+ label="Max tabs"+ description="Maximum number of tabs per managed instance."+ >+ <input+ type="number"+ min={1}+ value={backendConfig.instanceDefaults.maxTabs}+ onChange={(e) =>+ updateBackendSection("instanceDefaults", {+ maxTabs: Number(e.target.value),+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="Max parallel tabs"+ description="Set to 0 to auto-detect from CPU count."+ >+ <input+ type="number"+ min={0}+ value={backendConfig.instanceDefaults.maxParallelTabs}+ onChange={(e) =>+ updateBackendSection("instanceDefaults", {+ maxParallelTabs: Number(e.target.value),+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="Timezone"+ description="Optional timezone override for launched instances."+ >+ <input+ value={backendConfig.instanceDefaults.timezone}+ onChange={(e) =>+ updateBackendSection("instanceDefaults", {+ timezone: e.target.value,+ })+ }+ placeholder="Europe/Rome"+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="User agent"+ description="Optional override applied to new managed instances."+ >+ <input+ value={backendConfig.instanceDefaults.userAgent}+ onChange={(e) =>+ updateBackendSection("instanceDefaults", {+ userAgent: e.target.value,+ })+ }+ placeholder="Custom user agent"+ className={fieldClass}+ />+ </SettingRow>+ {[+ ["blockImages", "Block images"],+ ["blockMedia", "Block media"],+ ["blockAds", "Block ads"],+ ["noAnimations", "Disable CSS animations"],+ ["noRestore", "Skip session restore"],+ ].map(([key, label]) => (+ <SettingRow+ key={key}+ label={label}+ description="Applies to newly launched managed instances."+ >+ <label className="flex items-center justify-end gap-3 text-sm text-text-secondary">+ <input+ type="checkbox"+ checked={+ backendConfig.instanceDefaults[+ key as keyof BackendConfig["instanceDefaults"]+ ] as boolean+ }+ onChange={(e) =>+ updateBackendSection("instanceDefaults", {+ [key]: e.target.checked,+ } as Partial<BackendConfig["instanceDefaults"]>)+ }+ className="h-4 w-4"+ />+ Enable+ </label>+ </SettingRow>))}- </select>- </div>- </div>- </Card>+ </SectionCard>+ )}- {/* Stealth */}- <Card className="p-4">- <h3 className="mb-4 text-sm font-semibold text-text-primary">- 🛡️ Stealth- </h3>- <div className="flex items-center justify-between">- <label className="text-sm text-text-secondary">Level</label>- <select- value={local.stealth}- onChange={(e) =>- setLocal({- ...local,- stealth: e.target.value as "light" | "full",- })- }- className="rounded border border-border-default bg-bg-elevated px-2 py-1 text-sm text-text-primary"- >- <option value="light">Light (default)</option>- <option value="full">Full (canvas noise, WebGL, fonts)</option>- </select>- </div>- </Card>+ {activeSection === "orchestration" && (+ <SectionCard+ title="Orchestration"+ description="Port range and allocation policy can be applied immediately for future launches. Strategy changes require a dashboard restart because routes are registered at startup."+ >+ <SettingRow+ label="Strategy"+ description="Controls how shorthand routes are routed in dashboard mode."+ >+ <select+ value={backendConfig.multiInstance.strategy}+ onChange={(e) =>+ updateBackendSection("multiInstance", {+ strategy: e.target+ .value as BackendConfig["multiInstance"]["strategy"],+ })+ }+ className={selectClass}+ >+ <option value="simple">Simple</option>+ <option value="explicit">Explicit</option>+ <option value="simple-autorestart">+ Simple autorestart+ </option>+ </select>+ </SettingRow>+ <SettingRow+ label="Allocation policy"+ description="Determines how running instances are chosen for shorthand requests."+ >+ <select+ value={backendConfig.multiInstance.allocationPolicy}+ onChange={(e) =>+ updateBackendSection("multiInstance", {+ allocationPolicy: e.target+ .value as BackendConfig["multiInstance"]["allocationPolicy"],+ })+ }+ className={selectClass}+ >+ <option value="fcfs">First available</option>+ <option value="round_robin">Round robin</option>+ <option value="random">Random</option>+ </select>+ </SettingRow>+ <SettingRow+ label="Instance port start"+ description="Lower bound for auto-allocated instance ports."+ >+ <input+ type="number"+ min={1}+ value={backendConfig.multiInstance.instancePortStart}+ onChange={(e) =>+ updateBackendSection("multiInstance", {+ instancePortStart: Number(e.target.value),+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="Instance port end"+ description="Upper bound for auto-allocated instance ports."+ >+ <input+ type="number"+ min={1}+ value={backendConfig.multiInstance.instancePortEnd}+ onChange={(e) =>+ updateBackendSection("multiInstance", {+ instancePortEnd: Number(e.target.value),+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ </SectionCard>+ )}- {/* Browser */}- <Card className="p-4">- <h3 className="mb-4 text-sm font-semibold text-text-primary">- 🌐 Browser- </h3>- <div className="space-y-3">- {[- { key: "blockImages", label: "Block Images" },- { key: "blockMedia", label: "Block Media" },- { key: "noAnimations", label: "No Animations" },- ].map(({ key, label }) => (- <label key={key} className="flex items-center justify-between">- <span className="text-sm text-text-secondary">{label}</span>- <input- type="checkbox"- checked={local.browser[key as keyof typeof local.browser]}- onChange={(e) =>- setLocal({- ...local,- browser: { ...local.browser, [key]: e.target.checked },- })- }- className="h-4 w-4"- />- </label>- ))}- </div>- </Card>+ {activeSection === "security" && (+ <SectionCard+ title="Security"+ description="These feature gates affect what sensitive capabilities PinchTab exposes. They are applied to future launched instances and live middleware where supported."+ >+ <div+ className={`rounded-sm px-4 py-3 text-sm leading-6 ${+ sensitiveEndpointsEnabled+ ? "border border-destructive/35 bg-destructive/10 text-destructive"+ : "border border-warning/25 bg-warning/10 text-warning"+ }`}+ >+ {sensitiveEndpointsEnabled+ ? "One or more sensitive endpoint families are enabled. Features like script execution, downloads, uploads, and live capture can expose high-risk capabilities. Only enable them in trusted environments. You are responsible for securing network access, authentication, and downstream use."+ : "These endpoint families can expose high-risk capabilities when enabled. Only turn them on in trusted environments, and only when you accept responsibility for network access, authentication, and downstream use."}+ </div>+ {[+ ["allowEvaluate", "Allow evaluate"],+ ["allowMacro", "Allow macro"],+ ["allowScreencast", "Allow screencast"],+ ["allowDownload", "Allow download"],+ ["allowUpload", "Allow upload"],+ ].map(([key, label]) => (+ <SettingRow+ key={key}+ label={label}+ description="Controls whether the corresponding endpoint family is enabled."+ >+ <label className="flex items-center justify-end gap-3 text-sm text-text-secondary">+ <input+ type="checkbox"+ checked={+ backendConfig.security[+ key as keyof BackendConfig["security"]+ ]+ }+ onChange={(e) =>+ updateBackendSection("security", {+ [key]: e.target.checked,+ } as Partial<BackendConfig["security"]>)+ }+ className="h-4 w-4"+ />+ Enable+ </label>+ </SettingRow>+ ))}+ </SectionCard>+ )}- {/* Monitoring */}- <Card className="p-4">- <h3 className="mb-4 text-sm font-semibold text-text-primary">- 📈 Monitoring- </h3>- <div className="space-y-3">- <label className="flex items-center justify-between">- <div>- <span className="text-sm text-text-secondary">- Tab Memory Metrics{" "}- <span className="rounded bg-yellow-500/20 px-1 py-0.5 text-xs text-yellow-500">- experimental- </span>- </span>- <p className="text-xs text-text-muted">- Track JS heap usage per tab via CDP (may cause instability)- </p>- </div>- <input- type="checkbox"- checked={local.monitoring?.memoryMetrics ?? false}- onChange={(e) =>- setLocal({- ...local,- monitoring: {- ...local.monitoring,- memoryMetrics: e.target.checked,- },- })- }- className="h-4 w-4"- />- </label>- <div className="flex items-center justify-between">- <div>- <span className="text-sm text-text-secondary">- Poll Interval- </span>- <p className="text-xs text-text-muted">- How often to fetch tab/memory data- </p>- </div>- <div className="flex items-center gap-2">- <input- type="range"- min={5}- max={120}- step={5}- value={local.monitoring?.pollInterval ?? 30}- onChange={(e) =>- setLocal({- ...local,- monitoring: {- ...local.monitoring,- pollInterval: +e.target.value,- },- })- }- className="w-24"- />- <span className="w-12 text-right text-sm text-text-muted">- {local.monitoring?.pollInterval ?? 30}s- </span>- </div>- </div>- </div>- </Card>+ {activeSection === "profiles" && (+ <SectionCard+ title="Profiles"+ description="Profile storage is host-level. Changing the base directory requires restart because the profile manager and orchestrator are created with it at boot."+ >+ <SettingRow+ label="Profiles base directory"+ description="Root directory where browser profiles are stored."+ >+ <input+ value={backendConfig.profiles.baseDir}+ onChange={(e) =>+ updateBackendSection("profiles", {+ baseDir: e.target.value,+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="Default profile"+ description="Profile name used when the server needs an implicit default."+ >+ <input+ value={backendConfig.profiles.defaultProfile}+ onChange={(e) =>+ updateBackendSection("profiles", {+ defaultProfile: e.target.value,+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ </SectionCard>+ )}++ {activeSection === "network" && (+ <SectionCard+ title="Network & Attach"+ description="Port and bind changes require a restart. Token changes update request auth immediately because middleware reads runtime config live."+ >+ <SettingRow+ label="Server port"+ description="HTTP port for the dashboard process."+ >+ <input+ value={backendConfig.server.port}+ onChange={(e) =>+ updateBackendSection("server", { port: e.target.value })+ }+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="Bind address"+ description="Network interface the dashboard process binds to."+ >+ <input+ value={backendConfig.server.bind}+ onChange={(e) =>+ updateBackendSection("server", { bind: e.target.value })+ }+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="API token"+ description="Bearer token required by authenticated requests when set. Leaving this empty means reachable clients are unauthenticated."+ >+ <div className="space-y-2">+ <input+ value={backendConfig.server.token}+ onChange={(e) =>+ updateBackendSection("server", {+ token: e.target.value,+ })+ }+ className={fieldClass}+ />+ {apiTokenMissing && (+ <div className="rounded-sm border border-destructive/35 bg-destructive/10 px-3 py-2 text-xs leading-5 text-destructive">+ No API token is set. Anyone who can reach this server+ can access exposed endpoints. Keep it on trusted local+ networks only, or set a strong token. You are+ responsible for protecting access.+ </div>+ )}+ </div>+ </SettingRow>+ <SettingRow+ label="State directory"+ description="Base state path used by managed child instances."+ >+ <input+ value={backendConfig.server.stateDir}+ onChange={(e) =>+ updateBackendSection("server", {+ stateDir: e.target.value,+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="Allow attach"+ description="Permit attaching PinchTab to externally managed Chrome sessions."+ >+ <label className="flex items-center justify-end gap-3 text-sm text-text-secondary">+ <input+ type="checkbox"+ checked={backendConfig.attach.enabled}+ onChange={(e) =>+ updateBackendSection("attach", {+ enabled: e.target.checked,+ })+ }+ className="h-4 w-4"+ />+ Enable+ </label>+ </SettingRow>+ <SettingRow+ label="Allowed attach hosts"+ description="Comma-separated host allowlist for attach requests. Only include hosts you control and trust."+ >+ <div className="space-y-2">+ <input+ value={listToCsv(backendConfig.attach.allowHosts)}+ onChange={(e) =>+ updateBackendSection("attach", {+ allowHosts: csvToList(e.target.value),+ })+ }+ className={fieldClass}+ />+ <div className="rounded-sm border border-warning/25 bg-warning/10 px-3 py-2 text-xs leading-5 text-warning">+ Hosts in this allowlist may be used for remote attach+ requests. Broad or untrusted entries can expose external+ Chrome sessions and browser contents.+ </div>+ </div>+ </SettingRow>+ <SettingRow+ label="Allowed attach schemes"+ description="Comma-separated scheme allowlist, usually ws and wss."+ >+ <input+ value={listToCsv(backendConfig.attach.allowSchemes)}+ onChange={(e) =>+ updateBackendSection("attach", {+ allowSchemes: csvToList(e.target.value),+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ </SectionCard>+ )}++ {activeSection === "browser" && (+ <SectionCard+ title="Browser Runtime"+ description="These settings are written into the generated child config for new managed instances."+ >+ <SettingRow+ label="Chrome version"+ description="Version string used in generated UA/fingerprint defaults."+ >+ <input+ value={backendConfig.browser.version}+ onChange={(e) =>+ updateBackendSection("browser", {+ version: e.target.value,+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="Chrome binary"+ description="Optional path override for the Chrome executable."+ >+ <input+ value={backendConfig.browser.binary}+ onChange={(e) =>+ updateBackendSection("browser", {+ binary: e.target.value,+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="Extra flags"+ description="Additional Chrome flags appended when launching managed instances."+ >+ <input+ value={backendConfig.browser.extraFlags}+ onChange={(e) =>+ updateBackendSection("browser", {+ extraFlags: e.target.value,+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="Extension paths"+ description="Comma-separated extension directories to load."+ >+ <input+ value={listToCsv(backendConfig.browser.extensionPaths)}+ onChange={(e) =>+ updateBackendSection("browser", {+ extensionPaths: csvToList(e.target.value),+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ </SectionCard>+ )}++ {activeSection === "timeouts" && (+ <SectionCard+ title="Timeouts"+ description="Runtime timing defaults written into new child configs. Existing running instances keep their current timeouts."+ >+ {[+ [+ "actionSec",+ "Action timeout",+ "Maximum time for action requests.",+ ],+ [+ "navigateSec",+ "Navigate timeout",+ "Maximum time for navigation requests.",+ ],+ [+ "shutdownSec",+ "Shutdown timeout",+ "Grace period before force-closing a child process.",+ ],+ [+ "waitNavMs",+ "Wait-after-navigation delay",+ "Post-navigation stabilization delay in milliseconds.",+ ],+ ].map(([key, label, description]) => (+ <SettingRow+ key={key}+ label={label}+ description={description}+ >+ <input+ type="number"+ min={0}+ value={+ backendConfig.timeouts[+ key as keyof BackendConfig["timeouts"]+ ]+ }+ onChange={(e) =>+ updateBackendSection("timeouts", {+ [key]: Number(e.target.value),+ } as Partial<BackendConfig["timeouts"]>)+ }+ className={fieldClass}+ />+ </SettingRow>+ ))}+ </SectionCard>+ )}+ </>+ )}</div></div></div>diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 10980be3..fc3f67b3 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -4,11 +4,19 @@ import type {InstanceTab,InstanceMetrics,Agent,- ServerInfo,CreateProfileRequest,CreateProfileResponse,LaunchInstanceRequest,} from "../generated/types";+import type {+ BackendConfig,+ BackendConfigState,+ DashboardServerInfo,+} from "../types";+import {+ normalizeBackendConfigState,+ normalizeDashboardServerInfo,+} from "../types";const BASE = ""; // Uses proxy in dev@@ -109,14 +117,29 @@ export async function fetchServerMetrics(): Promise<ServerMetrics> {return res.metrics;}-// Agents — endpoint is /api/agents (dashboard API)-export async function fetchAgents(): Promise<Agent[]> {- return request<Agent[]>("/api/agents");-}-// Health-export async function fetchHealth(): Promise<ServerInfo> {- return request<ServerInfo>("/health");+export async function fetchHealth(): Promise<DashboardServerInfo> {+ return normalizeDashboardServerInfo(+ await request<DashboardServerInfo>("/health"),+ );+}++export async function fetchBackendConfig(): Promise<BackendConfigState> {+ return normalizeBackendConfigState(+ await request<BackendConfigState>("/api/config"),+ );+}++export async function saveBackendConfig(+ config: BackendConfig,+): Promise<BackendConfigState> {+ return normalizeBackendConfigState(+ await request<BackendConfigState>("/api/config", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(config),+ }),+ );}// SSE Events — endpoint is /api/eventsdiff --git a/dashboard/src/stores/useAppStore.ts b/dashboard/src/stores/useAppStore.tsindex 04b7d1e3..b3908d17 100644--- a/dashboard/src/stores/useAppStore.ts+++ b/dashboard/src/stores/useAppStore.ts@@ -6,8 +6,8 @@ import type {Agent,ActivityEvent,Settings,- ServerInfo,} from "../generated/types";+import type { DashboardServerInfo } from "../types";export interface TabDataPoint {timestamp: number;@@ -69,8 +69,8 @@ interface AppState {setSettings: (settings: Settings) => void;// Server info- serverInfo: ServerInfo | null;- setServerInfo: (info: ServerInfo | null) => void;+ serverInfo: DashboardServerInfo | null;+ setServerInfo: (info: DashboardServerInfo | null) => void;}const defaultSettings: Settings = {diff --git a/dashboard/src/types/index.ts b/dashboard/src/types/index.tsindex 7ac3a3f7..08183991 100644--- a/dashboard/src/types/index.ts+++ b/dashboard/src/types/index.ts@@ -1,4 +1,15 @@-// Re-export generated types from Go+import type {+ Agent,+ ActivityEvent,+ BrowserSettings,+ CreateProfileRequest,+ Instance,+ LaunchInstanceRequest,+ Profile,+ ScreencastSettings,+ Settings,+} from "../generated/types";+export type {Profile,Instance,@@ -7,7 +18,228 @@ export type {Settings,ScreencastSettings,BrowserSettings,- ServerInfo,CreateProfileRequest,LaunchInstanceRequest,-} from "../generated/types";+};++export interface DashboardServerInfo {+ status: string;+ mode: string;+ version: string;+ uptime: number;+ profiles: number;+ instances: number;+ agents: number;+ restartRequired?: boolean;+ restartReasons?: string[];+}++export interface BackendServerConfig {+ port: string;+ bind: string;+ token: string;+ stateDir: string;+}++export interface BackendBrowserConfig {+ version: string;+ binary: string;+ extraFlags: string;+ extensionPaths: string[];+}++export interface BackendInstanceDefaultsConfig {+ mode: "headless" | "headed";+ noRestore: boolean;+ timezone: string;+ blockImages: boolean;+ blockMedia: boolean;+ blockAds: boolean;+ maxTabs: number;+ maxParallelTabs: number;+ userAgent: string;+ noAnimations: boolean;+ stealthLevel: "light" | "medium" | "full";+ tabEvictionPolicy: "reject" | "close_oldest" | "close_lru";+}++export interface BackendSecurityConfig {+ allowEvaluate: boolean;+ allowMacro: boolean;+ allowScreencast: boolean;+ allowDownload: boolean;+ allowUpload: boolean;+}++export interface BackendProfilesConfig {+ baseDir: string;+ defaultProfile: string;+}++export interface BackendMultiInstanceConfig {+ strategy: "simple" | "explicit" | "simple-autorestart";+ allocationPolicy: "fcfs" | "round_robin" | "random";+ instancePortStart: number;+ instancePortEnd: number;+}++export interface BackendAttachConfig {+ enabled: boolean;+ allowHosts: string[];+ allowSchemes: string[];+}++export interface BackendTimeoutsConfig {+ actionSec: number;+ navigateSec: number;+ shutdownSec: number;+ waitNavMs: number;+}++export interface BackendConfig {+ server: BackendServerConfig;+ browser: BackendBrowserConfig;+ instanceDefaults: BackendInstanceDefaultsConfig;+ security: BackendSecurityConfig;+ profiles: BackendProfilesConfig;+ multiInstance: BackendMultiInstanceConfig;+ attach: BackendAttachConfig;+ timeouts: BackendTimeoutsConfig;+}++export interface BackendConfigState {+ config: BackendConfig;+ configPath: string;+ restartRequired: boolean;+ restartReasons: string[];+}++export const defaultBackendConfig: BackendConfig = {+ server: {+ port: "9867",+ bind: "127.0.0.1",+ token: "",+ stateDir: "",+ },+ browser: {+ version: "144.0.7559.133",+ binary: "",+ extraFlags: "",+ extensionPaths: [],+ },+ instanceDefaults: {+ mode: "headless",+ noRestore: false,+ timezone: "",+ blockImages: false,+ blockMedia: false,+ blockAds: false,+ maxTabs: 20,+ maxParallelTabs: 0,+ userAgent: "",+ noAnimations: false,+ stealthLevel: "light",+ tabEvictionPolicy: "reject",+ },+ security: {+ allowEvaluate: false,+ allowMacro: false,+ allowScreencast: false,+ allowDownload: false,+ allowUpload: false,+ },+ profiles: {+ baseDir: "",+ defaultProfile: "default",+ },+ multiInstance: {+ strategy: "simple",+ allocationPolicy: "fcfs",+ instancePortStart: 9868,+ instancePortEnd: 9968,+ },+ attach: {+ enabled: false,+ allowHosts: ["127.0.0.1", "localhost", "::1"],+ allowSchemes: ["ws", "wss"],+ },+ timeouts: {+ actionSec: 30,+ navigateSec: 60,+ shutdownSec: 10,+ waitNavMs: 1000,+ },+};++export function normalizeBackendConfig(+ input?: Partial<BackendConfig> | null,+): BackendConfig {+ return {+ server: {+ ...defaultBackendConfig.server,+ ...(input?.server ?? {}),+ },+ browser: {+ ...defaultBackendConfig.browser,+ ...(input?.browser ?? {}),+ extensionPaths:+ input?.browser?.extensionPaths ??+ defaultBackendConfig.browser.extensionPaths,+ },+ instanceDefaults: {+ ...defaultBackendConfig.instanceDefaults,+ ...(input?.instanceDefaults ?? {}),+ },+ security: {+ ...defaultBackendConfig.security,+ ...(input?.security ?? {}),+ },+ profiles: {+ ...defaultBackendConfig.profiles,+ ...(input?.profiles ?? {}),+ },+ multiInstance: {+ ...defaultBackendConfig.multiInstance,+ ...(input?.multiInstance ?? {}),+ },+ attach: {+ ...defaultBackendConfig.attach,+ ...(input?.attach ?? {}),+ allowHosts:+ input?.attach?.allowHosts ?? defaultBackendConfig.attach.allowHosts,+ allowSchemes:+ input?.attach?.allowSchemes ?? defaultBackendConfig.attach.allowSchemes,+ },+ timeouts: {+ ...defaultBackendConfig.timeouts,+ ...(input?.timeouts ?? {}),+ },+ };+}++export function normalizeBackendConfigState(+ input: Partial<BackendConfigState>,+): BackendConfigState {+ return {+ config: normalizeBackendConfig(input.config),+ configPath: input.configPath ?? "",+ restartRequired: input.restartRequired ?? false,+ restartReasons: input.restartReasons ?? [],+ };+}++export function normalizeDashboardServerInfo(+ input: DashboardServerInfo,+): DashboardServerInfo {+ return {+ ...input,+ restartRequired: input.restartRequired ?? false,+ restartReasons: input.restartReasons ?? [],+ };+}++export type {+ Settings as LocalDashboardSettings,+ ScreencastSettings as LocalScreencastSettings,+ BrowserSettings as LocalBrowserSettings,+};diff --git a/internal/config/config.go b/internal/config/config.goindex 2583087c..d87e6b49 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -693,6 +693,17 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {}}+// ApplyFileConfigToRuntime merges file configuration into an existing runtime+// config and refreshes derived profile paths for long-running processes.+func ApplyFileConfigToRuntime(cfg *RuntimeConfig, fc *FileConfig) {+ if cfg == nil || fc == nil {+ return+ }++ applyFileConfig(cfg, fc)+ finalizeProfileConfig(cfg)+}+// DefaultFileConfig returns a FileConfig with sensible defaults (nested format).func DefaultFileConfig() FileConfig {start := 9868diff --git a/internal/dashboard/config_api.go b/internal/dashboard/config_api.gonew file mode 100644index 00000000..8a04ed38--- /dev/null+++ b/internal/dashboard/config_api.go@@ -0,0 +1,237 @@+package dashboard++import (+ "encoding/json"+ "net/http"+ "strings"+ "sync"+ "time"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/web"+)++type profileLister interface {+ List() ([]bridge.ProfileInfo, error)+}++type runtimeConfigApplier interface {+ ApplyRuntimeConfig(*config.RuntimeConfig)+}++type ConfigAPI struct {+ runtime *config.RuntimeConfig+ instances InstanceLister+ profiles profileLister+ applier runtimeConfigApplier+ version string+ startedAt time.Time+ boot config.FileConfig+ mu sync.RWMutex+}++type configEnvelope struct {+ Config config.FileConfig `json:"config"`+ ConfigPath string `json:"configPath"`+ RestartRequired bool `json:"restartRequired"`+ RestartReasons []string `json:"restartReasons,omitempty"`+}++type healthEnvelope struct {+ Status string `json:"status"`+ Mode string `json:"mode"`+ Version string `json:"version"`+ Uptime int64 `json:"uptime"`+ Profiles int `json:"profiles"`+ Instances int `json:"instances"`+ Agents int `json:"agents"`+ RestartRequired bool `json:"restartRequired"`+ RestartReasons []string `json:"restartReasons,omitempty"`+}++func NewConfigAPI(+ runtime *config.RuntimeConfig,+ instances InstanceLister,+ profiles profileLister,+ applier runtimeConfigApplier,+ version string,+ startedAt time.Time,+) *ConfigAPI {+ boot := config.DefaultFileConfig()+ if runtime != nil {+ boot = config.FileConfigFromRuntime(runtime)+ }+ return &ConfigAPI{+ runtime: runtime,+ instances: instances,+ profiles: profiles,+ applier: applier,+ version: version,+ startedAt: startedAt,+ boot: boot,+ }+}++func (c *ConfigAPI) RegisterHandlers(mux *http.ServeMux) {+ mux.HandleFunc("GET /api/config", c.HandleGetConfig)+ mux.HandleFunc("PUT /api/config", c.HandlePutConfig)+}++func (c *ConfigAPI) HandleHealth(w http.ResponseWriter, r *http.Request) {+ info, err := c.healthInfo()+ if err != nil {+ web.Error(w, 500, err)+ return+ }+ web.JSON(w, 200, info)+}++func (c *ConfigAPI) HandleGetConfig(w http.ResponseWriter, r *http.Request) {+ cfg, path, restartReasons, err := c.currentConfig()+ if err != nil {+ web.Error(w, 500, err)+ return+ }+ web.JSON(w, 200, configEnvelope{+ Config: cfg,+ ConfigPath: path,+ RestartRequired: len(restartReasons) > 0,+ RestartReasons: restartReasons,+ })+}++func (c *ConfigAPI) HandlePutConfig(w http.ResponseWriter, r *http.Request) {+ var incoming config.FileConfig+ if err := json.NewDecoder(r.Body).Decode(&incoming); err != nil {+ web.ErrorCode(w, 400, "bad_config_json", "invalid config payload", false, nil)+ return+ }++ normalized, err := normalizeFileConfig(&incoming)+ if err != nil {+ web.Error(w, 400, err)+ return+ }++ if errs := config.ValidateFileConfig(&normalized); len(errs) > 0 {+ messages := make([]string, 0, len(errs))+ for _, validationErr := range errs {+ messages = append(messages, validationErr.Error())+ }+ web.ErrorCode(w, 400, "invalid_config", "config validation failed", false, map[string]any{+ "errors": messages,+ })+ return+ }++ c.mu.Lock()+ defer c.mu.Unlock()++ _, path, err := config.LoadFileConfig()+ if err != nil {+ web.Error(w, 500, err)+ return+ }+ if err := config.SaveFileConfig(&normalized, path); err != nil {+ web.Error(w, 500, err)+ return+ }++ config.ApplyFileConfigToRuntime(c.runtime, &normalized)+ if c.applier != nil {+ c.applier.ApplyRuntimeConfig(c.runtime)+ }++ restartReasons := c.restartReasonsFor(normalized)+ web.JSON(w, 200, configEnvelope{+ Config: normalized,+ ConfigPath: path,+ RestartRequired: len(restartReasons) > 0,+ RestartReasons: restartReasons,+ })+}++func (c *ConfigAPI) healthInfo() (healthEnvelope, error) {+ _, _, restartReasons, err := c.currentConfig()+ if err != nil {+ return healthEnvelope{}, err+ }++ profileCount := 0+ if c.profiles != nil {+ profiles, err := c.profiles.List()+ if err == nil {+ profileCount = len(profiles)+ }+ }++ instanceCount := 0+ if c.instances != nil {+ instanceCount = len(c.instances.List())+ }+ return healthEnvelope{+ Status: "ok",+ Mode: "dashboard",+ Version: c.version,+ Uptime: int64(time.Since(c.startedAt).Milliseconds()),+ Profiles: profileCount,+ Instances: instanceCount,+ Agents: 0,+ RestartRequired: len(restartReasons) > 0,+ RestartReasons: restartReasons,+ }, nil+}++func (c *ConfigAPI) currentConfig() (config.FileConfig, string, []string, error) {+ c.mu.RLock()+ defer c.mu.RUnlock()++ fc, path, err := config.LoadFileConfig()+ if err != nil {+ return config.FileConfig{}, "", nil, err+ }+ normalized, err := normalizeFileConfig(fc)+ if err != nil {+ return config.FileConfig{}, "", nil, err+ }+ restartReasons := c.restartReasonsFor(normalized)+ return normalized, path, restartReasons, nil+}++func (c *ConfigAPI) restartReasonsFor(next config.FileConfig) []string {+ reasons := make([]string, 0, 4)++ if c.boot.Server.Port != next.Server.Port || c.boot.Server.Bind != next.Server.Bind {+ reasons = append(reasons, "Server address")+ }+ if c.boot.Profiles.BaseDir != next.Profiles.BaseDir {+ reasons = append(reasons, "Profiles directory")+ }+ if c.boot.MultiInstance.Strategy != next.MultiInstance.Strategy {+ reasons = append(reasons, "Routing strategy")+ }++ return reasons+}++func normalizeFileConfig(fc *config.FileConfig) (config.FileConfig, error) {+ base := config.DefaultFileConfig()+ if fc == nil {+ return base, nil+ }++ data, err := json.Marshal(fc)+ if err != nil {+ return config.FileConfig{}, err+ }+ patch := strings.TrimSpace(string(data))+ if patch == "" || patch == "null" || patch == "{}" {+ return base, nil+ }++ if err := config.PatchConfigJSON(&base, patch); err != nil {+ return config.FileConfig{}, err+ }+ return base, nil+}diff --git a/internal/dashboard/dashboard.go b/internal/dashboard/dashboard.goindex 8ce84e76..5f72c7f5 100644--- a/internal/dashboard/dashboard.go+++ b/internal/dashboard/dashboard.go@@ -146,9 +146,18 @@ func (d *Dashboard) handleSSE(w http.ResponseWriter, r *http.Request) {return}+ // SSE connections are intentionally long-lived. Clear the server-level write+ // deadline for this response so the stream is not terminated after+ // http.Server.WriteTimeout elapses.+ if err := http.NewResponseController(w).SetWriteDeadline(time.Time{}); err != nil {+ http.Error(w, "streaming deadline unsupported", http.StatusInternalServerError)+ return+ }+w.Header().Set("Content-Type", "text/event-stream")w.Header().Set("Cache-Control", "no-cache")w.Header().Set("Connection", "keep-alive")+ w.Header().Set("X-Accel-Buffering", "no")agentCh := make(chan AgentEvent, d.cfg.SSEBufferSize)sysCh := make(chan SystemEvent, d.cfg.SSEBufferSize)diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.goindex 5c483999..b65b71e4 100644--- a/internal/orchestrator/handlers.go+++ b/internal/orchestrator/handlers.go@@ -23,7 +23,7 @@ func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {mux.HandleFunc("POST /instances/{id}/start", o.handleStartByInstanceID)mux.HandleFunc("POST /instances/{id}/stop", o.handleStopByInstanceID)mux.HandleFunc("GET /instances/{id}/logs", o.handleLogsByID)- mux.HandleFunc("GET /instances/{id}/tabs", o.proxyToInstance)+ mux.HandleFunc("GET /instances/{id}/tabs", o.handleInstanceTabs)mux.HandleFunc("GET /instances/{id}/proxy/screencast", o.handleProxyScreencast)mux.HandleFunc("POST /instances/{id}/tabs/open", o.handleInstanceTabOpen)mux.HandleFunc("POST /instances/{id}/tab", o.proxyToInstance)diff --git a/internal/orchestrator/handlers_instances.go b/internal/orchestrator/handlers_instances.goindex 2228746a..f83b7f0f 100644--- a/internal/orchestrator/handlers_instances.go+++ b/internal/orchestrator/handlers_instances.go@@ -183,6 +183,42 @@ func (o *Orchestrator) handleStartInstance(w http.ResponseWriter, r *http.Requesweb.JSON(w, 201, inst)}+func (o *Orchestrator) handleInstanceTabs(w http.ResponseWriter, r *http.Request) {+ id := r.PathValue("id")++ o.mu.RLock()+ inst, ok := o.instances[id]+ o.mu.RUnlock()++ if !ok {+ web.Error(w, 404, fmt.Errorf("instance %q not found", id))+ return+ }++ if inst.Status != "running" || !instanceIsActive(inst) {+ web.Error(w, 503, fmt.Errorf("instance %q is not running (status: %s)", id, inst.Status))+ return+ }++ tabs, err := o.fetchTabs(inst.URL)+ if err != nil {+ web.Error(w, 502, fmt.Errorf("failed to fetch tabs for instance %q: %w", id, err))+ return+ }++ result := make([]map[string]any, 0, len(tabs))+ for _, tab := range tabs {+ result = append(result, map[string]any{+ "id": tab.ID,+ "instanceId": inst.ID,+ "url": tab.URL,+ "title": tab.Title,+ })+ }++ web.JSON(w, 200, result)+}+func (o *Orchestrator) handleAttachInstance(w http.ResponseWriter, r *http.Request) {var req struct {CdpURL string `json:"cdpUrl"`diff --git a/internal/orchestrator/health.go b/internal/orchestrator/health.goindex b64c674d..21f25f78 100644--- a/internal/orchestrator/health.go+++ b/internal/orchestrator/health.go@@ -144,7 +144,7 @@ type memoryMetrics struct {}func (o *Orchestrator) fetchTabs(baseURL string) ([]remoteTab, error) {- req, err := http.NewRequest(http.MethodGet, baseURL+"/screencast/tabs", nil)+ req, err := http.NewRequest(http.MethodGet, baseURL+"/tabs", nil)if err != nil {return nil, err}@@ -158,11 +158,17 @@ func (o *Orchestrator) fetchTabs(baseURL string) ([]remoteTab, error) {}defer func() { _ = resp.Body.Close() }()- var tabs []remoteTab- if err := json.NewDecoder(resp.Body).Decode(&tabs); err != nil {+ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("fetch tabs: status %d", resp.StatusCode)+ }++ var result struct {+ Tabs []remoteTab `json:"tabs"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {return nil, err}- return tabs, nil+ return result.Tabs, nil}func (o *Orchestrator) fetchMetrics(baseURL string) (*memoryMetrics, error) {diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.goindex 479275b4..97aade34 100644--- a/internal/orchestrator/orchestrator.go+++ b/internal/orchestrator/orchestrator.go@@ -612,7 +612,7 @@ func (o *Orchestrator) AllTabs() []bridge.InstanceTab {}o.mu.RUnlock()- var all []bridge.InstanceTab+ all := make([]bridge.InstanceTab, 0)for _, inst := range instances {tabs, err := o.fetchTabs(inst.URL)if err != nil {@@ -640,7 +640,7 @@ func (o *Orchestrator) AllMetrics() []types.InstanceMetrics {}o.mu.RUnlock()- var all []types.InstanceMetrics+ all := make([]types.InstanceMetrics, 0)for _, inst := range instances {mem, err := o.fetchMetrics(inst.URL)if err != nil || mem == nil {