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): Bots 2.0 — inbox, create and edit bots, permissions in words

Salman Qureshi40a6a76105c8
diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.ts
index 7e4540e1..d9a259fa 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,
- BotManifest, BotRunRecord, BotStatus, ChatMessage, ChatSettings, ChatThread, CodeStatus, HealthInfo,
+ BotInboxEntry, BotManifest, BotRunRecord, BotStatus, BotTier, BotTierId, ChatMessage, ChatSettings, ChatThread, CodeStatus, HealthInfo,
McpServer, ModelsResponse, CodeMode, CostReport, Deliverable, RunTranscript, PairResponse, PluginItem, ReasoningChoice, Skill, DeviceSummary,
} from "./types";
@@ -82,7 +82,7 @@ export const code = {
};
export const bots = {
- list: () => http.get<{ bots: BotStatus[]; available: boolean }>("/api/bots"),
+ list: () => http.get<{ bots: BotStatus[]; available: boolean; unread?: number }>("/api/bots"),
get: (id: string) => http.get<{ bot: BotManifest; state: BotStatus | null; journal: BotRunRecord[] }>(`/api/bots/${encodeURIComponent(id)}`),
message: (id: string, message: string) => http.post<{ accepted: boolean; jobId?: string; reasonCode?: string }>(`/api/bots/${encodeURIComponent(id)}/message`, { message }),
enable: (id: string) => http.post<{ ok: boolean }>(`/api/bots/${encodeURIComponent(id)}/enable`),
@@ -98,6 +98,20 @@ export const bots = {
cost: (days: number) => http.get<CostReport>(`/api/bots-cost?days=${days}`),
avatarUrl: (id: string) => `/api/bots/${encodeURIComponent(id)}/avatar`,
runNow: (id: string) => http.post<{ accepted: boolean }>(`/api/bots/${encodeURIComponent(id)}/run`, {}),
+ /** Resume a stopped bot (and its switched-off routines). */
+ start: (id: string) => http.post<{ ok: boolean; message: string }>(`/api/bots/${encodeURIComponent(id)}/start`, {}),
+ create: (input: { id: string; name: string; description?: string; persona?: string; tier?: BotTierId; manifest?: Partial<BotManifest> }) =>
+ http.post<{ bot: BotManifest }>("/api/bots", input),
+ update: (id: string, patch: Partial<BotManifest>) => http.patch<{ bot: BotManifest }>(`/api/bots/${encodeURIComponent(id)}`, patch),
+ persona: (id: string) => http.get<{ persona: string }>(`/api/bots/${encodeURIComponent(id)}/persona`).then((r) => r.persona),
+ setPersona: (id: string, persona: string) => http.put<{ ok: boolean }>(`/api/bots/${encodeURIComponent(id)}/persona`, { persona }),
+ tiers: () => http.get<{ tiers: BotTier[] }>("/api/bots/tiers").then((r) => r.tiers),
+ setTier: (id: string, tier: BotTierId) => http.put<{ ok: boolean }>(`/api/bots/${encodeURIComponent(id)}/permissions`, { tier }),
+ 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 } : {}),
+ dlq: (id: string) => http.get<{ dlq: Array<{ id: string; prompt: string; reasonCode?: string; createdAt: number }> }>(`/api/bots/${encodeURIComponent(id)}/dlq`),
+ replay: (id: string, jobId: string) => http.post<{ accepted: boolean }>(`/api/bots/${encodeURIComponent(id)}/replay/${encodeURIComponent(jobId)}`, {}),
};
export const plugins = {
diff --git a/apps/desktop/src/api/types.ts b/apps/desktop/src/api/types.ts
index f5b46704..ae023941 100644
--- a/apps/desktop/src/api/types.ts
+++ b/apps/desktop/src/api/types.ts
@@ -148,6 +148,30 @@ export interface BotStatus {
parent?: string;
crewWorking?: number;
hasAvatar?: boolean;
+ /** Unread inbox entries from this bot. */
+ unread?: number;
+ /** Permission tier, or "custom" for a hand-edited permissions file. */
+ tier?: BotTierId | "custom";
+ /** Stopped by the owner; stays stopped until Start. */
+ stopped?: boolean;
+ description?: string;
+ routinePausedUntil?: number;
+}
+
+export type BotTierId = "readonly" | "builder" | "operator" | "full";
+
+export interface BotTier {
+ id: BotTierId;
+ label: string;
+ description: string;
+ deny: string[];
+}
+
+export interface BotSchedule {
+ name: string;
+ cron: string;
+ prompt: string;
+ expects?: "work" | "message" | "check";
}
export interface BotManifest {
@@ -158,8 +182,25 @@ export interface BotManifest {
fleetRole?: "lead" | "crew";
parent?: string;
model?: { provider?: string; model?: string };
- schedules?: Array<{ name: string; cron: string; prompt: string }>;
- autonomy?: { maxSteps?: number; dailyTokenBudget?: number };
+ schedules?: BotSchedule[];
+ autonomy?: { maxSteps?: number; dailyTokenBudget?: number; maxTokensPerTurn?: number; maxTurnMinutes?: number };
+ memory?: { scope?: "own" | "shared-read" | "none"; learn?: boolean };
+}
+
+/** One thing a bot did for you (GET /api/bots/inbox). */
+export interface BotInboxEntry {
+ id: string;
+ botId: string;
+ botName: string;
+ runId: string;
+ kind: "result" | "failed" | "needs-you";
+ title: string;
+ summary: string;
+ files: string[];
+ complete?: boolean;
+ reasonCode?: string;
+ at: number;
+ read: boolean;
}
export interface BotRunRecord {
@@ -177,6 +218,11 @@ export interface BotRunRecord {
steps?: number;
toolCalls?: number;
outcome?: string;
+ /** How the bot closed the run: result, no_update (quiet) or failure. */
+ report?: "result" | "no_update" | "failure";
+ complete?: boolean;
+ /** Files delivered by this run. */
+ deliverables?: string[];
}
export interface Deliverable {
diff --git a/apps/desktop/src/app/events.ts b/apps/desktop/src/app/events.ts
index cb9e794a..cc63cd94 100644
--- a/apps/desktop/src/app/events.ts
+++ b/apps/desktop/src/app/events.ts
@@ -9,7 +9,7 @@ import { useEffect } from "react";
import { openStream } from "~/api/stream";
import * as api from "~/api/mercury";
import { ApiError, http } from "~/api/client";
-import type { BotActivityEvent, ChatMessage, CodeMode, PendingPrompt } from "~/api/types";
+import type { BotActivityEvent, BotInboxEntry, BotStatus, ChatMessage, CodeMode, PendingPrompt } from "~/api/types";
import { useBots, useChat, useRuntimeState, type AgentState } from "./store";
import { conversations, useCodeSessions, type ConversationStore, type Surface } from "./conversation";
import type { ArtifactRef } from "~/api/artifacts";
@@ -26,6 +26,21 @@ export function useRuntimeEvents(enabled: boolean): void {
if (!enabled) return;
const stream = openStream("/api/bots/events", {
onEvent: (event, raw) => {
+ if (event === "bot_roster") {
+ // Roster news (an edit, a new crew member, a delete) from any screen.
+ const r = safeJson<{ bots: BotStatus[] }>(raw);
+ if (r?.bots) useBots.getState().setBots(r.bots, true);
+ return;
+ }
+ if (event === "bot_inbox") {
+ // A result, a reported failure, or a run that needs you.
+ const entry = safeJson<BotInboxEntry>(raw);
+ if (!entry) return;
+ useBots.getState().inboxChanged();
+ void refreshBots();
+ void import("./notify/notify").then(({ tellBotInbox }) => tellBotInbox(entry));
+ return;
+ }
if (event !== "bot_activity") return;
const ev = safeJson<BotActivityEvent>(raw);
if (!ev || ev.kind === "thinking") return;
@@ -242,8 +257,8 @@ export async function setThreadSaved(threadId: string, saved: boolean): Promise<
export async function refreshBots(): Promise<void> {
try {
- const { bots, available } = await api.bots.list();
- useBots.getState().setBots(bots, available);
+ const { bots, available, unread } = await api.bots.list();
+ useBots.getState().setBots(bots, available, unread);
} catch { /* bots unavailable on this runtime */ }
}
diff --git a/apps/desktop/src/app/notify/notify.ts b/apps/desktop/src/app/notify/notify.ts
index 2c14899f..fda38594 100644
--- a/apps/desktop/src/app/notify/notify.ts
+++ b/apps/desktop/src/app/notify/notify.ts
@@ -189,8 +189,29 @@ export function handleActivity(e: ActivityEvent): void {
}
}
-/** Open the conversation an alert is about. */
+/**
+ * A bot's inbox entry: a result, a failure it reported, or a run that needs
+ * you. Told through the same layers as a conversation (sound, banner when the
+ * app is in the background, in-app alert when it's in front), unless you're
+ * already looking at the bots.
+ */
+export function tellBotInbox(entry: { botId: string; botName: string; kind: "result" | "failed" | "needs-you"; title: string; summary: string }): void {
+ const n = useNotify.getState();
+ if (useVoice.getState().active) return;
+ if (useUi.getState().view === "bots" && windowFocused()) return;
+ if (entry.kind === "needs-you" && !n.prefs.needsYou) return;
+ const body = entry.summary.replace(/\s+/g, " ").slice(0, 180);
+ if (entry.kind === "result") tell("done", `bot:${entry.botId}`, entry.title, body || "Finished.");
+ else if (entry.kind === "failed") tell("failed", `bot:${entry.botId}`, entry.title, body);
+ else tell("needs", `bot:${entry.botId}`, entry.title, body || "It needs you.");
+}
+
+/** Open the conversation (or bot) an alert is about. */
export function openFromAlert(sessionId: string): void {
+ if (sessionId.startsWith("bot:")) {
+ useUi.getState().openBot(sessionId.slice(4));
+ return;
+ }
const surface = surfaceOf(sessionId);
useUi.getState().setView(surface);
void import("../events").then(({ openThread }) => openThread(surface, sessionId));
diff --git a/apps/desktop/src/app/store.ts b/apps/desktop/src/app/store.ts
index 4b2ccafb..2938e8cb 100644
--- a/apps/desktop/src/app/store.ts
+++ b/apps/desktop/src/app/store.ts
@@ -28,6 +28,10 @@ interface UiState {
pluginFocus: string | null;
openPlugin(id: string): void;
clearPluginFocus(): void;
+ /** What Bots should show next: a bot's page, or "inbox" (from a notification). */
+ botFocus: string | null;
+ openBot(target: string): void;
+ clearBotFocus(): void;
}
export const useUi = create<UiState>((set) => ({
@@ -43,6 +47,9 @@ export const useUi = create<UiState>((set) => ({
pluginFocus: null,
openPlugin: (id) => set({ view: "plugins", pluginFocus: id }),
clearPluginFocus: () => set({ pluginFocus: null }),
+ botFocus: null,
+ openBot: (target) => set({ view: "bots", botFocus: target }),
+ clearBotFocus: () => set({ botFocus: null }),
}));
interface RuntimeState {
@@ -98,7 +105,12 @@ interface BotsState {
bots: BotStatus[];
available: boolean;
activity: Record<string, string>;
- setBots(bots: BotStatus[], available: boolean): void;
+ /** Unread inbox entries across every bot. */
+ unread: number;
+ /** Bumped when an inbox entry arrives, so open lists reload. */
+ inboxVersion: number;
+ setBots(bots: BotStatus[], available: boolean, unread?: number): void;
+ inboxChanged(unread?: number): void;
setActivity(botId: string, label: string | null): void;
}
@@ -106,7 +118,10 @@ export const useBots = create<BotsState>((set) => ({
bots: [],
available: true,
activity: {},
- setBots: (bots, available) => set({ bots, available }),
+ unread: 0,
+ inboxVersion: 0,
+ setBots: (bots, available, unread) => set(unread === undefined ? { bots, available } : { bots, available, unread }),
+ inboxChanged: (unread) => set((s) => ({ inboxVersion: s.inboxVersion + 1, ...(unread === undefined ? {} : { unread }) })),
setActivity: (botId, label) => set((s) => {
const activity = { ...s.activity };
if (label === null) delete activity[botId];
diff --git a/apps/desktop/src/layout/Rail.tsx b/apps/desktop/src/layout/Rail.tsx
index 042a93bf..adc43cb3 100644
--- a/apps/desktop/src/layout/Rail.tsx
+++ b/apps/desktop/src/layout/Rail.tsx
@@ -1,7 +1,7 @@
import { Bot, Brain, Code2, MessageSquare, Puzzle, Settings, Sparkles, Layers } from "lucide-react";
import { useEffect, useMemo } from "react";
import { cx } from "~/lib/cx";
-import { useChat, useRuntimeState, useUi, type View } from "~/app/store";
+import { useChat, useRuntimeState, useUi, type View, useBots } from "~/app/store";
import { Mark } from "~/components/Logo";
import { LABELS } from "~/components/indicators/StateOrb";
import { Tooltip } from "~/components/ui/Tooltip";
@@ -33,6 +33,9 @@ export function Rail({ connectionName }: { connectionName: string }) {
const waiting = useNotify((s) => s.waiting);
const codeIds = useCodeSessions((s) => s.sessions);
const threads = useChat((s) => s.threads);
+ // Bots: amber when one needs you, blue when the inbox has something unread.
+ const botsWaiting = useBots((s) => s.bots.filter((b) => b.needsYou).length);
+ const botsUnread = useBots((s) => s.unread);
// Count only conversations that are in that list, so every dot here has a dot to find there.
const dots = useMemo(() => {
const code = new Set(codeIds.map((c) => c.id));
@@ -79,6 +82,9 @@ export function Rail({ connectionName }: { connectionName: string }) {
if (d.unread > 0) return <span className="absolute right-1.5 top-1.5 block h-1.5 w-1.5 rounded-full bg-blue" aria-label={`${d.unread} with something new`} />;
return null;
})()}
+ {v === "bots" && (botsWaiting > 0
+ ? <span className="absolute right-1.5 top-1.5 block h-1.5 w-1.5 rounded-full bg-amber" aria-label={`${botsWaiting} bot${botsWaiting === 1 ? "" : "s"} need you`} />
+ : botsUnread > 0 ? <span className="absolute right-1.5 top-1.5 block h-1.5 w-1.5 rounded-full bg-blue" aria-label={`${botsUnread} unread in the bots inbox`} /> : null)}
</button>
</Tooltip>
))}
diff --git a/apps/desktop/src/views/bots/Activity.tsx b/apps/desktop/src/views/bots/Activity.tsx
index 60a45f16..8b1336f2 100644
--- a/apps/desktop/src/views/bots/Activity.tsx
+++ b/apps/desktop/src/views/bots/Activity.tsx
@@ -54,7 +54,7 @@ export function Activity({ bots }: { bots: Array<{ id: string; name: string; has
<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>
+ <Badge tone={r.outcome === "failed" || r.state === "failed" ? "red" : r.outcome === "quiet" ? "neutral" : r.state === "completed" ? "accent" : "neutral"}>{runLabel(r)}</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} />}
@@ -103,12 +103,20 @@ function RunDetail({ botId, runId }: { botId: string; runId: string }) {
</ol>
</section>
<section>
- <h4 className="mb-1.5 text-xs font-medium uppercase tracking-wider text-ink4">Concluded</h4>
+ <h4 className="mb-1.5 text-xs font-medium uppercase tracking-wider text-ink4">{rec.report === "no_update" ? "Nothing new" : rec.report === "failure" ? "Couldn't do it" : "Concluded"}</h4>
<Markdown text={t.output || rec.summary || "(no output)"} />
</section>
+ {rec.deliverables && rec.deliverables.length > 0 && (
+ <section>
+ <h4 className="mb-1.5 text-xs font-medium uppercase tracking-wider text-ink4">Delivered</h4>
+ <ul className="flex flex-col gap-1">
+ {rec.deliverables.map((f) => <li key={f} className="break-all font-mono text-xs text-ink2" data-selectable>{f}</li>)}
+ </ul>
+ </section>
+ )}
</div>
<aside className="flex flex-col gap-3 text-sm">
- <Stat label="Outcome" value={rec.outcome ?? rec.state} />
+ <Stat label="Outcome" value={runLabel(rec)} />
<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()} />
@@ -128,3 +136,16 @@ function Stat({ label, value }: { label: string; value: React.ReactNode }) {
</div>
);
}
+
+/** A run in words: how the bot closed it when it did, else what it did. */
+function runLabel(r: { state: string; outcome?: string; report?: string; complete?: boolean }): string {
+ if (r.state === "failed") return "failed";
+ if (r.outcome === "failed") return "couldn't do it";
+ if (r.outcome === "quiet") return "nothing new";
+ if (r.outcome === "deliverable") return r.complete ? "delivered · done" : "delivered";
+ if (r.outcome === "message") return r.complete ? "reported · done" : "reported";
+ if (r.outcome === "action") return "acted";
+ if (r.outcome === "delegated") return "delegated";
+ if (r.outcome === "none" && r.state === "completed") return "no result";
+ return r.state;
+}
diff --git a/apps/desktop/src/views/bots/BotForms.test.ts b/apps/desktop/src/views/bots/BotForms.test.ts
new file mode 100644
index 00000000..57526114
--- /dev/null
+++ b/apps/desktop/src/views/bots/BotForms.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+import { describeCron, slugify, tooFrequent } from "./BotForms";
+
+/** The new-bot form: ids the runtime accepts, schedules in words, and the 15-minute floor said up front. */
+describe("bot forms", () => {
+ it("makes an id the runtime accepts from any name", () => {
+ expect(slugify("Rust Watcher")).toBe("rust-watcher");
+ expect(slugify(" Café Daily Brief!! ")).toBe("cafe-daily-brief");
+ expect(slugify("42 news")).toBe("bot-42-news");
+ expect(slugify("")).toBe("bot-new");
+ expect(slugify("x".repeat(80))).toHaveLength(30);
+ for (const id of [slugify("Rust Watcher"), slugify("42 news"), slugify("Ünïcode")]) expect(id).toMatch(/^[a-z][a-z0-9-]*$/);
+ });
+
+ it("says common schedules in words and leaves the rest as cron", () => {
+ expect(describeCron("0 9 * * 1-5")).toBe("Weekdays at 9");
+ expect(describeCron("0 * * * *")).toBe("Every hour");
+ expect(describeCron("30 7 * * *")).toBe("30 7 * * *");
+ });
+
+ it("warns when a schedule asks for more than one run every 15 minutes", () => {
+ expect(tooFrequent("*/5 * * * *")).toBe(true);
+ expect(tooFrequent("* * * * *")).toBe(true);
+ expect(tooFrequent("*/15 * * * *")).toBe(false);
+ expect(tooFrequent("0 9 * * *")).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/views/bots/BotForms.tsx b/apps/desktop/src/views/bots/BotForms.tsx
new file mode 100644
index 00000000..ea637ddb
--- /dev/null
+++ b/apps/desktop/src/views/bots/BotForms.tsx
@@ -0,0 +1,140 @@
+import { Plus, ShieldAlert, 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 { Input } from "~/components/ui/Input";
+import { cx } from "~/lib/cx";
+
+/**
+ * The pieces the bot wizard and a bot's Settings share: who it may act as
+ * (permission tier, in plain words), when it runs (schedules with presets),
+ * and which model it thinks with.
+ */
+
+/** Tiers in plain words: what the bot can and can't do. Falls back to the runtime's own text. */
+const TIER_WORDS: Record<BotTierId, { title: string; can: string; cant: string }> = {
+ readonly: { title: "Read only", can: "Browse the web, search, read files, message other bots, report back.", cant: "Can't write files or run commands." },
+ builder: { title: "Writes files", can: "Everything in Read only, plus create and edit files in its own folder.", cant: "Can't run commands or delete anything." },
+ operator: { title: "Runs commands", can: "Everything in Writes files, plus run commands inside its own folder.", cant: "Can't delete files or touch the rest of your computer." },
+ full: { title: "Full access", can: "Everything, including deleting files and reading and writing your whole home folder.", cant: "Only for automation you fully trust." },
+};
+
+export function TierPicker({ value, onChange, tiers }: { value: BotTierId | "custom" | undefined; onChange: (t: BotTierId) => void; tiers?: BotTier[] }) {
+ const ids: BotTierId[] = (tiers?.map((t) => t.id) ?? (Object.keys(TIER_WORDS) as BotTierId[]));
+ return (
+ <div className="flex flex-col gap-1.5" role="radiogroup" aria-label="Permissions">
+ {value === "custom" && (
+ <p className="rounded-lg border border-amber/40 bg-amber/[0.06] px-3 py-2 text-xs text-ink2">
+ This bot's permissions were edited by hand (its permissions.yaml). Picking a level below replaces them.
+ </p>
+ )}
+ {ids.map((id) => {
+ const w = TIER_WORDS[id];
+ const on = value === id;
+ return (
+ <button key={id} role="radio" aria-checked={on} onClick={() => onChange(id)}
+ className={cx("flex items-start gap-3 rounded-lg border px-3 py-2.5 text-left transition-colors", on ? "border-accent/60 bg-accent/[0.06]" : "border-line hover:border-line-strong")}>
+ <span className={cx("mt-1 h-3.5 w-3.5 shrink-0 rounded-full border", on ? "border-[5px] border-accent" : "border-line-strong")} aria-hidden="true" />
+ <span className="min-w-0 flex-1">
+ <span className="flex items-center gap-2 text-sm font-medium text-ink">
+ {w?.title ?? id}
+ {id === "readonly" && <span className="text-xs font-normal text-ink4">recommended</span>}
+ {id === "full" && <ShieldAlert size={13} className="text-amber" aria-hidden="true" />}
+ </span>
+ <span className="block text-xs text-ink3">{w ? `${w.can} ${w.cant}` : tiers?.find((t) => t.id === id)?.description}</span>
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+/** Common schedules, in words. Anything else is a custom cron. */
+export const SCHEDULE_PRESETS: Array<{ label: string; cron: string }> = [
+ { label: "Every hour", cron: "0 * * * *" },
+ { label: "Every 4 hours", cron: "0 */4 * * *" },
+ { label: "Every morning at 9", cron: "0 9 * * *" },
+ { label: "Weekdays at 9", cron: "0 9 * * 1-5" },
+ { label: "Every evening at 6", cron: "0 18 * * *" },
+ { label: "Mondays at 9", cron: "0 9 * * 1" },
+];
+
+export function describeCron(cron: string): string {
+ return SCHEDULE_PRESETS.find((p) => p.cron === cron.trim())?.label ?? cron;
+}
+
+/** Runs more often than every 15 minutes are slowed to that by Mercury. */
+export function tooFrequent(cron: string): boolean {
+ const minute = cron.trim().split(/\s+/)[0] ?? "";
+ if (minute === "*") return true;
+ const step = /^\*\/(\d+)$/.exec(minute);
+ return !!step && Number(step[1]) < 15;
+}
+
+export function ScheduleEditor({ value, onChange }: { value: BotSchedule[]; onChange: (s: BotSchedule[]) => void }) {
+ const set = (i: number, patch: Partial<BotSchedule>) => onChange(value.map((s, j) => (j === i ? { ...s, ...patch } : s)));
+ return (
+ <div className="flex flex-col gap-2.5">
+ {value.length === 0 && <p className="text-sm text-ink3">No schedule: it runs when you message it or press Run now.</p>}
+ {value.map((s, i) => {
+ const preset = SCHEDULE_PRESETS.some((p) => p.cron === s.cron);
+ return (
+ <div key={i} className="flex flex-col gap-2 rounded-lg border border-line p-3">
+ <div className="flex items-center gap-2">
+ <select value={preset ? s.cron : "custom"} onChange={(e) => set(i, { cron: e.target.value === "custom" ? s.cron || "0 9 * * *" : e.target.value })}
+ className="h-8 rounded-md border border-line bg-surface px-2 text-sm text-ink" aria-label="When">
+ {SCHEDULE_PRESETS.map((p) => <option key={p.cron} value={p.cron}>{p.label}</option>)}
+ <option value="custom">Custom (cron)…</option>
+ </select>
+ {!preset && <Input value={s.cron} onChange={(e) => set(i, { cron: e.target.value })} mono className="h-8 w-40" aria-label="Cron expression" placeholder="0 9 * * *" />}
+ <span className="flex-1" />
+ <button onClick={() => onChange(value.filter((_, j) => j !== i))} className="rounded p-1.5 text-ink4 hover:text-red" aria-label="Remove schedule"><Trash2 size={14} /></button>
+ </div>
+ <textarea value={s.prompt} onChange={(e) => set(i, { prompt: e.target.value })} rows={2} placeholder="What to do each time, and when to report nothing (e.g. “Check Hacker News for posts about Rust. Report only new ones; otherwise nothing new.”)"
+ 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="Instructions" />
+ {tooFrequent(s.cron) && <p className="text-xs text-amber">Mercury runs a routine at most every 15 minutes, so this runs every 15 minutes.</p>}
+ </div>
+ );
+ })}
+ <div>
+ <button onClick={() => onChange([...value, { name: nextName(value), cron: "0 9 * * *", prompt: "" }])} className="flex items-center gap-1.5 text-sm text-ink2 hover:text-ink">
+ <Plus size={14} /> Add a schedule
+ </button>
+ </div>
+ </div>
+ );
+}
+
+function nextName(list: BotSchedule[]): string {
+ for (let i = 1; ; i++) {
+ const name = i === 1 ? "routine" : `routine-${i}`;
+ if (!list.some((s) => s.name === name)) return name;
+ }
+}
+
+/** Which model the bot thinks with; empty = Mercury's default. */
+export function ModelPicker({ value, onChange }: { value: { provider?: string; model?: string } | undefined; onChange: (v: { provider?: string; model?: string } | undefined) => void }) {
+ const [models, setModels] = useState<ModelsResponse | null>(null);
+ useEffect(() => { void api.chat.models().then(setModels).catch(() => setModels(null)); }, []);
+ const key = value?.provider ? `${value.provider}::${value.model ?? ""}` : "";
+ return (
+ <select value={key} onChange={(e) => {
+ const v = e.target.value;
+ if (!v) { onChange(undefined); return; }
+ const [provider, model] = v.split("::");
+ onChange({ provider, model: model || undefined });
+ }} className="h-9 w-full rounded-md border border-line bg-surface px-2 text-sm text-ink" aria-label="Model">
+ <option value="">Mercury's default model{models?.current ? ` (${models.current.model})` : ""}</option>
+ {(models?.providers ?? []).filter((p) => p.available).map((p) => (
+ <option key={`${p.name}::${p.model}`} value={`${p.name}::${p.model}`}>{p.label ?? p.name} · {p.model}</option>
+ ))}
+ </select>
+ );
+}
+
+/** A bot id from its name: lowercase, dashes, unique-ish. */
+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"}`;
+}
diff --git a/apps/desktop/src/views/bots/BotSettings.tsx b/apps/desktop/src/views/bots/BotSettings.tsx
new file mode 100644
index 00000000..87bf6bbe
--- /dev/null
+++ b/apps/desktop/src/views/bots/BotSettings.tsx
@@ -0,0 +1,162 @@
+import { useEffect, useState } from "react";
+import * as api from "~/api/mercury";
+import type { BotManifest, BotSchedule, BotStatus, BotTier, BotTierId } from "~/api/types";
+import { refreshBots } from "~/app/events";
+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";
+
+/**
+ * Everything about a bot that the owner decides, on one page: its name and
+ * line, its instructions, when it runs, what it may do, its model and limits.
+ * Each section saves on its own; nothing waits for a restart.
+ */
+export function BotSettings({ id, status }: { id: string; status: BotStatus | null }) {
+ const [bot, setBot] = useState<BotManifest | null>(null);
+ const [persona, setPersona] = useState<string | null>(null);
+ const [tiers, setTiers] = useState<BotTier[] | undefined>(undefined);
+
+ async function load() {
+ const [b, p] = await Promise.all([api.bots.get(id).then((r) => r.bot).catch(() => null), api.bots.persona(id).catch(() => "")]);
+ setBot(b);
+ setPersona(p);
+ }
+ useEffect(() => { setBot(null); setPersona(null); void load(); }, [id]); // eslint-disable-line react-hooks/exhaustive-deps
+ useEffect(() => { void api.bots.tiers().then(setTiers).catch(() => {}); }, []);
+
+ if (!bot || persona === null) return <div className="flex h-40 items-center justify-center text-ink3"><Spinner size={18} /></div>;
+
+ return (
+ <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} />
+ </Card>
+ <SchedulesCard bot={bot} onSaved={load} />
+ <Card title="What it may do">
+ <TierCard id={id} tier={status?.tier} tiers={tiers} />
+ </Card>
+ <Limits bot={bot} onSaved={load} />
+ </div>
+ );
+}
+
+function Card({ title, hint, children }: { title: string; hint?: string; children: React.ReactNode }) {
+ return (
+ <section className="flex flex-col gap-3 rounded-xl border border-line bg-surface p-4">
+ <div>
+ <h3 className="text-sm font-semibold text-ink">{title}</h3>
+ {hint && <p className="text-xs text-ink3">{hint}</p>}
+ </div>
+ {children}
+ </section>
+ );
+}
+
+/** Save button + its result, shared by every section. */
+function useSave() {
+ const [state, setState] = useState<{ busy: boolean; note: string | null; ok: boolean }>({ busy: false, note: null, ok: true });
+ async function run(fn: () => Promise<unknown>, done = "Saved.") {
+ setState({ busy: true, note: null, ok: true });
+ try {
+ await fn();
+ setState({ busy: false, note: done, ok: true });
+ void refreshBots();
+ setTimeout(() => setState((s) => (s.note === done ? { ...s, note: null } : s)), 2500);
+ } catch (e) {
+ setState({ busy: false, note: e instanceof Error ? e.message : String(e), ok: false });
+ }
+ }
+ const footer = (onClick: () => void, disabled = false, label = "Save") => (
+ <div className="flex items-center justify-end gap-3">
+ {state.note && <span className={state.ok ? "text-xs text-ok" : "text-xs text-red"}>{state.note}</span>}
+ <Button size="sm" variant="primary" loading={state.busy} disabled={disabled} onClick={onClick}>{label}</Button>
+ </div>
+ );
+ return { run, footer };
+}
+
+function Basics({ bot, onSaved }: { bot: BotManifest; onSaved: () => Promise<void> }) {
+ const [name, setName] = useState(bot.name);
+ const [description, setDescription] = useState(bot.description ?? "");
+ const { run, footer } = useSave();
+ const changed = name.trim() !== bot.name || description.trim() !== (bot.description ?? "");
+ return (
+ <Card title="Name">
+ <Input value={name} onChange={(e) => setName(e.target.value)} aria-label="Name" />
+ <Input value={description} onChange={(e) => setDescription(e.target.value)} placeholder="What it's for, in one line" aria-label="Description" />
+ {footer(() => void run(async () => { await api.bots.update(bot.id, { name: name.trim(), description: description.trim() }); await onSaved(); }), !changed || !name.trim())}
+ </Card>
+ );
+}
+
+function PersonaEditor({ id, initial }: { id: 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" />
+ {footer(() => void run(() => api.bots.setPersona(id, text)), text.trim() === initial.trim() || !text.trim())}
+ </>
+ );
+}
+
+function SchedulesCard({ bot, onSaved }: { bot: BotManifest; onSaved: () => Promise<void> }) {
+ const [schedules, setSchedules] = useState<BotSchedule[]>(bot.schedules ?? []);
+ const { run, footer } = useSave();
+ const changed = JSON.stringify(schedules) !== JSON.stringify(bot.schedules ?? []);
+ const empty = schedules.some((s) => !s.prompt.trim());
+ return (
+ <Card title="When it runs" hint="Changes apply right away. Between runs of one schedule there are always at least 15 minutes.">
+ <ScheduleEditor value={schedules} onChange={setSchedules} />
+ {footer(() => void run(async () => { await api.bots.update(bot.id, { schedules: schedules.map((s) => ({ ...s, prompt: s.prompt.trim() })) }); await onSaved(); }), !changed || empty)}
+ </Card>
+ );
+}
+
+function TierCard({ id, tier, tiers }: { id: string; tier: BotTierId | "custom" | undefined; tiers?: BotTier[] }) {
+ const [value, setValue] = useState<BotTierId | "custom" | undefined>(tier);
+ useEffect(() => { setValue(tier); }, [tier]);
+ const { run, footer } = useSave();
+ return (
+ <>
+ <TierPicker value={value} onChange={setValue} tiers={tiers} />
+ {footer(() => void run(() => api.bots.setTier(id, value as BotTierId)), value === tier || value === "custom" || value === undefined)}
+ </>
+ );
+}
+
+function Limits({ bot, onSaved }: { bot: BotManifest; onSaved: () => Promise<void> }) {
+ const [model, setModel] = useState(bot.model);
+ const [budget, setBudget] = useState(String(bot.autonomy?.dailyTokenBudget ?? ""));
+ const [steps, setSteps] = useState(String(bot.autonomy?.maxSteps ?? ""));
+ const [learn, setLearn] = useState(bot.memory?.learn !== false);
+ const { run, footer } = useSave();
+ const num = (s: string) => (s.trim() ? Number(s.replace(/[,\s_]/g, "")) : undefined);
+ const bad = [num(budget), num(steps)].some((n) => n !== undefined && (!Number.isFinite(n) || n <= 0));
+ return (
+ <Card title="Model and limits">
+ <label className="flex flex-col gap-1 text-xs text-ink3">Model<ModelPicker value={model} onChange={setModel} /></label>
+ <div className="grid grid-cols-2 gap-3">
+ <label className="flex flex-col gap-1 text-xs text-ink3">Daily token budget<Input value={budget} onChange={(e) => setBudget(e.target.value)} mono placeholder="Fleet default" /></label>
+ <label className="flex flex-col gap-1 text-xs text-ink3">Steps per run<Input value={steps} onChange={(e) => setSteps(e.target.value)} mono placeholder="25" /></label>
+ </div>
+ <div className="flex items-center gap-3">
+ <span className="flex-1 text-sm text-ink2">Learn from its runs (remembers useful facts for next time)</span>
+ <Switch checked={learn} onCheckedChange={setLearn} label="Learn from runs" />
+ </div>
+ {footer(() => void run(async () => {
+ await api.bots.update(bot.id, {
+ // null clears a model choice: back to Mercury's default.
+ model: (model ?? null) as BotManifest["model"],
+ autonomy: { ...(bot.autonomy ?? {}), dailyTokenBudget: num(budget), maxSteps: num(steps) },
+ memory: { ...(bot.memory ?? {}), learn },
+ });
+ await onSaved();
+ }), bad)}
+ </Card>
+ );
+}
diff --git a/apps/desktop/src/views/bots/BotsView.tsx b/apps/desktop/src/views/bots/BotsView.tsx
index 1438db8b..74eef051 100644
--- a/apps/desktop/src/views/bots/BotsView.tsx
+++ b/apps/desktop/src/views/bots/BotsView.tsx
@@ -1,11 +1,11 @@
-import { ChevronDown, Play, RefreshCw, Square, Trash2 } from "lucide-react";
+import { ChevronDown, 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";
import * as api from "~/api/mercury";
import type { BotManifest, BotStatus } from "~/api/types";
import type { AgentState } from "~/app/store";
-import { useBots } from "~/app/store";
+import { useBots, useUi } from "~/app/store";
import { refreshBots } from "~/app/events";
import { Button } from "~/components/ui/Button";
import { Switch } from "~/components/ui/Switch";
@@ -17,6 +17,10 @@ import { ConfirmButton } from "~/components/ui/kit";
import { Deliverables } from "./Deliverables";
import { Activity } from "./Activity";
import { Usage } from "./Usage";
+import { BotInbox, InboxRow } from "./Inbox";
+import { CreateBot } from "./CreateBot";
+import { BotSettings } from "./BotSettings";
+import { describeCron } from "./BotForms";
/**
* Bots, organised the way they work: each fleet is a lead with its crew
@@ -55,13 +59,22 @@ export function BotsView() {
const bots = useBots((s) => s.bots);
const available = useBots((s) => s.available);
const activity = useBots((s) => s.activity);
+ const unread = useBots((s) => s.unread);
+ const focus = useUi((s) => s.botFocus);
+ // "inbox", "new", or a bot id.
const [selected, setSelected] = useState<string | null>(null);
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
const { fleets, solo } = useMemo(() => organise(bots), [bots]);
+ // A notification or another screen asked for something specific.
useEffect(() => {
- if (!selected && bots.length) setSelected(fleets[0]?.lead.id ?? solo[0]?.id ?? null);
- }, [bots, selected, fleets, solo]);
+ if (!focus) return;
+ setSelected(focus);
+ useUi.getState().clearBotFocus();
+ }, [focus]);
+ useEffect(() => {
+ if (!selected) setSelected(bots.length ? "inbox" : "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." />;
@@ -73,10 +86,14 @@ export function BotsView() {
<aside className="flex w-[300px] shrink-0 flex-col border-r border-line bg-soft">
<header className="flex h-[52px] shrink-0 items-center justify-between px-4" data-tauri-drag-region>
<span className="text-base font-medium text-ink">Bots</span>
- <Button variant="ghost" size="sm" icon onClick={() => void refreshBots()} aria-label="Refresh"><RefreshCw size={14} /></Button>
+ <span className="flex items-center gap-1" data-no-drag>
+ <Button variant="ghost" size="sm" icon onClick={() => void refreshBots()} aria-label="Refresh"><RefreshCw size={14} /></Button>
+ <Button variant="secondary" size="sm" onClick={() => setSelected("new")}><Plus size={14} /> New bot</Button>
+ </span>
</header>
<div className="min-h-0 flex-1 overflow-y-auto px-2 pb-4">
- {bots.length === 0 && <p className="px-2 text-sm text-ink4">No bots yet. Create one with `mercury bots create`.</p>}
+ <InboxRow active={selected === "inbox"} unread={unread} onClick={() => setSelected("inbox")} />
+ {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) => {
const working = f.crew.filter((c) => c.state === "running").length + (f.lead.state === "running" ? 1 : 0);
@@ -85,14 +102,15 @@ export function BotsView() {
<div key={f.lead.id} className="mb-3">
<div className={cx("flex items-center rounded-lg", selected === f.lead.id ? "bg-ink/[0.07]" : "hover:bg-ink/[0.05]")}>
<button onClick={() => setSelected(f.lead.id)} className="flex min-w-0 flex-1 items-center gap-3 px-2.5 py-2 text-left">
- <BotAvatar id={f.lead.id} name={f.lead.name} hasAvatar={f.lead.hasAvatar} size={36} dimmed={!f.lead.enabled} />
+ <BotAvatar id={f.lead.id} name={f.lead.name} hasAvatar={f.lead.hasAvatar} size={36} dimmed={!f.lead.enabled || f.lead.stopped} />
<span className="min-w-0 flex-1">
<span className="flex items-center gap-2">
<span className="truncate text-sm font-medium text-ink">{f.lead.name}</span>
{f.lead.needsYou && <span className="block h-1.5 w-1.5 shrink-0 rounded-full bg-amber" aria-label="needs you" />}
</span>
- <span className="block truncate text-xs text-ink3">Fleet · {f.crew.length} crew{working ? ` · ${working} working` : ""}</span>
+ <span className="block truncate text-xs text-ink3">Fleet · {f.crew.length} crew{working ? ` · ${working} working` : ""}{f.lead.stopped ? " · stopped" : ""}</span>
</span>
+ <UnreadBadge n={f.lead.unread} />
</button>
<button onClick={() => setCollapsed((c) => ({ ...c, [f.lead.id]: !isCollapsed }))} className="mr-1.5 rounded p-1 text-ink4 hover:text-ink" aria-label={isCollapsed ? "Show crew" : "Hide crew"} aria-expanded={!isCollapsed}>
<ChevronDown size={15} className={cx("transition-transform", isCollapsed && "-rotate-90")} />
@@ -111,25 +129,46 @@ export function BotsView() {
{solo.length > 0 && (
<>
- <div className="px-2.5 pb-1 pt-2 text-2xs font-medium uppercase tracking-wider text-ink4">On their own</div>
+ <div className="px-2.5 pb-1 pt-2 text-2xs font-medium uppercase tracking-wider text-ink4">{fleets.length ? "On their own" : "Your bots"}</div>
{solo.map((b) => <BotRow key={b.id} bot={b} activity={activity[b.id]} active={selected === b.id} onClick={() => setSelected(b.id)} size={32} />)}
</>
)}
</div>
</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} onDeleted={() => setSelected(null)} /> : <Empty title="Pick a bot" />}
+ <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)} />
+ ) : selected === "inbox" ? (
+ <div className="mx-auto flex max-w-[860px] flex-col gap-5 px-8 py-7">
+ <div>
+ <h1 className="text-xl font-semibold tracking-tight text-ink">Inbox</h1>
+ <p className="mt-0.5 text-sm text-ink3">What your bots did, newest first. Runs with nothing new stay quiet; every run is in a bot's Activity.</p>
+ </div>
+ <BotInbox bots={bots} onOpenBot={setSelected} />
+ </div>
+ ) : selectedFleet ? (
+ <FleetDetail fleet={selectedFleet} activity={activity} onSelect={setSelected} />
+ ) : selected ? (
+ <BotDetail id={selected} status={selectedBot} onDeleted={() => setSelected("inbox")} />
+ ) : (
+ <Empty title="Pick a bot" />
+ )}
</section>
</div>
);
}
+function UnreadBadge({ n }: { n?: number }) {
+ if (!n) return null;
+ return <span className="shrink-0 rounded-full bg-accent px-1.5 text-2xs font-semibold leading-5 text-on-accent" aria-label={`${n} unread`}>{n}</span>;
+}
+
function BotRow({ bot, activity, active, onClick, size }: { bot: BotStatus; activity?: string; active: boolean; onClick: () => void; size: number }) {
return (
<button onClick={onClick} className={cx("flex w-full items-center gap-2.5 rounded-md px-2 py-1.5 text-left", active ? "bg-ink/[0.07]" : "hover:bg-ink/[0.05]")}>
<span className="relative">
- <BotAvatar id={bot.id} name={bot.name} hasAvatar={bot.hasAvatar} size={size} dimmed={!bot.enabled} />
+ <BotAvatar id={bot.id} name={bot.name} hasAvatar={bot.hasAvatar} size={size} dimmed={!bot.enabled || bot.stopped} />
<StateOrb state={orbFor(bot)} size={8} className="absolute -bottom-0.5 -right-0.5 rounded-full bg-soft p-[1.5px]" />
</span>
<span className="min-w-0 flex-1">
@@ -137,6 +176,7 @@ function BotRow({ bot, activity, active, onClick, size }: { bot: BotStatus; acti
<span className={cx("block truncate text-xs", bot.state === "running" ? "text-accent" : "text-ink3")}>{activity ?? describe(bot)}</span>
</span>
{bot.needsYou && <span className="block h-1.5 w-1.5 shrink-0 rounded-full bg-amber" aria-label="needs you" />}
+ <UnreadBadge n={bot.unread} />
</button>
);
}
@@ -151,6 +191,7 @@ function orbFor(b: BotStatus): AgentState {
function describe(b: BotStatus): string {
if (!b.enabled) return "Off";
+ if (b.stopped) return "Stopped";
if (b.state === "running") return "Working";
if (b.state === "queued") return "Queued";
if (b.state === "paused") return "Paused";
@@ -158,14 +199,16 @@ function describe(b: BotStatus): string {
return "Idle";
}
-type Tab = "overview" | "deliverables" | "activity" | "usage";
+type Tab = "overview" | "results" | "deliverables" | "activity" | "usage" | "settings";
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: "results", label: "Results" },
+ { id: "deliverables", label: fleet ? "Fleet files" : "Files" },
{ id: "activity", label: "Activity" },
{ id: "usage", label: "Usage" },
+ { id: "settings", label: "Settings" },
];
return (
<div className="flex gap-1 border-b border-line" role="tablist">
@@ -211,9 +254,11 @@ function FleetDetail({ fleet, activity, onSelect }: { fleet: Fleet; activity: Re
<BotBody id={lead.id} status={lead} />
</>
)}
+ {tab === "results" && <BotInbox bots={members} botId={lead.id} />}
{tab === "deliverables" && <Deliverables bots={members} />}
{tab === "activity" && <Activity bots={members} />}
{tab === "usage" && <Usage bots={members} />}
+ {tab === "settings" && <BotSettings id={lead.id} status={lead} />}
</div>
);
}
@@ -227,9 +272,11 @@ function BotDetail({ id, status, onDeleted }: { id: string; status: BotStatus |
<BotHeader id={id} status={status} onDeleted={onDeleted} />
<TabBar tab={tab} onChange={setTab} fleet={false} />
{tab === "overview" && <BotBody id={id} status={status} />}
+ {tab === "results" && <BotInbox bots={status ? [status] : []} botId={id} />}
{tab === "deliverables" && <Deliverables bots={me} />}
{tab === "activity" && <Activity bots={me} />}
{tab === "usage" && <Usage bots={me} />}
+ {tab === "settings" && <BotSettings id={id} status={status} />}
</div>
);
}
@@ -272,12 +319,17 @@ function BotHeader({ id, status, subtitle, crewCount = 0, onDeleted }: { id: str
<Mono>{bot.id}</Mono>
{bot.model?.model && <Badge>{bot.model.model}</Badge>}
{bot.autonomy?.dailyTokenBudget && <Badge>{bot.autonomy.dailyTokenBudget.toLocaleString()} tokens/day</Badge>}
+ {status?.tier && <TierBadge tier={status.tier} />}
+ {status?.stopped && <Badge tone="amber">stopped</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" ? (
+ {status?.stopped || status?.needsYou ? (
+ // Start lifts a stop, re-runs held work, and turns switched-off routines back on.
+ <Button size="sm" variant="primary" onClick={() => void api.bots.start(id).then(refreshBots)}><Play size={13} /> Start</Button>
+ ) : 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>
@@ -336,8 +388,7 @@ function BotBody({ id, status }: { id: string; status: BotStatus | null }) {
<SectionTitle>Schedules</SectionTitle>
{bot.schedules.map((s) => (
<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="text-ink">{describeCron(s.cron)}</span>
<span className="min-w-0 flex-1 truncate text-sm text-ink3">{s.prompt}</span>
</div>
))}
@@ -357,3 +408,14 @@ function ago(ts: number): string {
if (h < 48) return `${h} h ago`;
return `${Math.round(h / 24)} d ago`;
}
+
+const TIER_LABEL: Record<string, string> = { readonly: "read only", builder: "writes files", operator: "runs commands", full: "full access", custom: "custom permissions" };
+
+function TierBadge({ tier }: { tier: string }) {
+ return (
+ <Badge tone={tier === "full" || tier === "custom" ? "amber" : "neutral"}>
+ {tier === "full" ? <ShieldAlert size={11} className="mr-1 inline" /> : <Shield size={11} className="mr-1 inline" />}
+ {TIER_LABEL[tier] ?? tier}
+ </Badge>
+ );
+}
diff --git a/apps/desktop/src/views/bots/CreateBot.tsx b/apps/desktop/src/views/bots/CreateBot.tsx
new file mode 100644
index 00000000..dfb13c95
--- /dev/null
+++ b/apps/desktop/src/views/bots/CreateBot.tsx
@@ -0,0 +1,203 @@
+import { Bot, Eye, Newspaper, PenLine, Search } from "lucide-react";
+import { useEffect, useState } from "react";
+import * as api from "~/api/mercury";
+import type { BotSchedule, BotTier, BotTierId } from "~/api/types";
+import { refreshBots } from "~/app/events";
+import { Button } from "~/components/ui/Button";
+import { Input } from "~/components/ui/Input";
+import { cx } from "~/lib/cx";
+import { ModelPicker, 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.
+ */
+
+interface Template {
+ id: string;
+ label: string;
+ blurb: string;
+ icon: typeof Bot;
+ description: string;
+ persona: string;
+ tier: BotTierId;
+ schedules: BotSchedule[];
+}
+
+const TEMPLATES: Template[] = [
+ {
+ id: "researcher", label: "Researcher", blurb: "Looks things up and reports what it found.", icon: Search, tier: "readonly",
+ 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",
+ 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",
+ 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",
+ 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",
+ description: "", persona: "", schedules: [],
+ },
+];
+
+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("");
+ const [description, setDescription] = useState("");
+ const [persona, setPersona] = useState("");
+ const [tier, setTier] = useState<BotTierId>("readonly");
+ const [schedules, setSchedules] = useState<BotSchedule[]>([]);
+ const [model, setModel] = useState<{ provider?: string; model?: string } | undefined>(undefined);
+ const [budget, setBudget] = useState("1000000");
+ const [tiers, setTiers] = useState<BotTier[] | undefined>(undefined);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => { void api.bots.tiers().then(setTiers).catch(() => {}); }, []);
+
+ function pick(t: Template) {
+ setTemplate(t);
+ setDescription(t.description);
+ setPersona(t.persona);
+ setTier(t.tier);
+ setSchedules(t.schedules);
+ if (!name && t.id !== "blank") setName(t.label);
+ }
+
+ const id = uniqueId(slugify(name || "bot"), existingIds);
+ const budgetNum = Number(budget.replace(/[,\s_]/g, ""));
+ const problem = !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;
+
+ async function create() {
+ if (problem) { setError(problem); return; }
+ setBusy(true);
+ 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) } },
+ });
+ // 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();
+ onCreated(id);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ 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>
+ </div>
+ <div className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
+ {TEMPLATES.map((t) => (
+ <button key={t.id} onClick={() => pick(t)} className="flex items-start gap-3 rounded-xl border border-line bg-surface p-4 text-left hover:border-line-strong">
+ <t.icon size={18} className="mt-0.5 shrink-0 text-ink2" aria-hidden="true" />
+ <span>
+ <span className="block text-sm font-medium text-ink">{t.label}</span>
+ <span className="block text-xs text-ink3">{t.blurb}</span>
+ </span>
+ </button>
+ ))}
+ </div>
+ <div><Button variant="ghost" size="sm" onClick={onCancel}>Cancel</Button></div>
+ </div>
+ );
+ }
+
+ 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>
+ </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" />
+ </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="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="When it runs">
+ <ScheduleEditor value={schedules} onChange={setSchedules} />
+ </Section>
+
+ <Section title="What it may do">
+ <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>
+ </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>
+ );
+}
+
+function Section({ title, hint, children }: { title: string; hint?: string; children: React.ReactNode }) {
+ return (
+ <section className={cx("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>}
+ </div>
+ {children}
+ </section>
+ );
+}
+
+function uniqueId(base: string, taken: string[]): string {
+ if (!taken.includes(base)) return base;
+ for (let i = 2; ; i++) if (!taken.includes(`${base}-${i}`)) return `${base}-${i}`;
+}
diff --git a/apps/desktop/src/views/bots/Deliverables.tsx b/apps/desktop/src/views/bots/Deliverables.tsx
index b83d90ed..d68ba7c9 100644
--- a/apps/desktop/src/views/bots/Deliverables.tsx
+++ b/apps/desktop/src/views/bots/Deliverables.tsx
@@ -69,7 +69,7 @@ export function Deliverables({ bots }: { bots: Array<{ id: string; name: string;
);
}
-function Preview({ d, onDeleted }: { d: Deliverable; onDeleted: () => void }) {
+export 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);
diff --git a/apps/desktop/src/views/bots/Inbox.tsx b/apps/desktop/src/views/bots/Inbox.tsx
new file mode 100644
index 00000000..90f5fc35
--- /dev/null
+++ b/apps/desktop/src/views/bots/Inbox.tsx
@@ -0,0 +1,151 @@
+import { AlertTriangle, CheckCheck, CircleCheck, FileText, Inbox as InboxIcon, OctagonAlert } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import * as api from "~/api/mercury";
+import type { BotInboxEntry, BotStatus } from "~/api/types";
+import { useBots } from "~/app/store";
+import { refreshBots } from "~/app/events";
+import { BotAvatar } from "~/components/BotAvatar";
+import { Markdown } from "~/components/Markdown";
+import { Button } from "~/components/ui/Button";
+import { Badge, Empty, Spinner } from "~/components/ui/bits";
+import { Dialog } from "~/components/ui/Dialog";
+import { cx } from "~/lib/cx";
+import { Preview } from "./Deliverables";
+
+/**
+ * The inbox: what the bots did for you, newest first, kept until you read it
+ * — results (the bot's own summary, and the files it delivered), failures a
+ * bot reported, and runs that need you. Runs where nothing was new aren't
+ * here; the bot's Activity has every run.
+ */
+export function BotInbox({ bots, botId, onOpenBot }: { bots: BotStatus[]; botId?: string; onOpenBot?: (id: string) => void }) {
+ const version = useBots((s) => s.inboxVersion);
+ const [entries, setEntries] = useState<BotInboxEntry[] | null>(null);
+ const [filter, setFilter] = useState<"all" | "unread">("all");
+ const [file, setFile] = useState<{ botId: string; path: string } | null>(null);
+ const byId = useMemo(() => new Map(bots.map((b) => [b.id, b])), [bots]);
+
+ async function load() {
+ try {
+ const r = await api.bots.inbox({ bot: botId, unread: filter === "unread", limit: 200 });
+ setEntries(r.entries);
+ } catch {
+ setEntries([]);
+ }
+ }
+ useEffect(() => { void load(); }, [botId, filter, version]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ async function markRead(ids?: string[]) {
+ const r = await api.bots.markRead(ids).catch(() => null);
+ setEntries((list) => list?.map((e) => (!ids || ids.includes(e.id) ? { ...e, read: true } : e)) ?? null);
+ if (r) useBots.getState().inboxChanged(r.unread);
+ void refreshBots();
+ }
+
+ if (entries === null) return <div className="flex h-40 items-center justify-center text-ink3"><Spinner size={18} /></div>;
+ const unread = entries.filter((e) => !e.read).length;
+
+ return (
+ <div className="flex flex-col gap-4">
+ <div className="flex items-center gap-2">
+ <div className="flex gap-1 rounded-lg bg-ink/[0.05] p-0.5">
+ {(["all", "unread"] as const).map((f) => (
+ <button key={f} onClick={() => setFilter(f)} className={cx("rounded-md px-2.5 py-1 text-xs", filter === f ? "bg-surface text-ink shadow-sm" : "text-ink3 hover:text-ink")}>
+ {f === "all" ? "All" : "Unread"}
+ </button>
+ ))}
+ </div>
+ <span className="flex-1" />
+ {unread > 0 && <Button size="sm" variant="ghost" onClick={() => void markRead(entries.filter((e) => !e.read).map((e) => e.id))}><CheckCheck size={13} /> Mark all read</Button>}
+ </div>
+
+ {entries.length === 0 && (
+ <Empty
+ title={filter === "unread" ? "Nothing unread" : "Nothing here yet"}
+ body={botId ? "When this bot finishes something, reports a problem, or needs you, it lands here." : "When a bot finishes something, reports a problem, or needs you, it lands here — even if the app was closed. Runs with nothing new stay quiet."}
+ />
+ )}
+
+ {groupByDay(entries).map(([day, list]) => (
+ <div key={day} className="flex flex-col gap-2">
+ <div className="text-2xs font-medium uppercase tracking-wider text-ink4">{day}</div>
+ {list.map((e) => {
+ const bot = byId.get(e.botId);
+ return (
+ <article key={e.id} onClick={() => { if (!e.read) void markRead([e.id]); }}
+ className={cx("flex gap-3 rounded-xl border bg-surface p-4", e.read ? "border-line" : "border-accent/40")}>
+ <BotAvatar id={e.botId} name={e.botName} hasAvatar={bot?.hasAvatar} size={32} />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-start gap-2">
+ <KindIcon kind={e.kind} />
+ <h3 className="min-w-0 flex-1 text-sm font-medium leading-snug text-ink">{e.title}</h3>
+ {!e.read && <span className="mt-1.5 block h-1.5 w-1.5 shrink-0 rounded-full bg-accent" aria-label="unread" />}
+ <time className="shrink-0 text-xs text-ink4">{time(e.at)}</time>
+ </div>
+ <div className="mt-1.5 max-h-[220px] overflow-y-auto text-sm text-ink2">
+ <Markdown text={e.summary} />
+ </div>
+ {(e.files.length > 0 || e.complete || e.kind === "needs-you") && (
+ <div className="mt-2.5 flex flex-wrap items-center gap-2">
+ {e.files.map((f) => (
+ <button key={f} onClick={() => setFile({ botId: e.botId, path: f })} className="flex max-w-[280px] 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">
+ <FileText size={12} className="shrink-0" /> <span className="truncate">{basename(f)}</span>
+ </button>
+ ))}
+ {e.complete && <Badge tone="accent">job done</Badge>}
+ {e.kind === "needs-you" && e.reasonCode && <Badge tone="amber">{e.reasonCode.replace(/_/g, " ")}</Badge>}
+ </div>
+ )}
+ {!botId && onOpenBot && (
+ <button onClick={() => onOpenBot(e.botId)} className="mt-2 text-xs text-ink3 hover:text-ink">Open {e.botName} →</button>
+ )}
+ </div>
+ </article>
+ );
+ })}
+ </div>
+ ))}
+
+ <Dialog open={!!file} onOpenChange={(o) => { if (!o) setFile(null); }} title={file ? basename(file.path) : ""} width={820}>
+ {file && <Preview d={{ botId: file.botId, name: basename(file.path), bytes: 0, mtimeMs: Date.now() }} onDeleted={() => setFile(null)} />}
+ </Dialog>
+ </div>
+ );
+}
+
+function KindIcon({ kind }: { kind: BotInboxEntry["kind"] }) {
+ if (kind === "result") return <CircleCheck size={15} className="mt-0.5 shrink-0 text-ok" aria-label="result" />;
+ if (kind === "failed") return <OctagonAlert size={15} className="mt-0.5 shrink-0 text-red" aria-label="couldn't do it" />;
+ return <AlertTriangle size={15} className="mt-0.5 shrink-0 text-amber" aria-label="needs you" />;
+}
+
+/** The inbox entry in the sidebar: an icon, "Inbox", and the unread count. */
+export function InboxRow({ active, unread, onClick }: { active: boolean; unread: number; onClick: () => void }) {
+ return (
+ <button onClick={onClick} className={cx("mb-2 flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-left", active ? "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]"><InboxIcon size={15} className="text-ink2" /></span>
+ <span className="flex-1 text-sm font-medium text-ink">Inbox</span>
+ {unread > 0 && <span className="rounded-full bg-accent px-1.5 text-2xs font-semibold leading-5 text-on-accent">{unread}</span>}
+ </button>
+ );
+}
+
+function groupByDay(entries: BotInboxEntry[]): Array<[string, BotInboxEntry[]]> {
+ const out = new Map<string, BotInboxEntry[]>();
+ const today = new Date().toDateString();
+ const yesterday = new Date(Date.now() - 86_400_000).toDateString();
+ for (const e of entries) {
+ const d = new Date(e.at).toDateString();
+ const label = d === today ? "Today" : d === yesterday ? "Yesterday" : new Date(e.at).toLocaleDateString([], { weekday: "long", month: "short", day: "numeric" });
+ out.set(label, [...(out.get(label) ?? []), e]);
+ }
+ return [...out];
+}
+
+function time(at: number): string {
+ return new Date(at).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
+}
+
+function basename(p: string): string {
+ return p.split(/[\\/]/).pop() ?? p;
+}
diff --git a/src/web/api/bots.ts b/src/web/api/bots.ts
index 657b6fac..0dadd5c6 100644
--- a/src/web/api/bots.ts
+++ b/src/web/api/bots.ts
@@ -259,7 +259,8 @@ app.patch('/api/bots/:id', async (c: any) => {
}
if (patch.enabled !== undefined) m.enabled = patch.enabled;
if (patch.description !== undefined) m.description = patch.description;
- if (patch.model !== undefined) m.model = patch.model;
+ // null clears the choice: back to Mercury's default model.
+ if (patch.model !== undefined) { if (patch.model) m.model = patch.model; else delete m.model; }
if (patch.tools !== undefined) m.tools = patch.tools;
if (patch.memory !== undefined) m.memory = patch.memory;
if (patch.comms !== undefined) m.comms = patch.comms;