Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(attach): the launch pad opens the attach TUI; a command right after /stop waits instead of "busy" (1.3.2)
Salman Qureshibaacb66b99fc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 774dab86..ec3c870c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,7 +1,9 @@# Changelog-## 1.3.2 — hotfix: /code from the default launch+## 1.3.2 — hotfix: /code, the launch pad, and /stop from the default launch+- **Launch pad on `mercury`.** The default launch attaches to the daemon (ADR-024) and the attach screen had dropped the launch pad — the wordmark, provider/skills/web/budget rows and tip the main TUI opens with. It is back, fed by real runtime state, above the session picker.+- **`/stop` then a command.** `/stop` aborts asynchronously; a slash command typed before the turn finished unwinding was answered "Agent is busy…". The launcher now waits for the stop to complete (up to 5 s) and runs the command normally.- **`/code` works again from `mercury`.** Since 1.3.1 the default launch attaches to the daemon, and `/code` typed there was forwarded to the daemon's web channel — which has no terminal to switch into — so it printed "Programming mode: Off". The attach TUI now hands the terminal to Mercury Code (`/code` or `/code <dir>`), exactly what `mercury code` does; the runtime keeps running in the background. `/code plan|auto|off` inside the attach TUI explain where to run them.## 1.3.1 — Steady Mercurydiff --git a/src/cli/attach.ts b/src/cli/attach.tsindex e7546bfe..fe34e5a6 100644--- a/src/cli/attach.ts+++ b/src/cli/attach.ts@@ -160,6 +160,30 @@ export class AttachClient {}}+ getBaseUrl(): string { return this.baseUrl; }++ /** Provider the runtime answers with right now (launch pad "Provider" row). */+ async currentModel(): Promise<{ name: string; model: string } | null> {+ try {+ const res = await this.request('/api/chat/models');+ if (!res.ok) return null;+ const body = await res.json() as { current?: { name?: string; model?: string } };+ return body.current?.name ? { name: body.current.name, model: body.current.model ?? '' } : null;+ } catch { return null; }+ }++ /** Today's token use against the cap (launch pad "Budget" row). */+ async budget(): Promise<{ used: number; budget: number } | null> {+ try {+ const res = await this.request('/api/status');+ if (!res.ok) return null;+ const b = await res.json() as Record<string, unknown> & { tokens?: { used?: number; budget?: number } };+ const used = Number(b.tokensUsed ?? b.tokens?.used ?? NaN);+ const budget = Number(b.tokenBudget ?? b.tokens?.budget ?? NaN);+ return Number.isFinite(used) && Number.isFinite(budget) ? { used, budget } : null;+ } catch { return null; }+ }+async listThreads(): Promise<AttachThread[]> {const res = await this.request('/api/chat/threads');if (!res.ok) throw new Error(`HTTP ${res.status}`);@@ -466,9 +490,11 @@ export async function runAttach(opts: AttachRunOptions = {}): Promise<AttachResu}let handoff: { kind: 'code'; dir?: string } | null = null;+ const info = await client.healthCheck().catch(() => null);const instance = render(React.createElement(AttachTui, {client,pid: target.pid,+ version: info?.version || undefined,onExit: () => {},onHandoff: (h) => { handoff = h; },}));diff --git a/src/core/agent.ts b/src/core/agent.tsindex eca4ec0a..7cd64cd9 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -795,6 +795,17 @@ export class Agent {}}+ // /stop is asynchronous: the abort lands, the turn unwinds, THEN+ // processing clears. A command typed in that window used to be answered+ // "Agent is busy" — wait for the stop to finish and route it normally.+ if (this.processing && trimmed.startsWith('/') && this.currentAbortReason && !msg.metadata?.waitedForStop) {+ void this.waitUntilIdle(5000).then(() => {+ msg.metadata = { ...msg.metadata, waitedForStop: true };+ this.enqueueMessage(msg);+ });+ return;+ }+if (this.processing && trimmed.startsWith('/')) {this.handleFastPathCommand(msg).catch((err) => {logger.error({ err, content: trimmed.slice(0, 50) }, 'Fast-path command failed');@@ -1040,6 +1051,15 @@ export class Agent {return reason === 'halted' ? 'Foreground task halted.' : 'Foreground task stopped, locks released, task board cleared.';}+ /** Resolves when no turn is running (or after the deadline). */+ private waitUntilIdle(maxMs: number): Promise<void> {+ const deadline = Date.now() + maxMs;+ return new Promise((resolve) => {+ const tick = () => { if (!this.processing || Date.now() >= deadline) resolve(); else setTimeout(tick, 50); };+ tick();+ });+ }+private async handleFastPathCommand(msg: ChannelMessage): Promise<void> {return handleFastPathCommandImpl(this, msg);}diff --git a/src/ui/attach-launch-pad.test.tsx b/src/ui/attach-launch-pad.test.tsxnew file mode 100644index 00000000..c529ab8f--- /dev/null+++ b/src/ui/attach-launch-pad.test.tsx@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';+import React from 'react';+import { render } from 'ink';+import { EventEmitter } from 'node:events';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { AttachTui } from './attach-tui.js';+import { VtScreen } from './vt-screen.js';++class FakeStdout extends EventEmitter { isTTY = true; constructor(public screen: VtScreen) { super(); } get columns() { return this.screen.columns; } get rows() { return this.screen.rows; } write(c: string) { this.screen.write(c); return true; } }+class FakeStdin extends EventEmitter { isTTY = true; setEncoding() {} setRawMode() {} resume() {} pause() {} ref() {} unref() {} read() { return null; } }+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));++const fakeClient = {+ getBaseUrl: () => 'http://127.0.0.1:6174',+ listThreads: async () => [],+ listSkills: async () => [{ name: 'deploy', description: 'ship it' }],+ listBots: async () => [],+ currentModel: async () => ({ name: 'anthropic', model: 'claude-opus-5-5' }),+ budget: async () => ({ used: 1200, budget: 1_000_000 }),+} as never;++describe('attach TUI opens with the launch pad', () => {+ it('shows the wordmark and the real status rows before the session picker', async () => {+ const screen = new VtScreen(100, 36);+ const app = render(<AttachTui client={fakeClient} pid={4242} version="1.3.3" onExit={() => {}} />, { stdout: new FakeStdout(screen) as never, stdin: new FakeStdin() as never, exitOnCtrlC: false, patchConsole: false } as never);+ await sleep(400);+ const text = screen.text().join('\n');+ app.unmount();+ expect(text).toContain('Provider');+ expect(text).toContain('anthropic · claude-opus-5-5');+ expect(text).toContain('1 ready');+ expect(text).toContain('127.0.0.1:6174');+ expect(text).toContain('v1.3.3');+ expect(text).toContain('Attached to the running Mercury');+ });++ it('a slash command typed while /stop is unwinding waits for idle instead of "busy"', () => {+ const agent = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'core', 'agent.ts'), 'utf8').replace(/\r\n/g, '\n');+ expect(agent).toContain("this.processing && trimmed.startsWith('/') && this.currentAbortReason && !msg.metadata?.waitedForStop");+ expect(agent).toContain('private waitUntilIdle(maxMs: number): Promise<void>');+ });+});diff --git a/src/ui/attach-tui.tsx b/src/ui/attach-tui.tsxindex 87161df4..d8df3f6b 100644--- a/src/ui/attach-tui.tsx+++ b/src/ui/attach-tui.tsx@@ -1,5 +1,8 @@import React from 'react';import { parseAttachHandoff } from './attach-handoff.js';+import { LaunchPad } from './launch-pad.js';+import { rotateTip } from './tips.js';+import type { TuiState } from '../channels/cli.js';import { Box, Text, Spacer, Static, useApp, useInput } from 'ink';import type { AttachClient, AttachEvent, AttachThread } from '../cli/attach.js';import { renderMarkdown } from '../utils/markdown.js';@@ -117,7 +120,7 @@ function AttachPromptView({ prompt, activeIdx }: { prompt: AttachPrompt; activeI);}-export function AttachTui({ client, pid, onExit, onHandoff }: { client: AttachClient; pid: number | null; onExit: () => void; onHandoff?: (handoff: { kind: 'code'; dir?: string }) => void }): React.ReactNode {+export function AttachTui({ client, pid, version, onExit, onHandoff }: { client: AttachClient; pid: number | null; version?: string; onExit: () => void; onHandoff?: (handoff: { kind: 'code'; dir?: string }) => void }): React.ReactNode {const { exit } = useApp();const [phase, setPhase] = React.useState<'pick' | 'chat'>('pick');@@ -133,6 +136,8 @@ export function AttachTui({ client, pid, onExit, onHandoff }: { client: AttachClconst [prompt, setPrompt] = React.useState<AttachPrompt | null>(null);const [promptIdx, setPromptIdx] = React.useState(0);const [provider, setProvider] = React.useState<{ name: string; model: string } | null>(null);+ const [tokenInfo, setTokenInfo] = React.useState<{ used: number; budget: number } | null>(null);+ const launchTip = React.useMemo(() => rotateTip('chat')?.tip ?? null, []);const [notice, setNotice] = React.useState<string | null>(null);const [input, setInput] = React.useState('');@@ -154,6 +159,9 @@ export function AttachTui({ client, pid, onExit, onHandoff }: { client: AttachClReact.useEffect(() => {let cancelled = false;client.listSkills().then((list) => { if (!cancelled) setSkills(list); }).catch(() => {});+ // Launch pad rows: real state from the runtime, same as the main TUI.+ client.currentModel().then((m) => { if (!cancelled && m) setProvider(m); }).catch(() => {});+ client.budget().then((b) => { if (!cancelled && b) setTokenInfo({ used: b.used, budget: b.budget }); }).catch(() => {});client.listBots().then((list) => { if (!cancelled) setBots(list); }).catch(() => {});return () => { cancelled = true; };}, [client]);@@ -466,10 +474,21 @@ export function AttachTui({ client, pid, onExit, onHandoff }: { client: AttachCl});if (phase === 'pick') {+ // The same launch pad the main TUI opens with (ADR-024 made attach the+ // default launch; the first screen must not get plainer for it).+ const padState = {+ version: version ?? 'dev',+ agentName: 'Mercury',+ provider,+ skills,+ web: { enabled: true, port: Number(new URL(client.getBaseUrl()).port) || 6174 },+ tokenInfo: tokenInfo ? { used: tokenInfo.used, budget: tokenInfo.budget, percentage: tokenInfo.budget > 0 ? Math.round((tokenInfo.used / tokenInfo.budget) * 100) : 0 } : null,+ } as unknown as TuiState;return (<Box flexDirection="column" paddingX={1}>- <Text bold color="cyan">⚿ Attach to Mercury</Text>- {pid != null && <Text dimColor>runtime PID {pid} · Ctrl+C cancels</Text>}+ <LaunchPad state={padState} cols={terminalSize.cols} showDetails={false} tip={launchTip} />+ <Text bold color="cyan">⚿ Attached to the running Mercury</Text>+ {pid != null && <Text dimColor>runtime PID {pid} · Ctrl+C detaches (Mercury keeps running)</Text>}<Text> </Text>{!threadsLoaded ? (<Text dimColor>Loading sessions…</Text>