Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(desktop): bot tabs — deliverables, activity with thought process, usage; delete

Salman Qureshi4cf7a8c38587
diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.ts
index e1b24130..eb25e758 100644
--- a/apps/desktop/src/api/mercury.ts
+++ b/apps/desktop/src/api/mercury.ts
@@ -6,7 +6,7 @@
import { http, ApiError } from "./client";
import type {
BotManifest, BotRunRecord, BotStatus, ChatMessage, ChatSettings, ChatThread, CodeStatus, HealthInfo,
- McpServer, ModelsResponse, CodeMode, PairResponse, PluginItem, ReasoningChoice, Skill, DeviceSummary,
+ McpServer, ModelsResponse, CodeMode, CostReport, Deliverable, RunTranscript, PairResponse, PluginItem, ReasoningChoice, Skill, DeviceSummary,
} from "./types";
export const health = {
@@ -71,8 +71,16 @@ export const bots = {
enable: (id: string) => http.post<{ ok: boolean }>(`/api/bots/${encodeURIComponent(id)}/enable`),
disable: (id: string) => http.post<{ ok: boolean }>(`/api/bots/${encodeURIComponent(id)}/disable`),
stop: (id: string) => http.post<{ ok: boolean }>(`/api/bots/${encodeURIComponent(id)}/stop`),
+ remove: (id: string) => http.delete<{ ok: boolean }>(`/api/bots/${encodeURIComponent(id)}`),
+ journal: (id: string, limit = 60) => http.get<{ journal: BotRunRecord[] }>(`/api/bots/${encodeURIComponent(id)}/journal?limit=${limit}`),
+ run: (id: string, runId: string) => http.get<RunTranscript>(`/api/bots/${encodeURIComponent(id)}/runs/${encodeURIComponent(runId)}`),
+ outputs: (id: string) => http.get<{ outputs: Deliverable[] }>(`/api/bots/${encodeURIComponent(id)}/outputs`),
+ outputPreview: (id: string, name: string) => http.get<{ preview: string; truncated: boolean }>(`/api/bots/${encodeURIComponent(id)}/outputs/${encodeURIComponent(name)}/preview`),
+ outputDownloadPath: (id: string, name: string) => `/api/bots/${encodeURIComponent(id)}/outputs/${encodeURIComponent(name)}/download`,
+ deleteOutput: (id: string, name: string) => http.delete<{ ok: boolean }>(`/api/bots/${encodeURIComponent(id)}/outputs/${encodeURIComponent(name)}`),
+ cost: (days: number) => http.get<CostReport>(`/api/bots-cost?days=${days}`),
avatarUrl: (id: string) => `/api/bots/${encodeURIComponent(id)}/avatar`,
- run: (id: string) => http.post<{ accepted: boolean }>(`/api/bots/${encodeURIComponent(id)}/run`, {}),
+ runNow: (id: string) => http.post<{ accepted: boolean }>(`/api/bots/${encodeURIComponent(id)}/run`, {}),
};
export const plugins = {
diff --git a/apps/desktop/src/api/types.ts b/apps/desktop/src/api/types.ts
index 9ff53f6f..f0a9e12b 100644
--- a/apps/desktop/src/api/types.ts
+++ b/apps/desktop/src/api/types.ts
@@ -144,6 +144,50 @@ export interface BotRunRecord {
summary?: string;
error?: string;
reasonCode?: string;
+ steps?: number;
+ toolCalls?: number;
+ outcome?: string;
+}
+
+export interface Deliverable {
+ botId: string;
+ name: string;
+ bytes: number;
+ mtimeMs: number;
+ path?: string;
+ final?: boolean;
+}
+
+export interface RunTraceStep {
+ name: string;
+ ok: boolean;
+ arg?: string;
+}
+
+export interface RunTranscript {
+ record: BotRunRecord & { steps?: number; toolCalls?: number; peakInputTokens?: number; outcome?: string };
+ prompt: string;
+ output: string;
+ trace: RunTraceStep[];
+}
+
+export interface UsageBucket {
+ runs: number;
+ completed: number;
+ failed: number;
+ noOutcome: number;
+ deliverables: number;
+ tokensIn: number;
+ tokensOut: number;
+}
+
+export interface CostReport {
+ days: number;
+ bots: Array<{ id: string; name: string; parent?: string; today: UsageBucket; window: UsageBucket; cap: number; paused: boolean }>;
+ fleets: Array<{ id: string; name: string; members: number; today: UsageBucket; window: UsageBucket }>;
+ fleetToday: number;
+ fleetCap: number;
+ fleetPaused: boolean;
}
export interface BotActivityEvent {
diff --git a/apps/desktop/src/views/bots/Activity.tsx b/apps/desktop/src/views/bots/Activity.tsx
new file mode 100644
index 00000000..60a45f16
--- /dev/null
+++ b/apps/desktop/src/views/bots/Activity.tsx
@@ -0,0 +1,130 @@
+import { Check, ChevronRight, CircleAlert } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import * as api from "~/api/mercury";
+import type { BotRunRecord, RunTranscript } from "~/api/types";
+import { Badge, Empty, Mono, Spinner } from "~/components/ui/bits";
+import { BotAvatar } from "~/components/BotAvatar";
+import { Markdown } from "~/components/Markdown";
+import { cx } from "~/lib/cx";
+import { compact } from "./Usage";
+
+/**
+ * Activity: every run, newest first, across the fleet for a lead. Open a
+ * run to see its thought process: what it was asked, each step it took
+ * (tool, argument, worked or not) as a timeline, and what it concluded.
+ */
+export function Activity({ bots }: { bots: Array<{ id: string; name: string; hasAvatar?: boolean }> }) {
+ const [runs, setRuns] = useState<BotRunRecord[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [open, setOpen] = useState<string | null>(null);
+ const [filter, setFilter] = useState<"all" | "completed" | "failed">("all");
+ const ids = bots.map((b) => b.id).join(",");
+ const byId = useMemo(() => new Map(bots.map((b) => [b.id, b])), [ids]);
+
+ useEffect(() => {
+ let live = true;
+ setLoading(true);
+ void Promise.all(bots.map((b) => api.bots.journal(b.id, 60).then((r) => r.journal).catch(() => [] as BotRunRecord[])))
+ .then((all) => { if (live) { setRuns(all.flat().sort((a, b) => b.startedAt - a.startedAt)); setLoading(false); } });
+ return () => { live = false; };
+ }, [ids]);
+
+ const shown = runs.filter((r) => filter === "all" || (filter === "failed" ? r.state === "failed" : r.state === "completed"));
+ if (loading) return <div className="flex h-40 items-center justify-center text-ink3"><Spinner size={18} /></div>;
+ if (runs.length === 0) return <Empty title="No runs yet" />;
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="mb-1 flex items-center gap-2 text-sm">
+ {(["all", "completed", "failed"] as const).map((f) => (
+ <button key={f} onClick={() => setFilter(f)} className={cx("rounded-full px-3 py-1 capitalize", filter === f ? "bg-ink/[0.08] text-ink" : "text-ink3 hover:text-ink")}>
+ {f} {f === "all" ? runs.length : runs.filter((r) => r.state === f).length}
+ </button>
+ ))}
+ </div>
+ {shown.map((r) => {
+ const bot = byId.get(r.botId);
+ const isOpen = open === `${r.botId}/${r.runId}`;
+ return (
+ <div key={`${r.botId}/${r.runId}`} className={cx("rounded-xl border bg-surface", r.state === "failed" ? "border-red/25" : "border-line")}>
+ <button onClick={() => setOpen(isOpen ? null : `${r.botId}/${r.runId}`)} className="flex w-full items-center gap-3 px-4 py-3 text-left" aria-expanded={isOpen}>
+ <ChevronRight size={15} className={cx("shrink-0 text-ink4 transition-transform", isOpen && "rotate-90")} aria-hidden="true" />
+ {bots.length > 1 && bot && <BotAvatar id={bot.id} name={bot.name} hasAvatar={bot.hasAvatar} size={22} />}
+ <span className="min-w-0 flex-1">
+ <span className="line-clamp-1 text-sm text-ink">{r.summary || r.error || r.reasonCode || r.state}</span>
+ <span className="text-xs text-ink4">{bots.length > 1 && bot ? `${bot.name} · ` : ""}{new Date(r.startedAt).toLocaleString([], { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })} · {r.trigger}</span>
+ </span>
+ <Badge tone={r.state === "completed" ? "accent" : r.state === "failed" ? "red" : "neutral"}>{r.state}</Badge>
+ <Mono className="w-[150px] shrink-0 text-right">{Math.round(r.durationMs / 1000)}s · {compact(r.tokensIn + r.tokensOut)} tok</Mono>
+ </button>
+ {isOpen && <RunDetail botId={r.botId} runId={r.runId} />}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+function RunDetail({ botId, runId }: { botId: string; runId: string }) {
+ const [t, setT] = useState<RunTranscript | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ useEffect(() => {
+ let live = true;
+ api.bots.run(botId, runId).then((x) => { if (live) setT(x); }).catch((e) => { if (live) setError(e instanceof Error ? e.message : String(e)); });
+ return () => { live = false; };
+ }, [botId, runId]);
+
+ if (error) return <p className="px-5 pb-4 text-sm text-ink3">No transcript for this run ({error}).</p>;
+ if (!t) return <div className="px-5 pb-4 text-ink3"><Spinner size={14} /></div>;
+ const rec = t.record;
+ const failedSteps = t.trace.filter((s) => !s.ok).length;
+ return (
+ <div className="grid grid-cols-[1fr_220px] gap-6 border-t border-line px-5 py-4">
+ <div className="flex min-w-0 flex-col gap-4">
+ {t.prompt && (
+ <section>
+ <h4 className="mb-1.5 text-xs font-medium uppercase tracking-wider text-ink4">Asked</h4>
+ <p className="whitespace-pre-wrap text-sm text-ink2" data-selectable>{t.prompt}</p>
+ </section>
+ )}
+ <section>
+ <h4 className="mb-2 text-xs font-medium uppercase tracking-wider text-ink4">Thought process · {t.trace.length} step{t.trace.length === 1 ? "" : "s"}{failedSteps ? ` · ${failedSteps} failed` : ""}</h4>
+ {t.trace.length === 0 && <p className="text-sm text-ink4">Answered without tools.</p>}
+ <ol className="relative ml-2 border-l border-line">
+ {t.trace.map((s, i) => (
+ <li key={i} className="relative pb-3 pl-5 last:pb-0">
+ <span className={cx("absolute -left-[9px] top-0.5 flex h-[17px] w-[17px] items-center justify-center rounded-full border bg-surface", s.ok ? "border-accent/50 text-accent" : "border-red/50 text-red")}>
+ {s.ok ? <Check size={11} strokeWidth={3} /> : <CircleAlert size={11} strokeWidth={2.5} />}
+ </span>
+ <span className="font-mono text-[13px] text-ink">{s.name}</span>
+ {s.arg && <span className="ml-2 break-all font-mono text-xs text-ink3" data-selectable>{s.arg}</span>}
+ </li>
+ ))}
+ </ol>
+ </section>
+ <section>
+ <h4 className="mb-1.5 text-xs font-medium uppercase tracking-wider text-ink4">Concluded</h4>
+ <Markdown text={t.output || rec.summary || "(no output)"} />
+ </section>
+ </div>
+ <aside className="flex flex-col gap-3 text-sm">
+ <Stat label="Outcome" value={rec.outcome ?? rec.state} />
+ <Stat label="Duration" value={`${(rec.durationMs / 1000).toFixed(1)} s`} />
+ <Stat label="Steps / tool calls" value={`${rec.steps ?? "—"} / ${rec.toolCalls ?? t.trace.length}`} />
+ <Stat label="Tokens in" value={rec.tokensIn.toLocaleString()} />
+ <Stat label="Tokens out" value={rec.tokensOut.toLocaleString()} />
+ {rec.peakInputTokens !== undefined && <Stat label="Largest prompt" value={`${rec.peakInputTokens.toLocaleString()} tok`} />}
+ <Stat label="Run" value={<Mono>{rec.runId}</Mono>} />
+ </aside>
+ </div>
+ );
+}
+
+function Stat({ label, value }: { label: string; value: React.ReactNode }) {
+ return (
+ <div>
+ <div className="text-xs text-ink4">{label}</div>
+ <div className="text-ink">{value}</div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/views/bots/BotsView.tsx b/apps/desktop/src/views/bots/BotsView.tsx
index 1f09fc9a..957343eb 100644
--- a/apps/desktop/src/views/bots/BotsView.tsx
+++ b/apps/desktop/src/views/bots/BotsView.tsx
@@ -1,8 +1,8 @@
-import { ChevronDown, Play, RefreshCw, Square } from "lucide-react";
+import { ChevronDown, Play, RefreshCw, Square, Trash2 } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { cx } from "~/lib/cx";
import * as api from "~/api/mercury";
-import type { BotManifest, BotRunRecord, BotStatus } from "~/api/types";
+import type { BotManifest, BotStatus } from "~/api/types";
import type { AgentState } from "~/app/store";
import { useBots } from "~/app/store";
import { refreshBots } from "~/app/events";
@@ -12,6 +12,10 @@ import { Badge, Empty, Mono, SectionTitle } from "~/components/ui/bits";
import { StateOrb } from "~/components/indicators/StateOrb";
import { Input } from "~/components/ui/Input";
import { BotAvatar } from "~/components/BotAvatar";
+import { ConfirmButton } from "~/components/ui/kit";
+import { Deliverables } from "./Deliverables";
+import { Activity } from "./Activity";
+import { Usage } from "./Usage";
/**
* Bots, organised the way they work: each fleet is a lead with its crew
@@ -114,7 +118,7 @@ export function BotsView() {
</aside>
<section className="min-w-0 flex-1 overflow-y-auto">
- {selectedFleet ? <FleetDetail fleet={selectedFleet} activity={activity} onSelect={setSelected} /> : selected ? <BotDetail id={selected} status={selectedBot} /> : <Empty title="Pick a bot" />}
+ {selectedFleet ? <FleetDetail fleet={selectedFleet} activity={activity} onSelect={setSelected} /> : selected ? <BotDetail id={selected} status={selectedBot} onDeleted={() => setSelected(null)} /> : <Empty title="Pick a bot" />}
</section>
</div>
);
@@ -153,93 +157,142 @@ function describe(b: BotStatus): string {
return "Idle";
}
-function FleetDetail({ fleet, activity, onSelect }: { fleet: Fleet; activity: Record<string, string>; onSelect: (id: string) => void }) {
+type Tab = "overview" | "deliverables" | "activity" | "usage";
+
+function TabBar({ tab, onChange, fleet }: { tab: Tab; onChange: (t: Tab) => void; fleet: boolean }) {
+ const tabs: Array<{ id: Tab; label: string }> = [
+ { id: "overview", label: "Overview" },
+ { id: "deliverables", label: fleet ? "Fleet deliverables" : "Deliverables" },
+ { id: "activity", label: "Activity" },
+ { id: "usage", label: "Usage" },
+ ];
+ return (
+ <div className="flex gap-1 border-b border-line" role="tablist">
+ {tabs.map((t) => (
+ <button key={t.id} role="tab" aria-selected={tab === t.id} onClick={() => onChange(t.id)}
+ className={cx("-mb-px border-b-2 px-3 pb-2.5 pt-1 text-base transition-colors", tab === t.id ? "border-accent text-ink" : "border-transparent text-ink3 hover:text-ink")}>
+ {t.label}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+function FleetDetail({ fleet, activity, onSelect }: { fleet: Fleet; activity: Record<string, string>; onSelect: (id: string | null) => void }) {
const { lead, crew } = fleet;
+ const [tab, setTab] = useState<Tab>("overview");
+ useEffect(() => { setTab("overview"); }, [lead.id]);
+ const members = [lead, ...crew];
return (
- <div className="mx-auto flex max-w-[820px] flex-col gap-7 px-8 py-7">
- <BotHeader id={lead.id} status={lead} subtitle={`Fleet lead · ${crew.length} crew`} />
- <div className="flex flex-col gap-3">
- <SectionTitle>Crew</SectionTitle>
- <div className="grid grid-cols-2 gap-2.5 xl:grid-cols-3">
- {crew.map((b) => (
- <button key={b.id} onClick={() => onSelect(b.id)} className="flex items-center gap-3 rounded-lg border border-line bg-surface p-3 text-left hover:border-line-strong">
- <span className="relative">
- <BotAvatar id={b.id} name={b.name} hasAvatar={b.hasAvatar} size={36} dimmed={!b.enabled} />
- <StateOrb state={orbFor(b)} size={9} className="absolute -bottom-0.5 -right-0.5 rounded-full bg-surface p-[1.5px]" />
- </span>
- <span className="min-w-0 flex-1">
- <span className="block truncate text-sm font-medium text-ink">{b.name}</span>
- <span className={cx("block truncate text-xs", b.state === "running" ? "text-accent" : "text-ink3")}>{activity[b.id] ?? describe(b)}</span>
- </span>
- </button>
- ))}
- {crew.length === 0 && <p className="text-sm text-ink4">No crew yet.</p>}
- </div>
- </div>
- <BotBody id={lead.id} status={lead} />
+ <div className="mx-auto flex max-w-[1000px] flex-col gap-6 px-8 py-7">
+ <BotHeader id={lead.id} status={lead} subtitle={`Fleet lead · ${crew.length} crew`} crewCount={crew.length} onDeleted={() => onSelect(null)} />
+ <TabBar tab={tab} onChange={setTab} fleet />
+ {tab === "overview" && (
+ <>
+ <div className="flex flex-col gap-3">
+ <SectionTitle>Crew</SectionTitle>
+ <div className="grid grid-cols-2 gap-2.5 xl:grid-cols-3">
+ {crew.map((b) => (
+ <button key={b.id} onClick={() => onSelect(b.id)} className="flex items-center gap-3 rounded-xl border border-line bg-surface p-3 text-left hover:border-line-strong">
+ <span className="relative">
+ <BotAvatar id={b.id} name={b.name} hasAvatar={b.hasAvatar} size={36} dimmed={!b.enabled} />
+ <StateOrb state={orbFor(b)} size={9} className="absolute -bottom-0.5 -right-0.5 rounded-full bg-surface p-[1.5px]" />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-sm font-medium text-ink">{b.name}</span>
+ <span className={cx("block truncate text-xs", b.state === "running" ? "text-accent" : "text-ink3")}>{activity[b.id] ?? describe(b)}</span>
+ </span>
+ </button>
+ ))}
+ {crew.length === 0 && <p className="text-sm text-ink4">No crew yet.</p>}
+ </div>
+ </div>
+ <BotBody id={lead.id} status={lead} />
+ </>
+ )}
+ {tab === "deliverables" && <Deliverables bots={members} />}
+ {tab === "activity" && <Activity bots={members} />}
+ {tab === "usage" && <Usage bots={members} />}
</div>
);
}
-function BotDetail({ id, status }: { id: string; status: BotStatus | null }) {
+function BotDetail({ id, status, onDeleted }: { id: string; status: BotStatus | null; onDeleted: () => void }) {
+ const [tab, setTab] = useState<Tab>("overview");
+ useEffect(() => { setTab("overview"); }, [id]);
+ const me = [{ id, name: status?.name ?? id, hasAvatar: status?.hasAvatar }];
return (
- <div className="mx-auto flex max-w-[820px] flex-col gap-7 px-8 py-7">
- <BotHeader id={id} status={status} />
- <BotBody id={id} status={status} />
+ <div className="mx-auto flex max-w-[1000px] flex-col gap-6 px-8 py-7">
+ <BotHeader id={id} status={status} onDeleted={onDeleted} />
+ <TabBar tab={tab} onChange={setTab} fleet={false} />
+ {tab === "overview" && <BotBody id={id} status={status} />}
+ {tab === "deliverables" && <Deliverables bots={me} />}
+ {tab === "activity" && <Activity bots={me} />}
+ {tab === "usage" && <Usage bots={me} />}
</div>
);
}
function useBot(id: string, status: BotStatus | null) {
const [bot, setBot] = useState<BotManifest | null>(null);
- const [journal, setJournal] = useState<BotRunRecord[]>([]);
async function load() {
- try {
- const res = await api.bots.get(id);
- setBot(res.bot);
- setJournal(res.journal ?? []);
- } catch {
- setBot(null);
- }
+ try { setBot((await api.bots.get(id)).bot); } catch { setBot(null); }
}
useEffect(() => { void load(); }, [id, status?.state, status?.lastRunAt, status?.enabled]);
- return { bot, journal, reload: load };
+ return { bot, reload: load };
}
-function BotHeader({ id, status, subtitle }: { id: string; status: BotStatus | null; subtitle?: string }) {
+function BotHeader({ id, status, subtitle, crewCount = 0, onDeleted }: { id: string; status: BotStatus | null; subtitle?: string; crewCount?: number; onDeleted: () => void }) {
const { bot, reload } = useBot(id, status);
+ const [error, setError] = useState<string | null>(null);
async function toggle(enabled: boolean) {
try { await (enabled ? api.bots.enable(id) : api.bots.disable(id)); } catch { /* keep */ }
void refreshBots(); void reload();
}
+ async function remove() {
+ setError(null);
+ try {
+ await api.bots.remove(id);
+ onDeleted();
+ void refreshBots();
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ }
if (!bot) return <div className="h-16" />;
return (
- <header className="flex items-start gap-4">
- <BotAvatar id={id} name={bot.name} hasAvatar={status?.hasAvatar} size={56} dimmed={!bot.enabled} />
- <div className="min-w-0 flex-1">
- <h1 className="text-xl font-medium tracking-tight text-ink">{bot.name}</h1>
- <p className="mt-0.5 text-sm text-ink3">{subtitle ?? bot.description ?? (bot.fleetRole === "crew" ? `Crew of ${bot.parent}` : "")}</p>
- <div className="mt-2 flex flex-wrap items-center gap-2">
- <Mono>{bot.id}</Mono>
- {bot.model?.model && <Badge>{bot.model.model}</Badge>}
- {bot.autonomy?.dailyTokenBudget && <Badge>{bot.autonomy.dailyTokenBudget.toLocaleString()} tokens/day</Badge>}
- {status?.needsYou && <Badge tone="amber">needs you</Badge>}
+ <header className="flex flex-col gap-2">
+ <div className="flex items-start gap-4">
+ <BotAvatar id={id} name={bot.name} hasAvatar={status?.hasAvatar} size={56} dimmed={!bot.enabled} />
+ <div className="min-w-0 flex-1">
+ <h1 className="text-xl font-semibold tracking-tight text-ink">{bot.name}</h1>
+ <p className="mt-0.5 text-sm text-ink3">{subtitle ?? bot.description ?? (bot.fleetRole === "crew" ? `Crew of ${bot.parent}` : "")}</p>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <Mono>{bot.id}</Mono>
+ {bot.model?.model && <Badge>{bot.model.model}</Badge>}
+ {bot.autonomy?.dailyTokenBudget && <Badge>{bot.autonomy.dailyTokenBudget.toLocaleString()} tokens/day</Badge>}
+ {status?.needsYou && <Badge tone="amber">needs you</Badge>}
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <Switch id={`bot-${id}`} checked={bot.enabled} onCheckedChange={(v) => void toggle(v)} label={bot.enabled ? "On" : "Off"} />
+ {status?.state === "running" ? (
+ <Button size="sm" variant="outline" onClick={() => void api.bots.stop(id).then(refreshBots)}><Square size={13} /> Stop</Button>
+ ) : (
+ <Button size="sm" variant="outline" disabled={!bot.enabled} onClick={() => void api.bots.runNow(id).then(refreshBots)}><Play size={13} /> Run now</Button>
+ )}
+ <ConfirmButton size="sm" confirmLabel={crewCount > 0 ? `Delete fleet (${crewCount + 1} bots)?` : "Delete bot?"} onConfirm={() => void remove()}>
+ <Trash2 size={13} /> Delete
+ </ConfirmButton>
</div>
</div>
- <div className="flex items-center gap-2">
- <Switch id={`bot-${id}`} checked={bot.enabled} onCheckedChange={(v) => void toggle(v)} label={bot.enabled ? "On" : "Off"} />
- {status?.state === "running" ? (
- <Button size="sm" variant="outline" onClick={() => void api.bots.stop(id).then(refreshBots)}><Square size={13} /> Stop</Button>
- ) : (
- <Button size="sm" variant="outline" disabled={!bot.enabled} onClick={() => void api.bots.run(id).then(refreshBots)}><Play size={13} /> Run now</Button>
- )}
- </div>
+ {error && <p className="text-sm text-red">{error}</p>}
</header>
);
}
function BotBody({ id, status }: { id: string; status: BotStatus | null }) {
- const { bot, journal } = useBot(id, status);
+ const { bot } = useBot(id, status);
const [message, setMessage] = useState("");
const [note, setNote] = useState<string | null>(null);
useEffect(() => { setNote(null); setMessage(""); }, [id]);
@@ -265,12 +318,11 @@ function BotBody({ id, status }: { id: string; status: BotStatus | null }) {
</div>
{note && <p className="text-sm text-ink3">{note}</p>}
</div>
-
{bot.schedules && bot.schedules.length > 0 && (
<div className="flex flex-col gap-2">
<SectionTitle>Schedules</SectionTitle>
{bot.schedules.map((s) => (
- <div key={s.name} className="flex items-center gap-3 rounded-lg border border-line bg-surface px-3.5 py-2.5 text-sm">
+ <div key={s.name} className="flex items-center gap-3 rounded-xl border border-line bg-surface px-3.5 py-2.5 text-sm">
<span className="text-ink">{s.name}</span>
<Mono>{s.cron}</Mono>
<span className="min-w-0 flex-1 truncate text-sm text-ink3">{s.prompt}</span>
@@ -278,19 +330,6 @@ function BotBody({ id, status }: { id: string; status: BotStatus | null }) {
))}
</div>
)}
-
- <div className="flex flex-col gap-2">
- <SectionTitle>Recent runs</SectionTitle>
- {journal.length === 0 && <p className="text-sm text-ink4">Nothing yet.</p>}
- {journal.slice(0, 15).map((r) => (
- <div key={r.runId} className="flex items-center gap-3 rounded-lg border border-line bg-surface px-3.5 py-2.5 text-sm">
- <StateOrb state={r.state === "failed" ? "needs-you" : r.state === "running" ? "working" : "idle"} size={9} />
- <span className="w-24 shrink-0 text-ink2">{ago(r.startedAt)}</span>
- <span className="min-w-0 flex-1 truncate text-ink">{r.summary || r.error || r.state}</span>
- <Mono>{Math.round(r.durationMs / 1000)}s · {(r.tokensIn + r.tokensOut).toLocaleString()} tok</Mono>
- </div>
- ))}
- </div>
</>
);
}
diff --git a/apps/desktop/src/views/bots/Deliverables.tsx b/apps/desktop/src/views/bots/Deliverables.tsx
new file mode 100644
index 00000000..b83d90ed
--- /dev/null
+++ b/apps/desktop/src/views/bots/Deliverables.tsx
@@ -0,0 +1,131 @@
+import { Copy, Download, FileText } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import * as api from "~/api/mercury";
+import { apiUrl, authHeaders } from "~/api/client";
+import type { Deliverable } from "~/api/types";
+import { Button } from "~/components/ui/Button";
+import { Badge, Empty, Spinner } from "~/components/ui/bits";
+import { ConfirmButton, SearchField } from "~/components/ui/kit";
+import { BotAvatar } from "~/components/BotAvatar";
+import { Markdown } from "~/components/Markdown";
+import { cx } from "~/lib/cx";
+
+/**
+ * Deliverables: the files bots produced. For a fleet lead, the whole
+ * fleet's files (lead + every crew member), each marked with who made it;
+ * for one bot, only its own. List on the left, the file on the right.
+ */
+export function Deliverables({ bots }: { bots: Array<{ id: string; name: string; hasAvatar?: boolean }> }) {
+ const [items, setItems] = useState<Deliverable[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [query, setQuery] = useState("");
+ const [selected, setSelected] = useState<string | null>(null);
+ const ids = bots.map((b) => b.id).join(",");
+
+ async function load() {
+ setLoading(true);
+ const all = await Promise.all(bots.map((b) => api.bots.outputs(b.id).then((r) => r.outputs).catch(() => [] as Deliverable[])));
+ const merged = all.flat().sort((a, b) => b.mtimeMs - a.mtimeMs);
+ setItems(merged);
+ setLoading(false);
+ }
+ useEffect(() => { setSelected(null); void load(); }, [ids]);
+
+ const byId = useMemo(() => new Map(bots.map((b) => [b.id, b])), [ids]);
+ const q = query.trim().toLowerCase();
+ const shown = items.filter((d) => !q || d.name.toLowerCase().includes(q));
+ const current = shown.find((d) => key(d) === selected) ?? shown[0] ?? null;
+
+ if (loading) return <div className="flex h-40 items-center justify-center text-ink3"><Spinner size={18} /></div>;
+ if (items.length === 0) return <Empty title="No deliverables yet" body={bots.length > 1 ? "Nothing from this fleet so far." : "Nothing from this bot so far."} />;
+
+ return (
+ <div className="flex min-h-[420px] gap-4">
+ <div className="flex w-[300px] shrink-0 flex-col gap-2">
+ <SearchField value={query} onChange={setQuery} placeholder={`Search ${items.length} files`} />
+ <div className="flex max-h-[560px] flex-col gap-1 overflow-y-auto pr-1">
+ {shown.map((d) => {
+ const bot = byId.get(d.botId);
+ const active = current && key(current) === key(d);
+ return (
+ <button key={key(d)} onClick={() => setSelected(key(d))} className={cx("flex items-start gap-2.5 rounded-lg px-2.5 py-2 text-left", active ? "bg-ink/[0.07]" : "hover:bg-ink/[0.05]")}>
+ <FileText size={16} className="mt-0.5 shrink-0 text-ink3" aria-hidden="true" />
+ <span className="min-w-0 flex-1">
+ <span className="line-clamp-2 text-sm text-ink">{d.name}</span>
+ <span className="mt-0.5 flex items-center gap-1.5 text-xs text-ink4">
+ {bots.length > 1 && bot && <><BotAvatar id={bot.id} name={bot.name} hasAvatar={bot.hasAvatar} size={14} /> <span className="truncate">{bot.name}</span> ·</>}
+ {date(d.mtimeMs)} · {size(d.bytes)}
+ </span>
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ <div className="min-w-0 flex-1">
+ {current ? <Preview d={current} onDeleted={() => void load()} /> : <Empty title="No file matches" />}
+ </div>
+ </div>
+ );
+}
+
+function Preview({ d, onDeleted }: { d: Deliverable; onDeleted: () => void }) {
+ const [text, setText] = useState<string | null>(null);
+ const [truncated, setTruncated] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [copied, setCopied] = useState(false);
+ useEffect(() => {
+ let live = true;
+ setText(null); setError(null);
+ api.bots.outputPreview(d.botId, d.name)
+ .then((r) => { if (live) { setText(r.preview); setTruncated(r.truncated); } })
+ .catch((e) => { if (live) setError(e instanceof Error ? e.message : String(e)); });
+ return () => { live = false; };
+ }, [d.botId, d.name]);
+
+ async function download() {
+ const res = await fetch(apiUrl(api.bots.outputDownloadPath(d.botId, d.name)), { headers: authHeaders() });
+ if (!res.ok) return;
+ const url = URL.createObjectURL(await res.blob());
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = d.name;
+ a.click();
+ setTimeout(() => URL.revokeObjectURL(url), 2000);
+ }
+
+ const isMarkdown = /\.(md|markdown|txt)$/i.test(d.name);
+ return (
+ <div className="flex h-full flex-col rounded-xl border border-line bg-surface">
+ <div className="flex items-center gap-2 border-b border-line px-4 py-3">
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-base font-medium text-ink">{d.name}</div>
+ <div className="text-xs text-ink4">{date(d.mtimeMs)} · {size(d.bytes)} {d.final && <Badge tone="accent" className="ml-1">final</Badge>}</div>
+ </div>
+ <Button size="sm" variant="ghost" onClick={() => { if (text) void navigator.clipboard.writeText(text).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1200); }); }} disabled={!text}><Copy size={14} /> {copied ? "Copied" : "Copy"}</Button>
+ <Button size="sm" variant="ghost" onClick={() => void download()}><Download size={14} /> Download</Button>
+ <ConfirmButton size="sm" confirmLabel="Delete?" onConfirm={() => void api.bots.deleteOutput(d.botId, d.name).then(onDeleted)}>Delete</ConfirmButton>
+ </div>
+ <div className="max-h-[560px] min-h-0 flex-1 overflow-y-auto px-5 py-4">
+ {error && <p className="text-sm text-red">{error}</p>}
+ {text === null && !error && <Spinner size={16} className="text-ink3" />}
+ {text !== null && (isMarkdown ? <Markdown text={text} /> : <pre className="whitespace-pre-wrap font-mono text-xs text-ink" data-selectable>{text}</pre>)}
+ {truncated && <p className="mt-3 text-xs text-ink4">Preview shows the first 64 KB. Download for the full file.</p>}
+ </div>
+ </div>
+ );
+}
+
+function key(d: Deliverable): string {
+ return `${d.botId}/${d.name}`;
+}
+
+export function date(ms: number): string {
+ return new Date(ms).toLocaleString([], { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" });
+}
+
+export function size(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / 1048576).toFixed(1)} MB`;
+}
diff --git a/apps/desktop/src/views/bots/Usage.tsx b/apps/desktop/src/views/bots/Usage.tsx
new file mode 100644
index 00000000..65e6a229
--- /dev/null
+++ b/apps/desktop/src/views/bots/Usage.tsx
@@ -0,0 +1,164 @@
+import { useEffect, useMemo, useState } from "react";
+import * as api from "~/api/mercury";
+import type { BotRunRecord, CostReport, UsageBucket } from "~/api/types";
+import { Segmented, Spinner } from "~/components/ui/bits";
+import { BotAvatar } from "~/components/BotAvatar";
+import { cx } from "~/lib/cx";
+
+/**
+ * Token usage, in depth:
+ * - totals for the period (in, out, runs, success, deliverables, tokens per
+ * run and per deliverable) and today against the daily cap;
+ * - a bar per run (input and output stacked, failed runs marked), hover
+ * for numbers;
+ * - for a fleet, each member's share.
+ */
+export function Usage({ bots }: { bots: Array<{ id: string; name: string; hasAvatar?: boolean }> }) {
+ const [days, setDays] = useState<"1" | "7" | "30">("7");
+ const [report, setReport] = useState<CostReport | null>(null);
+ const [runs, setRuns] = useState<BotRunRecord[]>([]);
+ const ids = bots.map((b) => b.id);
+ const key = ids.join(",");
+
+ useEffect(() => {
+ let live = true;
+ setReport(null);
+ void api.bots.cost(Number(days)).then((r) => { if (live) setReport(r); }).catch(() => {});
+ void Promise.all(ids.map((id) => api.bots.journal(id, 100).then((r) => r.journal).catch(() => [] as BotRunRecord[])))
+ .then((all) => { if (live) setRuns(all.flat()); });
+ return () => { live = false; };
+ }, [key, days]);
+
+ const rows = useMemo(() => (report?.bots ?? []).filter((b) => ids.includes(b.id)), [report, key]);
+ const total = useMemo(() => sum(rows.map((r) => r.window)), [rows]);
+ const today = useMemo(() => sum(rows.map((r) => r.today)), [rows]);
+ const cap = rows.reduce((n, r) => n + (r.cap || 0), 0);
+ const since = Date.now() - Number(days) * 86_400_000;
+ const periodRuns = runs.filter((r) => r.startedAt >= since).sort((a, b) => a.startedAt - b.startedAt).slice(-80);
+
+ if (!report) return <div className="flex h-40 items-center justify-center text-ink3"><Spinner size={18} /></div>;
+
+ const tokens = total.tokensIn + total.tokensOut;
+ const success = total.runs ? Math.round((total.completed / total.runs) * 100) : 0;
+
+ return (
+ <div className="flex flex-col gap-6">
+ <div className="flex items-center justify-between">
+ <span className="text-sm text-ink3">{bots.length > 1 ? `${bots.length} bots in this fleet` : "This bot"}</span>
+ <Segmented size="md" value={days} onChange={setDays} options={[{ value: "1", label: "24 h" }, { value: "7", label: "7 days" }, { value: "30", label: "30 days" }]} />
+ </div>
+
+ <div className="grid grid-cols-4 gap-3">
+ <Tile label="Tokens" value={compact(tokens)} sub={`${compact(total.tokensIn)} in · ${compact(total.tokensOut)} out`} />
+ <Tile label="Runs" value={String(total.runs)} sub={`${success}% completed · ${total.failed} failed`} tone={total.runs && success < 50 ? "warn" : undefined} />
+ <Tile label="Per run" value={total.runs ? compact(Math.round(tokens / total.runs)) : "—"} sub="tokens on average" />
+ <Tile label="Deliverables" value={String(total.deliverables)} sub={total.deliverables ? `${compact(Math.round(tokens / total.deliverables))} tokens each` : "none in this period"} />
+ </div>
+
+ {cap > 0 && (
+ <div className="rounded-xl border border-line bg-surface p-4">
+ <div className="mb-2 flex items-baseline justify-between text-sm">
+ <span className="text-ink">Today against the daily cap</span>
+ <span className="font-mono text-xs text-ink3">{compact(today.tokensIn + today.tokensOut)} / {compact(cap)}</span>
+ </div>
+ <Meter ratio={(today.tokensIn + today.tokensOut) / cap} />
+ </div>
+ )}
+
+ <div className="rounded-xl border border-line bg-surface p-4">
+ <div className="mb-3 flex items-center justify-between text-sm">
+ <span className="text-ink">Tokens per run</span>
+ <span className="flex items-center gap-3 text-xs text-ink3">
+ <Legend className="bg-accent" label="input" /><Legend className="bg-cyan" label="output" /><Legend className="bg-red" label="failed run" />
+ </span>
+ </div>
+ <RunBars runs={periodRuns} names={new Map(bots.map((b) => [b.id, b.name]))} />
+ </div>
+
+ {bots.length > 1 && (
+ <div className="rounded-xl border border-line bg-surface p-4">
+ <div className="mb-3 text-sm text-ink">Share of the fleet</div>
+ <div className="flex flex-col gap-2.5">
+ {[...rows].sort((a, b) => (b.window.tokensIn + b.window.tokensOut) - (a.window.tokensIn + a.window.tokensOut)).map((r) => {
+ const t = r.window.tokensIn + r.window.tokensOut;
+ const bot = bots.find((b) => b.id === r.id);
+ return (
+ <div key={r.id} className="grid grid-cols-[200px_1fr_120px] items-center gap-3 text-sm">
+ <span className="flex min-w-0 items-center gap-2"><BotAvatar id={r.id} name={r.name} hasAvatar={bot?.hasAvatar} size={20} /><span className="truncate text-ink">{bot?.name ?? r.name}</span></span>
+ <span className="h-2 overflow-hidden rounded-full bg-ink/[0.08]"><span className="block h-full rounded-full bg-accent" style={{ width: `${tokens ? (t / tokens) * 100 : 0}%` }} /></span>
+ <span className="text-right font-mono text-xs text-ink3">{compact(t)} · {r.window.runs} runs</span>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function RunBars({ runs, names }: { runs: BotRunRecord[]; names: Map<string, string> }) {
+ const [hover, setHover] = useState<BotRunRecord | null>(null);
+ if (runs.length === 0) return <p className="text-sm text-ink4">No runs in this period.</p>;
+ const max = Math.max(...runs.map((r) => r.tokensIn + r.tokensOut), 1);
+ return (
+ <div>
+ <div className="flex h-36 items-end gap-[3px]" onMouseLeave={() => setHover(null)}>
+ {runs.map((r) => {
+ const total = r.tokensIn + r.tokensOut;
+ const h = Math.max(2, (total / max) * 100);
+ const outShare = total ? r.tokensOut / total : 0;
+ return (
+ <div key={`${r.botId}/${r.runId}`} onMouseEnter={() => setHover(r)} className="relative flex min-w-[4px] flex-1 flex-col justify-end" style={{ height: "100%" }}>
+ <div className={cx("flex w-full flex-col overflow-hidden rounded-t-[3px]", hover === r && "opacity-80")} style={{ height: `${h}%` }}>
+ <div className={r.state === "failed" ? "bg-red" : "bg-cyan"} style={{ height: `${Math.max(outShare * 100, 4)}%` }} />
+ <div className={cx("flex-1", r.state === "failed" ? "bg-red/60" : "bg-accent")} />
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ <div className="mt-2 h-5 text-xs text-ink3">
+ {hover
+ ? `${names.get(hover.botId) ?? hover.botId} · ${new Date(hover.startedAt).toLocaleString([], { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })} · ${hover.tokensIn.toLocaleString()} in · ${hover.tokensOut.toLocaleString()} out · ${hover.state}`
+ : `${runs.length} runs · hover a bar for details`}
+ </div>
+ </div>
+ );
+}
+
+function Tile({ label, value, sub, tone }: { label: string; value: string; sub: string; tone?: "warn" }) {
+ return (
+ <div className={cx("rounded-xl border bg-surface p-4", tone === "warn" ? "border-amber/40" : "border-line")}>
+ <div className="text-xs text-ink4">{label}</div>
+ <div className="mt-1 text-2xl font-semibold tracking-tight text-ink">{value}</div>
+ <div className="mt-0.5 text-xs text-ink3">{sub}</div>
+ </div>
+ );
+}
+
+function Meter({ ratio }: { ratio: number }) {
+ const r = Math.min(1, Math.max(0, ratio));
+ return (
+ <div className="h-2 overflow-hidden rounded-full bg-ink/[0.08]">
+ <div className={cx("h-full rounded-full", r > 0.9 ? "bg-red" : r > 0.7 ? "bg-amber" : "bg-accent")} style={{ width: `${r * 100}%` }} />
+ </div>
+ );
+}
+
+function Legend({ className, label }: { className: string; label: string }) {
+ return <span className="flex items-center gap-1.5"><span className={cx("block h-2 w-2 rounded-sm", className)} />{label}</span>;
+}
+
+function sum(list: UsageBucket[]): UsageBucket {
+ return list.reduce((a, b) => ({
+ runs: a.runs + b.runs, completed: a.completed + b.completed, failed: a.failed + b.failed, noOutcome: a.noOutcome + b.noOutcome,
+ deliverables: a.deliverables + b.deliverables, tokensIn: a.tokensIn + b.tokensIn, tokensOut: a.tokensOut + b.tokensOut,
+ }), { runs: 0, completed: 0, failed: 0, noOutcome: 0, deliverables: 0, tokensIn: 0, tokensOut: 0 });
+}
+
+export function compact(n: number): string {
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(n >= 10_000_000 ? 0 : 1)}M`;
+ if (n >= 1_000) return `${(n / 1_000).toFixed(n >= 10_000 ? 0 : 1)}K`;
+ return String(n);
+}