Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(tui): persist input history to ~/.mercury/history; Delete, Ctrl+W/U/K, Alt+arrows
Salman Qureshic3cc2a6a3ff3
diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex 09e73a5c..ce8794ea 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -12,6 +12,7 @@ import { highlightCodeBlock } from '../utils/highlight.js';import { normalizeTerminalText, getViewportWindow } from './terminal-viewport.js';import { useTerminalSize as useSharedTerminalSize } from './use-terminal-size.js';import { useTick, spinnerFrame, elapsedSeconds, SPINNER_FRAMES } from './tick-store.js';+import { loadInputHistory, saveInputHistory } from './input-history-store.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';@@ -112,7 +113,16 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, onInterrconst albumArtCache = React.useRef<Map<string, string>>(new Map());// Shell-style input history — shared composer state (↑/↓ navigation with// draft snapshotting; see input-composer.tsx).- const [inputHistory, setInputHistory] = React.useState(createInputHistoryState);+ // Seeded from ~/.mercury/history (last 500 lines) and persisted on every+ // submission — see input-history-store.ts.+ const [inputHistory, setInputHistory] = React.useState(() => createInputHistoryState(loadInputHistory()));+ const recordHistory = React.useCallback((line: string) => {+ setInputHistory((prev) => {+ const next = pushHistoryLine(prev, line);+ if (next !== prev) saveInputHistory(next.history);+ return next;+ });+ }, []);const [gitCursor, setGitCursor] = React.useState(0);// Ctrl+C: clear the input when it has text; on an empty input the first// tap arms a 1.5 s window and shows a hint, the second tap exits. A single@@ -391,7 +401,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, onInterronInput(trimmed);// 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));+ recordHistory(trimmed);setInputAndCursor('');}return;@@ -559,7 +569,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, onInterronInput(trimmed);// 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));+ recordHistory(trimmed);setInputAndCursor('');return;}diff --git a/src/ui/attach-tui.tsx b/src/ui/attach-tui.tsxindex de35ee84..e3366012 100644--- a/src/ui/attach-tui.tsx+++ b/src/ui/attach-tui.tsx@@ -23,6 +23,7 @@ import {type BotRosterEntry,type SkillEntry,} from './input-composer.js';+import { loadInputHistory, saveInputHistory } from './input-history-store.js';/*** Attach TUI — the terminal face of `mercury attach`. Native scrollback@@ -134,7 +135,8 @@ 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 persisted history as the main TUI (~/.mercury/history).+ const [inputHistory, setInputHistory] = React.useState(() => createInputHistoryState(loadInputHistory()));// ── Shared-composer suggestion state (main-TUI parity) ──const [skills, setSkills] = React.useState<SkillEntry[]>([]);@@ -393,7 +395,11 @@ export function AttachTui({ client, pid, onExit }: { client: AttachClient; pid:}setInput('');setCursorPos(0);- setInputHistory((prev) => pushHistoryLine(prev, trimmed));+ setInputHistory((prev) => {+ const next = pushHistoryLine(prev, trimmed);+ if (next !== prev) saveInputHistory(next.history);+ return next;+ });void sendInput(trimmed);return;}diff --git a/src/ui/input-composer.tsx b/src/ui/input-composer.tsxindex ac6ab41a..7d104aa4 100644--- a/src/ui/input-composer.tsx+++ b/src/ui/input-composer.tsx@@ -211,14 +211,18 @@ export interface InputHistoryState {* 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: '' };+/** In-memory cap — matches the persisted file (input-history-store.ts). */+export const INPUT_HISTORY_LIMIT = 500;++/** Fresh history state, optionally seeded from the persisted file (oldest first). */+export function createInputHistoryState(initial: readonly string[] = []): InputHistoryState {+ return { history: initial.slice(-INPUT_HISTORY_LIMIT), 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: '' };+ return { ...state, history: [...state.history.slice(-(INPUT_HISTORY_LIMIT - 1)), line], index: -1, draft: '' };}export function historyPrev(state: InputHistoryState, currentInput: string): { state: InputHistoryState; input: string } {diff --git a/src/ui/input-history-store.test.ts b/src/ui/input-history-store.test.tsnew file mode 100644index 00000000..18810f9c--- /dev/null+++ b/src/ui/input-history-store.test.ts@@ -0,0 +1,79 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdtempSync, rmSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ appendInputHistory,+ decodeHistoryLine,+ encodeHistoryLine,+ historyFilePath,+ loadInputHistory,+ saveInputHistory,+ HISTORY_LIMIT,+} from './input-history-store.js';+import { createInputHistoryState, historyPrev, pushHistoryLine, INPUT_HISTORY_LIMIT } from './input-composer.js';++describe('persistent input history (~/.mercury/history)', () => {+ let home = '';+ let file = '';+ beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'mercury-history-'));+ file = historyFilePath(join(home, 'nested', '.mercury'));+ });+ afterEach(() => { rmSync(home, { recursive: true, force: true }); });++ it('round-trips multi-line entries and backslashes as single rows', () => {+ const line = 'fix this:\nconst a = "x\\\\y";';+ expect(decodeHistoryLine(encodeHistoryLine(line))).toBe(line);+ expect(encodeHistoryLine(line).includes('\n')).toBe(false);+ });++ it('creates the directory, writes mode 0600, and loads oldest-first', () => {+ expect(loadInputHistory(file)).toEqual([]);+ let lines = appendInputHistory([], 'first', file);+ lines = appendInputHistory(lines, 'second\nline', file);+ lines = appendInputHistory(lines, 'second\nline', file); // consecutive dup collapses+ lines = appendInputHistory(lines, ' ', file); // blanks are skipped+ expect(lines).toEqual(['first', 'second\nline']);+ expect(loadInputHistory(file)).toEqual(['first', 'second\nline']);+ expect(statSync(file).mode & 0o777).toBe(0o600);+ });++ it('keeps only the newest HISTORY_LIMIT lines on disk and on load', () => {+ const many = Array.from({ length: HISTORY_LIMIT + 25 }, (_, i) => `cmd ${i}`);+ expect(saveInputHistory(many, file)).toBe(true);+ const rows = readFileSync(file, 'utf8').split('\n').filter(Boolean);+ expect(rows).toHaveLength(HISTORY_LIMIT);+ expect(rows[0]).toBe('cmd 25');+ // An over-long file written by something else is still capped on load.+ writeFileSync(file, Array.from({ length: HISTORY_LIMIT + 10 }, (_, i) => `x${i}`).join('\n') + '\n');+ const loaded = loadInputHistory(file);+ expect(loaded).toHaveLength(HISTORY_LIMIT);+ expect(loaded[loaded.length - 1]).toBe(`x${HISTORY_LIMIT + 9}`);+ });++ it('tightens the mode of a pre-existing world-readable file', () => {+ saveInputHistory(['a'], file);+ writeFileSync(file, 'a\n', { mode: 0o644 });+ // chmod on an existing path: writeFileSync keeps 0o644 unless we fix it+ saveInputHistory(['a', 'b'], file);+ expect(statSync(file).mode & 0o777).toBe(0o600);+ });++ it('seeds the composer history so ↑ recalls the previous session, with the same cap', () => {+ const seeded = createInputHistoryState(['older', 'newest']);+ expect(historyPrev(seeded, 'draft').input).toBe('newest');+ expect(INPUT_HISTORY_LIMIT).toBe(HISTORY_LIMIT);+ let state = createInputHistoryState();+ for (let i = 0; i < INPUT_HISTORY_LIMIT + 5; i++) state = pushHistoryLine(state, `l${i}`);+ expect(state.history).toHaveLength(INPUT_HISTORY_LIMIT);+ expect(state.history[0]).toBe('l5');+ });++ it('never throws when the history file cannot be written', () => {+ expect(saveInputHistory(['x'], join(home, 'not-a-dir-file', 'x', 'history'))).toBe(true); // creates dirs+ writeFileSync(join(home, 'blocker'), '');+ expect(saveInputHistory(['x'], join(home, 'blocker', 'history'))).toBe(false);+ expect(loadInputHistory(join(home, 'blocker', 'history'))).toEqual([]);+ });+});diff --git a/src/ui/input-history-store.ts b/src/ui/input-history-store.tsnew file mode 100644index 00000000..75318e86--- /dev/null+++ b/src/ui/input-history-store.ts@@ -0,0 +1,80 @@+import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from 'node:fs';+import { join } from 'node:path';+import { getMercuryHome } from '../utils/config.js';++/**+ * Persistent input history for the terminal UIs: `~/.mercury/history`,+ * one submitted line per row (embedded newlines are escaped as `\n` so a+ * multi-line prompt stays one history entry), newest last, capped to the+ * most recent `HISTORY_LIMIT` lines, mode 0600 (prompts can carry secrets).+ *+ * Loaded once at TUI start; every submission appends and rewrites the+ * capped file. Every operation is best-effort — a read-only or missing+ * home directory must never break input.+ */+export const HISTORY_LIMIT = 500;+export const HISTORY_FILE_NAME = 'history';++export function historyFilePath(home = getMercuryHome()): string {+ return join(home, HISTORY_FILE_NAME);+}++/** Escape a submitted line into one history row. */+export function encodeHistoryLine(line: string): string {+ return line.replace(/\\/g, '\\\\').replace(/\n/g, '\\n');+}++/** Inverse of `encodeHistoryLine`. */+export function decodeHistoryLine(row: string): string {+ let out = '';+ for (let i = 0; i < row.length; i++) {+ const c = row[i];+ if (c === '\\' && i + 1 < row.length) {+ const n = row[i + 1];+ if (n === 'n') { out += '\n'; i++; continue; }+ if (n === '\\') { out += '\\'; i++; continue; }+ }+ out += c;+ }+ return out;+}++/** Read the persisted history (oldest first). Missing / unreadable → []. */+export function loadInputHistory(file = historyFilePath()): string[] {+ try {+ if (!existsSync(file)) return [];+ const rows = readFileSync(file, 'utf8').split('\n').filter((r) => r.length > 0);+ return rows.slice(-HISTORY_LIMIT).map(decodeHistoryLine);+ } catch {+ return [];+ }+}++/** Rewrite the file with the newest `HISTORY_LIMIT` lines, mode 0600. */+export function saveInputHistory(lines: readonly string[], file = historyFilePath()): boolean {+ try {+ const dir = join(file, '..');+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });+ const body = lines.slice(-HISTORY_LIMIT).map(encodeHistoryLine).join('\n');+ writeFileSync(file, body.length > 0 ? body + '\n' : '', { encoding: 'utf8', mode: 0o600 });+ // writeFileSync's mode only applies on creation; an existing file keeps+ // whatever it had — tighten it every time.+ try { chmodSync(file, 0o600); } catch { /* best effort */ }+ return true;+ } catch {+ return false;+ }+}++/**+ * Append one submitted line. Consecutive duplicates collapse (same rule as+ * the in-memory history). Returns the new in-memory list.+ */+export function appendInputHistory(existing: readonly string[], line: string, file = historyFilePath()): string[] {+ const trimmed = line.trim();+ if (!trimmed) return [...existing];+ if (existing[existing.length - 1] === trimmed) return [...existing];+ const next = [...existing, trimmed].slice(-HISTORY_LIMIT);+ saveInputHistory(next, file);+ return next;+}