Skip to main content

trusty_code_tui/
commands.rs

1//! The slash-command parser/dispatcher — DOC-50 §5 Slice 7, §6 Q4 ("mixed
2//! routing").
3//!
4//! Why: DOC-50 §6 Q4 resolves slash-command handling as a split: a small,
5//! fixed set of client-side built-ins (`/help`, `/clear`, `/quit`/`/exit`)
6//! that never reach a product's [`crate::engine::TuiEngine`], and every
7//! other slash command (domain commands like `/model`, `/workstream`, plus
8//! any command this crate has never heard of) forwarded verbatim to
9//! `TuiEngine::handle_input` — "the client does NOT interpret domain
10//! commands" (thin-client axiom, DOC-39 §2.1 C-1/C-2). This module is where
11//! that split is decided. It replaces tagent's monolithic
12//! `try_handle_slash`/`SLASH_COMMANDS` (`crates/trusty-agents/src/repl/*.rs`,
13//! `crates/trusty-agents/src/repl/tui/helpers.rs:156-181`), which mixed
14//! generic commands with tagent-specific ones and carried no routing
15//! metadata at all.
16//!
17//! What: three pieces.
18//! - [`route`] — pure, engine-free: given a submitted line, decide
19//!   [`Route::BuiltIn`] or [`Route::Forward`]. Only needs the fixed
20//!   [`built_in_commands`] table, so [`crate::app::ReplApp::submit_line`]
21//!   (which has no engine handle — see `crate::app::reduce`'s module doc
22//!   comment) can call it directly and apply a built-in's effect inline
23//!   ([`Route::BuiltIn(BuiltIn::Clear)`](BuiltIn::Clear) reuses
24//!   [`crate::app::ReplApp::clear_scrollback`], the same effect
25//!   `ReplEvent::ClearScrollback` produces).
26//! - [`resolve_forward`]/[`compose_selection`] — the picker half (DOC-50
27//!   §3.2/Q6): a bare `/name` (no args) `Route::Forward` line whose name
28//!   matches `TuiEngine::picker(name)` opens an inline picker instead of
29//!   reaching `handle_input`; confirming a picker item resubmits
30//!   `"{dispatch_command} {selected.id}"`. These DO need engine access, so
31//!   they're free functions a product's async event-loop wiring calls
32//!   (rather than living inside the sync [`crate::app::reduce::apply`](crate::app::apply)
33//!   reducer, which cannot reach a `TuiEngine` — see that module's doc
34//!   comment).
35//! - [`dispatch_forward`] — composes the two into the actual integration
36//!   point: given a `Route::Forward` line staged in
37//!   [`crate::app::ReplApp::pending_submit`], either opens a picker or calls
38//!   `engine.handle_input`.
39//!
40//! # Spec References
41//! - [`SPEC-TTUI-05~draft`](docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-05~draft) — Slice 7 deliverable (§5, Slice 7) and Q4 (mixed routing), Q6 (inline pickers).
42
43use tokio::sync::mpsc::UnboundedSender;
44
45use crate::app::ReplApp;
46use crate::engine::TuiEngine;
47use crate::event::ReplEvent;
48use crate::model::{CommandDescriptor, CommandRouting, PickerItem, PickerRequest};
49
50/// The fixed, client-side built-in command table (DOC-50 §6 Q4) — never
51/// forwarded to `TuiEngine::handle_input`.
52///
53/// Why: a plain function (not a `const`) so each call returns an owned
54/// `Vec` — cheap, and avoids a `static`/`OnceLock` for four short-lived
55/// rows. `/quit` and `/exit` are both listed (two independent entries, not
56/// one row with an alias note) so `/help`'s output and prefix-based
57/// discovery treat them identically; [`route`] recognizes both names as
58/// [`BuiltIn::Quit`].
59/// What: `name` matches [`route`]'s match arms exactly; `summary` is what
60/// [`render_help`] prints. None of these carry `args_hint` — all four take
61/// no arguments.
62/// Test: `tests::built_in_commands_names_match_route_recognition`.
63pub fn built_in_commands() -> Vec<CommandDescriptor> {
64    vec![
65        CommandDescriptor {
66            name: "help".to_string(),
67            summary: "Show available commands".to_string(),
68            routing: CommandRouting::BuiltIn,
69            args_hint: None,
70        },
71        CommandDescriptor {
72            name: "clear".to_string(),
73            summary: "Clear the scrollback".to_string(),
74            routing: CommandRouting::BuiltIn,
75            args_hint: None,
76        },
77        CommandDescriptor {
78            name: "quit".to_string(),
79            summary: "Exit".to_string(),
80            routing: CommandRouting::BuiltIn,
81            args_hint: None,
82        },
83        CommandDescriptor {
84            name: "exit".to_string(),
85            summary: "Exit (alias for /quit)".to_string(),
86            routing: CommandRouting::BuiltIn,
87            args_hint: None,
88        },
89    ]
90}
91
92/// The effect of a recognized built-in command — applied directly by
93/// [`crate::app::ReplApp::submit_line`], never round-tripped through
94/// `TuiEngine`.
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub enum BuiltIn {
97    /// Render the combined built-in + engine command list.
98    Help,
99    /// Clear the scrollback — same effect as `ReplEvent::ClearScrollback`.
100    Clear,
101    /// Set `ReplApp::quit = true`.
102    Quit,
103}
104
105/// Where a submitted line should route (DOC-50 §6 Q4).
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub enum Route {
108    /// Handled entirely client-side — see [`BuiltIn`].
109    BuiltIn(BuiltIn),
110    /// Not a recognized built-in: forward this exact (trimmed) line to
111    /// `TuiEngine::handle_input`. Covers domain commands (`/model`,
112    /// `/workstream`), plain chat text, AND any slash command this crate
113    /// doesn't recognize — the shared crate never rejects a command outright
114    /// (thin-client axiom: only the engine knows what's valid).
115    Forward(String),
116}
117
118/// Split a trimmed `/`-prefixed line into its command name (no leading `/`)
119/// and trimmed argument tail (`""` when bare). `None` when `line` isn't a
120/// slash command at all (doesn't start with `/`, or is exactly `/`).
121fn command_name(line: &str) -> Option<(&str, &str)> {
122    let trimmed = line.trim();
123    let rest = trimmed.strip_prefix('/')?;
124    if rest.is_empty() {
125        return None;
126    }
127    match rest.split_once(char::is_whitespace) {
128        Some((name, args)) => Some((name, args.trim())),
129        None => Some((rest, "")),
130    }
131}
132
133/// Classify one submitted line per DOC-50 §6 Q4's mixed-routing model.
134///
135/// Why: pure and engine-free (only consults the fixed [`built_in_commands`]
136/// table) so [`crate::app::ReplApp::submit_line`] — which has no
137/// `TuiEngine` handle — can call it directly. See the module doc comment
138/// for why built-in recognition doesn't need `TuiEngine::commands()` at all:
139/// the built-in set is fixed and product-independent.
140/// What: non-slash lines (plain chat) and any `/name` not in
141/// [`built_in_commands`] both resolve to `Route::Forward` — see that
142/// variant's doc comment for why "unrecognized" and "domain command" are
143/// treated identically.
144/// Test: `tests::route_recognizes_each_builtin_name`,
145/// `tests::route_forwards_plain_chat`,
146/// `tests::route_forwards_unrecognized_slash_command`,
147/// `tests::route_forwards_engine_domain_command`.
148pub fn route(line: &str) -> Route {
149    match command_name(line) {
150        Some(("help", _)) => Route::BuiltIn(BuiltIn::Help),
151        Some(("clear", _)) => Route::BuiltIn(BuiltIn::Clear),
152        Some(("quit", _)) | Some(("exit", _)) => Route::BuiltIn(BuiltIn::Quit),
153        _ => Route::Forward(line.trim().to_string()),
154    }
155}
156
157/// Render `/help`'s output: the built-ins plus every engine-supplied
158/// command, one line each.
159///
160/// Why: DOC-50 §5 Slice 7 requires `/help` to enumerate both sides of the
161/// routing split — `engine_commands` is expected to be
162/// [`crate::app::ReplApp::commands`] (the cache a product populates from
163/// `TuiEngine::commands()` during setup; see that field's doc comment).
164/// What: one `"  /{name}{ args_hint} — {summary}"` line per command,
165/// built-ins first. Pure string formatting — no ratatui dependency, so this
166/// stays usable from both the plain-text scrollback path and a future
167/// richer help widget.
168/// Test: `tests::render_help_lists_builtins_and_engine_commands`,
169/// `tests::render_help_includes_args_hint_when_present`.
170pub fn render_help(engine_commands: &[CommandDescriptor]) -> String {
171    let mut lines = vec!["Available commands:".to_string()];
172    for cmd in built_in_commands().iter().chain(engine_commands.iter()) {
173        let hint = cmd
174            .args_hint
175            .as_deref()
176            .map(|h| format!(" {h}"))
177            .unwrap_or_default();
178        lines.push(format!("  /{}{} — {}", cmd.name, hint, cmd.summary));
179    }
180    lines.join("\n")
181}
182
183/// `true` when `line` is a bare `/name` invocation (no arguments) —
184/// convention for picker-eligible commands (DOC-50 §3.2
185/// `TuiEngine::picker`'s doc comment: "a command's name doubles as its
186/// picker name").
187fn bare_command_name(line: &str) -> Option<&str> {
188    match command_name(line) {
189        Some((name, "")) => Some(name),
190        _ => None,
191    }
192}
193
194/// What the caller should do with a `Route::Forward` line.
195#[derive(Debug, Clone, PartialEq, Eq)]
196pub enum Forward {
197    /// Open this inline picker instead of calling `handle_input`.
198    OpenPicker(PickerRequest),
199    /// No matching picker: forward to `TuiEngine::handle_input` as-is.
200    ToEngine(String),
201}
202
203/// Resolve a `Route::Forward` line against `engine`: does it open a picker,
204/// or does it genuinely need `handle_input`?
205///
206/// Why: split out of [`dispatch_forward`] so the picker decision itself
207/// (needs `&dyn TuiEngine`, but no `tx`/`ReplApp` mutation) is unit-testable
208/// against a bare mock engine.
209/// What: only a *bare* command (see [`bare_command_name`]) is picker-
210/// eligible — `/model opus-4` (already has an argument) always forwards,
211/// even if `engine.picker("model")` would return `Some`, matching tagent's
212/// precedent (`crates/trusty-agents/src/repl/bridge.rs`: the picker overlay
213/// only opens for the no-arg form; a supplied argument is assumed to be the
214/// user directly naming their choice).
215/// Test: `tests::resolve_forward_opens_picker_for_bare_matching_command`,
216/// `tests::resolve_forward_ignores_picker_when_args_present`,
217/// `tests::resolve_forward_falls_back_to_engine_when_no_picker_matches`.
218pub fn resolve_forward(line: &str, engine: &dyn TuiEngine) -> Forward {
219    if let Some(name) = bare_command_name(line)
220        && let Some(request) = engine.picker(name)
221    {
222        return Forward::OpenPicker(request);
223    }
224    Forward::ToEngine(line.to_string())
225}
226
227/// Compose the line to resubmit when the user confirms `selected` from
228/// `request` (DOC-50 §3.2 `PickerRequest` contract:
229/// `"{dispatch_command} {selected.id}"`).
230///
231/// Why: a free function (not a `PickerRequest` method — that type lives in
232/// `crate::model`, which must stay free of any TUI-driver-shaped API) so
233/// both this module's [`dispatch_forward`]-adjacent flow and a future
234/// picker *widget*'s Enter-key handling share one composition rule.
235/// Test: `tests::compose_selection_matches_picker_request_contract`.
236pub fn compose_selection(request: &PickerRequest, selected: &PickerItem) -> String {
237    format!("{} {}", request.dispatch_command, selected.id)
238}
239
240/// The `Route::Forward` half of the dispatch pipeline: resolve a picker or
241/// call `engine.handle_input`.
242///
243/// Why: the actual integration point a product's event-loop wiring calls
244/// after draining a `Route::Forward` line from
245/// [`crate::app::ReplApp::pending_submit`] — composes [`resolve_forward`]
246/// (the routing decision) with the two possible effects (open a picker on
247/// `app`, or await the engine call) in one place, so callers don't have to
248/// re-derive the "which one am I supposed to do" branch themselves.
249/// What: on [`Forward::OpenPicker`], stages the picker on `app` (via
250/// [`crate::app::ReplApp::open_picker`]), clears [`crate::app::ReplApp::busy`],
251/// and returns `Ok(true)` — the engine is never touched. Clearing `busy`
252/// here (not in [`crate::app::ReplApp::submit_line`]) matters: `submit_line`
253/// unconditionally sets `busy = true` for every `Route::Forward` line
254/// because it can't know in advance whether this function will end up
255/// opening a picker instead of actually calling `handle_input` — this arm
256/// is the one place that knows the round-trip to the engine never
257/// happened. Leaving `busy` set would strand the input composer's busy
258/// spinner for as long as the picker stays open (nothing else clears it —
259/// `busy` is only ever reset by an `AssistantOutput` event, which never
260/// arrives on this path) and would spuriously gate `apply_up`'s
261/// busy-triggered `pending_cancel` (`crate::app::reduce::apply_up`), firing
262/// an unwanted `engine.cancel_session()` the next time a picker-open Up
263/// arrow is drained. On [`Forward::ToEngine`], forwards verbatim to
264/// `engine.handle_input`, returning its `Result<bool>` unchanged (per
265/// `TuiEngine::handle_input`'s own contract: `Ok(false)` means quit) —
266/// `busy` is left as `submit_line` set it, since the engine call is the
267/// thing `busy` is meant to track.
268/// Test: `tests::dispatch_forward_opens_picker_without_calling_engine`,
269/// `tests::dispatch_forward_calls_engine_when_no_picker_matches`,
270/// `tests::dispatch_forward_clears_busy_set_by_submit_line_when_opening_picker`.
271pub async fn dispatch_forward(
272    app: &mut ReplApp,
273    line: String,
274    engine: &dyn TuiEngine,
275    tx: &UnboundedSender<ReplEvent>,
276) -> anyhow::Result<bool> {
277    match resolve_forward(&line, engine) {
278        Forward::OpenPicker(request) => {
279            app.open_picker(request);
280            app.busy = false;
281            Ok(true)
282        }
283        Forward::ToEngine(line) => engine.handle_input(line, tx.clone()).await,
284    }
285}
286
287#[cfg(test)]
288mod tests;