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: live bot activity, Needs-you carousel, plans that keep up, chat works like Mercury Code

Salman Qureshi134a61cd7ea0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ae585564..18ccdcbd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,62 @@
## Unreleased
+### Chat: complex work done the way Mercury Code does it
+A real chat ("install the HyperFrames skills, then make an intro video with an ElevenLabs beat") went wrong in a chain:
+- the HyperFrames CLI refused to run ("requires Node.js >= 22");
+- Mercury tried to upgrade Node with brew, then switched to an AI video model, which hit its quota;
+- it made a black MP4 with ffmpeg and announced "Video created & sent!";
+- it wrote six summary documents nobody asked for.
+
+Each link is fixed:
+- **Commands use Mercury's own Node.** A service PATH often lists an old system Node (`/usr/local/bin`) before a newer one, so every Node tool the model ran used Node 18 even though Mercury runs on 22. The Node that runs Mercury now comes first in a command's PATH, so `npx`, `hyperframes` and other Node CLIs get the right version.
+- **A video that never rendered isn't sent as if it worked.** Before `send_file` sends a video, ffmpeg's own detectors look at it once. If it's black for most of its length, or the same frame the whole time (the animation never ran), it isn't sent, and the model is told why, so it fixes the render or says plainly that it couldn't. Without ffmpeg, files are sent as before.
+- **Mercury Code's discipline, in chat, when the work is real.** It applies when the model makes a plan of three or more steps, which is its own sign that this is multi-step work. Quick questions and ordinary chats don't change.
+ - **Working rules with the plan:**
+ - act, don't announce;
+ - a step is done when its result exists and was checked;
+ - when a tool or requirement fails, fix the cause or ask: never switch to a method you didn't ask for, or present a workaround as the result;
+ - no summaries nobody asked for.
+ - **One check before "done":** if the turn made something (files, renders, sent files), the model gets one round to look at what it produced and fix it, then reports only what it verified. It's the chat version of Mercury Code's verification gate.
+- **Always:** never call something done without checking it, and no unrequested summary or README files.
+
+### Plans that keep up
+- **A plan no longer freezes mid-way.** The checklist moved only when the model ticked a step, and models often finish the work and forget the last tick. Stopping a task also left its step "in progress" for good. In one owner's chats, 7 of 21 plans were stuck like that (✓✓✓✓◐). Now, when a turn ends:
+ - **finished, only the last step unticked:** it's marked done, since the reply is that step;
+ - **a reply with several steps still open:** "Plan paused" at the first open step, with "say continue to pick it up";
+ - **stopped by you, or failed:** "Plan stopped", with no guessed ticks.
+
+ Only the turn that worked on a plan settles it, so a quick question asked in between leaves it alone. The plan tool also reminds the model to tick its finished steps before its final reply. The terminal's checklist gets the same end-of-turn tidy.
+- **An open plan in an idle chat never looks in progress.** No pulsing step while nothing runs, plans saved before this release included.
+
+### Desktop: "Needs you", one at a time
+- **Approvals look like the rest of the app.** A question Mercury is waiting on (allow a command, write a file, use an MCP tool, keep going, pick one) used to be an amber box in the conversation, with the raw request dumped in monospace and one box stacked under another. It's now a card pinned above the message box, in the same style as the plan:
+ - a plain title ("Run a command", "Write a file", "Use create_issue", "Suspicious request: schedule a task");
+ - the exact command or path underneath, folded when long;
+ - what it read and any warning in a quiet line;
+ - the main answer as the primary button, and Deny quietly on the right.
+- **Several questions are a carousel:** "1 of 4", ‹ › or ←/→ to move between them. Answering one shows the next, and the card leaves when none are left. Y / N and 1–9 still answer from the keyboard.
+- **Bots ask the same way:** their questions use the same card on every bot screen, and in Live it sits above the message box, with how long the bot will wait.
+
+### Bots: watch them live, talk to them, fewer false alarms
+- **Live, the first tab of every bot and fleet.** What the bots are doing as it happens, one card per run:
+ - who started it (you, a schedule, another bot) and what was asked;
+ - each step as it runs: tool, running → done or failed, with the error;
+ - what the bot is writing as it writes it;
+ - how it ended.
+
+ A run's status comes from its latest event, so it can't go stale: "Waiting for you" appears only while a question for that very run is pending, and a run cut short by a restart says it ended instead of "working" forever. Long runs fold their earlier steps, and a fleet shows every member's runs together. Opening the screen mid-run shows what already happened: the runtime keeps a short, capped log of recent events, in memory only. The old Activity tab is now History.
+- **Talk to them from the same place.** The box under the feed messages the bot, or any crew member in a fleet. A message to a busy bot shows as queued and runs after the current one. A bot's question sits inside its run with its buttons, and every finished run has Reply, which answers with that run quoted.
+- **Far fewer "needs you" questions that weren't needed.** A bot's shell command used to be scanned for anything that looked like a path, and each one was asked about as a file to write. Now the scan reads the command the way the shell does:
+ - code inside a heredoc no longer counts (it used to ask to write to "/", "/*" and "/\s+");
+ - quoted paths with spaces stay whole;
+ - `/dev/null` is not a file;
+ - `ls`, `find`, `cat` and `grep` read, they don't write;
+ - `-o` only means an output file to `curl`, `wget` and `sort` (to `find` it means "or").
+
+ A read-only command (with pipes and `2>/dev/null`) that touches only folders the bot may read now runs without asking. Writes, the network and anything that can run other commands still ask.
+- **Bot faces always have colour.** A face shown in two places shared one colour gradient. If the first copy sat in a hidden tab, macOS drew the others black, or as bare white eyes. Each face now has its own gradient, written in notation every engine reads, with a solid colour under it.
+
### Voice: only the words are spoken
- **Directions stay out of the audio.** Asking for a natural reading ("keep it natural, don't make it sound like it was shared by AI") could put that request into the recording itself. The cause was Gemini, which takes the style as words in front of the text ("Say this …:") and reads anything that isn't a short description of a voice out loud.
- Only a short tone goes to Gemini now ("calm and warm", "like a news anchor"). Requests about the audio itself are dropped, since they shape how the words are written, not how they're read.
diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.ts
index d8124070..4542dd1d 100644
--- a/apps/desktop/src/api/mercury.ts
+++ b/apps/desktop/src/api/mercury.ts
@@ -7,7 +7,7 @@ import { http, ApiError } from "./client";
import type { ChatEffort, ImageIntent, MediaModelsResponse, TurnsInfo, VoiceReplies } from "./types";
import type { CommandEntry } from "~/views/chat/picker";
import type { SkillDraft,
- BotApproval, BotInboxEntry, BotManifest, BotPlan, CrewSpec, BotRunRecord, BotStatus, BotTier, BotTierId, ChatMessage, ChatSettings, ChatThread, CodeStatus, HealthInfo,
+ BotActivityEvent, BotApproval, BotInboxEntry, BotManifest, BotPlan, CrewSpec, BotRunRecord, BotStatus, BotTier, BotTierId, ChatMessage, ChatSettings, ChatThread, CodeStatus, HealthInfo,
McpServer, ModelsResponse, CodeMode, CostReport, Deliverable, RunTranscript, PairResponse, PendingPair, OwnerApproval, PluginItem, ReasoningChoice, Skill, DeviceSummary,
} from "./types";
@@ -140,6 +140,8 @@ export const bots = {
disable: (id: string) => http.post<{ ok: boolean }>(`/api/bots/${encodeURIComponent(id)}/disable`),
stop: (id: string) => http.post<{ ok: boolean }>(`/api/bots/${encodeURIComponent(id)}/stop`),
remove: (id: string) => http.delete<{ ok: boolean }>(`/api/bots/${encodeURIComponent(id)}`),
+ /** The live feed's recent past, oldest first (the bots stream sends what happens next). */
+ activity: (bots: string[], limit = 400) => http.get<{ events: BotActivityEvent[]; now: number }>(`/api/bots/activity?bots=${encodeURIComponent(bots.join(","))}&limit=${limit}`),
journal: (id: string, limit = 60) => http.get<{ journal: BotRunRecord[] }>(`/api/bots/${encodeURIComponent(id)}/journal?limit=${limit}`),
run: (id: string, runId: string) => http.get<RunTranscript>(`/api/bots/${encodeURIComponent(id)}/runs/${encodeURIComponent(runId)}`),
outputs: (id: string) => http.get<{ outputs: Deliverable[] }>(`/api/bots/${encodeURIComponent(id)}/outputs`),
diff --git a/apps/desktop/src/api/types.ts b/apps/desktop/src/api/types.ts
index 79f2f1ae..99ed9b6b 100644
--- a/apps/desktop/src/api/types.ts
+++ b/apps/desktop/src/api/types.ts
@@ -439,10 +439,25 @@ export interface CostReport {
fleetPaused: boolean;
}
+/** What a bot is doing right now (SSE bot_activity; GET /api/bots/activity for the recent past). */
export interface BotActivityEvent {
botId: string;
- kind: "turn-start" | "step" | "tool" | "turn-end" | "thinking";
+ /** The run (job); "" for events outside a run (a delivery). */
+ jobId?: string;
+ kind: "turn-start" | "step" | "tool" | "turn-end" | "thinking" | "queued";
label: string;
+ detail?: string;
+ stepIndex?: number;
+ elapsedMs?: number;
+ status?: "running" | "done" | "error";
+ reasoningTail?: string;
+ textTail?: string;
+ at?: number;
+ botName?: string;
+ /** What started the run: api (you), cron (a schedule), mailbox (another bot), … */
+ trigger?: string;
+ prompt?: string;
+ fromBot?: string;
}
// ── Plugins / MCP / Skills ──
diff --git a/apps/desktop/src/app/conversation.ts b/apps/desktop/src/app/conversation.ts
index 95adc5b6..2cac7a87 100644
--- a/apps/desktop/src/app/conversation.ts
+++ b/apps/desktop/src/app/conversation.ts
@@ -43,7 +43,8 @@ export interface ConversationState {
draft: string | null;
setDraft(draft: string | null): void;
/** The conversation's plan checklist (update_plan), if Mercury made one. */
- plan: { steps: Array<{ label: string; status: "pending" | "active" | "done" }>; updatedAt: number } | null;
+ /** The plan checklist; `state` once the turn that worked on it ended without finishing it. */
+ plan: { steps: Array<{ label: string; status: "pending" | "active" | "done" }>; updatedAt: number; state?: "paused" | "stopped" } | null;
setPlan(plan: ConversationState["plan"]): void;
/**
* Research in this conversation: switched on for the next message
diff --git a/apps/desktop/src/app/events.ts b/apps/desktop/src/app/events.ts
index 78150243..4644fb83 100644
--- a/apps/desktop/src/app/events.ts
+++ b/apps/desktop/src/app/events.ts
@@ -49,7 +49,10 @@ export function useRuntimeEvents(enabled: boolean): void {
}
if (event !== "bot_activity") return;
const ev = safeJson<BotActivityEvent>(raw);
- if (!ev || ev.kind === "thinking") return;
+ if (!ev) return;
+ // Everything goes to the live feed; the roster label follows steps only.
+ useBots.getState().addLive([{ ...ev, at: ev.at ?? Date.now() }]);
+ if (ev.kind === "thinking" || ev.kind === "queued") return;
useBots.getState().setActivity(ev.botId, ev.kind === "turn-end" ? null : ev.label);
if (ev.kind === "turn-end" || ev.kind === "turn-start") void refreshBots();
},
@@ -220,7 +223,8 @@ export function handleEvent(store: ConversationStore, event: string, raw: string
break;
case "plan": {
const steps = Array.isArray(data.steps) ? (data.steps as Array<{ label: string; status: "pending" | "active" | "done" }>) : [];
- if (steps.length) conv.setPlan({ steps, updatedAt: Number(data.updatedAt) || Date.now() });
+ const state = data.state === "paused" || data.state === "stopped" ? data.state : undefined;
+ if (steps.length) conv.setPlan({ steps, updatedAt: Number(data.updatedAt) || Date.now(), ...(state ? { state } : {}) });
break;
}
case "artifacts": {
@@ -508,7 +512,7 @@ export async function openThread(surface: Surface, id: string | null): Promise<v
})
.catch(() => { /* older Mercury */ });
// The plan Mercury was working through in this conversation, if any.
- void http.get<{ plan: { steps: Array<{ label: string; status: "pending" | "active" | "done" }>; updatedAt: number } | null }>(`/api/chat/plan?sessionId=${encodeURIComponent(id)}`)
+ void http.get<{ plan: { steps: Array<{ label: string; status: "pending" | "active" | "done" }>; updatedAt: number; state?: "paused" | "stopped" } | null }>(`/api/chat/plan?sessionId=${encodeURIComponent(id)}`)
.then((r) => { if (store.getState().activeId === id && r.plan?.steps?.length) store.getState().setPlan(r.plan); })
.catch(() => { /* older Mercury: no plans */ });
try {
diff --git a/apps/desktop/src/app/store.ts b/apps/desktop/src/app/store.ts
index e42bc799..b2a3c899 100644
--- a/apps/desktop/src/app/store.ts
+++ b/apps/desktop/src/app/store.ts
@@ -5,7 +5,7 @@
═══════════════════════════════════════════════════════════════ */
import { create } from "zustand";
-import type { BotStatus, ChatThread, PendingPrompt, BotApproval } from "~/api/types";
+import type { BotActivityEvent, BotStatus, ChatThread, PendingPrompt, BotApproval } from "~/api/types";
export type View = "chat" | "artifacts" | "code" | "bots" | "brain" | "plugins" | "skills" | "settings";
@@ -115,6 +115,33 @@ interface BotsState {
setBots(bots: BotStatus[], available: boolean, unread?: number): void;
inboxChanged(unread?: number): void;
setActivity(botId: string, label: string | null): void;
+ /** The live feed: recent bot events, oldest first, capped (LIVE_CAP). */
+ live: BotActivityEvent[];
+ /** Add events (from the stream or the history endpoint); duplicates are dropped. */
+ addLive(events: BotActivityEvent[]): void;
+}
+
+/** How many live events the app keeps (the whole fleet). */
+export const LIVE_CAP = 2000;
+
+/** One key per distinct event: the same event from history and the stream counts once. */
+export function liveKey(e: BotActivityEvent): string {
+ return `${e.jobId ?? ""}|${e.kind}|${e.stepIndex ?? 0}|${e.label}|${e.status ?? ""}|${e.at ?? 0}`;
+}
+
+/** Merge events into the feed: dedupe, keep only the latest thinking preview per run, sort by time, cap. */
+export function mergeLive(current: BotActivityEvent[], incoming: BotActivityEvent[]): BotActivityEvent[] {
+ const seen = new Set(current.map(liveKey));
+ let next = current.slice();
+ for (const e of incoming) {
+ const k = liveKey(e);
+ if (seen.has(k)) continue;
+ seen.add(k);
+ if (e.kind === "thinking") next = next.filter((x) => !(x.kind === "thinking" && x.jobId === e.jobId && (x.at ?? 0) <= (e.at ?? 0)));
+ next.push(e);
+ }
+ next.sort((a, b) => (a.at ?? 0) - (b.at ?? 0));
+ return next.length > LIVE_CAP ? next.slice(next.length - LIVE_CAP) : next;
}
export const useBots = create<BotsState>((set) => ({
@@ -127,6 +154,8 @@ export const useBots = create<BotsState>((set) => ({
setApprovals: (approvals) => set({ approvals }),
setBots: (bots, available, unread) => set(unread === undefined ? { bots, available } : { bots, available, unread }),
inboxChanged: (unread) => set((s) => ({ inboxVersion: s.inboxVersion + 1, ...(unread === undefined ? {} : { unread }) })),
+ live: [],
+ addLive: (events) => set((s) => ({ live: mergeLive(s.live, events) })),
setActivity: (botId, label) => set((s) => {
const activity = { ...s.activity };
if (label === null) delete activity[botId];
diff --git a/apps/desktop/src/components/BotAvatar.tsx b/apps/desktop/src/components/BotAvatar.tsx
index bc0b0ce8..0b780917 100644
--- a/apps/desktop/src/components/BotAvatar.tsx
+++ b/apps/desktop/src/components/BotAvatar.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useEffect, useId, useState } from "react";
import { apiUrl, authHeaders } from "~/api/client";
import * as api from "~/api/mercury";
import { cx } from "~/lib/cx";
@@ -70,18 +70,21 @@ function GeneratedFace({ id, name, size, dimmed, className }: { id: string; name
const tri = shape === SHAPES[2];
const eyeY = tri ? 36 : 44;
const mouthY = tri ? 52 : 60;
- const gid = `g-${id}`;
+ // Each face its own gradient id: a shared one ("g-<bot>") broke when the first
+ // copy sat in a hidden tab — WebKit then filled every other copy black.
+ const gid = `bot-face-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
return (
<svg viewBox="0 0 100 100" width={size} height={size} role="img" aria-label={name} className={cx("shrink-0", dimmed && "opacity-90", className)}>
<defs>
<linearGradient id={gid} x1="0" y1="0" x2="1" y2="1">
- <stop offset="0" stopColor={`hsl(${hue} 70% 62%)`} />
- <stop offset="1" stopColor={`hsl(${hue2} 72% 44%)`} />
+ {/* Comma syntax: understood by every engine (a colour it can't parse is black). */}
+ <stop offset="0" stopColor={`hsl(${hue}, 70%, 62%)`} />
+ <stop offset="1" stopColor={`hsl(${hue2}, 72%, 44%)`} />
</linearGradient>
</defs>
{/* The same path stroked wide with round joins softens every corner;
drawn at 88% so the rounded edge stays inside the frame. */}
- <path d={shape} fill={`url(#${gid})`} stroke={`url(#${gid})`} strokeWidth={10} strokeLinejoin="round" transform="translate(6 6) scale(0.88)" />
+ <path d={shape} fill={`url(#${gid}) hsl(${hue}, 70%, 55%)`} stroke={`url(#${gid}) hsl(${hue}, 70%, 55%)`} strokeWidth={10} strokeLinejoin="round" transform="translate(6 6) scale(0.88)" />
<circle cx={50 - eyeGap} cy={eyeY} r="5.2" fill="#fff" />
<circle cx={50 + eyeGap} cy={eyeY} r="5.2" fill="#fff" />
{mouth === 0 && <path d={`M${40} ${mouthY} q10 9 20 0`} stroke="#fff" strokeWidth="4.5" strokeLinecap="round" fill="none" />}
diff --git a/apps/desktop/src/components/needs-you/NeedsYou.tsx b/apps/desktop/src/components/needs-you/NeedsYou.tsx
new file mode 100644
index 00000000..449a052d
--- /dev/null
+++ b/apps/desktop/src/components/needs-you/NeedsYou.tsx
@@ -0,0 +1,186 @@
+import { AlertTriangle, ChevronLeft, ChevronRight } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { Button } from "~/components/ui/Button";
+import { Kbd, Spinner } from "~/components/ui/bits";
+import { splitLabel } from "~/components/indicators/Approval";
+import { cx } from "~/lib/cx";
+import type { Described } from "./describe";
+
+/* ═══════════════════════════════════════════════════════════════
+ "Needs you": everything waiting on your answer, one at a time, in
+ the same card as the plan (pinned above the composer). "1 of 4" with
+ ‹ › and ←/→ to move through them; answering one moves to the next, and
+ the card goes away when none are left. Y / N answer allow / deny,
+ 1–9 pick from a list. Plain words on top, the exact command or path
+ underneath, folded when long.
+ ═══════════════════════════════════════════════════════════════ */
+
+export interface NeedsYouOption {
+ value: string;
+ label: string;
+ /** primary: the main answer; secondary: another yes; quiet: no / deny (on the right). */
+ role: "primary" | "secondary" | "quiet";
+}
+
+export interface NeedsYouItem {
+ id: string;
+ described: Described;
+ options: NeedsYouOption[];
+ /** A pick from a list (rows, 1–9) rather than buttons. */
+ list?: boolean;
+ /** Who asks, when it isn't Mercury itself ("Researcher · waits 8 min"). */
+ from?: string;
+ onAnswer(value: string | null): Promise<void> | void;
+ /** A pick can be cancelled. */
+ cancelable?: boolean;
+}
+
+const CODE_FOLD = 6;
+
+export function NeedsYou({ items, keys = true, className }: { items: NeedsYouItem[]; keys?: boolean; className?: string }) {
+ const [index, setIndex] = useState(0);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [open, setOpen] = useState(false);
+ const lastIds = useRef<string[]>([]);
+
+ // Keep showing the same question when others arrive or leave; a new list starts at the first.
+ useEffect(() => {
+ const ids = items.map((i) => i.id);
+ const current = lastIds.current[index];
+ const at = current ? ids.indexOf(current) : -1;
+ setIndex(at >= 0 ? at : Math.min(index, Math.max(0, ids.length - 1)));
+ lastIds.current = ids;
+ }, [items.map((i) => i.id).join("|")]); // eslint-disable-line react-hooks/exhaustive-deps
+ useEffect(() => { setOpen(false); }, [index]);
+
+ const item = items[Math.min(index, items.length - 1)];
+ const busyRef = useRef(busy);
+ busyRef.current = busy;
+
+ async function answer(value: string | null) {
+ if (!item || busyRef.current !== null) return;
+ setBusy(value ?? "__cancel");
+ try { await item.onAnswer(value); } finally { setBusy(null); }
+ }
+ const answerRef = useRef(answer);
+ answerRef.current = answer;
+ const count = items.length;
+ const go = (d: number) => setIndex((i) => (count ? (i + d + count) % count : 0));
+
+ useEffect(() => {
+ if (!keys || !item) return;
+ const onKey = (e: KeyboardEvent) => {
+ const t = e.target as HTMLElement | null;
+ if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.tagName === "SELECT" || t.isContentEditable)) return;
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
+ const k = e.key.toLowerCase();
+ if (k === "arrowright" && count > 1) { e.preventDefault(); go(1); return; }
+ if (k === "arrowleft" && count > 1) { e.preventDefault(); go(-1); return; }
+ if (item.list && /^[1-9]$/.test(k)) {
+ const o = item.options[Number(k) - 1];
+ if (o) { e.preventDefault(); void answerRef.current(o.value); }
+ return;
+ }
+ const yes = item.options.find((o) => o.role === "primary");
+ const no = item.options.find((o) => o.role === "quiet");
+ if (!item.list && k === "y" && yes) { e.preventDefault(); void answerRef.current(yes.value); }
+ if (!item.list && k === "n" && no) { e.preventDefault(); void answerRef.current(no.value); }
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [keys, item, count]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ if (!item) return null;
+ const d = item.described;
+ const codeLines = d.code ? d.code.split("\n") : [];
+ const folded = !open && codeLines.length > CODE_FOLD;
+ const yes = item.options.filter((o) => o.role !== "quiet");
+ const no = item.options.filter((o) => o.role === "quiet");
+
+ return (
+ <section className={cx("overflow-hidden rounded-2xl border border-line bg-surface shadow-[0_1px_2px_rgb(0_0_0/0.04)]", className)} aria-label="Needs you" role="group">
+ <div className="flex items-center gap-3 px-4 py-2.5">
+ <span className="relative flex h-4 w-4 shrink-0 items-center justify-center" aria-hidden="true">
+ <span className="absolute h-2 w-2 animate-ping rounded-full bg-amber/50" />
+ <span className="h-2 w-2 rounded-full bg-amber" />
+ </span>
+ <span className="shrink-0 text-sm font-medium text-ink">Needs you</span>
+ {count > 1 && <span className="shrink-0 font-mono text-xs tabular-nums text-ink3">{index + 1} of {count}</span>}
+ {item.from && <span className="min-w-0 truncate text-xs text-ink3">· {item.from}</span>}
+ <span className="flex-1" />
+ {count > 1 && (
+ <span className="flex shrink-0 items-center gap-1">
+ <span className="mr-1 hidden gap-1 sm:flex" aria-hidden="true">
+ {items.slice(0, 8).map((x, i) => <span key={x.id} className={cx("h-1.5 rounded-full transition-all", i === index ? "w-4 bg-ink/60" : "w-1.5 bg-ink/15")} />)}
+ </span>
+ <button onClick={() => go(-1)} className="rounded-md p-1 text-ink3 hover:bg-ink/[0.06] hover:text-ink" aria-label="Previous"><ChevronLeft size={15} /></button>
+ <button onClick={() => go(1)} className="rounded-md p-1 text-ink3 hover:bg-ink/[0.06] hover:text-ink" aria-label="Next"><ChevronRight size={15} /></button>
+ </span>
+ )}
+ </div>
+
+ <div key={item.id} className="animate-fade-in border-t border-line px-4 py-3">
+ <div className="text-sm font-medium text-ink">{d.title}</div>
+ {d.warning && (
+ <p className="mt-1 flex items-start gap-1.5 text-xs text-amber"><AlertTriangle size={12} className="mt-0.5 shrink-0" aria-hidden="true" />{d.warning}</p>
+ )}
+ {d.code && (
+ <div className="mt-2">
+ <pre className="max-w-full overflow-x-auto whitespace-pre-wrap break-words rounded-lg border border-line bg-ink/[0.03] px-3 py-2 font-mono text-[12.5px] leading-relaxed text-ink [overflow-wrap:anywhere]" data-selectable>
+ {folded ? codeLines.slice(0, CODE_FOLD).join("\n") : d.code}
+ </pre>
+ {codeLines.length > CODE_FOLD && (
+ <button onClick={() => setOpen(!open)} className="mt-1 text-2xs text-ink3 hover:text-ink">{open ? "Show less" : `Show all ${codeLines.length} lines`}</button>
+ )}
+ </div>
+ )}
+ {d.body && <p className="mt-1 whitespace-pre-wrap break-words text-sm leading-relaxed text-ink2 [overflow-wrap:anywhere]" data-selectable>{d.body}</p>}
+ {d.note && <p className="mt-1.5 text-xs text-ink3">{d.note}</p>}
+
+ {item.list ? (
+ <div className="mt-3 flex flex-col gap-1.5" role="listbox" aria-label={d.title}>
+ {item.options.map((o, i) => {
+ const { name, detail } = splitLabel(o.label);
+ return (
+ <button key={o.value} role="option" aria-selected={false} disabled={busy !== null} onClick={() => void answer(o.value)}
+ className="flex w-full min-w-0 items-start gap-3 rounded-lg border border-line bg-surface px-3 py-2 text-left transition-colors hover:border-ink/25 hover:bg-ink/[0.03] disabled:opacity-60">
+ <span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border border-line bg-soft font-mono text-2xs text-ink3">
+ {busy === o.value ? <Spinner size={10} /> : i < 9 ? i + 1 : "·"}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block break-words text-sm font-medium text-ink [overflow-wrap:anywhere]">{name}</span>
+ {detail && <span className="mt-0.5 line-clamp-2 block text-xs leading-relaxed text-ink3">{detail}</span>}
+ </span>
+ </button>
+ );
+ })}
+ {item.cancelable && (
+ <div><Button size="sm" variant="ghost" loading={busy === "__cancel"} disabled={busy !== null} onClick={() => void answer(null)}>Cancel</Button></div>
+ )}
+ </div>
+ ) : (
+ <div className="mt-3 flex flex-wrap items-center gap-1.5">
+ {yes.map((o) => (
+ <Button key={o.value} size="sm" variant={o.role === "primary" ? "primary" : "outline"} loading={busy === o.value} disabled={busy !== null} onClick={() => void answer(o.value)}>{o.label}</Button>
+ ))}
+ <span className="flex-1" />
+ {keys && yes[0] && no[0] && (
+ <span className="mr-1 hidden items-center gap-1 text-2xs text-ink4 md:inline-flex"><Kbd>Y</Kbd> / <Kbd>N</Kbd></span>
+ )}
+ {no.map((o) => (
+ <Button key={o.value} size="sm" variant="ghost" loading={busy === o.value} disabled={busy !== null} onClick={() => void answer(o.value)}>{o.label}</Button>
+ ))}
+ </div>
+ )}
+ </div>
+ </section>
+ );
+}
+
+/** Roles for a runtime prompt's answers: the first is the main one, a deny-like one is quiet, the rest secondary. */
+export function rolesFor(options: Array<{ value: string; label: string }>): NeedsYouOption[] {
+ const denyIdx = options.length >= 2
+ ? Math.max(options.findIndex((o) => /^(deny|no|don'?t|stop|reject|decline|never|cancel)\b/i.test(o.label)), -1)
+ : -1;
+ return options.map((o, i) => ({ ...o, role: i === denyIdx ? "quiet" : i === 0 ? "primary" : "secondary" }));
+}
diff --git a/apps/desktop/src/components/needs-you/describe.test.ts b/apps/desktop/src/components/needs-you/describe.test.ts
new file mode 100644
index 00000000..58a93835
--- /dev/null
+++ b/apps/desktop/src/components/needs-you/describe.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vitest";
+import { describePrompt } from "./describe";
+
+const perm = (text: string) => describePrompt({ kind: "permission", text });
+
+describe("a question, in words", () => {
+ it("commands, files, folders, MCP and pages", () => {
+ expect(perm("Run command: npm install @scope/pkg")).toEqual({ title: "Run a command", code: "npm install @scope/pkg" });
+ expect(perm("Run command (changes Mercury's MCP servers or config, so it always asks): mercury mcp add x")).toMatchObject({ title: "Run a command", code: "mercury mcp add x", note: "Changes Mercury's MCP servers or config, so it always asks" });
+ expect(perm("Write to file: /Users/me/a.txt")).toEqual({ title: "Write a file", code: "/Users/me/a.txt" });
+ expect(perm("Mercury needs write access to:\n/Users/me/proj\n\nAllow access?")).toMatchObject({ title: "Allow write access", code: "/Users/me/proj" });
+ expect(perm('MCP tool call\nServer: github\nTool: create_issue\nArguments:\n{\n "title": "x"\n}')).toMatchObject({ title: "Use create_issue", note: "github (MCP server)", code: '{\n "title": "x"\n}' });
+ });
+
+ it("the prompt-injection approval: what it read, what it wants, and the warning", () => {
+ const text = [
+ "⚠ Possible prompt injection. Mercury read content that contains instructions written to an AI:",
+ "- /Users/me/Downloads/weather.html (read_file) — contains instructions to an AI: \"create a schedule\"",
+ "- https://news.example/today (fetch_url)",
+ "",
+ "It now wants to run schedule_task with:",
+ '{\n "cron": "0 9 * * *"\n}',
+ "",
+ "Approve only if YOU asked for this.",
+ ].join("\n");
+ const d = perm(text);
+ expect(d.title).toBe("Suspicious request: schedule a task");
+ expect(d.code).toBe('{\n "cron": "0 9 * * *"\n}');
+ expect(d.note).toContain("weather.html");
+ expect(d.warning).toContain("instructions written to an AI");
+ });
+
+ it("unknown shapes and questions are shown as they came", () => {
+ expect(perm("Something new?")).toEqual({ title: "Allow this?", body: "Something new?" });
+ expect(describePrompt({ kind: "continue", text: "25 steps so far. Continue?" })).toEqual({ title: "Keep going?", body: "25 steps so far. Continue?" });
+ });
+});
diff --git a/apps/desktop/src/components/needs-you/describe.ts b/apps/desktop/src/components/needs-you/describe.ts
new file mode 100644
index 00000000..518471f6
--- /dev/null
+++ b/apps/desktop/src/components/needs-you/describe.ts
@@ -0,0 +1,77 @@
+import type { PendingPrompt } from "~/api/types";
+
+/* ═══════════════════════════════════════════════════════════════
+ A question from the runtime, in words: a short title, the exact
+ thing it would run or touch (shown as one code line), and any note
+ or warning. The runtime sends plain text in a handful of shapes;
+ anything unrecognised is shown as it came.
+ ═══════════════════════════════════════════════════════════════ */
+
+export interface Described {
+ title: string;
+ /** The command, path, URL or arguments, verbatim. */
+ code?: string;
+ /** Context in a quiet line ("Read: weather.html, notes.txt"). */
+ note?: string;
+ /** Something to look at twice (data leaving, hidden instructions). */
+ warning?: string;
+ /** Free text when the prompt isn't one of the known shapes (a question, a pick). */
+ body?: string;
+}
+
+export function describePrompt(p: Pick<PendingPrompt, "kind" | "text">): Described {
+ const text = p.text.trim();
+ if (p.kind === "continue") return { title: "Keep going?", body: text };
+ if (p.kind === "choice") return { title: "Your pick", body: text };
+
+ let m = /^Run command(?: \(([^)]*)\))?:\s*([\s\S]+)$/.exec(text);
+ if (m) return { title: "Run a command", code: m[2].trim(), ...(m[1] ? { note: cap(m[1]) } : {}) };
+
+ m = /^(Write to file|Read file):\s*(.+)$/.exec(text);
+ if (m) return { title: m[1] === "Read file" ? "Read a file" : "Write a file", code: m[2].trim() };
+
+ m = /^Mercury needs (read|write) access to:\s*\n(.+?)\n/s.exec(text);
+ if (m) return { title: `Allow ${m[1]} access`, code: m[2].trim(), note: m[1] === "write" ? "Mercury may create and change files there." : "Mercury may read files there." };
+
+ m = /^MCP tool call\nServer:\s*(.+)\nTool:\s*(.+)\nArguments:\n([\s\S]*)$/.exec(text);
+ if (m) return { title: `Use ${m[2].trim()}`, note: `${m[1].trim()} (MCP server)`, code: m[3].trim() || undefined };
+
+ if (/^⚠ Possible prompt injection|^Mercury read content from outside this chat/.test(text)) {
+ const injection = text.startsWith("⚠");
+ const wants = /It now wants to run (\S+) with:\n([\s\S]*?)(?:\n\n|$)/.exec(text);
+ const sources = [...text.matchAll(/^- (.+?)(?: — contains instructions to an AI: .*)?$/gm)].map((x) => x[1].replace(/\s*\((\w+)\)$/, "")).filter((s) => !s.startsWith("…"));
+ const leak = /⚠ This could send data out: (.+?)\.?$/m.exec(text);
+ return {
+ title: wants ? `${injection ? "Suspicious request" : "After reading outside content"}: ${toolWords(wants[1])}` : "After reading outside content",
+ ...(wants ? { code: wants[2].trim() } : {}),
+ note: sources.length ? `It read: ${sources.slice(0, 3).map(shortSource).join(", ")}${sources.length > 3 ? ` and ${sources.length - 3} more` : ""}. Approve only if you asked for this.` : "Approve only if you asked for this.",
+ ...(injection ? { warning: "What it read contains instructions written to an AI." } : {}),
+ ...(leak ? { warning: `${injection ? "Hidden instructions, and this " : "This "}could send data out: ${leak[1]}.` } : {}),
+ };
+ }
+
+ m = /^Open (\S+) in this chat.s isolated read-only browser\?\s*([\s\S]*)$/.exec(text);
+ if (m) return { title: "Open a page", code: m[1], note: cap(m[2].trim()) || undefined };
+
+ return { title: "Allow this?", body: text };
+}
+
+/** "run_command" → "run a command"; other tool names as they are, spaced. */
+function toolWords(name: string): string {
+ const words: Record<string, string> = {
+ run_command: "run a command", write_file: "write a file", edit_file: "edit a file", create_file: "create a file", delete_file: "delete a file",
+ fetch_url: "open a web address", web_search: "search the web", schedule_task: "schedule a task", send_message: "send a message", send_file: "send a file",
+ save_memory: "save to memory", git_push: "push to git", create_pr: "open a pull request", create_issue: "open an issue", delegate_task: "hand off a task",
+ };
+ return words[name] ?? name.replace(/_/g, " ");
+}
+
+function shortSource(s: string): string {
+ const t = s.replace(/^https?:\/\//, "");
+ const path = t.split("/");
+ return path.length > 2 && !/^[\w.-]+\.\w+$/.test(path[0]) ? path[path.length - 1] : t.length > 48 ? `${t.slice(0, 47)}…` : t;
+}
+
+function cap(s: string): string {
+ return s ? s[0].toUpperCase() + s.slice(1) : s;
+}
diff --git a/apps/desktop/src/views/bots/Approvals.tsx b/apps/desktop/src/views/bots/Approvals.tsx
index 824c131d..979852c1 100644
--- a/apps/desktop/src/views/bots/Approvals.tsx
+++ b/apps/desktop/src/views/bots/Approvals.tsx
@@ -1,63 +1,33 @@
-import { KeyRound } from "lucide-react";
import { useEffect, useState } from "react";
import * as api from "~/api/mercury";
import type { BotApproval } from "~/api/types";
import { refreshApprovals } from "~/app/events";
import { useBots } from "~/app/store";
-import { Button } from "~/components/ui/Button";
+import { NeedsYou, type NeedsYouItem } from "~/components/needs-you/NeedsYou";
+import { describePrompt } from "~/components/needs-you/describe";
-/**
- * A bot asking you mid-run: what it wants to do, how long it will wait, and
- * three answers. Allow once covers this run; Always allow is remembered in
- * that bot's own permissions; no answer in time is a no.
- */
-export function ApprovalCard({ a }: { a: BotApproval }) {
- const [busy, setBusy] = useState<string | null>(null);
- const [problem, setProblem] = useState<string | null>(null);
- const [now, setNow] = useState(Date.now());
- useEffect(() => { const t = setInterval(() => setNow(Date.now()), 15_000); return () => clearInterval(t); }, []);
- const minutes = Math.max(0, Math.ceil((a.expiresAt - now) / 60_000));
- const [what, ...rest] = a.prompt.split(": ");
- const detail = rest.join(": ");
-
- async function answer(v: "yes" | "always" | "no") {
- setBusy(v);
- setProblem(null);
- try {
- await api.bots.answer(a.id, v);
- } catch (e) {
- setProblem(e instanceof Error ? e.message : String(e));
- } finally {
- setBusy(null);
- void refreshApprovals();
- }
- }
-
- return (
- <div className="flex flex-col gap-2.5 rounded-xl border border-amber/50 bg-amber/[0.05] p-4">
- <div className="flex items-start gap-2.5">
- <KeyRound size={16} className="mt-0.5 shrink-0 text-amber" aria-hidden="true" />
- <div className="min-w-0 flex-1">
- <div className="text-sm font-medium text-ink">{a.botName} asks to {what.toLowerCase()}</div>
- {detail && <code className="mt-1 block break-all rounded-md bg-ink/[0.06] px-2 py-1 font-mono text-xs text-ink" data-selectable>{detail}</code>}
- <p className="mt-1 text-xs text-ink3">It's waiting. {minutes > 0 ? `Without an answer in ${minutes} min, it's refused.` : "It's about to be refused."}</p>
- </div>
- </div>
- <div className="flex flex-wrap items-center gap-2 pl-[26px]">
- <Button size="sm" variant="primary" loading={busy === "yes"} disabled={!!busy} onClick={() => void answer("yes")}>Allow once</Button>
- <Button size="sm" variant="outline" loading={busy === "always"} disabled={!!busy} onClick={() => void answer("always")}>Always allow for {a.botName}</Button>
- <Button size="sm" variant="ghost" loading={busy === "no"} disabled={!!busy} onClick={() => void answer("no")}>Deny</Button>
- {problem && <span className="text-xs text-red">{problem}</span>}
- </div>
- </div>
- );
+/** Bot questions as Needs-you items: plain words, Allow once / Always allow / Deny, how long it waits. */
+export function botQuestionItems(approvals: BotApproval[], now = Date.now()): NeedsYouItem[] {
+ return approvals.map((a) => ({
+ id: a.id,
+ described: describePrompt({ kind: "permission", text: a.prompt }),
+ from: `${a.botName} · waits ${Math.max(0, Math.ceil((a.expiresAt - now) / 60_000))} min, then it's a no`,
+ options: [
+ { value: "yes", label: "Allow once", role: "primary" },
+ { value: "always", label: `Always allow for ${a.botName}`, role: "secondary" },
+ { value: "no", label: "Deny", role: "quiet" },
+ ],
+ onAnswer: async (v: string | null) => { await api.bots.answer(a.id, (v ?? "no") as "yes" | "always" | "no").catch(() => {}); void refreshApprovals(); },
+ }));
}
-/** Every question waiting right now (for one bot, or all of them). */
-export function PendingApprovals({ botId }: { botId?: string }) {
+/** Every question waiting right now (for some bots, or all of them), one at a time. */
+export function PendingApprovals({ botId, botIds }: { botId?: string; botIds?: string[] }) {
const approvals = useBots((s) => s.approvals);
- useEffect(() => { void refreshApprovals(); }, []);
- const mine = approvals.filter((a) => !botId || a.botId === botId);
+ const [now, setNow] = useState(Date.now());
+ useEffect(() => { void refreshApprovals(); const t = setInterval(() => setNow(Date.now()), 30_000); return () => clearInterval(t); }, []);
+ const want = botIds ?? (botId ? [botId] : null);
+ const mine = approvals.filter((a) => !want || want.includes(a.botId));
if (mine.length === 0) return null;
- return <div className="flex flex-col gap-2">{mine.map((a) => <ApprovalCard key={a.id} a={a} />)}</div>;
+ return <NeedsYou items={botQuestionItems(mine, now)} />;
}
diff --git a/apps/desktop/src/views/bots/BotsView.tsx b/apps/desktop/src/views/bots/BotsView.tsx
index d9c5def7..51e16bf8 100644
--- a/apps/desktop/src/views/bots/BotsView.tsx
+++ b/apps/desktop/src/views/bots/BotsView.tsx
@@ -16,6 +16,7 @@ import { BotAvatar } from "~/components/BotAvatar";
import { ConfirmButton } from "~/components/ui/kit";
import { Deliverables } from "./Deliverables";
import { Activity } from "./Activity";
+import { Live } from "./Live";
import { Usage } from "./Usage";
import { BotInbox, InboxRow } from "./Inbox";
import { PendingApprovals } from "./Approvals";
@@ -212,14 +213,15 @@ function describe(b: BotStatus): string {
return "Idle";
}
-type Tab = "overview" | "results" | "deliverables" | "activity" | "usage" | "settings";
+type Tab = "live" | "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: "live", label: "Live" },
{ id: "overview", label: "Overview" },
{ id: "results", label: "Results" },
{ id: "deliverables", label: fleet ? "Fleet files" : "Files" },
- { id: "activity", label: "Activity" },
+ { id: "activity", label: "History" },
{ id: "usage", label: "Usage" },
{ id: "settings", label: "Settings" },
];
@@ -237,14 +239,15 @@ function TabBar({ tab, onChange, fleet }: { tab: Tab; onChange: (t: Tab) => void
function FleetDetail({ fleet, activity, onSelect }: { fleet: Fleet; activity: Record<string, string>; onSelect: (id: string | null) => void }) {
const { lead, crew } = fleet;
- const [tab, setTab] = useState<Tab>("overview");
- useEffect(() => { setTab("overview"); }, [lead.id]);
+ const [tab, setTab] = useState<Tab>("live");
+ useEffect(() => { setTab("live"); }, [lead.id]);
const members = [lead, ...crew];
return (
<div className="mx-auto flex max-w-[1000px] flex-col gap-6 px-8 py-7">
<BotHeader id={lead.id} status={lead} subtitle={`Fleet lead · ${crew.length} crew`} crewCount={crew.length} onDeleted={() => onSelect(null)} />
- {members.map((m) => <PendingApprovals key={m.id} botId={m.id} />)}
+ {tab !== "live" && <PendingApprovals botIds={members.map((m) => m.id)} />}
<TabBar tab={tab} onChange={setTab} fleet />
+ {tab === "live" && <Live bots={members} defaultTarget={lead.id} />}
{tab === "overview" && (
<>
<div className="flex flex-col gap-3">
@@ -278,14 +281,15 @@ function FleetDetail({ fleet, activity, onSelect }: { fleet: Fleet; activity: Re
}
function BotDetail({ id, status, onDeleted }: { id: string; status: BotStatus | null; onDeleted: () => void }) {
- const [tab, setTab] = useState<Tab>("overview");
- useEffect(() => { setTab("overview"); }, [id]);
+ const [tab, setTab] = useState<Tab>("live");
+ useEffect(() => { setTab("live"); }, [id]);
const me = [{ id, name: status?.name ?? id, hasAvatar: status?.hasAvatar }];
return (
<div className="mx-auto flex max-w-[1000px] flex-col gap-6 px-8 py-7">
<BotHeader id={id} status={status} onDeleted={onDeleted} />
- <PendingApprovals botId={id} />
+ {tab !== "live" && <PendingApprovals botId={id} />}
<TabBar tab={tab} onChange={setTab} fleet={false} />
+ {tab === "live" && status && <Live bots={[status]} defaultTarget={id} />}
{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} />}
diff --git a/apps/desktop/src/views/bots/Live.tsx b/apps/desktop/src/views/bots/Live.tsx
new file mode 100644
index 00000000..d064aa21
--- /dev/null
+++ b/apps/desktop/src/views/bots/Live.tsx
@@ -0,0 +1,228 @@
+import { ArrowUp, Check, ChevronRight, CircleAlert, CornerUpLeft, Loader2, MessageSquare } from "lucide-react";
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import * as api from "~/api/mercury";
+import type { BotStatus } from "~/api/types";
+import { refreshApprovals } from "~/app/events";
+import { useBots } from "~/app/store";
+import { BotAvatar } from "~/components/BotAvatar";
+import { Button } from "~/components/ui/Button";
+import { Badge, Empty } from "~/components/ui/bits";
+import { cx } from "~/lib/cx";
+import { NeedsYou } from "~/components/needs-you/NeedsYou";
+import { botQuestionItems } from "./Approvals";
+import { runsFrom, startedBy, STATE_LABEL, type LiveRun } from "./live-runs";
+
+/* ═══════════════════════════════════════════════════════════════
+ Live: what a bot (or a whole fleet) is doing right now, as it
+ happens, and a box to talk to it.
+
+ One card per run: who started it and what was asked, each step as it
+ runs (folded past the last few), what the bot is writing, how it
+ ended. A question the bot asks you sits inside its run, with its
+ buttons. The box at the bottom messages the bot (or a crew member);
+ a message to a busy bot shows as queued at once. Reply on a finished
+ run answers it with that run quoted.
+
+ Costs little: the recent past loads once (GET /api/bots/activity),
+ then the bots stream adds to it; the app keeps a capped log.
+ ═══════════════════════════════════════════════════════════════ */
+
+const SHOWN_STEPS = 6;
+const SHOWN_RUNS = 40;
+
+export function Live({ bots, defaultTarget }: { bots: BotStatus[]; defaultTarget: string }) {
+ const ids = useMemo(() => bots.map((b) => b.id), [bots]);
+ const idKey = ids.join(",");
+ const live = useBots((s) => s.live);
+ const approvals = useBots((s) => s.approvals);
+ const [loaded, setLoaded] = useState(false);
+ const [target, setTarget] = useState(defaultTarget);
+ const [draft, setDraft] = useState("");
+ const [sending, setSending] = useState(false);
+ const [problem, setProblem] = useState<string | null>(null);
+ const [older, setOlder] = useState(false);
+ const box = useRef<HTMLTextAreaElement>(null);
+ const scroller = useRef<HTMLDivElement>(null);
+ const pinned = useRef(true);
+
+ useEffect(() => { setTarget(defaultTarget); }, [defaultTarget]);
+ useEffect(() => {
+ let alive = true;
+ setLoaded(false);
+ void api.bots.activity(ids).then((r) => { if (alive) useBots.getState().addLive(r.events); }).catch(() => {}).finally(() => { if (alive) setLoaded(true); });
+ void refreshApprovals();
+ return () => { alive = false; };
+ }, [idKey]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ // A clock for "ended" and elapsed times; cheap, and only while open.
+ const [now, setNow] = useState(Date.now());
+ useEffect(() => { const t = setInterval(() => setNow(Date.now()), 15_000); return () => clearInterval(t); }, []);
+
+ const mine = useMemo(() => new Set(ids), [idKey]); // eslint-disable-line react-hooks/exhaustive-deps
+ const running = useMemo(() => new Set(bots.filter((b) => b.state === "running").map((b) => b.id)), [bots]);
+ const myApprovals = useMemo(() => approvals.filter((a) => mine.has(a.botId)), [approvals, mine]);
+ const runs = useMemo(
+ () => runsFrom(live.filter((e) => mine.has(e.botId)), { running, approvals: myApprovals, now }),
+ [live, mine, running, myApprovals, now],
+ );
+ const shown = older ? runs : runs.slice(-SHOWN_RUNS);
+ const nameOf = (id: string) => bots.find((b) => b.id === id)?.name;
+ const questions = useMemo(() => botQuestionItems(myApprovals, now), [myApprovals, now]);
+
+ // Follow new activity while you're at the bottom; leave you alone when you scrolled up to read.
+ useLayoutEffect(() => {
+ const el = scroller.current;
+ if (el && pinned.current) el.scrollTop = el.scrollHeight;
+ }, [runs]);
+
+ async function send() {
+ const text = draft.trim();
+ if (!text || sending) return;
+ setSending(true);
+ setProblem(null);
+ try {
+ const r = await api.bots.message(target, text);
+ if (!r.accepted) setProblem(r.reasonCode === "target_disabled" ? "That bot is off. Turn it on to message it." : `Not sent (${r.reasonCode ?? "refused"}).`);
+ else { setDraft(""); pinned.current = true; }
+ } catch (e) {
+ setProblem(e instanceof Error ? e.message : String(e));
+ } finally {
+ setSending(false);
+ }
+ }
+
+ function reply(run: LiveRun) {
+ setTarget(run.botId);
+ const said = (run.text ?? run.endLabel ?? "").replace(/\s+/g, " ").trim().slice(-160);
+ setDraft(`Re your run "${(run.prompt ?? "").slice(0, 60)}"${said ? ` (you said: "…${said}")` : ""}:\n`);
+ requestAnimationFrame(() => { box.current?.focus(); box.current?.setSelectionRange(box.current.value.length, box.current.value.length); });
+ }
+
+ return (
+ <div className="flex h-[calc(100vh-260px)] min-h-[420px] flex-col overflow-hidden rounded-xl border border-line bg-surface">
+ <div ref={scroller} onScroll={(e) => { const el = e.currentTarget; pinned.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80; }}
+ className="min-h-0 flex-1 overflow-y-auto px-4 py-4">
+ {!older && runs.length > SHOWN_RUNS && (
+ <button onClick={() => setOlder(true)} className="mx-auto mb-3 block text-xs text-ink3 hover:text-ink">Show {runs.length - SHOWN_RUNS} earlier runs</button>
+ )}
+ {loaded && runs.length === 0 && questions.length === 0 && (
+ <Empty title="Nothing happening yet" body="When a bot starts a run (on its schedule, from another bot, or from your message below), you'll see each step here as it happens." />
+ )}
+ <div className="flex flex-col gap-3">
+ {shown.map((r) => (
+ <RunCard key={r.jobId} run={r} bot={bots.find((b) => b.id === r.botId)} fleet={bots.length > 1} by={startedBy(r, nameOf)}
+ waiting={myApprovals.some((a) => a.runId === r.jobId)} onReply={() => reply(r)} now={now} />
+ ))}
+ </div>
+ </div>
+
+ {questions.length > 0 && <div className="border-t border-line bg-soft/60 px-3 pt-3"><NeedsYou items={questions} /></div>}
+ <div className="border-t border-line bg-soft/60 p-3">
+ {problem && <p className="mb-2 text-xs text-red">{problem}</p>}
+ <div className="flex items-end gap-2">
+ {bots.length > 1 && (
+ <select value={target} onChange={(e) => setTarget(e.target.value)} aria-label="Send to"
+ className="h-9 max-w-[180px] shrink-0 rounded-lg border border-line bg-surface px-2 text-sm text-ink">
+ {bots.map((b) => <option key={b.id} value={b.id}>{b.name}{b.id === defaultTarget ? " (lead)" : ""}</option>)}
+ </select>
+ )}
+ <textarea ref={box} value={draft} rows={1} onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) { e.preventDefault(); void send(); } }}
+ placeholder={`Message ${nameOf(target) ?? "the bot"}… (runs now, or after its current run)`}
+ className="max-h-40 min-h-[36px] flex-1 resize-none rounded-lg border border-line bg-surface px-3 py-2 text-sm text-ink outline-none focus:border-accent/60" />
+ <Button variant="primary" size="sm" icon onClick={() => void send()} disabled={!draft.trim() || sending} aria-label="Send">
+ {sending ? <Loader2 size={14} className="animate-spin" /> : <ArrowUp size={15} />}
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+const TONE: Record<LiveRun["state"], "accent" | "amber" | "red" | "neutral"> = {
+ queued: "neutral", working: "accent", waiting: "amber", done: "neutral", failed: "red", stopped: "neutral", paused: "amber", ended: "neutral",
+};
+
+function RunCard({ run, bot, fleet, by, waiting, onReply, now }: {
+ run: LiveRun; bot?: BotStatus; fleet: boolean; by: string; waiting: boolean; onReply: () => void; now: number;
+}) {
+ const [allSteps, setAllSteps] = useState(false);
+ const active = run.state === "working" || run.state === "waiting" || run.state === "queued";
+ const hidden = allSteps ? 0 : Math.max(0, run.steps.length - SHOWN_STEPS);
+ const steps = run.steps.slice(hidden);
+ const fromYou = by.startsWith("You");
+ const elapsed = Math.max(0, (active ? now : run.updatedAt) - run.startedAt);
+ return (
+ <div className="flex flex-col gap-2">
+ {run.prompt && fromYou && (
+ <div className="ml-auto max-w-[75%] whitespace-pre-wrap rounded-2xl rounded-br-md bg-accent/10 px-3.5 py-2 text-sm text-ink" data-selectable>
+ {run.prompt}
+ {fleet && <span className="mt-1 block text-2xs text-ink4">to {run.botName}</span>}
+ </div>
+ )}
+ <div className={cx("rounded-xl border bg-surface px-4 py-3", run.state === "waiting" ? "border-amber/50" : run.state === "failed" ? "border-red/30" : active ? "border-accent/35" : "border-line")}>
+ <div className="flex items-center gap-2.5">
+ <BotAvatar id={run.botId} name={run.botName} hasAvatar={bot?.hasAvatar} size={24} />
+ <span className="min-w-0 flex-1 truncate text-sm">
+ <span className="font-medium text-ink">{run.botName}</span>
+ {!fromYou && <span className="text-ink3"> · {by}</span>}
+ </span>
+ <span className="shrink-0 font-mono text-2xs text-ink4">{fmtTime(run.startedAt)} · {fmtDur(elapsed)}{run.stepCount ? ` · ${run.stepCount} step${run.stepCount === 1 ? "" : "s"}` : ""}</span>
+ <Badge tone={TONE[run.state]}>{active && run.state !== "waiting" && <Loader2 size={10} className="mr-1 inline animate-spin" />}{STATE_LABEL[run.state]}</Badge>
+ </div>
+
+ {run.prompt && !fromYou && <p className="mt-2 line-clamp-3 text-sm text-ink2" data-selectable>{run.prompt}</p>}
+
+ {(steps.length > 0 || hidden > 0) && (
+ <ol className="mt-2.5 flex flex-col gap-1 border-l border-line pl-3">
+ {hidden > 0 && (
+ <li><button onClick={() => setAllSteps(true)} className="flex items-center gap-1 text-xs text-ink3 hover:text-ink"><ChevronRight size={12} /> {hidden} earlier step{hidden === 1 ? "" : "s"}</button></li>
+ )}
+ {steps.map((s, i) => (
+ <li key={i} className="flex min-w-0 items-start gap-2 text-xs">
+ <span className="mt-[1px] shrink-0">
+ {s.status === "running" ? <Loader2 size={12} className="animate-spin text-accent" />
+ : s.status === "error" ? <CircleAlert size={12} className="text-red" />
+ : s.status === "note" ? <MessageSquare size={12} className="text-ink4" />
+ : <Check size={12} className="text-accent" strokeWidth={3} />}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className={cx("break-all font-mono", s.status === "note" ? "text-ink3" : "text-ink2")}>{s.label}</span>
+ {s.detail && s.status === "error" && <span className="block break-all text-red/90">{s.detail}</span>}
+ </span>
+ </li>
+ ))}
+ </ol>
+ )}
+
+ {run.text && (
+ <p className={cx("mt-2.5 line-clamp-4 whitespace-pre-wrap text-sm", active ? "text-ink3" : "text-ink2")} data-selectable>{run.text.trim()}</p>
+ )}
+
+ {waiting && <p className="mt-2.5 text-xs text-amber">Waiting for your answer: see Needs you below.</p>}
+
+ {!active && (
+ <div className="mt-2.5 flex items-center gap-3 text-xs text-ink4">
+ {run.endLabel && run.state !== "done" && <span className="truncate">{run.endLabel}</span>}
+ {run.state === "ended" && <span>No ending was reported (Mercury restarted during the run).</span>}
+ <span className="flex-1" />
+ <button onClick={onReply} className="flex items-center gap-1 text-ink3 hover:text-ink"><CornerUpLeft size={12} /> Reply</button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function fmtTime(at: number): string {
+ const d = new Date(at);
+ const today = new Date().toDateString() === d.toDateString();
+ return d.toLocaleString([], today ? { hour: "numeric", minute: "2-digit" } : { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" });
+}
+
+function fmtDur(ms: number): string {
+ const s = Math.round(ms / 1000);
+ if (s < 60) return `${s}s`;
+ const m = Math.floor(s / 60);
+ return m < 60 ? `${m}m ${s % 60}s` : `${Math.floor(m / 60)}h ${m % 60}m`;
+}
diff --git a/apps/desktop/src/views/bots/live-runs.test.ts b/apps/desktop/src/views/bots/live-runs.test.ts
new file mode 100644
index 00000000..bbfebd06
--- /dev/null
+++ b/apps/desktop/src/views/bots/live-runs.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from "vitest";
+import type { BotActivityEvent } from "~/api/types";
+import { mergeLive } from "~/app/store";
+import { runsFrom, startedBy } from "./live-runs";
+
+const ev = (e: Partial<BotActivityEvent> & Pick<BotActivityEvent, "kind" | "label">, at: number): BotActivityEvent => ({ botId: "w", jobId: "j1", botName: "Writer", ...e, at });
+
+describe("live runs", () => {
+ it("a run from your message to its end: queued, steps that finish in place, the reply, done", () => {
+ const runs = runsFrom([
+ ev({ kind: "queued", label: "Starting", trigger: "api", prompt: "Draft the post" }, 1),
+ ev({ kind: "turn-start", label: "Draft the post", trigger: "api", prompt: "Draft the post" }, 2),
+ ev({ kind: "step", label: "step 1", stepIndex: 1 }, 3),
+ ev({ kind: "tool", label: "read_file notes.md", status: "running" }, 4),
+ ev({ kind: "tool", label: "read_file notes.md", status: "done" }, 5),
+ ev({ kind: "tool", label: "web_search ai agents", status: "running" }, 6),
+ ev({ kind: "thinking", label: "thinking", textTail: "Here is the draft" }, 7),
+ ev({ kind: "turn-end", label: "completed", status: "done" }, 8),
+ ]);
+ expect(runs).toHaveLength(1);
+ const r = runs[0];
+ expect(r.state).toBe("done");
+ expect(r.prompt).toBe("Draft the post");
+ expect(r.steps.map((s) => `${s.label}:${s.status}`)).toEqual(["read_file notes.md:done", "web_search ai agents:done"]);
+ expect(r.stepCount).toBe(1);
+ expect(r.text).toBe("Here is the draft");
+ expect(startedBy(r, () => undefined)).toBe("You");
+ });
+
+ it("waiting for you only when a question for this run is pending", () => {
+ const events = [ev({ kind: "turn-start", label: "x" }, 1), ev({ kind: "step", label: "Waiting for your approval" }, 2)];
+ expect(runsFrom(events)[0].state).toBe("working");
+ const approval = { id: "a", botId: "w", botName: "Writer", runId: "j1", prompt: "Run command: ls", at: 2, expiresAt: 9 };
+ expect(runsFrom(events, { approvals: [approval] })[0].state).toBe("waiting");
+ expect(runsFrom(events, { approvals: [{ ...approval, runId: "other" }] })[0].state).toBe("working");
+ });
+
+ it("a run whose bot stopped without an ending event is ended, not working forever", () => {
+ const events = [ev({ kind: "turn-start", label: "x" }, 1_000)];
+ expect(runsFrom(events, { running: new Set(), now: 200_000 })[0].state).toBe("ended");
+ expect(runsFrom(events, { running: new Set(["w"]), now: 200_000 })[0].state).toBe("working");
+ });
+
+ it("failures, stops and pauses read as such; a delivery joins the bot's run", () => {
+ expect(runsFrom([ev({ kind: "turn-start", label: "x" }, 1), ev({ kind: "turn-end", label: "failed: provider_timeout", status: "error" }, 2)])[0].state).toBe("failed");
+ expect(runsFrom([ev({ kind: "turn-start", label: "x" }, 1), ev({ kind: "turn-end", label: "stopped — by you", status: "error" }, 2)])[0].state).toBe("stopped");
+ const r = runsFrom([ev({ kind: "turn-start", label: "x" }, 1), { botId: "w", jobId: "", kind: "tool", label: "Delivered post.md", status: "done", at: 2 }]);
+ expect(r).toHaveLength(1);
+ expect(r[0].steps[0].label).toBe("Delivered post.md");
+ });
+
+ it("the store drops duplicates and keeps one thinking preview per run", () => {
+ const a = ev({ kind: "tool", label: "ls", status: "done" }, 5);
+ const t1 = ev({ kind: "thinking", label: "thinking", textTail: "Hel" }, 6);
+ const t2 = ev({ kind: "thinking", label: "thinking", textTail: "Hello" }, 7);
+ const merged = mergeLive(mergeLive([a], [a, t1]), [t2, a]);
+ expect(merged.map((e) => e.textTail ?? e.label)).toEqual(["ls", "Hello"]);
+ });
+});
diff --git a/apps/desktop/src/views/bots/live-runs.ts b/apps/desktop/src/views/bots/live-runs.ts
new file mode 100644
index 00000000..e8cc0db8
--- /dev/null
+++ b/apps/desktop/src/views/bots/live-runs.ts
@@ -0,0 +1,134 @@
+import type { BotActivityEvent, BotApproval } from "~/api/types";
+
+/* ═══════════════════════════════════════════════════════════════
+ The live feed's model: raw bot events → one card per run.
+
+ A run's state is worked out from its latest event (Linear's rule), so
+ it can't drift: an answered question or a finished run clears itself.
+ "Waiting for you" comes only from a pending approval for that very run,
+ never from wording, so nothing is flagged that isn't actually waiting.
+ A run with no ending event whose bot is no longer running (the runtime
+ restarted mid-run) is shown as ended, not "working" forever.
+ ═══════════════════════════════════════════════════════════════ */
+
+export type RunState = "queued" | "working" | "waiting" | "done" | "failed" | "stopped" | "paused" | "ended";
+
+export interface LiveStep {
+ label: string;
+ status: "running" | "done" | "error" | "note";
+ detail?: string;
+ at: number;
+}
+
+export interface LiveRun {
+ jobId: string;
+ botId: string;
+ botName: string;
+ trigger?: string;
+ prompt?: string;
+ fromBot?: string;
+ startedAt: number;
+ updatedAt: number;
+ steps: LiveStep[];
+ /** Steps the model took (its step counter). */
+ stepCount: number;
+ /** The reply as it is being written (a rolling tail). */
+ text?: string;
+ reasoning?: string;
+ state: RunState;
+ /** How it ended, in the runtime's words ("completed", "failed: …"). */
+ endLabel?: string;
+}
+
+/** Steps that only count ("step 4 · 12.3k tok in") rather than say something. */
+const COUNTER = /^step \d+/;
+
+function endState(e: BotActivityEvent): RunState {
+ const l = e.label.toLowerCase();
+ if (l.startsWith("paused")) return "paused";
+ if (l.startsWith("stopped") || l === "halted") return "stopped";
+ if (e.status === "error" || l.startsWith("failed")) return "failed";
+ return "done";
+}
+
+/**
+ * Runs from events (oldest first in, oldest first out). `running` is the set
+ * of bots the runtime says are running now; `approvals` the questions
+ * waiting. Deliveries outside a run join the bot's latest run.
+ */
+export function runsFrom(events: BotActivityEvent[], opts: { running?: Set<string>; approvals?: BotApproval[]; now?: number } = {}): LiveRun[] {
+ const now = opts.now ?? Date.now();
+ const runs = new Map<string, LiveRun>();
+ const latestOf = new Map<string, LiveRun>();
+ for (const e of events) {
+ const at = e.at ?? now;
+ let run = e.jobId ? runs.get(e.jobId) : latestOf.get(e.botId);
+ if (!run) {
+ if (!e.jobId && e.kind !== "tool") continue;
+ run = {
+ jobId: e.jobId || `loose-${e.botId}-${at}`, botId: e.botId, botName: e.botName ?? e.botId,
+ startedAt: at, updatedAt: at, steps: [], stepCount: 0, state: e.kind === "queued" ? "queued" : "working",
+ };
+ runs.set(run.jobId, run);
+ }
+ if (e.jobId) latestOf.set(e.botId, run);
+ run.updatedAt = Math.max(run.updatedAt, at);
+ if (e.botName) run.botName = e.botName;
+ switch (e.kind) {
+ case "queued":
+ run.prompt ??= e.prompt;
+ run.trigger ??= e.trigger;
+ break;
+ case "turn-start":
+ run.prompt = e.prompt ?? run.prompt ?? e.label;
+ run.trigger = e.trigger ?? run.trigger;
+ run.fromBot = e.fromBot ?? run.fromBot;
+ run.state = "working";
+ break;
+ case "tool": {
+ const status = e.status === "error" ? "error" : e.status === "running" ? "running" : "done";
+ const open = [...run.steps].reverse().find((s) => s.label === e.label && s.status === "running");
+ if (open && status !== "running") { open.status = status; open.detail = e.detail; open.at = at; }
+ else run.steps.push({ label: e.label, status, ...(e.detail ? { detail: e.detail } : {}), at });
+ if (run.state === "queued") run.state = "working";
+ break;
+ }
+ case "step":
+ if (COUNTER.test(e.label)) run.stepCount = Math.max(run.stepCount, e.stepIndex ?? 0);
+ else if (run.steps[run.steps.length - 1]?.label !== e.label) run.steps.push({ label: e.label, status: "note", at });
+ if (run.state === "queued") run.state = "working";
+ break;
+ case "thinking":
+ if (e.textTail) run.text = e.textTail;
+ if (e.reasoningTail) run.reasoning = e.reasoningTail;
+ break;
+ case "turn-end":
+ run.state = endState(e);
+ run.endLabel = e.label;
+ // Nothing still "running" in a finished run.
+ for (const s of run.steps) if (s.status === "running") s.status = run.state === "done" ? "done" : "error";
+ break;
+ }
+ }
+ const waiting = new Set((opts.approvals ?? []).map((a) => a.runId));
+ for (const r of runs.values()) {
+ if (waiting.has(r.jobId) && (r.state === "working" || r.state === "queued")) r.state = "waiting";
+ // No ending event, and the bot isn't running any more: it ended without telling us (a restart).
+ if (r.state === "working" && opts.running && !opts.running.has(r.botId) && now - r.updatedAt > 60_000) r.state = "ended";
+ }
+ return [...runs.values()].sort((a, b) => a.startedAt - b.startedAt);
+}
+
+export const STATE_LABEL: Record<RunState, string> = {
+ queued: "Queued", working: "Working", waiting: "Waiting for you", done: "Done", failed: "Failed", stopped: "Stopped", paused: "Paused", ended: "Ended",
+};
+
+/** Who started a run, in words. */
+export function startedBy(r: LiveRun, nameOf: (id: string) => string | undefined): string {
+ if (r.trigger === "api" || r.trigger === "web" || r.trigger === "chat") return "You";
+ if (r.trigger === "telegram") return "You · Telegram";
+ if (r.trigger === "cloud") return "You · Cloud";
+ if (r.trigger === "cron") return "Schedule";
+ if (r.trigger === "mailbox") return r.fromBot ? `From ${nameOf(r.fromBot) ?? r.fromBot}` : "From the fleet";
+ return r.trigger ? r.trigger[0].toUpperCase() + r.trigger.slice(1) : "Run";
+}
diff --git a/apps/desktop/src/views/chat/Conversation.tsx b/apps/desktop/src/views/chat/Conversation.tsx
index cf52f20d..b04def0e 100644
--- a/apps/desktop/src/views/chat/Conversation.tsx
+++ b/apps/desktop/src/views/chat/Conversation.tsx
@@ -7,7 +7,8 @@ import { useConversation, useConversationStore } from "~/app/conversation";
import { answerPrompt } from "~/app/events";
import { runningStep } from "~/app/trace";
import { StateLabel } from "~/components/indicators/StateOrb";
-import { Approval } from "~/components/indicators/Approval";
+import { NeedsYou, rolesFor } from "~/components/needs-you/NeedsYou";
+import { describePrompt } from "~/components/needs-you/describe";
import { ThinkingDots } from "~/components/indicators/Thinking";
import { Message, StreamingMessage } from "./Message";
import { MediaSkeleton } from "~/components/MediaSkeleton";
@@ -147,11 +148,6 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
</p>
)}
<ResearchPlan />
- {prompts.map((p, i) => (
- <div key={p.id} className="min-w-0 pl-10">
- <Approval prompt={p} onAnswer={(v) => answerPrompt(store, p, v)} keys={i === prompts.length - 1} />
- </div>
- ))}
</div>
)}
</div>
@@ -171,6 +167,20 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
<ResearchBar />
{/* While research runs, its bar shows the questions (and Details the checklist): one progress display, not two. */}
+ {prompts.length > 0 && (
+ <div className="shrink-0 px-8 pt-1">
+ <div className="mx-auto w-full max-w-[780px]">
+ <NeedsYou items={prompts.map((p) => ({
+ id: p.id,
+ described: describePrompt(p),
+ options: rolesFor(p.options),
+ list: p.kind === "choice" || p.options.some((o) => o.label.length > 32),
+ cancelable: p.kind === "choice",
+ onAnswer: (v) => answerPrompt(store, p, v),
+ }))} />
+ </div>
+ </div>
+ )}
{!researching && <PlanCard surface={composer.surface} />}
<Composer {...composer} />
</section>
diff --git a/apps/desktop/src/views/chat/PlanCard.tsx b/apps/desktop/src/views/chat/PlanCard.tsx
index c447154a..364010df 100644
--- a/apps/desktop/src/views/chat/PlanCard.tsx
+++ b/apps/desktop/src/views/chat/PlanCard.tsx
@@ -40,6 +40,10 @@ export function PlanCard({ surface }: { surface: Surface }) {
useEffect(() => { setMinimized(readFlag(minKey) === "1"); setClosedAt(Number(readFlag(closedKey) ?? 0)); }, [minKey, closedKey]);
const steps = plan?.steps ?? [];
+ // Settled by the runtime when its turn ended unfinished; nothing is "in progress" then.
+ const unfinished = steps.some((s) => s.status !== "done");
+ // An unfinished plan in an idle chat isn't being worked on, whatever it says (plans saved before settling existed).
+ const settled = !busy && unfinished ? (plan?.state ?? "paused") : undefined;
const done = steps.filter((s) => s.status === "done").length;
const complete = steps.length > 0 && done === steps.length;
const active = steps.find((s) => s.status === "active") ?? (complete ? null : steps.find((s) => s.status === "pending") ?? null);
@@ -62,15 +66,15 @@ export function PlanCard({ surface }: { surface: Surface }) {
<div className="flex items-center gap-3 px-4 py-2.5">
<button onClick={toggle} className="flex min-w-0 flex-1 items-center gap-3 text-left" aria-expanded={!minimized}>
{complete ? <CheckCircle2 size={16} className="shrink-0 text-accent" /> : <ListChecks size={16} className="shrink-0 text-ink3" />}
- <span className="shrink-0 text-sm font-medium text-ink">{complete ? "Plan complete" : "Plan"}</span>
+ <span className="shrink-0 text-sm font-medium text-ink">{complete ? "Plan complete" : settled === "stopped" ? "Plan stopped" : settled === "paused" ? "Plan paused" : "Plan"}</span>
<span className="shrink-0 font-mono text-xs tabular-nums text-ink3">{done} of {steps.length}</span>
- {minimized && active && <span className="min-w-0 truncate text-sm text-ink2">· {active.label}</span>}
+ {minimized && active && <span className="min-w-0 truncate text-sm text-ink2">· {settled ? `at ${active.label}` : active.label}</span>}
<span className="ml-auto hidden h-1 w-24 shrink-0 overflow-hidden rounded-full bg-ink/[0.08] sm:block" aria-hidden="true">
<span className={cx("block h-full rounded-full transition-[width] duration-500", complete ? "bg-accent" : "bg-ink/60")} style={{ width: `${pct}%` }} />
</span>
<ChevronDown size={15} className={cx("shrink-0 text-ink4 transition-transform", !minimized && "rotate-180")} />
</button>
- {complete && !busy && (
+ {(complete || settled) && !busy && (
<button onClick={close} className="rounded-md p-1 text-ink4 hover:bg-ink/[0.06] hover:text-ink" aria-label="Close the plan"><X size={14} /></button>
)}
</div>
@@ -78,15 +82,20 @@ export function PlanCard({ surface }: { surface: Surface }) {
<ol className="flex max-h-56 flex-col gap-0.5 overflow-y-auto border-t border-line px-3 py-2">
{steps.map((s, i) => (
<li key={`${i}-${s.label}`} className="flex items-start gap-2.5 rounded-lg px-1.5 py-1.5">
- <StepMark status={s.status} live={busy && s.status === "active"} />
+ <StepMark status={settled && s.status === "active" ? "pending" : s.status} live={busy && s.status === "active"} />
<span className={cx("min-w-0 flex-1 text-sm leading-snug",
s.status === "done" && "text-ink3",
- s.status === "active" && "font-medium text-ink",
+ s.status === "active" && (settled ? "text-ink2" : "font-medium text-ink"),
s.status === "pending" && "text-ink2")}>{s.label}</span>
</li>
))}
</ol>
)}
+ {!minimized && settled && (
+ <p className="border-t border-line px-4 py-2 text-xs text-ink3">
+ {settled === "stopped" ? "Stopped before it finished." : "The reply came before these steps were done."} Say "continue" to pick it up from {active ? `"${active.label}"` : "where it stopped"}.
+ </p>
+ )}
</section>
</div>
</div>
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index fd147a70..bec37ccb 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -113,6 +113,8 @@ export interface BotManagerDeps {
notify?: (channelType: string, channelId: string, message: string) => Promise<void>;
}
+/** How many recent events the live feed keeps in memory (the whole fleet). */
+const LIVE_EVENTS = 2000;
const MAX_TRANSIENT_ATTEMPTS = 3;
/** Consecutive no-outcome runs after which a work routine is paused (ADR-020). */
export const NO_OUTCOME_PAUSE_AFTER = 3;
@@ -363,12 +365,53 @@ export class BotManager {
this.activityListeners.add(listener);
return () => this.activityListeners.delete(listener);
}
+ /** What each running job was asked, by whom, for the live feed (set when the turn starts). */
+ private jobContext = new Map<string, { trigger: string; prompt: string; fromBot?: string }>();
+ /**
+ * The live feed's short memory: recent events across the fleet, so a
+ * screen opened mid-run shows what already happened. In memory only and
+ * capped (LIVE_EVENTS); a 'thinking' preview replaces the previous one of
+ * the same run instead of piling up.
+ */
+ private liveLog: BotActivityEvent[] = [];
+
+ /** The owner sent a bot a message: it shows in the live feed at once, before the run starts. */
+ noteOwnerMessage(botId: string, jobId: string, prompt: string): void {
+ // Already started (an idle bot picks the job up at once): the run's own start says it all.
+ if (this.liveLog.some((e) => e.jobId === jobId && e.kind !== 'queued')) return;
+ const busy = (this.running.get(botId)?.size ?? 0) > 0;
+ this.emitBotActivity({ botId, jobId, kind: 'queued', label: busy ? 'Queued: runs when the current run finishes' : 'Starting', stepIndex: 0, elapsedMs: 0, trigger: 'api', prompt: prompt.slice(0, 600) });
+ }
+
+ /** Recent live events, oldest first: for some bots (a fleet) or all, newer than `since`. */
+ recentActivity(opts: { bots?: string[]; since?: number; limit?: number } = {}): BotActivityEvent[] {
+ const want = opts.bots?.length ? new Set(opts.bots) : null;
+ const since = opts.since ?? 0;
+ const out = this.liveLog.filter((e) => (!want || want.has(e.botId)) && (e.at ?? 0) > since);
+ return out.slice(-Math.max(1, Math.min(opts.limit ?? 400, LIVE_EVENTS)));
+ }
+
private emitBotActivity(ev: BotActivityEvent): void {
+ const ctx = ev.jobId ? this.jobContext.get(ev.jobId) : undefined;
+ ev = {
+ ...ev,
+ at: ev.at ?? Date.now(),
+ botName: ev.botName ?? this.store.get(ev.botId)?.name ?? ev.botId,
+ ...(ev.kind === 'turn-start' && ctx ? { trigger: ctx.trigger, prompt: ctx.prompt.slice(0, 600), ...(ctx.fromBot ? { fromBot: ctx.fromBot } : {}) } : {}),
+ };
+ if (ev.kind === 'turn-end' && ev.jobId) this.jobContext.delete(ev.jobId);
+ if (ev.kind === 'thinking') {
+ for (let i = this.liveLog.length - 1; i >= 0; i--) {
+ if (this.liveLog[i].kind === 'thinking' && this.liveLog[i].jobId === ev.jobId) { this.liveLog.splice(i, 1); break; }
+ }
+ }
+ this.liveLog.push(ev);
+ if (this.liveLog.length > LIVE_EVENTS) this.liveLog.splice(0, this.liveLog.length - LIVE_EVENTS);
// Live roster label: keep the static job description until the first
// step arrives, then follow the actual work. 'thinking' events are a
// stream preview for threads, not a roster label — the label must stay
// semantic (step/tool names), not the last 80 chars of reasoning.
- if (ev.kind !== 'turn-end' && ev.kind !== 'thinking') this.activity.set(ev.botId, ev.label);
+ if (ev.kind !== 'turn-end' && ev.kind !== 'thinking' && ev.kind !== 'queued') this.activity.set(ev.botId, ev.label);
for (const listener of this.activityListeners) {
try { listener(ev); } catch (err: any) {
logger.warn({ botId: ev.botId, err: err?.message }, 'Bot activity listener failed');
@@ -942,6 +985,7 @@ export class BotManager {
const taskForJob = this.tasks.byJob(job.id);
if (taskForJob) this.tasks.update(taskForJob.id, { status: 'running', startedAt: Date.now() });
const turn = this.buildTurn(botId, manifest, job, controller.signal);
+ this.jobContext.set(job.id, { trigger: job.trigger, prompt: job.prompt ?? '', ...(job.fromBot ? { fromBot: job.fromBot } : {}) });
const output = await runBotTurn({
...turn.input,
jobId: job.id,
diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.ts
index 65cd80c2..dcd92a6a 100644
--- a/src/bots/bot-turn.ts
+++ b/src/bots/bot-turn.ts
@@ -33,7 +33,7 @@ export interface BotTurnMail {
export type BotActivityEvent = {
botId: string;
jobId: string;
- kind: 'turn-start' | 'step' | 'tool' | 'turn-end' | 'thinking';
+ kind: 'turn-start' | 'step' | 'tool' | 'turn-end' | 'thinking' | 'queued';
/** Human-readable: "read_file ~/cookies" / "step 4 · 12.3k tok in". */
label: string;
detail?: string;
@@ -44,6 +44,14 @@ export type BotActivityEvent = {
* every consumer to reassemble state — tails render stateless instead). */
reasoningTail?: string;
textTail?: string;
+ /** Filled by the manager for the live feed: when, which bot by name, what started the run. */
+ at?: number;
+ botName?: string;
+ trigger?: string;
+ /** turn-start / queued: the full request (≤ 600 chars). */
+ prompt?: string;
+ /** turn-start / queued: the bot that sent the work, for crew mail. */
+ fromBot?: string;
};
/**
diff --git a/src/bots/bots2.test.ts b/src/bots/bots2.test.ts
index f0d4444f..f0081d3c 100644
--- a/src/bots/bots2.test.ts
+++ b/src/bots/bots2.test.ts
@@ -325,21 +325,21 @@ describe('asking the owner', () => {
});
let commandResult = '';
mockedGenerateText.mockImplementation((async (opts: Opts) => {
- commandResult = String(await opts.tools.run_command.execute({ command: 'echo approved | cat' }, {}));
+ commandResult = String(await opts.tools.run_command.execute({ command: 'printf approved | tee /dev/null' }, {}));
const r = await opts.tools.bot_report.execute({ summary: 'Ran it.' }, {});
opts.onStepFinish?.({ usage: { inputTokens: 1, outputTokens: 1 }, toolCalls: [{ toolName: 'bot_report', toolCallId: 'r' }], toolResults: [{ toolCallId: 'r', output: { type: 'text', value: r } }] });
return { text: '', finishReason: 'stop', usage: {} };
}) as never);
manager.enqueue('ops', { trigger: 'api', prompt: 'run the check' });
await idle(manager, 'ops');
- expect(asked).toEqual(['Run command: echo approved | cat']);
+ expect(asked).toEqual(['Run command: printf approved | tee /dev/null']);
expect(commandResult).toContain('approved');
// A chain is remembered exactly as written, never as a whole family of commands.
- expect(store.readPermissions('ops').autoApproveCommands).toEqual(['echo approved | cat']);
+ expect(store.readPermissions('ops').autoApproveCommands).toEqual(['printf approved | tee /dev/null']);
// The question was an inbox entry; answered, it's read.
const q = manager.inbox.list().find((e) => e.approvalId);
expect(q).toMatchObject({ kind: 'needs-you', read: true });
- expect(q!.title).toBe('Ops asks: Run command: echo approved | cat');
+ expect(q!.title).toBe('Ops asks: Run command: printf approved | tee /dev/null');
});
it('no answer in time is a no, and the run carries on without it', async () => {
@@ -350,7 +350,7 @@ describe('asking the owner', () => {
try {
let commandResult = '';
mockedGenerateText.mockImplementation((async (opts: Opts) => {
- const pending = opts.tools.run_command.execute({ command: 'echo nope | cat' }, {});
+ const pending = opts.tools.run_command.execute({ command: 'printf nope | tee /dev/null' }, {});
await vi.advanceTimersByTimeAsync(61_000);
commandResult = String(await pending);
const r = await opts.tools.bot_report_failure.execute({ reason: 'Not allowed to run the check.' }, {});
@@ -380,3 +380,29 @@ describe('durable grants', () => {
expect(durableGrant('MCP tool call\nServer: x')).toBeNull();
});
});
+
+describe('the live feed', () => {
+ it('a message from you: queued at once, then the run with its request, its steps and its end, kept for a screen opened later', async () => {
+ const { manager, store } = makeManager();
+ store.create({ id: 'w', name: 'Writer' });
+ mockedGenerateText.mockImplementation((async (opts: Opts) => {
+ const r = await opts.tools.bot_report.execute({ summary: 'Drafted.' }, {});
+ opts.onStepFinish?.({ usage: { inputTokens: 1, outputTokens: 1 }, toolCalls: [{ toolName: 'bot_report', toolCallId: 'r' }], toolResults: [{ toolCallId: 'r', output: { type: 'text', value: r } }] });
+ return { text: 'Drafted.', finishReason: 'stop', usage: {} };
+ }) as never);
+ const res = manager.enqueue('w', { trigger: 'api', prompt: 'Draft the post' });
+ manager.noteOwnerMessage('w', res.jobId, 'Draft the post');
+ await idle(manager, 'w');
+ const feed = manager.recentActivity({ bots: ['w'] });
+ const kinds = feed.map((e) => e.kind);
+ // An idle bot starts at once: no "queued" after its start.
+ expect(kinds[0]).toBe('turn-start');
+ expect(kinds).not.toContain('queued');
+ expect(kinds[kinds.length - 1]).toBe('turn-end');
+ const start = feed.find((e) => e.kind === 'turn-start')!;
+ expect(start).toMatchObject({ trigger: 'api', prompt: 'Draft the post', botName: 'Writer', jobId: res.jobId });
+ expect(feed.every((e) => typeof e.at === 'number')).toBe(true);
+ expect(manager.recentActivity({ bots: ['someone-else'] })).toEqual([]);
+ });
+});
+
diff --git a/src/capabilities/filesystem/send-file.ts b/src/capabilities/filesystem/send-file.ts
index 2e8eef41..5d8fe960 100644
--- a/src/capabilities/filesystem/send-file.ts
+++ b/src/capabilities/filesystem/send-file.ts
@@ -1,3 +1,4 @@
+import { checkVideo } from '../../media/blank-check.js';
import { tool, zodSchema } from 'ai';
import { z } from 'zod';
import { existsSync, statSync } from 'node:fs';
@@ -40,6 +41,12 @@ export function createSendFileTool(
return `Error: File too large (${Math.round(stat.size / (1024 * 1024))}MB). Maximum is 50MB.`;
}
+ // A video that never rendered (all black, or one still frame) isn't sent as if it worked.
+ const blank = await checkVideo(target).catch(() => null);
+ if (blank) {
+ return `Not sent: ${basename(resolved)} isn't a real video — ${blank.problem}. Fix the render (check that the composition actually draws and animates when captured), or tell the user plainly what went wrong. Don't send it or describe it as finished.`;
+ }
+
try {
await sendFile(target, channel);
const filename = basename(resolved);
diff --git a/src/capabilities/interaction/update-plan.test.ts b/src/capabilities/interaction/update-plan.test.ts
index 465b00e9..ec7cbd1c 100644
--- a/src/capabilities/interaction/update-plan.test.ts
+++ b/src/capabilities/interaction/update-plan.test.ts
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { createUpdatePlanTool } from './update-plan.js';
+import { createUpdatePlanTool, WORK_RULES } from './update-plan.js';
import { CLIChannel } from '../../channels/cli.js';
describe('update_plan tool', () => {
@@ -70,4 +70,21 @@ describe('CLIChannel.setPlanProgress normalization', () => {
channel.setPlanProgress('nope');
expect(channel.getTuiState().planProgress).toBeNull();
});
-});
\ No newline at end of file
+});
+
+const runPlan = (steps: Array<{ label: string; status: 'pending' | 'active' | 'done' }>) =>
+ (createUpdatePlanTool() as unknown as { execute: (i: unknown, o: unknown) => Promise<string> }).execute({ steps }, { toolCallId: 't', messages: [] });
+
+describe('update_plan: the working rules', () => {
+ it('a new plan of real work brings the working rules, once', async () => {
+ const fresh = await runPlan([{ label: 'a', status: 'active' }, { label: 'b', status: 'pending' }, { label: 'c', status: 'pending' }]);
+ expect(fresh).toContain(WORK_RULES);
+ const later = await runPlan([{ label: 'a', status: 'done' }, { label: 'b', status: 'active' }, { label: 'c', status: 'pending' }]);
+ expect(later).not.toContain(WORK_RULES);
+ expect(later).toMatch(/before your final reply/);
+ });
+ it('a short plan stays short', async () => {
+ expect(await runPlan([{ label: 'a', status: 'active' }])).not.toContain(WORK_RULES);
+ });
+});
+
diff --git a/src/capabilities/interaction/update-plan.ts b/src/capabilities/interaction/update-plan.ts
index 3a2a72ab..bab41dbe 100644
--- a/src/capabilities/interaction/update-plan.ts
+++ b/src/capabilities/interaction/update-plan.ts
@@ -9,6 +9,22 @@ import { z } from 'zod';
* working on it and `done` once finished. Display state flows through the
* agent's step observation, not through this tool's return value.
*/
+/**
+ * How multi-step work is done (Mercury Code's contract, for chat): sent with
+ * a new plan, where the model is about to do the work. Each line is a
+ * failure seen in real chats: a Node version error answered with a switch to
+ * another tool, a black MP4 announced as "pixel-perfect", six summary files
+ * nobody asked for.
+ */
+export const WORK_RULES = [
+ 'How to carry this out:',
+ '- Act, don\'t announce: a sentence about what you\'ll do next comes with the tool call that does it.',
+ '- A step is done when its result exists and you checked it (open the file, probe the video, look at the output). Report only what you checked.',
+ '- When a tool or requirement fails (a version, a missing dependency, a quota), fix the cause (another installed version, a flag, a setting) or ask the user. Never switch to a different method the user didn\'t ask for, and never present a workaround as the requested result.',
+ '- Don\'t create summaries, READMEs or reports nobody asked for.',
+ '- Mark each step done as you finish it; the user watches this checklist.',
+].join('\n');
+
export function createUpdatePlanTool() {
return tool({
description:
@@ -22,7 +38,11 @@ export function createUpdatePlanTool() {
execute: async ({ steps }) => {
const done = steps.filter((s) => s.status === 'done').length;
const active = steps.find((s) => s.status === 'active');
- return `Plan updated: ${steps.length} steps, ${done} done${active ? `, working on: ${active.label}` : ''}.`;
+ const open = steps.length - done;
+ const head = `Plan updated: ${steps.length} steps, ${done} done${active ? `, working on: ${active.label}` : ''}.`;
+ // A new plan of real multi-step work: the working rules Mercury Code uses, once.
+ if (done === 0 && steps.length >= 3) return `${head}\n\n${WORK_RULES}`;
+ return head + (open > 0 ? ' When a step is finished, mark it done; before your final reply, send the plan once more with every finished step done.' : '');
},
});
}
\ No newline at end of file
diff --git a/src/capabilities/permissions.test.ts b/src/capabilities/permissions.test.ts
index 604ac510..a488c2a0 100644
--- a/src/capabilities/permissions.test.ts
+++ b/src/capabilities/permissions.test.ts
@@ -110,6 +110,37 @@ describe('fail-closed execute scopes (bots)', () => {
});
});
+describe('bots reading where they may read: no question (real false alarms)', () => {
+ function bot() {
+ const permissions = new PermissionManager();
+ const m = permissions.getManifest();
+ m.capabilities.shell.enabled = true;
+ m.capabilities.filesystem.scopes = [{ path: '/tmp/fleet/_shared', read: true, write: false }, { path: '/tmp/fleet/me', read: true, write: true }];
+ permissions.setAutoApproveAll(false);
+ permissions.setFailClosed(true);
+ permissions.setCurrentContext('bot', 'worker');
+ const asked: string[] = [];
+ permissions.onAsk(async (q: string) => { asked.push(q); return "no"; });
+ return { permissions, asked };
+ }
+
+ it('ls / find with pipes and 2>/dev/null inside readable folders run without asking', async () => {
+ const { permissions, asked } = bot();
+ await expect(permissions.checkShellCommand('ls -lrt "/tmp/fleet/_shared/" 2>/dev/null | tail -20')).resolves.toMatchObject({ allowed: true });
+ await expect(permissions.checkShellCommand('find "/tmp/fleet/_shared" -name "*project*" -o -name "*curated*" 2>/dev/null')).resolves.toMatchObject({ allowed: true });
+ expect(asked).toEqual([]);
+ });
+
+ it('reading outside, writing, and running other things still ask', async () => {
+ const { permissions, asked } = bot();
+ await expect(permissions.checkShellCommand('find ~ -name "wrangler.toml" 2>/dev/null | head -3')).resolves.toMatchObject({ allowed: false });
+ await expect(permissions.checkShellCommand('ls /tmp/fleet/_shared > /tmp/elsewhere.txt')).resolves.toMatchObject({ allowed: false });
+ await expect(permissions.checkShellCommand('find /tmp/fleet/_shared -delete')).resolves.toMatchObject({ allowed: false });
+ expect(asked.length).toBeGreaterThan(0);
+ expect(asked.some((q) => /Write to file: \/(dev\/null|\*)?$/.test(q))).toBe(false);
+ });
+});
+
describe('fail-closed skill elevation', () => {
it('elevateForSkill is a no-op in fail-closed mode (skills never re-permission a bot)', async () => {
const permissions = new PermissionManager();
diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.ts
index 964fd5d0..ceda9487 100644
--- a/src/capabilities/permissions.ts
+++ b/src/capabilities/permissions.ts
@@ -5,6 +5,7 @@ import { join, resolve, sep, dirname, basename } from 'node:path';
import { homedir } from 'node:os';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import { getMercuryHome } from '../utils/config.js';
+import { isReadOnlySegment, shellPaths, stripHeredocs } from './shell-paths.js';
import { logger } from '../utils/logger.js';
import { redactSecrets } from '../utils/redact.js';
import { BLOCKED_COMMANDS } from './shell/blocklist.js';
@@ -1094,12 +1095,16 @@ export class PermissionManager {
}
if (shell.cwdOnly) {
- for (const segment of segments) {
- const hasPathTraversal = this.hasPathBeyondCwd(segment);
- if (hasPathTraversal) {
- const scopeCheck = await this.checkFsAccess(hasPathTraversal, 'write');
- if (!scopeCheck.allowed && !this.isExecuteScoped(hasPathTraversal)) {
- return { allowed: false, reason: `No permission to access ${hasPathTraversal}. Use approve_scope tool with path="${hasPathTraversal}" and mode="write" to request access.`, needsApproval: false };
+ // The files the command touches, read as the shell reads it (shell-paths.ts):
+ // heredoc bodies are data, quotes are honoured, /dev/null is not a file,
+ // and `ls dir` is a read, not a write.
+ for (const segment of splitShellSegments(stripHeredocs(trimmed))) {
+ for (const { path: raw, mode } of shellPaths(segment)) {
+ const target = resolve(cwd, raw.replace(/^~(?=\/|$)/, homedir()));
+ if (target.startsWith(this.cwd)) continue;
+ const scopeCheck = await this.checkFsAccess(target, mode);
+ if (!scopeCheck.allowed && !this.isExecuteScoped(target)) {
+ return { allowed: false, reason: `No permission to ${mode} ${target}. Use approve_scope tool with path="${target}" and mode="${mode}" to request access.`, needsApproval: false };
}
}
}
@@ -1158,9 +1163,17 @@ export class PermissionManager {
// approval-gated: an unscoped `npm install` mutates cwd and can reach
// anywhere via the network, so it is not covered by a directory grant.
if (this.failClosed) {
- const pathTokens = segments.flatMap(s => this.extractPathTokens(s));
- if (pathTokens.length > 0 && pathTokens.every(t => this.isExecuteScoped(t))) {
- logger.info({ cmd: trimmed, paths: pathTokens.length }, 'Shell command allowed by execute scope');
+ const pathSegments = splitShellSegments(stripHeredocs(trimmed));
+ const paths = pathSegments.flatMap((s) => shellPaths(s)).map((p) => ({ ...p, path: resolve(cwd, p.path.replace(/^~(?=\/|$)/, homedir())) }));
+ if (paths.length > 0 && paths.every((p) => this.isExecuteScoped(p.path))) {
+ logger.info({ cmd: trimmed, paths: paths.length }, 'Shell command allowed by execute scope');
+ return { allowed: true, needsApproval: false, lane: 'shell' };
+ }
+ // Only reading, only where it may read (`ls … | grep`, `find … 2>/dev/null | head`):
+ // no question. These used to ask the owner every time a pipe or redirect was used.
+ if (pathSegments.length > 0 && pathSegments.every(isReadOnlySegment)
+ && paths.every((p) => p.path.startsWith(this.cwd) || this.isWithinScope(this.canonicalizePath(p.path), 'read'))) {
+ logger.info({ cmd: trimmed, paths: paths.length }, 'Shell command allowed: read-only within granted scopes');
return { allowed: true, needsApproval: false, lane: 'shell' };
}
}
@@ -1451,38 +1464,12 @@ export class PermissionManager {
}
}
- private static readonly PATH_PATTERNS = [
- /(?:^|\s)(\/[^\s]+)/,
- /(?:^|\s)(~\/[^\s]+)/,
- /(?:^|\s)\.\.\/([^\s]+)/,
- /(?:^|\s)([A-Za-z]:\\[^\s]+)/,
- /(?:^|\s)(\\\\[^\s]+)/,
- ];
-
- /** Every path-like token in a command segment, resolved (tilde expanded). */
- private extractPathTokens(text: string): string[] {
- const out: string[] = [];
- for (const pattern of PermissionManager.PATH_PATTERNS) {
- for (const match of text.matchAll(new RegExp(pattern.source, 'g'))) {
- out.push(resolve(match[1].replace(/^~/, homedir())));
- }
- }
- return out;
- }
-
/** A resolved path is covered by an explicit execute grant. */
private isExecuteScoped(resolvedPath: string): boolean {
if (this.findScope(resolvedPath)?.execute) return true;
return this.findTempScope(resolvedPath)?.execute === true;
}
- private hasPathBeyondCwd(command: string): string | null {
- for (const candidate of this.extractPathTokens(command)) {
- if (!candidate.startsWith(this.cwd)) return candidate;
- }
- return null;
- }
-
private mergeDefaults(parsed: Partial<PermissionsManifest>): PermissionsManifest {
const mergeArray = (existing: string[] | undefined, defaults: string[]): string[] => {
if (!existing) return [...defaults];
diff --git a/src/capabilities/shell-paths.test.ts b/src/capabilities/shell-paths.test.ts
new file mode 100644
index 00000000..ccffb988
--- /dev/null
+++ b/src/capabilities/shell-paths.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest';
+import { isReadOnlySegment, shellPaths, shellWords, stripHeredocs } from './shell-paths.js';
+import { splitShellSegments } from './permissions.js';
+
+const all = (cmd: string) => splitShellSegments(stripHeredocs(cmd)).flatMap((s) => shellPaths(s));
+
+describe('the files a command touches (from real bot questions that were false alarms)', () => {
+ it('a heredoc body is data: no "/", "/*" or "/\\s+" files', () => {
+ const cmd = "cat > /bots/me/sandbox/load-data.js << 'ENDJS'\n// Load and transform project data\n/* block */\nconst re = /\\s+/g;\nENDJS";
+ expect(all(cmd)).toEqual([{ path: '/bots/me/sandbox/load-data.js', mode: 'write' }]);
+ });
+
+ it('a quoted path with a space stays one path', () => {
+ expect(all('cp "/Users/s/Documents/Mercury/opersource.fyi manger/README.md" "/bots/me/sandbox/README.md"')).toEqual([
+ { path: '/Users/s/Documents/Mercury/opersource.fyi manger/README.md', mode: 'write' },
+ { path: '/bots/me/sandbox/README.md', mode: 'write' },
+ ]);
+ });
+
+ it('/dev/null is not a file, and reading commands read', () => {
+ expect(all('curl -s -o /dev/null -w "%{http_code}" http://localhost:8080/blog/index.html')).toEqual([]);
+ expect(all('find "/Users/s/.mercury/bots/_shared" -name "*project*" 2>/dev/null')).toEqual([{ path: '/Users/s/.mercury/bots/_shared', mode: 'read' }]);
+ expect(all('ls -la "/Users/s/Documents/Mercury/" | grep -i opersource')).toEqual([{ path: '/Users/s/Documents/Mercury/', mode: 'read' }]);
+ });
+
+ it('writes stay writes: redirects, -o, find -delete, sed -i, unknown commands', () => {
+ expect(all('ls /a > /b/out.txt')).toEqual([{ path: '/a', mode: 'read' }, { path: '/b/out.txt', mode: 'write' }]);
+ expect(all('curl -o /tmp/x.zip https://e.com/x.zip')).toEqual([{ path: '/tmp/x.zip', mode: 'write' }]);
+ expect(all('find /a -name "*.log" -delete')).toEqual([{ path: '/a', mode: 'write' }]);
+ expect(all("sed -i 's/a/b/' /etc/hosts")).toEqual([{ path: '/etc/hosts', mode: 'write' }]);
+ expect(all('rm -rf /')).toEqual([{ path: '/', mode: 'write' }]);
+ expect(all("grep -r '/api/v1' /src")).toEqual([{ path: '/src', mode: 'read' }]);
+ });
+
+ it('words and redirects as the shell splits them', () => {
+ expect(shellWords('echo "a b" c\\ d 2>/dev/null')).toEqual(['echo', 'a b', 'c d', '2>', '/dev/null']);
+ });
+
+ it('read-only segments: quiet readers only, nothing written, nothing run', () => {
+ expect(isReadOnlySegment('ls -lh "/x/_shared/"')).toBe(true);
+ expect(isReadOnlySegment('find /x -name a -exec rm {} ;')).toBe(false);
+ expect(isReadOnlySegment('cat /x > /y')).toBe(false);
+ expect(isReadOnlySegment('cat $(echo /etc/passwd)')).toBe(false);
+ expect(isReadOnlySegment('curl https://e.com')).toBe(false);
+ });
+});
diff --git a/src/capabilities/shell-paths.ts b/src/capabilities/shell-paths.ts
new file mode 100644
index 00000000..20fc7d18
--- /dev/null
+++ b/src/capabilities/shell-paths.ts
@@ -0,0 +1,148 @@
+/**
+ * The files a shell command touches, read the way the shell reads it — for
+ * the "is this inside the folders I may use?" gate (cwdOnly; every bot).
+ *
+ * The old scan took every whitespace-preceded "/token" as a file to WRITE,
+ * which asked the owner about things that are not files at all:
+ * - the body of a heredoc (`cat > a.js << 'EOF' … // comment, /\s+/ …`)
+ * gave "/", "/*" and "/\s+";
+ * - a quoted path with a space ("…/opersource.fyi manger/README.md") was
+ * cut at the space;
+ * - `-o /dev/null` was a write to /dev/null;
+ * - `ls`, `find`, `cat` were writes.
+ * Here: heredoc bodies are data, quotes are honoured, device files are
+ * ignored, and each path is a read or a write by what the command does with
+ * it (a redirect target or `-o file` is a write; `ls dir` is a read; a
+ * command not known to be read-only keeps treating its paths as writes).
+ */
+
+export interface ShellPath { path: string; mode: 'read' | 'write' }
+
+/** Commands that only read the paths they are given (unless redirected, or with a writing flag). */
+const READ_ONLY = new Set(['ls', 'find', 'cat', 'head', 'tail', 'grep', 'egrep', 'fgrep', 'rg', 'wc', 'stat', 'file', 'du', 'df', 'tree', 'less', 'more',
+ 'diff', 'cmp', 'md5', 'md5sum', 'shasum', 'sha256sum', 'realpath', 'readlink', 'dirname', 'basename', 'test', '[', 'jq', 'sort', 'uniq', 'cut', 'awk',
+ 'sed', 'xxd', 'hexdump', 'strings', 'od', 'open', 'curl', 'wget', 'ping', 'echo', 'printf', 'sleep', 'which', 'type', 'pwd', 'date', 'git']);
+/** Their first non-option argument is a pattern or script, not a file. */
+const PATTERN_FIRST = new Set(['grep', 'egrep', 'fgrep', 'rg', 'sed', 'awk', 'jq']);
+/** Flags that make an otherwise read-only command write (or run something). */
+const WRITING_FLAGS: Record<string, RegExp> = {
+ find: /^-(delete|exec|execdir|ok|okdir|fprint\w*|fls)$/,
+ sed: /^(-i\S*|--in-place\S*)$/,
+ sort: /^(-o|--output\S*)$/,
+ git: /^(push|commit|checkout|reset|clean|rm|mv|apply|am|merge|rebase|pull|clone|init|add|stash|restore|switch|tag|branch|worktree)$/,
+};
+/** Options whose value is a file the command writes, per command (`-o` is "or" to find). */
+const OUTPUT_OPTION: Record<string, RegExp> = {
+ curl: /^(-o|--output)$/,
+ wget: /^(-O|--output-document|-o|--output-file|-a|--append-output)$/,
+ sort: /^(-o|--output)$/,
+};
+const DEVICE = /^\/dev\/(null|zero|stdin|stdout|stderr|tty|fd\/\d+|random|urandom)$/;
+
+/** Remove heredoc bodies: everything after `<<WORD` / `<<-'WORD'` up to the line that is WORD. */
+export function stripHeredocs(command: string): string {
+ const lines = command.split('\n');
+ const out: string[] = [];
+ let end: string | null = null;
+ let dash = false;
+ for (const line of lines) {
+ if (end !== null) {
+ if ((dash ? line.replace(/^\t+/, '') : line).trim() === end) end = null;
+ continue;
+ }
+ out.push(line);
+ const m = /<<(-?)\s*(['"]?)([A-Za-z_][\w-]*)\2/.exec(line);
+ if (m) { end = m[3]; dash = m[1] === '-'; }
+ }
+ return out.join('\n');
+}
+
+/** Shell words of one segment: quotes joined and removed, backslash escapes kept as the character. */
+export function shellWords(segment: string): string[] {
+ const words: string[] = [];
+ let cur = '';
+ let has = false;
+ let q: '"' | "'" | null = null;
+ for (let i = 0; i < segment.length; i++) {
+ const c = segment[i];
+ if (q) {
+ if (c === q) q = null;
+ else if (c === '\\' && q === '"' && i + 1 < segment.length) cur += segment[++i];
+ else cur += c;
+ continue;
+ }
+ if (c === "'" || c === '"') { q = c; has = true; continue; }
+ if (c === '\\' && i + 1 < segment.length) { cur += segment[++i]; has = true; continue; }
+ if (/\s/.test(c)) { if (has || cur) words.push(cur); cur = ''; has = false; continue; }
+ // A redirect operator is its own word: `2>/dev/null` → "2>", "/dev/null".
+ if (c === '>' || c === '<') {
+ let op = c;
+ while (segment[i + 1] === '>' || segment[i + 1] === '&') op += segment[++i];
+ if (/^\d+$/.test(cur) || cur === '&') { op = cur + op; cur = ''; has = false; }
+ if (has || cur) words.push(cur);
+ words.push(op);
+ cur = ''; has = false;
+ continue;
+ }
+ cur += c; has = true;
+ }
+ if (has || cur) words.push(cur);
+ return words;
+}
+
+const looksLikePath = (w: string) => w.startsWith('/') || w.startsWith('~/') || w === '~' || w.startsWith('../') || /^[A-Za-z]:\\/.test(w) || w.startsWith('\\\\');
+
+/** The paths in one command segment (after stripHeredocs and segment splitting), each a read or a write. */
+export function shellPaths(segment: string): ShellPath[] {
+ const words = shellWords(segment);
+ // Skip leading env assignments and wrappers ("FOO=1 sudo time cmd").
+ let k = 0;
+ while (k < words.length && (/^[A-Za-z_]\w*=/.test(words[k]) || ['sudo', 'time', 'nice', 'nohup', 'env', 'command', 'exec'].includes(words[k]))) k++;
+ const cmd = (words[k] ?? '').split('/').pop() ?? '';
+ const readOnly = READ_ONLY.has(cmd) && !words.slice(k + 1).some((w) => WRITING_FLAGS[cmd]?.test(w));
+ const out: ShellPath[] = [];
+ // A program run by its path ("/opt/x/run.sh") touches that path.
+ if (words[k] && looksLikePath(words[k])) out.push({ path: words[k], mode: 'write' });
+ let patternSkipped = !PATTERN_FIRST.has(cmd);
+ for (let i = k + 1; i < words.length; i++) {
+ const w = words[i];
+ if (/^\d*>{1,2}&?$|^&>{1,2}$/.test(w)) {
+ const target = words[++i];
+ if (target && !/^&?\d+$/.test(target) && !DEVICE.test(target)) out.push({ path: target, mode: 'write' });
+ continue;
+ }
+ if (/^\d*<{1,3}$/.test(w)) { const src = words[++i]; if (src && looksLikePath(src) && !DEVICE.test(src)) out.push({ path: src, mode: 'read' }); continue; }
+ if (OUTPUT_OPTION[cmd]?.test(w)) {
+ const target = words[++i];
+ if (target && !DEVICE.test(target) && target !== '-') out.push({ path: target, mode: 'write' });
+ continue;
+ }
+ if (w.startsWith('-')) {
+ // --output=/path
+ const eq = OUTPUT_OPTION[cmd] ? /^--(output|output-document|output-file)=(.+)$/.exec(w) : null;
+ if (eq && !DEVICE.test(eq[2])) out.push({ path: eq[2], mode: 'write' });
+ continue;
+ }
+ if (!patternSkipped) { patternSkipped = true; continue; }
+ if (!looksLikePath(w) || DEVICE.test(w)) continue;
+ out.push({ path: w, mode: readOnly ? 'read' : 'write' });
+ }
+ return out;
+}
+
+/** Read-only and unable to run anything else or reach the network: safe to run when every path is readable. */
+const QUIET_READERS = new Set(['ls', 'find', 'cat', 'head', 'tail', 'grep', 'egrep', 'fgrep', 'rg', 'wc', 'stat', 'file', 'du', 'tree', 'diff', 'cmp',
+ 'md5', 'md5sum', 'shasum', 'sha256sum', 'realpath', 'readlink', 'dirname', 'basename', 'sort', 'uniq', 'cut', 'jq', 'echo', 'printf', 'pwd', 'date', 'test', '[', 'which']);
+
+/**
+ * A segment that only reads: a quiet reader, no writing flag, no output
+ * redirect to a file, no command substitution. `2>/dev/null` is fine.
+ */
+export function isReadOnlySegment(segment: string): boolean {
+ if (/\$\(|`|<\(|>\(/.test(segment)) return false;
+ const words = shellWords(segment);
+ const cmd = (words[0] ?? '').split('/').pop() ?? '';
+ if (!QUIET_READERS.has(cmd)) return false;
+ if (words.slice(1).some((w) => WRITING_FLAGS[cmd]?.test(w))) return false;
+ return shellPaths(segment).every((p) => p.mode === 'read');
+}
diff --git a/src/capabilities/shell/run-command.test.ts b/src/capabilities/shell/run-command.test.ts
index 3dcef336..708bb421 100644
--- a/src/capabilities/shell/run-command.test.ts
+++ b/src/capabilities/shell/run-command.test.ts
@@ -67,3 +67,17 @@ describe('run_command executor (ROADMAP P1.8)', () => {
expect(arg).toBe('$HOME;echo pwned');
});
});
+
+describe('the shell finds the Node that runs Mercury first', () => {
+ it('an old system Node earlier on PATH no longer wins', async () => {
+ const { shellEnv } = await import('./run-command.js');
+ const env = shellEnv({ PATH: '/usr/bin:/usr/local/bin:/Users/me/.nvm/versions/node/v22/bin', HOME: '/Users/me' }, '/Users/me/.nvm/versions/node/v22/bin/node', 'darwin');
+ expect(env.PATH).toBe('/Users/me/.nvm/versions/node/v22/bin:/usr/bin:/usr/local/bin');
+ expect(env.HOME).toBe('/Users/me');
+ });
+ it('a standalone Mercury binary leaves PATH alone', async () => {
+ const { shellEnv } = await import('./run-command.js');
+ const src = { PATH: '/usr/bin' };
+ expect(shellEnv(src, '/Applications/Mercury.app/Contents/MacOS/mercury', 'darwin')).toBe(src);
+ });
+});
diff --git a/src/capabilities/shell/run-command.ts b/src/capabilities/shell/run-command.ts
index 66b247a2..c0497e42 100644
--- a/src/capabilities/shell/run-command.ts
+++ b/src/capabilities/shell/run-command.ts
@@ -1,7 +1,7 @@
import { tool, zodSchema } from 'ai';
import { z } from 'zod';
import { spawn, execFile, type ChildProcess } from 'node:child_process';
-import { resolve, isAbsolute } from 'node:path';
+import { basename, dirname, isAbsolute, resolve } from 'node:path';
import { existsSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
import type { PermissionManager } from '../permissions.js';
@@ -40,6 +40,7 @@ interface ExecOptions {
export function executeCommand(command: string, cwd: string, timeoutMs: number, options: ExecOptions = {}): Promise<ExecResult> {
return superviseChild(() => spawn(command, [], {
cwd,
+ env: shellEnv(),
shell: true,
stdio: ['pipe', 'pipe', 'pipe'],
// Its own process group, so a stop ends everything it started.
@@ -47,6 +48,23 @@ export function executeCommand(command: string, cwd: string, timeoutMs: number,
}), timeoutMs, options);
}
+/**
+ * The approval lane's environment: the owner's, with the Node that runs
+ * Mercury first on PATH. A service PATH often lists an old system Node
+ * (/usr/local/bin) before a newer one, so `node`, `npx` and every Node CLI
+ * (`hyperframes`, needing Node 22) ran on Node 18 and refused, and the
+ * model went round the failure instead of doing the task. Not when Mercury
+ * runs as a standalone binary (its executable isn't a Node).
+ */
+export function shellEnv(source: NodeJS.ProcessEnv = process.env, execPath: string = process.execPath, platform: NodeJS.Platform = process.platform): NodeJS.ProcessEnv {
+ const exe = basename(execPath).toLowerCase();
+ if (exe !== 'node' && exe !== 'node.exe') return source;
+ const sep = platform === 'win32' ? ';' : ':';
+ const own = dirname(execPath);
+ const rest = (source.PATH ?? source.Path ?? '').split(sep).filter((d) => d && d !== own);
+ return { ...source, PATH: [own, ...rest].join(sep) };
+}
+
/**
* Argv-lane executor: `execFile(absBinary, args)` with no shell and a
* minimal environment (pinned PATH, no secrets). Used only for commands the
diff --git a/src/channels/cli.ts b/src/channels/cli.ts
index 90b8a7c5..2cba6456 100644
--- a/src/channels/cli.ts
+++ b/src/channels/cli.ts
@@ -1763,6 +1763,11 @@ export class CLIChannel extends BaseChannel {
* Replace the live plan checklist (from the update_plan tool). Validates
* defensively — malformed model output must never break the TUI.
*/
+ /** The checklist as the terminal shows it now (null: none). */
+ currentPlanProgress(): PlanStep[] | null {
+ return this.state.planProgress ? this.state.planProgress.map((s) => ({ ...s })) : null;
+ }
+
setPlanProgress(steps: unknown): void {
if (!Array.isArray(steps)) return;
const normalized: PlanStep[] = [];
diff --git a/src/channels/web.ts b/src/channels/web.ts
index 16995edc..887e64a5 100644
--- a/src/channels/web.ts
+++ b/src/channels/web.ts
@@ -1,5 +1,5 @@
import { BaseChannel } from './base.js';
-import { normalizePlan, PlanStore } from '../core/plan.js';
+import { normalizePlan, PlanStore, type PlanState } from '../core/plan.js';
import type { ChannelMessage, ChannelAttachment } from '../types/channel.js';
import { logger } from '../utils/logger.js';
import { randomUUID } from 'node:crypto';
@@ -613,11 +613,11 @@ export class WebChannel extends BaseChannel {
plans = new PlanStore();
/** The model updated its plan checklist: keep it with the conversation and show it live. */
- sendPlan(steps: unknown, targetId?: string): void {
+ sendPlan(steps: unknown, targetId?: string, state?: PlanState): void {
const normalized = normalizePlan(steps);
if (normalized.length === 0) return;
- const plan = targetId ? this.plans.set(targetId, normalized) : { steps: normalized, updatedAt: Date.now() };
- this.broadcast({ type: 'plan', data: { steps: plan.steps, updatedAt: plan.updatedAt, targetId } });
+ const plan = targetId ? this.plans.set(targetId, normalized, Date.now(), state) : { steps: normalized, updatedAt: Date.now(), ...(state ? { state } : {}) };
+ this.broadcast({ type: 'plan', data: { steps: plan.steps, updatedAt: plan.updatedAt, targetId, ...(plan.state ? { state: plan.state } : {}) } });
}
/**
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 0c679060..0472552d 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -54,6 +54,7 @@ import { WebChannel } from '../channels/web.js';
import type { ArrowSelectOption } from '../utils/arrow-select.js';
import { setAskUserHandler } from '../capabilities/interaction/ask-user.js';
import { classifyResearchIntent } from './research-intent.js';
+import { settlePlan } from './plan.js';
import { closePlan, coverageSection, parsePlanLines, reportBody, reportFileName, RESEARCH_PLAN_SYSTEM, RESEARCH_WRITE_SYSTEM, sourcesAppendix, unansweredFrom, type ResearchRun } from './research-run.js';
import type { SpotifyClient } from '../spotify/client.js';
import { fallbackSessionTitle, isThinOpening, normalizeGeneratedSessionTitle, SessionResolutionError, type SessionRepository } from '../sessions/index.js';
@@ -99,7 +100,7 @@ import { compactConversation } from './memory-governor.js';
import { writeCrashFlag } from './crash-flag.js';
import { summarizeSilentTurn, type TurnAction } from './silent-turn.js';
import { classifyStreamCompletion, isLengthTruncation, truncationContinuationPrompt, toolTruncationContinuationPrompt } from './stream-completion.js';
-import { MAX_EXECUTE_CONTINUATIONS, MAX_VERIFICATION_CONTINUATIONS, executeContinuationPrompt, shouldForceExecuteContinuation, isFailedToolResult, shouldRequireVerification, isVerificationOutputOk, verificationPrompt, responseAsksUser, EXECUTE_MUTATING_TOOLS, VERIFICATION_COMMAND_PATTERN, wakeUpPrompt } from './execute-guard.js';
+import { MAX_EXECUTE_CONTINUATIONS, MAX_VERIFICATION_CONTINUATIONS, executeContinuationPrompt, shouldForceExecuteContinuation, isFailedToolResult, shouldRequireVerification, isVerificationOutputOk, verificationPrompt, responseAsksUser, EXECUTE_MUTATING_TOOLS, VERIFICATION_COMMAND_PATTERN, wakeUpPrompt, chatNeedsCheck, chatCheckPrompt } from './execute-guard.js';
import { classifyTurnEnd, stepsExhaustedPrompt, STEPS_PAUSED_BANNER, WORK_NOT_STARTED_BANNER, VERIFICATION_FAILED_BANNER, type LoopEndCause } from './completion-verdict.js';
import { HISTORY_TOKEN_BUDGET, HISTORY_TOKEN_BUDGET_SAVER, TOOL_TRACE_KIND, selectHistoryWindow, buildModelHistory, withReasoningParts, formatToolTrace, formatToolTraceLine, summarizeToolArgs, summarizeToolResult, detectRepetitionLoop } from './context-window.js';
import { buildSystemPrompt as assembleSystemPrompt, buildSystemPromptParts, budgetContext, type SystemPromptInputs } from './system-prompt.js';
@@ -3109,9 +3110,33 @@ export class Agent {
} catch { /* telling about artifacts must never break a turn */ }
}
+ /** End of a turn: settle the chat's plan (settlePlan) and show it settled. Never throws. */
+ private settleTurnPlan(msg: ChannelMessage, outcome: 'completed' | 'stopped' | 'failed', turnStartedAt: number): void {
+ try {
+ // A plan from an earlier turn (a question asked in between) is left as it is.
+ if ((this.planTouchedAt.get(msg.channelId) ?? 0) < turnStartedAt) return;
+ this.planTouchedAt.delete(msg.channelId);
+ const channel = this.channels.getChannelForMessage(msg);
+ if (channel instanceof WebChannel) {
+ const plan = channel.plans.get(msg.channelId);
+ if (!plan || plan.state) return;
+ const settled = settlePlan(plan.steps, outcome);
+ if (settled) channel.sendPlan(settled.steps, msg.channelId, settled.state);
+ } else if (channel instanceof CLIChannel) {
+ const steps = channel.currentPlanProgress();
+ const settled = steps ? settlePlan(steps, outcome) : null;
+ if (settled) channel.setPlanProgress(settled.steps);
+ }
+ } catch { /* the plan display must never break a turn */ }
+ }
+
+ /** When each chat's plan was last updated by the model: only the turn that worked on a plan settles it. */
+ private planTouchedAt = new Map<string, number>();
+
private maybeRecordPlanProgress(channel: unknown, toolName: string, input: unknown, targetId?: string): void {
try {
if (toolName !== 'update_plan') return;
+ if (targetId) this.planTouchedAt.set(targetId, Date.now());
const steps = (input as { steps?: Parameters<CLIChannel['setPlanProgress']>[0] } | null)?.steps;
if (channel instanceof CLIChannel) channel.setPlanProgress(steps);
else {
@@ -3594,6 +3619,9 @@ export class Agent {
? this.researchMode.beginRun(msg.channelId, msg.content, this.saverMode.adjustMaxSteps(MAX_STEPS) * 3)
: null;
if (researchRun) this.emitResearch(msg, researchRun);
+ // How the turn ended, for the plan it leaves behind (settlePlan).
+ let turnFailed = false;
+ const turnStartedAt = Date.now();
if (!isSlashCommand) raiseTurnIndicator();
const stopHeartbeat = isSlashCommand ? () => {} : this.startForegroundHeartbeat(msg);
// Memory: the turn governor watches the heap for the whole process (one
@@ -5272,19 +5300,24 @@ export class Agent {
// (no build/test/typecheck ran clean after the last edit). Force one
// bounded evidence round. Execute mode only: in plain chat "write my
// notes to notes.md" must not trigger "running the build/tests now".
+ // Chat doing real multi-step work (it made a plan this turn) and producing something:
+ // Mercury Code's rule, adapted — look at the result before calling it done.
+ const chatCheck = !this.programmingMode.isExecute()
+ && (this.planTouchedAt.get(msg.channelId) ?? 0) >= turnStartedAt
+ && chatNeedsCheck(executeToolSucceeded)
+ && !responseAsksUser(result.text || '');
if (
!loopAbortController.signal.aborted
&& turnEnd() === 'text-stop'
- && this.programmingMode.isExecute()
&& !this.capabilities.areToolsDisabled()
&& verificationContinuations < MAX_VERIFICATION_CONTINUATIONS
- && shouldRequireVerification({
+ && (chatCheck || (this.programmingMode.isExecute() && shouldRequireVerification({
taskText: msg.content,
hasApprovedPlan: this.programmingMode.getLastPlan() != null,
commandsRun: executeCommandsRun,
toolsSucceeded: executeToolSucceeded,
verifiedOk: verifiedAfterLastMutation(),
- })
+ })))
) {
verificationContinuations++;
logger.warn(
@@ -5295,13 +5328,13 @@ export class Agent {
this.pushLiveActivity('Verifying the work', 'verification gate');
if (channel && msg.channelType !== 'internal') {
await this.sendProgressNote(channel,
- 'Checking my work before I call it done — running the build/tests now...',
+ chatCheck ? 'Checking the result before I call it done...' : 'Checking my work before I call it done — running the build/tests now...',
msg.channelId,
).catch((e) => logger.warn({ e }, 'channel send failed'));
}
const verifyText = (result.text || '').trim();
if (verifyText && verifyText !== '(no text response)') messages.push({ role: 'assistant', content: verifyText });
- messages.push({ role: 'user', content: verificationPrompt(msg.content) });
+ messages.push({ role: 'user', content: chatCheck ? chatCheckPrompt(msg.content) : verificationPrompt(msg.content) });
const verifyProvider = usedProvider
? (providersForAttempt.find((p) => p.name === usedProvider!.name && p.getModel() === usedProvider!.model) ?? providersForAttempt[0])
: providersForAttempt[0];
@@ -5616,6 +5649,7 @@ export class Agent {
this.lifecycle.transition('idle');
} catch (err) {
+ turnFailed = true;
logger.error({ err }, 'Error handling message');
const ledgerEntry = this.currentWorkKey ? this.workLedger.get(this.currentWorkKey) : undefined;
if (this.currentWorkKey) {
@@ -5682,6 +5716,8 @@ export class Agent {
this.emitResearch(msg, researchRun);
this.researchMode.endRun(msg.channelId);
}
+ // The plan as this turn leaves it: a forgotten last tick done, open steps paused or stopped.
+ if (!researchRun) this.settleTurnPlan(msg, this.turnCancelled() ? 'stopped' : turnFailed ? 'failed' : 'completed', turnStartedAt);
stallWatchdog.stop();
stopHeartbeat();
this.finalizeChannelTask(msg);
diff --git a/src/core/execute-guard.test.ts b/src/core/execute-guard.test.ts
index e6d891e6..4fe56a28 100644
--- a/src/core/execute-guard.test.ts
+++ b/src/core/execute-guard.test.ts
@@ -340,3 +340,14 @@ describe('wakeUpPrompt — the final automatic attempt', () => {
expect(prompt).toContain('3D world');
});
});
+
+describe('chat: check before done', () => {
+ it('only when the turn made something', async () => {
+ const { chatNeedsCheck, chatCheckPrompt } = await import('./execute-guard.js');
+ expect(chatNeedsCheck(new Map([['run_command', true]]))).toBe(true);
+ expect(chatNeedsCheck(new Map([['run_command', false], ['web_search', true]]))).toBe(false);
+ expect(chatNeedsCheck(new Map([['read_file', true]]))).toBe(false);
+ expect(chatCheckPrompt('make an intro video')).toMatch(/probe a video/);
+ expect(chatCheckPrompt()).toMatch(/do not present a workaround/);
+ });
+});
diff --git a/src/core/execute-guard.ts b/src/core/execute-guard.ts
index 133af569..656b021d 100644
--- a/src/core/execute-guard.ts
+++ b/src/core/execute-guard.ts
@@ -268,4 +268,28 @@ export function wakeUpPrompt(taskHint?: string): string {
task,
'Your very next response MUST begin with a mutating tool call — create_file, write_file, edit_file, or run_command. ZERO prose before the call. Pick the smallest real piece of the task (even scaffolding or a stub) and DO it. Only after the call lands may you write text.',
].join(' ');
-}
\ No newline at end of file
+}
+
+/** Tools whose success means a chat turn produced something worth checking. */
+const CHAT_DELIVERABLE_TOOLS: ReadonlySet<string> = new Set(['create_file', 'write_file', 'edit_file', 'run_command', 'send_file']);
+
+/** A planned chat turn made something (a file, a render, a sent file): check it before calling it done. */
+export function chatNeedsCheck(toolsSucceeded: ReadonlyMap<string, boolean>): boolean {
+ return [...toolsSucceeded].some(([tool, ok]) => ok && CHAT_DELIVERABLE_TOOLS.has(tool));
+}
+
+/**
+ * The chat version of the verification round: not "run the tests" but "look
+ * at what you made". It exists because a chat could make a black MP4 with
+ * ffmpeg, send it, and announce "Video created & sent! pixel-perfect".
+ */
+export function chatCheckPrompt(taskHint?: string): string {
+ const hint = taskHint?.trim();
+ return [
+ '[SYSTEM: CHECK BEFORE DONE] Before you tell the user this is finished, look at what you actually produced.',
+ hint ? `The request: "${hint.slice(0, 200)}".` : '',
+ 'For each deliverable: confirm it exists and is what was asked — open or read the file, probe a video (e.g. ffprobe, or extract a frame and look), check a page renders, check sizes and durations.',
+ 'If it is wrong or incomplete, fix it now. If you could not do what was asked the way it was asked (a tool failed, a requirement is missing), say so plainly and what is needed — do not present a workaround or a different method as the result.',
+ 'Then reply with only what you verified.',
+ ].filter(Boolean).join(' ');
+}
diff --git a/src/core/plan.test.ts b/src/core/plan.test.ts
index 21b3c9ca..3229dc91 100644
--- a/src/core/plan.test.ts
+++ b/src/core/plan.test.ts
@@ -2,7 +2,7 @@ import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
-import { normalizePlan, PlanStore } from './plan.js';
+import { normalizePlan, PlanStore, settlePlan, type PlanStep } from './plan.js';
describe('plan checklist', () => {
it('cleans what the model sends: unknown statuses and duplicates dropped, one active step', () => {
@@ -31,3 +31,33 @@ describe('plan checklist', () => {
expect(b.get('other')).toBeNull();
});
});
+
+const plan = (marks: string): PlanStep[] => [...marks].map((m, i) => ({ label: `step ${i + 1}`, status: m === '✓' ? 'done' : m === '◐' ? 'active' : 'pending' }));
+const marks = (steps: PlanStep[]) => steps.map((s) => (s.status === 'done' ? '✓' : s.status === 'active' ? '◐' : '○')).join('');
+
+describe('the plan a turn leaves behind', () => {
+ it('the work is done and only the last tick was forgotten: done', () => {
+ expect(marks(settlePlan(plan('✓✓✓✓◐'), 'completed')!.steps)).toBe('✓✓✓✓✓');
+ expect(settlePlan(plan('✓✓✓✓◐'), 'completed')!.state).toBeUndefined();
+ expect(marks(settlePlan(plan('✓✓✓○'), 'completed')!.steps)).toBe('✓✓✓✓');
+ });
+
+ it('a reply with several steps open: paused at the first open one', () => {
+ const r = settlePlan(plan('✓◐○○○'), 'completed')!;
+ expect(r.state).toBe('paused');
+ expect(marks(r.steps)).toBe('✓◐○○○');
+ expect(marks(settlePlan(plan('◐○○'), 'completed')!.steps)).toBe('◐○○');
+ });
+
+ it('stopped or failed: stopped, never a guessed tick', () => {
+ expect(settlePlan(plan('✓✓✓◐'), 'stopped')).toMatchObject({ state: 'stopped' });
+ expect(marks(settlePlan(plan('✓✓✓◐'), 'stopped')!.steps)).toBe('✓✓✓◐');
+ expect(settlePlan(plan('✓○◐'), 'failed')).toMatchObject({ state: 'stopped' });
+ expect(marks(settlePlan(plan('✓○◐'), 'failed')!.steps)).toBe('✓◐○');
+ });
+
+ it('nothing to do for a finished plan or none', () => {
+ expect(settlePlan(plan('✓✓✓'), 'completed')).toBeNull();
+ expect(settlePlan([], 'stopped')).toBeNull();
+ });
+});
diff --git a/src/core/plan.ts b/src/core/plan.ts
index 10501be3..24f3209d 100644
--- a/src/core/plan.ts
+++ b/src/core/plan.ts
@@ -11,7 +11,34 @@ import { getMercuryHome } from '../utils/config.js';
export type PlanStatus = 'pending' | 'active' | 'done';
export interface PlanStep { label: string; status: PlanStatus }
-export interface Plan { steps: PlanStep[]; updatedAt: number }
+/**
+ * How a plan stands once the turn that worked on it ended without finishing
+ * it: paused (the reply came, steps are still open; continues when you ask)
+ * or stopped (you stopped the turn, or it failed). Absent while it is worked on.
+ */
+export type PlanState = 'paused' | 'stopped';
+export interface Plan { steps: PlanStep[]; updatedAt: number; state?: PlanState }
+
+/**
+ * A plan as the turn left it. Models often finish the work and forget to
+ * tick the last step (✓✓✓✓◐ while the answer is already there), and a
+ * stopped turn left its step "in progress" for good. So when a turn ends:
+ * - completed, one step open and every step before it done → that step is
+ * done (the reply is the last step);
+ * - completed, more open → paused, at the first open step;
+ * - stopped or failed → stopped, at the first open step.
+ * Null when there's nothing to change (no plan, or already all done).
+ */
+export function settlePlan(steps: PlanStep[], outcome: 'completed' | 'stopped' | 'failed'): { steps: PlanStep[]; state?: PlanState } | null {
+ if (!steps.length || steps.every((s) => s.status === 'done')) return null;
+ const open = steps.map((s, i) => (s.status === 'done' ? -1 : i)).filter((i) => i >= 0);
+ if (outcome === 'completed' && open.length === 1 && open[0] === steps.length - 1) {
+ return { steps: steps.map((s) => ({ ...s, status: 'done' as const })) };
+ }
+ // Nothing is "in progress" once the turn is over: the first open step is where it stopped.
+ const at = open[0];
+ return { steps: steps.map((s, i) => (s.status === 'done' ? s : { ...s, status: i === at ? 'active' as const : 'pending' as const })), state: outcome === 'completed' ? 'paused' : 'stopped' };
+}
/** Clean up what the model sent: labels trimmed and unique, known statuses, at most one active step. */
export function normalizePlan(steps: unknown): PlanStep[] {
@@ -42,7 +69,7 @@ export class PlanStore {
try {
if (!existsSync(this.file)) return;
const raw = JSON.parse(readFileSync(this.file, 'utf-8')) as Record<string, Plan>;
- for (const [k, v] of Object.entries(raw)) if (Array.isArray(v?.steps)) this.plans.set(k, { steps: normalizePlan(v.steps), updatedAt: Number(v.updatedAt) || 0 });
+ for (const [k, v] of Object.entries(raw)) if (Array.isArray(v?.steps)) this.plans.set(k, { steps: normalizePlan(v.steps), updatedAt: Number(v.updatedAt) || 0, ...(v.state === 'paused' || v.state === 'stopped' ? { state: v.state } : {}) });
} catch { /* a broken file starts fresh */ }
}
@@ -51,9 +78,9 @@ export class PlanStore {
return this.plans.get(id) ?? null;
}
- set(id: string, steps: PlanStep[], now = Date.now()): Plan {
+ set(id: string, steps: PlanStep[], now = Date.now(), state?: PlanState): Plan {
this.load();
- const plan = { steps, updatedAt: now };
+ const plan: Plan = { steps, updatedAt: now, ...(state ? { state } : {}) };
this.plans.delete(id);
this.plans.set(id, plan);
while (this.plans.size > MAX_KEPT) this.plans.delete(this.plans.keys().next().value as string);
diff --git a/src/core/system-prompt.ts b/src/core/system-prompt.ts
index cd8df8a2..178fc91c 100644
--- a/src/core/system-prompt.ts
+++ b/src/core/system-prompt.ts
@@ -57,6 +57,7 @@ export const CHAT_WORK_CONTRACT = `**How you work:**
- When the user asks for something to be done, do it with your tools; don't describe how they could do it.
- First work out the end result they want, then the fastest reliable way to get there (an existing command, library or service beats manual steps).
- For real multi-step work (three or more distinct steps: research across sources, building or changing several things), keep a short plan with update_plan and work through it, marking each step as you go. Never make a plan for a question, a chat, or a quick single action.
+- Say something is done only after you checked it exists and works; if it doesn't, say so plainly. Don't write summary or README files nobody asked for.
- Report what you did and what you checked, briefly. If something failed or you could not confirm it, say so plainly.
- Need the user to decide before you go on — yes or no, or which of a few options? Ask with ask_user, so they pick with the arrow keys instead of typing an answer. Only a question that needs free text (a name, a path, a date) is asked in words.
- Plain questions and conversation don't need tools: just answer.`;
diff --git a/src/index.ts b/src/index.ts
index 5625fa76..93f81120 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -2897,7 +2897,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
// label is updated inside the manager itself.
const botCliChannel = channels.get('cli');
bot.onBotActivity((ev) => {
- if (botCliChannel instanceof CLIChannel) botCliChannel.setBotLiveActivity(ev.botId, ev);
+ if (botCliChannel instanceof CLIChannel && ev.kind !== 'queued') botCliChannel.setBotLiveActivity(ev.botId, { ...ev, kind: ev.kind });
webChannel.broadcastBotActivity(ev);
});
if (config.bots?.webhookSecret) {
diff --git a/src/media/blank-check.test.ts b/src/media/blank-check.test.ts
new file mode 100644
index 00000000..ba474dfc
--- /dev/null
+++ b/src/media/blank-check.test.ts
@@ -0,0 +1,29 @@
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterAll, describe, expect, it } from 'vitest';
+import { checkVideo, judgeBlank } from './blank-check.js';
+
+const hasFfmpeg = (() => { try { execFileSync('ffmpeg', ['-version'], { stdio: 'ignore' }); return true; } catch { return false; } })();
+const dir = mkdtempSync(join(tmpdir(), 'mercury-blank-'));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+const make = (name: string, src: string) => {
+ const file = join(dir, name);
+ execFileSync('ffmpeg', ['-y', '-loglevel', 'error', '-f', 'lavfi', '-i', src, '-f', 'lavfi', '-i', 'sine=frequency=440:duration=5', '-t', '5', '-pix_fmt', 'yuv420p', '-shortest', file]);
+ return file;
+};
+
+describe('a video that never rendered is caught', () => {
+ it('judges from the detector log', () => {
+ expect(judgeBlank('Duration: 00:00:15.00, start\nblack_start:0 black_end:15 black_duration:15')?.problem).toMatch(/black for 100%/);
+ expect(judgeBlank('Duration: 00:00:10.00, start\nfreeze_start: 0\nlavfi.freezedetect.freeze_duration: 9.9')?.problem).toMatch(/nothing moves/);
+ expect(judgeBlank('Duration: 00:00:10.00, start\nblack_duration:2')).toBeNull();
+ });
+
+ it.skipIf(!hasFfmpeg)('black with sound, and one still colour, are refused; a moving picture passes', async () => {
+ expect((await checkVideo(make('black.mp4', 'color=c=black:s=320x240:d=5')))?.problem).toMatch(/black/);
+ expect((await checkVideo(make('still.mp4', 'color=c=0x1a2b4c:s=320x240:d=5')))?.problem).toMatch(/nothing moves/);
+ expect(await checkVideo(make('moving.mp4', 'testsrc=s=320x240:d=5'))).toBeNull();
+ }, 60_000);
+});
diff --git a/src/media/blank-check.ts b/src/media/blank-check.ts
new file mode 100644
index 00000000..d9c238fc
--- /dev/null
+++ b/src/media/blank-check.ts
@@ -0,0 +1,72 @@
+/**
+ * Is this video actually a video? A render that failed quietly still makes
+ * an MP4: all black frames with the soundtrack, or one still frame for its
+ * whole length (HTML whose animation never ran). Sent as is, the owner gets
+ * "Video created!" and a black screen. This looks before it goes out, with
+ * ffmpeg's own detectors (blackdetect, freezedetect), in one pass.
+ *
+ * Fails open: no ffmpeg, an unreadable file, or a probe that takes too long
+ * says nothing, and the file is sent as before.
+ */
+import { execFile } from 'node:child_process';
+
+export interface BlankVerdict {
+ /** Why it isn't a real video, in words for the model and the owner. */
+ problem: string;
+}
+
+const VIDEO_EXT = /\.(mp4|mov|m4v|webm|mkv|avi)$/i;
+
+function run(file: string, args: string[], timeoutMs: number): Promise<{ stdout: string; stderr: string } | null> {
+ return new Promise((resolve) => {
+ execFile(file, args, { timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {
+ if (err && !stderr) return resolve(null);
+ resolve({ stdout: String(stdout), stderr: String(stderr) });
+ });
+ });
+}
+
+/** Seconds covered by detector lines like "black_duration:1.5" / "freeze_duration: 3.2". */
+export function coveredSeconds(log: string, key: 'black_duration' | 'freeze_duration'): number {
+ let total = 0;
+ for (const m of log.matchAll(new RegExp(`${key}:\\s*([\\d.]+)`, 'g'))) total += Number(m[1]) || 0;
+ return total;
+}
+
+/** A video's length from ffmpeg's banner ("Duration: 00:00:15.04"). */
+export function durationOf(log: string): number {
+ const m = /Duration:\s*(\d+):(\d+):([\d.]+)/.exec(log);
+ return m ? Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]) : 0;
+}
+
+/** The verdict from ffmpeg's log: black ≥ 90% of the length, or no motion for ≥ 95% of it. */
+export function judgeBlank(log: string): BlankVerdict | null {
+ const length = durationOf(log);
+ if (length < 1) return null;
+ const black = coveredSeconds(log, 'black_duration');
+ if (black >= length * 0.9) return { problem: `it is black for ${Math.round((black / length) * 100)}% of its ${length.toFixed(1)}s: the picture never rendered (only the sound did)` };
+ let frozen = coveredSeconds(log, 'freeze_duration');
+ // A freeze that lasts to the end is reported with a start and no end.
+ const starts = [...log.matchAll(/freeze_start:\s*([\d.]+)/g)].map((m) => Number(m[1]));
+ const ends = [...log.matchAll(/freeze_end:\s*([\d.]+)/g)].length;
+ if (starts.length > ends) frozen += Math.max(0, length - starts[starts.length - 1]);
+ if (length >= 3 && frozen >= length * 0.95) return { problem: `nothing moves in it: the same frame for ${frozen.toFixed(1)} of its ${length.toFixed(1)}s, so the animation never ran` };
+ return null;
+}
+
+export async function checkVideo(path: string, opts: { ffmpeg?: string; timeoutMs?: number } = {}): Promise<BlankVerdict | null> {
+ if (!VIDEO_EXT.test(path)) return null;
+ const out = await run(opts.ffmpeg ?? 'ffmpeg', [
+ '-hide_banner', '-nostdin', '-i', path, '-t', '120', '-an',
+ '-vf', 'blackdetect=d=0.2:pix_th=0.08,freezedetect=n=0.003:d=1',
+ '-f', 'null', '-',
+ ], opts.timeoutMs ?? 30_000);
+ if (!out) return null;
+ // The banner (with Duration) comes without -hide_banner's input section suppressed: ask once more if missing.
+ let log = out.stderr;
+ if (!durationOf(log)) {
+ const probe = await run(opts.ffmpeg ?? 'ffmpeg', ['-nostdin', '-i', path], 10_000);
+ log = `${probe?.stderr ?? ''}\n${log}`;
+ }
+ return judgeBlank(log);
+}
diff --git a/src/web/api/bots.ts b/src/web/api/bots.ts
index 5f06cb8c..a051a31d 100644
--- a/src/web/api/bots.ts
+++ b/src/web/api/bots.ts
@@ -37,6 +37,15 @@ app.get('/api/bots', (c: any) => {
// The owner's inbox (Bots 2.0): results, reported failures and runs that need
// the owner, newest first. `?unread=1` for unread only, `?bot=<id>` for one bot.
+// The live feed's recent history (the stream sends what happens next).
+app.get('/api/bots/activity', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const bots = String(c.req.query('bots') ?? '').split(',').map((s: string) => s.trim()).filter(Boolean);
+ const since = Number(c.req.query('since') ?? 0) || 0;
+ const limit = Number(c.req.query('limit') ?? 400) || 400;
+ return c.json({ events: botManager.recentActivity({ bots, since, limit }), now: Date.now() });
+});
+
app.get('/api/bots/inbox', (c: Context) => {
if (!botManager) return c.json({ entries: [], unread: 0, available: false });
const limit = Math.max(1, Math.min(500, Number(c.req.query('limit')) || 100));
@@ -369,6 +378,7 @@ app.post('/api/bots/:id/message', async (c: any) => {
for (const a of upload.attachments) rmSync(a.path, { force: true });
return c.json({ accepted: false, reasonCode: result.reasonCode }, 409);
}
+ if (!result.duplicated) botManager.noteOwnerMessage(id, result.jobId, message || '(attachments)');
if (result.duplicated) {
// A retry of a job already queued: that job holds its own copies of the files.
for (const a of upload.attachments) rmSync(a.path, { force: true });