Skip to main content

TuiEngine

Trait TuiEngine 

Source
pub trait TuiEngine: Send + Sync {
    // Required methods
    fn handle_input<'life0, 'async_trait>(
        &'life0 self,
        line: String,
        tx: UnboundedSender<ReplEvent>,
    ) -> Pin<Box<dyn Future<Output = Result<bool>> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait;
    fn setup<'life0, 'async_trait>(
        &'life0 self,
        tx: UnboundedSender<ReplEvent>,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait;

    // Provided methods
    fn cancel_session<'life0, 'async_trait>(
        &'life0 self,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait { ... }
    fn subscribe_workstream_events<'life0, 'async_trait>(
        &'life0 self,
        tx: UnboundedSender<ReplEvent>,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait { ... }
    fn commands(&self) -> Vec<CommandDescriptor> { ... }
    fn picker(&self, name: &str) -> Option<PickerRequest> { ... }
    fn shutdown<'life0, 'async_trait>(
        &'life0 self,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait { ... }
}
Expand description

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

Required Methods§

Source

fn handle_input<'life0, 'async_trait>( &'life0 self, line: String, tx: UnboundedSender<ReplEvent>, ) -> Pin<Box<dyn Future<Output = Result<bool>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

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.

Source

fn setup<'life0, 'async_trait>( &'life0 self, tx: UnboundedSender<ReplEvent>, ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

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.

Provided Methods§

Source

fn cancel_session<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

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; the shared event loop calls this exactly once per Ctrl-C while a request is in flight. Test: see handle_input.

Source

fn subscribe_workstream_events<'life0, 'async_trait>( &'life0 self, tx: UnboundedSender<ReplEvent>, ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

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.

Source

fn commands(&self) -> Vec<CommandDescriptor>

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).

Source

fn picker(&self, name: &str) -> Option<PickerRequest>

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).

Source

fn shutdown<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

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.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§