trusty_code_tui/model.rs
1//! Engine-supplied UI data: [`StatuslineSegment`], [`PickerItem`]/[`PickerRequest`],
2//! and [`CommandDescriptor`].
3//!
4//! Why: DOC-50 §3.2 (Slice 1.5) requires the statusline, pickers, and
5//! slash-command help to be driven entirely by data the engine supplies, not
6//! by constants baked into the shared crate. Slice 1 shipped provisional
7//! stubs for these three types directly in `crate::event`, flagged as
8//! zero-consumer placeholders; this module is their real, spec-shaped home.
9//! Splitting them out of `event.rs` also keeps that module's focus narrow
10//! (the `ReplEvent` wire vocabulary) versus this module's focus (the
11//! semantic data an engine hands the TUI to render).
12//!
13//! What: three families of type, one per generalized surface:
14//! - [`StatuslineSegment`] — an enum, per DOC-50 §3.2's explicit correction
15//! of Slice 1's flat `{label, value}` struct.
16//! - [`PickerItem`] / [`PickerRequest`] — a named, engine-supplied picker
17//! (replacing tagent's hardcoded `PickerKind::{Model,Provider}`,
18//! `crates/trusty-agents/src/repl/tui/types.rs:28-35`).
19//! - [`CommandDescriptor`] / [`CommandRouting`] — a slash-command registry
20//! entry that records whether the shared crate or the engine handles it
21//! (replacing tagent's hardcoded `SLASH_COMMANDS` array,
22//! `crates/trusty-agents/src/repl/tui/helpers.rs:156-181`).
23//!
24//! None of these types encode product-specific formulas or lists (e.g.
25//! tagent's OpenRouter haiku cost formula, `crates/trusty-agents/src/repl/tui/status.rs:145-155`,
26//! or its `/model`/`/provider` literals) — that logic stays in each engine
27//! adapter (`AgentEngine`, `CodeEngine`); this crate only defines the shapes
28//! the engine populates.
29//!
30//! # Spec References
31//! - [`SPEC-TTUI-03~draft`](../../../docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-03~draft) — §3.2, the generalization layer this module implements.
32//! - [`SPEC-TTUI-05~draft`](../../../docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-05~draft) — Slice 1.5 deliverable and acceptance criteria.
33
34use serde::{Deserialize, Serialize};
35
36/// One labeled segment of the status line, supplied by the engine.
37///
38/// Why: DOC-50 §3.2 specifies the statusline as "enum-driven, engine
39/// populated" — each variant is a semantic kind of thing an engine can
40/// report (a session, the active model, the project, the active
41/// workstream, an approximate cost), not an arbitrary string pair. This
42/// replaces Slice 1's provisional flat `StatuslineSegment { label, value }`
43/// (zero consumers today, so the redefinition is free — see that struct's
44/// removal from `crate::event`).
45/// What: `ReplEvent::StatuslineUpdate(Vec<StatuslineSegment>)` carries these
46/// in render order; the Slice 4 status-line widget matches on variant to
47/// decide layout/styling per kind, falling back to [`Self::Custom`] for
48/// anything not worth a first-class variant (e.g. tagent's TM/claude-mpm
49/// session counts, `status.rs`'s `tm_chunk`/`local_model_chunk`).
50/// [`Self::Cost`] carries a pre-formatted string rather than raw
51/// token/pricing data — per DOC-50 Q9, cost display is a Phase 2 concern
52/// pending a daemon API, and the shared crate must never contain a pricing
53/// formula (tagent's OpenRouter haiku formula stays in `AgentEngine`, not
54/// here).
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
57pub enum StatuslineSegment {
58 /// The active session's identifier (e.g. a short session id).
59 SessionId(String),
60 /// The active LLM provider + model (e.g. `provider: "anthropic"`,
61 /// `name: "claude-sonnet-5"`). Kept as two fields (not one formatted
62 /// string) so the widget can style them independently, mirroring
63 /// tagent's `LLM: {provider} ({model})` chunk without hardcoding the
64 /// `provider (model)` formatting choice into the shared crate.
65 Model { provider: String, name: String },
66 /// The active project name or path.
67 Project(String),
68 /// The active workstream (DOC-48 §2.1): `id` + `name`, matching
69 /// `WorkstreamSummary` and the Slice 6 status-line example
70 /// ("WS: Token rotation (a1b2c3d4)").
71 Workstream { id: String, name: String },
72 /// A pre-formatted, engine-computed cost string (e.g. `"$0.0034"`).
73 /// Deferred to Phase 2 per DOC-50 Q9 (no daemon API yet to source real
74 /// cost from) — this variant exists so the wire shape doesn't need a
75 /// breaking change once that API lands; no engine populates it yet.
76 ///
77 /// **Multi-cost case:** `Cost` carries a single string, not a label +
78 /// value pair, so an engine that wants to show more than one cost
79 /// figure at once (tagent shows both the current session's cost and
80 /// the day's running total, `status.rs`'s `session_cost`/`daily_cost`)
81 /// bakes the distinction into the string itself and emits multiple
82 /// `Cost` segments — e.g. `Cost("$0.0034 session")` and
83 /// `Cost("$0.0145 today")` — matching tagent's existing `"{cost}
84 /// session"` / `"{cost} today"` suffix convention
85 /// (`crates/trusty-agents/src/repl/tui/status.rs`'s `format_cost_value`
86 /// call sites) rather than inventing a new labeled-cost shape here.
87 Cost(String),
88 /// Escape hatch for an engine-specific segment that doesn't warrant a
89 /// first-class variant (e.g. tagent's `TM: N sessions` / `MPM: N
90 /// sessions` counts). `label` is the short prefix, `value` is the
91 /// rendered text; `emphasis` is the same wire-safe style hint
92 /// [`Chrome`](Self::Chrome) carries — added so a labeled segment like
93 /// `MPM: 2 sessions` can render bold/accented the way tagent's
94 /// `status.rs` distinguishes it from the plainer `TM: N sessions`
95 /// segment, without the shared crate encoding either label's meaning.
96 Custom {
97 label: String,
98 value: String,
99 emphasis: StatuslineEmphasis,
100 },
101 /// Free-form styled text with no `label: value` structure — the
102 /// generalization of tagent's un-labeled statusline chrome (the bold-
103 /// cyan `"[trusty-agents] "` bracket prefix, the green `"✓ "` / `"All
104 /// systems go."` success framing, `status.rs`'s `style_status_chunk`).
105 /// Why a separate variant from `Custom` rather than an empty `label`:
106 /// `Custom`'s renderer always emits the `"{label}: "` separator, which
107 /// is wrong for chrome that isn't a label/value pair at all — an empty
108 /// label would still render `": ✓ All systems go."`.
109 /// What: `text` renders verbatim, styled per `emphasis`. No tagent-
110 /// specific color/text is hardcoded here — the engine supplies both.
111 Chrome {
112 text: String,
113 emphasis: StatuslineEmphasis,
114 },
115}
116
117/// A generic, wire-safe (JSON, via `serde`) style hint an engine can attach
118/// to a free-form statusline segment ([`StatuslineSegment::Custom`]/
119/// [`StatuslineSegment::Chrome`]).
120///
121/// Why: tagent's statusline (`crates/trusty-agents/src/repl/tui/status.rs`,
122/// NOT migrated to this crate — see `crate::widgets::status_line`'s module
123/// doc comment) has real chrome this crate's Slice 1.5 segment set couldn't
124/// express at all: a bold-cyan bracket prefix, green success framing, and a
125/// bold/dim distinction between two otherwise-identical `Custom`-shaped
126/// segments (`TM: N sessions` vs `MPM: N sessions`). Without a style hook,
127/// Slice 10's tagent cutover would have no way to reproduce that chrome
128/// through this crate's widgets — a silent UX regression Slice 10 wouldn't
129/// discover until it tried. This enum is deliberately independent of any
130/// terminal-rendering library (`crate::model` has zero terminal-library
131/// dependency, by design, per the crate root doc comment — even though
132/// `trusty-code-tui` as a whole now depends on `ratatui`) so it stays JSON-safe
133/// for an HTTP-transported engine (`CodeEngine`, Slice 3) and so this module
134/// never needs a `ratatui::style::Color`/`Modifier` in its public API.
135/// What: a small, closed set of semantic emphases — not raw RGB/attribute
136/// bits — so an engine names *what kind* of emphasis it wants (`Success`,
137/// `Accent`, …) and [`crate::widgets::status_line`] owns the actual
138/// `ratatui::style::Style` each maps to. `Normal` (the default) renders
139/// exactly like today's unstyled segments, so this is purely additive.
140#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
141#[serde(rename_all = "snake_case")]
142pub enum StatuslineEmphasis {
143 /// No special styling — today's default rendering.
144 #[default]
145 Normal,
146 /// De-emphasized (tagent's `Modifier::DIM`).
147 Dim,
148 /// Emphasized (tagent's `Modifier::BOLD`).
149 Bold,
150 /// A positive/OK signal (tagent's green "✓ … All systems go.").
151 Success,
152 /// A caution signal.
153 Warning,
154 /// A problem signal.
155 Error,
156 /// The product's accent color (tagent's bold-cyan `"[trusty-agents] "`
157 /// bracket prefix).
158 Accent,
159}
160
161/// One selectable row in an engine-supplied picker (model, provider,
162/// workstream, …).
163///
164/// Why: DOC-50 §3.3 requires picker data sources to be engine-provided
165/// rather than hardcoded lists (tagent's model/provider pickers today are
166/// hardcoded in `pickers.rs`, with items carried as bare `Vec<String>` in
167/// `PickerState.items`, `crates/trusty-agents/src/repl/tui/types.rs:44-50`).
168/// What: `id` is what gets sent back to the engine on selection (via
169/// [`PickerRequest::dispatch_command`]); `label` is the display text (may
170/// differ from `id`, e.g. a friendly name over a model slug);
171/// `description` is optional secondary text (e.g. a model's context-window
172/// size) the Slice 4 widget may render alongside the label.
173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
174pub struct PickerItem {
175 pub id: String,
176 pub label: String,
177 pub description: Option<String>,
178}
179
180/// A complete engine-supplied picker: what to show, and what selecting an
181/// item does.
182///
183/// Why: tagent hardcodes two picker kinds (`PickerKind::Model`,
184/// `PickerKind::Provider`, `crates/trusty-agents/src/repl/tui/types.rs:28-35`)
185/// with Enter-dispatch bound to the literal strings `"/model"` /
186/// `"/provider"` — the shared crate must not know either of those concepts
187/// exist. `PickerRequest` generalizes this: the engine names the picker
188/// (`title`), supplies the rows (`items`), and supplies the command prefix
189/// to dispatch on selection (`dispatch_command`) — the shared event loop
190/// (Slice 4/7) confirms a selection by emitting
191/// `ReplEvent::Submit(format!("{} {}", dispatch_command, selected.id))`,
192/// reproducing tagent's exact `/model <selected>` / `/provider <selected>`
193/// behavior without the shared crate hardcoding either command name.
194/// What: `title` renders in the picker's border/header; `items` is the
195/// (already-fetched) list of choices — no lazy paging in this slice.
196/// `TuiEngine::picker` (see `crate::engine`) is how the shared event loop
197/// asks an engine for one of these by name.
198#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
199pub struct PickerRequest {
200 pub title: String,
201 pub items: Vec<PickerItem>,
202 pub dispatch_command: String,
203}
204
205/// One entry in an engine-supplied slash-command registry.
206///
207/// Why: DOC-50 §5 Slice 7 / Q4 splits slash commands into client-side
208/// built-ins (`/help`, `/clear`, `/quit`, handled entirely inside
209/// `trusty-code-tui`, never reaching `TuiEngine::handle_input`) and
210/// engine-routed domain commands (`/model`, `/workstream`, forwarded to
211/// `TuiEngine::handle_input`). `/help` needs to enumerate both, so
212/// [`CommandRouting`] records which side owns dispatch — generalizing
213/// tagent's flat `SLASH_COMMANDS: &[(&str, &str)]` array
214/// (`crates/trusty-agents/src/repl/tui/helpers.rs:156-181`), which mixes
215/// generic commands (`/help`, `/clear`) with tagent-specific ones
216/// (`/agent`, `/local`, `/tm`) and carries no routing information at all.
217/// What: `name` is the command without its leading `/` (e.g.
218/// `"workstream"`); `summary` is the one-line help text `/help` renders;
219/// `args_hint` is optional completion metadata shown after the name (e.g.
220/// `Some("<id>")` renders as `/workstream activate <id>` in autocomplete),
221/// mirroring tagent's `update_slash_completions` prefix-match behavior
222/// without hardcoding argument shapes into the shared crate.
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
224pub struct CommandDescriptor {
225 pub name: String,
226 pub summary: String,
227 pub routing: CommandRouting,
228 pub args_hint: Option<String>,
229}
230
231/// Which side of the seam dispatches a [`CommandDescriptor`] (DOC-50 §6 Q4,
232/// "mixed routing").
233#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
234#[serde(rename_all = "snake_case")]
235pub enum CommandRouting {
236 /// Handled entirely inside `trusty-code-tui` (`/help`, `/clear`, `/quit`);
237 /// never reaches `TuiEngine::handle_input`.
238 BuiltIn,
239 /// Forwarded to `TuiEngine::handle_input` for the engine to execute
240 /// (`/model`, `/workstream`, and other domain commands).
241 Engine,
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 /// Every `StatuslineSegment` variant must round-trip through JSON — the
249 /// wire shape an HTTP-transported engine (`CodeEngine`, Slice 3) will
250 /// carry these over.
251 #[test]
252 fn statusline_segment_variants_round_trip_through_json() {
253 let segments = vec![
254 StatuslineSegment::SessionId("a1b2c3d4".to_string()),
255 StatuslineSegment::Model {
256 provider: "anthropic".to_string(),
257 name: "claude-sonnet-5".to_string(),
258 },
259 StatuslineSegment::Project("trusty-tools".to_string()),
260 StatuslineSegment::Workstream {
261 id: "a1b2c3d4".to_string(),
262 name: "Token rotation".to_string(),
263 },
264 StatuslineSegment::Cost("$0.0034".to_string()),
265 StatuslineSegment::Custom {
266 label: "TM".to_string(),
267 value: "2 sessions".to_string(),
268 emphasis: StatuslineEmphasis::Normal,
269 },
270 StatuslineSegment::Custom {
271 label: "MPM".to_string(),
272 value: "2 sessions".to_string(),
273 emphasis: StatuslineEmphasis::Bold,
274 },
275 StatuslineSegment::Chrome {
276 text: "✓ All systems go.".to_string(),
277 emphasis: StatuslineEmphasis::Success,
278 },
279 ];
280 for seg in segments {
281 let json = serde_json::to_string(&seg).expect("serialize");
282 let back: StatuslineSegment = serde_json::from_str(&json).expect("deserialize");
283 assert_eq!(seg, back);
284 }
285 }
286
287 /// `StatuslineSegment` is an enum per DOC-50 §3.2 — confirm distinct
288 /// variants (even ones sharing a `String` payload shape) are not equal,
289 /// which would be the failure mode of accidentally collapsing back to a
290 /// flat struct.
291 #[test]
292 fn statusline_segment_variants_are_distinct() {
293 let session = StatuslineSegment::SessionId("x".to_string());
294 let project = StatuslineSegment::Project("x".to_string());
295 assert_ne!(session, project);
296 }
297
298 /// `Custom` segments that differ ONLY in `emphasis` must be distinct —
299 /// the whole point of adding the field is to distinguish a bold `MPM:`
300 /// segment from an otherwise-identical plain one.
301 #[test]
302 fn custom_segments_with_different_emphasis_are_distinct() {
303 let plain = StatuslineSegment::Custom {
304 label: "TM".to_string(),
305 value: "2 sessions".to_string(),
306 emphasis: StatuslineEmphasis::Normal,
307 };
308 let bold = StatuslineSegment::Custom {
309 label: "TM".to_string(),
310 value: "2 sessions".to_string(),
311 emphasis: StatuslineEmphasis::Bold,
312 };
313 assert_ne!(plain, bold);
314 }
315
316 /// `StatuslineEmphasis::default()` must be `Normal` so an engine that
317 /// doesn't care about styling gets today's plain rendering for free.
318 #[test]
319 fn statusline_emphasis_defaults_to_normal() {
320 assert_eq!(StatuslineEmphasis::default(), StatuslineEmphasis::Normal);
321 }
322
323 /// `PickerItem`/`PickerRequest` must round-trip through JSON for the
324 /// same HTTP-transport reason as statusline segments.
325 #[test]
326 fn picker_request_round_trips_through_json() {
327 let req = PickerRequest {
328 title: "Select a model".to_string(),
329 items: vec![
330 PickerItem {
331 id: "opus-4".to_string(),
332 label: "Claude Opus 4".to_string(),
333 description: Some("Most capable".to_string()),
334 },
335 PickerItem {
336 id: "haiku-4-5".to_string(),
337 label: "Claude Haiku 4.5".to_string(),
338 description: None,
339 },
340 ],
341 dispatch_command: "/model".to_string(),
342 };
343 let json = serde_json::to_string(&req).expect("serialize");
344 let back: PickerRequest = serde_json::from_str(&json).expect("deserialize");
345 assert_eq!(req, back);
346 }
347
348 /// The whole point of `dispatch_command`: the shared event loop
349 /// synthesizes `"<dispatch_command> <selected.id>"` on confirmation,
350 /// reproducing tagent's `/model <selected>` behavior generically. This
351 /// test locks the exact composition so a future event-loop
352 /// implementation (Slice 4/7) has a documented contract to build
353 /// against.
354 #[test]
355 fn picker_request_dispatch_command_composes_with_selected_item_id() {
356 let req = PickerRequest {
357 title: "Select a provider".to_string(),
358 items: vec![PickerItem {
359 id: "openrouter".to_string(),
360 label: "OpenRouter".to_string(),
361 description: None,
362 }],
363 dispatch_command: "/provider".to_string(),
364 };
365 let selected = &req.items[0];
366 let synthesized = format!("{} {}", req.dispatch_command, selected.id);
367 assert_eq!(synthesized, "/provider openrouter");
368 }
369
370 /// `CommandDescriptor`/`CommandRouting` must round-trip through JSON,
371 /// covering both routing kinds so DOC-50 Q4's mixed-routing model is
372 /// exercised, not just the default.
373 #[test]
374 fn command_descriptor_round_trips_through_json_for_both_routing_kinds() {
375 let builtin = CommandDescriptor {
376 name: "clear".to_string(),
377 summary: "clear chat".to_string(),
378 routing: CommandRouting::BuiltIn,
379 args_hint: None,
380 };
381 let json = serde_json::to_string(&builtin).expect("serialize");
382 assert_eq!(builtin, serde_json::from_str(&json).expect("deserialize"));
383
384 let engine_routed = CommandDescriptor {
385 name: "workstream".to_string(),
386 summary: "List or activate a workstream".to_string(),
387 routing: CommandRouting::Engine,
388 args_hint: Some("activate <id>".to_string()),
389 };
390 let json = serde_json::to_string(&engine_routed).expect("serialize");
391 assert_eq!(
392 engine_routed,
393 serde_json::from_str(&json).expect("deserialize")
394 );
395 }
396}