xonecas.io
79113
Ma

mini-coding-agent / commit 029cb27

feat: interactive picker

xonecas2026-10-25 029cb2783e34fb24c5081a770c69960f113af611 parent f73367a

2 files changed

README.md+67−23
@@ -22,12 +22,17 @@ Arguments:
2222
2323 | Flag | Meaning |
2424 |---|---|
25-| `-p`, `--print` | run one prompt non-interactively and print the assistant text |
26-| `-c`, `--config` | read a config file after the global one; its keys win |
25+| `-p <prompt>`, `--print <prompt>` | run one prompt non-interactively and print the assistant text |
26+| `-c <file>`, `--config <file>` | read a config file after the global one; its keys win |
27+
28+`-p=<prompt>`, `--print=<prompt>`, `-c=<file>`, and `--config=<file>` work too.
29+Any other argument exits 1.
2730
2831 `-p` requires a model in the config. Without one it exits 1 and prints where
2932 the config lives. Interactive mode requires a TTY. In `-p` mode tool calls and
3033 tool output go to stderr, the assistant text to stdout; a failed turn exits 1.
34+`SIGINT` and `SIGTERM` cancel the turn and then re-raise, so the exit status is
35+the signal.
3136
3237 ## TUI commands
3338
@@ -35,26 +40,39 @@ tool output go to stderr, the assistant text to stdout; a failed turn exits 1.
3540 |---|---|
3641 | `/help` | list commands and keybindings |
3742 | `/new` | start a new session |
38-| `/provider` | choose the provider and model |
43+| `/provider` | choose the provider, then its model |
3944 | `/model` | choose a model for the current provider |
4045 | `/thinking` | set the thinking level |
4146
42-`/provider`, `/model`, and `/thinking` write the change back to the config file.
47+`/provider` lists only providers whose API key is present. `/model` needs a
48+configured model and asks the provider for its model list over the wire. A
49+custom provider lists what it declares. Choosing a model writes `provider` and
50+`model` back to the config file, then opens the thinking picker; `/thinking`
51+writes `thinkingEffort`. The file written is the one `-c` named, when given.
4352
4453 ## Keybindings
4554
4655 | Key | Meaning |
4756 |---|---|
4857 | `Enter` | submit; on an empty draft after a failure, retry it |
49-| `Shift+Enter` | newline (`Ctrl+J` also works) |
50-| `Esc` | pause the turn at the next step boundary |
51-| `Ctrl+C` | cancel the turn |
52-| `Ctrl+D` | exit on an empty draft |
58+| `Shift+Enter`, `Alt+Enter`, `Ctrl+J` | newline |
59+| `Shift+Up`, `Shift+Down` | walk past input |
5360 | `Ctrl+R` | reverse search past input |
61+| `Esc` | pause the turn at the next step boundary; close a picker |
62+| `Ctrl+C` | cancel the turn; otherwise close a picker or clear the draft |
63+| `Ctrl+D` | exit on an empty draft |
5464 | `Tab` | complete command or path |
65+| `Ctrl+Left`, `Ctrl+Right` | move by word |
66+| `Ctrl+W`, `Ctrl+Backspace`, `Alt+B` | delete the word before the cursor |
67+| `Home`, `Ctrl+A` / `End`, `Ctrl+E` | line start / line end |
68+| `Ctrl+Home`, `Ctrl+End` | draft start / draft end |
69+| `Delete` | delete forward |
5570
5671 While a turn is paused (`Esc`), submitting a message steers the running turn.
5772
73+The status line shows the phase, the elapsed time, the estimated context use
74+against the model's window, and the cache-read share of the last prompt.
75+
5876 ## Tools
5977
6078 The model sees only the tools listed in `tools`; a call to any other name is an
@@ -62,9 +80,16 @@ error.
6280
6381 | Tool | Behavior |
6482 |---|---|
65-| `read` | returns a file's text; `offset` (1-based) and `range` give a line window; text is cut at 100k characters; binary files are refused; `png`/`jpg`/`webp` are returned as an image only when the model accepts image input |
83+| `read` | returns a file's text; `offset` (1-based) and `range` give a line window; text is cut at 100k characters; binary files are refused; `png`/`jpg`/`jpeg`/`webp` are returned as an image only when the model accepts image input, and only if the base64 form stays under 5 MiB |
6684 | `edit` | replaces `oldText`, which must occur exactly once; an empty `oldText` creates a new file and fails if it exists; prints a unified diff |
67-| `bash` | runs `bash -c` in the cwd with a 120s default `timeout`; output keeps the first 10k and last 6k bytes; a before/after snapshot of the cwd reports changed files as diffs |
85+| `bash` | runs `bash -c` in the cwd with a 120s default `timeout`; output keeps the first 10k and last 6k bytes around a truncation marker and ends with an `exit code:` line; a before/after snapshot of the cwd reports changed files as diffs |
86+
87+Both `read` and `edit` expand a leading `~/`. Tool arguments are parsed once at
88+the boundary and validated there; a bad shape fails the call with a message.
89+
90+The TUI renders a summary line per call (the command for `bash`, the path for
91+`read`/`edit`), the output body, and a diff with `+added -removed` counts.
92+`exit code: 0` folds into a `└ exit 0` line.
6893
6994 ## Configure
7095
@@ -86,6 +111,8 @@ A full example:
86111 "discoverAgentFiles": true,
87112 "skillsDirs": ["/home/me/.agents/skills"],
88113 "tools": ["edit", "read", "bash"],
114+ "programStatus": false,
115+ "herdr": false,
89116 "snapshotIgnoreDirs": [".git"],
90117 "snapshotUsesGitignore": true,
91118 "historySize": 100,
@@ -121,21 +148,25 @@ Keys:
121148 |---|---|---|
122149 | `provider` | unset | provider id; built-ins are `opencode` and `opencode-go`, or a `customProviders` id |
123150 | `model` | unset | model id |
124-| `thinkingEffort` | unset | one of `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`; unset sends no reasoning parameter and clamps to what the model accepts |
125-| `showImages` | `false` | display PNGs the `read` tool returns inline using the kitty graphics protocol; requires kitty 0.28+ |
151+| `thinkingEffort` | unset | one of `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`; unset sends no reasoning parameter; a level the model does not accept clamps up to the next accepted one, else down |
152+| `showImages` | `false` | draw the images the `read` tool returns inline using the kitty graphics protocol; requires kitty 0.28+ |
126153 | `systemPrompt` | `""` | prepended to the system prompt |
127154 | `sessionsDir` | `$XDG_STATE_HOME/mini-coding-agent/sessions`, else `$HOME/.local/state/mini-coding-agent/sessions`, else `sessions` | where JSONL session logs go |
128-| `discoverAgentFiles` | `true` | load `AGENTS.md`/`CLAUDE.md` from `$HOME/.agents` and the cwd |
155+| `discoverAgentFiles` | `true` | load `AGENTS.md`/`CLAUDE.md` from `$HOME/.agents` and the cwd, deduplicated by real path |
129156 | `skillsDirs` | `[]` | directories holding `<name>/SKILL.md` skills; each `SKILL.md` needs a `name` in its frontmatter (optional `description`) |
130157 | `tools` | `["edit", "read", "bash"]` | which tools the model sees |
131158 | `customProviders` | `[]` | in-tree provider definitions |
159+| `programStatus` | `false` | report agent state to the terminal with OSC 7501 |
160+| `herdr` | `false` | report agent state to a Herdr pane; only active inside one (`HERDR_ENV=1` with `HERDR_BIN_PATH` and `HERDR_PANE_ID`) |
132161 | `snapshotIgnoreDirs` | `[]` | directory names skipped when the `bash` tool snapshots the cwd for diffs |
133-| `snapshotUsesGitignore` | `true` | also skip directories named in `.gitignore` when snapshotting |
134-| `historySize` | `100` | past inputs kept in `<state dir>/mini-coding-agent/history` for `Ctrl+R` |
162+| `snapshotUsesGitignore` | `true` | also skip paths matched by the `.gitignore` files under the cwd when snapshotting |
163+| `historySize` | `100` | past inputs kept in `<state dir>/mini-coding-agent/history` for `Shift+Up`/`Shift+Down` and `Ctrl+R` |
135164 | `maxDiffLines` | `2000` | diffs longer than this render as a "too large" notice instead of highlighting every line |
136165
137166 Unknown keys are rejected. `provider` and `model` must both be set to make a
138-request; a custom provider must list the model in its `models`.
167+request; a custom provider must list the model in its `models`. Config errors
168+name the file and the parser message, then exit 1. A `-c` file must exist.
169+Saving rewrites the file through a `.tmp` sibling and a rename.
139170
140171 A `customProvider` field:
141172
@@ -144,7 +175,7 @@ A `customProvider` field:
144175 | `id` | yes | the id `provider` selects |
145176 | `name` | no | display name; falls back to `id` |
146177 | `models` | yes | non-empty list of model objects |
147-| `envKeys` | no | environment variables searched, in order, for the API key |
178+| `envKeys` | no | environment variables searched, in order, for the API key; with none the provider is always usable |
148179 | `headers` | no | extra request headers |
149180
150181 A `customProvider` model object; every model carries its own wire and metadata,
@@ -167,16 +198,29 @@ so one provider may mix APIs and base URLs:
167198
168199 The built-in providers are named, keyed and described by the embedded models.dev
169200 document. `opencode` and `opencode-go` read the first present variable in their
170-`env` list (`OPENCODE_API_KEY`). A provider without a key is listed but fails at
171-request time.
201+`env` list (`OPENCODE_API_KEY`), and send the session id as
202+`x-opencode-session`.
203+
204+Each wire carries its own key header:
205+
206+| API | Key header | Path |
207+|---|---|---|
208+| `openai-completions` | `Authorization: Bearer <key>` | `/chat/completions` |
209+| `openai-responses` | `Authorization: Bearer <key>` | `/responses` |
210+| `anthropic-messages` | `x-api-key: <key>`, plus `anthropic-version: 2023-06-01` | `/messages` |
211+| `google-generative-ai` | `x-goog-api-key: <key>` | `/{model}:streamGenerateContent?alt=sse` under `baseUrl` |
212+
213+All requests ask for an SSE stream. A built-in provider with no key is left out
214+of `/provider`, and so is a custom one whose `envKeys` are all unset.
172215
173216 ## Sessions
174217
175218 Each session is a directory under `sessionsDir` named
176-`<timestamp>-<title>-<id>` with a `session.jsonl` inside it. The title is
177-slugified from the first user message. A header line opens the log; every
178-message and every model request is then appended and fsynced. The log is
179-write-only; a write failure stops the turn.
219+`<timestamp>-<title>-<id>` with a `session.jsonl` inside it. The title is the
220+first user message slugified to at most 40 characters, else `session`. A header
221+line opens the log; every message and every model request is then appended and
222+fsynced. The log is write-only; a write failure stops the turn. `/new` closes
223+the current log and opens the next one.
180224
181225 A failed model request is never appended: the attempt stays a request line with
182226 no message, so the context holds no error and the next turn resends the same
src/tui/tui.zig+151−147
@@ -36,10 +36,16 @@ const PendingCall = tool_view.PendingCall;
3636
3737 const Command = commands.Command;
3838
39-const Search = struct {
39+const Picker = struct {
40+ kind: enum { provider, model, thinking, history },
41+ title: []const u8,
42+ ids: []const []const u8 = &.{},
43+ labels: []const []const u8 = &.{},
44+ provider: []const u8 = "",
45+ draft: []const u8 = "",
4046 query: std.ArrayList(u8) = .empty,
41- saved: []const u8 = "",
42- match: ?[]const u8 = null,
47+ matches: std.ArrayList(usize) = .empty,
48+ sel: usize = 0,
4349 };
4450
4551 var resize_flag = std.atomic.Value(bool).init(false);
@@ -123,18 +129,13 @@ const Tui = struct {
123129 last_input_ms: i64 = 0,
124130 command_active: bool = false,
125131
126- search: ?Search = null,
132+ picker_arena: std.heap.ArenaAllocator,
133+ picker_m: std.mem.Allocator = undefined,
127134
128135 hist_index: ?usize = null,
129136 hist_saved: []const u8 = "",
130137
131- prompt_open: bool = false,
132- prompt_options: []const []const u8 = &.{},
133- prompt_ids: []const []const u8 = &.{},
134- prompt_answer: []const u8 = "",
135- prompt_ready: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
136- pending_command: enum { none, provider, model, thinking } = .none,
137- pending_provider: ?[]const u8 = null,
138+ picker: ?Picker = null,
138139
139140 model_thread: ?std.Thread = null,
140141 model_abort: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
@@ -162,6 +163,7 @@ const Tui = struct {
162163 .qarena = std.heap.ArenaAllocator.init(a),
163164 .q = undefined,
164165 .model_arena = std.heap.ArenaAllocator.init(a),
166+ .picker_arena = std.heap.ArenaAllocator.init(a),
165167 .reply = undefined,
166168 };
167169 }
@@ -173,6 +175,7 @@ const Tui = struct {
173175 self.ca = self.calls.allocator();
174176 self.q = self.qarena.allocator();
175177 self.model_m = self.model_arena.allocator();
178+ self.picker_m = self.picker_arena.allocator();
176179 self.editor = editor_mod.Editor.init(self.backing);
177180 self.editor.bind();
178181 self.editor.s = self.s;
@@ -224,9 +227,13 @@ const Tui = struct {
224227 else
225228 std.fmt.allocPrint(self.s, "{s} · no model configured", .{brand}) catch brand);
226229 const loaded = self.opts.loaded;
227- self.push(std.fmt.allocPrint(self.s, "{d} agent files · {d} skills", .{
228- loaded.agent_files, loaded.skills,
229- }) catch "resources");
230+ var parts: std.ArrayList([]const u8) = .empty;
231+ if (loaded.agent_files > 0)
232+ parts.append(self.s, plural(self.s, loaded.agent_files, "agent file", "agent files")) catch {};
233+ if (loaded.skills > 0)
234+ parts.append(self.s, plural(self.s, loaded.skills, "skill", "skills")) catch {};
235+ if (parts.items.len > 0)
236+ self.push(styles.comment(self.s, std.mem.join(self.s, " · ", parts.items) catch "resources"));
230237 self.scrollback.separator = true;
231238 }
232239
@@ -314,6 +321,10 @@ const Tui = struct {
314321 return out.items;
315322 }
316323
324+ fn plural(a: std.mem.Allocator, n: usize, one: []const u8, many: []const u8) []const u8 {
325+ return std.fmt.allocPrint(a, "{d} {s}", .{ n, if (n == 1) one else many }) catch many;
326+ }
327+
317328 fn spinnerChar(frame: usize) []const u8 {
318329 var idx = frame % 256;
319330 var i: usize = 0;
@@ -340,26 +351,30 @@ const Tui = struct {
340351 lines.append(self.s, status_line) catch {};
341352 var caret_line: usize = 0;
342353 var caret_col: usize = 0;
343- if (self.search) |sr| {
344- const prompt = std.fmt.allocPrint(self.s, "reverse: {s}", .{sr.query.items}) catch "reverse: ";
354+ if (self.picker) |*p| {
355+ const prefix = std.fmt.allocPrint(self.s, "{s} › ", .{p.title}) catch "";
356+ lines.append(self.s, std.fmt.allocPrint(self.s, "{s}{s}", .{
357+ styles.styledWith(self.s, .{ .fg = styles.roles.prompt, .bold = true }, prefix),
358+ render.sanitize(self.s, p.query.items),
359+ }) catch "> ") catch {};
345360 caret_line = 1;
346- caret_col = "reverse: ".len + sr.query.items.len;
347- lines.append(self.s, prompt) catch {};
348- if (self.searchMatch(&sr)) |m| {
349- const text = render.sanitize(self.s, m);
350- const budget_rows = @max(height -| 2, 1);
351- var used: usize = 0;
352- var it = std.mem.splitScalar(u8, text, '\n');
353- while (it.next()) |raw| {
354- const part = if (raw.len == 0) " " else raw;
355- for (render.wrapLine(self.s, part, width)) |row| {
356- if (used >= budget_rows) break;
357- used += 1;
358- lines.append(self.s, styles.comment(self.s, row)) catch {};
359- }
360- }
361+ caret_col = render.displayWidth(prefix) + render.displayWidth(p.query.items);
362+ if (p.matches.items.len == 0) {
363+ lines.append(self.s, styles.comment(self.s, " no matches")) catch {};
361364 } else {
362- lines.append(self.s, styles.comment(self.s, "no matches")) catch {};
365+ const budget = @max(height -| 2, 1);
366+ const first = if (p.sel >= budget) p.sel + 1 - budget else 0;
367+ const last = @min(p.matches.items.len, first + budget);
368+ for (p.matches.items[first..last], first..) |idx, i| {
369+ const row = std.fmt.allocPrint(self.s, "{s}{s}", .{
370+ if (i == p.sel) "❯ " else " ",
371+ render.sanitize(self.s, p.labels[idx]),
372+ }) catch p.labels[idx];
373+ lines.append(self.s, if (i == p.sel)
374+ styles.styledWith(self.s, .{ .fg = styles.roles.prompt, .bold = true }, row)
375+ else
376+ styles.comment(self.s, row)) catch {};
377+ }
363378 }
364379 } else {
365380 for (ed.rows) |r| lines.append(self.s, r) catch {};
@@ -374,12 +389,6 @@ const Tui = struct {
374389 self.sa = self.sarena.allocator();
375390 }
376391
377- fn searchMatch(self: *Tui, sr: *const Search) ?[]const u8 {
378- for (self.history.entries.items) |entry| {
379- if (sr.query.items.len == 0 or std.ascii.findIgnoreCase(entry, sr.query.items) != null) return entry;
380- }
381- return null;
382- }
383392 fn keepName(self: *Tui, slot: *?[]const u8, value: ?[]const u8) void {
384393 if (slot.*) |old| self.backing.free(old);
385394 slot.* = if (value) |v| self.backing.dupe(u8, v) catch null else null;
@@ -585,64 +594,33 @@ const Tui = struct {
585594 self.dirty = true;
586595 }
587596
588- fn openSearch(self: *Tui) void {
597+ fn openHistorySearch(self: *Tui) void {
589598 self.resetHistory();
590- const draft = self.editor.contents();
591- self.search = .{ .saved = self.backing.dupe(u8, draft) catch return };
592- self.editor.clear();
593- self.dirty = true;
594- }
595-
596- fn closeSearch(self: *Tui, restore: bool, chosen: ?[]const u8) void {
597- var search = self.search orelse return;
598- self.search = null;
599- self.editor.clear();
600- defer self.dirty = true;
601- if (chosen) |text| self.editor.setText(text);
602- if (restore) self.editor.setText(search.saved);
603- self.backing.free(search.saved);
604- search.query.deinit(self.backing);
605- }
606-
607- fn searchKey(self: *Tui, key: input.Key) void {
608- const search = &(self.search orelse return);
609- switch (key) {
610- .text => |t| search.query.appendSlice(self.backing, t) catch {},
611- .backspace => {
612- if (search.query.items.len > 0) {
613- var start = search.query.items.len - 1;
614- while (start > 0 and (search.query.items[start] & 0xc0) == 0x80) start -= 1;
615- search.query.shrinkRetainingCapacity(start);
616- }
617- },
618- .interrupt => return self.closeSearch(true, null),
619- .escape => return self.closeSearch(true, null),
620- .submit => return self.searchSubmit(),
621- else => {},
599+ self.startPicker(.history, "history");
600+ const p = &(self.picker orelse return);
601+ const entries = self.history.entries.items;
602+ const ids = self.picker_m.alloc([]const u8, entries.len) catch return;
603+ const labels = self.picker_m.alloc([]const u8, entries.len) catch return;
604+ for (entries, 0..) |e, i| {
605+ ids[i] = e;
606+ labels[i] = e[0 .. std.mem.indexOfScalar(u8, e, '\n') orelse e.len];
622607 }
608+ p.ids = ids;
609+ p.labels = labels;
610+ p.draft = self.picker_m.dupe(u8, self.editor.contents()) catch "";
611+ self.editor.clear();
612+ self.pickerRefresh();
623613 self.dirty = true;
624614 }
625615
626- fn searchSubmit(self: *Tui) void {
627- var match: ?[]const u8 = null;
628- const query = self.search.?.query.items;
629- for (self.history.entries.items) |entry| {
630- if (query.len == 0 or std.ascii.findIgnoreCase(entry, query) != null) {
631- match = entry;
632- break;
633- }
634- }
635- if (match) |text| self.closeSearch(false, text) else self.dirty = true;
636- }
637-
638616 fn handleKey(self: *Tui, key: input.Key) void {
639617 self.resetScratch();
640- if (self.search != null) {
641- self.searchKey(key);
618+ if (self.picker != null) {
619+ self.pickerKey(key);
642620 return;
643621 }
644622 if (key == .reverse_search) {
645- self.openSearch();
623+ self.openHistorySearch();
646624 return;
647625 }
648626 if (key == .history_prev) {
@@ -670,7 +648,7 @@ const Tui = struct {
670648 self.dirty = true;
671649 } else if (self.command_active) {
672650 self.command_active = false;
673- self.prompt_open = false;
651+ self.closePicker();
674652 self.model_abort.store(true, .seq_cst);
675653 self.dirty = true;
676654 } else if (self.editor.contents().len != 0) {
@@ -717,13 +695,6 @@ const Tui = struct {
717695 }
718696 return;
719697 }
720- if (self.prompt_open) {
721- self.editor.clear();
722- self.prompt_answer = self.a.dupe(u8, text) catch text;
723- self.prompt_ready.store(true, .seq_cst);
724- self.dirty = true;
725- return;
726- }
727698 if (self.command_active) return;
728699 if (std.mem.trim(u8, text, " \t\r\n").len == 0) {
729700 self.retryTurn();
@@ -793,15 +764,16 @@ const Tui = struct {
793764 const m = self.opts.model orelse return self.fail("! no model configured", .{});
794765 self.startModelFetch(m.provider);
795766 },
796- .thinking => {
797- const m = self.opts.model orelse return self.fail("! no model configured", .{});
798- const levels = models_mod.supportedLevels(self.a, self.cfg, m.provider, m.id);
799- self.beginPrompt("Select a thinking level", levels, levels);
800- self.pending_command = .thinking;
801- },
767+ .thinking => self.startThinkingSelect(),
802768 }
803769 }
804770
771+ fn startThinkingSelect(self: *Tui) void {
772+ const m = self.opts.model orelse return self.fail("! no model configured", .{});
773+ const levels = models_mod.supportedLevels(self.a, self.cfg, m.provider, m.id);
774+ self.openPicker(.thinking, "thinking", levels, levels);
775+ }
776+
805777 fn showHelp(self: *Tui) void {
806778 const keys = [_][2][]const u8{
807779 .{ "Enter", "submit; on an empty draft after a failure, retry it" },
@@ -834,11 +806,6 @@ const Tui = struct {
834806 self.pending_calls.clearRetainingCapacity();
835807 self.streamed.clearRetainingCapacity();
836808 self.reply.reset();
837- if (self.search) |*sr| {
838- self.backing.free(sr.saved);
839- sr.query.deinit(self.backing);
840- self.search = null;
841- }
842809 self.keepName(&self.detail, null);
843810 self.keepName(&self.writing_tool, null);
844811 self.steering_text = "";
@@ -863,8 +830,7 @@ const Tui = struct {
863830 self.fail("! no authenticated providers", .{});
864831 return;
865832 }
866- self.beginPrompt("Select a provider", names.items, ids.items);
867- self.pending_command = .provider;
833+ self.openPicker(.provider, "provider", ids.items, names.items);
868834 }
869835
870836 fn startModelFetch(self: *Tui, provider_id: []const u8) void {
@@ -885,7 +851,6 @@ const Tui = struct {
885851 return;
886852 };
887853 self.command_active = true;
888- self.prompt_open = false;
889854 self.note(styles.comment(self.s, "querying models..."));
890855 self.dirty = true;
891856 }
@@ -912,43 +877,98 @@ const Tui = struct {
912877 ids.append(self.a, e.id) catch {};
913878 names.append(self.a, e.name) catch {};
914879 }
915- self.beginPrompt(std.fmt.allocPrint(self.a, "Select a model for {s}", .{self.model_provider}) catch "Select a model", names.items, ids.items);
916- self.pending_command = .model;
917- self.pending_provider = self.model_provider;
880+ self.openPicker(.model, "model", ids.items, names.items);
881+ if (self.picker) |*p| p.provider = self.model_provider;
882+ }
883+
884+ fn openPicker(self: *Tui, kind: @FieldType(Picker, "kind"), title: []const u8, ids: []const []const u8, labels: []const []const u8) void {
885+ self.startPicker(kind, title);
886+ if (self.picker) |*p| {
887+ p.ids = ids;
888+ p.labels = labels;
889+ }
890+ self.pickerRefresh();
891+ self.dirty = true;
918892 }
919893
920- fn beginPrompt(self: *Tui, message: []const u8, options: []const []const u8, ids: []const []const u8) void {
921- self.prompt_open = true;
922- self.prompt_options = options;
923- self.prompt_ids = ids;
924- self.prompt_answer = "";
925- self.prompt_ready.store(false, .seq_cst);
894+ fn startPicker(self: *Tui, kind: @FieldType(Picker, "kind"), title: []const u8) void {
895+ _ = self.picker_arena.reset(.retain_capacity);
896+ self.picker_m = self.picker_arena.allocator();
897+ self.picker = .{ .kind = kind, .title = title };
926898 self.command_active = true;
927- self.scrollback.separator = true;
928- self.push(message);
929- for (options, 0..) |o, i| {
930- self.push(std.fmt.allocPrint(self.s, " {d}. {s}", .{ i + 1, o }) catch o);
899+ }
900+
901+ fn closePicker(self: *Tui) void {
902+ self.picker = null;
903+ }
904+
905+ fn pickerRefresh(self: *Tui) void {
906+ const p = &(self.picker orelse return);
907+ p.matches.clearRetainingCapacity();
908+ const query = p.query.items;
909+ const n = @min(p.ids.len, p.labels.len);
910+ for (p.ids[0..n], p.labels[0..n], 0..) |id, label, i| {
911+ if (query.len != 0 and std.ascii.findIgnoreCase(label, query) == null and
912+ std.ascii.findIgnoreCase(id, query) == null) continue;
913+ p.matches.append(self.picker_m, i) catch {};
931914 }
932- self.scrollback.separator = true;
915+ p.sel = if (p.matches.items.len == 0) 0 else @min(p.sel, p.matches.items.len - 1);
916+ }
917+
918+ fn pickerKey(self: *Tui, key: input.Key) void {
919+ const p = &(self.picker orelse return);
920+ switch (key) {
921+ .text => |t| {
922+ p.query.appendSlice(self.picker_m, t) catch {};
923+ p.sel = 0;
924+ self.pickerRefresh();
925+ },
926+ .backspace => {
927+ if (p.query.items.len > 0) {
928+ var start = p.query.items.len - 1;
929+ while (start > 0 and (p.query.items[start] & 0xc0) == 0x80) start -= 1;
930+ p.query.shrinkRetainingCapacity(start);
931+ p.sel = 0;
932+ self.pickerRefresh();
933+ }
934+ },
935+ .up, .history_prev => if (p.sel > 0) {
936+ p.sel -= 1;
937+ },
938+ .down, .history_next => if (p.sel + 1 < p.matches.items.len) {
939+ p.sel += 1;
940+ },
941+ .submit => self.pickerAccept(),
942+ .escape, .interrupt => {
943+ const draft = p.draft;
944+ const restore = p.kind == .history;
945+ self.closePicker();
946+ self.command_active = false;
947+ if (restore) self.editor.setText(draft);
948+ },
949+ else => return,
950+ }
951+ self.dirty = true;
933952 }
934953
935- fn answerPrompt(self: *Tui) void {
936- const answer = std.mem.trim(u8, self.prompt_answer, " \t\r\n");
937- const command = self.pending_command;
938- self.prompt_open = false;
939- self.prompt_answer = "";
954+ fn pickerAccept(self: *Tui) void {
955+ const p = self.picker orelse return;
956+ if (p.matches.items.len == 0) return;
957+ const id = p.ids[p.matches.items[p.sel]];
958+ const kind = p.kind;
959+ const provider_id = p.provider;
960+ self.closePicker();
940961 self.command_active = false;
941- const id = matchOption(answer, self.prompt_options, self.prompt_ids) orelse return;
942- switch (command) {
962+ switch (kind) {
943963 .provider => self.startModelFetch(id),
944964 .model => {
945- const provider_id = self.pending_provider orelse return;
946965 var err: ?[]const u8 = null;
947966 const m = models_mod.resolveNamed(self.a, self.cfg, provider_id, id, &err) orelse return;
948967 const ptr = self.a.create(models_mod.Model) catch return;
949968 ptr.* = m;
950969 self.select(ptr);
951970 config.save(self.a, self.cfg, .{ .provider = provider_id, .model = id }) catch {};
971+ self.startThinkingSelect();
952972 },
953973 .thinking => {
954974 const m = self.opts.model orelse return;
@@ -958,7 +978,7 @@ const Tui = struct {
958978 self.select(updated);
959979 config.save(self.a, self.cfg, .{ .thinking_effort = id }) catch {};
960980 },
961- .none => {},
981+ .history => self.editor.setText(id),
962982 }
963983 }
964984
@@ -1016,20 +1036,6 @@ const Tui = struct {
10161036 }
10171037 };
10181038
1019-fn matchOption(answer: []const u8, options: []const []const u8, ids: []const []const u8) ?[]const u8 {
1020- const n = std.fmt.parseInt(usize, answer, 10) catch {
1021- for (options, 0..) |o, i| {
1022- if (std.mem.eql(u8, o, answer)) return ids[i];
1023- }
1024- for (ids) |id| {
1025- if (std.mem.eql(u8, id, answer)) return id;
1026- }
1027- return null;
1028- };
1029- if (n >= 1 and n <= ids.len) return ids[n - 1];
1030- return null;
1031-}
1032-
10331039 fn completePathStep(word: []const u8) ?[]const u8 {
10341040 return complete.completePath(word);
10351041 }
@@ -1202,8 +1208,6 @@ pub fn run(opts: agent.Options, cfg: *const config.Config, tool_names: []const c
12021208 }
12031209 }
12041210
1205- if (self.prompt_open and self.prompt_ready.load(.seq_cst)) self.answerPrompt();
1206-
12071211 if (self.turn_done.load(.seq_cst) and self.active) {
12081212 self.active = false;
12091213 self.paused = false;