Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(bots): stop/start/run lifecycle + close the bot-thread chat leaks
Salman Qureshif2223a7e43a2
diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.tsindex bd1c92cc..1f400c26 100644--- a/src/bots/bot-manager.test.ts+++ b/src/bots/bot-manager.test.ts@@ -103,16 +103,32 @@ describe('BotManager queue + turn lifecycle', () => {expect(records[0].state).toBe('completed');});// Hermes/OpenClaw contract: the full result lands in the bot's OWN thread;- // the requesting session gets at most a one-line pointer.+ // the CLI session that asked gets NOTHING — no pointer into the main chat+ // (a delayed routine/retry run would otherwise print into whatever+ // session is open days later — the thread leak).await vi.waitFor(() => {expect(delivered.some(d => d.target === 'bot:researcher' && d.message.includes('done'))).toBe(true);- expect(delivered.some(d => d.message.includes('finished its task') && d.message.includes('/bots open researcher'))).toBe(true);});+ expect(delivered.every(d => d.target === 'bot:researcher')).toBe(true);+ expect(delivered.some(d => d.message.includes('finished its task'))).toBe(false);const summary = manager.getStatusSummaries().find(s => s.id === 'researcher');expect(summary?.state).toBe('idle');expect(summary?.lastRunState).toBe('completed');});+ it('remote source channels still receive the full result (no bot threads there)', async () => {+ mockedGenerateText.mockResolvedValue({ text: 'remote done', finishReason: 'stop', usage: { inputTokens: 10, outputTokens: 5 } } as any);+ seedBot(store, 'courier');+ const delivered: Array<{ target: string; message: string }> = [];+ manager['notify'] = async (t, target, message) => { delivered.push({ target: `${t}:${target}`, message }); };+ manager.enqueue('courier', { trigger: 'chat', prompt: 'go', source: { channelType: 'telegram', channelId: 'chat-42' } });+ await vi.waitFor(() => {+ expect(delivered.some(d => d.target === 'telegram:chat-42' && d.message.includes('remote done'))).toBe(true);+ });+ // The bot thread still gets it too.+ expect(delivered.some(d => d.target === 'cli:bot:courier' && d.message.includes('remote done'))).toBe(true);+ });+it('pauses the bot for the rest of the day when the daily token budget is hit', async () => {mockedGenerateText.mockImplementation(async (opts: any) => {opts.onStepFinish?.({ usage: { inputTokens: 100, outputTokens: 100 } });@@ -142,6 +158,54 @@ describe('BotManager queue + turn lifecycle', () => {}});+ it('stop holds queued jobs (durable, nothing lost) and start resumes them', async () => {+ let release!: () => void;+ const gate = new Promise<void>(res => { release = res; });+ mockedGenerateText.mockImplementation(() => gate.then(() => ({ text: 'ok', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any)));+ seedBot(store, 'worker');+ manager.enqueue('worker', { trigger: 'chat', prompt: 'one' });+ manager.enqueue('worker', { trigger: 'chat', prompt: 'two' }); // queues behind the running turn+ await vi.waitFor(() => expect(manager.getQueuedCount('worker')).toBe(1));++ const stop = await manager.stop('worker');+ expect(stop.halted).toBe(true);+ expect(stop.heldJobs).toBe(1);+ expect(manager.getQueuedCount('worker')).toBe(0);+ // The queued job is NOT destroyed — its durable row stays pending.+ expect(manager.queue.pendingJobs('worker').map(j => j.prompt)).toContain('two');++ release(); // let the in-flight turn finish+ await vi.waitFor(() => expect(manager.getJournal('worker').length).toBe(1));++ const start = manager.start('worker');+ expect(start.resumed).toBe(1);+ await vi.waitFor(() => expect(manager.getJournal('worker').length).toBe(2));+ });++ it('start on an idle stopped bot resumes nothing and reports it', async () => {+ seedBot(store, 'calm');+ await manager.stop('calm'); // nothing running, nothing queued+ expect(manager.start('calm').resumed).toBe(0);+ expect(manager.getStatusSummaries().find(s => s.id === 'calm')?.state).toBe('idle');+ });++ it('runNow fires a configured routine now, rejects unknown ones, and wakes bare', async () => {+ mockedGenerateText.mockResolvedValue({ text: 'digest done', finishReason: 'stop', usage: { inputTokens: 5, outputTokens: 5 } } as any);+ seedBot(store, 'crony', { schedules: [{ name: 'digest', cron: '0 9 * * *', prompt: 'Write the daily digest' }] });+ // Name resolution is case-insensitive; the run is journalled with trigger cron.+ expect(manager.runNow('crony', 'DIGEST').accepted).toBe(true);+ await vi.waitFor(() => {+ const records = manager.getJournal('crony');+ expect(records.length).toBe(1);+ expect(records[0].trigger).toBe('cron');+ expect(records[0].summary).toContain('digest done');+ });+ expect(manager.runNow('crony', 'nope')).toMatchObject({ accepted: false, reasonCode: 'routine_unknown' });+ expect(manager.runNow('ghost', 'digest')).toMatchObject({ accepted: false, reasonCode: 'target_unknown' });+ // No routine named → a bare wake turn with the canned wake prompt.+ expect(manager.runNow('crony').accepted).toBe(true);+ });+it('degrades to a stateless bot when the memory store cannot be built', async () => {// Simulates a SQLite-less device: the store factory throws.const config = getDefaultConfig() as MercuryConfig;@@ -194,6 +258,9 @@ describe('Main-agent bots awareness (system prompt section)', () => {expect(section).toContain('/bot <id> <message>');expect(section).toContain('dispatch_bot');expect(section).toContain('/bots open <id>');+ // The main agent must not promise main-chat delivery — results live in+ // the bot thread only (§3.1, thread-leak fix).+ expect(section).toContain('never in this chat');});it('empty fleet produces NO prompt section (zero drift for botless users)', () => {diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex 656b583f..526aaefb 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -59,6 +59,10 @@ export interface BotManagerDeps {const MAX_TRANSIENT_ATTEMPTS = 3;const MAILBOX_CAPACITY = 100;+/** Bare wake turn (`/bots run <id>` with no routine): the bot gets a real+ * turn with no task attached — it checks its mailbox and standing work. */+const WAKE_PROMPT = '[wake] You were triggered manually with no specific task attached. Check your mailbox and any pending work; act on whatever your persona or standing routines call for, otherwise reply with a one-line status.';+/** Structural subset of the main Scheduler the bot runtime needs. */type BotSchedulerLike = {addDelayedTask(m: { id: string; description: string; prompt: string; delaySeconds?: number; executeAt?: string; botId?: string; createdAt: string }): void;@@ -102,8 +106,18 @@ export class BotManager {}private async alertOwner(botId: string, message: string): Promise<void> {- if (!this.alert) return;- await this.alert(message).catch((e) => logger.warn({ e, botId }, 'Bot alert send failed'));+ // Needs-you events (permanent failure, budget pause) live in the BOT'S+ // OWN thread — the main chat is never informed (§3.1). Remote owner+ // surfaces (signal/telegram/…) still get the heads-up via the alert+ // channel; the CLI is excluded there (agent wiring) because it would+ // print into whatever main session is open.+ if (this.notify) {+ await this.notify('cli', `bot:${botId}`, message).catch((e) =>+ logger.warn({ e, botId }, 'Bot alert to bot thread failed'));+ }+ if (this.alert) {+ await this.alert(message).catch((e) => logger.warn({ e, botId }, 'Bot alert send failed'));+ }}private queues: Map<string, BotJob[]> = new Map();@@ -118,6 +132,9 @@ export class BotManager {private journals: Map<string, BotJournal> = new Map();private userMemories: Map<string, UserMemoryStore | null> = new Map();private disabled = new Set<string>();+ /** Bots stopped by the user (/bots stop) — their held jobs must not sneak+ * back in via the passive due-sweep; only /bots start (or a restart) resumes. */+ private held = new Set<string>();/** Per-bot daily token usage: botId → { day (UTC yyyy-mm-dd), tokens }. */private dailyTokens: Map<string, { day: string; tokens: number }> = new Map();private pausedForBudget = new Set<string>();@@ -173,7 +190,7 @@ export class BotManager {private resumeDueJobs(): void {const due = this.queue.dueJobs();for (const job of due) {- if (this.disabled.has(job.botId)) continue;+ if (this.disabled.has(job.botId) || this.held.has(job.botId)) continue;const running = this.running.get(job.botId)?.size ?? 0;const q = this.queues.get(job.botId) ?? [];const alreadyQueued = q.some(j => j.id === job.id);@@ -423,11 +440,14 @@ export class BotManager {this.queue.settle(job.id, 'done');}- // Deliver the outcome — Hermes/OpenClaw model (BOTS-ARCHITECTURE §3.1):- // the FULL result always lands in the BOT'S OWN thread; the session- // that asked for it gets only a one-line pointer. Remote channels- // (Telegram/web) are the exception — the user cannot open bot threads- // from there, so the full result is delivered in that chat. Halts+ // Deliver the outcome — the bot thread is the ONLY local surface+ // (BOTS-ARCHITECTURE §3.1): the FULL result lands in the BOT'S OWN+ // thread and the CLI session that asked is NOT notified at all — a+ // pointer into the main chat would leak into whatever session is open+ // days later (a routine or retry finishing inside a brand-new session+ // printed bot traffic into the user's regular chat/code). Remote+ // channels (Telegram/web) stay the exception: their user cannot open+ // bot threads, so the full result is delivered in that chat. Halts// report too (a stopped run must announce it stopped, §2.6).if (this.notify && job.trigger !== 'mailbox') {const botThread = `bot:${botId}`;@@ -438,21 +458,13 @@ export class BotManager {// 1. Full result → the bot's own thread, always.await this.notify('cli', botThread, fullText).catch((e) =>logger.warn({ e, botId }, 'Bot result deliver to bot thread failed'));- // 2. Requesting surface: pointer line for TUI sessions; full result- // for remote channels (their user can't open bot threads).+ // 2. Remote requesting surface only — no CLI pointer, no main-chat+ // traffic, ever.const sourceChannelType = job.source?.channelType ?? 'cli';const sourceChannelId = job.source?.channelId;- if (sourceChannelId && sourceChannelId !== botThread) {- if (sourceChannelType === 'cli') {- const pointer = output.status === 'completed'- ? `🤖 **${manifest.name}** finished its task — full result in its chat (\`/bots open ${botId}\`).`- : `🤖 **${manifest.name}** run ended (${output.status}) — details in \`/bots open ${botId}\`.`;- await this.notify('cli', sourceChannelId, pointer).catch((e) =>- logger.warn({ e, botId }, 'Bot pointer notify failed'));- } else {- await this.notify(sourceChannelType, sourceChannelId, fullText).catch((e) =>- logger.warn({ e, botId }, 'Bot remote-channel result notify failed'));- }+ if (sourceChannelId && sourceChannelId !== botThread && sourceChannelType !== 'cli') {+ await this.notify(sourceChannelType, sourceChannelId, fullText).catch((e) =>+ logger.warn({ e, botId }, 'Bot remote-channel result notify failed'));}}} catch (err: any) {@@ -584,6 +596,7 @@ export class BotManager {this.lastRun.delete(botId);this.needsYou.delete(botId);this.pausedForBudget.delete(botId);+ this.held.delete(botId);logger.info({ botId }, 'Bot deleted: queue/mail/DLQ purged, routines removed');}@@ -622,13 +635,16 @@ export class BotManager {async halt(botId: string, jobId?: string): Promise<boolean> {const running = this.running.get(botId);- if (!running || running.size === 0) return false;- for (const id of running) {+ const hadRunning = !!running && running.size > 0;+ for (const id of running ?? []) {if (jobId && id !== jobId) continue;this.aborts.get(`${botId}:${id}`)?.abort();}+ // Queued-but-not-started jobs leave the in-memory lane; their durable rows+ // stay pending, so /bots start (or a restart) can resume them — stop never+ // silently destroys queued work (§2.7 control plane).this.queues.set(botId, jobId ? (this.queues.get(botId) ?? []).filter(j => j.id !== jobId) : []);- return true;+ return hadRunning;}async haltAll(): Promise<void> {@@ -637,6 +653,74 @@ export class BotManager {}}+ /**+ * User-facing stop: abort the running turn(s) AND hold queued work. Held+ * jobs stay durable-pending (survive a restart); the passive due-sweep+ * skips held bots, so nothing resumes until /bots start. Explicit new+ * triggers (send/mail/cron) still work — the bot is stopped, not disabled.+ */+ async stop(botId: string): Promise<{ halted: boolean; heldJobs: number }> {+ const heldJobs = (this.queues.get(botId) ?? []).length;+ const halted = await this.halt(botId);+ this.held.add(botId);+ if (heldJobs > 0) {+ logger.info({ botId, heldJobs }, 'Bot stopped — queued jobs held (resumable via /bots start)');+ }+ return { halted, heldJobs };+ }++ /**+ * User-facing resume (the counterpart of stop): clear the stop-hold,+ * re-enter held/pending durable jobs, and kick the queue. A disabled bot+ * is enabled first — "start" is unambiguous. Safe on an already-running bot.+ */+ start(botId: string): { resumed: number } {+ const manifest = this.store.get(botId);+ if (!manifest) throw new Error(`Bot "${botId}" does not exist`);+ this.held.delete(botId);+ const resumed = this.rehydratePending(botId);+ if (!manifest.enabled || this.disabled.has(botId)) {+ this.setEnabled(botId, true); // persists enabled + pumps+ } else {+ this.pump(botId);+ }+ return { resumed };+ }++ /** Pull durable pending jobs for a bot back into the in-memory queue. */+ private rehydratePending(botId: string): number {+ const pending = this.queue.pendingJobs(botId);+ if (pending.length === 0) return 0;+ const q = this.queues.get(botId) ?? [];+ const running = this.running.get(botId) ?? new Set();+ let added = 0;+ for (const job of pending) {+ if (q.some(j => j.id === job.id) || running.has(job.id)) continue;+ q.push({+ id: job.id, botId, trigger: job.trigger, prompt: job.prompt,+ fromBot: job.fromBot, source: job.source, createdAt: job.createdAt, attempts: job.attempts,+ });+ added++;+ }+ if (added > 0) {+ this.queues.set(botId, q);+ logger.info({ botId, resumed: added }, 'Re-entered pending bot jobs (explicit resume)');+ }+ return added;+ }++ /** Fire a bot's configured routine immediately, or send a bare wake turn. */+ runNow(botId: string, routineName?: string): { accepted: boolean; jobId?: string; reasonCode?: string } {+ const manifest = this.store.get(botId);+ if (!manifest) return { accepted: false, reasonCode: 'target_unknown' };+ if (routineName) {+ const routine = (manifest.schedules ?? []).find(r => r.name.toLowerCase() === routineName.toLowerCase());+ if (!routine) return { accepted: false, reasonCode: 'routine_unknown' };+ return this.enqueue(botId, { trigger: 'cron', prompt: routine.prompt });+ }+ return this.enqueue(botId, { trigger: 'chat', prompt: WAKE_PROMPT });+ }+setEnabled(botId: string, enabled: boolean): void {if (enabled) {this.disabled.delete(botId);@@ -735,10 +819,10 @@ export class BotManager {lines.push(`- **${m.name}** (\`${m.id}\`)${desc} [${state}]`);}lines.push(`Bot control (never route bot work through this main conversation):-- \`/bot <id> <message>\` or \`@<id> <message>\` — dispatch a task to a bot; its reply arrives in this chat when done.+- \`/bot <id> <message>\` or \`@<id> <message>\` — dispatch a task to a bot; the result lands ONLY in the bot's own thread (\`/bots open <id>\`), never in this chat.- \`/bots open <id>\` — open the bot's own chat; \`/bots\` — roster with live states.- \`/bots create <id> "Name" "Description"\` — onboard; \`/bots persona <id> <text>\` — set its character.-- \`/bots journal <id>\` — recent runs; \`/bots dlq\` — failed jobs (replayable); \`/bots stop|enable|disable <id>\`.+- \`/bots journal <id>\` — recent runs; \`/bots dlq\` — failed jobs (replayable); \`/bots stop|start|enable|disable <id>\`; \`/bots run <id> [routine]\` — fire a routine now (or a bare wake).- The dispatch_bot tool lets you hand a task to a bot mid-conversation and continue talking; the result is delivered when the bot finishes.`);return lines.join('\n');}diff --git a/src/bots/queue.test.ts b/src/bots/queue.test.tsindex 3551df17..7e888bed 100644--- a/src/bots/queue.test.ts+++ b/src/bots/queue.test.ts@@ -84,6 +84,16 @@ describe('BotQueue backends (JSON-file + SQLite semantics)', () => {expect(backend.counts()).toEqual({ pending: 0, claimed: 0, dlq: 0 });});+ it('pendingJobs returns only that bot’s pending work, ignoring retry backoff', () => {+ const backend = name === 'json' ? new JsonFileQueueBackend(root, 100) : new SqliteQueueBackend(root, 100, require('better-sqlite3'));+ backend.enqueue(job('h1'));+ backend.enqueue(job('h2', { botId: 'other' }));+ backend.enqueue(job('backoff', { idempotencyKey: idempotencyKeyFor('researcher', 'chat', 'task backoff') }));+ backend.retry('backoff', 1, Date.now() + 60_000); // in retry backoff+ const pending = backend.pendingJobs('researcher');+ expect(pending.map(j => j.id)).toEqual(['h1', 'backoff']); // backoff included: explicit resume overrides it+ });+it('settle dead moves the job to the DLQ with the reason', () => {const backend = name === 'json' ? new JsonFileQueueBackend(root, 100) : new SqliteQueueBackend(root, 100, require('better-sqlite3'));backend.enqueue(job('a1'));diff --git a/src/bots/queue.ts b/src/bots/queue.tsindex 186d7136..abfbedb0 100644--- a/src/bots/queue.ts+++ b/src/bots/queue.ts@@ -86,6 +86,8 @@ export interface BotQueueBackend {rehydratable(): DurableBotJob[];/** Pending jobs whose run-after time has arrived (retry backoff elapsed). */dueJobs(): DurableBotJob[];+ /** All pending jobs for one bot, in creation order — explicit resume (/bots start), ignores retry backoff. */+ pendingJobs(botId: string): DurableBotJob[];/** Expired-lease claimed jobs → pending. Returns the count requeued. */requeueExpiredLeases(): number;heartbeatLease(jobId: string, leaseSeconds: number): void;@@ -178,6 +180,11 @@ export class BotQueue {return this.backend.dueJobs();}+ /** All pending jobs for one bot — explicit resume via /bots start. */+ pendingJobs(botId: string): DurableBotJob[] {+ return this.backend.pendingJobs(botId);+ }+enqueueMail(mail: Omit<DurableMail, 'id'>): string {return this.backend.enqueueMail(mail);}@@ -345,6 +352,13 @@ export class SqliteQueueBackend implements BotQueueBackend {return rows.map(normalizeJob);}+ pendingJobs(botId: string): DurableBotJob[] {+ const rows = this.db.prepare(+ `SELECT * FROM bot_jobs WHERE bot_id = ? AND state = 'pending' ORDER BY created_at`,+ ).all(botId) as any[];+ return rows.map(normalizeJob);+ }+enqueueMail(mail: Omit<DurableMail, 'id'>): string {const id = randomUUID().slice(0, 12);this.db.prepare(@@ -533,6 +547,10 @@ export class JsonFileQueueBackend implements BotQueueBackend {return this.data.jobs.filter(j => j.state === 'pending' && (j.runAfter === undefined || j.runAfter <= now));}+ pendingJobs(botId: string): DurableBotJob[] {+ return this.data.jobs.filter(j => j.botId === botId && j.state === 'pending');+ }+enqueueMail(mail: Omit<DurableMail, 'id'>): string {const id = randomUUID().slice(0, 12);this.data.mails.push({ ...mail, id });diff --git a/src/core/agent.ts b/src/core/agent.tsindex a045ea67..7eb7f83b 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -576,7 +576,12 @@ export class Agent {});botManager.setAlert(async (message) => {const channel = this.channels.getNotificationChannel();- await channel?.send(message).catch((e) => logger.warn({ e }, 'bot alert send failed'));+ // The CLI is NOT a needs-you surface: an alert printed there lands in+ // the main chat (bot thread leak) — the bot's own thread already+ // carries the event via botManager's own notify.+ if (channel && channel.type !== 'cli') {+ await channel.send(message).catch((e) => logger.warn({ e }, 'bot alert send failed'));+ }});}@@ -1275,7 +1280,7 @@ export class Agent {const action = (parts[0] ?? '').toLowerCase();// All bot-targeting actions accept id OR name — resolve to the id here.- if (['open', 'send', 'journal', 'inbox', 'budget', 'edit', 'delete', 'enable', 'disable', 'stop', 'pause'].includes(action) && parts[1]) {+ if (['open', 'send', 'journal', 'inbox', 'budget', 'edit', 'delete', 'enable', 'disable', 'stop', 'pause', 'start', 'run'].includes(action) && parts[1]) {const resolved = bm.resolveBotId(parts[1]);if (resolved) parts[1] = resolved;}@@ -1491,8 +1496,51 @@ export class Agent {await channel.send('Usage: `/bots stop <id>`', channelId);return;}- const halted = await bm.halt(target);- await channel.send(halted ? `⛔ Halt signal sent to **${target}** — it will stop after the current tool step.` : `**${target}** has nothing running.`, channelId);+ const result = await bm.stop(target);+ const heldNote = result.heldJobs > 0 ? `\n↩ ${result.heldJobs} queued job(s) held — resume with \`/bots start ${target}\`.` : '';+ await channel.send(result.halted+ ? `⛔ Halt signal sent to **${target}** — it will stop after the current tool step.${heldNote}`+ : `⛔ **${target}** stopped — nothing was running.${heldNote}`, channelId);+ return;+ }++ if (action === 'start') {+ const target = parts[1]?.toLowerCase();+ if (!target) {+ await channel.send('Usage: `/bots start <id>`', channelId);+ return;+ }+ try {+ const { resumed } = bm.start(target);+ await channel.send(resumed > 0+ ? `▶️ **${target}** started — ${resumed} held job(s) back in the queue.`+ : `▶️ **${target}** started — nothing was held; it is idle and ready for tasks.`, channelId);+ } catch (err: any) {+ await channel.send(`Failed: ${err?.message}`, channelId);+ }+ return;+ }++ if (action === 'run') {+ const target = parts[1]?.toLowerCase();+ const routine = parts.slice(2).join(' ') || undefined;+ if (!target) {+ await channel.send('Usage: `/bots run <id> [routineName]` — no routine = a bare wake turn.', channelId);+ return;+ }+ const result = bm.runNow(target, routine);+ if (!result.accepted) {+ if (result.reasonCode === 'routine_unknown') {+ const names = (bm.store.get(target)?.schedules ?? []).map(r => r.name);+ await channel.send(`No routine "${routine}" on **${target}**.${names.length ? ` Configured: ${names.join(', ')}` : ' This bot has no routines — add them with `/bots edit <id>` or /bots open.'}`, channelId);+ return;+ }+ await channel.send(`Could not run **${target}**: [reason: ${result.reasonCode}]`, channelId);+ return;+ }+ await channel.send(routine+ ? `🏃 Routine **${routine}** fired on **${target}** (job ${result.jobId}) — runs outside the main conversation.`+ : `🏃 Wake sent to **${target}** (job ${result.jobId}) — it gets a turn to check its mailbox and pending work.`, channelId);return;}@@ -1600,7 +1648,8 @@ export class Agent {'`/bots dlq` — dead-lettered jobs\n' +'`/bots replay <botId> <jobId>` — re-run a dead-lettered job\n' +'`/bots storage` — disk usage\n' +- '`/bots enable|disable|stop <id>` — control (disable = pause, enable = resume)\n' ++ '`/bots enable|disable|stop|start <id>` — control (stop holds queued jobs; start resumes them)\n' ++ '`/bots run <id> [routineName]` — fire a routine now, or a bare wake turn\n' +'`/bots delete <id> confirm` — permanently delete',channelId,);diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex a09f47c5..764a55b8 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -1041,6 +1041,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyCprogrammingMode={state.programmingMode}projectContext={state.projectContext}botChat={state.botChat}+ botsWorking={state.botRoster.filter((b) => b.state === 'running').length}/>)}{showInput && state.mode !== 'mercury-code' && slashSuggestions.length > 0 && (@@ -2189,6 +2190,7 @@ function InputBox({programmingMode,projectContext,botChat,+ botsWorking,}: {input: string;cursorPos: number;@@ -2196,6 +2198,8 @@ function InputBox({programmingMode: ProgrammingModeState;projectContext: string | null;botChat?: { botId: string; botName: string } | null;+ /** Bots currently running a turn (live roster, polled every 2s). */+ botsWorking?: number;}) {const inWorkspace = mode === 'workspace';const inCoding = mode === 'coding' || inWorkspace;@@ -2228,6 +2232,11 @@ function InputBox({<Text color={programmingMode === 'execute' ? 'green' : programmingMode === 'plan' ? 'yellow' : 'gray'}>mode={programmingMode.toUpperCase()}</Text>+ {/* Ambient bot-fleet status: shown ONLY while bots are actually+ working (idle = nothing rendered, no "idle" noise). */}+ {botsWorking && botsWorking > 0 ? (+ <Text color="magenta"> 🤖 {botsWorking} working</Text>+ ) : null}</Box><Box paddingX={1} flexDirection="column">{lines.map((line, i) => (diff --git a/src/web/api/bots.ts b/src/web/api/bots.tsindex c4179f9f..4dae6a97 100644--- a/src/web/api/bots.ts+++ b/src/web/api/bots.ts@@ -134,7 +134,7 @@ app.post('/api/bots/:id/replay/:jobId', (c: any) => {return c.json({ ...result, status: 'accepted' });});-// Enable/disable/stop controls+// Enable/disable/stop/start controlsapp.post('/api/bots/:id/enable', (c: any) => {if (!botManager) return c.json({ error: 'Bots not available' }, 400);try {@@ -157,10 +157,34 @@ app.post('/api/bots/:id/disable', (c: any) => {app.post('/api/bots/:id/stop', async (c: any) => {if (!botManager) return c.json({ error: 'Bots not available' }, 400);- const halted = await botManager.halt(c.req.param('id'));- return c.json({ ok: halted, message: halted ? 'Halt signal sent' : 'Nothing running' });+ const result = await botManager.stop(c.req.param('id'));+ return c.json({ ok: true, halted: result.halted, heldJobs: result.heldJobs, message: haltedMessage(result) });});+app.post('/api/bots/:id/start', (c: any) => {+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);+ try {+ const result = botManager.start(c.req.param('id'));+ return c.json({ ok: true, resumed: result.resumed, message: result.resumed > 0 ? `Resumed ${result.resumed} held job(s)` : 'Nothing held — bot is ready' });+ } catch (err: any) {+ return c.json({ error: err?.message }, 404);+ }+});++// Fire a routine now (body { routine }) or send a bare wake turn+app.post('/api/bots/:id/run', async (c: any) => {+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);+ const body = await c.req.json().catch(() => null) as { routine?: string } | null;+ const result = botManager.runNow(c.req.param('id'), body?.routine);+ if (!result.accepted) return c.json(result, result.reasonCode === 'routine_unknown' ? 404 : 409);+ return c.json({ ...result, status: 'accepted' }, 202);+});++function haltedMessage(result: { halted: boolean; heldJobs: number }): string {+ const base = result.halted ? 'Halt signal sent' : 'Nothing running';+ return result.heldJobs > 0 ? `${base}; ${result.heldJobs} queued job(s) held` : base;+}+// Storage viewapp.get('/api/bots-storage', (c: any) => {if (!botManager) return c.json({ error: 'Bots not available' }, 400);