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
//! The engine-adapter seam: [`TuiEngine`].
//!
//! Why: `trusty-code-tui` renders one interaction model for two different
//! products — trusty-code (daemon-backed coding agent) and trusty-agents
//! (tagent's REPL). Rather than fork the TUI per product, the TUI stays
//! engine-agnostic and each product supplies a thin [`TuiEngine`]
//! implementation that translates user input into its own backend calls and
//! backend responses into [`crate::ReplEvent`] values pushed onto the shared
//! channel. See DOC-50 §2.2 for the full architecture rationale.
//!
//! What: this module defines only the trait — no event loop, no rendering.
//! The event loop that drives `handle_input`/`setup`/`shutdown` lands in
//! Slice 2 (#3414). Slice 1.5 (#3413) adds two data-supply accessors,
//! `commands` and `picker`, so the shared crate can render slash-command
//! help and inline pickers from engine-supplied data instead of hardcoded
//! per-product lists (DOC-50 §3.2) — both default to "nothing supplied" so
//! no existing/future `TuiEngine` implementor breaks by not overriding
//! them. Statusline segments do NOT get a parallel accessor here: Slice 1's
//! `ReplEvent::StatuslineUpdate` (pushed from `setup`/
//! `subscribe_workstream_events`) already is the engine-supply mechanism
//! for those; adding a second, pull-based path would just give the shared
//! event loop two sources of truth to reconcile.
//!
//! # Spec References
//! - [`SPEC-TTUI-02~draft`](docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-02~draft) — architecture, the engine-adapter seam.
//! - [`SPEC-TTUI-03~draft`](docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-03~draft) — Slice 1 trait shape; §3.2, Slice 1.5 generalization layer.

use crate::event::ReplEvent;
use crate::model::{CancelReply, CommandDescriptor, PermissionAnswer, PickerRequest};
use anyhow::Result;
use tokio::sync::mpsc::UnboundedSender;

/// Translates one product's backend (tcode daemon, tagent's in-process LLM
/// dispatch) into the shared TUI's vocabulary.
///
/// Why: this is the entire "seam" DOC-50 §2.2 describes — the TUI knows
/// nothing about tcode or tagent, only about `TuiEngine`. Keeping the trait
/// to a handful of methods keeps engine adapters "thin" per the thin-client
/// axiom (DOC-50 §2.1, C-1/C-2): all real work (running the agent,
/// cancelling a session, subscribing to workstream events) happens on the
/// far side of `handle_input`/`cancel_session`/`subscribe_workstream_events`,
/// never inside the TUI itself.
///
/// What: implementors push zero or more [`ReplEvent`] values onto `tx` for
/// every method; the shared event loop (Slice 2+) owns turning those events
/// into screen updates. `cancel_session` and `subscribe_workstream_events`
/// default to no-ops so an engine that doesn't support in-flight cancellation
/// or workstream awareness (e.g. an MVP or test double) needs no boilerplate.
///
/// Thread-safety: `Send + Sync` because the shared event loop dispatches
/// `handle_input` onto a spawned `tokio::task` per submitted line (mirroring
/// `crates/trusty-agents/src/repl/tui/events.rs`), so the engine must be
/// shareable across that task boundary (typically via `Arc<dyn TuiEngine>`).
///
/// # Spec References
/// - [`SPEC-TTUI-02~draft`](docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-02~draft)
#[async_trait::async_trait]
pub trait TuiEngine: Send + Sync {
    /// Process one submitted line — either free-form chat input or a slash
    /// command the shared router didn't handle client-side.
    ///
    /// Why: this is the single request/response entry point between the TUI
    /// and the product backend; keeping it to one method (vs. exposing many
    /// backend-specific calls) is what lets the TUI stay backend-agnostic.
    /// What: `line` is the raw text the user submitted (echoing to the
    /// scrollback already happened before this is called, mirroring tagent's
    /// existing `process_event` behavior). Implementations push output
    /// (assistant text, tool invocations, status messages, errors) onto `tx`
    /// as [`ReplEvent`] values. Returns `Ok(true)` to keep the REPL running,
    /// `Ok(false)` to quit; an `Err` is surfaced to the user as an error
    /// event by the caller, not propagated as a panic.
    ///
    /// **Contract on `tx`'s lifetime (DOC-50 §5 Slice 5's dispatch layer,
    /// `crate::run::dispatch_pending`):** `tx` is a private, per-call channel
    /// — do not retain a clone of it (e.g. inside a detached background
    /// task) past this call's return. The shared dispatch layer awaits that
    /// channel's forwarder to fully drain immediately after this future
    /// resolves, as part of detecting whether a terminal signal
    /// (`AssistantOutput { done: true, .. }` or the quit path) was ever
    /// produced; a clone kept alive beyond the call would stall that
    /// detection. This does not restrict implementations from spawning their
    /// OWN background work — only from smuggling `tx` itself into anything
    /// outliving the call. Note also that **not every `Ok(true)` needs to
    /// send a terminal `AssistantOutput`** (e.g. a `/workstream list` that
    /// only pushes `StatusMessage`/`WorkstreamUpdated`) — the dispatch layer
    /// detects that gap and synthesizes `ReplEvent::TurnFinished` itself, so
    /// implementations are NOT required to send a synthetic empty
    /// `AssistantOutput { done: true, .. }` just to clear `busy`.
    /// Test: exercised via a mock `TuiEngine` in Slice 2+ integration tests
    /// (`crates/trusty-code-tui/tests/`); no runtime behavior to unit-test yet in
    /// Slice 1.
    async fn handle_input(&self, line: String, tx: UnboundedSender<ReplEvent>) -> Result<bool>;

    /// Load initial state (session id, model, workstream, roster, …) before
    /// the render loop starts.
    ///
    /// Why: the REPL needs to show a populated status line and scrollback on
    /// first frame rather than blank state that fills in asynchronously with
    /// a visible flash.
    /// What: implementations push whatever startup [`ReplEvent`] values are
    /// relevant (e.g. `WorkstreamUpdated`, `StatusMessage`) onto `tx`. Called
    /// exactly once, before the first render.
    /// Test: see `handle_input`.
    async fn setup(&self, tx: UnboundedSender<ReplEvent>) -> Result<()>;

    /// Cancel the in-flight request started by the most recent
    /// `handle_input` call, if any.
    ///
    /// Why: DOC-50 §5 Slice 5 requires Ctrl-C to relay a real cancellation to
    /// the backend (thin-client axiom C-2 — the backend performs the
    /// cancellation, not just the UI stopping its own render). Defaulting to
    /// a no-op lets engines without a cancellable backend operation (or test
    /// doubles) skip the override.
    /// What: implementations that support cancellation should call through
    /// to their backend's cancel/abort API. This is the one-state form: it
    /// says only whether the request was delivered, never whether the run
    /// actually stopped. The shared event loop reaches it through
    /// [`Self::cancel_session_reply`]'s default, so an engine whose backend
    /// can report "not stopped yet" overrides that method instead of this one.
    /// Test: see `handle_input`.
    async fn cancel_session(&self) -> Result<()> {
        Ok(())
    }

    /// Cancel the in-flight request and report what the backend actually
    /// CONFIRMED (#8207).
    ///
    /// Why: [`Self::cancel_session`]'s `Result<()>` has no way to say
    /// "accepted, but the run has not stopped yet" — the state a cooperative
    /// cancel really can be in. Flattening that into `Ok(())` is what let the
    /// TUI print "cancelled" and reopen input while the daemon task was still
    /// winding down, so the next prompt came back `-32003 already has a task
    /// running` (#8207). Flattening it into `Err` is no better: a cancel that
    /// did not land must not read as one that did, but neither should one that
    /// was accepted read as a transport failure.
    /// What: deliberately infallible — every failure is a
    /// [`CancelReply::Failed`], so no arm can be forgotten by a caller doing a
    /// total match. Each payload string is rendered verbatim to the user, so an
    /// implementor strips protocol detail (an error code, a JSON-RPC envelope)
    /// before returning it. The default lifts [`Self::cancel_session`]:
    /// `Ok(())` becomes [`CancelReply::Stopped`] and an `Err` becomes
    /// [`CancelReply::Failed`], so an engine with a one-state cancel — and
    /// every test double — needs no override. The shared event loop calls this
    /// exactly once per cancel gesture.
    /// Test: `cancel_session_reply_defaults_to_stopped`,
    /// `cancel_session_reply_default_reports_an_error_as_failed` (this
    /// module); `crate::run::tests::dispatch_pending_cancel_holds_input_until_the_reply_lands`
    /// covers the dispatch wiring.
    async fn cancel_session_reply(&self) -> CancelReply {
        match self.cancel_session().await {
            Ok(()) => CancelReply::Stopped,
            Err(e) => CancelReply::Failed {
                error: format!("{e:#}"),
            },
        }
    }

    /// Answer one suspended permission request (#3422).
    ///
    /// Why: a [`ReplEvent::PermissionRequested`] leaves a tool call stopped
    /// on the backend; only the backend can release it, so the key press has
    /// to become a real backend call — the same thin-client reasoning as
    /// [`Self::cancel_session`] (ADR-0063, DOC-50 §2.1 C-2). The TUI applies
    /// no local policy: it does not pre-approve, does not remember grants,
    /// and does not decide what a session-wide grant covers.
    /// What: `request_id` comes off the event that opened the prompt;
    /// `answer` names which of the three the user chose. Implementations
    /// translate `answer` into their own backend's decision type — this
    /// crate deliberately carries no wire words. The shared event loop calls
    /// this exactly once per answered prompt. Default no-op, for engines
    /// (and test doubles) with no permission surface.
    /// Test: `respond_permission_defaults_to_ok` (this module);
    /// `crate::run::tests::dispatch_pending_permission_answer_reaches_respond_permission`
    /// covers the dispatch wiring.
    async fn respond_permission(&self, request_id: String, answer: PermissionAnswer) -> Result<()> {
        let _ = (request_id, answer);
        Ok(())
    }

    /// Open (or re-open) a subscription to backend-pushed events that aren't
    /// direct responses to `handle_input` — chiefly workstream activation
    /// changes (DOC-48 §5.3).
    ///
    /// Why: workstream awareness (DOC-50 §5 Slice 6) is push-driven — the
    /// daemon can activate a different workstream out-of-band (another
    /// client, another session) and the TUI must reflect that without the
    /// user typing anything. Modeling this as a trait method (rather than a
    /// bespoke SSE client living in the TUI) keeps the thin-client axiom
    /// intact: only the engine adapter knows the transport (SSE over HTTP
    /// for tcode; nothing, for tagent today).
    /// What: implementations that support push events spawn their own
    /// listener and forward `WorkstreamUpdated` / `WorkstreamActivationChanged`
    /// (and, on transport loss, `ConnectionLost`) onto `tx`. The default
    /// no-op is correct for engines with no push transport; the shared event
    /// loop calls this once, after `setup`.
    /// Test: see `handle_input`.
    async fn subscribe_workstream_events(&self, tx: UnboundedSender<ReplEvent>) -> Result<()> {
        let _ = tx;
        Ok(())
    }

    /// Domain slash-command entries this engine contributes (e.g. `/model`,
    /// `/workstream` for `AgentEngine`/`CodeEngine` respectively).
    ///
    /// Why: DOC-50 §6 Q4 (mixed routing) splits slash commands into
    /// client-side built-ins (`/help`, `/clear`, `/quit` — owned by
    /// `trusty-code-tui` itself, never listed here) and engine-routed domain
    /// commands. This is how `/help` (Slice 7) learns about the latter
    /// without the shared crate hardcoding tagent's or tcode's command set
    /// (replacing tagent's `SLASH_COMMANDS` array,
    /// `crates/trusty-agents/src/repl/tui/helpers.rs:156-181`).
    /// What: returns every [`CommandDescriptor`] this engine handles via
    /// `handle_input`. Entries should use [`crate::model::CommandRouting::Engine`]
    /// (the shared crate does not currently validate this, but a
    /// `BuiltIn`-routed entry here would never be dispatched — built-ins are
    /// intercepted before `handle_input` is called). Default: empty, for
    /// engines/test doubles with no domain commands.
    ///
    /// **Sync constraint:** this method is deliberately synchronous (no
    /// network I/O on the calling path) so `/help` can render instantly.
    /// A network-backed implementor (Slice 3's HTTP `CodeEngine`) therefore
    /// CANNOT fetch its command list on demand here — it must pre-fetch the
    /// daemon's command table during `async setup()` and cache it (e.g. in
    /// an `Arc<Mutex<Vec<CommandDescriptor>>>` or similar), then have this
    /// method serve from that cache. Returning a stale/empty list here is
    /// preferable to blocking `/help` on a request.
    /// Test: `commands_defaults_to_empty` (this module).
    fn commands(&self) -> Vec<CommandDescriptor> {
        Vec::new()
    }

    /// Look up an engine-supplied picker by name (e.g. `"model"`,
    /// `"provider"`, `"workstream"`) — the data source behind DOC-50 §3.2's
    /// picker generalization.
    ///
    /// Why: generalizes tagent's hardcoded `PickerKind::{Model,Provider}`
    /// (`crates/trusty-agents/src/repl/tui/types.rs:28-35`), where the
    /// items and the Enter-dispatch command are both baked into the REPL
    /// itself. Here, the engine names the picker, supplies its items, and
    /// supplies the dispatch command — see [`PickerRequest`] for the full
    /// contract the shared event loop (Slice 4/7) builds on.
    /// What: `name` identifies which picker was requested (e.g. via a
    /// `/model` invocation reaching `handle_input`, which — instead of
    /// answering inline — can have the shared router call this first).
    /// Returns `None` when the engine has no picker under that name.
    /// Default: always `None`, for engines with no pickers yet.
    ///
    /// **Naming convention (not type-enforced):** a command's name doubles
    /// as its picker name — a bare `/model` (no args) reaching
    /// `handle_input` is expected to trigger `picker("model")`, `/provider`
    /// triggers `picker("provider")`, and so on. On confirmation, the
    /// shared event loop (Slice 4/5) composes
    /// `"{PickerRequest::dispatch_command} {selected.id}"` (e.g.
    /// `"/model opus-4"`) and resubmits it as `ReplEvent::Submit`, which is
    /// what actually performs the selection — `picker()` itself only
    /// supplies the list, it never applies a selection. Nothing in the type
    /// system links a `CommandDescriptor.name` to a `picker()` name or a
    /// `PickerRequest.dispatch_command`; an engine implementing both must
    /// keep them in lockstep by convention (mirrors tagent's existing
    /// `PickerKind::Model` → `"/model <selected>"` pairing,
    /// `crates/trusty-agents/src/repl/tui/types.rs:28-35`).
    ///
    /// **Sync constraint:** same as [`Self::commands`] — this method is
    /// synchronous, so a network-backed implementor (Slice 3's
    /// `CodeEngine`) cannot fetch items on demand here. Pre-fetch during
    /// `async setup()` (or on first use of a given picker name, cached
    /// after) and serve from that cache; a `handle_input` invocation that
    /// needs fresh data should refresh the cache there, not inside
    /// `picker()`.
    /// Test: `picker_defaults_to_none` (this module).
    fn picker(&self, name: &str) -> Option<PickerRequest> {
        let _ = name;
        None
    }

    /// Graceful shutdown — close any open backend connections.
    ///
    /// Why: mirrors the original `ReplHandler` contract in
    /// `crates/trusty-agents/src/repl/tui/run.rs`; kept optional since most
    /// engines have nothing to flush.
    /// What: called once, after the render loop exits (`app.quit == true` or
    /// Ctrl-D). Errors are logged, not fatal.
    /// Test: see `handle_input`.
    async fn shutdown(&self) -> Result<()> {
        Ok(())
    }
}

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

    /// A minimal `TuiEngine` implementing only the two required methods —
    /// stands in for a test double or an MVP engine that hasn't grown
    /// domain commands/pickers yet.
    struct BareEngine;

    #[async_trait::async_trait]
    impl TuiEngine for BareEngine {
        async fn handle_input(
            &self,
            _line: String,
            _tx: UnboundedSender<ReplEvent>,
        ) -> Result<bool> {
            Ok(true)
        }

        async fn setup(&self, _tx: UnboundedSender<ReplEvent>) -> Result<()> {
            Ok(())
        }
    }

    /// An engine that overrides `commands`/`picker` — stands in for
    /// `AgentEngine`/`CodeEngine` once Slice 10/3 land, proving the trait
    /// defaults are genuinely overridable (not accidentally `sealed` or
    /// `final` via the macro expansion).
    struct RichEngine;

    #[async_trait::async_trait]
    impl TuiEngine for RichEngine {
        async fn handle_input(
            &self,
            _line: String,
            _tx: UnboundedSender<ReplEvent>,
        ) -> Result<bool> {
            Ok(true)
        }

        async fn setup(&self, _tx: UnboundedSender<ReplEvent>) -> Result<()> {
            Ok(())
        }

        fn commands(&self) -> Vec<CommandDescriptor> {
            vec![CommandDescriptor {
                name: "workstream".to_string(),
                summary: "List or activate a workstream".to_string(),
                routing: CommandRouting::Engine,
                args_hint: Some("activate <id>".to_string()),
            }]
        }

        fn picker(&self, name: &str) -> Option<PickerRequest> {
            (name == "model").then(|| PickerRequest {
                title: "Select a model".to_string(),
                items: Vec::new(),
                dispatch_command: "/model".to_string(),
            })
        }
    }

    /// An engine that implements only the required methods (no `commands`
    /// override) must still compile and yield an empty command list — the
    /// whole point of giving `commands()` a default body (existing/future
    /// implementors don't break, and "supply nothing" is silent rather than
    /// a panic or an error). Cited by the `commands()` doc comment's
    /// `Test:` pointer.
    #[test]
    fn commands_defaults_to_empty() {
        let engine = BareEngine;
        assert!(engine.commands().is_empty());
    }

    /// An engine that implements only the required methods (no `picker`
    /// override) must still compile and yield `None` for any picker name —
    /// same "nothing supplied, no panic" contract as `commands()`. Cited by
    /// the `picker()` doc comment's `Test:` pointer.
    #[test]
    fn picker_defaults_to_none() {
        let engine = BareEngine;
        assert!(engine.picker("model").is_none());
        assert!(engine.picker("anything").is_none());
    }

    /// An engine with no permission surface must still compile and report
    /// success — the "nothing to do, no panic" contract every defaulted
    /// method here shares. Cited by `respond_permission`'s `Test:` pointer.
    #[tokio::test]
    async fn respond_permission_defaults_to_ok() {
        let engine = BareEngine;
        assert!(
            engine
                .respond_permission("req-1".to_string(), PermissionAnswer::Deny)
                .await
                .is_ok()
        );
    }

    /// An engine whose `cancel_session` fails — the transport-gone shape
    /// [`TuiEngine::cancel_session_reply`]'s default has to translate (#8207).
    struct FailingCancelEngine;

    #[async_trait::async_trait]
    impl TuiEngine for FailingCancelEngine {
        async fn handle_input(
            &self,
            _line: String,
            _tx: UnboundedSender<ReplEvent>,
        ) -> Result<bool> {
            Ok(true)
        }

        async fn setup(&self, _tx: UnboundedSender<ReplEvent>) -> Result<()> {
            Ok(())
        }

        async fn cancel_session(&self) -> Result<()> {
            Err(anyhow::anyhow!("socket closed"))
        }
    }

    /// #8207: an engine with a one-state cancel needs no override, and its
    /// `Ok(())` must lift to `Stopped` — the arm that reopens input. Compile-
    /// level as much as behavioural: `BareEngine` overrides nothing, so this
    /// also proves the new method did not become a required one.
    #[tokio::test]
    async fn cancel_session_reply_defaults_to_stopped() {
        assert_eq!(
            BareEngine.cancel_session_reply().await,
            CancelReply::Stopped
        );
    }

    /// #8207: a failed `cancel_session` must lift to `Failed`, never `Stopped`
    /// — the default is the fail-open hazard's first opportunity, so it is
    /// asserted at the seam and not only in the reducer.
    #[tokio::test]
    async fn cancel_session_reply_default_reports_an_error_as_failed() {
        assert_eq!(
            FailingCancelEngine.cancel_session_reply().await,
            CancelReply::Failed {
                error: "socket closed".to_string()
            }
        );
    }

    /// An engine that DOES override `commands`/`picker` must have its
    /// overrides take effect (not silently fall back to the trait default).
    #[test]
    fn commands_and_picker_overrides_take_effect() {
        let engine = RichEngine;

        let commands = engine.commands();
        assert_eq!(commands.len(), 1);
        assert_eq!(commands[0].name, "workstream");
        assert_eq!(commands[0].routing, CommandRouting::Engine);

        let picker = engine.picker("model").expect("model picker present");
        assert_eq!(picker.title, "Select a model");
        assert_eq!(picker.dispatch_command, "/model");
        assert!(engine.picker("provider").is_none());
    }
}