hermes-agent/web/src/components/ToolsetConfigDrawer.tsx
Teknium 875aa8f162
feat(dashboard): unify multi-profile management — one machine dashboard, global profile switcher (#44007)
* feat(dashboard): unify multi-profile management — one machine dashboard, global profile switcher

The dashboard becomes a machine-level management surface with one
write-target selector, replacing per-profile dashboard fragmentation.

Backend:
- profile param (query or body) on /api/config (get/put/raw), /api/env
  (get/put/delete/reveal), /api/mcp/servers (list/add/remove/test/enabled),
  /api/mcp/catalog (list/install), /api/model/info, /api/model/set —
  all scoped through the existing _profile_scope() context manager
- model/set restructured: expensive-model warning (await) runs before the
  scope; the config write runs sync inside the scope in a worker thread
- MCP catalog installs + git-bootstrap entries spawn 'hermes -p <profile>'
- chat PTY: ?profile= on /api/pty points the child's HERMES_HOME at the
  profile dir (its own gateway subprocess, config/skills/memory/state.db
  all profile-bound); in-process gateway attach skipped when scoped

CLI launch unification:
- '<profile> dashboard' routes to the machine dashboard: attach (open
  browser at ?profile=) when one is listening, else re-exec pinned to the
  default profile with --open-profile preselecting the launcher
- --isolated preserves the old dedicated per-profile server behavior
- start_server(initial_profile=...) appends ?profile= to the auto-open URL

Frontend:
- ProfileProvider + sidebar ProfileSwitcher: ONE global selector, URL-
  persisted (?profile=), mirrored into fetchJSON which auto-appends the
  param to the scoped endpoint families (explicit params win)
- app-wide amber banner names the managed profile
- SkillsPage's page-local selector (from the skills-scoping PR) folded
  into the global context — single source of truth
- ChatPage threads the scope into the PTY WS URL; switching profiles
  remounts the terminal into a fresh scoped session

Omitted profile keeps legacy behavior everywhere.

* docs(dashboard): document machine-level multi-profile management

- web-dashboard.md: 'Managing multiple profiles' section (switcher, URL
  deep-links, unified launch, --isolated, scoped Chat, what stays
  per-profile) + --isolated in the options table
- profiles.md: 'From the dashboard' subsection + set-as-active vs
  switcher clarification
- cli-commands.md: --isolated flag + profile-alias launch example

* fix(dashboard): address profile-unification review findings

Review findings (dev review on PR #44007):

1. HIGH — stale page state on profile switch: pages load data on mount
   and didn't consume the profile scope, so a page opened under profile A
   kept showing A's state while writes silently targeted the newly
   selected B. Fixed structurally: ProfileKeyedRoutes wraps the routed
   page tree and keys it by the selected profile, remounting every page
   (fresh state + refetch) on switch. ChatPage keeps its own remount
   (channel keyed on scopedProfile).

2. HIGH — /api/model/auxiliary read was unscoped while /api/model/set
   wrote scoped (Models page could show default's aux pins while editing
   worker's). Endpoint now takes profile + _profile_scope, added to
   PROFILE_SCOPED_PREFIXES, HTTPException re-raise so ghost profiles 404
   instead of 500. Regression test asserts read/write symmetry with
   differing worker/default aux config.

3. MEDIUM — tools post-setup spawned unscoped from the profile-aware
   drawer. Now spawns 'hermes -p <profile> tools post-setup <key>'
   (same mechanism as hub installs); drawer threads its profile prop.
   Most hooks install machine-level artifacts where the scope is inert,
   but hooks reading config/env now see the drawer's HERMES_HOME.

4. LOW — ty warnings: env Optional asserts before subscript/membership,
   fastapi import replaced with web_server.HTTPException re-use.

298 tests green across the four affected suites; tsc -b + vite build
green; aux scoping E2E-verified with real imports.

* fix(dashboard): address second profile-unification review (gille)

1. BLOCKER — profile scope dropped on sidebar navigation: ProfileProvider
   derived the selection from the current URL, and nav links are bare
   paths, so clicking Config from /skills?profile=worker silently reset
   the write target. State is now the source of truth; an effect
   re-asserts ?profile= onto the new location after every navigation
   (URL stays a synchronized projection for deep links/refresh), and an
   incoming URL param (e.g. 'Manage skills & tools' links) still wins.

2. BLOCKER — /api/model/options unscoped while model/set wrote scoped:
   the picker context (current model/provider, custom providers,
   per-profile .env auth state) now loads inside _profile_scope; added
   to PROFILE_SCOPED_PREFIXES. Test: a worker-only current-model pin
   appears in the scoped payload and not the unscoped one.

3. BLOCKER — MCP test-server probe escaped the scope after the config
   read: the probe now re-enters _profile_scope inside the worker thread
   so env-placeholder expansion resolves against the selected profile's
   .env. Known limit (documented): the probe's dedicated MCP event-loop
   thread doesn't inherit the contextvar (OAuth token paths). Test
   asserts get_hermes_home() inside the probe == the worker profile dir.

4. BLOCKER — broad excepts swallowed unknown-profile 404s: /api/model/info
   degraded to 200-with-empty-model-info and /api/mcp/catalog to a
   silently-empty catalog. Both re-raise HTTPException; 404 regression
   tests added for info/options/catalog.

Polish: scope banner clears the fixed mobile header (mt-14 lg:mt-0);
--open-profile hidden via argparse.SUPPRESS (internal re-exec flag);
attach-path test now asserts the opened ?profile= URL.

(Stale-page-state + /api/model/auxiliary findings from this review were
already fixed in 92bcd1568 — the review ran against e600f6951.)

35 tests in the two new suites + 274 in the adjacent ones, all green;
tsc -b + vite build green; scoping E2E-verified with real imports.

* docs(dashboard)+fix: self-review pass — Profiles page section, REST profile-param tip, body-beats-query precedence

Docs:
- web-dashboard.md: add the missing 'Profiles' subsection to Pages
  (cards, create/builder, manage-skills jump, set-as-active vs switcher
  distinction, editors); REST API section gets a profile-scoped-endpoints
  tip documenting ?profile= / body profile / 404 semantics / /api/pty
- (profiles.md + cli-commands.md were already updated in e600f6951)

Precedence fix: scoped endpoints taking BOTH a query param and a body
field now resolve body.profile first. The SPA's fetchJSON injects the
query param from the GLOBAL switcher; an explicit body.profile (e.g.
Profile Builder flows writing into a specific new profile) is the more
specific intent and must not be overridden by whatever the sidebar
happens to be set to. Matches the documented 'explicit beats global'
contract in api.ts.

Verified: 304 tests green across the four suites; tsc -b + vite build
green; docusaurus build green (only pre-existing broken-link warnings,
none from this PR's pages).
2026-06-11 03:29:33 -07:00

451 lines
17 KiB
TypeScript

import { useCallback, useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { Check, ExternalLink, Loader2, Terminal, X } from "lucide-react";
import { api } from "@/lib/api";
import type {
ToolsetConfig,
ToolsetInfo,
ToolsetProvider,
} from "@/lib/api";
import { useToast } from "@nous-research/ui/hooks/use-toast";
import { Button } from "@nous-research/ui/ui/components/button";
import { Input } from "@nous-research/ui/ui/components/input";
import { Label } from "@nous-research/ui/ui/components/label";
import { Badge } from "@nous-research/ui/ui/components/badge";
import { Switch } from "@nous-research/ui/ui/components/switch";
import { Spinner } from "@nous-research/ui/ui/components/spinner";
import { Toast } from "@nous-research/ui/ui/components/toast";
import { cn, themedBody } from "@/lib/utils";
interface Props {
/** The toolset whose backends are being configured. */
toolset: ToolsetInfo;
/** Optional profile to scope config reads/writes to (Skills page profile
* selector). Omitted = the dashboard process's own profile. */
profile?: string;
onClose: () => void;
/** Called after a toggle/provider/key change so the parent grid refreshes. */
onChanged: () => void;
}
/**
* Full configuration surface for a single toolset's backends — the dashboard
* equivalent of selecting a toolset in the `hermes tools` curses UI: toggle
* the toolset on/off, pick a provider, enter API keys, and run a provider's
* post-setup install hook (npm/pip/binary) with a live log tail.
*/
export function ToolsetConfigDrawer({ toolset, profile, onClose, onChanged }: Props) {
const { toast, showToast } = useToast();
const [config, setConfig] = useState<ToolsetConfig | null>(null);
const [loading, setLoading] = useState(true);
const [enabled, setEnabled] = useState(toolset.enabled);
const [toggling, setToggling] = useState(false);
const [selecting, setSelecting] = useState<string | null>(null);
const [activeProvider, setActiveProvider] = useState<string | null>(null);
// Per-env-var draft input values, keyed by env var name.
const [drafts, setDrafts] = useState<Record<string, string>>({});
const [savingProvider, setSavingProvider] = useState<string | null>(null);
const [isSet, setIsSet] = useState<Record<string, boolean>>({});
// Post-setup install log tail state.
const [postSetupRunning, setPostSetupRunning] = useState(false);
const [postSetupLog, setPostSetupLog] = useState<string[]>([]);
const [postSetupKey, setPostSetupKey] = useState<string | null>(null);
// Bumped each time a post-setup is kicked off, to (re)trigger the poll
// effect below. Mirrors the SkillsPage HubBrowser action-poll pattern so
// the recursive timer lives inside the effect (lint-clean — no ref
// mutation, no self-referencing memo).
const [postSetupTrigger, setPostSetupTrigger] = useState(0);
const loadConfig = useCallback(() => {
// Promise-chain shape (not async/await with a leading synchronous
// setLoading) so callers in a useEffect don't trip
// react-hooks/set-state-in-effect — setState only fires inside the
// async .then/.catch/.finally callbacks.
return api
.getToolsetConfig(toolset.name, profile)
.then((cfg) => {
setConfig(cfg);
setActiveProvider(cfg.active_provider);
const seed: Record<string, boolean> = {};
for (const p of cfg.providers) {
for (const e of p.env_vars) seed[e.key] = e.is_set;
}
setIsSet(seed);
})
.catch(() => showToast("Failed to load toolset config", "error"))
.finally(() => setLoading(false));
}, [toolset.name, profile, showToast]);
useEffect(() => {
void loadConfig();
}, [loadConfig]);
// Poll the post-setup action's log until it exits. Driven by
// postSetupTrigger; the recursive timer + cleanup live entirely inside the
// effect (matches the SkillsPage HubBrowser pattern — lint-clean).
useEffect(() => {
if (postSetupTrigger === 0) return;
let cancelled = false;
let timer: ReturnType<typeof setTimeout> | null = null;
const poll = async () => {
try {
const st = await api.getActionStatus("tools-post-setup", 300);
if (cancelled) return;
setPostSetupLog(st.lines);
if (st.running) {
timer = setTimeout(() => void poll(), 1200);
} else {
setPostSetupRunning(false);
const ok = st.exit_code === 0;
showToast(
ok ? "Post-setup complete" : "Post-setup finished with errors",
ok ? "success" : "error",
);
// Refresh — a backend may now report itself configured/available.
void loadConfig();
onChanged();
}
} catch {
if (!cancelled) {
setPostSetupRunning(false);
showToast("Lost track of the post-setup process", "error");
}
}
};
// Small delay so the spawned action has a log file to read.
timer = setTimeout(() => void poll(), 800);
return () => {
cancelled = true;
if (timer) clearTimeout(timer);
};
}, [postSetupTrigger, showToast, loadConfig, onChanged]);
const handleToggle = async (next: boolean) => {
setToggling(true);
try {
await api.toggleToolset(toolset.name, next, profile);
setEnabled(next);
showToast(
`${toolset.label || toolset.name} ${next ? "enabled" : "disabled"}`,
"success",
);
onChanged();
} catch {
showToast("Failed to toggle toolset", "error");
} finally {
setToggling(false);
}
};
const handleSelectProvider = async (provider: ToolsetProvider) => {
setSelecting(provider.name);
try {
await api.selectToolsetProvider(toolset.name, provider.name, profile);
setActiveProvider(provider.name);
showToast(`Provider set to ${provider.name}`, "success");
onChanged();
} catch (e) {
showToast(
e instanceof Error ? e.message : "Failed to select provider",
"error",
);
} finally {
setSelecting(null);
}
};
const handleSaveKeys = async (provider: ToolsetProvider) => {
const env: Record<string, string> = {};
for (const e of provider.env_vars) {
const v = drafts[e.key];
if (v && v.trim()) env[e.key] = v.trim();
}
if (Object.keys(env).length === 0) {
showToast("Enter at least one value to save", "error");
return;
}
setSavingProvider(provider.name);
try {
const res = await api.saveToolsetEnv(toolset.name, env, profile);
setIsSet((prev) => ({ ...prev, ...res.is_set }));
// Clear saved drafts so the inputs reset to the "saved" placeholder.
setDrafts((prev) => {
const next = { ...prev };
for (const k of res.saved) delete next[k];
return next;
});
showToast(
res.saved.length
? `Saved ${res.saved.length} key${res.saved.length > 1 ? "s" : ""}`
: "Nothing to save",
"success",
);
onChanged();
} catch (e) {
showToast(
e instanceof Error ? e.message : "Failed to save keys",
"error",
);
} finally {
setSavingProvider(null);
}
};
const handleRunPostSetup = async (provider: ToolsetProvider) => {
if (!provider.post_setup) return;
setPostSetupRunning(true);
setPostSetupLog([]);
setPostSetupKey(provider.post_setup);
try {
await api.runToolsetPostSetup(toolset.name, provider.post_setup, profile);
// Bump the trigger so the poll effect (re)starts tailing the log.
setPostSetupTrigger((n) => n + 1);
} catch (e) {
setPostSetupRunning(false);
showToast(
e instanceof Error ? e.message : "Failed to start post-setup",
"error",
);
}
};
const labelText = toolset.label?.trim() || toolset.name;
return createPortal(
<div
className="fixed inset-0 z-[100] flex items-center justify-center bg-background/85 backdrop-blur-sm p-4"
onMouseDown={(e) => {
if (e.target === e.currentTarget) onClose();
}}
>
<div
className={cn(
themedBody,
"relative w-full max-w-2xl max-h-[85vh] border border-border bg-card shadow-2xl flex flex-col",
)}
>
<Button
ghost
size="xs"
className="absolute right-2 top-2 text-muted-foreground hover:text-foreground"
onClick={onClose}
aria-label="Close"
>
<X />
</Button>
{/* Header — toolset identity + enable toggle */}
<header className="p-5 pb-3 border-b border-border">
<div className="flex items-center gap-3 pr-8">
<span className="font-mondwest text-display text-base tracking-wider">
{labelText}
</span>
<Badge tone={enabled ? "success" : "outline"} className="text-xs">
{enabled ? "Active" : "Inactive"}
</Badge>
</div>
<p className="text-xs text-muted-foreground mt-1">
{toolset.description}
</p>
<div className="mt-3 flex items-center gap-2">
<Switch
checked={enabled}
onCheckedChange={(v) => void handleToggle(v)}
disabled={toggling}
aria-label="Enable toolset"
/>
<span className="text-xs text-muted-foreground">
{enabled ? "Enabled for the agent" : "Disabled"}
</span>
</div>
</header>
{/* Body — provider matrix */}
<div className="flex-1 min-h-0 overflow-y-auto p-5 pt-4 space-y-4">
{loading ? (
<div className="flex items-center justify-center py-10">
<Spinner />
</div>
) : !config?.has_category ? (
<p className="text-sm text-muted-foreground py-6 text-center">
This toolset has no configurable backends toggle it on or off
above. It works with no provider selection or API keys.
</p>
) : config.providers.length === 0 ? (
<p className="text-sm text-muted-foreground py-6 text-center">
No providers are available for this toolset in this install.
</p>
) : (
config.providers.map((provider) => {
const isActive = provider.name === activeProvider;
return (
<div
key={provider.name}
className={cn(
"border border-border p-3",
isActive && "border-emerald-500/60 bg-emerald-500/5",
)}
>
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2 min-w-0">
<span className="font-medium text-sm">
{provider.name}
</span>
{provider.badge && (
<Badge tone="secondary" className="text-xs">
{provider.badge}
</Badge>
)}
{provider.requires_nous_auth && (
<Badge tone="outline" className="text-xs">
Nous Portal
</Badge>
)}
</div>
{isActive ? (
<Badge tone="success" className="text-xs shrink-0">
<Check className="h-3 w-3 mr-0.5" /> Selected
</Badge>
) : (
<Button
size="xs"
outlined
onClick={() => void handleSelectProvider(provider)}
disabled={selecting !== null}
>
{selecting === provider.name ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
"Select"
)}
</Button>
)}
</div>
{provider.tag && (
<p className="text-xs text-muted-foreground mt-1">
{provider.tag}
</p>
)}
{/* API key inputs */}
{provider.env_vars.length > 0 && (
<div className="mt-3 space-y-2.5">
{provider.env_vars.map((ev) => (
<div key={ev.key} className="space-y-1">
<div className="flex items-center justify-between gap-2">
<Label
htmlFor={`env-${ev.key}`}
className="text-xs font-mono"
>
{ev.key}
</Label>
{isSet[ev.key] && (
<Badge tone="success" className="text-xs">
Saved
</Badge>
)}
</div>
<Input
id={`env-${ev.key}`}
type="password"
className="h-8 rounded-none text-xs font-mono"
placeholder={
isSet[ev.key]
? "•••••••• (saved — leave blank to keep)"
: ev.prompt || ev.key
}
value={drafts[ev.key] ?? ""}
onChange={(e) =>
setDrafts((prev) => ({
...prev,
[ev.key]: e.target.value,
}))
}
/>
{ev.url && (
<a
href={ev.url}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
>
<ExternalLink className="h-3 w-3" /> Get a key
</a>
)}
</div>
))}
<Button
size="xs"
onClick={() => void handleSaveKeys(provider)}
disabled={savingProvider !== null}
>
{savingProvider === provider.name ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
"Save keys"
)}
</Button>
</div>
)}
{/* Post-setup install hook */}
{provider.post_setup && (
<div className="mt-3 border-t border-border pt-3">
<p className="text-xs text-muted-foreground mb-1.5">
This backend needs a one-time install
{" "}
<span className="font-mono">
({provider.post_setup})
</span>
. Runs on this host may take a few minutes.
</p>
<Button
size="xs"
outlined
onClick={() => void handleRunPostSetup(provider)}
disabled={postSetupRunning}
>
{postSetupRunning &&
postSetupKey === provider.post_setup ? (
<>
<Loader2 className="h-3 w-3 animate-spin mr-1" />
Installing
</>
) : (
<>
<Terminal className="h-3 w-3 mr-1" /> Run setup
</>
)}
</Button>
</div>
)}
</div>
);
})
)}
{/* Post-setup live log */}
{(postSetupRunning || postSetupLog.length > 0) && (
<div className="border border-border">
<div className="flex items-center gap-2 px-3 py-1.5 border-b border-border bg-muted/30">
<Terminal className="h-3.5 w-3.5 text-muted-foreground" />
<span className="text-xs font-mono text-muted-foreground">
post-setup: {postSetupKey}
</span>
{postSetupRunning && (
<Loader2 className="h-3 w-3 animate-spin ml-auto text-muted-foreground" />
)}
</div>
<pre className="max-h-48 overflow-y-auto p-3 text-xs font-mono whitespace-pre-wrap text-text-secondary">
{postSetupLog.length ? postSetupLog.join("\n") : "Starting…"}
</pre>
</div>
)}
</div>
</div>
<Toast toast={toast} />
</div>,
document.body,
);
}