Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(desktop): a real plugin manager — browse, install, set up, configure, update, remove
Salman Qureshi4228dd4960f9
diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.tsindex 385e9845..989df107 100644--- a/apps/desktop/src/api/mercury.ts+++ b/apps/desktop/src/api/mercury.ts@@ -99,11 +99,16 @@ export const bots = {export const plugins = {list: (refresh = false) => http.get<{ items: PluginItem[]; catalogError?: string; stale: boolean; safeMode: boolean }>(`/api/plugins${refresh ? "?refresh=1" : ""}`),- install: (source: string) => http.post<{ id: string; name: string; version: string }>("/api/plugins/install", { source }),+ install: (source: string, opts: { enable?: boolean; force?: boolean } = {}) =>+ http.post<{ id: string; name: string; version: string; unchanged?: boolean; tier?: string; verified?: boolean }>("/api/plugins/install", { source, ...opts }),+ /** Full detail: settings with values (secrets as isSet), groups, what's missing. */+ info: (id: string) => http.get<{ plugin: PluginItem | null }>(`/api/plugins/${encodeURIComponent(id)}`).then((r) => r.plugin),+ setSetting: (id: string, key: string, value: unknown) => http.post<{ ok: boolean }>(`/api/plugins/${encodeURIComponent(id)}/settings`, { key, value }),+ rollback: (id: string) => http.post<{ from: string; to: string }>(`/api/plugins/${encodeURIComponent(id)}/rollback`),enable: (id: string) => http.post<{ ok: boolean }>(`/api/plugins/${encodeURIComponent(id)}/enable`),disable: (id: string) => http.post<{ ok: boolean }>(`/api/plugins/${encodeURIComponent(id)}/disable`),update: (id: string) => http.post<{ changed: Array<{ id: string; from: string; to: string }> }>(`/api/plugins/${encodeURIComponent(id)}/update`),- uninstall: (id: string) => http.delete<{ ok: boolean }>(`/api/plugins/${encodeURIComponent(id)}`),+ uninstall: (id: string, purge = false) => http.delete<{ ok: boolean }>(`/api/plugins/${encodeURIComponent(id)}${purge ? "?purge=1" : ""}`),};export const mcp = {diff --git a/apps/desktop/src/api/types.ts b/apps/desktop/src/api/types.tsindex c8744be4..2d93c942 100644--- a/apps/desktop/src/api/types.ts+++ b/apps/desktop/src/api/types.ts@@ -225,14 +225,25 @@ export interface BotActivityEvent {// ── Plugins / MCP / Skills ──export type PluginStatus = "available" | "installed" | "enabled" | "disabled" | "update-available" | "incompatible" | "error";+/** A setting a plugin declares (from GET /api/plugins/:id). Secrets never carry a value, only isSet. */export interface PluginSetting {key: string;- label: string;- type: string;- value?: unknown;+ type: "string" | "number" | "boolean" | "enum" | "secret";+ label?: string;description?: string;- secret?: boolean;+ value?: unknown;+ options?: string[];+ optionLabels?: Record<string, string>;+ examples?: string[];+ format?: "text" | "phone";+ required?: boolean;+ /** Asked during setup (right after install), in declaration order. */+ setup?: boolean;+ /** Only asked during setup while this requirement is missing (e.g. "provider:openai"). */+ setupWhenMissing?: string;+ isSet?: boolean;group?: string;+ when?: Record<string, string | string[]> | Array<Record<string, string | string[]>>;}export interface PluginItem {@@ -243,6 +254,8 @@ export interface PluginItem {tier: "official" | "community" | "local";status: PluginStatus;installedVersion?: string;+ /** The version rollback goes back to, when it's still on disk. */+ previousVersion?: string;latestVersion?: string;sizeBytes?: number;enabled: boolean;@@ -250,8 +263,12 @@ export interface PluginItem {verified: boolean;tools: string[];commands: string[];- permissions?: { network: string[]; secrets: string[] };+ permissions?: { network: string[]; secrets: string[]; desktop?: boolean; providers?: Record<string, { unlocks?: string }> };disabled?: { code: string; message: string; at: string };+ /** Menu sections, with whether each is ready. */+ settingGroups?: Array<{ id: string; label: string; description?: string; ready: boolean }>;+ /** Optional providers or keys that aren't set up: what's off, and how to fix it. */+ missing?: Array<{ key: string; unlocks: string; needs: string; fix: string }>;lastError?: string;incompatibleReason?: string;settings?: PluginSetting[];diff --git a/apps/desktop/src/views/plugins/PluginDetail.tsx b/apps/desktop/src/views/plugins/PluginDetail.tsxnew file mode 100644index 00000000..28eda8c8--- /dev/null+++ b/apps/desktop/src/views/plugins/PluginDetail.tsx@@ -0,0 +1,241 @@+import { AlertTriangle, ArrowUpCircle, Download, Globe, KeyRound, ListChecks, Monitor, RotateCcw, Sparkles, Trash2, Wrench } from "lucide-react";+import { useCallback, useEffect, useState } from "react";+import * as api from "~/api/mercury";+import type { PluginItem, PluginSetting } from "~/api/types";+import { Button } from "~/components/ui/Button";+import { Switch } from "~/components/ui/Switch";+import { Badge, Mono, Spinner } from "~/components/ui/bits";+import { ConfirmButton, IconTile } from "~/components/ui/kit";+import { cx } from "~/lib/cx";+import { ChannelPanel } from "./ChannelPanel";+import { applies, SettingField } from "./SettingField";+import { needsSetup, setupKeys } from "./SetupFlow";++/**+ * One plugin, everything about it on one page: on or off; what needs+ * attention and how to fix it; setup again; the account it's linked to;+ * every setting, in the plugin's own sections; what it can reach (sites,+ * keys, the screen) and what it adds (tools, commands); update, roll back,+ * remove (with or without its data).+ */++function errorText(e: unknown): string {+ return e instanceof Error ? e.message : String(e);+}++function size(bytes?: number): string {+ if (!bytes) return "";+ return bytes > 1048576 ? `${(bytes / 1048576).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`;+}++export function StatusDot({ on, className }: { on: boolean; className?: string }) {+ return <span className={cx("inline-block h-2.5 w-2.5 shrink-0 rounded-full", on ? "bg-accent" : "bg-ink/25", className)} aria-label={on ? "On" : "Off"} />;+}++export function PluginDetail({ id, onSetup, onChanged, onRemoved }: { id: string; onSetup: () => void; onChanged: () => void; onRemoved: () => void }) {+ const [p, setP] = useState<PluginItem | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState<string | null>(null);+ const [note, setNote] = useState<{ text: string; ok: boolean } | null>(null);+ const [purge, setPurge] = useState(false);++ const load = useCallback(async () => {+ try { setP(await api.plugins.info(id)); setError(null); } catch (e) { setError(errorText(e)); }+ }, [id]);+ useEffect(() => { setP(null); setNote(null); void load(); }, [load]);++ async function run(key: string, fn: () => Promise<unknown>, done?: string) {+ setBusy(key);+ setNote(null);+ try { await fn(); if (done) setNote({ text: done, ok: true }); await load(); onChanged(); } catch (e) { setNote({ text: errorText(e), ok: false }); } finally { setBusy(null); }+ }++ async function saveSetting(key: string, value: unknown) {+ await api.plugins.setSetting(id, key, value);+ await load();+ onChanged();+ }++ if (error && !p) return <p className="p-6 text-sm text-red">{error}{/only|local|this computer/i.test(error) ? "" : ""}</p>;+ if (!p) return <div className="p-6"><Spinner size={16} /></div>;++ const all = p.settings ?? [];+ const shown = all.filter((s) => applies(s, all));+ const groups = p.settingGroups ?? [];+ const loose = shown.filter((s) => !s.group || !groups.some((g) => g.id === s.group));+ const problem = p.lastError || p.disabled?.message || p.incompatibleReason;+ const attention = needsSetup(p);+ const hasSetup = setupKeys(p).length > 0 || (!!p.channel && p.channel.type !== "desktop");+ const updatable = p.status === "update-available";++ return (+ <div className="flex flex-col gap-6 px-6 py-6">+ <div className="flex items-start gap-4">+ <IconTile id={p.id} label={p.name} size={48} />+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <h2 className="text-lg font-semibold text-ink">{p.name}</h2>+ <Mono>{p.installedVersion}</Mono>+ {p.tier === "official" && <Badge tone="accent">official</Badge>}+ {p.tier === "local" && <Badge>local</Badge>}+ {p.verified && p.tier !== "official" && <Badge>verified</Badge>}+ </div>+ <p className="mt-1 text-sm leading-relaxed text-ink2">{p.description}</p>+ </div>+ <div className="flex shrink-0 flex-col items-end gap-1">+ <div className="flex items-center gap-2">+ {busy === "toggle" && <Spinner size={12} />}+ <StatusDot on={p.enabled} />+ <Switch checked={p.enabled} disabled={busy !== null || (p.status === "incompatible" && !p.enabled)}+ onCheckedChange={(v) => void run("toggle", () => (v ? api.plugins.enable(id) : api.plugins.disable(id)), v ? `${p.name} is on.` : `${p.name} is off.`)} label={p.enabled ? "On" : "Off"} />+ </div>+ {p.enabled && !p.running && !problem && <span className="text-2xs text-ink4">on · runs in the background service</span>}+ </div>+ </div>++ {note && <p className={cx("text-sm", note.ok ? "text-accent" : "text-red")}>{note.text}</p>}++ {(problem || attention || (p.missing ?? []).length > 0) && (+ <section className="flex flex-col gap-2 rounded-xl border border-amber/40 bg-amber/[0.05] p-4">+ <div className="flex items-center gap-2 text-sm font-medium text-ink"><AlertTriangle size={15} className="text-amber" /> Needs your attention</div>+ {problem && <p className="text-sm text-ink2">{problem}</p>}+ {attention && <p className="text-sm text-ink2">Some required settings aren't filled in yet.</p>}+ {(p.missing ?? []).map((m) => (+ <p key={m.key} className="text-sm text-ink2"><span className="text-ink">{m.unlocks}</span> is off: it needs {m.needs}. <span className="text-ink3">{m.fix}</span></p>+ ))}+ {hasSetup && <div><Button size="sm" variant="primary" onClick={onSetup}><ListChecks size={13} /> Run setup</Button></div>}+ </section>+ )}++ {updatable && (+ <section className="flex items-center gap-3 rounded-xl border border-cyan/40 bg-cyan/[0.05] px-4 py-3">+ <ArrowUpCircle size={16} className="text-cyan" />+ <span className="flex-1 text-sm text-ink2">Version {p.latestVersion} is available.</span>+ <Button size="sm" variant="primary" loading={busy === "update"} onClick={() => void run("update", () => api.plugins.update(id), `Updated to ${p.latestVersion}.`)}>Update</Button>+ </section>+ )}++ {p.channel && p.channel.type !== "desktop" && (+ <Section title="Account" hint="The account Mercury talks through.">+ {p.enabled ? <ChannelPanel id={id} name={p.name} /> : <p className="text-sm text-ink3">Turn {p.name} on to link an account.</p>}+ </Section>+ )}++ {shown.length > 0 && (+ <Section title="Settings" hint="Changes apply at once; the plugin restarts if it needs to." action={hasSetup && !attention ? <Button size="sm" variant="ghost" onClick={onSetup}><Sparkles size={13} /> Run setup again</Button> : null}>+ <div className="flex flex-col gap-4">+ {groups.map((g) => {+ const fields = shown.filter((s) => s.group === g.id);+ if (!fields.length) return null;+ return (+ <div key={g.id} className="flex flex-col gap-4 rounded-xl border border-line p-4">+ <div>+ <div className="flex items-center gap-2"><span className="text-sm font-medium text-ink">{g.label.replace(/^[^\p{L}\p{N}]+/u, "")}</span><Badge tone={g.ready ? "accent" : "amber"}>{g.ready ? "ready" : "needs setup"}</Badge></div>+ {g.description && <p className="text-xs text-ink3">{g.description}</p>}+ </div>+ {fields.map((s) => <SettingField key={s.key} s={s} onSave={(v) => saveSetting(s.key, v)} />)}+ </div>+ );+ })}+ {loose.length > 0 && (+ <div className="flex flex-col gap-4 rounded-xl border border-line p-4">+ {groups.length > 0 && <span className="text-sm font-medium text-ink">General</span>}+ {orderLoose(loose).map((s) => <SettingField key={s.key} s={s} onSave={(v) => saveSetting(s.key, v)} />)}+ </div>+ )}+ </div>+ </Section>+ )}++ <Section title="What it can do and reach">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">+ <Fact icon={<Wrench size={13} />} title={`${p.tools.length} tool${p.tools.length === 1 ? "" : "s"}${p.commands.length ? ` · ${p.commands.length} command${p.commands.length === 1 ? "" : "s"}` : ""}`}+ body={[...p.tools.map((t) => t.replace(/^[^_]+__/, "")), ...p.commands].join(", ") || "None"} />+ <Fact icon={<Globe size={13} />} title="Internet" body={p.permissions?.network?.length ? p.permissions.network.join(", ") : "No internet access"} />+ <Fact icon={<KeyRound size={13} />} title="Keys it can read" body={p.permissions?.secrets?.length ? p.permissions.secrets.join(", ") : "None"} />+ <Fact icon={<Monitor size={13} />} title="Runs" body={`${p.kind === "in-process" ? "Inside Mercury" : "In its own process"}${p.permissions?.desktop ? " · uses this computer's screen, mouse and keyboard" : ""}${p.sizeBytes ? ` · ${size(p.sizeBytes)}` : ""}`} />+ </div>+ </Section>++ <Section title="Version and removal">+ <div className="flex flex-col gap-3">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-sm text-ink2">Installed <Mono>{p.installedVersion}</Mono>{p.latestVersion && p.latestVersion !== p.installedVersion ? <> · catalog <Mono>{p.latestVersion}</Mono></> : null}</span>+ <span className="flex-1" />+ {p.previousVersion && (+ <ConfirmButton size="sm" variant="ghost" confirmLabel={`Go back to ${p.previousVersion}?`} loading={busy === "rollback"}+ onConfirm={() => void run("rollback", async () => { const r = await api.plugins.rollback(id); setNote({ text: `Rolled back from ${r.from} to ${r.to}.`, ok: true }); })}>+ <RotateCcw size={13} /> Roll back to {p.previousVersion}+ </ConfirmButton>+ )}+ </div>+ <div className="flex flex-wrap items-center gap-3 rounded-lg border border-red/25 bg-red/[0.03] px-3 py-2.5">+ <Trash2 size={14} className="text-red" />+ <span className="flex-1 text-sm text-ink2">Remove {p.name}</span>+ <label className="flex items-center gap-1.5 text-xs text-ink3"><input type="checkbox" checked={purge} onChange={(e) => setPurge(e.target.checked)} className="accent-[var(--red,#d14)]" /> also delete its data and settings</label>+ <ConfirmButton size="sm" variant="ghost" confirmLabel={purge ? "Remove with data?" : "Remove?"} loading={busy === "remove"} onConfirm={() => void (async () => {+ setBusy("remove");+ try { await api.plugins.uninstall(id, purge); onRemoved(); } catch (e) { setNote({ text: errorText(e), ok: false }); setBusy(null); }+ })()}>Remove</ConfirmButton>+ </div>+ </div>+ </Section>+ </div>+ );+}++/** Ungrouped settings: setup ones first (they matter most), in the plugin's order. */+function orderLoose(list: PluginSetting[]): PluginSetting[] {+ return [...list.filter((s) => s.setup), ...list.filter((s) => !s.setup)];+}++function Section({ title, hint, action, children }: { title: string; hint?: string; action?: React.ReactNode; children: React.ReactNode }) {+ return (+ <section className="flex flex-col gap-3">+ <div className="flex items-end justify-between gap-3">+ <div><h3 className="text-sm font-semibold text-ink">{title}</h3>{hint && <p className="text-xs text-ink3">{hint}</p>}</div>+ {action}+ </div>+ {children}+ </section>+ );+}++function Fact({ icon, title, body }: { icon: React.ReactNode; title: string; body: string }) {+ return (+ <div className="rounded-lg border border-line px-3 py-2.5">+ <div className="flex items-center gap-1.5 text-xs font-medium text-ink2">{icon}{title}</div>+ <p className="mt-0.5 break-words font-mono text-xs text-ink3">{body}</p>+ </div>+ );+}++/** A plugin from the catalog, before installing: what it is, what it can reach, Install. */+export function CatalogDetail({ p, installing, onInstall }: { p: PluginItem; installing: boolean; onInstall: () => void }) {+ const incompatible = p.status === "incompatible";+ return (+ <div className="flex flex-col gap-6 px-6 py-6">+ <div className="flex items-start gap-4">+ <IconTile id={p.id} label={p.name} size={48} />+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <h2 className="text-lg font-semibold text-ink">{p.name}</h2>+ <Mono>{p.latestVersion}</Mono>+ {p.tier === "official" ? <Badge tone="accent">official</Badge> : <Badge>community</Badge>}+ </div>+ <p className="mt-1 text-sm leading-relaxed text-ink2">{p.description}</p>+ </div>+ <Button size="md" variant="primary" loading={installing} disabled={incompatible} onClick={onInstall}><Download size={14} /> {installing ? "Installing…" : "Install"}</Button>+ </div>+ {incompatible && <p className="rounded-lg border border-amber/40 bg-amber/[0.05] px-3 py-2 text-sm text-ink2">{p.incompatibleReason ?? "Not compatible with this Mercury or computer."}</p>}+ <Section title="What it can do and reach" hint="From the catalog. You'll set it up right after installing.">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">+ <Fact icon={<Wrench size={13} />} title={`${p.tools.length} tool${p.tools.length === 1 ? "" : "s"}`} body={p.tools.map((t) => t.replace(/^[^_]+__/, "")).join(", ") || "None listed"} />+ <Fact icon={<Globe size={13} />} title="Internet" body={p.permissions?.network?.length ? p.permissions.network.join(", ") : "No internet access"} />+ <Fact icon={<KeyRound size={13} />} title="Keys it can read" body={p.permissions?.secrets?.length ? p.permissions.secrets.join(", ") : "None"} />+ <Fact icon={<Monitor size={13} />} title="Runs" body={`${p.kind === "in-process" ? "Inside Mercury" : "In its own process"}${p.sizeBytes ? ` · ${size(p.sizeBytes)} download` : ""}`} />+ </div>+ </Section>+ </div>+ );+}diff --git a/apps/desktop/src/views/plugins/PluginsView.tsx b/apps/desktop/src/views/plugins/PluginsView.tsxindex 52d318d3..0d3ee2d5 100644--- a/apps/desktop/src/views/plugins/PluginsView.tsx+++ b/apps/desktop/src/views/plugins/PluginsView.tsx@@ -1,24 +1,41 @@-import { RefreshCw } from "lucide-react";-import { useEffect, useMemo, useState } from "react";+import { AlertTriangle, ArrowUpCircle, FolderOpen, Plug, RefreshCw } from "lucide-react";+import { useCallback, useEffect, useMemo, useState } from "react";import * as api from "~/api/mercury";import type { McpServer, PluginItem } from "~/api/types";+import { useUi } from "~/app/store";import { Button } from "~/components/ui/Button";-import { Switch } from "~/components/ui/Switch";-import { Badge, Empty, Mono, Segmented } from "~/components/ui/bits";-import { ConfirmButton, IconTile, ItemRow, PageHeader, SearchField } from "~/components/ui/kit";-import { StateOrb } from "~/components/indicators/StateOrb";import { Input } from "~/components/ui/Input";-import { Dialog } from "~/components/ui/Dialog";-import { useUi } from "~/app/store";-import { ChannelPanel } from "./ChannelPanel";--type Tab = "installed" | "catalog" | "mcp";+import { Badge, Mono, Segmented, Spinner } from "~/components/ui/bits";+import { IconTile, SearchField } from "~/components/ui/kit";+import { cx } from "~/lib/cx";+import { CatalogDetail, PluginDetail, StatusDot } from "./PluginDetail";+import { SetupFlow } from "./SetupFlow";/**- * Plugins: installed, the catalog, MCP servers. One row style across all- * three; one primary action per row that names its state (Install,- * Installing…, Update); on/off separate from Remove, and Remove asks twice.+ * Plugins, as a manager: the list on the left (yours, the catalog to+ * discover, MCP servers), the chosen one on the right. Installing goes+ * straight into the plugin's own setup; every setting, account, version+ * and removal lives on its page. A plain dot says on (green) or off (grey).*/++type Tab = "installed" | "discover" | "mcp";+type Pane = { kind: "plugin"; id: string } | { kind: "catalog"; id: string } | { kind: "setup"; id: string } | { kind: "mcp"; id: string } | { kind: "source" } | null;++function errorText(e: unknown): string {+ return e instanceof Error ? e.message : String(e);+}++/** The one line under a plugin's name: what matters most about it right now. */+function rowLine(p: PluginItem): { text: string; tone: "amber" | "cyan" | "muted" } {+ if (p.lastError || p.status === "error") return { text: p.lastError ?? "Stopped with an error", tone: "amber" };+ if (p.status === "incompatible") return { text: p.incompatibleReason ?? "Not compatible", tone: "amber" };+ if (p.status === "update-available") return { text: `Update to ${p.latestVersion}`, tone: "cyan" };+ if (p.enabled && (p.missing ?? []).length > 0) return { text: `${p.missing!.length} thing${p.missing!.length === 1 ? "" : "s"} to set up`, tone: "amber" };+ if (p.channel && p.channel.type !== "desktop" && p.enabled && p.channel.state !== "connected") return { text: "Account not linked", tone: "amber" };+ if (p.channel?.account) return { text: `Linked · ${p.channel.account}`, tone: "muted" };+ return { text: p.enabled ? `${p.tools.length} tool${p.tools.length === 1 ? "" : "s"}` : "Off", tone: "muted" };+}+export function PluginsView() {const [tab, setTab] = useState<Tab>("installed");const [items, setItems] = useState<PluginItem[]>([]);@@ -26,21 +43,22 @@ export function PluginsView() {const [mcpAvailable, setMcpAvailable] = useState(true);const [safeMode, setSafeMode] = useState(false);const [catalogError, setCatalogError] = useState<string | null>(null);- const [loading, setLoading] = useState(false);- const [busy, setBusy] = useState<string | null>(null);+ const [loaded, setLoaded] = useState(false);+ const [refreshing, setRefreshing] = useState(false);const [query, setQuery] = useState("");- const [source, setSource] = useState("");- const [note, setNote] = useState<string | null>(null);+ const [pane, setPane] = useState<Pane>(null);+ const [installing, setInstalling] = useState<string | null>(null);+ const [note, setNote] = useState<{ text: string; ok: boolean } | null>(null);- async function load(refresh = false) {- setLoading(true);+ const load = useCallback(async (refresh = false) => {+ if (refresh) setRefreshing(true);try {const res = await api.plugins.list(refresh);setItems(res.items);setSafeMode(res.safeMode);setCatalogError(res.catalogError ?? null);} catch (err) {- setNote(err instanceof Error ? err.message : String(err));+ setNote({ text: errorText(err), ok: false });}try {const m = await api.mcp.list();@@ -49,147 +67,186 @@ export function PluginsView() {} catch {setMcpAvailable(false);}- setLoading(false);- }- useEffect(() => { void load(); }, []);+ setLoaded(true);+ setRefreshing(false);+ }, []);+ useEffect(() => { void load(); }, [load]);+ const yours = items.filter((p) => !!p.installedVersion);+ const catalog = items.filter((p) => !p.installedVersion);const q = query.trim().toLowerCase();- const match = (s: string) => !q || s.toLowerCase().includes(q);- const installed = useMemo(() => items.filter((p) => p.status !== "available" && match(`${p.name} ${p.description}`)), [items, q]);- const catalog = useMemo(() => items.filter((p) => p.status === "available" && match(`${p.name} ${p.description}`)), [items, q]);- const mcpShown = useMemo(() => servers.filter((s) => match(`${s.id} ${s.target}`)), [servers, q]);- const updates = items.filter((p) => p.status === "update-available").length;+ const match = (s: string) => !q || q.split(/\s+/).every((w) => s.toLowerCase().includes(w));+ const list = useMemo(() => (tab === "installed" ? yours : tab === "discover" ? catalog : []).filter((p) => match(`${p.name} ${p.id} ${p.description} ${p.tools.join(" ")}`)), [tab, items, q]); // eslint-disable-line react-hooks/exhaustive-deps+ const mcpShown = servers.filter((s) => match(`${s.id} ${s.target}`));+ const updates = yours.filter((p) => p.status === "update-available").length;- const [linking, setLinking] = useState<PluginItem | null>(null);- // Settings → Channels sends WhatsApp here: open its linking panel.+ // Settings → Channels sends WhatsApp here.const focus = useUi((st) => st.pluginFocus);const clearFocus = useUi((st) => st.clearPluginFocus);useEffect(() => {- if (!focus) return;- const target = installed.find((x) => x.id === focus);- if (target) { setLinking(target); clearFocus(); }- }, [focus, installed, clearFocus]);+ if (!focus || !loaded) return;+ if (yours.some((x) => x.id === focus)) { setTab("installed"); setPane({ kind: "plugin", id: focus }); }+ else if (catalog.some((x) => x.id === focus)) { setTab("discover"); setPane({ kind: "catalog", id: focus }); }+ clearFocus();+ }, [focus, loaded]); // eslint-disable-line react-hooks/exhaustive-deps- async function act(key: string, fn: () => Promise<unknown>, done?: string) {+ // Something sensible on the right once the list is in.+ useEffect(() => {+ if (!loaded || pane) return;+ const first = yours[0] ?? catalog[0];+ if (first) { setTab(yours[0] ? "installed" : "discover"); setPane(yours[0] ? { kind: "plugin", id: first.id } : { kind: "catalog", id: first.id }); }+ }, [loaded]); // eslint-disable-line react-hooks/exhaustive-deps++ async function install(source: string, opts: { fromCatalog: boolean }) {+ setInstalling(source);setNote(null);- setBusy(key);- try { await fn(); if (done) setNote(done); } catch (err) { setNote(err instanceof Error ? err.message : String(err)); }- setBusy(null);- void load();+ try {+ const r = await api.plugins.install(source, { enable: true });+ await load();+ setTab("installed");+ setPane({ kind: "setup", id: r.id });+ setNote({ text: r.unchanged ? `${r.name} ${r.version} was already installed.` : `Installed ${r.name} ${r.version}${opts.fromCatalog ? "" : ". It isn't from the catalog, so it hasn't been checked"}.`, ok: true });+ } catch (e) {+ setNote({ text: errorText(e), ok: false });+ } finally {+ setInstalling(null);+ }}- return (- <div className="flex h-full min-h-0 flex-col">- <PageHeader title="Plugins" meta={updates > 0 ? `${updates} update${updates === 1 ? "" : "s"} available` : undefined}>- {safeMode && <Badge tone="amber">safe mode</Badge>}- <Button variant="ghost" size="sm" icon onClick={() => void load(true)} loading={loading} aria-label="Refresh"><RefreshCw size={15} /></Button>- </PageHeader>-- <div className="min-h-0 flex-1 overflow-y-auto">- <div className="mx-auto flex max-w-[820px] flex-col gap-3 px-8 py-6">- <div className="flex items-center gap-3">- <Segmented size="md" value={tab} onChange={setTab} options={[- { value: "installed", label: `Installed · ${items.filter((p) => p.status !== "available").length}` },- { value: "catalog", label: `Catalog · ${items.filter((p) => p.status === "available").length}` },- { value: "mcp", label: `MCP · ${servers.length}` },- ]} />- <SearchField value={query} onChange={setQuery} placeholder="Search plugins" className="ml-auto w-[260px]" />- </div>-- {note && <p className="text-sm text-ink3">{note}</p>}- {catalogError && tab === "catalog" && <p className="text-sm text-amber">Catalog: {catalogError}</p>}-- {tab === "installed" && (installed.length === 0- ? <Empty title={q ? "No installed plugin matches" : "No plugins installed"} body={q ? undefined : "Browse the catalog, or install from a path or URL below."} />- : installed.map((p) => (- <PluginRow key={p.id} p={p} actions={- <>- {p.status === "update-available" && <Button size="sm" variant="primary" loading={busy === `u:${p.id}`} onClick={() => void act(`u:${p.id}`, () => api.plugins.update(p.id), `${p.name} updated.`)}>Update</Button>}- {p.channel && p.channel.type !== "desktop" && p.enabled && <Button size="sm" variant="outline" onClick={() => setLinking(p)}>{p.channel.state === "connected" ? "Manage" : "Link account"}</Button>}- <Switch id={`plugin-${p.id}`} checked={p.enabled} onCheckedChange={(v) => void act(`t:${p.id}`, () => (v ? api.plugins.enable(p.id) : api.plugins.disable(p.id)))} label={p.enabled ? "On" : "Off"} />- <ConfirmButton size="sm" confirmLabel="Remove?" onConfirm={() => void act(`r:${p.id}`, () => api.plugins.uninstall(p.id), `${p.name} removed.`)}>Remove</ConfirmButton>- </>- } />- )))}-- {tab === "catalog" && (catalog.length === 0- ? <Empty title={q ? "No catalog plugin matches" : "Nothing new in the catalog"} />- : catalog.map((p) => (- <PluginRow key={p.id} p={p} actions={- <Button size="sm" variant="outline" loading={busy === `i:${p.id}`} onClick={() => void act(`i:${p.id}`, () => api.plugins.install(p.id), `${p.name} installed.`)}>- {busy === `i:${p.id}` ? "Installing…" : "Install"}- </Button>- } />- )))}+ const switchTab = (t: Tab) => {+ setTab(t);+ setNote(null);+ const first = t === "installed" ? yours[0] : t === "discover" ? catalog[0] : undefined;+ setPane(t === "mcp" ? (servers[0] ? { kind: "mcp", id: servers[0].id } : null) : first ? (t === "installed" ? { kind: "plugin", id: first.id } : { kind: "catalog", id: first.id }) : null);+ };- {tab === "installed" && (- <div className="mt-3 flex gap-2">- <Input value={source} onChange={(e) => setSource(e.target.value)} placeholder="Install from a path, URL or catalog id…" mono className="h-10" />- <Button variant="outline" size="lg" disabled={!source.trim()} loading={busy === "src"} onClick={() => void act("src", () => api.plugins.install(source.trim()), "Installed.").then(() => setSource(""))}>Install</Button>- </div>+ return (+ <div className="flex h-full min-h-0">+ <aside className="flex w-[330px] shrink-0 flex-col border-r border-line bg-soft">+ <div className="flex h-[52px] shrink-0 items-center gap-2 px-4" data-tauri-drag-region>+ <span className="flex-1 text-base font-semibold text-ink" data-tauri-drag-region>Plugins</span>+ {safeMode && <Badge tone="amber">safe mode</Badge>}+ <Button variant="ghost" size="sm" icon onClick={() => void load(true)} loading={refreshing} aria-label="Refresh the catalog" title="Refresh the catalog"><RefreshCw size={14} /></Button>+ </div>+ <div className="flex flex-col gap-2 px-3 pb-2">+ <Segmented value={tab} onChange={switchTab} options={[+ { value: "installed", label: `Yours · ${yours.length}` },+ { value: "discover", label: `Discover · ${catalog.length}` },+ { value: "mcp", label: `MCP · ${servers.length}` },+ ]} />+ <SearchField value={query} onChange={setQuery} placeholder={tab === "discover" ? "Search the catalog" : tab === "mcp" ? "Search servers" : "Search your plugins"} />+ {tab === "installed" && updates > 0 && <span className="flex items-center gap-1.5 px-1 text-xs text-cyan"><ArrowUpCircle size={12} /> {updates} update{updates === 1 ? "" : "s"} available</span>}+ {tab === "discover" && catalogError && <span className="flex items-start gap-1.5 px-1 text-xs text-amber"><AlertTriangle size={12} className="mt-0.5 shrink-0" /> Catalog unreachable: {catalogError}</span>}+ {safeMode && <span className="px-1 text-xs text-amber">Safe mode: every plugin is off until Mercury restarts normally.</span>}+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto px-2 pb-3">+ {!loaded && <div className="p-4"><Spinner size={14} /></div>}+ {loaded && tab !== "mcp" && list.length === 0 && (+ <p className="px-3 py-6 text-center text-sm text-ink4">+ {q ? "Nothing matches." : tab === "installed" ? "No plugins yet. Find some in Discover." : "Nothing new in the catalog."}+ </p>)}-- {tab === "mcp" && (!mcpAvailable- ? <Empty title="MCP is not available on this runtime" body="Upgrade Mercury to 1.5 or newer." />- : mcpShown.length === 0- ? <Empty title={q ? "No server matches" : "No MCP servers"} body={q ? undefined : "Add one with `mercury mcp add` on the runtime's machine."} />- : mcpShown.map((s) => <McpRow key={s.id} s={s} />))}+ {tab !== "mcp" && list.map((p) => {+ const selected = !!pane && (pane.kind === "plugin" || pane.kind === "catalog" || pane.kind === "setup") && pane.id === p.id;+ const line = tab === "installed" ? rowLine(p) : { text: p.description, tone: "muted" as const };+ return (+ <button key={p.id} onClick={() => { setNote(null); setPane(tab === "installed" ? { kind: "plugin", id: p.id } : { kind: "catalog", id: p.id }); }}+ className={cx("flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-left", selected ? "bg-ink/[0.07]" : "hover:bg-ink/[0.04]")} aria-current={selected ? "true" : undefined}>+ <IconTile id={p.id} label={p.name} size={32} />+ <span className="min-w-0 flex-1">+ <span className="flex items-center gap-1.5">+ <span className="truncate text-sm font-medium text-ink">{p.name}</span>+ {tab === "discover" && p.tier === "official" && <Badge tone="accent">official</Badge>}+ </span>+ <span className={cx("block truncate text-xs", line.tone === "amber" ? "text-amber" : line.tone === "cyan" ? "text-cyan" : "text-ink3")}>{line.text}</span>+ </span>+ {tab === "installed" && <StatusDot on={p.enabled} />}+ {tab === "discover" && installing === p.id && <Spinner size={12} />}+ </button>+ );+ })}+ {tab === "mcp" && !mcpAvailable && <p className="px-3 py-6 text-center text-sm text-ink4">MCP isn't available on this Mercury.</p>}+ {tab === "mcp" && mcpAvailable && mcpShown.length === 0 && <p className="px-3 py-6 text-center text-sm text-ink4">{q ? "Nothing matches." : "No MCP servers."}</p>}+ {tab === "mcp" && mcpShown.map((s) => (+ <button key={s.id} onClick={() => setPane({ kind: "mcp", id: s.id })}+ className={cx("flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-left", pane?.kind === "mcp" && pane.id === s.id ? "bg-ink/[0.07]" : "hover:bg-ink/[0.04]")}>+ <IconTile id={s.id} label={s.id} size={32} />+ <span className="min-w-0 flex-1"><span className="block truncate text-sm font-medium text-ink">{s.id}</span><span className="block truncate font-mono text-xs text-ink3">{s.target}</span></span>+ <StatusDot on={s.state === "connected"} />+ </button>+ ))}</div>- </div>- <Dialog open={!!linking} onOpenChange={(o) => { if (!o) { setLinking(null); void load(); } }} title={linking ? `${linking.name} account` : ""} description="Link the account Mercury talks through." width={460}>- {linking && <ChannelPanel id={linking.id} name={linking.name} />}- </Dialog>+ {tab === "installed" && (+ <div className="border-t border-line p-2">+ <Button size="sm" variant="ghost" className="w-full justify-start" onClick={() => { setNote(null); setPane({ kind: "source" }); }}><FolderOpen size={13} /> Install from a file or link…</Button>+ </div>+ )}+ </aside>++ <main className="min-w-0 flex-1 overflow-y-auto">+ {note && (+ <div className={cx("mx-6 mt-4 rounded-lg border px-3 py-2 text-sm", note.ok ? "border-accent/30 bg-accent/[0.05] text-ink2" : "border-red/30 bg-red/[0.05] text-red")}>+ {note.text}{!note.ok && /from this machine|loopback/i.test(note.text) ? " Plugins can only be changed on the computer Mercury runs on." : ""}+ </div>+ )}+ {pane?.kind === "plugin" && <PluginDetail key={pane.id} id={pane.id} onSetup={() => setPane({ kind: "setup", id: pane.id })} onChanged={() => void load()} onRemoved={() => { setNote({ text: "Removed.", ok: true }); setPane(null); void load(); }} />}+ {pane?.kind === "setup" && <div className="h-full"><SetupFlow key={pane.id} id={pane.id} onClose={() => setPane({ kind: "plugin", id: pane.id })} onChanged={() => void load()} /></div>}+ {pane?.kind === "catalog" && (() => {+ const p = items.find((x) => x.id === pane.id);+ return p ? <CatalogDetail p={p} installing={installing === p.id} onInstall={() => void install(p.id, { fromCatalog: true })} /> : null;+ })()}+ {pane?.kind === "mcp" && (() => {+ const s = servers.find((x) => x.id === pane.id);+ return s ? <McpDetail s={s} /> : null;+ })()}+ {pane?.kind === "source" && <SourceInstall installing={installing !== null} onInstall={(src) => void install(src, { fromCatalog: false })} />}+ {!pane && loaded && (+ <div className="flex h-full flex-col items-center justify-center gap-3 p-8 text-center">+ <Plug size={26} className="text-ink4" />+ <p className="max-w-[360px] text-sm text-ink3">{yours.length ? "Pick a plugin to see and change everything about it." : "Plugins add abilities to Mercury: chat apps, your computer, tools. Find one in Discover."}</p>+ {!yours.length && <Button variant="primary" onClick={() => switchTab("discover")}>Discover plugins</Button>}+ </div>+ )}+ </main></div>);}-function PluginRow({ p, actions }: { p: PluginItem; actions: React.ReactNode }) {- const problem = p.lastError || p.disabled?.message || p.incompatibleReason;- const state = p.status === "error" || p.disabled ? "needs-you" : p.running ? "working" : p.enabled ? "idle" : "offline";+/** Install a plugin that isn't in the catalog: a folder, a .tgz, a URL or github:owner/repo. */+function SourceInstall({ installing, onInstall }: { installing: boolean; onInstall: (src: string) => void }) {+ const [src, setSrc] = useState("");+ const [trust, setTrust] = useState(false);return (- <ItemRow- tone={problem ? "warn" : undefined}- tile={<span className="relative"><IconTile id={p.id} label={p.name} />{p.status !== "available" && <StateOrb state={state} size={9} className="absolute -bottom-0.5 -right-0.5 rounded-full bg-surface p-[1.5px]" />}</span>}- title={p.name}- badges={- <>- <Mono>{p.installedVersion ?? p.latestVersion ?? ""}</Mono>- {p.tier === "official" && <Badge tone="accent">official</Badge>}- {p.verified && p.tier !== "official" && <Badge>verified</Badge>}- {p.status === "update-available" && <Badge tone="cyan">{p.latestVersion} available</Badge>}- {p.status === "incompatible" && <Badge tone="amber">incompatible</Badge>}- {p.channel?.state && <Badge>{p.channel.type} · {p.channel.state}</Badge>}- </>- }- description={p.description}- footer={- <>- {(p.tools.length > 0 || p.commands.length > 0) && (- <p className="truncate font-mono text-xs text-ink4">- {p.tools.length > 0 && `${p.tools.length} tool${p.tools.length === 1 ? "" : "s"}`}- {p.tools.length > 0 && p.commands.length > 0 && " · "}- {p.commands.map((c) => `/${c}`).join(" ")}- </p>- )}- {problem && <p className="mt-1 text-sm text-amber">{problem}</p>}- </>- }- actions={actions}- />+ <div className="mx-auto flex max-w-[560px] flex-col gap-4 px-6 py-8">+ <div><h2 className="text-lg font-semibold text-ink">Install from a file or link</h2><p className="text-sm text-ink3">A plugin folder or .tgz on the computer Mercury runs on, an https:// link to a .tgz, or github:owner/repo.</p></div>+ <Input value={src} onChange={(e) => setSrc(e.target.value)} placeholder="/path/to/plugin.tgz or github:owner/repo" mono autoFocus />+ <div className="flex items-start gap-2.5 rounded-lg border border-amber/40 bg-amber/[0.05] p-3 text-sm text-ink2">+ <AlertTriangle size={15} className="mt-0.5 shrink-0 text-amber" />+ <span>This isn't from Mercury's catalog, so it hasn't been checked. A plugin can run code with your permissions. Only install ones from people you trust.</span>+ </div>+ <label className="flex items-center gap-2 text-sm text-ink2"><input type="checkbox" checked={trust} onChange={(e) => setTrust(e.target.checked)} /> I trust where this comes from</label>+ <div><Button variant="primary" loading={installing} disabled={!src.trim() || !trust} onClick={() => onInstall(src.trim())}>Install and set up</Button></div>+ </div>);}-function McpRow({ s }: { s: McpServer }) {- const state = s.state === "connected" ? "idle" : s.state === "failed" ? "needs-you" : s.state === "disabled" ? "offline" : "thinking";- const allowed = s.tools.filter((t) => t.allowed !== false).length;+function McpDetail({ s }: { s: McpServer }) {+ const allowed = s.tools.filter((t) => t.allowed !== false);return (- <ItemRow- tone={s.state === "failed" ? "warn" : undefined}- tile={<span className="relative"><IconTile id={s.id} label={s.id} /><StateOrb state={state} size={9} className="absolute -bottom-0.5 -right-0.5 rounded-full bg-surface p-[1.5px]" /></span>}- title={s.id}- badges={<><Badge>{s.transport}</Badge><Badge tone={s.state === "connected" ? "accent" : s.state === "failed" ? "red" : "neutral"}>{s.state}</Badge></>}- description={<Mono className="text-sm">{s.target}</Mono>}- footer={<p className="text-sm text-ink3">{allowed} of {s.toolCount} tools allowed{s.error ? ` · ${s.error}` : ""}</p>}- />+ <div className="flex flex-col gap-5 px-6 py-6">+ <div className="flex items-start gap-4">+ <IconTile id={s.id} label={s.id} size={48} />+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2"><h2 className="text-lg font-semibold text-ink">{s.id}</h2><Badge>{s.transport}</Badge><Badge tone={s.state === "connected" ? "accent" : s.state === "failed" ? "red" : "neutral"}>{s.state}</Badge></div>+ <Mono className="mt-1 block break-all text-sm">{s.target}</Mono>+ {s.error && <p className="mt-1 text-sm text-red">{s.error}</p>}+ </div>+ </div>+ <div>+ <h3 className="text-sm font-semibold text-ink">{allowed.length} of {s.toolCount} tools allowed</h3>+ <div className="mt-2 flex flex-wrap gap-1.5">{s.tools.map((t) => <span key={t.name} className={cx("rounded-md border px-2 py-0.5 font-mono text-xs", t.allowed === false ? "border-line text-ink4 line-through" : "border-line text-ink2")}>{t.name}</span>)}</div>+ </div>+ <p className="text-xs text-ink4">Add, remove or change MCP servers with <code className="font-mono">mercury mcp</code> on the computer Mercury runs on.</p>+ </div>);}diff --git a/apps/desktop/src/views/plugins/SettingField.tsx b/apps/desktop/src/views/plugins/SettingField.tsxnew file mode 100644index 00000000..51294e1c--- /dev/null+++ b/apps/desktop/src/views/plugins/SettingField.tsx@@ -0,0 +1,175 @@+import { Check, Eye, EyeOff } from "lucide-react";+import { useEffect, useState } from "react";+import type { PluginSetting } from "~/api/types";+import { Button } from "~/components/ui/Button";+import { Input } from "~/components/ui/Input";+import { Switch } from "~/components/ui/Switch";+import { Badge, Spinner } from "~/components/ui/bits";+import { cx } from "~/lib/cx";++/**+ * One plugin setting, the right control for its type: choices as cards+ * (with the plugin's own words for each), on/off as a switch, text and+ * numbers as a field that saves on Enter or when you leave it, secrets as+ * a hidden field with Save (never shown back). Used inline in a plugin's+ * page and, larger, as a setup step.+ */++export function humanize(key: string): string {+ return key.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase());+}++export function labelOf(s: PluginSetting): string {+ return s.label ?? humanize(s.key);+}++/** Does a setting apply, given the others' values? (Mirrors the runtime's whenMatches.) */+export function applies(s: PluginSetting, all: PluginSetting[]): boolean {+ if (!s.when) return true;+ const values = Object.fromEntries(all.map((x) => [x.key, x.value])) as Record<string, unknown>;+ const conds = Array.isArray(s.when) ? s.when : [s.when];+ return conds.some((c) => Object.entries(c).every(([k, want]) => {+ const v = String(values[k]);+ return Array.isArray(want) ? want.includes(v) : v === String(want);+ }));+}++/** Filled in? (Secrets: stored. Others: a non-empty value.) */+export function filled(s: PluginSetting): boolean {+ return s.type === "secret" ? !!s.isSet : s.value !== undefined && s.value !== null && s.value !== "";+}++/** "OpenAI: the most natural…" → { title: "OpenAI", body: "the most natural…" } */+function splitOptionLabel(label: string | undefined, fallback: string): { title: string; body: string | null } {+ if (!label) return { title: fallback, body: null };+ const m = label.match(/^([^:]{1,48}):\s+(.+)$/);+ return m ? { title: m[1].replace(/^[^\p{L}\p{N}]+/u, "").trim() || fallback, body: m[2] } : { title: label, body: null };+}++export function SettingField({ s, onSave, size = "inline" }: { s: PluginSetting; onSave: (value: unknown) => Promise<void>; size?: "inline" | "step" }) {+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [ok, setOk] = useState(false);+ async function save(v: unknown) {+ setBusy(true);+ setError(null);+ setOk(false);+ try { await onSave(v); setOk(true); setTimeout(() => setOk(false), 1500); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); }+ }+ const step = size === "step";++ let control: React.ReactNode;+ if (s.type === "enum") {+ const options = s.options ?? [];+ const cards = step || options.length <= 4;+ control = cards ? (+ <div className={cx("grid gap-2", step ? "grid-cols-1" : "grid-cols-1 sm:grid-cols-2")} role="radiogroup" aria-label={labelOf(s)}>+ {options.map((o) => {+ const { title, body } = splitOptionLabel(s.optionLabels?.[o], o);+ const on = s.value === o;+ return (+ <button key={o} role="radio" aria-checked={on} disabled={busy} onClick={() => void save(o)}+ className={cx("flex items-start gap-2.5 rounded-lg border px-3 py-2 text-left transition-colors", on ? "border-accent/60 bg-accent/[0.07]" : "border-line hover:border-ink/25")}>+ <span className={cx("mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full border", on ? "border-accent bg-accent text-white" : "border-line")}>{on && <Check size={10} strokeWidth={3} />}</span>+ <span className="min-w-0">+ <span className="block text-sm text-ink">{title}</span>+ {body && <span className="block text-xs text-ink3">{body}</span>}+ </span>+ </button>+ );+ })}+ </div>+ ) : (+ <select value={String(s.value ?? "")} onChange={(e) => void save(e.target.value)} disabled={busy} aria-label={labelOf(s)}+ className="h-9 w-full rounded-md border border-line bg-surface px-2.5 text-sm text-ink">+ {options.map((o) => <option key={o} value={o}>{s.optionLabels?.[o] ?? o}</option>)}+ </select>+ );+ } else if (s.type === "boolean") {+ const on = s.value === true;+ const labels = s.optionLabels;+ control = step && labels ? (+ <div className="grid grid-cols-1 gap-2" role="radiogroup" aria-label={labelOf(s)}>+ {(["true", "false"] as const).map((k) => {+ const { title, body } = splitOptionLabel(labels[k], k === "true" ? "On" : "Off");+ const sel = (k === "true") === on;+ return (+ <button key={k} role="radio" aria-checked={sel} disabled={busy} onClick={() => void save(k === "true")}+ className={cx("flex items-start gap-2.5 rounded-lg border px-3 py-2 text-left", sel ? "border-accent/60 bg-accent/[0.07]" : "border-line hover:border-ink/25")}>+ <span className={cx("mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full border", sel ? "border-accent bg-accent text-white" : "border-line")}>{sel && <Check size={10} strokeWidth={3} />}</span>+ <span><span className="block text-sm text-ink">{title}</span>{body && <span className="block text-xs text-ink3">{body}</span>}</span>+ </button>+ );+ })}+ </div>+ ) : (+ <Switch checked={on} onCheckedChange={(v) => void save(v)} disabled={busy} />+ );+ } else if (s.type === "secret") {+ control = <SecretInput s={s} busy={busy} onSave={save} />;+ } else {+ control = <TextInput s={s} busy={busy} onSave={save} />;+ }++ const inlineRow = !step && (s.type === "boolean");+ return (+ <div className={cx("flex flex-col gap-1.5", inlineRow && "flex-row items-center justify-between gap-4")}>+ <div className="min-w-0">+ <div className="flex flex-wrap items-center gap-2">+ <span className={cx(step ? "text-base font-medium" : "text-sm", "text-ink")}>{labelOf(s)}</span>+ {s.type === "secret" && (s.isSet ? <Badge tone="accent">saved</Badge> : s.required ? <Badge tone="amber">required</Badge> : null)}+ {s.type !== "secret" && s.required && !filled(s) && <Badge tone="amber">required</Badge>}+ {busy && <Spinner size={11} />}+ {ok && !busy && <Check size={13} className="text-accent" />}+ </div>+ {s.description && <p className="text-xs leading-relaxed text-ink3">{s.description}</p>}+ </div>+ {control}+ {error && <p className="text-xs text-red">{error}</p>}+ </div>+ );+}++function TextInput({ s, busy, onSave }: { s: PluginSetting; busy: boolean; onSave: (v: unknown) => Promise<void> }) {+ const current = s.value === undefined || s.value === null ? "" : String(s.value);+ const [v, setV] = useState(current);+ useEffect(() => { setV(current); }, [current]);+ const commit = () => {+ if (v === current) return;+ if (s.type === "number") {+ const n = Number(v);+ if (v.trim() === "" || !Number.isFinite(n)) { setV(current); return; }+ void onSave(n);+ } else void onSave(v.trim());+ };+ return (+ <div className="flex flex-col gap-1.5">+ <Input value={v} onChange={(e) => setV(e.target.value)} onBlur={commit} onKeyDown={(e) => { if (e.key === "Enter") (e.target as HTMLInputElement).blur(); }}+ type={s.type === "number" ? "number" : s.format === "phone" ? "tel" : "text"} disabled={busy} aria-label={labelOf(s)} placeholder={s.format === "phone" ? "+92 300 1234567" : "Not set"} mono={s.type !== "number"} />+ {s.examples && s.examples.length > 0 && (+ <div className="flex flex-wrap gap-1.5">+ {s.examples.map((x) => (+ <button key={x} onClick={() => { setV(x); void onSave(s.type === "number" ? Number(x) : x); }} disabled={busy}+ className={cx("rounded-full border px-2.5 py-0.5 font-mono text-xs", v === x ? "border-accent/60 bg-accent/[0.07] text-ink" : "border-line text-ink2 hover:border-ink/25")}>{x}</button>+ ))}+ </div>+ )}+ </div>+ );+}++function SecretInput({ s, busy, onSave }: { s: PluginSetting; busy: boolean; onSave: (v: unknown) => Promise<void> }) {+ const [v, setV] = useState("");+ const [show, setShow] = useState(false);+ return (+ <div className="flex gap-2">+ <div className="relative min-w-0 flex-1">+ <Input type={show ? "text" : "password"} autoComplete="off" mono value={v} onChange={(e) => setV(e.target.value)} disabled={busy}+ onKeyDown={(e) => { if (e.key === "Enter" && v.trim()) { void onSave(v.trim()).then(() => setV("")); } }}+ placeholder={s.isSet ? "Saved. Paste a new value to replace it" : "Paste it here"} aria-label={labelOf(s)} className="pr-9" />+ <button type="button" onClick={() => setShow((x) => !x)} className="absolute right-2 top-1/2 -translate-y-1/2 text-ink4 hover:text-ink" aria-label={show ? "Hide" : "Show"}>{show ? <EyeOff size={14} /> : <Eye size={14} />}</button>+ </div>+ <Button size="md" variant="primary" disabled={!v.trim() || busy} onClick={() => void onSave(v.trim()).then(() => setV(""))}>Save</Button>+ </div>+ );+}diff --git a/apps/desktop/src/views/plugins/SetupFlow.tsx b/apps/desktop/src/views/plugins/SetupFlow.tsxnew file mode 100644index 00000000..04fe4d6f--- /dev/null+++ b/apps/desktop/src/views/plugins/SetupFlow.tsx@@ -0,0 +1,155 @@+import { ArrowLeft, ArrowRight, CheckCircle2, PartyPopper } from "lucide-react";+import { useCallback, useEffect, useMemo, useState } from "react";+import * as api from "~/api/mercury";+import type { PluginItem, PluginSetting } from "~/api/types";+import { Button } from "~/components/ui/Button";+import { Spinner } from "~/components/ui/bits";+import { ChannelPanel } from "./ChannelPanel";+import { applies, filled, labelOf, SettingField } from "./SettingField";++/**+ * Guided setup, the way the plugin defines it: each setting it marks for+ * setup, in its order, asked one at a time with its own words; a setting+ * that depends on a missing key is asked only while it's missing; answers+ * can change which later questions apply (picking a voice engine asks for+ * that engine's key), so the steps are worked out again after each one.+ * Messaging plugins finish by linking their account. Then it's on.+ */++export function setupKeys(p: PluginItem): string[] {+ const all = p.settings ?? [];+ const missing = new Set((p.missing ?? []).map((m) => m.key));+ return all.filter((s) => s.setup && (!s.setupWhenMissing || missing.has(s.setupWhenMissing)) && applies(s, all)).map((s) => s.key);+}++export function needsSetup(p: PluginItem): boolean {+ const all = p.settings ?? [];+ return all.some((s) => s.required && applies(s, all) && !filled(s)) || (p.settingGroups ?? []).some((g) => !g.ready);+}++type Step = { kind: "setting"; key: string } | { kind: "link" } | { kind: "done" };++export function SetupFlow({ id, onClose, onChanged }: { id: string; onClose: () => void; onChanged: () => void }) {+ const [p, setP] = useState<PluginItem | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [at, setAt] = useState<Step | null>(null);+ const [history, setHistory] = useState<Step[]>([]);+ const [finishing, setFinishing] = useState(false);++ const load = useCallback(async () => {+ try { const info = await api.plugins.info(id); setP(info); return info; } catch (e) { setError(e instanceof Error ? e.message : String(e)); return null; }+ }, [id]);++ const linkable = !!p?.channel && p.channel.type !== "desktop";+ const steps = useMemo<Step[]>(() => {+ if (!p) return [];+ return [...setupKeys(p).map((key) => ({ kind: "setting" as const, key })), ...(linkable ? [{ kind: "link" as const }] : []), { kind: "done" as const }];+ }, [p, linkable]);++ useEffect(() => { void load().then((info) => { if (info) setAt(null); }); }, [load]);+ // Start at the first step once loaded.+ useEffect(() => { if (p && !at && steps.length) setAt(steps[0]); }, [p, at, steps]);++ const same = (a: Step, b: Step) => a.kind === b.kind && (a.kind !== "setting" || b.kind !== "setting" || a.key === b.key);+ const index = at ? steps.findIndex((s) => same(s, at)) : -1;+ // A setting that stopped applying (an earlier answer changed things) moves on by itself.+ useEffect(() => { if (p && at && index === -1) setAt(steps[0]); }, [p, at, index, steps]);++ function next() {+ if (!at) return;+ const i = steps.findIndex((s) => same(s, at));+ const n = steps[i + 1];+ if (n) { setHistory((h) => [...h, at]); setAt(n); }+ }+ function back() {+ setHistory((h) => {+ const prev = h[h.length - 1];+ if (prev) setAt(prev);+ return h.slice(0, -1);+ });+ }++ async function save(key: string, value: unknown) {+ await api.plugins.setSetting(id, key, value);+ await load();+ onChanged();+ }++ async function finish() {+ setFinishing(true);+ try {+ if (p && !p.enabled) await api.plugins.enable(id);+ onChanged();+ onClose();+ } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setFinishing(false); }+ }++ if (error && !p) return <p className="p-6 text-sm text-red">{error}</p>;+ if (!p || !at) return <div className="p-6"><Spinner size={16} /></div>;++ const settingNow: PluginSetting | undefined = at.kind === "setting" ? p.settings?.find((s) => s.key === at.key) : undefined;+ const total = steps.length - 1;+ const position = Math.min(index + 1, total);+ const canContinue = at.kind !== "setting" || !settingNow || !settingNow.required || filled(settingNow);++ return (+ <div className="flex h-full min-h-0 flex-col">+ <div className="flex items-center gap-3 border-b border-line px-6 py-4">+ <div className="min-w-0 flex-1">+ <div className="text-base font-medium text-ink">Set up {p.name}</div>+ <div className="text-xs text-ink3">{at.kind === "done" ? "All set" : `Step ${position} of ${total}`}</div>+ </div>+ <Button size="sm" variant="ghost" onClick={onClose}>{at.kind === "done" ? "Close" : "Finish later"}</Button>+ </div>+ <div className="h-1 bg-ink/[0.06]"><div className="h-full bg-accent transition-[width] duration-300" style={{ width: `${total ? (Math.min(index, total) / total) * 100 : 100}%` }} /></div>++ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-6">+ <div className="mx-auto flex max-w-[520px] flex-col gap-4">+ {at.kind === "setting" && settingNow && <SettingField key={settingNow.key} s={settingNow} size="step" onSave={(v) => save(settingNow.key, v)} />}+ {at.kind === "setting" && !settingNow && <p className="text-sm text-ink3">This step no longer applies.</p>}+ {at.kind === "link" && (+ <>+ <div><div className="text-base font-medium text-ink">Link the {p.name} account</div><p className="text-xs text-ink3">Use a spare number, not your main one.</p></div>+ <ChannelPanel id={id} name={p.name} />+ </>+ )}+ {at.kind === "done" && (+ <div className="flex flex-col items-center gap-3 py-6 text-center">+ <PartyPopper size={28} className="text-accent" />+ <div className="text-lg font-medium text-ink">{p.name} is ready</div>+ <p className="max-w-[420px] text-sm text-ink3">+ {p.enabled ? "It's on." : "Turn it on to start."} You can change any of this later on its page.+ {(p.missing ?? []).length > 0 && ` Still optional: ${(p.missing ?? []).map((m) => m.unlocks).join("; ")}.`}+ </p>+ {(p.settings ?? []).filter((s) => s.setup && applies(s, p.settings ?? [])).length > 0 && (+ <ul className="w-full max-w-[420px] divide-y divide-line rounded-lg border border-line text-left text-sm">+ {(p.settings ?? []).filter((s) => s.setup && applies(s, p.settings ?? [])).map((s) => (+ <li key={s.key} className="flex items-center gap-2 px-3 py-2">+ <CheckCircle2 size={13} className={filled(s) ? "text-accent" : "text-ink4"} />+ <span className="min-w-0 flex-1 truncate text-ink2">{labelOf(s)}</span>+ <span className="max-w-[180px] truncate font-mono text-xs text-ink3">{s.type === "secret" ? (s.isSet ? "saved" : "not set") : String(s.value ?? "not set")}</span>+ </li>+ ))}+ </ul>+ )}+ </div>+ )}+ {error && <p className="text-sm text-red">{error}</p>}+ </div>+ </div>++ <div className="flex items-center gap-2 border-t border-line px-6 py-3">+ <Button size="md" variant="ghost" disabled={history.length === 0} onClick={back}><ArrowLeft size={14} /> Back</Button>+ <span className="flex-1" />+ {at.kind === "done"+ ? <Button size="md" variant="primary" loading={finishing} onClick={() => void finish()}>{p.enabled ? "Done" : `Turn on ${p.name}`}</Button>+ : (+ <>+ {at.kind === "setting" && settingNow && !settingNow.required && !filled(settingNow) && <Button size="md" variant="ghost" onClick={next}>Skip</Button>}+ <Button size="md" variant="primary" disabled={!canContinue} onClick={next}>Continue <ArrowRight size={14} /></Button>+ </>+ )}+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/views/plugins/plugins.test.ts b/apps/desktop/src/views/plugins/plugins.test.tsnew file mode 100644index 00000000..4d6ccc3e--- /dev/null+++ b/apps/desktop/src/views/plugins/plugins.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from "vitest";+import type { PluginItem, PluginSetting } from "~/api/types";+import { applies, filled } from "./SettingField";+import { needsSetup, setupKeys } from "./SetupFlow";++const s = (key: string, extra: Partial<PluginSetting> = {}): PluginSetting => ({ key, type: "string", ...extra });+const plugin = (settings: PluginSetting[], extra: Partial<PluginItem> = {}): PluginItem => ({+ id: "qa", name: "QA", description: "", kind: "in-process", tier: "local", status: "enabled", enabled: true, running: true, verified: false, tools: [], commands: [], settings, ...extra,+});++describe("plugin setup steps", () => {+ it("asks the setup settings in the plugin's order, only those that apply", () => {+ const p = plugin([+ s("mode", { type: "enum", setup: true, value: "friendly", options: ["friendly", "pirate"] }),+ s("pirateName", { setup: true, when: { mode: ["pirate"] } }),+ s("loud", { type: "boolean", setup: true, value: false }),+ s("greeting", { value: "Hello" }),+ ]);+ expect(setupKeys(p)).toEqual(["mode", "loud"]);+ p.settings![0].value = "pirate";+ expect(setupKeys(p)).toEqual(["mode", "pirateName", "loud"]);+ });++ it("asks a setupWhenMissing setting only while that requirement is missing", () => {+ const voice = s("voiceEngine", { type: "enum", setup: true, setupWhenMissing: "provider:openai", value: "openai" });+ expect(setupKeys(plugin([voice], { missing: [{ key: "provider:openai", unlocks: "Talking", needs: "an OpenAI key", fix: "add it" }] }))).toEqual(["voiceEngine"]);+ expect(setupKeys(plugin([voice], { missing: [] }))).toEqual([]);+ });++ it("needs setup when a required setting that applies is empty, or a section isn't ready", () => {+ expect(needsSetup(plugin([s("token", { type: "secret", required: true, isSet: false })]))).toBe(true);+ expect(needsSetup(plugin([s("token", { type: "secret", required: true, isSet: true })]))).toBe(false);+ expect(needsSetup(plugin([s("key", { required: true, when: { mode: ["x"] } }), s("mode", { value: "y" })]))).toBe(false);+ expect(needsSetup(plugin([], { settingGroups: [{ id: "voice", label: "Voice", ready: false }] }))).toBe(true);+ });++ it("when-conditions: any of several, and filled-ness by type", () => {+ const all = [s("a", { value: "1" }), s("b", { value: "2" })];+ expect(applies(s("x", { when: [{ a: "9" }, { b: ["2", "3"] }] }), all)).toBe(true);+ expect(applies(s("x", { when: { a: "9" } }), all)).toBe(false);+ expect(filled(s("x", { value: "" }))).toBe(false);+ expect(filled(s("x", { type: "number", value: 0 }))).toBe(true);+ });+});diff --git a/src/plugins/manager.ts b/src/plugins/manager.tsindex 6fd35ffa..c3a01363 100644--- a/src/plugins/manager.ts+++ b/src/plugins/manager.ts@@ -666,6 +666,7 @@ export class PluginManager {tier: inst && inst.source.type !== 'catalog' ? 'local' : cat?.tier ?? 'local',status,installedVersion: inst?.version,+ previousVersion: inst?.previousVersion && existsSync(pluginVersionDir(id, inst.previousVersion)) ? inst.previousVersion : undefined,latestVersion: cat?.version,sizeBytes: inst ? packageSize(id, inst.version) : (cat?.artifacts ? Object.values(cat.artifacts)[0]?.size : cat?.artifact?.size),enabled: inst?.enabled ?? false,diff --git a/src/plugins/types.ts b/src/plugins/types.tsindex bd1793c6..27cd8446 100644--- a/src/plugins/types.ts+++ b/src/plugins/types.ts@@ -344,6 +344,8 @@ export interface PluginListItem {tier: 'official' | 'community' | 'local';status: PluginStatus;installedVersion?: string;+ /** The version before the last update, if it's still on disk (what rollback goes back to). */+ previousVersion?: string;latestVersion?: string;sizeBytes?: number;enabled: boolean;