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::{CancelReply, CommandDescriptor, PermissionAnswer, 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. This is the one-state form: it
116    /// says only whether the request was delivered, never whether the run
117    /// actually stopped. The shared event loop reaches it through
118    /// [`Self::cancel_session_reply`]'s default, so an engine whose backend
119    /// can report "not stopped yet" overrides that method instead of this one.
120    /// Test: see `handle_input`.
121    async fn cancel_session(&self) -> Result<()> {
122        Ok(())
123    }
124
125    /// Cancel the in-flight request and report what the backend actually
126    /// CONFIRMED (#8207).
127    ///
128    /// Why: [`Self::cancel_session`]'s `Result<()>` has no way to say
129    /// "accepted, but the run has not stopped yet" — the state a cooperative
130    /// cancel really can be in. Flattening that into `Ok(())` is what let the
131    /// TUI print "cancelled" and reopen input while the daemon task was still
132    /// winding down, so the next prompt came back `-32003 already has a task
133    /// running` (#8207). Flattening it into `Err` is no better: a cancel that
134    /// did not land must not read as one that did, but neither should one that
135    /// was accepted read as a transport failure.
136    /// What: deliberately infallible — every failure is a
137    /// [`CancelReply::Failed`], so no arm can be forgotten by a caller doing a
138    /// total match. Each payload string is rendered verbatim to the user, so an
139    /// implementor strips protocol detail (an error code, a JSON-RPC envelope)
140    /// before returning it. The default lifts [`Self::cancel_session`]:
141    /// `Ok(())` becomes [`CancelReply::Stopped`] and an `Err` becomes
142    /// [`CancelReply::Failed`], so an engine with a one-state cancel — and
143    /// every test double — needs no override. The shared event loop calls this
144    /// exactly once per cancel gesture.
145    /// Test: `cancel_session_reply_defaults_to_stopped`,
146    /// `cancel_session_reply_default_reports_an_error_as_failed` (this
147    /// module); `crate::run::tests::dispatch_pending_cancel_holds_input_until_the_reply_lands`
148    /// covers the dispatch wiring.
149    async fn cancel_session_reply(&self) -> CancelReply {
150        match self.cancel_session().await {
151            Ok(()) => CancelReply::Stopped,
152            Err(e) => CancelReply::Failed {
153                error: format!("{e:#}"),
154            },
155        }
156    }
157
158    /// Answer one suspended permission request (#3422).
159    ///
160    /// Why: a [`ReplEvent::PermissionRequested`] leaves a tool call stopped
161    /// on the backend; only the backend can release it, so the key press has
162    /// to become a real backend call — the same thin-client reasoning as
163    /// [`Self::cancel_session`] (ADR-0063, DOC-50 §2.1 C-2). The TUI applies
164    /// no local policy: it does not pre-approve, does not remember grants,
165    /// and does not decide what a session-wide grant covers.
166    /// What: `request_id` comes off the event that opened the prompt;
167    /// `answer` names which of the three the user chose. Implementations
168    /// translate `answer` into their own backend's decision type — this
169    /// crate deliberately carries no wire words. The shared event loop calls
170    /// this exactly once per answered prompt. Default no-op, for engines
171    /// (and test doubles) with no permission surface.
172    /// Test: `respond_permission_defaults_to_ok` (this module);
173    /// `crate::run::tests::dispatch_pending_permission_answer_reaches_respond_permission`
174    /// covers the dispatch wiring.
175    async fn respond_permission(&self, request_id: String, answer: PermissionAnswer) -> Result<()> {
176        let _ = (request_id, answer);
177        Ok(())
178    }
179
180    /// Open (or re-open) a subscription to backend-pushed events that aren't
181    /// direct responses to `handle_input` — chiefly workstream activation
182    /// changes (DOC-48 §5.3).
183    ///
184    /// Why: workstream awareness (DOC-50 §5 Slice 6) is push-driven — the
185    /// daemon can activate a different workstream out-of-band (another
186    /// client, another session) and the TUI must reflect that without the
187    /// user typing anything. Modeling this as a trait method (rather than a
188    /// bespoke SSE client living in the TUI) keeps the thin-client axiom
189    /// intact: only the engine adapter knows the transport (SSE over HTTP
190    /// for tcode; nothing, for tagent today).
191    /// What: implementations that support push events spawn their own
192    /// listener and forward `WorkstreamUpdated` / `WorkstreamActivationChanged`
193    /// (and, on transport loss, `ConnectionLost`) onto `tx`. The default
194    /// no-op is correct for engines with no push transport; the shared event
195    /// loop calls this once, after `setup`.
196    /// Test: see `handle_input`.
197    async fn subscribe_workstream_events(&self, tx: UnboundedSender<ReplEvent>) -> Result<()> {
198        let _ = tx;
199        Ok(())
200    }
201
202    /// Domain slash-command entries this engine contributes (e.g. `/model`,
203    /// `/workstream` for `AgentEngine`/`CodeEngine` respectively).
204    ///
205    /// Why: DOC-50 §6 Q4 (mixed routing) splits slash commands into
206    /// client-side built-ins (`/help`, `/clear`, `/quit` — owned by
207    /// `trusty-code-tui` itself, never listed here) and engine-routed domain
208    /// commands. This is how `/help` (Slice 7) learns about the latter
209    /// without the shared crate hardcoding tagent's or tcode's command set
210    /// (replacing tagent's `SLASH_COMMANDS` array,
211    /// `crates/trusty-agents/src/repl/tui/helpers.rs:156-181`).
212    /// What: returns every [`CommandDescriptor`] this engine handles via
213    /// `handle_input`. Entries should use [`crate::model::CommandRouting::Engine`]
214    /// (the shared crate does not currently validate this, but a
215    /// `BuiltIn`-routed entry here would never be dispatched — built-ins are
216    /// intercepted before `handle_input` is called). Default: empty, for
217    /// engines/test doubles with no domain commands.
218    ///
219    /// **Sync constraint:** this method is deliberately synchronous (no
220    /// network I/O on the calling path) so `/help` can render instantly.
221    /// A network-backed implementor (Slice 3's HTTP `CodeEngine`) therefore
222    /// CANNOT fetch its command list on demand here — it must pre-fetch the
223    /// daemon's command table during `async setup()` and cache it (e.g. in
224    /// an `Arc<Mutex<Vec<CommandDescriptor>>>` or similar), then have this
225    /// method serve from that cache. Returning a stale/empty list here is
226    /// preferable to blocking `/help` on a request.
227    /// Test: `commands_defaults_to_empty` (this module).
228    fn commands(&self) -> Vec<CommandDescriptor> {
229        Vec::new()
230    }
231
232    /// Look up an engine-supplied picker by name (e.g. `"model"`,
233    /// `"provider"`, `"workstream"`) — the data source behind DOC-50 §3.2's
234    /// picker generalization.
235    ///
236    /// Why: generalizes tagent's hardcoded `PickerKind::{Model,Provider}`
237    /// (`crates/trusty-agents/src/repl/tui/types.rs:28-35`), where the
238    /// items and the Enter-dispatch command are both baked into the REPL
239    /// itself. Here, the engine names the picker, supplies its items, and
240    /// supplies the dispatch command — see [`PickerRequest`] for the full
241    /// contract the shared event loop (Slice 4/7) builds on.
242    /// What: `name` identifies which picker was requested (e.g. via a
243    /// `/model` invocation reaching `handle_input`, which — instead of
244    /// answering inline — can have the shared router call this first).
245    /// Returns `None` when the engine has no picker under that name.
246    /// Default: always `None`, for engines with no pickers yet.
247    ///
248    /// **Naming convention (not type-enforced):** a command's name doubles
249    /// as its picker name — a bare `/model` (no args) reaching
250    /// `handle_input` is expected to trigger `picker("model")`, `/provider`
251    /// triggers `picker("provider")`, and so on. On confirmation, the
252    /// shared event loop (Slice 4/5) composes
253    /// `"{PickerRequest::dispatch_command} {selected.id}"` (e.g.
254    /// `"/model opus-4"`) and resubmits it as `ReplEvent::Submit`, which is
255    /// what actually performs the selection — `picker()` itself only
256    /// supplies the list, it never applies a selection. Nothing in the type
257    /// system links a `CommandDescriptor.name` to a `picker()` name or a
258    /// `PickerRequest.dispatch_command`; an engine implementing both must
259    /// keep them in lockstep by convention (mirrors tagent's existing
260    /// `PickerKind::Model` → `"/model <selected>"` pairing,
261    /// `crates/trusty-agents/src/repl/tui/types.rs:28-35`).
262    ///
263    /// **Sync constraint:** same as [`Self::commands`] — this method is
264    /// synchronous, so a network-backed implementor (Slice 3's
265    /// `CodeEngine`) cannot fetch items on demand here. Pre-fetch during
266    /// `async setup()` (or on first use of a given picker name, cached
267    /// after) and serve from that cache; a `handle_input` invocation that
268    /// needs fresh data should refresh the cache there, not inside
269    /// `picker()`.
270    /// Test: `picker_defaults_to_none` (this module).
271    fn picker(&self, name: &str) -> Option<PickerRequest> {
272        let _ = name;
273        None
274    }
275
276    /// Graceful shutdown — close any open backend connections.
277    ///
278    /// Why: mirrors the original `ReplHandler` contract in
279    /// `crates/trusty-agents/src/repl/tui/run.rs`; kept optional since most
280    /// engines have nothing to flush.
281    /// What: called once, after the render loop exits (`app.quit == true` or
282    /// Ctrl-D). Errors are logged, not fatal.
283    /// Test: see `handle_input`.
284    async fn shutdown(&self) -> Result<()> {
285        Ok(())
286    }
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292    use crate::model::CommandRouting;
293
294    /// A minimal `TuiEngine` implementing only the two required methods —
295    /// stands in for a test double or an MVP engine that hasn't grown
296    /// domain commands/pickers yet.
297    struct BareEngine;
298
299    #[async_trait::async_trait]
300    impl TuiEngine for BareEngine {
301        async fn handle_input(
302            &self,
303            _line: String,
304            _tx: UnboundedSender<ReplEvent>,
305        ) -> Result<bool> {
306            Ok(true)
307        }
308
309        async fn setup(&self, _tx: UnboundedSender<ReplEvent>) -> Result<()> {
310            Ok(())
311        }
312    }
313
314    /// An engine that overrides `commands`/`picker` — stands in for
315    /// `AgentEngine`/`CodeEngine` once Slice 10/3 land, proving the trait
316    /// defaults are genuinely overridable (not accidentally `sealed` or
317    /// `final` via the macro expansion).
318    struct RichEngine;
319
320    #[async_trait::async_trait]
321    impl TuiEngine for RichEngine {
322        async fn handle_input(
323            &self,
324            _line: String,
325            _tx: UnboundedSender<ReplEvent>,
326        ) -> Result<bool> {
327            Ok(true)
328        }
329
330        async fn setup(&self, _tx: UnboundedSender<ReplEvent>) -> Result<()> {
331            Ok(())
332        }
333
334        fn commands(&self) -> Vec<CommandDescriptor> {
335            vec![CommandDescriptor {
336                name: "workstream".to_string(),
337                summary: "List or activate a workstream".to_string(),
338                routing: CommandRouting::Engine,
339                args_hint: Some("activate <id>".to_string()),
340            }]
341        }
342
343        fn picker(&self, name: &str) -> Option<PickerRequest> {
344            (name == "model").then(|| PickerRequest {
345                title: "Select a model".to_string(),
346                items: Vec::new(),
347                dispatch_command: "/model".to_string(),
348            })
349        }
350    }
351
352    /// An engine that implements only the required methods (no `commands`
353    /// override) must still compile and yield an empty command list — the
354    /// whole point of giving `commands()` a default body (existing/future
355    /// implementors don't break, and "supply nothing" is silent rather than
356    /// a panic or an error). Cited by the `commands()` doc comment's
357    /// `Test:` pointer.
358    #[test]
359    fn commands_defaults_to_empty() {
360        let engine = BareEngine;
361        assert!(engine.commands().is_empty());
362    }
363
364    /// An engine that implements only the required methods (no `picker`
365    /// override) must still compile and yield `None` for any picker name —
366    /// same "nothing supplied, no panic" contract as `commands()`. Cited by
367    /// the `picker()` doc comment's `Test:` pointer.
368    #[test]
369    fn picker_defaults_to_none() {
370        let engine = BareEngine;
371        assert!(engine.picker("model").is_none());
372        assert!(engine.picker("anything").is_none());
373    }
374
375    /// An engine with no permission surface must still compile and report
376    /// success — the "nothing to do, no panic" contract every defaulted
377    /// method here shares. Cited by `respond_permission`'s `Test:` pointer.
378    #[tokio::test]
379    async fn respond_permission_defaults_to_ok() {
380        let engine = BareEngine;
381        assert!(
382            engine
383                .respond_permission("req-1".to_string(), PermissionAnswer::Deny)
384                .await
385                .is_ok()
386        );
387    }
388
389    /// An engine whose `cancel_session` fails — the transport-gone shape
390    /// [`TuiEngine::cancel_session_reply`]'s default has to translate (#8207).
391    struct FailingCancelEngine;
392
393    #[async_trait::async_trait]
394    impl TuiEngine for FailingCancelEngine {
395        async fn handle_input(
396            &self,
397            _line: String,
398            _tx: UnboundedSender<ReplEvent>,
399        ) -> Result<bool> {
400            Ok(true)
401        }
402
403        async fn setup(&self, _tx: UnboundedSender<ReplEvent>) -> Result<()> {
404            Ok(())
405        }
406
407        async fn cancel_session(&self) -> Result<()> {
408            Err(anyhow::anyhow!("socket closed"))
409        }
410    }
411
412    /// #8207: an engine with a one-state cancel needs no override, and its
413    /// `Ok(())` must lift to `Stopped` — the arm that reopens input. Compile-
414    /// level as much as behavioural: `BareEngine` overrides nothing, so this
415    /// also proves the new method did not become a required one.
416    #[tokio::test]
417    async fn cancel_session_reply_defaults_to_stopped() {
418        assert_eq!(
419            BareEngine.cancel_session_reply().await,
420            CancelReply::Stopped
421        );
422    }
423
424    /// #8207: a failed `cancel_session` must lift to `Failed`, never `Stopped`
425    /// — the default is the fail-open hazard's first opportunity, so it is
426    /// asserted at the seam and not only in the reducer.
427    #[tokio::test]
428    async fn cancel_session_reply_default_reports_an_error_as_failed() {
429        assert_eq!(
430            FailingCancelEngine.cancel_session_reply().await,
431            CancelReply::Failed {
432                error: "socket closed".to_string()
433            }
434        );
435    }
436
437    /// An engine that DOES override `commands`/`picker` must have its
438    /// overrides take effect (not silently fall back to the trait default).
439    #[test]
440    fn commands_and_picker_overrides_take_effect() {
441        let engine = RichEngine;
442
443        let commands = engine.commands();
444        assert_eq!(commands.len(), 1);
445        assert_eq!(commands[0].name, "workstream");
446        assert_eq!(commands[0].routing, CommandRouting::Engine);
447
448        let picker = engine.picker("model").expect("model picker present");
449        assert_eq!(picker.title, "Select a model");
450        assert_eq!(picker.dispatch_command, "/model");
451        assert!(engine.picker("provider").is_none());
452    }
453}