Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(desktop): fleets in the app — let Mercury decide, design the crew, or pick it
Salman Qureshi6cf2dc8a84dd
diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.tsindex 1048d911..231953ed 100644--- a/apps/desktop/src/api/mercury.ts+++ b/apps/desktop/src/api/mercury.ts@@ -5,7 +5,7 @@import { http, ApiError } from "./client";import type { SkillDraft,- BotApproval, BotInboxEntry, BotManifest, BotRunRecord, BotStatus, BotTier, BotTierId, ChatMessage, ChatSettings, ChatThread, CodeStatus, HealthInfo,+ BotApproval, BotInboxEntry, BotManifest, BotPlan, CrewSpec, BotRunRecord, BotStatus, BotTier, BotTierId, ChatMessage, ChatSettings, ChatThread, CodeStatus, HealthInfo,McpServer, ModelsResponse, CodeMode, CostReport, Deliverable, RunTranscript, PairResponse, PluginItem, ReasoningChoice, Skill, DeviceSummary,} from "./types";@@ -110,6 +110,14 @@ export const bots = {inbox: (opts: { unread?: boolean; bot?: string; limit?: number } = {}) =>http.get<{ entries: BotInboxEntry[]; unread: number }>(`/api/bots/inbox?limit=${opts.limit ?? 100}${opts.unread ? "&unread=1" : ""}${opts.bot ? `&bot=${encodeURIComponent(opts.bot)}` : ""}`),markRead: (ids?: string[]) => http.post<{ ok: boolean; unread: number }>("/api/bots/inbox/read", ids ? { ids } : {}),+ /** The persona builder: rough instructions → the structured persona. Nothing is saved. */+ buildPersona: (text: string, name: string) => http.post<{ persona: string }>("/api/bots/persona-builder", { text, name }).then((r) => r.persona),+ /** Solo or fleet for this job, with a proposed crew. fleet: true = you already chose a fleet. */+ plan: (input: { name: string; description: string; persona: string; fleet?: boolean }) => http.post<{ plan: BotPlan; maxCrew: number }>("/api/bots/plan", input),+ promote: (id: string) => http.post<{ ok: boolean }>(`/api/bots/${encodeURIComponent(id)}/promote`, {}),+ /** Mercury designs and adds crew to a lead, in the background (roster updates arrive live). */+ autoCrew: (id: string) => http.post<{ accepted: boolean }>(`/api/bots/${encodeURIComponent(id)}/autocrew`, {}),+ addCrew: (leadId: string, crew: CrewSpec & { tier?: BotTierId }) => http.post<{ bot: BotManifest }>(`/api/bots/${encodeURIComponent(leadId)}/crew`, crew),approvals: () => http.get<{ approvals: BotApproval[] }>("/api/bots/approvals").then((r) => r.approvals),answer: (approvalId: string, answer: "yes" | "always" | "no") => http.post<{ ok: boolean }>(`/api/bots/approvals/${encodeURIComponent(approvalId)}`, { answer }),dlq: (id: string) => http.get<{ dlq: Array<{ id: string; prompt: string; reasonCode?: string; createdAt: number }> }>(`/api/bots/${encodeURIComponent(id)}/dlq`),diff --git a/apps/desktop/src/api/types.ts b/apps/desktop/src/api/types.tsindex 87f7c034..193970c5 100644--- a/apps/desktop/src/api/types.ts+++ b/apps/desktop/src/api/types.ts@@ -187,6 +187,21 @@ export interface BotManifest {memory?: { scope?: "own" | "shared-read" | "none"; learn?: boolean };}+/** A crew member, proposed by Mercury or written by you. */+export interface CrewSpec {+ id: string;+ name: string;+ description: string;+ persona: string;+}++/** "Let Mercury decide" (POST /api/bots/plan). */+export interface BotPlan {+ shape: "solo" | "fleet";+ reason: string;+ crew: CrewSpec[];+}+/** A bot waiting for your answer mid-run (GET /api/bots/approvals). */export interface BotApproval {id: string;diff --git a/apps/desktop/src/views/bots/BotForms.tsx b/apps/desktop/src/views/bots/BotForms.tsxindex ea637ddb..93c31ce8 100644--- a/apps/desktop/src/views/bots/BotForms.tsx+++ b/apps/desktop/src/views/bots/BotForms.tsx@@ -1,7 +1,7 @@-import { Plus, ShieldAlert, Trash2 } from "lucide-react";+import { Plus, ShieldAlert, Sparkles, Trash2 } from "lucide-react";import { useEffect, useState } from "react";import * as api from "~/api/mercury";-import type { BotSchedule, BotTier, BotTierId, ModelsResponse } from "~/api/types";+import type { BotSchedule, BotTier, BotTierId, CrewSpec, ModelsResponse } from "~/api/types";import { Input } from "~/components/ui/Input";import { cx } from "~/lib/cx";@@ -138,3 +138,67 @@ export function slugify(name: string): string {const s = name.toLowerCase().normalize("NFKD").replace(/[^\w\s-]/g, "").trim().replace(/[\s_]+/g, "-").replace(/-+/g, "-").slice(0, 30).replace(/^-|-$/g, "");return /^[a-z]/.test(s) ? s : `bot-${s || "new"}`;}++/**+ * The persona builder, next to any instructions box: turns rough notes into+ * the structured persona (Character, Standing instructions, Output) without+ * adding anything you didn't say. One click to undo.+ */+export function PersonaBuilderButton({ text, name, onBuilt }: { text: string; name: string; onBuilt: (persona: string) => void }) {+ const [busy, setBusy] = useState(false);+ const [before, setBefore] = useState<string | null>(null);+ const [problem, setProblem] = useState<string | null>(null);+ async function build() {+ setBusy(true);+ setProblem(null);+ try {+ const persona = await api.bots.buildPersona(text, name);+ setBefore(text);+ onBuilt(persona);+ } catch (e) {+ setProblem(e instanceof Error ? e.message : String(e));+ } finally {+ setBusy(false);+ }+ }+ return (+ <div className="flex flex-wrap items-center gap-2">+ <button onClick={() => void build()} disabled={busy || text.trim().length < 10}+ className="flex items-center gap-1.5 rounded-md border border-line px-2 py-1 text-xs text-ink2 hover:border-line-strong hover:text-ink disabled:opacity-50">+ {busy ? <span className="h-3 w-3 animate-spin rounded-full border-2 border-ink3 border-t-transparent" aria-hidden="true" /> : <Sparkles size={12} />}+ {busy ? "Structuring… (10–60 s)" : "Structure with the persona builder"}+ </button>+ {before !== null && !busy && <button onClick={() => { onBuilt(before); setBefore(null); }} className="text-xs text-ink3 hover:text-ink">Undo</button>}+ {problem && <span className="text-xs text-red">{problem}</span>}+ {!problem && !busy && before === null && <span className="text-xs text-ink4">Keeps everything you wrote; adds nothing.</span>}+ </div>+ );+}++/** A team of crew members you write yourself (or edit after Mercury proposed them). */+export function CrewEditor({ value, onChange, max = 6 }: { value: CrewSpec[]; onChange: (c: CrewSpec[]) => void; max?: number }) {+ const set = (i: number, patch: Partial<CrewSpec>) => onChange(value.map((c, j) => (j === i ? { ...c, ...patch, ...(patch.name !== undefined ? { id: slugify(patch.name) } : {}) } : c)));+ return (+ <div className="flex flex-col gap-2.5">+ {value.map((c, i) => (+ <div key={i} className="flex flex-col gap-2 rounded-lg border border-line p-3">+ <div className="flex items-center gap-2">+ <Input value={c.name} onChange={(e) => set(i, { name: e.target.value })} placeholder="Crew member name, e.g. Fact Checker" className="h-8" aria-label="Crew name" />+ <button onClick={() => onChange(value.filter((_, j) => j !== i))} className="rounded p-1.5 text-ink4 hover:text-red" aria-label="Remove crew member"><Trash2 size={14} /></button>+ </div>+ <Input value={c.description} onChange={(e) => set(i, { description: e.target.value })} placeholder="What it does, in one line" className="h-8" aria-label="Crew description" />+ <textarea value={c.persona} onChange={(e) => set(i, { persona: e.target.value })} rows={3} placeholder="How it works and what it hands back to the lead."+ className="w-full resize-y rounded-md border border-line bg-surface px-2.5 py-1.5 text-sm text-ink placeholder:text-ink4" aria-label="Crew instructions" />+ <PersonaBuilderButton text={c.persona} name={c.name} onBuilt={(p) => set(i, { persona: p })} />+ </div>+ ))}+ {value.length < max && (+ <div>+ <button onClick={() => onChange([...value, { id: "", name: "", description: "", persona: "" }])} className="flex items-center gap-1.5 text-sm text-ink2 hover:text-ink">+ <Plus size={14} /> Add a crew member+ </button>+ </div>+ )}+ </div>+ );+}diff --git a/apps/desktop/src/views/bots/BotSettings.tsx b/apps/desktop/src/views/bots/BotSettings.tsxindex 87bf6bbe..8d4a880c 100644--- a/apps/desktop/src/views/bots/BotSettings.tsx+++ b/apps/desktop/src/views/bots/BotSettings.tsx@@ -6,7 +6,7 @@ import { Button } from "~/components/ui/Button";import { Input } from "~/components/ui/Input";import { Switch } from "~/components/ui/Switch";import { Spinner } from "~/components/ui/bits";-import { ModelPicker, ScheduleEditor, TierPicker } from "./BotForms";+import { ModelPicker, PersonaBuilderButton, ScheduleEditor, TierPicker } from "./BotForms";/*** Everything about a bot that the owner decides, on one page: its name and@@ -32,7 +32,7 @@ export function BotSettings({ id, status }: { id: string; status: BotStatus | nu<div className="flex max-w-[760px] flex-col gap-5"><Basics bot={bot} onSaved={load} /><Card title="How it works" hint="Its instructions. Say what a good result is, and when there's nothing to report.">- <PersonaEditor id={id} initial={persona} />+ <PersonaEditor id={id} name={bot.name} initial={persona} /></Card><SchedulesCard bot={bot} onSaved={load} /><Card title="What it may do">@@ -92,13 +92,14 @@ function Basics({ bot, onSaved }: { bot: BotManifest; onSaved: () => Promise<voi);}-function PersonaEditor({ id, initial }: { id: string; initial: string }) {+function PersonaEditor({ id, name, initial }: { id: string; name: string; initial: string }) {const [text, setText] = useState(initial);const { run, footer } = useSave();return (<><textarea value={text} onChange={(e) => setText(e.target.value)} rows={10}className="w-full resize-y rounded-md border border-line bg-surface px-3 py-2 font-mono text-xs leading-relaxed text-ink" aria-label="Instructions" />+ <PersonaBuilderButton text={text} name={name} onBuilt={setText} />{footer(() => void run(() => api.bots.setPersona(id, text)), text.trim() === initial.trim() || !text.trim())}</>);diff --git a/apps/desktop/src/views/bots/BotsView.tsx b/apps/desktop/src/views/bots/BotsView.tsxindex bf9c627f..d9c5def7 100644--- a/apps/desktop/src/views/bots/BotsView.tsx+++ b/apps/desktop/src/views/bots/BotsView.tsx@@ -1,4 +1,4 @@-import { ChevronDown, Play, Plus, RefreshCw, Shield, ShieldAlert, Square, Trash2 } from "lucide-react";+import { ChevronDown, LayoutGrid, Play, Plus, RefreshCw, Shield, ShieldAlert, Square, Trash2 } from "lucide-react";import { DictationNotice, MicButton, RecordingBar, joinText, useDictation } from "~/components/dictation/Dictation";import { useEffect, useMemo, useRef, useState } from "react";import { cx } from "~/lib/cx";@@ -19,6 +19,8 @@ import { Activity } from "./Activity";import { Usage } from "./Usage";import { BotInbox, InboxRow } from "./Inbox";import { PendingApprovals } from "./Approvals";+import { BotsOverview } from "./Overview";+import { CrewActions, MakeFleet } from "./FleetTools";import { CreateBot } from "./CreateBot";import { BotSettings } from "./BotSettings";import { describeCron } from "./BotForms";@@ -75,7 +77,7 @@ export function BotsView() {useUi.getState().clearBotFocus();}, [focus]);useEffect(() => {- if (!selected) setSelected(bots.length ? "inbox" : "new");+ if (!selected) setSelected(bots.length ? "all" : "new");}, [bots.length, selected]);if (!available) return <Empty title="Bots are not available on this runtime" body="Enable bots in the runtime's configuration to see them here." />;@@ -95,6 +97,12 @@ export function BotsView() {</header><div className="min-h-0 flex-1 overflow-y-auto px-2 pb-4"><InboxRow active={selected === "inbox"} unread={unread} waiting={waiting} onClick={() => setSelected("inbox")} />+ <button onClick={() => setSelected("all")} className={cx("mb-3 flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-left", selected === "all" ? "bg-ink/[0.07]" : "hover:bg-ink/[0.05]")}>+ <span className="flex h-8 w-8 items-center justify-center rounded-full bg-ink/[0.06]"><LayoutGrid size={15} className="text-ink2" /></span>+ <span className="flex-1 text-sm font-medium text-ink">All bots</span>+ <span className="text-xs text-ink4">{fleets.length ? `${fleets.length} fleet${fleets.length === 1 ? "" : "s"} · ` : ""}{bots.length}</span>+ </button>+ {fleets.length > 0 && <div className="px-2.5 pb-1 text-2xs font-medium uppercase tracking-wider text-ink4">Fleets</div>}{bots.length === 0 && <p className="px-2 pt-1 text-sm text-ink4">No bots yet. Press New bot to make one.</p>}{fleets.map((f) => {@@ -140,7 +148,9 @@ export function BotsView() {<section className={cx("min-w-0 flex-1", selected === "new" ? "flex flex-col overflow-hidden" : "overflow-y-auto")}>{selected === "new" ? (- <CreateBot existingIds={bots.map((b) => b.id)} onCancel={() => setSelected(bots.length ? "inbox" : null)} onCreated={(id) => setSelected(id)} />+ <CreateBot existingIds={bots.map((b) => b.id)} onCancel={() => setSelected(bots.length ? "all" : null)} onCreated={(id) => setSelected(id)} />+ ) : selected === "all" ? (+ <BotsOverview fleets={fleets} solo={solo} onOpen={setSelected} onNew={() => setSelected("new")} />) : selected === "inbox" ? (<div className="mx-auto flex max-w-[860px] flex-col gap-5 px-8 py-7"><div>@@ -153,7 +163,7 @@ export function BotsView() {) : selectedFleet ? (<FleetDetail fleet={selectedFleet} activity={activity} onSelect={setSelected} />) : selected ? (- <BotDetail id={selected} status={selectedBot} onDeleted={() => setSelected("inbox")} />+ <BotDetail id={selected} status={selectedBot} onDeleted={() => setSelected("all")} />) : (<Empty title="Pick a bot" />)}@@ -238,7 +248,7 @@ function FleetDetail({ fleet, activity, onSelect }: { fleet: Fleet; activity: Re{tab === "overview" && (<><div className="flex flex-col gap-3">- <SectionTitle>Crew</SectionTitle>+ <SectionTitle right={<CrewActions leadId={lead.id} leadName={lead.name} crewCount={crew.length} />}>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">@@ -252,7 +262,7 @@ function FleetDetail({ fleet, activity, onSelect }: { fleet: Fleet; activity: Re</span></button>))}- {crew.length === 0 && <p className="text-sm text-ink4">No crew yet.</p>}+ {crew.length === 0 && <p className="text-sm text-ink4">No crew yet. Add a member, or let Mercury suggest them.</p>}</div></div><BotBody id={lead.id} status={lead} />@@ -276,6 +286,7 @@ function BotDetail({ id, status, onDeleted }: { id: string; status: BotStatus |<BotHeader id={id} status={status} onDeleted={onDeleted} /><PendingApprovals botId={id} /><TabBar tab={tab} onChange={setTab} fleet={false} />+ {tab === "overview" && status && !status.parent && status.fleetRole !== "lead" && <MakeFleet id={id} name={status.name} />}{tab === "overview" && <BotBody id={id} status={status} />}{tab === "results" && <BotInbox bots={status ? [status] : []} botId={id} />}{tab === "deliverables" && <Deliverables bots={me} />}diff --git a/apps/desktop/src/views/bots/CreateBot.tsx b/apps/desktop/src/views/bots/CreateBot.tsxindex dfb13c95..25809f18 100644--- a/apps/desktop/src/views/bots/CreateBot.tsx+++ b/apps/desktop/src/views/bots/CreateBot.tsx@@ -1,19 +1,24 @@-import { Bot, Eye, Newspaper, PenLine, Search } from "lucide-react";+import { Bot, Crown, Eye, Newspaper, PenLine, Search, Users, Wand2 } from "lucide-react";import { useEffect, useState } from "react";import * as api from "~/api/mercury";-import type { BotSchedule, BotTier, BotTierId } from "~/api/types";+import type { BotPlan, BotSchedule, BotTier, BotTierId, CrewSpec } from "~/api/types";import { refreshBots } from "~/app/events";import { Button } from "~/components/ui/Button";import { Input } from "~/components/ui/Input";+import { Spinner } from "~/components/ui/bits";import { cx } from "~/lib/cx";-import { ModelPicker, ScheduleEditor, TierPicker, slugify } from "./BotForms";+import { CrewEditor, ModelPicker, PersonaBuilderButton, ScheduleEditor, TierPicker, slugify } from "./BotForms";/**- * A new bot in one screen: start from what it's for, name it, say what it- * does and when, and how much it may do. Everything can be changed later in- * its Settings. A template only fills the fields; nothing is hidden.+ * A new bot: start from what it's for, say what it does and when, how much+ * it may do — and whether it works alone or leads a fleet. "Let Mercury+ * decide" (the default) looks at the job and proposes one bot or a small team;+ * you review the proposal, edit the crew, and only then is anything created.+ * Everything can be changed later in the bot's Settings.*/+type Structure = "auto" | "solo" | "fleet-auto" | "fleet-manual";+interface Template {id: string;label: string;@@ -23,39 +28,53 @@ interface Template {persona: string;tier: BotTierId;schedules: BotSchedule[];+ structure: Structure;}const TEMPLATES: Template[] = [{- id: "researcher", label: "Researcher", blurb: "Looks things up and reports what it found.", icon: Search, tier: "readonly",+ id: "researcher", label: "Researcher", blurb: "Looks things up and reports what it found.", icon: Search, tier: "readonly", structure: "auto",description: "Researches topics on the web and reports clear, sourced findings.",persona: "You research what you're asked about using the web and the files you can read.\n\n- Lead with the answer, then the evidence, with links.\n- Say what you couldn't verify.\n- Close with bot_report: the findings in a few paragraphs. If a written report was asked for, deliver it as a .md file first.",schedules: [],},{- id: "monitor", label: "Monitor", blurb: "Checks something on a schedule and tells you only when it changed.", icon: Eye, tier: "readonly",+ id: "monitor", label: "Monitor", blurb: "Checks something on a schedule and tells you only when it changed.", icon: Eye, tier: "readonly", structure: "solo",description: "Watches for changes and reports only what's new.",persona: "You check one thing on a schedule and report only what changed since last time.\n\n- Use your working state (bot_state) to remember what you saw last.\n- If nothing changed, call bot_no_update — never write a status note.\n- If something changed, close with bot_report: what changed, in one or two sentences, with a link.",schedules: [{ name: "check", cron: "0 * * * *", prompt: "Check for changes since your last run. Report only what's new; otherwise call bot_no_update." }],},{- id: "writer", label: "Writer", blurb: "Drafts articles, posts or reports and delivers the file.", icon: PenLine, tier: "builder",+ id: "writer", label: "Writer", blurb: "Drafts articles, posts or reports and delivers the file.", icon: PenLine, tier: "builder", structure: "auto",description: "Writes drafts and delivers them as files.",persona: "You write what you're asked for: articles, posts, summaries, reports.\n\n- Write in plain, direct sentences in the owner's voice.\n- Save the draft in your workspace as a .md file, deliver it with bot_deliver (final: true for the finished piece), then close with bot_report saying what you delivered.",schedules: [],},{- id: "digest", label: "Daily digest", blurb: "Every morning, a short brief on a topic you choose.", icon: Newspaper, tier: "readonly",+ id: "digest", label: "Daily digest", blurb: "Every morning, a short brief on a topic you choose.", icon: Newspaper, tier: "readonly", structure: "solo",description: "Sends a short morning brief.",persona: "Each morning you prepare a short brief on the owner's topics.\n\n- Five items at most, each one line with a link, newest first.\n- Skip anything you already reported (check your recent runs).\n- Close with bot_report containing the brief. If there's genuinely nothing new, call bot_no_update.",schedules: [{ name: "morning", cron: "0 9 * * *", prompt: "Prepare today's brief." }],},{- id: "blank", label: "Start from scratch", blurb: "An empty bot you describe yourself.", icon: Bot, tier: "readonly",+ id: "team", label: "A team (fleet)", blurb: "A lead that hands parts of the job to specialists, e.g. research → write → check.", icon: Users, tier: "builder", structure: "fleet-auto",+ description: "Leads a small team of specialists.",+ persona: "You lead a small team. Break each job into parts, hand each part to the right crew member with a clear goal and what \"done\" means, then combine what they hand back into one result.\n\n- Close with bot_report: the combined result, and the files delivered.",+ schedules: [],+ },+ {+ id: "blank", label: "Start from scratch", blurb: "An empty bot you describe yourself.", icon: Bot, tier: "readonly", structure: "auto",description: "", persona: "", schedules: [],},];+const STRUCTURES: Array<{ id: Structure; title: string; body: string; icon: typeof Bot }> = [+ { id: "auto", title: "Let Mercury decide", body: "It looks at the job and suggests one bot or a small team. You review it before anything is created.", icon: Wand2 },+ { id: "solo", title: "One bot", body: "Does the whole job itself. Cheapest, and right for most jobs.", icon: Bot },+ { id: "fleet-auto", title: "A fleet — Mercury designs the team", body: "This bot leads; Mercury proposes 2–5 specialists for it to hand work to.", icon: Crown },+ { id: "fleet-manual", title: "A fleet — I'll choose the team", body: "This bot leads the crew you write here.", icon: Users },+];+export function CreateBot({ onCreated, onCancel, existingIds }: { onCreated: (id: string) => void; onCancel: () => void; existingIds: string[] }) {const [template, setTemplate] = useState<Template | null>(null);const [name, setName] = useState("");@@ -65,8 +84,13 @@ export function CreateBot({ onCreated, onCancel, existingIds }: { onCreated: (idconst [schedules, setSchedules] = useState<BotSchedule[]>([]);const [model, setModel] = useState<{ provider?: string; model?: string } | undefined>(undefined);const [budget, setBudget] = useState("1000000");+ const [structure, setStructure] = useState<Structure>("auto");+ const [crew, setCrew] = useState<CrewSpec[]>([]);+ const [maxCrew, setMaxCrew] = useState(6);const [tiers, setTiers] = useState<BotTier[] | undefined>(undefined);- const [busy, setBusy] = useState(false);+ /** Mercury's proposal, once asked for: the review screen shows it. */+ const [plan, setPlan] = useState<BotPlan | null>(null);+ const [busy, setBusy] = useState<"plan" | "create" | null>(null);const [error, setError] = useState<string | null>(null);useEffect(() => { void api.bots.tiers().then(setTiers).catch(() => {}); }, []);@@ -77,26 +101,60 @@ export function CreateBot({ onCreated, onCancel, existingIds }: { onCreated: (idsetPersona(t.persona);setTier(t.tier);setSchedules(t.schedules);- if (!name && t.id !== "blank") setName(t.label);+ setStructure(t.structure);+ if (!name && t.id !== "blank") setName(t.label === "A team (fleet)" ? "" : t.label);}const id = uniqueId(slugify(name || "bot"), existingIds);const budgetNum = Number(budget.replace(/[,\s_]/g, ""));- const problem = !name.trim() ? "Give it a name."+ const formProblem = !name.trim() ? "Give it a name.": !persona.trim() ? "Say how it should work (its instructions).": !Number.isFinite(budgetNum) || budgetNum < 10_000 ? "The daily budget must be at least 10,000 tokens.": schedules.find((s) => !s.prompt.trim()) ? "Every schedule needs instructions."- : null;+ : structure === "fleet-manual" && crew.filter((c) => c.name.trim()).length === 0 ? "Add at least one crew member, or pick another option."+ : null;+ const crewProblem = (list: CrewSpec[]) => list.find((c) => !c.name.trim() || !c.persona.trim()) ? "Every crew member needs a name and instructions." : null;++ async function askMercury(fleet: boolean) {+ if (formProblem) { setError(formProblem); return; }+ setBusy("plan");+ setError(null);+ try {+ const r = await api.bots.plan({ name: name.trim(), description: description.trim(), persona: persona.trim(), ...(fleet ? { fleet: true } : {}) });+ setMaxCrew(r.maxCrew);+ if (fleet && r.plan.shape !== "fleet") {+ setError("Mercury couldn't design a team for this right now. Try again, or choose the team yourself.");+ return;+ }+ setPlan(r.plan);+ setCrew(r.plan.crew);+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ } finally {+ setBusy(null);+ }+ }- async function create() {+ async function create(asFleet: boolean, team: CrewSpec[]) {+ const problem = formProblem ?? (asFleet ? crewProblem(team) : null);if (problem) { setError(problem); return; }- setBusy(true);+ setBusy("create");setError(null);try {await api.bots.create({id, name: name.trim(), description: description.trim() || undefined, persona: persona.trim(), tier,manifest: { ...(model ? { model } : {}), autonomy: { dailyTokenBudget: Math.round(budgetNum) } },});+ if (asFleet) {+ await api.bots.promote(id);+ // Crew inherit the lead's permission level; their ids are unique next to every bot's.+ const taken = [...existingIds, id];+ for (const c of team.filter((m) => m.name.trim())) {+ const crewId = uniqueId(slugify(c.name), taken);+ taken.push(crewId);+ await api.bots.addCrew(id, { id: crewId, name: c.name.trim(), description: c.description.trim(), persona: c.persona.trim() });+ }+ }// Schedules go through the editor's path so they're registered with the scheduler at once.if (schedules.length) await api.bots.update(id, { schedules: schedules.map((s) => ({ ...s, prompt: s.prompt.trim() })) });await refreshBots();@@ -104,16 +162,17 @@ export function CreateBot({ onCreated, onCancel, existingIds }: { onCreated: (id} catch (e) {setError(e instanceof Error ? e.message : String(e));} finally {- setBusy(false);+ setBusy(null);}}+ // ── 1. What it's for ────────────────────────────────────────────────if (!template) {return (<div className="mx-auto flex max-w-[760px] flex-col gap-5 px-8 py-8"><div><h1 className="text-xl font-semibold tracking-tight text-ink">New bot</h1>- <p className="mt-1 text-sm text-ink3">A bot works on its own, on a schedule or when you message it, and reports back to your inbox. Pick a starting point; you can change everything.</p>+ <p className="mt-1 text-sm text-ink3">A bot works on its own, on a schedule or when you message it, and reports back to your inbox. It can work alone, or lead a fleet of specialist bots. Pick a starting point; you can change everything.</p></div><div className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">{TEMPLATES.map((t) => (@@ -131,63 +190,143 @@ export function CreateBot({ onCreated, onCancel, existingIds }: { onCreated: (id);}- return (- <div className="flex h-full min-h-0 flex-col">- <div className="min-h-0 flex-1 overflow-y-auto">- <div className="mx-auto flex max-w-[760px] flex-col gap-6 px-8 py-8">- <div>- <h1 className="text-xl font-semibold tracking-tight text-ink">New bot · {template.label}</h1>- <p className="mt-1 text-sm text-ink3">Everything here can be changed later in the bot's Settings.</p>+ // ── 3. Mercury's proposal ───────────────────────────────────────────+ if (plan) {+ const fleet = plan.shape === "fleet";+ return (+ <Frame+ footer={<>+ <Button variant="ghost" onClick={() => { setPlan(null); setError(null); }}>Back</Button>+ <span className="flex-1 text-right text-sm text-red">{error}</span>+ <Button variant="primary" loading={busy === "create"} onClick={() => void create(fleet, crew)}>{fleet ? `Create the fleet (${crew.filter((c) => c.name.trim()).length + 1} bots)` : "Create bot"}</Button>+ </>}+ >+ <div>+ <h1 className="text-xl font-semibold tracking-tight text-ink">{fleet ? `Mercury suggests a fleet of ${crew.length + 1}` : "Mercury suggests one bot"}</h1>+ <p className="mt-1 text-sm text-ink2">{plan.reason}</p>+ </div>++ <div className="flex items-center gap-3 rounded-xl border border-line bg-surface p-4">+ {fleet ? <Crown size={18} className="shrink-0 text-amber" aria-hidden="true" /> : <Bot size={18} className="shrink-0 text-ink2" aria-hidden="true" />}+ <div className="min-w-0 flex-1">+ <div className="text-sm font-medium text-ink">{name}{fleet && <span className="ml-2 text-xs font-normal text-ink3">lead</span>}</div>+ <div className="truncate text-xs text-ink3">{description || "Your instructions"}</div></div>+ </div>- <Section title="Name" hint={`Its id will be ${id}.`}>- <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Rust Watcher" autoFocus aria-label="Name" />+ {fleet ? (+ <Section title="The crew" hint={`They work for ${name}: it hands them parts of the job and combines what they send back. Edit, remove or add members (up to ${maxCrew}).`}>+ <CrewEditor value={crew} onChange={setCrew} max={maxCrew} />+ <div><button onClick={() => { setPlan({ ...plan, shape: "solo", crew: [] }); setCrew([]); }} className="text-sm text-ink3 hover:text-ink">Make it one bot instead</button></div></Section>+ ) : (+ <div className="flex flex-col gap-2">+ <p className="text-sm text-ink3">One bot is the cheapest setup: every hand-off in a fleet is an extra run.</p>+ <div><Button variant="outline" size="sm" loading={busy === "plan"} onClick={() => void askMercury(true)}><Crown size={13} /> Make it a fleet anyway</Button></div>+ </div>+ )}+ </Frame>+ );+ }- <Section title="What it's for" hint="One line, shown in the bot list.">- <Input value={description} onChange={(e) => setDescription(e.target.value)} placeholder="e.g. Watches Hacker News for Rust posts" aria-label="Description" />- </Section>+ // ── 2. The bot itself ───────────────────────────────────────────────+ const needsPlan = structure === "auto" || structure === "fleet-auto";+ return (+ <Frame+ footer={<>+ <Button variant="ghost" onClick={() => setTemplate(null)}>Back</Button>+ <span className="flex-1 text-right text-sm text-red">{error}</span>+ <Button variant="ghost" onClick={onCancel}>Cancel</Button>+ {needsPlan ? (+ <Button variant="primary" loading={busy === "plan"} onClick={() => void askMercury(structure === "fleet-auto")}>+ {busy === "plan" ? "Mercury is planning…" : "Continue"}+ </Button>+ ) : (+ <Button variant="primary" loading={busy === "create"} onClick={() => void create(structure === "fleet-manual", crew)}>+ {structure === "fleet-manual" ? `Create the fleet (${crew.filter((c) => c.name.trim()).length + 1} bots)` : "Create bot"}+ </Button>+ )}+ </>}+ >+ <div>+ <h1 className="text-xl font-semibold tracking-tight text-ink">New bot · {template.label}</h1>+ <p className="mt-1 text-sm text-ink3">Everything here can be changed later in the bot's Settings.</p>+ </div>- <Section title="How it works" hint="Its instructions. Say what a good result is, and when there's nothing to report.">- <textarea value={persona} onChange={(e) => setPersona(e.target.value)} rows={8}- className="w-full resize-y rounded-md border border-line bg-surface px-3 py-2 text-sm text-ink placeholder:text-ink4" aria-label="Instructions"- placeholder="You… When you finish, close with bot_report; if there's nothing new, call bot_no_update." />- </Section>+ <Section title="Name" hint={`Its id will be ${id}.`}>+ <Input value={name} onChange={(e) => setName(e.target.value)} placeholder={template.id === "team" ? "e.g. Newsroom" : "e.g. Rust Watcher"} autoFocus aria-label="Name" />+ </Section>- <Section title="When it runs">- <ScheduleEditor value={schedules} onChange={setSchedules} />- </Section>+ <Section title="What it's for" hint="One line, shown in the bot list.">+ <Input value={description} onChange={(e) => setDescription(e.target.value)} placeholder="e.g. Watches Hacker News for Rust posts" aria-label="Description" />+ </Section>- <Section title="What it may do">- <TierPicker value={tier} onChange={setTier} tiers={tiers} />- </Section>+ <Section title="How it works" hint="Its instructions, in your own words. Say what a good result is, and when there's nothing to report.">+ <textarea value={persona} onChange={(e) => setPersona(e.target.value)} rows={8}+ className="w-full resize-y rounded-md border border-line bg-surface px-3 py-2 text-sm text-ink placeholder:text-ink4" aria-label="Instructions"+ placeholder="You… When you finish, close with bot_report; if there's nothing new, call bot_no_update." />+ <PersonaBuilderButton text={persona} name={name} onBuilt={setPersona} />+ </Section>- <Section title="Model and budget">- <div className="flex flex-col gap-2.5">- <ModelPicker value={model} onChange={setModel} />- <label className="flex items-center gap-2 text-sm text-ink2">- <span className="w-40 shrink-0">Daily token budget</span>- <Input value={budget} onChange={(e) => setBudget(e.target.value)} mono className="h-9 w-44" aria-label="Daily token budget" />- <span className="text-xs text-ink4">It pauses until tomorrow when it's spent.</span>- </label>- </div>- </Section>+ <Section title="Alone or a fleet" hint="A fleet is a lead bot that hands parts of the job to specialist crew bots.">+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2" role="radiogroup" aria-label="Alone or a fleet">+ {STRUCTURES.map((s) => (+ <button key={s.id} role="radio" aria-checked={structure === s.id} onClick={() => setStructure(s.id)}+ className={cx("flex items-start gap-3 rounded-lg border px-3 py-2.5 text-left transition-colors", structure === s.id ? "border-accent/60 bg-accent/[0.06]" : "border-line hover:border-line-strong")}>+ <s.icon size={16} className={cx("mt-0.5 shrink-0", structure === s.id ? "text-accent" : "text-ink3")} aria-hidden="true" />+ <span>+ <span className="flex items-center gap-2 text-sm font-medium text-ink">{s.title}{s.id === "auto" && <span className="text-xs font-normal text-ink4">recommended</span>}</span>+ <span className="block text-xs text-ink3">{s.body}</span>+ </span>+ </button>+ ))}</div>+ {structure === "fleet-manual" && (+ <div className="mt-2 flex flex-col gap-2">+ <p className="text-xs text-ink3">The crew. {name || "This bot"} leads them; they get its permission level.</p>+ <CrewEditor value={crew} onChange={setCrew} max={maxCrew} />+ </div>+ )}+ </Section>++ <Section title="When it runs">+ <ScheduleEditor value={schedules} onChange={setSchedules} />+ </Section>++ <Section title="What it may do" hint={structure === "solo" ? undefined : "If it leads a fleet, its crew get the same level."}>+ <TierPicker value={tier} onChange={setTier} tiers={tiers} />+ </Section>++ <Section title="Model and budget">+ <div className="flex flex-col gap-2.5">+ <ModelPicker value={model} onChange={setModel} />+ <label className="flex items-center gap-2 text-sm text-ink2">+ <span className="w-40 shrink-0">Daily token budget</span>+ <Input value={budget} onChange={(e) => setBudget(e.target.value)} mono className="h-9 w-44" aria-label="Daily token budget" />+ <span className="text-xs text-ink4">It pauses until tomorrow when it's spent.</span>+ </label>+ </div>+ </Section>+ {busy === "plan" && <p className="flex items-center gap-2 text-sm text-ink3"><Spinner size={13} /> Mercury is looking at the job (10–60 s)…</p>}+ </Frame>+ );+}++/** The scrolling form with its action bar always on screen. */+function Frame({ children, footer }: { children: React.ReactNode; footer: React.ReactNode }) {+ return (+ <div className="flex h-full min-h-0 flex-col">+ <div className="min-h-0 flex-1 overflow-y-auto">+ <div className="mx-auto flex max-w-[760px] flex-col gap-6 px-8 py-8">{children}</div></div>- {/* Always on screen: only the form above scrolls. */}- <div className="flex shrink-0 items-center gap-2 border-t border-line bg-surface px-8 py-3">- <Button variant="ghost" onClick={() => setTemplate(null)}>Back</Button>- <span className="flex-1 text-right text-sm text-red">{error}</span>- <Button variant="ghost" onClick={onCancel}>Cancel</Button>- <Button variant="primary" loading={busy} onClick={() => void create()}>Create bot</Button>- </div>+ <div className="flex shrink-0 items-center gap-2 border-t border-line bg-surface px-8 py-3">{footer}</div></div>);}function Section({ title, hint, children }: { title: string; hint?: string; children: React.ReactNode }) {return (- <section className={cx("flex flex-col gap-2")}>+ <section className="flex flex-col gap-2"><div><h2 className="text-sm font-semibold text-ink">{title}</h2>{hint && <p className="text-xs text-ink3">{hint}</p>}diff --git a/apps/desktop/src/views/bots/FleetTools.tsx b/apps/desktop/src/views/bots/FleetTools.tsxnew file mode 100644index 00000000..2d240d51--- /dev/null+++ b/apps/desktop/src/views/bots/FleetTools.tsx@@ -0,0 +1,106 @@+import { Crown, Sparkles, UserPlus } from "lucide-react";+import { useState } from "react";+import * as api from "~/api/mercury";+import type { CrewSpec } from "~/api/types";+import { refreshBots } from "~/app/events";+import { useBots } from "~/app/store";+import { Button } from "~/components/ui/Button";+import { Dialog } from "~/components/ui/Dialog";+import { CrewEditor, slugify } from "./BotForms";++/**+ * Growing a fleet from its page: write a crew member yourself, or let+ * Mercury design more (it reads the lead's instructions and proposes+ * specialists it doesn't have yet; they appear as they're created).+ */+export function CrewActions({ leadId, leadName, crewCount, maxCrew = 6 }: { leadId: string; leadName: string; crewCount: number; maxCrew?: number }) {+ const bots = useBots((s) => s.bots);+ const [adding, setAdding] = useState(false);+ const [draft, setDraft] = useState<CrewSpec[]>([{ id: "", name: "", description: "", persona: "" }]);+ const [busy, setBusy] = useState<"add" | "suggest" | null>(null);+ const [note, setNote] = useState<{ text: string; ok: boolean } | null>(null);+ const full = crewCount >= maxCrew;++ async function add() {+ const m = draft[0];+ if (!m.name.trim() || !m.persona.trim()) { setNote({ text: "Give it a name and instructions.", ok: false }); return; }+ setBusy("add");+ setNote(null);+ try {+ const taken = bots.map((b) => b.id);+ let id = slugify(m.name);+ for (let i = 2; taken.includes(id); i++) id = `${slugify(m.name)}-${i}`;+ await api.bots.addCrew(leadId, { id, name: m.name.trim(), description: m.description.trim(), persona: m.persona.trim() });+ setAdding(false);+ setDraft([{ id: "", name: "", description: "", persona: "" }]);+ setNote({ text: `${m.name.trim()} joined ${leadName}'s crew.`, ok: true });+ void refreshBots();+ } catch (e) {+ setNote({ text: e instanceof Error ? e.message : String(e), ok: false });+ } finally {+ setBusy(null);+ }+ }++ async function suggest() {+ setBusy("suggest");+ setNote(null);+ try {+ await api.bots.autoCrew(leadId);+ setNote({ text: "Mercury is designing crew for this fleet (up to a minute or two). New members appear here as they're created.", ok: true });+ } catch (e) {+ setNote({ text: e instanceof Error ? e.message : String(e), ok: false });+ } finally {+ setBusy(null);+ }+ }++ return (+ <div className="flex flex-col gap-2">+ <div className="flex flex-wrap items-center gap-2">+ <Button size="sm" variant="outline" disabled={full} onClick={() => setAdding(true)}><UserPlus size={13} /> Add a crew member</Button>+ <Button size="sm" variant="ghost" disabled={full} loading={busy === "suggest"} onClick={() => void suggest()}><Sparkles size={13} /> Let Mercury suggest crew</Button>+ {full && <span className="text-xs text-ink4">The crew is full ({maxCrew}).</span>}+ </div>+ {note && <p className={note.ok ? "text-xs text-ink3" : "text-xs text-red"}>{note.text}</p>}+ <Dialog open={adding} onOpenChange={setAdding} title={`New crew member for ${leadName}`} description="It gets the lead's permission level. The lead hands it work and combines what it sends back." width={560}>+ <div className="flex flex-col gap-3">+ <CrewEditor value={draft} onChange={(c) => setDraft(c.length ? c.slice(0, 1) : [{ id: "", name: "", description: "", persona: "" }])} max={1} />+ <div className="flex justify-end gap-2">+ <Button variant="ghost" onClick={() => setAdding(false)}>Cancel</Button>+ <Button variant="primary" loading={busy === "add"} onClick={() => void add()}>Add to the crew</Button>+ </div>+ </div>+ </Dialog>+ </div>+ );+}++/** A bot working alone can become a fleet lead: then it hands parts of its job to crew. */+export function MakeFleet({ id, name }: { id: string; name: string }) {+ const [busy, setBusy] = useState(false);+ const [problem, setProblem] = useState<string | null>(null);+ async function promote() {+ setBusy(true);+ setProblem(null);+ try {+ await api.bots.promote(id);+ await refreshBots();+ } catch (e) {+ setProblem(e instanceof Error ? e.message : String(e));+ } finally {+ setBusy(false);+ }+ }+ return (+ <div className="flex items-center gap-3 rounded-xl border border-line bg-surface p-4">+ <Crown size={16} className="shrink-0 text-ink3" aria-hidden="true" />+ <div className="min-w-0 flex-1">+ <div className="text-sm text-ink">{name} works alone</div>+ <p className="text-xs text-ink3">Make it a fleet lead when the job has separate parts (research, writing, checking…). You then add crew, or let Mercury suggest them.</p>+ {problem && <p className="text-xs text-red">{problem}</p>}+ </div>+ <Button size="sm" variant="outline" loading={busy} onClick={() => void promote()}>Turn into a fleet</Button>+ </div>+ );+}diff --git a/apps/desktop/src/views/bots/Overview.tsx b/apps/desktop/src/views/bots/Overview.tsxnew file mode 100644index 00000000..a609b70f--- /dev/null+++ b/apps/desktop/src/views/bots/Overview.tsx@@ -0,0 +1,104 @@+import { Crown, Plus } from "lucide-react";+import type { BotStatus } from "~/api/types";+import { BotAvatar } from "~/components/BotAvatar";+import { StateOrb } from "~/components/indicators/StateOrb";+import type { AgentState } from "~/app/store";+import { cx } from "~/lib/cx";++/**+ * Every bot at a glance, the way they're organised: fleets (a lead and its+ * crew) first, then the bots that work alone. One click opens a bot; the+ * last card makes a new one.+ */+export function BotsOverview({ fleets, solo, onOpen, onNew }: {+ fleets: Array<{ lead: BotStatus; crew: BotStatus[] }>;+ solo: BotStatus[];+ onOpen: (id: string) => void;+ onNew: () => void;+}) {+ return (+ <div className="mx-auto flex max-w-[1000px] flex-col gap-7 px-8 py-7">+ <div>+ <h1 className="text-xl font-semibold tracking-tight text-ink">All bots</h1>+ <p className="mt-0.5 text-sm text-ink3">+ {fleets.length} fleet{fleets.length === 1 ? "" : "s"} · {solo.length} on {solo.length === 1 ? "its" : "their"} own.+ A fleet is a lead that hands parts of a job to its crew; a bot on its own does the whole job.+ </p>+ </div>++ <section className="flex flex-col gap-3">+ <h2 className="text-sm font-semibold text-ink">Fleets</h2>+ {fleets.length === 0 && <p className="text-sm text-ink4">No fleets yet. Make one with New bot → “A fleet”, or turn a bot into a fleet lead from its page.</p>}+ <div className="grid grid-cols-1 gap-3 lg:grid-cols-2">+ {fleets.map(({ lead, crew }) => {+ const working = crew.filter((c) => c.state === "running").length + (lead.state === "running" ? 1 : 0);+ return (+ <button key={lead.id} onClick={() => onOpen(lead.id)} className="flex flex-col gap-3 rounded-xl border border-line bg-surface p-4 text-left hover:border-line-strong">+ <div className="flex items-center gap-3">+ <Avatar bot={lead} size={40} />+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5 text-sm font-medium text-ink"><Crown size={13} className="shrink-0 text-amber" aria-hidden="true" /><span className="truncate">{lead.name}</span></div>+ <div className="truncate text-xs text-ink3">{lead.description || "Fleet lead"}</div>+ </div>+ <Status bot={lead} />+ </div>+ <div className="flex items-center gap-2 border-t border-line pt-3">+ <div className="flex -space-x-1.5">+ {crew.slice(0, 8).map((c) => <span key={c.id} className="rounded-full ring-2 ring-surface"><BotAvatar id={c.id} name={c.name} hasAvatar={c.hasAvatar} size={24} dimmed={!c.enabled} /></span>)}+ </div>+ <span className="text-xs text-ink3">{crew.length} crew{working ? ` · ${working} working` : ""}</span>+ </div>+ </button>+ );+ })}+ </div>+ </section>++ <section className="flex flex-col gap-3">+ <h2 className="text-sm font-semibold text-ink">On their own</h2>+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">+ {solo.map((b) => (+ <button key={b.id} onClick={() => onOpen(b.id)} className="flex items-center gap-3 rounded-xl border border-line bg-surface p-3.5 text-left hover:border-line-strong">+ <Avatar bot={b} size={36} />+ <div className="min-w-0 flex-1">+ <div className="truncate text-sm font-medium text-ink">{b.name}</div>+ <div className="truncate text-xs text-ink3">{b.description || "Works alone"}</div>+ </div>+ <Status bot={b} />+ </button>+ ))}+ <button onClick={onNew} className="flex items-center justify-center gap-2 rounded-xl border border-dashed border-line p-3.5 text-sm text-ink3 hover:border-line-strong hover:text-ink">+ <Plus size={15} /> New bot+ </button>+ </div>+ </section>+ </div>+ );+}++function Avatar({ bot, size }: { bot: BotStatus; size: number }) {+ return (+ <span className="relative shrink-0">+ <BotAvatar id={bot.id} name={bot.name} hasAvatar={bot.hasAvatar} size={size} dimmed={!bot.enabled || bot.stopped} />+ <StateOrb state={orb(bot)} size={9} className="absolute -bottom-0.5 -right-0.5 rounded-full bg-surface p-[1.5px]" />+ </span>+ );+}++function Status({ bot }: { bot: BotStatus }) {+ const label = !bot.enabled ? "Off" : bot.stopped ? "Stopped" : bot.needsYou ? "Needs you" : bot.state === "running" ? "Working" : bot.state === "queued" ? "Queued" : bot.state === "paused" ? "Paused" : "Idle";+ return (+ <span className="flex shrink-0 items-center gap-2">+ {!!bot.unread && <span className="rounded-full bg-accent px-1.5 text-2xs font-semibold leading-5 text-on-accent">{bot.unread}</span>}+ <span className={cx("text-xs", bot.needsYou ? "text-amber" : bot.state === "running" ? "text-accent" : "text-ink4")}>{label}</span>+ </span>+ );+}++function orb(b: BotStatus): AgentState {+ if (b.needsYou) return "needs-you";+ if (!b.enabled || b.state === "disabled") return "offline";+ if (b.state === "running") return "working";+ if (b.state === "queued") return "thinking";+ return "idle";+}