Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(desktop): environment bar, customisable status bar, UI contribution registry
Salman Qureshiad3c769ed747
diff --git a/apps/desktop/README.md b/apps/desktop/README.mdindex f0e7eebf..685ae377 100644--- a/apps/desktop/README.md+++ b/apps/desktop/README.md@@ -22,6 +22,26 @@ Design: one quiet palette (`src/styles/tokens.css`), light / dark / auto, asingle accent the user can tint; amber means "needs you", red means halt,cyan means thinking — fixed. Geist and Geist Mono are bundled.+## Extending the chrome++The status bar is built from contributions (`src/extensions/registry.ts`).+Built-in items register exactly as a UI plugin will:++```ts+mercuryUi.registerStatusItem({+ id: "optimus.screen", // "<owner>.<name>", stable+ title: "Screen control", // shown in Customize and Settings → Status bar+ area: "status.right", // or "status.left"+ priority: 30, // higher sits further left in its area+ views: ["chat", "code"], // omit for every view+ render: ScreenStatus, // a React component+});+```++The user's choices (hidden, shown, order) are stored by id, so adding or+removing contributions never reshuffles their layout. Keep ids and fields+stable once published; add new optional fields, never rename.+## How a connection works| Kind | Address | Credential |diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.jsonindex d74d902c..d8257559 100644--- a/apps/desktop/src-tauri/tauri.conf.json+++ b/apps/desktop/src-tauri/tauri.conf.json@@ -21,7 +21,9 @@"minHeight": 600,"center": true,"resizable": true,- "dragDropEnabled": true+ "dragDropEnabled": true,+ "titleBarStyle": "Overlay",+ "hiddenTitle": true}],"security": {@@ -45,7 +47,7 @@"category": "DeveloperTool","shortDescription": "Mercury Desktop","longDescription": "The native desktop app for Mercury, the soul-driven AI agent. Attaches to a Mercury on this computer or connects to one anywhere.",- "copyright": "© Cosmic Stack",+ "copyright": "\u00a9 Cosmic Stack","icon": ["icons/32x32.png","icons/128x128.png",@@ -57,29 +59,49 @@"macOS": {"minimumSystemVersion": "11.0","dmg": {- "windowSize": { "width": 660, "height": 400 }+ "windowSize": {+ "width": 660,+ "height": 400+ }}},"windows": {- "webviewInstallMode": { "type": "downloadBootstrapper", "silent": true },+ "webviewInstallMode": {+ "type": "downloadBootstrapper",+ "silent": true+ },"nsis": {"installMode": "currentUser",- "languages": ["English"]+ "languages": [+ "English"+ ]}},"linux": {- "appimage": { "bundleMediaFramework": false },- "deb": { "section": "utils" }+ "appimage": {+ "bundleMediaFramework": false+ },+ "deb": {+ "section": "utils"+ }}},"plugins": {"updater": {- "endpoints": ["https://mercuryagent.sh/desktop/latest.json"],+ "endpoints": [+ "https://mercuryagent.sh/desktop/latest.json"+ ],"pubkey": "",- "windows": { "installMode": "passive" }+ "windows": {+ "installMode": "passive"+ }},"deep-link": {- "desktop": { "schemes": ["mercury"] }+ "desktop": {+ "schemes": [+ "mercury"+ ]+ }}}}diff --git a/apps/desktop/src/app/pulse.ts b/apps/desktop/src/app/pulse.tsnew file mode 100644index 00000000..29b58cbb--- /dev/null+++ b/apps/desktop/src/app/pulse.ts@@ -0,0 +1,89 @@+/* ═══════════════════════════════════════════════════════════════+ Pulse: the slow-moving runtime facts the chrome shows (owner, tokens,+ schedules, background work). One poller per connection, cadence per+ kind; live facts (agent state, bots) come from the event streams.+ ═══════════════════════════════════════════════════════════════ */++import { useEffect } from "react";+import { create } from "zustand";+import { http } from "~/api/client";++export interface UsageInfo {+ dailyUsed: number;+ dailyBudget: number;+ remaining: number;+ byProvider: Record<string, number>;+ byChannel: Record<string, number>;+ requestLog: Array<{ provider: string; model: string; inputTokens: number; outputTokens: number; totalTokens: number; channelType: string; timestamp: number }>;+}++export interface ScheduleInfo {+ id: string;+ description: string;+ cron?: string;+ delaySeconds?: number;+ prompt?: string;+ botId?: string;+ nextRun?: string;+ lastRun?: string;+}++export interface BackgroundInfo {+ tasks: Array<{ id: string; description: string; status: string; createdAt: string }>;+ agents: Array<{ id: string; task: string; status: string; tokensUsed?: number }>;+}++interface PulseState {+ owner: string;+ agentName: string;+ usage: UsageInfo | null;+ schedules: ScheduleInfo[];+ background: BackgroundInfo;+}++export const usePulse = create<PulseState>(() => ({+ owner: "",+ agentName: "",+ usage: null,+ schedules: [],+ background: { tasks: [], agents: [] },+}));++async function loadIdentity() {+ try {+ const c = await http.get<{ identity?: { owner?: string; name?: string } }>("/api/config");+ usePulse.setState({ owner: c.identity?.owner ?? "", agentName: c.identity?.name ?? "" });+ } catch { /* older runtime */ }+}+async function loadUsage() {+ try { usePulse.setState({ usage: await http.get<UsageInfo>("/api/usage") }); } catch { /* keep */ }+}+async function loadSchedules() {+ try { usePulse.setState({ schedules: (await http.get<{ schedules: ScheduleInfo[] }>("/api/schedules")).schedules }); } catch { /* keep */ }+}+async function loadBackground() {+ const [tasks, agents] = await Promise.all([+ http.get<{ tasks: BackgroundInfo["tasks"] }>("/api/bg").then((r) => r.tasks).catch(() => []),+ http.get<{ agents: BackgroundInfo["agents"] }>("/api/agents").then((r) => r.agents).catch(() => []),+ ]);+ usePulse.setState({ background: { tasks, agents } });+}++export function usePulsePolling(connectionId: string): void {+ useEffect(() => {+ void loadIdentity();+ void loadUsage();+ void loadSchedules();+ void loadBackground();+ const timers = [+ setInterval(() => void loadUsage(), 20_000),+ setInterval(() => void loadSchedules(), 60_000),+ setInterval(() => void loadBackground(), 8_000),+ ];+ const onFocus = () => { void loadUsage(); void loadBackground(); };+ window.addEventListener("focus", onFocus);+ return () => { timers.forEach(clearInterval); window.removeEventListener("focus", onFocus); };+ }, [connectionId]);+}++export const refreshPulse = { usage: loadUsage, schedules: loadSchedules, background: loadBackground };diff --git a/apps/desktop/src/extensions/builtin-status.tsx b/apps/desktop/src/extensions/builtin-status.tsxnew file mode 100644index 00000000..9f790ae8--- /dev/null+++ b/apps/desktop/src/extensions/builtin-status.tsx@@ -0,0 +1,232 @@+import { forwardRef, useEffect, useState, type ComponentPropsWithoutRef } from "react";+import { Bot, CalendarClock, Code2, Coins, Cpu, Layers, Server, Shield, ShieldCheck } from "lucide-react";+import { cx } from "~/lib/cx";+import * as api from "~/api/mercury";+import type { ChatSettings, CodeStatus } from "~/api/types";+import { useBots, useRuntimeState, useUi } from "~/app/store";+import { usePulse } from "~/app/pulse";+import { useConnections } from "~/shell/connections";+import { StateOrb, LABELS } from "~/components/indicators/StateOrb";+import { StatusButton, StatusPopover } from "~/layout/StatusBar";+import { compact } from "~/views/bots/Usage";+import { mercuryUi } from "./registry";++/* The built-in status bar items. Each is a contribution like any plugin's. */++const Trigger = forwardRef<HTMLButtonElement, ComponentPropsWithoutRef<"button"> & { tone?: "accent" | "amber" | "red" | "cyan" }>(function Trigger({ className, tone, ...rest }, ref) {+ return (+ <button+ ref={ref}+ {...rest}+ className={cx("flex h-[22px] items-center gap-1.5 rounded px-1.5 transition-colors hover:bg-ink/[0.07] hover:text-ink data-[state=open]:bg-ink/[0.07]",+ tone === "accent" && "text-accent", tone === "amber" && "text-amber", tone === "red" && "text-red", tone === "cyan" && "text-cyan", className)}+ />+ );+});++function Connection() {+ const connected = useRuntimeState((s) => s.connected);+ const active = useConnections((s) => s.connections.find((c) => c.id === s.activeId));+ const setView = useUi((s) => s.setView);+ return (+ <StatusButton title={active ? `${active.name} · ${active.baseUrl}` : "No connection"} onClick={() => setView("settings")} tone={connected ? undefined : "red"}>+ <Server size={13} />+ <span className="max-w-[160px] truncate">{active?.name ?? "—"}</span>+ {!connected && <span>offline</span>}+ </StatusButton>+ );+}++function AgentState() {+ const agent = useRuntimeState((s) => s.agent);+ const step = useRuntimeState((s) => s.step);+ const prompts = useRuntimeState((s) => s.prompts.length);+ const setView = useUi((s) => s.setView);+ return (+ <StatusButton title="What Mercury is doing" onClick={() => setView("chat")} tone={agent === "needs-you" ? "amber" : undefined}>+ <StateOrb state={agent} size={9} />+ <span>{LABELS[agent]}</span>+ {step?.tool && (agent === "working" || agent === "thinking") && <span className="max-w-[160px] truncate font-mono text-ink4">{step.tool}{step.total ? ` ${step.current}/${step.total}` : ""}</span>}+ {prompts > 0 && <span className="text-amber">· {prompts} waiting</span>}+ </StatusButton>+ );+}++function Background() {+ const bg = usePulse((s) => s.background);+ const bots = useBots((s) => s.bots);+ const activity = useBots((s) => s.activity);+ const runningTasks = bg.tasks.filter((t) => /run|pend|queue/i.test(t.status));+ const workingBots = bots.filter((b) => b.state === "running" || b.state === "queued");+ const agents = bg.agents.filter((a) => !/done|complete|fail|cancel/i.test(a.status));+ const count = runningTasks.length + workingBots.length + agents.length;+ return (+ <StatusPopover width={360} trigger={+ <Trigger title="Background work" tone={count ? "accent" : undefined}>+ <Layers size={13} />+ <span>{count ? `${count} running` : "Idle"}</span>+ </Trigger>+ }>+ <PanelTitle>Background</PanelTitle>+ {count === 0 && <p className="text-sm text-ink3">Nothing running in the background.</p>}+ {workingBots.map((b) => <Line key={b.id} icon={<Bot size={13} />} title={b.name} detail={activity[b.id] ?? b.state} />)}+ {agents.map((a) => <Line key={a.id} icon={<Cpu size={13} />} title={a.task} detail={`sub-agent · ${a.status}${a.tokensUsed ? ` · ${compact(a.tokensUsed)} tok` : ""}`} />)}+ {runningTasks.map((t) => <Line key={t.id} icon={<Layers size={13} />} title={t.description} detail={t.status} />)}+ </StatusPopover>+ );+}++function Schedules() {+ const schedules = usePulse((s) => s.schedules);+ return (+ <StatusPopover width={380} trigger={+ <Trigger title="Schedules">+ <CalendarClock size={13} />+ <span>{schedules.length} scheduled</span>+ </Trigger>+ }>+ <PanelTitle>Schedules · {schedules.length}</PanelTitle>+ {schedules.length === 0 && <p className="text-sm text-ink3">Nothing scheduled.</p>}+ {schedules.map((s) => (+ <Line key={s.id} icon={<CalendarClock size={13} />} title={s.description || s.id}+ detail={[s.cron ? cronLabel(s.cron) : s.delaySeconds ? `in ${s.delaySeconds}s` : "", s.botId ? `bot ${s.botId}` : "", s.nextRun ? `next ${new Date(s.nextRun).toLocaleString([], { hour: "numeric", minute: "2-digit", month: "short", day: "numeric" })}` : ""].filter(Boolean).join(" · ")} />+ ))}+ </StatusPopover>+ );+}++function Tokens() {+ const usage = usePulse((s) => s.usage);+ if (!usage) return null;+ const ratio = usage.dailyBudget ? usage.dailyUsed / usage.dailyBudget : 0;+ const providers = Object.entries(usage.byProvider).filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1]);+ const channels = Object.entries(usage.byChannel).filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1]);+ const models = new Map<string, { tokens: number; requests: number }>();+ let input = 0, output = 0;+ for (const r of usage.requestLog) {+ const m = models.get(r.model) ?? { tokens: 0, requests: 0 };+ m.tokens += r.totalTokens; m.requests += 1;+ models.set(r.model, m);+ input += r.inputTokens; output += r.outputTokens;+ }+ return (+ <StatusPopover width={380} trigger={+ <Trigger title="Tokens used today" tone={ratio > 0.9 ? "red" : ratio > 0.7 ? "amber" : undefined}>+ <Coins size={13} />+ <span>{compact(usage.dailyUsed)}</span>+ <span className="h-1 w-10 overflow-hidden rounded-full bg-ink/[0.12]"><span className={cx("block h-full rounded-full", ratio > 0.9 ? "bg-red" : ratio > 0.7 ? "bg-amber" : "bg-accent")} style={{ width: `${Math.max(3, Math.min(100, ratio * 100))}%` }} /></span>+ </Trigger>+ }>+ <PanelTitle>Tokens today</PanelTitle>+ <div className="mb-3 flex items-baseline justify-between">+ <span className="text-2xl font-semibold tracking-tight">{compact(usage.dailyUsed)}</span>+ <span className="font-mono text-xs text-ink3">of {compact(usage.dailyBudget)} · {compact(usage.remaining)} left</span>+ </div>+ <Breakdown title="By source" rows={channels} total={usage.dailyUsed} />+ <Breakdown title="By provider" rows={providers} total={usage.dailyUsed} />+ {models.size > 0 && (+ <>+ <Breakdown title={`By model · last ${usage.requestLog.length} requests`} rows={[...models.entries()].map(([k, v]) => [k, v.tokens] as [string, number]).sort((a, b) => b[1] - a[1])} total={[...models.values()].reduce((n, m) => n + m.tokens, 0)} />+ <p className="mt-1 text-xs text-ink4">Those requests: {compact(input)} in · {compact(output)} out</p>+ </>+ )}+ </StatusPopover>+ );+}++function Model() {+ const provider = useRuntimeState((s) => s.provider);+ const model = useRuntimeState((s) => s.model);+ if (!model && !provider) return null;+ return (+ <StatusButton title={`${provider} · ${model}`}>+ <Cpu size={13} />+ <span className="max-w-[200px] truncate">{model || provider}</span>+ </StatusButton>+ );+}++function Approval() {+ const [settings, setSettings] = useState<ChatSettings | null>(null);+ const view = useUi((s) => s.view);+ useEffect(() => { void api.chat.settings().then(setSettings).catch(() => {}); }, [view]);+ if (!settings) return null;+ const allowAll = settings.bypassPermissions;+ return (+ <StatusButton title="Click to switch Ask Me / Allow All" tone={allowAll ? "accent" : "amber"}+ onClick={() => void api.chat.updateSettings({ bypassPermissions: !allowAll }).then(setSettings).catch(() => {})}>+ {allowAll ? <ShieldCheck size={13} /> : <Shield size={13} />}+ <span>{allowAll ? "Allow All" : "Ask Me"}</span>+ </StatusButton>+ );+}++function CodeMode() {+ const [status, setStatus] = useState<CodeStatus | null>(null);+ const view = useUi((s) => s.view);+ const setView = useUi((s) => s.setView);+ useEffect(() => { void api.code.status().then(setStatus).catch(() => {}); }, [view]);+ if (!status?.available) return null;+ return (+ <StatusButton title="Code mode" onClick={() => setView("code")} tone={status.state !== "off" ? "cyan" : undefined}>+ <Code2 size={13} />+ <span className="capitalize">{status.state === "off" ? "Code off" : `Code ${status.state}`}</span>+ </StatusButton>+ );+}++function PanelTitle({ children }: { children: React.ReactNode }) {+ return <div className="mb-2 text-2xs font-medium uppercase tracking-wider text-ink4">{children}</div>;+}++function Line({ icon, title, detail }: { icon: React.ReactNode; title: string; detail?: string }) {+ return (+ <div className="flex items-start gap-2 rounded-md px-1 py-1.5">+ <span className="mt-0.5 text-ink3">{icon}</span>+ <span className="min-w-0 flex-1">+ <span className="line-clamp-2 text-sm text-ink">{title}</span>+ {detail && <span className="block truncate text-xs text-ink4">{detail}</span>}+ </span>+ </div>+ );+}++function Breakdown({ title, rows, total }: { title: string; rows: Array<[string, number]>; total: number }) {+ if (rows.length === 0) return null;+ return (+ <div className="mb-3">+ <div className="mb-1.5 text-xs text-ink3">{title}</div>+ {rows.slice(0, 6).map(([k, v]) => (+ <div key={k} className="grid grid-cols-[1fr_90px_52px] items-center gap-2 py-0.5 text-xs">+ <span className="truncate text-ink">{k}</span>+ <span className="h-1.5 overflow-hidden rounded-full bg-ink/[0.08]"><span className="block h-full rounded-full bg-accent" style={{ width: `${total ? (v / total) * 100 : 0}%` }} /></span>+ <span className="text-right font-mono text-ink3">{compact(v)}</span>+ </div>+ ))}+ </div>+ );+}++function cronLabel(cron: string): string {+ const m = /^\*\/(\d+) \* \* \* \*$/.exec(cron.trim());+ if (m) return `every ${m[1]} min`;+ const h = /^0 \*\/(\d+) \* \* \*$/.exec(cron.trim());+ if (h) return `every ${h[1]} h`;+ return cron;+}++let registered = false;++/** Register the built-ins once; plugins call mercuryUi.registerStatusItem the same way. */+export function registerBuiltinStatusItems(): void {+ if (registered) return;+ registered = true;+ mercuryUi.registerStatusItem({ id: "mercury.connection", title: "Connection", area: "status.left", priority: 100, render: Connection });+ mercuryUi.registerStatusItem({ id: "mercury.agent", title: "Agent state", area: "status.left", priority: 90, render: AgentState });+ mercuryUi.registerStatusItem({ id: "mercury.background", title: "Background work", area: "status.left", priority: 80, render: Background });+ mercuryUi.registerStatusItem({ id: "mercury.schedules", title: "Schedules", area: "status.left", priority: 70, render: Schedules });+ mercuryUi.registerStatusItem({ id: "mercury.code", title: "Code mode", area: "status.right", priority: 70, views: ["chat", "code"], render: CodeMode });+ mercuryUi.registerStatusItem({ id: "mercury.approval", title: "Ask Me / Allow All", area: "status.right", priority: 60, views: ["chat", "code"], render: Approval });+ mercuryUi.registerStatusItem({ id: "mercury.model", title: "Model", area: "status.right", priority: 50, views: ["chat", "code"], render: Model });+ mercuryUi.registerStatusItem({ id: "mercury.tokens", title: "Tokens today", area: "status.right", priority: 40, render: Tokens });+}diff --git a/apps/desktop/src/extensions/registry.test.ts b/apps/desktop/src/extensions/registry.test.tsnew file mode 100644index 00000000..294527ab--- /dev/null+++ b/apps/desktop/src/extensions/registry.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";+import { isVisible, orderedIds, type StatusContribution } from "./registry";++const Dummy = () => null;+const item = (id: string, priority: number, extra: Partial<StatusContribution> = {}): StatusContribution => ({ id, title: id, area: "status.left", priority, render: Dummy, ...extra });++describe("status bar contributions", () => {+ it("orders by priority, then by the user's order kept by id", () => {+ const items = { "a.one": item("a.one", 10), "a.two": item("a.two", 30), "a.three": item("a.three", 20) };+ expect(orderedIds(items, { hidden: [], shown: [], order: {} }, "status.left")).toEqual(["a.two", "a.three", "a.one"]);+ const layout = { hidden: [], shown: [], order: { "status.left": ["a.one", "gone.item"] } };+ expect(orderedIds(items, layout, "status.left")).toEqual(["a.one", "a.two", "a.three"]);+ });++ it("respects hidden and default-hidden items", () => {+ const shown = item("a.x", 1);+ const opt = item("a.y", 1, { defaultHidden: true });+ expect(isVisible(shown, { hidden: [], shown: [], order: {} })).toBe(true);+ expect(isVisible(shown, { hidden: ["a.x"], shown: [], order: {} })).toBe(false);+ expect(isVisible(opt, { hidden: [], shown: [], order: {} })).toBe(false);+ expect(isVisible(opt, { hidden: [], shown: ["a.y"], order: {} })).toBe(true);+ });+});diff --git a/apps/desktop/src/extensions/registry.ts b/apps/desktop/src/extensions/registry.tsnew file mode 100644index 00000000..5285547a--- /dev/null+++ b/apps/desktop/src/extensions/registry.ts@@ -0,0 +1,134 @@+/* ═══════════════════════════════════════════════════════════════+ UI contribution registry — the extension point for the app chrome.++ Everything in the status bar (and, later, the environment bar, the+ command palette and view toolbars) is a CONTRIBUTION: an object with a+ stable id that a module registers. Built-in items register the same way+ a future UI plugin will, so plugins get no special path and built-ins+ get no special privileges.++ The user's layout is stored BY ID (hidden, order), never by position, so+ adding or removing contributions never scrambles someone's setup.++ Contract for a contribution (keep it stable; plugins will depend on it):+ id "<owner>.<name>", e.g. "mercury.tokens", "optimus.screen"+ title what the Customize menu calls it+ area "status.left" | "status.right"+ priority higher sits further left within its area (VS Code's rule)+ views the views it appears in; omit for all+ render a React component, mounted while visible+ defaultHidden start hidden until the user turns it on+ ═══════════════════════════════════════════════════════════════ */++import { create } from "zustand";+import type { ComponentType } from "react";+import type { View } from "~/app/store";++export type ContributionArea = "status.left" | "status.right";++export interface StatusContribution {+ id: string;+ title: string;+ area: ContributionArea;+ priority: number;+ views?: View[];+ render: ComponentType;+ defaultHidden?: boolean;+ /** Who contributed it: "mercury" for built-ins, a plugin id otherwise. */+ source?: string;+}++interface Layout {+ hidden: string[];+ shown: string[];+ /** User order per area, by id; ids not listed fall back to priority. */+ order: Partial<Record<ContributionArea, string[]>>;+}++interface RegistryState {+ items: Record<string, StatusContribution>;+ layout: Layout;+ register(item: StatusContribution): () => void;+ setVisible(id: string, visible: boolean): void;+ move(id: string, direction: -1 | 1): void;+ reset(): void;+}++const LAYOUT_KEY = "mercury.statusbar.layout.v1";+const EMPTY: Layout = { hidden: [], shown: [], order: {} };++function readLayout(): Layout {+ try {+ const raw = JSON.parse(localStorage.getItem(LAYOUT_KEY) ?? "null") as Layout | null;+ if (!raw || !Array.isArray(raw.hidden)) return EMPTY;+ return { hidden: raw.hidden, shown: Array.isArray(raw.shown) ? raw.shown : [], order: raw.order ?? {} };+ } catch {+ return EMPTY;+ }+}++function writeLayout(layout: Layout): void {+ try { localStorage.setItem(LAYOUT_KEY, JSON.stringify(layout)); } catch { /* private mode */ }+}++const ID_RE = /^[a-z0-9][a-z0-9-]*\.[a-z0-9][a-z0-9.-]*$/;++export const useContributions = create<RegistryState>((set, get) => ({+ items: {},+ layout: readLayout(),+ register(item) {+ if (!ID_RE.test(item.id)) throw new Error(`Contribution id must look like "owner.name": ${item.id}`);+ set((s) => ({ items: { ...s.items, [item.id]: { source: "mercury", ...item } } }));+ return () => set((s) => {+ const items = { ...s.items };+ delete items[item.id];+ return { items };+ });+ },+ setVisible(id, visible) {+ const { layout } = get();+ const next: Layout = {+ ...layout,+ hidden: visible ? layout.hidden.filter((x) => x !== id) : [...new Set([...layout.hidden, id])],+ shown: visible ? [...new Set([...layout.shown, id])] : layout.shown.filter((x) => x !== id),+ };+ writeLayout(next);+ set({ layout: next });+ },+ move(id, direction) {+ const item = get().items[id];+ if (!item) return;+ const ordered = orderedIds(get().items, get().layout, item.area);+ const i = ordered.indexOf(id);+ const j = i + direction;+ if (i < 0 || j < 0 || j >= ordered.length) return;+ [ordered[i], ordered[j]] = [ordered[j], ordered[i]];+ const next: Layout = { ...get().layout, order: { ...get().layout.order, [item.area]: ordered } };+ writeLayout(next);+ set({ layout: next });+ },+ reset() {+ writeLayout(EMPTY);+ set({ layout: EMPTY });+ },+}));++export function isVisible(item: StatusContribution, layout: Layout): boolean {+ if (layout.hidden.includes(item.id)) return false;+ if (item.defaultHidden) return layout.shown.includes(item.id);+ return true;+}++/** Ids in an area in display order: the user's order first, then by priority. */+export function orderedIds(items: Record<string, StatusContribution>, layout: Layout, area: ContributionArea): string[] {+ const inArea = Object.values(items).filter((i) => i.area === area);+ const custom = (layout.order[area] ?? []).filter((id) => inArea.some((i) => i.id === id));+ const rest = inArea.filter((i) => !custom.includes(i.id)).sort((a, b) => b.priority - a.priority || a.id.localeCompare(b.id)).map((i) => i.id);+ // Items new since the user ordered go in by priority relative to the custom block's end.+ return [...custom, ...rest];+}++/** Public surface for UI add-ons. Stable names; extend, never rename. */+export const mercuryUi = {+ registerStatusItem: (item: StatusContribution) => useContributions.getState().register(item),+};diff --git a/apps/desktop/src/layout/EnvironmentBar.tsx b/apps/desktop/src/layout/EnvironmentBar.tsxnew file mode 100644index 00000000..3242be22--- /dev/null+++ b/apps/desktop/src/layout/EnvironmentBar.tsx@@ -0,0 +1,106 @@+import * as Dropdown from "@radix-ui/react-dropdown-menu";+import { Check, ChevronDown, Cloud, Laptop, Plus, Server, Settings2, UserRound } from "lucide-react";+import type { HealthInfo } from "~/api/types";+import { cx } from "~/lib/cx";+import { usePulse } from "~/app/pulse";+import { useRuntimeState, useUi } from "~/app/store";+import { useConnections, type Connection } from "~/shell/connections";+import { StateOrb } from "~/components/indicators/StateOrb";++/**+ * Where am I? The strip across the top of the window answers it at a+ * glance, every time: which environment (this computer, a remote server,+ * Mercury Cloud), who is signed in, which server this window is talking to,+ * and what that runtime is. Click it to switch.+ */++// macOS draws the traffic lights over this bar (titleBarStyle: Overlay).+const IS_MAC = typeof navigator !== "undefined" && /Mac/i.test(navigator.platform || navigator.userAgent);++export type Environment = "local" | "remote" | "cloud";++export function environmentOf(c: Connection): Environment {+ if (c.kind === "local") return "local";+ try {+ const host = new URL(c.baseUrl).hostname;+ if (/(^|\.)mercury(agent)?\.(sh|cloud|ai)$/i.test(host) || host.includes("mercury-cloud")) return "cloud";+ } catch { /* fall through */ }+ return "remote";+}++const ENV = {+ local: { label: "This computer", icon: Laptop, tone: "text-ink2 bg-ink/[0.06]" },+ remote: { label: "Remote", icon: Server, tone: "text-cyan bg-cyan/10" },+ cloud: { label: "Mercury Cloud", icon: Cloud, tone: "text-accent bg-accent/10" },+} as const;++export function EnvironmentBar({ connection, health }: { connection: Connection; health: HealthInfo }) {+ const owner = usePulse((s) => s.owner);+ const agentName = usePulse((s) => s.agentName);+ const connected = useRuntimeState((s) => s.connected);+ const agent = useRuntimeState((s) => s.agent);+ const env = environmentOf(connection);+ const E = ENV[env];+ const host = hostOf(connection.baseUrl);+ const signedIn = connection.kind === "local" ? owner || "owner" : owner ? `${owner} · this device` : "this device";++ return (+ <div className={cx("flex h-9 shrink-0 items-center gap-3 border-b border-line bg-soft pr-3 text-xs", IS_MAC ? "pl-[84px]" : "pl-3")} data-tauri-drag-region>+ <Switcher current={connection}>+ <button className="flex h-6 items-center gap-2 rounded-md px-1.5 hover:bg-ink/[0.06] data-[state=open]:bg-ink/[0.06]" data-no-drag aria-label="Switch environment">+ <StateOrb state={connected ? agent : "offline"} size={9} />+ <span className="font-medium text-ink">{agentName || "Mercury"}</span>+ <span className="text-ink4">on</span>+ <span className="max-w-[200px] truncate font-medium text-ink">{connection.name}</span>+ <ChevronDown size={12} className="text-ink4" />+ </button>+ </Switcher>++ <span className={cx("flex h-5 items-center gap-1 rounded-full px-2 font-medium", E.tone)}><E.icon size={11} />{E.label}</span>+ <span className="flex items-center gap-1 text-ink3" title="Signed in as"><UserRound size={12} />{signedIn}</span>+ <span className="font-mono text-ink4" title={connection.baseUrl} data-selectable>{host}</span>++ <div className="flex-1" data-tauri-drag-region />++ <span className="font-mono text-ink4" title={`Runtime ${health.version} · API v${health.apiVersion ?? "?"} · pid ${health.pid}`}>+ Mercury {health.version || "?"} · API v{health.apiVersion ?? "?"}+ </span>+ </div>+ );+}++function Switcher({ current, children }: { current: Connection; children: React.ReactNode }) {+ const connections = useConnections((s) => s.connections);+ const setActive = useConnections((s) => s.setActive);+ const setView = useUi((s) => s.setView);+ return (+ <Dropdown.Root>+ <Dropdown.Trigger asChild>{children}</Dropdown.Trigger>+ <Dropdown.Portal>+ <Dropdown.Content align="start" sideOffset={6} className="z-50 w-[320px] rounded-xl border border-line bg-raised p-1 text-sm text-ink shadow-xl animate-fade-in">+ <div className="px-2 pb-1 pt-1.5 text-2xs font-medium uppercase tracking-wider text-ink4">Environments</div>+ {connections.map((c) => {+ const E = ENV[environmentOf(c)];+ return (+ <Dropdown.Item key={c.id} onSelect={() => { if (c.id !== current.id) void setActive(c.id); }} className="flex cursor-default items-center gap-2.5 rounded-lg px-2 py-2 outline-none data-[highlighted]:bg-ink/[0.06]">+ <span className={cx("flex h-7 w-7 items-center justify-center rounded-lg", E.tone)}><E.icon size={14} /></span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm">{c.name}</span>+ <span className="block truncate font-mono text-2xs text-ink4">{E.label} · {hostOf(c.baseUrl)}</span>+ </span>+ {c.id === current.id && <Check size={14} className="text-accent" />}+ </Dropdown.Item>+ );+ })}+ <Dropdown.Separator className="my-1 h-px bg-line" />+ <Dropdown.Item onSelect={() => setView("settings")} className="flex cursor-default items-center gap-2 rounded-md px-2 py-1.5 outline-none data-[highlighted]:bg-ink/[0.06]"><Plus size={14} className="text-ink3" /> Add a connection…</Dropdown.Item>+ <Dropdown.Item onSelect={() => setView("settings")} className="flex cursor-default items-center gap-2 rounded-md px-2 py-1.5 outline-none data-[highlighted]:bg-ink/[0.06]"><Settings2 size={14} className="text-ink3" /> Manage connections</Dropdown.Item>+ </Dropdown.Content>+ </Dropdown.Portal>+ </Dropdown.Root>+ );+}++function hostOf(url: string): string {+ try { return new URL(url).host; } catch { return url; }+}diff --git a/apps/desktop/src/layout/StatusBar.tsx b/apps/desktop/src/layout/StatusBar.tsxnew file mode 100644index 00000000..f469a3af--- /dev/null+++ b/apps/desktop/src/layout/StatusBar.tsx@@ -0,0 +1,109 @@+import * as ContextMenu from "@radix-ui/react-dropdown-menu";+import { ArrowLeft, ArrowRight, Check } from "lucide-react";+import { useState, type ReactNode } from "react";+import { cx } from "~/lib/cx";+import { useUi } from "~/app/store";+import { isVisible, orderedIds, useContributions, type ContributionArea } from "~/extensions/registry";++/**+ * The bottom bar. It renders whatever is registered (extensions/registry),+ * filtered to the current view and the user's layout. Right-click anywhere+ * on it to choose items and their order — the VS Code model.+ */+export function StatusBar() {+ const items = useContributions((s) => s.items);+ const layout = useContributions((s) => s.layout);+ const view = useUi((s) => s.view);+ const [menuOpen, setMenuOpen] = useState(false);++ const visibleIn = (area: ContributionArea) =>+ orderedIds(items, layout, area)+ .map((id) => items[id])+ .filter((i) => i && isVisible(i, layout) && (!i.views || i.views.includes(view)));++ return (+ <footer+ className="relative flex h-7 shrink-0 select-none items-center gap-0.5 border-t border-line bg-soft px-1.5 text-xs text-ink3"+ onContextMenu={(e) => { e.preventDefault(); setMenuOpen(true); }}+ role="status"+ aria-label="Status bar"+ >+ {visibleIn("status.left").map((i) => { const C = i.render; return <C key={i.id} />; })}+ <div className="flex-1" />+ {visibleIn("status.right").map((i) => { const C = i.render; return <C key={i.id} />; })}+ <CustomizeMenu open={menuOpen} onOpenChange={setMenuOpen} />+ </footer>+ );+}++function CustomizeMenu({ open, onOpenChange }: { open: boolean; onOpenChange: (o: boolean) => void }) {+ const items = useContributions((s) => s.items);+ const layout = useContributions((s) => s.layout);+ const setVisible = useContributions((s) => s.setVisible);+ const move = useContributions((s) => s.move);+ const reset = useContributions((s) => s.reset);+ const areas: Array<[ContributionArea, string]> = [["status.left", "Left"], ["status.right", "Right"]];+ return (+ <ContextMenu.Root open={open} onOpenChange={onOpenChange}>+ <ContextMenu.Trigger asChild><span className="absolute bottom-full right-2 h-0 w-0" aria-hidden="true" /></ContextMenu.Trigger>+ <ContextMenu.Portal>+ <ContextMenu.Content side="top" align="end" sideOffset={4} className="z-50 w-[300px] rounded-lg border border-line bg-raised p-1 text-sm text-ink shadow-xl animate-fade-in">+ <div className="px-2 pb-1 pt-1.5 text-2xs font-medium uppercase tracking-wider text-ink4">Status bar items</div>+ {areas.map(([area, label]) => (+ <div key={area}>+ <div className="px-2 pt-1.5 text-2xs text-ink4">{label}</div>+ {orderedIds(items, layout, area).map((id) => {+ const item = items[id];+ const on = isVisible(item, layout);+ return (+ <div key={id} className="group flex items-center gap-1 rounded-md pr-1 hover:bg-ink/[0.06]">+ <ContextMenu.Item onSelect={(e) => { e.preventDefault(); setVisible(id, !on); }} className="flex flex-1 cursor-default items-center gap-2 rounded-md px-2 py-1.5 outline-none">+ <span className="flex h-4 w-4 items-center justify-center rounded border border-line-strong">{on && <Check size={12} className="text-accent" />}</span>+ <span className="flex-1 truncate">{item.title}</span>+ {item.source && item.source !== "mercury" && <span className="text-2xs text-ink4">{item.source}</span>}+ </ContextMenu.Item>+ <button onClick={() => move(id, -1)} className="hidden rounded p-0.5 text-ink4 hover:text-ink group-hover:block" aria-label={`Move ${item.title} left`}><ArrowLeft size={12} /></button>+ <button onClick={() => move(id, 1)} className="hidden rounded p-0.5 text-ink4 hover:text-ink group-hover:block" aria-label={`Move ${item.title} right`}><ArrowRight size={12} /></button>+ </div>+ );+ })}+ </div>+ ))}+ <ContextMenu.Separator className="my-1 h-px bg-line" />+ <ContextMenu.Item onSelect={() => reset()} className="cursor-default rounded-md px-2 py-1.5 outline-none data-[highlighted]:bg-ink/[0.06]">Reset to default</ContextMenu.Item>+ </ContextMenu.Content>+ </ContextMenu.Portal>+ </ContextMenu.Root>+ );+}++/** A clickable status bar entry. Items use this so they look and behave alike. */+export function StatusButton({ children, title, onClick, tone, className }: { children: ReactNode; title: string; onClick?: () => void; tone?: "accent" | "amber" | "red" | "cyan"; className?: string }) {+ return (+ <button+ onClick={onClick}+ title={title}+ className={cx(+ "flex h-[22px] items-center gap-1.5 rounded px-1.5 transition-colors hover:bg-ink/[0.07] hover:text-ink",+ tone === "accent" && "text-accent", tone === "amber" && "text-amber", tone === "red" && "text-red", tone === "cyan" && "text-cyan",+ className,+ )}+ >+ {children}+ </button>+ );+}++/** A status entry that opens a panel upwards (lists, breakdowns). */+export function StatusPopover({ trigger, children, width = 340 }: { trigger: ReactNode; children: ReactNode; width?: number }) {+ return (+ <ContextMenu.Root>+ <ContextMenu.Trigger asChild>{trigger}</ContextMenu.Trigger>+ <ContextMenu.Portal>+ <ContextMenu.Content side="top" align="start" sideOffset={6} style={{ width }} className="z-50 max-h-[60vh] overflow-y-auto rounded-xl border border-line bg-raised p-3 text-sm text-ink shadow-xl animate-fade-in">+ {children}+ </ContextMenu.Content>+ </ContextMenu.Portal>+ </ContextMenu.Root>+ );+}diff --git a/apps/desktop/src/layout/Workspace.tsx b/apps/desktop/src/layout/Workspace.tsxindex 51fbb1e2..e4dee721 100644--- a/apps/desktop/src/layout/Workspace.tsx+++ b/apps/desktop/src/layout/Workspace.tsx@@ -1,9 +1,13 @@import { useEffect } from "react";import { useUi, type View } from "~/app/store";import { useRuntimeEvents, refreshBots, refreshThreads } from "~/app/events";+import { usePulsePolling } from "~/app/pulse";+import { registerBuiltinStatusItems } from "~/extensions/builtin-status";import type { Connection } from "~/shell/connections";import type { HealthInfo } from "~/api/types";import { Rail } from "./Rail";+import { EnvironmentBar } from "./EnvironmentBar";+import { StatusBar } from "./StatusBar";import { ChatView } from "~/views/chat/ChatView";import { CodeView } from "~/views/code/CodeView";import { BotsView } from "~/views/bots/BotsView";@@ -11,13 +15,18 @@ import { PluginsView } from "~/views/plugins/PluginsView";import { SkillsView } from "~/views/skills/SkillsView";import { SettingsView } from "~/views/settings/SettingsView";+registerBuiltinStatusItems();+/**- * Everything after a connection is up. All views stay mounted; the active- * one is shown. No lazy chunks, no transitions: the app is already here.+ * Everything after a connection is up:+ * environment bar which Mercury, where, who+ * rail | view all views mounted; the active one shown+ * status bar registered items, user-customisable*/export function Workspace({ connection, health, onSwitchConnection }: { connection: Connection; health: HealthInfo; onSwitchConnection: () => void }) {const view = useUi((s) => s.view);useRuntimeEvents(true);+ usePulsePolling(connection.id);useEffect(() => {void refreshThreads();@@ -25,16 +34,20 @@ export function Workspace({ connection, health, onSwitchConnection }: { connecti}, [connection.id]);return (- <div className="flex h-full w-full overflow-hidden bg-bg">- <Rail connectionName={connection.name} />- <main className="relative flex min-w-0 flex-1 flex-col">- <Pane active={view === "chat"}><ChatView mode="chat" /></Pane>- <Pane active={view === "code"}><CodeView /></Pane>- <Pane active={view === "bots"}><BotsView /></Pane>- <Pane active={view === "plugins"}><PluginsView /></Pane>- <Pane active={view === "skills"}><SkillsView /></Pane>- <Pane active={view === "settings"}><SettingsView connection={connection} health={health} onSwitchConnection={onSwitchConnection} /></Pane>- </main>+ <div className="flex h-full w-full flex-col overflow-hidden bg-bg">+ <EnvironmentBar connection={connection} health={health} />+ <div className="flex min-h-0 flex-1">+ <Rail connectionName={connection.name} />+ <main className="relative flex min-w-0 flex-1 flex-col">+ <Pane active={view === "chat"}><ChatView mode="chat" /></Pane>+ <Pane active={view === "code"}><CodeView /></Pane>+ <Pane active={view === "bots"}><BotsView /></Pane>+ <Pane active={view === "plugins"}><PluginsView /></Pane>+ <Pane active={view === "skills"}><SkillsView /></Pane>+ <Pane active={view === "settings"}><SettingsView connection={connection} health={health} onSwitchConnection={onSwitchConnection} /></Pane>+ </main>+ </div>+ <StatusBar /></div>);}diff --git a/apps/desktop/src/views/settings/SettingsView.tsx b/apps/desktop/src/views/settings/SettingsView.tsxindex c6bbc3ca..69e67383 100644--- a/apps/desktop/src/views/settings/SettingsView.tsx+++ b/apps/desktop/src/views/settings/SettingsView.tsx@@ -1,4 +1,4 @@-import { Info, Palette, Power, Server, Smartphone } from "lucide-react";+import { Info, PanelBottom, Palette, Power, Server, Smartphone } from "lucide-react";import { useEffect, useState } from "react";import { cx } from "~/lib/cx";import * as api from "~/api/mercury";@@ -12,15 +12,17 @@ import { Badge, Mono, Segmented } from "~/components/ui/bits";import { Dialog } from "~/components/ui/Dialog";import { AddRemote } from "~/shell/AddRemote";import { StateOrb } from "~/components/indicators/StateOrb";+import { isVisible, orderedIds, useContributions, type ContributionArea } from "~/extensions/registry";/*** Settings: a section list on the left, one section on the right. Most-used* first (Appearance), plain labels, every control explains itself in one line.*/-type Section = "appearance" | "connections" | "devices" | "startup" | "about";+type Section = "appearance" | "statusbar" | "connections" | "devices" | "startup" | "about";const SECTIONS: Array<{ id: Section; label: string; icon: typeof Palette }> = [{ id: "appearance", label: "Appearance", icon: Palette },+ { id: "statusbar", label: "Status bar", icon: PanelBottom },{ id: "connections", label: "Connections", icon: Server },{ id: "devices", label: "Paired devices", icon: Smartphone },{ id: "startup", label: "Start-up", icon: Power },@@ -49,6 +51,7 @@ export function SettingsView({ connection, health, onSwitchConnection }: { conne<div className="mx-auto flex max-w-[680px] flex-col gap-6 px-8 py-8"><h1 className="text-xl font-semibold tracking-tight text-ink">{SECTIONS.find((s) => s.id === section)?.label}</h1>{section === "appearance" && <Appearance />}+ {section === "statusbar" && <StatusBarSettings />}{section === "connections" && <Connections current={connection} health={health} onSwitchConnection={onSwitchConnection} />}{section === "devices" && <Devices current={connection} />}{section === "startup" && <Startup />}@@ -203,3 +206,31 @@ function About({ health }: { health: HealthInfo }) {</section>);}++function StatusBarSettings() {+ const items = useContributions((s) => s.items);+ const layout = useContributions((s) => s.layout);+ const setVisible = useContributions((s) => s.setVisible);+ const reset = useContributions((s) => s.reset);+ const areas: Array<[ContributionArea, string]> = [["status.left", "Left side"], ["status.right", "Right side"]];+ return (+ <section className="flex flex-col gap-4">+ <p className="text-sm text-ink3">Choose what the bar at the bottom of the window shows. Right-click the bar for the same list and to reorder items. Plugins can add items here too.</p>+ {areas.map(([area, label]) => (+ <div key={area} className="overflow-hidden rounded-lg border border-line bg-surface">+ <div className="border-b border-line px-4 py-2 text-xs font-medium uppercase tracking-wider text-ink4">{label}</div>+ {orderedIds(items, layout, area).map((id) => {+ const item = items[id];+ return (+ <div key={id} className="flex items-center justify-between border-b border-line px-4 py-2.5 last:border-b-0">+ <span className="text-sm text-ink">{item.title}{item.views ? <span className="ml-2 text-xs text-ink4">in {item.views.join(", ")}</span> : null}</span>+ <Switch id={`sb-${id}`} checked={isVisible(item, layout)} onCheckedChange={(v) => setVisible(id, v)} />+ </div>+ );+ })}+ </div>+ ))}+ <div><Button variant="outline" onClick={reset}>Reset to default</Button></div>+ </section>+ );+}