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.

fix(ui): finish shared input-composer extraction — relaunch suggestions parity

Salman Qureshi6c47a928e3fd
diff --git a/src/autocomplete-sync.test.ts b/src/autocomplete-sync.test.ts
index 92a7ff60..c2ed37df 100644
--- a/src/autocomplete-sync.test.ts
+++ b/src/autocomplete-sync.test.ts
@@ -6,16 +6,28 @@ import { dirname, join } from 'node:path';
// This test lives in src/, so dirname is already the src directory.
const root = dirname(fileURLToPath(import.meta.url));
const appSrc = readFileSync(join(root, 'ui', 'App.tsx'), 'utf8');
+const composerSrc = readFileSync(join(root, 'ui', 'input-composer.tsx'), 'utf8');
+const attachSrc = readFileSync(join(root, 'ui', 'attach-tui.tsx'), 'utf8');
const manualSrc = readFileSync(join(root, 'utils', 'manual.ts'), 'utf8');
/**
* Slash-command sync contract: every real chat command must appear in the
- * TUI's autocomplete list (ui/App.tsx `slashCommands`) and in the manual.
- * New commands are easy to ship and forget to suggest — this test fails
- * until they are added everywhere.
+ * canonical autocomplete list (ui/input-composer.tsx `SLASH_COMMANDS`) and in
+ * the manual. Since the shared composer was extracted, App.tsx and the attach
+ * TUI import THE SAME list — the contract pins that wiring too: if either
+ * surface stops importing the composer, suggestions silently diverge again
+ * (the "close & relaunch feels different" class of bug).
*/
describe('slash autocomplete & help stay in sync', () => {
- it('the TUI autocomplete covers the recently added commands', () => {
+ it('both TUI surfaces consume the shared input composer', () => {
+ for (const src of [appSrc, attachSrc]) {
+ expect(src).toContain("from './input-composer.js'");
+ expect(src).toContain('SLASH_COMMANDS');
+ expect(src).toContain('SuggestionList');
+ }
+ });
+
+ it('the canonical autocomplete list covers the recently added commands', () => {
for (const cmd of [
'/whatsnew',
'/update ignore',
@@ -23,7 +35,7 @@ describe('slash autocomplete & help stay in sync', () => {
'/code chat',
'/code back',
]) {
- expect(appSrc).toContain(`'${cmd}'`);
+ expect(composerSrc).toContain(`'${cmd}'`);
}
});
diff --git a/src/cli/attach.ts b/src/cli/attach.ts
index b5d571bd..a24bded9 100644
--- a/src/cli/attach.ts
+++ b/src/cli/attach.ts
@@ -172,6 +172,35 @@ export class AttachClient {
}
}
+ /** Active skills for the `#name` picker — the same data the main TUI splash loads. */
+ async listSkills(): Promise<Array<{ name: string; description: string }>> {
+ try {
+ const res = await this.request('/api/skills');
+ if (!res.ok) return [];
+ const body = await res.json() as { skills?: Array<{ name?: string; description?: string; active?: boolean }> };
+ return (body.skills ?? [])
+ .filter((s) => s.active !== false)
+ .map((s) => ({ name: String(s.name ?? ''), description: String(s.description ?? '') }))
+ .filter((s) => s.name.length > 0);
+ } catch {
+ return [];
+ }
+ }
+
+ /** Live bot roster for `/bot <id>` argument completion (main-TUI parity). */
+ async listBots(): Promise<Array<{ id: string; name: string }>> {
+ try {
+ const res = await this.request('/api/bots');
+ if (!res.ok) return [];
+ const body = await res.json() as { bots?: Array<{ id?: string; name?: string }> };
+ return (body.bots ?? [])
+ .map((b) => ({ id: String(b.id ?? ''), name: String(b.name ?? '') }))
+ .filter((b) => b.id.length > 0);
+ } catch {
+ return [];
+ }
+ }
+
async send(content: string, sessionId?: string): Promise<{ ok: boolean; sessionId?: string; error?: string }> {
try {
const res = await this.request('/api/chat/send', {
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index 76274c11..6770667a 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -13,6 +13,7 @@ import { useTerminalSize as useSharedTerminalSize } from './use-terminal-size.js
import { buildMercuryMessageLines, buildMercuryBrandLines, buildStreamTailLines, parseChunkIndex, splitFinalMessage, splitStreamingMessage, type MercuryTranscriptLine } from './mercury-transcript.js';
import { GENERIC_PHASES, PLANNING_VERBS, lastUserText, pickStatusWord } from './status-word.js';
import { nextTip, rotateTip } from './tips.js';
+import { SLASH_COMMANDS, buildSlashSuggestions, buildSkillSuggestions, skillFillText, shouldSubmitSlash, pushHistoryLine, historyPrev, historyNext, insertInputChunk, backspaceAt, createInputHistoryState, SuggestionList, type SkillEntry } from './input-composer.js';
import { PLAYER_CONTROLS, formatNowPlaying } from '../spotify/ui.js';
import type { SpotifyClient } from '../spotify/client.js';
import type { SubAgentStatus } from '../types/agent.js';
@@ -113,129 +114,21 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
const [spotifyArtUrl, setSpotifyArtUrl] = React.useState<string | null>(null);
const [spotifyArtAnsi, setSpotifyArtAnsi] = React.useState<string>('');
const albumArtCache = React.useRef<Map<string, string>>(new Map());
- const [inputHistory, setInputHistory] = React.useState<string[]>([]);
- const [historyIndex, setHistoryIndex] = React.useState<number>(-1);
- const [historyDraft, setHistoryDraft] = React.useState<string>('');
+ // Shell-style input history — shared composer state (↑/↓ navigation with
+ // draft snapshotting; see input-composer.tsx).
+ const [inputHistory, setInputHistory] = React.useState(createInputHistoryState);
const [gitCursor, setGitCursor] = React.useState(0);
- const slashCommands = React.useMemo(() => [
- '/help',
- '/whatsnew',
- '/update ignore',
- '/log',
- '/sessions',
- '/session new',
- '/session current',
- '/session ',
- '/session archive ',
- '/session delete ',
- '/bots',
- '/bots list',
- '/bots open ',
- '/bots create ',
- '/bots send ',
- '/bots persona ',
- '/bots budget ',
- '/bots edit ',
- '/bots delete ',
- '/bots journal ',
- '/bots inbox ',
- '/bots storage',
- '/bots enable ',
- '/bots disable ',
- '/bots stop ',
- '/status',
- '/progress',
- '/menu',
- '/chat',
- '/code',
- '/code plan',
- '/code execute',
- '/code build',
- '/code diff',
- '/code init',
- '/code workspace',
- '/code agent ',
- '/code off',
- '/code toggle',
- '/code exit',
- '/code chat',
- '/code back',
- '/research',
- '/research on',
- '/research off',
- '/research toggle',
- '/research ',
- '/spotify',
- '/budget',
- '/permissions',
- '/memory',
- '/models',
- '/models use ',
- '/cloud',
- '/cloud models',
- '/cloud use ',
- '/agents',
- '/agents stop ',
- '/agents pause ',
- '/agents resume ',
- '/bg',
- '/bg current',
- '/bg list',
- '/bg cancel ',
- '/bg clear',
- '/bg killall',
- '/stop',
- '/halt',
- '/reset',
- '/tools',
- '/skills',
- '/skills search ',
- '/skills view ',
- '/skills install ',
- '/skills remove ',
- '/skills help',
- '/stream',
- '/saver',
- '/saver on',
- '/saver off',
- '/saver toggle',
- '/saver threshold ',
- '/saver auto on',
- '/saver auto off',
- '/saver routing on',
- '/saver routing off',
- '/view',
- '/view balanced',
- '/view detailed',
- '/ws',
- '/ws open ',
- '/ws exit',
- '/ws refresh',
- '/ws stage all',
- '/ws commit ',
- '/ws help',
- ], []);
-
- const slashSuggestions = React.useMemo(() => {
- if (!input.startsWith('/')) return [];
- const q = input.toLowerCase();
- // Bot-id argument completion: `/bots <action> <partial>` or `/bot <partial>`
- // suggests existing bots (id or name) — the roster arrives via the 2s poller.
- const botsArg = /^(\/bots\s+(?:open|send|journal|inbox|budget|edit|delete|enable|disable|stop|persona)\s+)(\S*)$/.exec(input);
- const botArg = /^(\/bot\s+)(\S*)$/.exec(input);
- if ((botsArg || botArg) && state.botRoster.length > 0) {
- const [_, cmdPrefix, typed] = botsArg ?? botArg!;
- const p = typed.toLowerCase();
- const botCmds = state.botRoster
- .filter((b) => b.id.startsWith(p) || b.name.toLowerCase().startsWith(p))
- .slice(0, 5)
- .map((b) => `${cmdPrefix}${b.id}`);
- const base = slashCommands.filter((cmd) => cmd.startsWith(q)).slice(0, 2);
- return [...botCmds, ...base].slice(0, 5);
- }
- return slashCommands.filter((cmd) => cmd.startsWith(q)).slice(0, 5);
- }, [input, slashCommands, state.botRoster]);
+ // Canonical command list lives in the shared input composer (single source
+ // of truth for the main TUI AND the attach TUI — see input-composer.tsx).
+ const slashCommands = SLASH_COMMANDS;
+
+ const slashSuggestions = React.useMemo(
+ () => buildSlashSuggestions(input, slashCommands, state.botRoster.length > 0
+ ? state.botRoster.map((b) => ({ id: b.id, name: b.name }))
+ : []),
+ [input, slashCommands, state.botRoster],
+ );
const [slashSelIdx, setSlashSelIdx] = React.useState(0);
@@ -249,26 +142,17 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
// skills by name prefix first, then by name-substring, then by
// description-substring (case-insensitive). The selected entry inserts as
// `#skill-name ` so the user can continue typing their request.
- const skillSuggestions = React.useMemo(() => {
- if (!input.startsWith('#')) return [] as Array<{ name: string; description: string }>;
- const q = input.slice(1).split(/\s/)[0].toLowerCase();
- const skills = state.skills || [];
- if (!q) {
- return skills.slice(0, 8).map((s) => ({ name: s.name, description: s.description }));
- }
- const prefix: typeof skills = [];
- const nameSub: typeof skills = [];
- const descSub: typeof skills = [];
- for (const s of skills) {
- const n = s.name.toLowerCase();
- if (n.startsWith(q)) prefix.push(s);
- else if (n.includes(q)) nameSub.push(s);
- else if ((s.description || '').toLowerCase().includes(q)) descSub.push(s);
- }
- return [...prefix, ...nameSub, ...descSub]
- .slice(0, 8)
- .map((s) => ({ name: s.name, description: s.description }));
- }, [input, state.skills]);
+ // Matching logic lives in the shared input composer.
+ const skillSuggestions = React.useMemo(
+ () => buildSkillSuggestions(input, (state.skills || []).map((s) => ({ name: s.name, description: s.description || '' }))),
+ [input, state.skills],
+ );
+
+ // Skill rows render as "#name — description" strings in the shared popup.
+ const skillSuggestionStrings = React.useMemo(
+ () => skillSuggestions.map((s) => `#${s.name}`),
+ [skillSuggestions],
+ );
const [skillSelIdx, setSkillSelIdx] = React.useState(0);
React.useEffect(() => {
@@ -280,10 +164,8 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
const completeSkillSelection = React.useCallback(() => {
const picked = skillSuggestions[skillSelIdx];
if (!picked) return false;
- // If the user already typed something after the hash-token, keep it.
- const rest = input.slice(1).split(/\s(.*)/s)[1] || '';
- const next = rest ? `#${picked.name} ${rest}` : `#${picked.name} `;
- setInputAndCursor(next);
+ // Shared fill helper: keeps any remainder typed after the hash-token.
+ setInputAndCursor(skillFillText(input, picked.name));
return true;
}, [skillSuggestions, skillSelIdx, input]);
@@ -480,12 +362,9 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
const trimmed = input.trim();
if (trimmed) {
onInput(trimmed);
- setInputHistory((prev) => {
- if (prev[prev.length - 1] === trimmed) return prev;
- return [...prev.slice(-99), trimmed];
- });
- setHistoryIndex(-1);
- setHistoryDraft('');
+ // Shared composer history helper (dedup + cap in one place —
+ // input-composer.tsx is the single source of truth for both TUIs).
+ setInputHistory((prev) => pushHistoryLine(prev, trimmed));
setInputAndCursor('');
}
return;
@@ -497,30 +376,19 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
if (key.rightArrow) { setCursorPos((p) => Math.min(input.length, p + 1)); return; }
// Transcript scrolling is terminal-native now (the transcript prints
// into scrollback via <Static>): ↑/↓ navigate input history instead.
+ // Shared composer history helpers (same behavior as chat mode).
if (key.upArrow) {
- if (inputHistory.length === 0) return;
- if (historyIndex === -1) {
- setHistoryDraft(input);
- const next = inputHistory.length - 1;
- setHistoryIndex(next);
- setInputAndCursor(inputHistory[next] ?? '');
- return;
- }
- const next = Math.max(0, historyIndex - 1);
- setHistoryIndex(next);
- setInputAndCursor(inputHistory[next] ?? '');
+ if (inputHistory.history.length === 0) return;
+ const h = historyPrev(inputHistory, input);
+ setInputHistory(h.state);
+ setInputAndCursor(h.input);
return;
}
if (key.downArrow) {
- if (historyIndex === -1) return;
- const next = historyIndex + 1;
- if (next >= inputHistory.length) {
- setHistoryIndex(-1);
- setInputAndCursor(historyDraft);
- return;
- }
- setHistoryIndex(next);
- setInputAndCursor(inputHistory[next] ?? '');
+ if (inputHistory.index === -1) return;
+ const h = historyNext(inputHistory);
+ setInputHistory(h.state);
+ setInputAndCursor(h.input);
return;
}
if ((key as any).home) { setCursorPos(0); return; }
@@ -530,27 +398,19 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
if (key.ctrl && (ch === 'a' || ch === 'A')) { setCursorPos(0); return; }
if (key.ctrl && (ch === 'e' || ch === 'E')) { setCursorPos(input.length); return; }
if (key.backspace || key.delete) {
- if (cursorPos > 0) {
- setInput((prev) => prev.slice(0, cursorPos - 1) + prev.slice(cursorPos));
- setCursorPos((p) => p - 1);
- }
+ const del = backspaceAt(input, cursorPos);
+ setInput(del.input);
+ setCursorPos(del.cursorPos);
return;
}
if (key.ctrl || key.meta) return;
if (ch && ch.length > 0 && !key.escape) {
- const clean = ch
- .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, '')
- .split('')
- .filter((c) => {
- const code = c.charCodeAt(0);
- return (code >= 0x20 && code <= 0x7e) || code >= 0xa0;
- })
- .join('');
- if (clean) {
- setInput((prev) => prev.slice(0, cursorPos) + clean + prev.slice(cursorPos));
- setCursorPos((p) => p + clean.length);
- }
+ // Shared composer char-insert (clean + cursor + flood guard in one
+ // place — same pipeline as the attach TUI and chat mode).
+ const next = insertInputChunk(input, cursorPos, ch);
+ setInput(next.input);
+ setCursorPos(next.cursorPos);
}
return;
}
@@ -667,7 +527,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
// If autocomplete popup is showing and input doesn't exactly match the selected suggestion,
// fill the suggestion into the input instead of submitting
- if (slashSuggestions.length > 0 && trimmed !== slashSuggestions[slashSelIdx]) {
+ if (!shouldSubmitSlash(slashSuggestions, trimmed, slashSelIdx)) {
setInputAndCursor(slashSuggestions[slashSelIdx]);
return;
}
@@ -685,12 +545,9 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
if (trimmed) {
onInput(trimmed);
- setInputHistory((prev) => {
- if (prev[prev.length - 1] === trimmed) return prev;
- return [...prev.slice(-99), trimmed];
- });
- setHistoryIndex(-1);
- setHistoryDraft('');
+ // Shared composer history helper (dedup + cap in one place —
+ // input-composer.tsx is the single source of truth for both TUIs).
+ setInputHistory((prev) => pushHistoryLine(prev, trimmed));
setInputAndCursor('');
return;
}
@@ -880,75 +737,38 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
}
}
- // Up arrow: navigate input history
+ // Up arrow: navigate input history (shared composer helpers)
if (key.upArrow) {
- if (inputHistory.length === 0) return;
- if (historyIndex === -1) {
- setHistoryDraft(input);
- const next = inputHistory.length - 1;
- setHistoryIndex(next);
- setInputAndCursor(inputHistory[next] ?? '');
- return;
- }
- const next = Math.max(0, historyIndex - 1);
- setHistoryIndex(next);
- setInputAndCursor(inputHistory[next] ?? '');
+ if (inputHistory.history.length === 0) return;
+ const h = historyPrev(inputHistory, input);
+ setInputHistory(h.state);
+ setInputAndCursor(h.input);
return;
}
if (key.downArrow) {
- if (historyIndex === -1) return;
- const next = historyIndex + 1;
- if (next >= inputHistory.length) {
- setHistoryIndex(-1);
- setInputAndCursor(historyDraft);
- return;
- }
- setHistoryIndex(next);
- setInputAndCursor(inputHistory[next] ?? '');
+ if (inputHistory.index === -1) return;
+ const h = historyNext(inputHistory);
+ setInputHistory(h.state);
+ setInputAndCursor(h.input);
return;
}
if (key.backspace || key.delete) {
- if (cursorPos > 0) {
- setInput((prev) => prev.slice(0, cursorPos - 1) + prev.slice(cursorPos));
- setCursorPos((p) => p - 1);
- }
+ const del = backspaceAt(input, cursorPos);
+ setInput(del.input);
+ setCursorPos(del.cursorPos);
return;
}
if (key.ctrl || key.meta) return;
if (ch && ch.length > 0 && !key.escape) {
- // Strip control chars and escape-sequence fragments (handles paste).
- // Mouse scroll in raw mode sends SGR sequences like \x1b[<0;row;colM
- // — Ink partially consumes \x1b[ but the remaining fragments (<, ;, digits,
- // M) leak through as individual ch characters. Reject any ch that isn't
- // a normal printable character (ASCII 0x20-0x7E or Unicode >= 0xA0).
- const clean = ch
- .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, '')
- .split('')
- .filter((c) => {
- const code = c.charCodeAt(0);
- return (code >= 0x20 && code <= 0x7e) || code >= 0xa0;
- })
- .join('');
- // Flood guard: a corrupt stream must never be able to grow the input
- // box unboundedly (input bloat previously cascaded into render
- // storms + V8 aborts). Keep typing functional, cap the reservoir.
- const MAX_INPUT_LEN = 8000;
- if (clean) {
- const next = input.slice(0, cursorPos) + clean + input.slice(cursorPos);
- if (next.length > MAX_INPUT_LEN) {
- if (input.length >= MAX_INPUT_LEN) return; // already full — drop silently
- const accepted = MAX_INPUT_LEN - input.length;
- setInput(next.slice(0, MAX_INPUT_LEN));
- setCursorPos((p) => p + accepted);
- } else {
- setInput(next);
- setCursorPos((p) => p + clean.length);
- }
- }
+ // Shared composer char-insert (clean + cursor + flood guard in one
+ // place — same pipeline as the attach TUI and Mercury Code mode).
+ const next = insertInputChunk(input, cursorPos, ch);
+ setInput(next.input);
+ setCursorPos(next.cursorPos);
}
});
@@ -1047,23 +867,10 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
/>
)}
{showInput && state.mode !== 'mercury-code' && slashSuggestions.length > 0 && (
- <Box flexDirection="column" paddingX={1}>
- <Text dimColor>Suggestions (↑↓ navigate · Tab/Enter to select):</Text>
- {slashSuggestions.map((cmd, idx) => (
- <Text key={cmd} color={idx === slashSelIdx ? 'cyan' : 'gray'}>{idx === slashSelIdx ? '›' : ' '} {cmd}</Text>
- ))}
- </Box>
+ <SuggestionList kind="slash" suggestions={slashSuggestions} selectedIndex={slashSelIdx} />
)}
{showInput && state.mode !== 'mercury-code' && skillSuggestions.length > 0 && (
- <Box flexDirection="column" paddingX={1}>
- <Text dimColor>Skills (↑↓ navigate · Tab/Enter to select):</Text>
- {skillSuggestions.map((s, idx) => (
- <Text key={s.name} color={idx === skillSelIdx ? 'magenta' : 'gray'}>
- {idx === skillSelIdx ? '›' : ' '} #{s.name}
- {s.description ? <Text dimColor> — {s.description.slice(0, 70)}{s.description.length > 70 ? '…' : ''}</Text> : null}
- </Text>
- ))}
- </Box>
+ <SuggestionList kind="skill" suggestions={skillSuggestionStrings} selectedIndex={skillSelIdx} />
)}
{state.mode !== 'mercury-code' && <TokenBarView state={state} cols={terminalSize.cols} />}
</Box>
diff --git a/src/ui/attach-tui.tsx b/src/ui/attach-tui.tsx
index 9f86ed4b..3b634963 100644
--- a/src/ui/attach-tui.tsx
+++ b/src/ui/attach-tui.tsx
@@ -1,8 +1,24 @@
import React from 'react';
import { Box, Text, Spacer, Static, useApp, useInput } from 'ink';
-import type { AttachClient, AttachEvent, AttachThread, AttachThreadMessage } from '../cli/attach.js';
+import type { AttachClient, AttachEvent, AttachThread } from '../cli/attach.js';
import { renderMarkdown } from '../utils/markdown.js';
import { useTerminalSize } from './use-terminal-size.js';
+import {
+ SLASH_COMMANDS,
+ buildSlashSuggestions,
+ buildSkillSuggestions,
+ skillFillText,
+ shouldSubmitSlash,
+ createInputHistoryState,
+ pushHistoryLine,
+ historyPrev,
+ historyNext,
+ insertInputChunk,
+ backspaceAt,
+ SuggestionList,
+ type BotRosterEntry,
+ type SkillEntry,
+} from './input-composer.js';
/**
* Attach TUI — the terminal face of `mercury attach`. Native scrollback
@@ -14,6 +30,12 @@ import { useTerminalSize } from './use-terminal-size.js';
* the conversation history comes from the shared session repository, so
* messages from other surfaces are visible as history (live mirroring of
* other surfaces is out of scope in v1).
+ *
+ * Input is built on the SHARED input composer (src/ui/input-composer.tsx) —
+ * the same slash/skill/bot suggestions, Enter-fill contract, and input
+ * history as the main TUI's boot path. Previously the attach surface used a
+ * bare character editor: no pickers, no history — the "close & relaunch
+ * feels different, auto-commands don't work" regression.
*/
interface ThreadInfo {
@@ -108,10 +130,11 @@ export function AttachTui({ client, pid, onExit }: { client: AttachClient; pid:
const [input, setInput] = React.useState('');
const [cursorPos, setCursorPos] = React.useState(0);
+ const [inputHistory, setInputHistory] = React.useState(createInputHistoryState);
- // Same input width as the main TUI's chat/Code input (App.tsx).
- const terminalSize = useTerminalSize();
- const inputWidth = Math.max(40, terminalSize.cols - 4);
+ // ── Shared-composer suggestion state (main-TUI parity) ──
+ const [skills, setSkills] = React.useState<SkillEntry[]>([]);
+ const [bots, setBots] = React.useState<BotRosterEntry[]>([]);
React.useEffect(() => {
client.listThreads()
@@ -119,6 +142,40 @@ export function AttachTui({ client, pid, onExit }: { client: AttachClient; pid:
.catch(() => setThreadsLoaded(true));
}, [client]);
+ // Picker data sources — the same endpoints the web dashboard uses.
+ React.useEffect(() => {
+ let cancelled = false;
+ client.listSkills().then((list) => { if (!cancelled) setSkills(list); }).catch(() => {});
+ client.listBots().then((list) => { if (!cancelled) setBots(list); }).catch(() => {});
+ return () => { cancelled = true; };
+ }, [client]);
+
+ // ── Shared-composer suggestion lists ──
+ const slashSuggestions = React.useMemo(
+ () => buildSlashSuggestions(input, SLASH_COMMANDS, bots),
+ [input, bots],
+ );
+ const skillSuggestions = React.useMemo(
+ () => buildSkillSuggestions(input, skills),
+ [input, skills],
+ );
+
+ // Skill rows render as "#name" strings in the shared popup (descriptions
+ // come from the shared SuggestionList's skill mode).
+ const skillSuggestionStrings = React.useMemo(
+ () => skillSuggestions.map((s) => `#${s.name}`),
+ [skillSuggestions],
+ );
+
+ const [slashSelIdx, setSlashSelIdx] = React.useState(0);
+ React.useEffect(() => { setSlashSelIdx(0); }, [slashSuggestions.length, input]);
+ const [skillSelIdx, setSkillSelIdx] = React.useState(0);
+ React.useEffect(() => { setSkillSelIdx(0); }, [skillSuggestions.length, input]);
+
+ // Same input width as the main TUI's chat/Code input (App.tsx).
+ const terminalSize = useTerminalSize();
+ const inputWidth = Math.max(40, terminalSize.cols - 4);
+
// Live event stream for the attached session.
React.useEffect(() => {
if (!thread) return;
@@ -264,7 +321,7 @@ export function AttachTui({ client, pid, onExit }: { client: AttachClient; pid:
}, [client, prompt]);
useInput((ch, key) => {
- if (ch === '' || (key.ctrl && (key as any).name === 'c')) {
+ if (ch === '\u0003' || (key.ctrl && (key as any).name === 'c')) {
// Detach only: the runtime keeps running.
exit();
return;
@@ -309,36 +366,93 @@ export function AttachTui({ client, pid, onExit }: { client: AttachClient; pid:
if (key.return) {
const trimmed = input.trim();
- if (trimmed) {
- setInput('');
- setCursorPos(0);
- void sendInput(trimmed);
+ if (!trimmed) return;
+ // Same Enter-fill contract as the main TUI: when the slash picker is
+ // showing and Enter was pressed with a non-exact input, FILL first.
+ if (!shouldSubmitSlash(slashSuggestions, trimmed, slashSelIdx)) {
+ const next = slashSuggestions[slashSelIdx] ?? trimmed;
+ setInput(next);
+ setCursorPos(next.length);
+ return;
+ }
+ // Skill picker: first Enter fills `#name ` (keeps any typed remainder);
+ // second Enter submits.
+ if (skillSuggestions.length > 0) {
+ const picked = skillSuggestions[skillSelIdx];
+ const expected = picked ? `#${picked.name}` : '';
+ if (picked && !trimmed.startsWith(expected + ' ') && trimmed !== expected) {
+ const next = skillFillText(input, picked.name);
+ setInput(next);
+ setCursorPos(next.length);
+ return;
+ }
}
+ setInput('');
+ setCursorPos(0);
+ setInputHistory((prev) => pushHistoryLine(prev, trimmed));
+ void sendInput(trimmed);
return;
}
if (key.leftArrow) { setCursorPos((p) => Math.max(0, p - 1)); return; }
if (key.rightArrow) { setCursorPos((p) => Math.min(input.length, p + 1)); return; }
- if (key.backspace || key.delete) {
- if (cursorPos > 0) {
- setInput((prev) => prev.slice(0, cursorPos - 1) + prev.slice(cursorPos));
- setCursorPos((p) => p - 1);
+ // ↑/↓ navigate suggestions when a picker is visible, else input history
+ // (shell-style, same helpers as the main TUI).
+ if (key.upArrow) {
+ if (slashSuggestions.length > 0) {
+ setSlashSelIdx((i) => (i > 0 ? i - 1 : slashSuggestions.length - 1));
+ return;
+ }
+ if (skillSuggestions.length > 0) {
+ setSkillSelIdx((i) => (i > 0 ? i - 1 : skillSuggestions.length - 1));
+ return;
}
+ const h = historyPrev(inputHistory, input);
+ setInputHistory(h.state);
+ setInput(h.input);
+ setCursorPos(h.input.length);
+ return;
+ }
+ if (key.downArrow) {
+ if (slashSuggestions.length > 0) {
+ setSlashSelIdx((i) => (i < slashSuggestions.length - 1 ? i + 1 : 0));
+ return;
+ }
+ if (skillSuggestions.length > 0) {
+ setSkillSelIdx((i) => (i < skillSuggestions.length - 1 ? i + 1 : 0));
+ return;
+ }
+ const h = historyNext(inputHistory);
+ setInputHistory(h.state);
+ setInput(h.input);
+ setCursorPos(h.input.length);
+ return;
+ }
+ if (key.tab) {
+ if (input.startsWith('/') && slashSuggestions.length > 0) {
+ const next = slashSuggestions[slashSelIdx] ?? input;
+ setInput(next);
+ setCursorPos(next.length);
+ } else if (input.startsWith('#') && skillSuggestions.length > 0) {
+ const picked = skillSuggestions[skillSelIdx];
+ if (picked) {
+ const next = skillFillText(input, picked.name);
+ setInput(next);
+ setCursorPos(next.length);
+ }
+ }
+ return;
+ }
+ if (key.backspace || key.delete) {
+ const next = backspaceAt(input, cursorPos);
+ setInput(next.input);
+ setCursorPos(next.cursorPos);
return;
}
if (key.ctrl || key.meta) return;
if (ch && ch.length > 0 && !key.escape) {
- const clean = ch
- .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, '')
- .split('')
- .filter((c) => {
- const code = c.charCodeAt(0);
- return (code >= 0x20 && code <= 0x7e) || code >= 0xa0;
- })
- .join('');
- if (clean) {
- setInput((prev) => prev.slice(0, cursorPos) + clean + prev.slice(cursorPos));
- setCursorPos((p) => p + clean.length);
- }
+ const next = insertInputChunk(input, cursorPos, ch);
+ setInput(next.input);
+ setCursorPos(next.cursorPos);
}
});
@@ -410,6 +524,9 @@ export function AttachTui({ client, pid, onExit }: { client: AttachClient; pid:
<Text color="yellow">{notice}</Text>
</Box>
)}
+ {/* Shared-composer pickers — identical behavior and visuals to the main TUI. */}
+ {slashSuggestions.length > 0 && <SuggestionList kind="slash" suggestions={slashSuggestions} selectedIndex={slashSelIdx} />}
+ {skillSuggestions.length > 0 && <SuggestionList kind="skill" suggestions={skillSuggestionStrings} selectedIndex={skillSelIdx} />}
<Box paddingX={2} flexShrink={0}>
{/* Explicit width, mirroring the main TUI's input: this box used to
rely on Yoga cross-stretch, but its wrapper is direction='row'
@@ -425,7 +542,7 @@ export function AttachTui({ client, pid, onExit }: { client: AttachClient; pid:
</Box>
</Box>
<Box paddingX={3} flexShrink={0}>
- <Text dimColor>↵ send · esc esc exit · ctrl+c detach</Text>
+ <Text dimColor>↵ send · ↑↓ history/suggest · tab complete · ctrl+c detach</Text>
<Spacer />
<Text color="blue" wrap="truncate-end">⚿ {thread ? `${thread.alias} [${thread.shortId}]` : ''} · {providerLabel}{pid != null ? ` · PID ${pid}` : ''}</Text>
</Box>
diff --git a/src/ui/input-composer.tsx b/src/ui/input-composer.tsx
new file mode 100644
index 00000000..3f85e8e3
--- /dev/null
+++ b/src/ui/input-composer.tsx
@@ -0,0 +1,351 @@
+import React from 'react';
+import { Box, Text } from 'ink';
+
+/**
+ * Shared input composer — ONE source of truth for the interactive input
+ * affordances used by every Mercury terminal surface (main TUI boot path and
+ * the attach TUI):
+ *
+ * • the canonical slash-command list (`SLASH_COMMANDS`)
+ * • slash + skill + bot-argument suggestion builders
+ * • input-history state helpers
+ * • the suggestion popup rendering
+ *
+ * The main TUI and the attach TUI both import from here. Before this module,
+ * the suggestion logic lived only in App.tsx and the attach TUI shipped with
+ * a bare character editor — which is exactly the "close & relaunch feels
+ * different, auto-commands don't work" regression.
+ */
+
+// ─── Canonical command list ─────────────────────────────────────────────────
+
+/**
+ * Canonical slash-command list, shared by the main TUI (App.tsx) and the
+ * attach TUI. Kept deliberately as a plain exported constant so the
+ * autocomplete-sync contract test can assert on it.
+ */
+export const SLASH_COMMANDS: readonly string[] = [
+ '/help',
+ '/whatsnew',
+ '/update ignore',
+ '/log',
+ '/sessions',
+ '/session new',
+ '/session current',
+ '/session ',
+ '/session archive ',
+ '/session delete ',
+ '/bots',
+ '/bots list',
+ '/bots open ',
+ '/bots create ',
+ '/bots send ',
+ '/bots persona ',
+ '/bots budget ',
+ '/bots edit ',
+ '/bots delete ',
+ '/bots journal ',
+ '/bots inbox ',
+ '/bots storage',
+ '/bots enable ',
+ '/bots disable ',
+ '/bots stop ',
+ '/status',
+ '/progress',
+ '/menu',
+ '/chat',
+ '/code',
+ '/code plan',
+ '/code execute',
+ '/code build',
+ '/code diff',
+ '/code init',
+ '/code workspace',
+ '/code agent ',
+ '/code off',
+ '/code toggle',
+ '/code exit',
+ '/code chat',
+ '/code back',
+ '/research',
+ '/research on',
+ '/research off',
+ '/research toggle',
+ '/research ',
+ '/spotify',
+ '/budget',
+ '/permissions',
+ '/memory',
+ '/models',
+ '/models use ',
+ '/cloud',
+ '/cloud models',
+ '/cloud use ',
+ '/agents',
+ '/agents stop ',
+ '/agents pause ',
+ '/agents resume ',
+ '/bg',
+ '/bg current',
+ '/bg list',
+ '/bg cancel ',
+ '/bg clear',
+ '/bg killall',
+ '/stop',
+ '/halt',
+ '/reset',
+ '/tools',
+ '/skills',
+ '/skills search ',
+ '/skills view ',
+ '/skills install ',
+ '/skills remove ',
+ '/skills help',
+ '/stream',
+ '/saver',
+ '/saver on',
+ '/saver off',
+ '/saver toggle',
+ '/saver threshold ',
+ '/saver auto on',
+ '/saver auto off',
+ '/saver routing on',
+ '/saver routing off',
+ '/view',
+ '/view balanced',
+ '/view detailed',
+ '/ws',
+ '/ws open ',
+ '/ws exit',
+ '/ws refresh',
+ '/ws stage all',
+ '/ws commit ',
+ '/ws help',
+] as const;
+
+/** Suggestion cap for the slash picker. */
+const MAX_SUGGESTIONS = 5;
+
+/** Skill suggestions show more rows (name + description lines). */
+const MAX_SKILL_SUGGESTIONS = 8;
+
+// ─── Types ──────────────────────────────────────────────────────────────────
+
+export interface BotRosterEntry {
+ id: string;
+ name: string;
+}
+
+export interface SkillEntry {
+ name: string;
+ description: string;
+}
+
+// ─── Suggestion builders ────────────────────────────────────────────────────
+
+/**
+ * Slash-command suggestions for the current input. Handles bot-id argument
+ * completion: `/bots <action> <partial>` and `/bot <partial>` suggest real
+ * bot ids from the live roster (mixed with top base-command matches).
+ */
+export function buildSlashSuggestions(
+ input: string,
+ commands: readonly string[] = SLASH_COMMANDS,
+ botRoster: readonly BotRosterEntry[] = [],
+): string[] {
+ if (!input.startsWith('/')) return [];
+ const q = input.toLowerCase();
+ const botsArg = /^(\/bots\s+(?:open|send|journal|inbox|budget|edit|delete|enable|disable|stop|persona)\s+)(\S*)$/.exec(input);
+ const botArg = /^(\/bot\s+)(\S*)$/.exec(input);
+ if ((botsArg || botArg) && botRoster.length > 0) {
+ const [, cmdPrefix, typed] = (botsArg ?? botArg)! as unknown as [string, string, string];
+ const p = typed.toLowerCase();
+ const botCmds = botRoster
+ .filter((b) => b.id.startsWith(p) || b.name.toLowerCase().startsWith(p))
+ .slice(0, MAX_SUGGESTIONS)
+ .map((b) => `${cmdPrefix}${b.id}`);
+ const base = commands.filter((cmd) => cmd.startsWith(q)).slice(0, 2);
+ return [...botCmds, ...base].slice(0, MAX_SUGGESTIONS);
+ }
+ return commands.filter((cmd) => cmd.startsWith(q)).slice(0, MAX_SUGGESTIONS);
+}
+
+/**
+ * Skill suggestions for `#name` input. Prefix match first, then name
+ * substring, then description substring (case-insensitive).
+ */
+export function buildSkillSuggestions(
+ input: string,
+ skills: readonly SkillEntry[] = [],
+): Array<{ name: string; description: string }> {
+ if (!input.startsWith('#')) return [];
+ const q = input.slice(1).split(/\s/)[0].toLowerCase();
+ if (!q) {
+ return skills.slice(0, MAX_SKILL_SUGGESTIONS).map((s) => ({ name: s.name, description: s.description }));
+ }
+ const prefix: SkillEntry[] = [];
+ const nameSub: SkillEntry[] = [];
+ const descSub: SkillEntry[] = [];
+ for (const s of skills) {
+ const n = s.name.toLowerCase();
+ if (n.startsWith(q)) prefix.push(s);
+ else if (n.includes(q)) nameSub.push(s);
+ else if ((s.description || '').toLowerCase().includes(q)) descSub.push(s);
+ }
+ return [...prefix, ...nameSub, ...descSub]
+ .slice(0, MAX_SKILL_SUGGESTIONS)
+ .map((s) => ({ name: s.name, description: s.description }));
+}
+
+// ─── Input history helpers ──────────────────────────────────────────────────
+
+export interface InputHistoryState {
+ history: string[];
+ index: number;
+ draft: string;
+}
+
+/**
+ * Shell-style input history state: ↑ walks backwards, ↓ walks forwards,
+ * editing mid-walk snapshots the draft, submissions dedup consecutive
+ * repeats. Pure state helpers — both TUIs share identical navigation.
+ */
+export function createInputHistoryState(): InputHistoryState {
+ return { history: [], index: -1, draft: '' };
+}
+
+/** Record a submitted line. Consecutive duplicates collapse. */
+export function pushHistoryLine(state: InputHistoryState, line: string): InputHistoryState {
+ if (state.history[state.history.length - 1] === line) return state;
+ return { ...state, history: [...state.history.slice(-99), line], index: -1, draft: '' };
+}
+
+export function historyPrev(state: InputHistoryState, currentInput: string): { state: InputHistoryState; input: string } {
+ if (state.history.length === 0) return { state, input: currentInput };
+ if (state.index === -1) {
+ const next = state.history.length - 1;
+ return { state: { ...state, index: next, draft: currentInput }, input: state.history[next] ?? currentInput };
+ }
+ const next = Math.max(0, state.index - 1);
+ return { state: { ...state, index: next }, input: state.history[next] ?? currentInput };
+}
+
+export function historyNext(state: InputHistoryState): { state: InputHistoryState; input: string } {
+ if (state.index === -1) return { state, input: '' };
+ const next = state.index + 1;
+ if (next >= state.history.length) {
+ return { state: { ...state, index: -1 }, input: state.draft };
+ }
+ return { state: { ...state, index: next }, input: state.history[next] ?? '' };
+}
+
+// ─── Character cleaning / paste safety ──────────────────────────────────────
+
+/**
+ * Strip control bytes and escape-sequence fragments from a raw `ch` payload.
+ * Mouse scroll in raw mode emits SGR sequences like `\x1b[<0;row;colM` — Ink
+ * partially consumes `\x1b[` and leaks the tail as individual chars, so every
+ * surface must filter non-printables before accepting input.
+ */
+export function cleanPrintableInput(ch: string): string {
+ return ch
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, '')
+ .split('')
+ .filter((c) => {
+ const code = c.charCodeAt(0);
+ return (code >= 0x20 && code <= 0x7e) || code >= 0xa0;
+ })
+ .join('');
+}
+
+/** Flood guard: never let a corrupt stream grow the input unboundedly. */
+export const MAX_INPUT_LEN = 8000;
+
+/**
+ * Insert a cleaned chunk at the cursor position with the flood guard applied.
+ * Returns the (possibly clamped) new input + new cursor position.
+ */
+export function insertInputChunk(
+ input: string,
+ cursorPos: number,
+ chunk: string,
+): { input: string; cursorPos: number } {
+ const clean = cleanPrintableInput(chunk);
+ if (!clean) return { input, cursorPos };
+ const next = input.slice(0, cursorPos) + clean + input.slice(cursorPos);
+ if (next.length > MAX_INPUT_LEN) {
+ if (input.length >= MAX_INPUT_LEN) return { input, cursorPos };
+ const accepted = MAX_INPUT_LEN - input.length;
+ return { input: next.slice(0, MAX_INPUT_LEN), cursorPos: cursorPos + Math.max(0, accepted) };
+ }
+ return { input: next, cursorPos: cursorPos + clean.length };
+}
+
+export function backspaceAt(input: string, cursorPos: number): { input: string; cursorPos: number } {
+ if (cursorPos <= 0) return { input, cursorPos };
+ return {
+ input: input.slice(0, cursorPos - 1) + input.slice(cursorPos),
+ cursorPos: cursorPos - 1,
+ };
+}
+
+// ─── Suggestion popup rendering ─────────────────────────────────────────────
+
+/**
+ * The shared suggestion popup. Identical visual contract on every surface: a
+ * dim header, `›`-selected rows, cyan for slash commands, magenta for skills.
+ * Both TUIs render this directly under the input box.
+ */
+export function SuggestionList({
+ kind,
+ suggestions,
+ selectedIndex,
+}: {
+ kind: 'slash' | 'skill';
+ suggestions: readonly string[];
+ selectedIndex: number;
+}): React.ReactNode {
+ if (suggestions.length === 0) return null;
+ if (kind === 'skill') {
+ const entries = suggestions as unknown as Array<{ name: string; description: string }>;
+ return (
+ <Box flexDirection="column" paddingX={1}>
+ <Text dimColor>Skills (↑↓ navigate · Tab/Enter to select):</Text>
+ {entries.map((s, idx) => (
+ <Text key={s.name} color={idx === selectedIndex ? 'magenta' : 'gray'}>
+ {idx === selectedIndex ? '›' : ' '} #{s.name}
+ {s.description ? <Text dimColor> — {s.description.slice(0, 70)}{s.description.length > 70 ? '…' : ''}</Text> : null}
+ </Text>
+ ))}
+ </Box>
+ );
+ }
+ return (
+ <Box flexDirection="column" paddingX={1}>
+ <Text dimColor>Suggestions (↑↓ navigate · Tab/Enter to select):</Text>
+ {suggestions.map((cmd, idx) => (
+ <Text key={cmd} color={idx === selectedIndex ? 'cyan' : 'gray'}>{idx === selectedIndex ? '›' : ' '} {cmd}</Text>
+ ))}
+ </Box>
+ );
+}
+
+/**
+ * Enter-fill contract for the slash picker: when suggestions are showing and
+ * the typed input does not exactly equal the selected one, Enter must FILL
+ * the suggestion into the input instead of submitting. Returns true when the
+ * caller should submit normally.
+ */
+export function shouldSubmitSlash(slashSuggestions: readonly string[], trimmedInput: string, selectedIndex: number): boolean {
+ if (slashSuggestions.length === 0) return true;
+ return trimmedInput === slashSuggestions[selectedIndex];
+}
+
+/**
+ * Skill-entry fill helper shared by both TUIs: inserts `#name ` while keeping
+ * any remainder typed after the hash-token.
+ */
+export function skillFillText(input: string, pickedName: string): string {
+ const rest = input.slice(1).split(/\s(.*)/s)[1] || '';
+ return rest ? `#${pickedName} ${rest}` : `#${pickedName} `;
+}
\ No newline at end of file