Skip to main content

trusty_code_tui/
engine.rs

1//! The engine-adapter seam: [`TuiEngine`].
2//!
3//! Why: `trusty-code-tui` renders one interaction model for two different
4//! products — trusty-code (daemon-backed coding agent) and trusty-agents
5//! (tagent's REPL). Rather than fork the TUI per product, the TUI stays
6//! engine-agnostic and each product supplies a thin [`TuiEngine`]
7//! implementation that translates user input into its own backend calls and
8//! backend responses into [`crate::ReplEvent`] values pushed onto the shared
9//! channel. See DOC-50 §2.2 for the full architecture rationale.
10//!
11//! What: this module defines only the trait — no event loop, no rendering.
12//! The event loop that drives `handle_input`/`setup`/`shutdown` lands in
13//! Slice 2 (#3414). Slice 1.5 (#3413) adds two data-supply accessors,
14//! `commands` and `picker`, so the shared crate can render slash-command
15//! help and inline pickers from engine-supplied data instead of hardcoded
16//! per-product lists (DOC-50 §3.2) — both default to "nothing supplied" so
17//! no existing/future `TuiEngine` implementor breaks by not overriding
18//! them. Statusline segments do NOT get a parallel accessor here: Slice 1's
19//! `ReplEvent::StatuslineUpdate` (pushed from `setup`/
20//! `subscribe_workstream_events`) already is the engine-supply mechanism
21//! for those; adding a second, pull-based path would just give the shared
22//! event loop two sources of truth to reconcile.
23//!
24//! # Spec References
25//! - [`SPEC-TTUI-02~draft`](../../../docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-02~draft) — architecture, the engine-adapter seam.
26//! - [`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.
27
28use crate::event::ReplEvent;
29use crate::model::{CommandDescriptor, PickerRequest};
30use anyhow::Result;
31use tokio::sync::mpsc::UnboundedSender;
32
33/// Translates one product's backend (tcode daemon, tagent's in-process LLM
34/// dispatch) into the shared TUI's vocabulary.
35///
36/// Why: this is the entire "seam" DOC-50 §2.2 describes — the TUI knows
37/// nothing about tcode or tagent, only about `TuiEngine`. Keeping the trait
38/// to a handful of methods keeps engine adapters "thin" per the thin-client
39/// axiom (DOC-50 §2.1, C-1/C-2): all real work (running the agent,
40/// cancelling a session, subscribing to workstream events) happens on the
41/// far side of `handle_input`/`cancel_session`/`subscribe_workstream_events`,
42/// never inside the TUI itself.
43///
44/// What: implementors push zero or more [`ReplEvent`] values onto `tx` for
45/// every method; the shared event loop (Slice 2+) owns turning those events
46/// into screen updates. `cancel_session` and `subscribe_workstream_events`
47/// default to no-ops so an engine that doesn't support in-flight cancellation
48/// or workstream awareness (e.g. an MVP or test double) needs no boilerplate.
49///
50/// Thread-safety: `Send + Sync` because the shared event loop dispatches
51/// `handle_input` onto a spawned `tokio::task` per submitted line (mirroring
52/// `crates/trusty-agents/src/repl/tui/events.rs`), so the engine must be
53/// shareable across that task boundary (typically via `Arc<dyn TuiEngine>`).
54///
55/// # Spec References
56/// - [`SPEC-TTUI-02~draft`](../../../docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-02~draft)
57#[async_trait::async_trait]
58pub trait TuiEngine: Send + Sync {
59    /// Process one submitted line — either free-form chat input or a slash
60    /// command the shared router didn't handle client-side.
61    ///
62    /// Why: this is the single request/response entry point between the TUI
63    /// and the product backend; keeping it to one method (vs. exposing many
64    /// backend-specific calls) is what lets the TUI stay backend-agnostic.
65    /// What: `line` is the raw text the user submitted (echoing to the
66    /// scrollback already happened before this is called, mirroring tagent's
67    /// existing `process_event` behavior). Implementations push output
68    /// (assistant text, tool invocations, status messages, errors) onto `tx`
69    /// as [`ReplEvent`] values. Returns `Ok(true)` to keep the REPL running,
70    /// `Ok(false)` to quit; an `Err` is surfaced to the user as an error
71    /// event by the caller, not propagated as a panic.
72    ///
73    /// **Contract on `tx`'s lifetime (DOC-50 §5 Slice 5's dispatch layer,
74    /// `crate::run::dispatch_pending`):** `tx` is a private, per-call channel
75    /// — do not retain a clone of it (e.g. inside a detached background
76    /// task) past this call's return. The shared dispatch layer awaits that
77    /// channel's forwarder to fully drain immediately after this future
78    /// resolves, as part of detecting whether a terminal signal
79    /// (`AssistantOutput { done: true, .. }` or the quit path) was ever
80    /// produced; a clone kept alive beyond the call would stall that
81    /// detection. This does not restrict implementations from spawning their
82    /// OWN background work — only from smuggling `tx` itself into anything
83    /// outliving the call. Note also that **not every `Ok(true)` needs to
84    /// send a terminal `AssistantOutput`** (e.g. a `/workstream list` that
85    /// only pushes `StatusMessage`/`WorkstreamUpdated`) — the dispatch layer
86    /// detects that gap and synthesizes `ReplEvent::TurnFinished` itself, so
87    /// implementations are NOT required to send a synthetic empty
88    /// `AssistantOutput { done: true, .. }` just to clear `busy`.
89    /// Test: exercised via a mock `TuiEngine` in Slice 2+ integration tests
90    /// (`crates/trusty-code-tui/tests/`); no runtime behavior to unit-test yet in
91    /// Slice 1.
92    async fn handle_input(&self, line: String, tx: UnboundedSender<ReplEvent>) -> Result<bool>;
93
94    /// Load initial state (session id, model, workstream, roster, …) before
95    /// the render loop starts.
96    ///
97    /// Why: the REPL needs to show a populated status line and scrollback on
98    /// first frame rather than blank state that fills in asynchronously with
99    /// a visible flash.
100    /// What: implementations push whatever startup [`ReplEvent`] values are
101    /// relevant (e.g. `WorkstreamUpdated`, `StatusMessage`) onto `tx`. Called
102    /// exactly once, before the first render.
103    /// Test: see `handle_input`.
104    async fn setup(&self, tx: UnboundedSender<ReplEvent>) -> Result<()>;
105
106    /// Cancel the in-flight request started by the most recent
107    /// `handle_input` call, if any.
108    ///
109    /// Why: DOC-50 §5 Slice 5 requires Ctrl-C to relay a real cancellation to
110    /// the backend (thin-client axiom C-2 — the backend performs the
111    /// cancellation, not just the UI stopping its own render). Defaulting to
112    /// a no-op lets engines without a cancellable backend operation (or test
113    /// doubles) skip the override.
114    /// What: implementations that support cancellation should call through
115    /// to their backend's cancel/abort API; the shared event loop calls this
116    /// exactly once per Ctrl-C while a request is in flight.
117    /// Test: see `handle_input`.
118    async fn cancel_session(&self) -> Result<()> {
119        Ok(())
120    }
121
122    /// Open (or re-open) a subscription to backend-pushed events that aren't
123    /// direct responses to `handle_input` — chiefly workstream activation
124    /// changes (DOC-48 §5.3).
125    ///
126    /// Why: workstream awareness (DOC-50 §5 Slice 6) is push-driven — the
127    /// daemon can activate a different workstream out-of-band (another
128    /// client, another session) and the TUI must reflect that without the
129    /// user typing anything. Modeling this as a trait method (rather than a
130    /// bespoke SSE client living in the TUI) keeps the thin-client axiom
131    /// intact: only the engine adapter knows the transport (SSE over HTTP
132    /// for tcode; nothing, for tagent today).
133    /// What: implementations that support push events spawn their own
134    /// listener and forward `WorkstreamUpdated` / `WorkstreamActivationChanged`
135    /// (and, on transport loss, `ConnectionLost`) onto `tx`. The default
136    /// no-op is correct for engines with no push transport; the shared event
137    /// loop calls this once, after `setup`.
138    /// Test: see `handle_input`.
139    async fn subscribe_workstream_events(&self, tx: UnboundedSender<ReplEvent>) -> Result<()> {
140        let _ = tx;
141        Ok(())
142    }
143
144    /// Domain slash-command entries this engine contributes (e.g. `/model`,
145    /// `/workstream` for `AgentEngine`/`CodeEngine` respectively).
146    ///
147    /// Why: DOC-50 §6 Q4 (mixed routing) splits slash commands into
148    /// client-side built-ins (`/help`, `/clear`, `/quit` — owned by
149    /// `trusty-code-tui` itself, never listed here) and engine-routed domain
150    /// commands. This is how `/help` (Slice 7) learns about the latter
151    /// without the shared crate hardcoding tagent's or tcode's command set
152    /// (replacing tagent's `SLASH_COMMANDS` array,
153    /// `crates/trusty-agents/src/repl/tui/helpers.rs:156-181`).
154    /// What: returns every [`CommandDescriptor`] this engine handles via
155    /// `handle_input`. Entries should use [`crate::model::CommandRouting::Engine`]
156    /// (the shared crate does not currently validate this, but a
157    /// `BuiltIn`-routed entry here would never be dispatched — built-ins are
158    /// intercepted before `handle_input` is called). Default: empty, for
159    /// engines/test doubles with no domain commands.
160    ///
161    /// **Sync constraint:** this method is deliberately synchronous (no
162    /// network I/O on the calling path) so `/help` can render instantly.
163    /// A network-backed implementor (Slice 3's HTTP `CodeEngine`) therefore
164    /// CANNOT fetch its command list on demand here — it must pre-fetch the
165    /// daemon's command table during `async setup()` and cache it (e.g. in
166    /// an `Arc<Mutex<Vec<CommandDescriptor>>>` or similar), then have this
167    /// method serve from that cache. Returning a stale/empty list here is
168    /// preferable to blocking `/help` on a request.
169    /// Test: `commands_defaults_to_empty` (this module).
170    fn commands(&self) -> Vec<CommandDescriptor> {
171        Vec::new()
172    }
173
174    /// Look up an engine-supplied picker by name (e.g. `"model"`,
175    /// `"provider"`, `"workstream"`) — the data source behind DOC-50 §3.2's
176    /// picker generalization.
177    ///
178    /// Why: generalizes tagent's hardcoded `PickerKind::{Model,Provider}`
179    /// (`crates/trusty-agents/src/repl/tui/types.rs:28-35`), where the
180    /// items and the Enter-dispatch command are both baked into the REPL
181    /// itself. Here, the engine names the picker, supplies its items, and
182    /// supplies the dispatch command — see [`PickerRequest`] for the full
183    /// contract the shared event loop (Slice 4/7) builds on.
184    /// What: `name` identifies which picker was requested (e.g. via a
185    /// `/model` invocation reaching `handle_input`, which — instead of
186    /// answering inline — can have the shared router call this first).
187    /// Returns `None` when the engine has no picker under that name.
188    /// Default: always `None`, for engines with no pickers yet.
189    ///
190    /// **Naming convention (not type-enforced):** a command's name doubles
191    /// as its picker name — a bare `/model` (no args) reaching
192    /// `handle_input` is expected to trigger `picker("model")`, `/provider`
193    /// triggers `picker("provider")`, and so on. On confirmation, the
194    /// shared event loop (Slice 4/5) composes
195    /// `"{PickerRequest::dispatch_command} {selected.id}"` (e.g.
196    /// `"/model opus-4"`) and resubmits it as `ReplEvent::Submit`, which is
197    /// what actually performs the selection — `picker()` itself only
198    /// supplies the list, it never applies a selection. Nothing in the type
199    /// system links a `CommandDescriptor.name` to a `picker()` name or a
200    /// `PickerRequest.dispatch_command`; an engine implementing both must
201    /// keep them in lockstep by convention (mirrors tagent's existing
202    /// `PickerKind::Model` → `"/model <selected>"` pairing,
203    /// `crates/trusty-agents/src/repl/tui/types.rs:28-35`).
204    ///
205    /// **Sync constraint:** same as [`Self::commands`] — this method is
206    /// synchronous, so a network-backed implementor (Slice 3's
207    /// `CodeEngine`) cannot fetch items on demand here. Pre-fetch during
208    /// `async setup()` (or on first use of a given picker name, cached
209    /// after) and serve from that cache; a `handle_input` invocation that
210    /// needs fresh data should refresh the cache there, not inside
211    /// `picker()`.
212    /// Test: `picker_defaults_to_none` (this module).
213    fn picker(&self, name: &str) -> Option<PickerRequest> {
214        let _ = name;
215        None
216    }
217
218    /// Graceful shutdown — close any open backend connections.
219    ///
220    /// Why: mirrors the original `ReplHandler` contract in
221    /// `crates/trusty-agents/src/repl/tui/run.rs`; kept optional since most
222    /// engines have nothing to flush.
223    /// What: called once, after the render loop exits (`app.quit == true` or
224    /// Ctrl-D). Errors are logged, not fatal.
225    /// Test: see `handle_input`.
226    async fn shutdown(&self) -> Result<()> {
227        Ok(())
228    }
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234    use crate::model::CommandRouting;
235
236    /// A minimal `TuiEngine` implementing only the two required methods —
237    /// stands in for a test double or an MVP engine that hasn't grown
238    /// domain commands/pickers yet.
239    struct BareEngine;
240
241    #[async_trait::async_trait]
242    impl TuiEngine for BareEngine {
243        async fn handle_input(
244            &self,
245            _line: String,
246            _tx: UnboundedSender<ReplEvent>,
247        ) -> Result<bool> {
248            Ok(true)
249        }
250
251        async fn setup(&self, _tx: UnboundedSender<ReplEvent>) -> Result<()> {
252            Ok(())
253        }
254    }
255
256    /// An engine that overrides `commands`/`picker` — stands in for
257    /// `AgentEngine`/`CodeEngine` once Slice 10/3 land, proving the trait
258    /// defaults are genuinely overridable (not accidentally `sealed` or
259    /// `final` via the macro expansion).
260    struct RichEngine;
261
262    #[async_trait::async_trait]
263    impl TuiEngine for RichEngine {
264        async fn handle_input(
265            &self,
266            _line: String,
267            _tx: UnboundedSender<ReplEvent>,
268        ) -> Result<bool> {
269            Ok(true)
270        }
271
272        async fn setup(&self, _tx: UnboundedSender<ReplEvent>) -> Result<()> {
273            Ok(())
274        }
275
276        fn commands(&self) -> Vec<CommandDescriptor> {
277            vec![CommandDescriptor {
278                name: "workstream".to_string(),
279                summary: "List or activate a workstream".to_string(),
280                routing: CommandRouting::Engine,
281                args_hint: Some("activate <id>".to_string()),
282            }]
283        }
284
285        fn picker(&self, name: &str) -> Option<PickerRequest> {
286            (name == "model").then(|| PickerRequest {
287                title: "Select a model".to_string(),
288                items: Vec::new(),
289                dispatch_command: "/model".to_string(),
290            })
291        }
292    }
293
294    /// An engine that implements only the required methods (no `commands`
295    /// override) must still compile and yield an empty command list — the
296    /// whole point of giving `commands()` a default body (existing/future
297    /// implementors don't break, and "supply nothing" is silent rather than
298    /// a panic or an error). Cited by the `commands()` doc comment's
299    /// `Test:` pointer.
300    #[test]
301    fn commands_defaults_to_empty() {
302        let engine = BareEngine;
303        assert!(engine.commands().is_empty());
304    }
305
306    /// An engine that implements only the required methods (no `picker`
307    /// override) must still compile and yield `None` for any picker name —
308    /// same "nothing supplied, no panic" contract as `commands()`. Cited by
309    /// the `picker()` doc comment's `Test:` pointer.
310    #[test]
311    fn picker_defaults_to_none() {
312        let engine = BareEngine;
313        assert!(engine.picker("model").is_none());
314        assert!(engine.picker("anything").is_none());
315    }
316
317    /// An engine that DOES override `commands`/`picker` must have its
318    /// overrides take effect (not silently fall back to the trait default).
319    #[test]
320    fn commands_and_picker_overrides_take_effect() {
321        let engine = RichEngine;
322
323        let commands = engine.commands();
324        assert_eq!(commands.len(), 1);
325        assert_eq!(commands[0].name, "workstream");
326        assert_eq!(commands[0].routing, CommandRouting::Engine);
327
328        let picker = engine.picker("model").expect("model picker present");
329        assert_eq!(picker.title, "Select a model");
330        assert_eq!(picker.dispatch_command, "/model");
331        assert!(engine.picker("provider").is_none());
332    }
333}