trusty-code-tui 0.2.0

Engine-agnostic terminal-UI seam (TuiEngine trait + ReplEvent) shared by trusty-code and trusty-agents interactive REPLs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//! Engine-supplied UI data: [`StatuslineSegment`], [`PickerItem`]/[`PickerRequest`],
//! and [`CommandDescriptor`].
//!
//! Why: DOC-50 §3.2 (Slice 1.5) requires the statusline, pickers, and
//! slash-command help to be driven entirely by data the engine supplies, not
//! by constants baked into the shared crate. Slice 1 shipped provisional
//! stubs for these three types directly in `crate::event`, flagged as
//! zero-consumer placeholders; this module is their real, spec-shaped home.
//! Splitting them out of `event.rs` also keeps that module's focus narrow
//! (the `ReplEvent` wire vocabulary) versus this module's focus (the
//! semantic data an engine hands the TUI to render).
//!
//! What: three families of type, one per generalized surface:
//! - [`StatuslineSegment`] — an enum, per DOC-50 §3.2's explicit correction
//!   of Slice 1's flat `{label, value}` struct.
//! - [`PickerItem`] / [`PickerRequest`] — a named, engine-supplied picker
//!   (replacing tagent's hardcoded `PickerKind::{Model,Provider}`,
//!   `crates/trusty-agents/src/repl/tui/types.rs:28-35`).
//! - [`CommandDescriptor`] / [`CommandRouting`] — a slash-command registry
//!   entry that records whether the shared crate or the engine handles it
//!   (replacing tagent's hardcoded `SLASH_COMMANDS` array,
//!   `crates/trusty-agents/src/repl/tui/helpers.rs:156-181`).
//!
//! None of these types encode product-specific formulas or lists (e.g.
//! tagent's OpenRouter haiku cost formula, `crates/trusty-agents/src/repl/tui/status.rs:145-155`,
//! or its `/model`/`/provider` literals) — that logic stays in each engine
//! adapter (`AgentEngine`, `CodeEngine`); this crate only defines the shapes
//! the engine populates.
//!
//! # Spec References
//! - [`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.
//! - [`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.

use serde::{Deserialize, Serialize};

/// One labeled segment of the status line, supplied by the engine.
///
/// Why: DOC-50 §3.2 specifies the statusline as "enum-driven, engine
/// populated" — each variant is a semantic kind of thing an engine can
/// report (a session, the active model, the project, the active
/// workstream, an approximate cost), not an arbitrary string pair. This
/// replaces Slice 1's provisional flat `StatuslineSegment { label, value }`
/// (zero consumers today, so the redefinition is free — see that struct's
/// removal from `crate::event`).
/// What: `ReplEvent::StatuslineUpdate(Vec<StatuslineSegment>)` carries these
/// in render order; the Slice 4 status-line widget matches on variant to
/// decide layout/styling per kind, falling back to [`Self::Custom`] for
/// anything not worth a first-class variant (e.g. tagent's TM/claude-mpm
/// session counts, `status.rs`'s `tm_chunk`/`local_model_chunk`).
/// [`Self::Cost`] carries a pre-formatted string rather than raw
/// token/pricing data — per DOC-50 Q9, cost display is a Phase 2 concern
/// pending a daemon API, and the shared crate must never contain a pricing
/// formula (tagent's OpenRouter haiku formula stays in `AgentEngine`, not
/// here).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
pub enum StatuslineSegment {
    /// The active session's identifier (e.g. a short session id).
    SessionId(String),
    /// The active LLM provider + model (e.g. `provider: "anthropic"`,
    /// `name: "claude-sonnet-5"`). Kept as two fields (not one formatted
    /// string) so the widget can style them independently, mirroring
    /// tagent's `LLM: {provider} ({model})` chunk without hardcoding the
    /// `provider (model)` formatting choice into the shared crate.
    Model { provider: String, name: String },
    /// The active project name or path.
    Project(String),
    /// The active workstream (DOC-48 §2.1): `id` + `name`, matching
    /// `WorkstreamSummary` and the Slice 6 status-line example
    /// ("WS: Token rotation (a1b2c3d4)").
    Workstream { id: String, name: String },
    /// A pre-formatted, engine-computed cost string (e.g. `"$0.0034"`).
    /// Deferred to Phase 2 per DOC-50 Q9 (no daemon API yet to source real
    /// cost from) — this variant exists so the wire shape doesn't need a
    /// breaking change once that API lands; no engine populates it yet.
    ///
    /// **Multi-cost case:** `Cost` carries a single string, not a label +
    /// value pair, so an engine that wants to show more than one cost
    /// figure at once (tagent shows both the current session's cost and
    /// the day's running total, `status.rs`'s `session_cost`/`daily_cost`)
    /// bakes the distinction into the string itself and emits multiple
    /// `Cost` segments — e.g. `Cost("$0.0034 session")` and
    /// `Cost("$0.0145 today")` — matching tagent's existing `"{cost}
    /// session"` / `"{cost} today"` suffix convention
    /// (`crates/trusty-agents/src/repl/tui/status.rs`'s `format_cost_value`
    /// call sites) rather than inventing a new labeled-cost shape here.
    Cost(String),
    /// Escape hatch for an engine-specific segment that doesn't warrant a
    /// first-class variant (e.g. tagent's `TM: N sessions` / `MPM: N
    /// sessions` counts). `label` is the short prefix, `value` is the
    /// rendered text; `emphasis` is the same wire-safe style hint
    /// [`Chrome`](Self::Chrome) carries — added so a labeled segment like
    /// `MPM: 2 sessions` can render bold/accented the way tagent's
    /// `status.rs` distinguishes it from the plainer `TM: N sessions`
    /// segment, without the shared crate encoding either label's meaning.
    Custom {
        label: String,
        value: String,
        emphasis: StatuslineEmphasis,
    },
    /// Free-form styled text with no `label: value` structure — the
    /// generalization of tagent's un-labeled statusline chrome (the bold-
    /// cyan `"[trusty-agents] "` bracket prefix, the green `"✓ "` / `"All
    /// systems go."` success framing, `status.rs`'s `style_status_chunk`).
    /// Why a separate variant from `Custom` rather than an empty `label`:
    /// `Custom`'s renderer always emits the `"{label}: "` separator, which
    /// is wrong for chrome that isn't a label/value pair at all — an empty
    /// label would still render `": ✓ All systems go."`.
    /// What: `text` renders verbatim, styled per `emphasis`. No tagent-
    /// specific color/text is hardcoded here — the engine supplies both.
    Chrome {
        text: String,
        emphasis: StatuslineEmphasis,
    },
}

/// A generic, wire-safe (JSON, via `serde`) style hint an engine can attach
/// to a free-form statusline segment ([`StatuslineSegment::Custom`]/
/// [`StatuslineSegment::Chrome`]).
///
/// Why: tagent's statusline (`crates/trusty-agents/src/repl/tui/status.rs`,
/// NOT migrated to this crate — see `crate::widgets::status_line`'s module
/// doc comment) has real chrome this crate's Slice 1.5 segment set couldn't
/// express at all: a bold-cyan bracket prefix, green success framing, and a
/// bold/dim distinction between two otherwise-identical `Custom`-shaped
/// segments (`TM: N sessions` vs `MPM: N sessions`). Without a style hook,
/// Slice 10's tagent cutover would have no way to reproduce that chrome
/// through this crate's widgets — a silent UX regression Slice 10 wouldn't
/// discover until it tried. This enum is deliberately independent of any
/// terminal-rendering library (`crate::model` has zero terminal-library
/// dependency, by design, per the crate root doc comment — even though
/// `trusty-code-tui` as a whole now depends on `ratatui`) so it stays JSON-safe
/// for an HTTP-transported engine (`CodeEngine`, Slice 3) and so this module
/// never needs a `ratatui::style::Color`/`Modifier` in its public API.
/// What: a small, closed set of semantic emphases — not raw RGB/attribute
/// bits — so an engine names *what kind* of emphasis it wants (`Success`,
/// `Accent`, …) and [`crate::widgets::status_line`] owns the actual
/// `ratatui::style::Style` each maps to. `Normal` (the default) renders
/// exactly like today's unstyled segments, so this is purely additive.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum StatuslineEmphasis {
    /// No special styling — today's default rendering.
    #[default]
    Normal,
    /// De-emphasized (tagent's `Modifier::DIM`).
    Dim,
    /// Emphasized (tagent's `Modifier::BOLD`).
    Bold,
    /// A positive/OK signal (tagent's green "✓ … All systems go.").
    Success,
    /// A caution signal.
    Warning,
    /// A problem signal.
    Error,
    /// The product's accent color (tagent's bold-cyan `"[trusty-agents] "`
    /// bracket prefix).
    Accent,
}

/// One selectable row in an engine-supplied picker (model, provider,
/// workstream, …).
///
/// Why: DOC-50 §3.3 requires picker data sources to be engine-provided
/// rather than hardcoded lists (tagent's model/provider pickers today are
/// hardcoded in `pickers.rs`, with items carried as bare `Vec<String>` in
/// `PickerState.items`, `crates/trusty-agents/src/repl/tui/types.rs:44-50`).
/// What: `id` is what gets sent back to the engine on selection (via
/// [`PickerRequest::dispatch_command`]); `label` is the display text (may
/// differ from `id`, e.g. a friendly name over a model slug);
/// `description` is optional secondary text (e.g. a model's context-window
/// size) the Slice 4 widget may render alongside the label.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PickerItem {
    pub id: String,
    pub label: String,
    pub description: Option<String>,
}

/// A complete engine-supplied picker: what to show, and what selecting an
/// item does.
///
/// Why: tagent hardcodes two picker kinds (`PickerKind::Model`,
/// `PickerKind::Provider`, `crates/trusty-agents/src/repl/tui/types.rs:28-35`)
/// with Enter-dispatch bound to the literal strings `"/model"` /
/// `"/provider"` — the shared crate must not know either of those concepts
/// exist. `PickerRequest` generalizes this: the engine names the picker
/// (`title`), supplies the rows (`items`), and supplies the command prefix
/// to dispatch on selection (`dispatch_command`) — the shared event loop
/// (Slice 4/7) confirms a selection by emitting
/// `ReplEvent::Submit(format!("{} {}", dispatch_command, selected.id))`,
/// reproducing tagent's exact `/model <selected>` / `/provider <selected>`
/// behavior without the shared crate hardcoding either command name.
/// What: `title` renders in the picker's border/header; `items` is the
/// (already-fetched) list of choices — no lazy paging in this slice.
/// `TuiEngine::picker` (see `crate::engine`) is how the shared event loop
/// asks an engine for one of these by name.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PickerRequest {
    pub title: String,
    pub items: Vec<PickerItem>,
    pub dispatch_command: String,
}

/// The permission request currently blocking the turn (#3422).
///
/// Why: [`crate::event::ReplEvent::PermissionRequested`]'s payload has to
/// outlive the event so the prompt widget can redraw it every frame and the
/// answer can be addressed back to the right `request_id`. Held in
/// [`crate::app::ReplApp::pending_permission`].
/// What: every field is the producer's own text, stored verbatim — `subject`
/// arrives already redacted and bounded, and this crate never re-derives,
/// re-redacts, or re-interprets any of them.
/// Test: `crate::app::reduce::tests::permission_requested_opens_a_prompt_and_records_it`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingPermission {
    /// The correlation key the answer is sent back on.
    pub request_id: String,
    /// The agent whose call is suspended.
    pub agent: String,
    /// That agent's opaque per-spawn id; empty when unattributed.
    pub agent_id: String,
    /// The tool that would run.
    pub tool: String,
    /// What the tool would act on, already redacted by the producer.
    pub subject: String,
    /// The policy pattern that matched.
    pub rule: String,
}

/// The user's answer to a [`PendingPermission`] (#3422).
///
/// Why: the TUI must offer all three answers the backend understands, and
/// must compute none of them — per the thin-client axiom (ADR-0063) this
/// enum only NAMES which button was pressed; the engine adapter translates
/// it into its own backend's decision type and the backend applies the
/// policy. Nothing here knows what a grant covers or how long it lasts.
/// What: `AllowForSession.pattern` is the optional grant width. This crate
/// never invents one — the key binding sends `None`, which asks the backend
/// for whatever its own default width is for the subject it asked about.
/// Test: `crate::app::reduce::tests::permission_key_y_answers_allow_once`
/// and its siblings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PermissionAnswer {
    /// Permit this one call.
    AllowOnce,
    /// Permit this call and stop asking for the rest of the session.
    AllowForSession { pattern: Option<String> },
    /// Refuse this call.
    Deny,
}

/// An answer staged for the outer driver to relay to
/// [`crate::engine::TuiEngine::respond_permission`] (#3422).
///
/// Why: the reducer holds only `&mut ReplApp` and cannot call an `async`
/// engine method, so it stages the answer here — the same pattern
/// [`crate::app::ReplApp::pending_submit`] and `pending_cancel` use.
/// What: drained by [`crate::run::TuiModel::take_pending_permission_response`]
/// after every `apply` call. It carries the whole [`PendingPermission`],
/// not just its `request_id` (#3422): the prompt is cleared optimistically
/// when the key is pressed, so the request would be unrecoverable if the
/// `respond_permission` RPC failed — the dispatch layer hands this value
/// back through [`crate::event::ReplEvent::PermissionAnswerFailed`] to
/// reopen the prompt.
/// Test: `crate::run::tests::dispatch_pending_permission_answer_reaches_respond_permission`,
/// `crate::run::tests::dispatch_pending_permission_answer_failure_reopens_the_prompt`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PermissionResponse {
    /// The request this answers, kept whole so a failed relay can reopen it.
    pub pending: PendingPermission,
    /// What the user chose.
    pub answer: PermissionAnswer,
}

impl PermissionResponse {
    /// The correlation key [`crate::engine::TuiEngine::respond_permission`]
    /// sends this answer back on.
    pub fn request_id(&self) -> &str {
        &self.pending.request_id
    }
}

/// What a backend actually confirmed about a dispatched cancel (#8207).
///
/// Why: a cooperative cancel has three outcomes, not two, and the TUI renders
/// each differently. "The run stopped" ends the turn and reopens input; "the
/// cancel was accepted but the run has not stopped yet" must keep the
/// cancelling state on screen, because reopening input there is exactly how
/// the next prompt earned a `-32003 already has a task running` refusal from
/// the daemon (#8207's transcript); "the cancel could not be delivered at all"
/// is a failure and must never read as either of the first two.
/// What: produced by [`crate::engine::TuiEngine::cancel_session_reply`] and
/// carried to the reducer as
/// [`crate::event::ReplEvent::CancelSettled`]. Every payload string here is
/// rendered VERBATIM into the scrollback, so an implementor owes a plain
/// sentence — never a protocol code or a JSON-RPC envelope.
/// Test: `crate::app::reduce::tests::apply_cancel_settled_stopped_reopens_input`
/// and its siblings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CancelReply {
    /// The backend confirmed the run has terminated. The turn is over.
    Stopped,
    /// The backend accepted the cancel; the run had not stopped yet. `detail`
    /// is the backend's own account of what it is still waiting on.
    StillCancelling { detail: String },
    /// The cancel never landed — a transport failure, or a refusal that is not
    /// "still cancelling". `error` is a plain sentence, already stripped of
    /// protocol detail by the engine adapter.
    Failed { error: String },
}

/// One entry in an engine-supplied slash-command registry.
///
/// Why: DOC-50 §5 Slice 7 / Q4 splits slash commands into client-side
/// built-ins (`/help`, `/clear`, `/quit`, handled entirely inside
/// `trusty-code-tui`, never reaching `TuiEngine::handle_input`) and
/// engine-routed domain commands (`/model`, `/workstream`, forwarded to
/// `TuiEngine::handle_input`). `/help` needs to enumerate both, so
/// [`CommandRouting`] records which side owns dispatch — generalizing
/// tagent's flat `SLASH_COMMANDS: &[(&str, &str)]` array
/// (`crates/trusty-agents/src/repl/tui/helpers.rs:156-181`), which mixes
/// generic commands (`/help`, `/clear`) with tagent-specific ones
/// (`/agent`, `/local`, `/tm`) and carries no routing information at all.
/// What: `name` is the command without its leading `/` (e.g.
/// `"workstream"`); `summary` is the one-line help text `/help` renders;
/// `args_hint` is optional completion metadata shown after the name (e.g.
/// `Some("<id>")` renders as `/workstream activate <id>` in autocomplete),
/// mirroring tagent's `update_slash_completions` prefix-match behavior
/// without hardcoding argument shapes into the shared crate.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandDescriptor {
    pub name: String,
    pub summary: String,
    pub routing: CommandRouting,
    pub args_hint: Option<String>,
}

/// Which side of the seam dispatches a [`CommandDescriptor`] (DOC-50 §6 Q4,
/// "mixed routing").
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CommandRouting {
    /// Handled entirely inside `trusty-code-tui` (`/help`, `/clear`, `/quit`);
    /// never reaches `TuiEngine::handle_input`.
    BuiltIn,
    /// Forwarded to `TuiEngine::handle_input` for the engine to execute
    /// (`/model`, `/workstream`, and other domain commands).
    Engine,
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Every `StatuslineSegment` variant must round-trip through JSON — the
    /// wire shape an HTTP-transported engine (`CodeEngine`, Slice 3) will
    /// carry these over.
    #[test]
    fn statusline_segment_variants_round_trip_through_json() {
        let segments = vec![
            StatuslineSegment::SessionId("a1b2c3d4".to_string()),
            StatuslineSegment::Model {
                provider: "anthropic".to_string(),
                name: "claude-sonnet-5".to_string(),
            },
            StatuslineSegment::Project("trusty-tools".to_string()),
            StatuslineSegment::Workstream {
                id: "a1b2c3d4".to_string(),
                name: "Token rotation".to_string(),
            },
            StatuslineSegment::Cost("$0.0034".to_string()),
            StatuslineSegment::Custom {
                label: "TM".to_string(),
                value: "2 sessions".to_string(),
                emphasis: StatuslineEmphasis::Normal,
            },
            StatuslineSegment::Custom {
                label: "MPM".to_string(),
                value: "2 sessions".to_string(),
                emphasis: StatuslineEmphasis::Bold,
            },
            StatuslineSegment::Chrome {
                text: "✓ All systems go.".to_string(),
                emphasis: StatuslineEmphasis::Success,
            },
        ];
        for seg in segments {
            let json = serde_json::to_string(&seg).expect("serialize");
            let back: StatuslineSegment = serde_json::from_str(&json).expect("deserialize");
            assert_eq!(seg, back);
        }
    }

    /// `StatuslineSegment` is an enum per DOC-50 §3.2 — confirm distinct
    /// variants (even ones sharing a `String` payload shape) are not equal,
    /// which would be the failure mode of accidentally collapsing back to a
    /// flat struct.
    #[test]
    fn statusline_segment_variants_are_distinct() {
        let session = StatuslineSegment::SessionId("x".to_string());
        let project = StatuslineSegment::Project("x".to_string());
        assert_ne!(session, project);
    }

    /// `Custom` segments that differ ONLY in `emphasis` must be distinct —
    /// the whole point of adding the field is to distinguish a bold `MPM:`
    /// segment from an otherwise-identical plain one.
    #[test]
    fn custom_segments_with_different_emphasis_are_distinct() {
        let plain = StatuslineSegment::Custom {
            label: "TM".to_string(),
            value: "2 sessions".to_string(),
            emphasis: StatuslineEmphasis::Normal,
        };
        let bold = StatuslineSegment::Custom {
            label: "TM".to_string(),
            value: "2 sessions".to_string(),
            emphasis: StatuslineEmphasis::Bold,
        };
        assert_ne!(plain, bold);
    }

    /// `StatuslineEmphasis::default()` must be `Normal` so an engine that
    /// doesn't care about styling gets today's plain rendering for free.
    #[test]
    fn statusline_emphasis_defaults_to_normal() {
        assert_eq!(StatuslineEmphasis::default(), StatuslineEmphasis::Normal);
    }

    /// `PickerItem`/`PickerRequest` must round-trip through JSON for the
    /// same HTTP-transport reason as statusline segments.
    #[test]
    fn picker_request_round_trips_through_json() {
        let req = PickerRequest {
            title: "Select a model".to_string(),
            items: vec![
                PickerItem {
                    id: "opus-4".to_string(),
                    label: "Claude Opus 4".to_string(),
                    description: Some("Most capable".to_string()),
                },
                PickerItem {
                    id: "haiku-4-5".to_string(),
                    label: "Claude Haiku 4.5".to_string(),
                    description: None,
                },
            ],
            dispatch_command: "/model".to_string(),
        };
        let json = serde_json::to_string(&req).expect("serialize");
        let back: PickerRequest = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(req, back);
    }

    /// The whole point of `dispatch_command`: the shared event loop
    /// synthesizes `"<dispatch_command> <selected.id>"` on confirmation,
    /// reproducing tagent's `/model <selected>` behavior generically. This
    /// test locks the exact composition so a future event-loop
    /// implementation (Slice 4/7) has a documented contract to build
    /// against.
    #[test]
    fn picker_request_dispatch_command_composes_with_selected_item_id() {
        let req = PickerRequest {
            title: "Select a provider".to_string(),
            items: vec![PickerItem {
                id: "openrouter".to_string(),
                label: "OpenRouter".to_string(),
                description: None,
            }],
            dispatch_command: "/provider".to_string(),
        };
        let selected = &req.items[0];
        let synthesized = format!("{} {}", req.dispatch_command, selected.id);
        assert_eq!(synthesized, "/provider openrouter");
    }

    /// `CommandDescriptor`/`CommandRouting` must round-trip through JSON,
    /// covering both routing kinds so DOC-50 Q4's mixed-routing model is
    /// exercised, not just the default.
    #[test]
    fn command_descriptor_round_trips_through_json_for_both_routing_kinds() {
        let builtin = CommandDescriptor {
            name: "clear".to_string(),
            summary: "clear chat".to_string(),
            routing: CommandRouting::BuiltIn,
            args_hint: None,
        };
        let json = serde_json::to_string(&builtin).expect("serialize");
        assert_eq!(builtin, serde_json::from_str(&json).expect("deserialize"));

        let engine_routed = CommandDescriptor {
            name: "workstream".to_string(),
            summary: "List or activate a workstream".to_string(),
            routing: CommandRouting::Engine,
            args_hint: Some("activate <id>".to_string()),
        };
        let json = serde_json::to_string(&engine_routed).expect("serialize");
        assert_eq!(
            engine_routed,
            serde_json::from_str(&json).expect("deserialize")
        );
    }
}