xonecas.io
64875
Mc

mini-coder / commit d093f31

feat(ui): add Ctrl+R prompt history search

Persist raw submitted prompts for global input history search and restore them into the input overlay.

Also update cel-tui to 0.4.1 for the upstream input and tmux fixes.

xonecas2026-04-07 d093f311a186935b201535d824f36f52f83a5a79 parent 58150b7

7 files changed

package.json+2−2
@@ -18,8 +18,8 @@
1818 "test": "bun test"
1919 },
2020 "dependencies": {
21- "@cel-tui/components": "^0.4.0",
22- "@cel-tui/core": "^0.4.0",
21+ "@cel-tui/components": "^0.4.1",
22+ "@cel-tui/core": "^0.4.1",
2323 "@mariozechner/pi-ai": "^0.65.0",
2424 "diff": "^8.0.4"
2525 },
spec.md+14−0
@@ -519,6 +519,7 @@ Multi-line text input with no prompt prefix — the blinking cursor is the affor
519519 Supports:
520520
521521 - `Tab` for file path autocomplete.
522+- `Ctrl+R` for global input history search. Opens the same centered Select overlay pattern used by interactive commands, populated with previously submitted raw prompt text from all sessions and working directories, newest first. The list is searchable, selecting an entry restores the exact raw prompt into the input for editing (it does not auto-submit), and dismissing the overlay leaves the current draft unchanged.
522523 - `/command` prefix for slash commands.
523524 - `/skill:skill-name` prefix to inject a skill's body into the user message. The `/skill:name` prefix is stripped from the input and the skill's `SKILL.md` body is prepended to the user message content. The rest of the input becomes the user's instruction. Example: `/skill:code-review check the auth module` sends the code-review skill body + "check the auth module" as the user message.
524525 - Image embedding: if we autocomplete a file path ending in `.png`, `.jpg`, `.jpeg`, `.gif`, or `.webp`, and the file exists, it is embedded as `ImageContent` in the user message (base64-encoded). Only when the current model supports image input (`Model.input` includes `"image"`). If the model doesn't support images, or the file doesn't exist, or the input contains other text, the path is sent as plain text. This is intentionally simple — no inline detection within sentences.
@@ -531,6 +532,7 @@ Supports:
531532 | `Shift+Enter` | Input focused | Insert newline |
532533 | `Escape` | Agent working | Interrupt current turn, preserve partial response |
533534 | `Tab` | Input focused | File path autocomplete |
535+| `Ctrl+R` | Input focused | Search global raw input history |
534536 | `Ctrl+C` | Any | Graceful exit |
535537 | `Ctrl+D` | Input empty | Graceful exit (EOF) |
536538 | `Ctrl+Z` | Any | Suspend/background process |
@@ -623,6 +625,16 @@ CREATE TABLE messages (
623625 );
624626
625627 CREATE INDEX idx_messages_session ON messages(session_id, turn);
628+
629+CREATE TABLE prompt_history (
630+ id INTEGER PRIMARY KEY AUTOINCREMENT,
631+ text TEXT NOT NULL, -- exact raw submitted prompt text
632+ cwd TEXT NOT NULL, -- working directory where it was submitted
633+ session_id TEXT, -- optional originating session id for display/context only
634+ created_at INTEGER NOT NULL -- unix ms
635+);
636+
637+CREATE INDEX idx_prompt_history_created_at ON prompt_history(created_at, id);
626638 ```
627639
628640 ### Design decisions
@@ -639,6 +651,8 @@ CREATE INDEX idx_messages_session ON messages(session_id, turn);
639651
640652 **Session truncation**: sessions are truncated per cwd to keep only the 20 most recently updated sessions (`updated_at DESC`), deleting older sessions and their messages via cascade.
641653
654+**Raw input history is global and append-only**: submitted prompt text is also recorded separately in `prompt_history` as the exact raw input the user entered before any `/skill:name` expansion or image conversion. This history is global across sessions and working directories, ordered newest first for `Ctrl+R` search, and is independent from conversational turn state — `/undo` does not remove entries from it. To bound storage, only the 1000 most recent prompt-history rows are kept.
655+
642656 ### Operations
643657
644658 | Operation | SQL |
src/index.ts+3−0
@@ -83,6 +83,9 @@ export { DEFAULT_SHOW_REASONING, DEFAULT_VERBOSE } from "./settings.ts";
8383 /** Maximum sessions to keep per CWD. */
8484 export const MAX_SESSIONS_PER_CWD = 20;
8585
86+/** Maximum raw prompt-history entries to retain globally. */
87+export const MAX_PROMPT_HISTORY = 1_000;
88+
8689 // ---------------------------------------------------------------------------
8790 // OAuth credential persistence
8891 // ---------------------------------------------------------------------------
src/session.test.ts+78−0
@@ -7,6 +7,7 @@ import type {
77 } from "@mariozechner/pi-ai";
88 import {
99 appendMessage,
10+ appendPromptHistory,
1011 computeStats,
1112 createSession,
1213 createUiMessage,
@@ -14,9 +15,11 @@ import {
1415 filterModelMessages,
1516 forkSession,
1617 getSession,
18+ listPromptHistory,
1719 listSessions,
1820 loadMessages,
1921 openDatabase,
22+ truncatePromptHistory,
2023 truncateSessions,
2124 undoLastTurn,
2225 } from "./session.ts";
@@ -410,6 +413,81 @@ describe("fork", () => {
410413 });
411414 });
412415
416+describe("prompt history", () => {
417+ test("listPromptHistory returns newest prompts first across sessions and CWDs", () => {
418+ const db = openDatabase(":memory:");
419+ const sessionA = createSession(db, { cwd: "/tmp/a" });
420+ const sessionB = createSession(db, { cwd: "/tmp/b" });
421+
422+ appendPromptHistory(db, {
423+ text: "first prompt",
424+ cwd: sessionA.cwd,
425+ sessionId: sessionA.id,
426+ });
427+ appendPromptHistory(db, {
428+ text: "second prompt",
429+ cwd: sessionB.cwd,
430+ sessionId: sessionB.id,
431+ });
432+ appendPromptHistory(db, {
433+ text: "third prompt",
434+ cwd: sessionA.cwd,
435+ });
436+
437+ const history = listPromptHistory(db);
438+
439+ expect(history.map((entry) => entry.text)).toEqual([
440+ "third prompt",
441+ "second prompt",
442+ "first prompt",
443+ ]);
444+ expect(history.map((entry) => entry.cwd)).toEqual([
445+ "/tmp/a",
446+ "/tmp/b",
447+ "/tmp/a",
448+ ]);
449+ expect(history[0]?.sessionId).toBeNull();
450+ expect(history[1]?.sessionId).toBe(sessionB.id);
451+ expect(history[2]?.sessionId).toBe(sessionA.id);
452+ db.close();
453+ });
454+
455+ test("listPromptHistory preserves duplicate prompts", () => {
456+ const db = openDatabase(":memory:");
457+
458+ appendPromptHistory(db, { text: "repeat", cwd: "/tmp/test" });
459+ appendPromptHistory(db, { text: "repeat", cwd: "/tmp/test" });
460+
461+ const history = listPromptHistory(db);
462+
463+ expect(history).toHaveLength(2);
464+ expect(history[0]?.text).toBe("repeat");
465+ expect(history[1]?.text).toBe("repeat");
466+ expect(history[0]?.id).not.toBe(history[1]?.id);
467+ db.close();
468+ });
469+
470+ test("truncatePromptHistory keeps the newest entries", () => {
471+ const db = openDatabase(":memory:");
472+
473+ for (let i = 1; i <= 5; i++) {
474+ appendPromptHistory(db, {
475+ text: `prompt ${i}`,
476+ cwd: "/tmp/test",
477+ });
478+ }
479+
480+ truncatePromptHistory(db, 3);
481+
482+ expect(listPromptHistory(db).map((entry) => entry.text)).toEqual([
483+ "prompt 5",
484+ "prompt 4",
485+ "prompt 3",
486+ ]);
487+ db.close();
488+ });
489+});
490+
413491 describe("cumulative stats", () => {
414492 test("computeStats sums usage from assistant messages", () => {
415493 const messages: Message[] = [
src/session.ts+118−0
@@ -59,6 +59,30 @@ export interface SessionStats {
5959 totalCost: number;
6060 }
6161
62+/** A raw submitted prompt stored for global input-history search. */
63+export interface PromptHistoryEntry {
64+ /** Monotonic row id. */
65+ id: number;
66+ /** Exact raw prompt text as submitted by the user. */
67+ text: string;
68+ /** Working directory where the prompt was submitted. */
69+ cwd: string;
70+ /** Originating session id when available. */
71+ sessionId: string | null;
72+ /** Unix timestamp in milliseconds when the prompt was submitted. */
73+ createdAt: number;
74+}
75+
76+/** Options for appending a raw prompt-history entry. */
77+export interface AppendPromptHistoryOpts {
78+ /** Exact raw prompt text as submitted by the user. */
79+ text: string;
80+ /** Working directory where the prompt was submitted. */
81+ cwd: string;
82+ /** Originating session id when available. */
83+ sessionId?: string;
84+}
85+
6286 /** A persisted UI-only message shown in the conversation log. */
6387 export interface UiMessage {
6488 /** Identifies this as an internal UI message. */
@@ -105,6 +129,15 @@ type MaxTurnRow = { max_turn: number | null };
105129 /** Row shape for `SELECT data` queries. */
106130 type DataRow = { data: string };
107131
132+/** Row shape returned by `SELECT * FROM prompt_history`. */
133+type PromptHistoryRow = {
134+ id: number;
135+ text: string;
136+ cwd: string;
137+ session_id: string | null;
138+ created_at: number;
139+};
140+
108141 // ---------------------------------------------------------------------------
109142 // SQL
110143 // ---------------------------------------------------------------------------
@@ -114,6 +147,8 @@ const SQL = {
114147 "SELECT * FROM sessions WHERE cwd = ? ORDER BY updated_at DESC, rowid DESC",
115148 maxTurn: "SELECT MAX(turn) as max_turn FROM messages WHERE session_id = ?",
116149 loadMessages: "SELECT data FROM messages WHERE session_id = ? ORDER BY id",
150+ listPromptHistory:
151+ "SELECT * FROM prompt_history ORDER BY created_at DESC, id DESC LIMIT ?",
117152 } as const;
118153
119154 const SCHEMA = `
@@ -138,6 +173,16 @@ CREATE TABLE IF NOT EXISTS messages (
138173 );
139174
140175 CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id, turn);
176+
177+CREATE TABLE IF NOT EXISTS prompt_history (
178+ id INTEGER PRIMARY KEY AUTOINCREMENT,
179+ text TEXT NOT NULL,
180+ cwd TEXT NOT NULL,
181+ session_id TEXT,
182+ created_at INTEGER NOT NULL
183+);
184+
185+CREATE INDEX IF NOT EXISTS idx_prompt_history_created_at ON prompt_history(created_at, id);
141186 `;
142187
143188 // ---------------------------------------------------------------------------
@@ -447,6 +492,79 @@ export function loadMessages(
447492 return rows.map((row) => JSON.parse(row.data) as PersistedMessage);
448493 }
449494
495+// ---------------------------------------------------------------------------
496+// Prompt history
497+// ---------------------------------------------------------------------------
498+
499+/**
500+ * Append a raw submitted prompt to the global prompt-history table.
501+ *
502+ * This history is separate from conversational turn state: it is global,
503+ * append-only, and not affected by `/undo`.
504+ *
505+ * @param db - Open database handle.
506+ * @param opts - Prompt-history fields to persist.
507+ * @returns The stored {@link PromptHistoryEntry}.
508+ */
509+export function appendPromptHistory(
510+ db: Database,
511+ opts: AppendPromptHistoryOpts,
512+): PromptHistoryEntry {
513+ const now = Date.now();
514+ const result = db.run(
515+ "INSERT INTO prompt_history (text, cwd, session_id, created_at) VALUES (?, ?, ?, ?)",
516+ [opts.text, opts.cwd, opts.sessionId ?? null, now],
517+ );
518+
519+ return {
520+ id: Number(result.lastInsertRowid),
521+ text: opts.text,
522+ cwd: opts.cwd,
523+ sessionId: opts.sessionId ?? null,
524+ createdAt: now,
525+ };
526+}
527+
528+/**
529+ * List raw submitted prompts newest first.
530+ *
531+ * @param db - Open database handle.
532+ * @param limit - Maximum number of entries to return.
533+ * @returns Prompt-history entries ordered newest first.
534+ */
535+export function listPromptHistory(
536+ db: Database,
537+ limit = Number.MAX_SAFE_INTEGER,
538+): PromptHistoryEntry[] {
539+ const rows = db
540+ .query<PromptHistoryRow, [number]>(SQL.listPromptHistory)
541+ .all(limit);
542+ return rows.map((row) => ({
543+ id: row.id,
544+ text: row.text,
545+ cwd: row.cwd,
546+ sessionId: row.session_id,
547+ createdAt: row.created_at,
548+ }));
549+}
550+
551+/**
552+ * Keep only the newest prompt-history rows.
553+ *
554+ * @param db - Open database handle.
555+ * @param keep - Maximum number of prompt-history rows to retain.
556+ */
557+export function truncatePromptHistory(db: Database, keep: number): void {
558+ db.run(
559+ `DELETE FROM prompt_history WHERE id IN (
560+ SELECT id FROM prompt_history
561+ ORDER BY created_at DESC, id DESC
562+ LIMIT -1 OFFSET ?
563+ )`,
564+ [keep],
565+ );
566+}
567+
450568 // ---------------------------------------------------------------------------
451569 // Undo
452570 // ---------------------------------------------------------------------------
src/ui.test.ts+184−1
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
22 import { mkdtempSync, rmSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
5-import type { Node } from "@cel-tui/types";
5+import type { ContainerNode, Node } from "@cel-tui/types";
66 import type { AssistantMessage, Model } from "@mariozechner/pi-ai";
77 import {
88 createAssistantMessageEventStream,
@@ -16,6 +16,7 @@ import {
1616 } from "@mariozechner/pi-ai";
1717 import type { AppState } from "./index.ts";
1818 import {
19+ appendPromptHistory,
1920 createSession,
2021 createUiMessage,
2122 loadMessages,
@@ -38,12 +39,14 @@ import {
3839 type InputController,
3940 type PendingToolCall,
4041 previewToolRenderLines,
42+ renderActiveOverlay,
4143 renderAssistantMessage,
4244 renderBaseLayout,
4345 renderInputArea,
4446 renderStatusBar,
4547 renderStreamingResponse,
4648 renderToolResult,
49+ resetUiState,
4750 type ToolRenderLine,
4851 } from "./ui.ts";
4952
@@ -85,6 +88,22 @@ function findTextNode(node: Node | null, content: string): Node | null {
8588 return null;
8689 }
8790
91+function findNodeWithKeyPress(node: Node | null): ContainerNode | null {
92+ if (!node || node.type === "textinput" || node.type === "text") {
93+ return null;
94+ }
95+ if (typeof node.props.onKeyPress === "function") {
96+ return node;
97+ }
98+ for (const child of node.children) {
99+ const found = findNodeWithKeyPress(child);
100+ if (found) {
101+ return found;
102+ }
103+ }
104+ return null;
105+}
106+
88107 const tempDirs: string[] = [];
89108
90109 function createTempDir(): string {
@@ -153,6 +172,7 @@ function makeAssistantWithUsage(
153172 }
154173
155174 afterEach(() => {
175+ resetUiState();
156176 for (const dir of tempDirs.splice(0)) {
157177 rmSync(dir, { recursive: true, force: true });
158178 }
@@ -430,6 +450,43 @@ describe("ui rendering", () => {
430450 }
431451 });
432452
453+ test("submitted prompts are stored as raw global input-history entries", async () => {
454+ const faux = registerFauxProvider();
455+ const state = createTestState();
456+ const originalPath = process.env.PATH;
457+ process.env.PATH = `${process.env.PATH ?? ""}:/usr/bin:/bin`;
458+ state.cwd = process.cwd();
459+ state.canonicalCwd = process.cwd();
460+ state.model = faux.getModel();
461+ faux.setResponses([fauxAssistantMessage("Done.")]);
462+
463+ try {
464+ handleInput(" hello from history ", state);
465+
466+ await waitFor(() => state.session !== null);
467+ const rows = state.db
468+ .query<
469+ { text: string; cwd: string; session_id: string | null },
470+ []
471+ >("SELECT text, cwd, session_id FROM prompt_history ORDER BY id DESC LIMIT 1")
472+ .all();
473+
474+ expect(rows).toHaveLength(1);
475+ expect(rows[0]?.text).toBe(" hello from history ");
476+ expect(rows[0]?.cwd).toBe(state.cwd);
477+ expect(rows[0]?.session_id).toBe(state.session?.id ?? null);
478+
479+ await waitFor(() =>
480+ state.messages.some((message) => message.role === "assistant"),
481+ );
482+ } finally {
483+ await stopRunningTurn(state);
484+ process.env.PATH = originalPath;
485+ faux.unregister();
486+ state.db.close();
487+ }
488+ });
489+
433490 test("/new clears the active session and defers replacement session creation", async () => {
434491 const faux = registerFauxProvider();
435492 const state = createTestState();
@@ -758,6 +815,132 @@ describe("ui rendering", () => {
758815 }
759816 });
760817
818+ test("Ctrl+R opens input history with newest prompts first", () => {
819+ const state = createTestState();
820+
821+ try {
822+ appendPromptHistory(state.db, {
823+ text: "older prompt",
824+ cwd: "/tmp/older",
825+ });
826+ appendPromptHistory(state.db, {
827+ text: "newest prompt",
828+ cwd: "/tmp/newer",
829+ });
830+
831+ const controller = createInputController(state);
832+ const base = renderBaseLayout(state, 80, controller);
833+
834+ expect(base.type).toBe("vstack");
835+ if (base.type !== "vstack") {
836+ throw new Error("Expected base layout to be a vstack");
837+ }
838+
839+ base.props.onKeyPress?.("ctrl+r");
840+
841+ const overlay = renderActiveOverlay(state);
842+ const text = collectText(overlay);
843+ const newestIndex = text.findIndex((line) =>
844+ line.includes("newest prompt"),
845+ );
846+ const olderIndex = text.findIndex((line) =>
847+ line.includes("older prompt"),
848+ );
849+
850+ expect(overlay).not.toBeNull();
851+ expect(text).toContain("Input history");
852+ expect(newestIndex).toBeGreaterThan(-1);
853+ expect(olderIndex).toBeGreaterThan(-1);
854+ expect(newestIndex).toBeLessThan(olderIndex);
855+ } finally {
856+ state.db.close();
857+ }
858+ });
859+
860+ test("selecting input history restores the exact raw prompt into the input", () => {
861+ const state = createTestState();
862+ const rawPrompt = "first line\nsecond line";
863+
864+ try {
865+ appendPromptHistory(state.db, {
866+ text: "older prompt",
867+ cwd: "/tmp/older",
868+ });
869+ appendPromptHistory(state.db, {
870+ text: rawPrompt,
871+ cwd: state.cwd,
872+ });
873+
874+ const controller = createInputController(state);
875+ const base = renderBaseLayout(state, 80, controller);
876+ if (base.type !== "vstack") {
877+ throw new Error("Expected base layout to be a vstack");
878+ }
879+
880+ base.props.onKeyPress?.("ctrl+r");
881+
882+ const overlay = renderActiveOverlay(state);
883+ const selectNode = findNodeWithKeyPress(overlay);
884+
885+ expect(selectNode).not.toBeNull();
886+ if (!selectNode) {
887+ throw new Error("Expected overlay to contain a Select root");
888+ }
889+
890+ selectNode.props.onKeyPress?.("enter");
891+
892+ expect(renderActiveOverlay(state)).toBeNull();
893+ const input = renderInputArea(state.theme, controller);
894+ if (input.type !== "textinput") {
895+ throw new Error("Expected input area to render a TextInput");
896+ }
897+ expect(input.props.value).toBe(rawPrompt);
898+ } finally {
899+ state.db.close();
900+ }
901+ });
902+
903+ test("dismissing input history keeps the current draft unchanged", () => {
904+ const state = createTestState();
905+ const draft = "draft prompt";
906+
907+ try {
908+ appendPromptHistory(state.db, {
909+ text: "saved prompt",
910+ cwd: state.cwd,
911+ });
912+
913+ const controller = createInputController(state);
914+ controller.onChange(draft);
915+
916+ const base = renderBaseLayout(state, 80, controller);
917+ if (base.type !== "vstack") {
918+ throw new Error("Expected base layout to be a vstack");
919+ }
920+
921+ base.props.onKeyPress?.("ctrl+r");
922+
923+ const overlay = renderActiveOverlay(state);
924+ const selectNode = findNodeWithKeyPress(overlay);
925+
926+ expect(selectNode).not.toBeNull();
927+ if (!selectNode) {
928+ throw new Error("Expected overlay to contain a Select root");
929+ }
930+
931+ selectNode.props.onBlur?.();
932+
933+ expect(renderActiveOverlay(state)).toBeNull();
934+ const input = renderInputArea(state.theme, controller);
935+ if (input.type !== "textinput") {
936+ throw new Error("Expected input area to render a TextInput");
937+ }
938+ expect(input.props.value).toBe(draft);
939+ } finally {
940+ state.db.close();
941+ }
942+ });
943+
761944 test("renderToolResult uses themed accent colors for tool headers", () => {
762945 const theme: Theme = {
763946 ...DEFAULT_THEME,
src/ui.ts+103−7
@@ -40,6 +40,7 @@ import {
4040 buildPrompt,
4141 buildToolList,
4242 getAvailableModels,
43+ MAX_PROMPT_HISTORY,
4344 MAX_SESSIONS_PER_CWD,
4445 saveOAuthCredentials,
4546 shutdown,
@@ -47,13 +48,16 @@ import {
4748 import { COMMANDS, parseInput } from "./input.ts";
4849 import {
4950 appendMessage,
51+ appendPromptHistory,
5052 computeStats,
5153 createSession,
5254 createUiMessage,
5355 filterModelMessages,
5456 forkSession,
57+ listPromptHistory,
5558 listSessions,
5659 loadMessages,
60+ truncatePromptHistory,
5761 truncateSessions,
5862 type UiMessage,
5963 undoLastTurn,
@@ -190,6 +194,25 @@ let activeOverlay: {
190194 title: string;
191195 } | null = null;
192196
197+/**
198+ * Reset all module-scoped UI state.
199+ *
200+ * Useful for reinitializing the UI and for keeping tests isolated.
201+ */
202+export function resetUiState(): void {
203+ scrollOffset = 0;
204+ stickToBottom = true;
205+ inputValue = "";
206+ inputFocused = true;
207+ dividerTick = 0;
208+ stopDividerAnimation();
209+ streamingText = "";
210+ streamingThinking = "";
211+ isStreaming = false;
212+ pendingToolCalls = [];
213+ activeOverlay = null;
214+}
215+
193216 // ---------------------------------------------------------------------------
194217 // Divider animation
195218 // ---------------------------------------------------------------------------
@@ -1008,6 +1031,19 @@ function renderOverlay(state: AppState): Node {
10081031 );
10091032 }
10101033
1034+/**
1035+ * Render the active overlay when one is open.
1036+ *
1037+ * @param state - Application state.
1038+ * @returns The rendered overlay node, or `null` when no overlay is active.
1039+ */
1040+export function renderActiveOverlay(state: AppState): Node | null {
1041+ if (!activeOverlay) {
1042+ return null;
1043+ }
1044+ return renderOverlay(state);
1045+}
1046+
10111047 // ---------------------------------------------------------------------------
10121048 // Status bar
10131049 // ---------------------------------------------------------------------------
@@ -1264,7 +1300,7 @@ function handleSessionCommand(state: AppState): void {
12641300 const currentSessionId = state.session?.id ?? null;
12651301 const items = sessions.map((s) => {
12661302 const date = new Date(s.updatedAt);
1267- const dateStr = formatSessionDate(date);
1303+ const dateStr = formatRelativeDate(date);
12681304 const model = s.model ?? "no model";
12691305 const current = s.id === currentSessionId ? " (current)" : "";
12701306 return {
@@ -1300,8 +1336,8 @@ function handleSessionCommand(state: AppState): void {
13001336 cel.render();
13011337 }
13021338
1303-/** Format a session date for display. */
1304-function formatSessionDate(date: Date): string {
1339+/** Format a recent timestamp for display. */
1340+function formatRelativeDate(date: Date): string {
13051341 const now = new Date();
13061342 const diffMs = now.getTime() - date.getTime();
13071343 const diffMins = Math.floor(diffMs / 60_000);
@@ -1315,6 +1351,11 @@ function formatSessionDate(date: Date): string {
13151351 return date.toLocaleDateString();
13161352 }
13171353
1354+/** Collapse a raw prompt into a one-line preview for the Select overlay. */
1355+function formatPromptHistoryPreview(text: string): string {
1356+ return text.replace(/\s+/g, " ").trim();
1357+}
1358+
13181359 /** Open a URL in the user's default browser. */
13191360 function openInBrowser(url: string): void {
13201361 const cmd = platform() === "darwin" ? "open" : "xdg-open";
@@ -1707,6 +1748,44 @@ function showCommandAutocomplete(state: AppState): void {
17071748 cel.render();
17081749 }
17091750
1751+/** Show global raw input-history search in the standard Select overlay. */
1752+function showInputHistoryOverlay(state: AppState): void {
1753+ const history = listPromptHistory(state.db);
1754+ if (history.length === 0) {
1755+ return;
1756+ }
1757+
1758+ const items = history.map((entry) => {
1759+ const preview = formatPromptHistoryPreview(entry.text);
1760+ const date = formatRelativeDate(new Date(entry.createdAt));
1761+ return {
1762+ label: `${preview} · ${abbreviatePath(entry.cwd)} · ${date}`,
1763+ value: String(entry.id),
1764+ filterText: `${entry.text} ${entry.cwd}`,
1765+ };
1766+ });
1767+
1768+ const select = Select({
1769+ items,
1770+ maxVisible: OVERLAY_MAX_VISIBLE,
1771+ placeholder: "type to filter history...",
1772+ focused: true,
1773+ highlightColor: state.theme.accentText,
1774+ onSelect: (value) => {
1775+ const picked = history.find((entry) => String(entry.id) === value);
1776+ if (picked) {
1777+ inputValue = picked.text;
1778+ }
1779+ dismissOverlay();
1780+ },
1781+ onBlur: dismissOverlay,
1782+ });
1783+
1784+ inputFocused = false;
1785+ activeOverlay = { select, title: "Input history" };
1786+ cel.render();
1787+}
1788+
17101789 /** Dispatch a parsed command. Returns true if handled. */
17111790 function handleCommand(command: string, state: AppState): boolean {
17121791 switch (command) {
@@ -1764,7 +1843,7 @@ export function handleInput(raw: string, state: AppState): void {
17641843 break;
17651844 case "text":
17661845 if (parsed.text) {
1767- submitMessage(parsed.text, state).catch((err) => {
1846+ submitMessage(parsed.text, state, raw).catch((err) => {
17681847 console.error("Submit error:", err);
17691848 });
17701849 }
@@ -1774,10 +1853,21 @@ export function handleInput(raw: string, state: AppState): void {
17741853 }
17751854
17761855 /** Send a plain text message and run the agent loop. */
1777-async function submitMessage(text: string, state: AppState): Promise<void> {
1856+async function submitMessage(
1857+ text: string,
1858+ state: AppState,
1859+ rawInput = text,
1860+): Promise<void> {
17781861 if (!text.trim() || !state.model || state.running) return;
17791862
17801863 const session = ensureSession(state);
1864+ appendPromptHistory(state.db, {
1865+ text: rawInput,
1866+ cwd: state.cwd,
1867+ sessionId: session.id,
1868+ });
1869+ truncatePromptHistory(state.db, MAX_PROMPT_HISTORY);
1870+
17811871 const userMessage: Message = {
17821872 role: "user",
17831873 content: text,
@@ -1978,6 +2068,10 @@ export function renderBaseLayout(
19782068 {
19792069 height: "100%",
19802070 onKeyPress: (key) => {
2071+ if (key === "ctrl+r") {
2072+ showInputHistoryOverlay(state);
2073+ return;
2074+ }
19812075 if (key === "ctrl+c") {
19822076 gracefulExit(state).catch(() => process.exit(1));
19832077 return;
@@ -2018,6 +2112,7 @@ export function renderBaseLayout(
20182112 * @param state - The initialized application state from {@link init}.
20192113 */
20202114 export function startUI(state: AppState): void {
2115+ resetUiState();
20212116 const terminal = new ProcessTerminal();
20222117 const inputController = createInputController(state);
20232118 cel.init(terminal);
@@ -2025,9 +2120,10 @@ export function startUI(state: AppState): void {
20252120 cel.viewport(() => {
20262121 const cols = terminal.columns;
20272122 const base = renderBaseLayout(state, cols, inputController);
2123+ const overlay = renderActiveOverlay(state);
20282124
2029- if (activeOverlay) {
2030- return [base, renderOverlay(state)];
2125+ if (overlay) {
2126+ return [base, overlay];
20312127 }
20322128 return base;
20332129 });