trusty_code/tui_client/engine.rs
1//! [`CodeEngine`]: the `trusty_code_tui::TuiEngine` adapter driving a long-lived
2//! `tcode serve --http` daemon (issue #3415, DOC-50 §3.3/§3.4).
3//!
4//! Why: see `crate::tui_client`'s module docs for the ephemeral-`--stdio`
5//! vs. long-lived-`--http` client distinction. This module is the `TuiEngine`
6//! impl itself — everything else in `tui_client` (`discovery`, `rpc`, `sse`)
7//! exists to support it. Split across sibling files (issue #610's 500-SLOC
8//! production-file cap): `engine_state.rs` holds [`super::engine_state::EngineState`]
9//! (the actual session/cache/streaming logic), `session_events.rs` holds
10//! the pure `Event` -> `ReplEvent` mapping, `workstream_subscription.rs`
11//! holds the background workstream-activation SSE loop. This file keeps
12//! only the public `CodeEngine` wrapper and the `TuiEngine` impl that
13//! delegates into `EngineState`.
14//! What: [`CodeEngine`] is a thin `Arc<EngineState>` wrapper so the
15//! background workstream-subscription task spawned by
16//! `subscribe_workstream_events` can share the SAME state (and refresh the
17//! SAME caches) without a second, divergent copy. `trusty-code-tui` Slice 1.5
18//! (#3428, merged) added the SYNCHRONOUS `TuiEngine::commands()`/
19//! `picker(name)` accessors this `impl TuiEngine` block implements directly
20//! (not as inherent methods — see the `impl TuiEngine for CodeEngine`
21//! block's `commands`/`picker` for why serving from `EngineState`'s
22//! `std::sync::Mutex`-guarded caches, populated during `setup()`, is the
23//! only way to satisfy a synchronous trait method with no I/O on the
24//! calling path).
25//! Test: `engine_tests::*` (in the sibling `engine_tests.rs`, included
26//! below) for the pure event-mapping/parsing helpers this module's siblings
27//! define; the full discover -> setup -> stream -> cancel ->
28//! workstream-activation flow against a mock HTTP daemon lives in
29//! `tests/tui_client_engine.rs`.
30
31use std::path::PathBuf;
32use std::sync::Arc;
33use std::sync::atomic::Ordering;
34use std::time::Duration;
35
36use serde_json::{Value, json};
37use tokio::sync::mpsc::UnboundedSender;
38use trusty_code_tui::{CommandDescriptor, CommandRouting, PickerRequest, ReplEvent, TuiEngine};
39
40use super::discovery::discover_daemon_url;
41use super::engine_state::EngineState;
42use super::error::EngineError;
43use super::rpc::RpcHttpClient;
44use super::workstream_subscription::run_workstream_subscription;
45
46/// How long a session-event / workstream-event SSE read may sit idle (no
47/// bytes, not even a keep-alive comment) before this client treats the
48/// connection as dead and reconnects. Axum's default `KeepAlive` sends a
49/// comment roughly every 15s (`crate::serve::http::session_events_sse`'s
50/// `KeepAlive::default()`), so three missed beats is a generous margin
51/// before declaring the daemon unreachable. Shared with `engine_state.rs`
52/// and `workstream_subscription.rs`.
53pub(super) const SSE_IDLE_TIMEOUT: Duration = Duration::from_secs(45);
54
55/// Bound on the initial `GET /sessions/{id}/events` request — from
56/// connecting through receiving response headers — before
57/// `EngineState::pump_session_events` treats it as a failed attempt (issue
58/// #3494).
59///
60/// Why: `build_http_client()` sets a `connect_timeout(5s)` at the
61/// `reqwest::Client` level, which only bounds the TCP handshake. A daemon
62/// that accepts the connection but then never sends response headers (e.g.
63/// wedged, deadlocked, or slow-lorising) leaves `.send().await` pending
64/// forever — hanging `pump_session_events` indefinitely and completely
65/// bypassing `SESSION_STREAM_MAX_RECONNECTS`, since that reconnect budget
66/// only starts counting once `.send().await` actually resolves. A
67/// request-level `.timeout(CONNECT_TIMEOUT)` (applied only to THIS request,
68/// not the whole client) closes that gap: reqwest's per-request timeout
69/// bounds the connect-through-headers future `.send()` awaits (the same
70/// future `Response` resolves from) — it does NOT extend to the
71/// already-established `resp.bytes_stream()` body read afterward, which
72/// stays governed by [`SSE_IDLE_TIMEOUT`] via the existing
73/// `tokio::time::timeout(SSE_IDLE_TIMEOUT, lines.next_data())` below. A
74/// timed-out connect surfaces as a `reqwest::Error` from `.send()`, so it
75/// falls into the SAME retryable `Err(source)` branch as any other
76/// transport failure — counted against `SESSION_STREAM_MAX_RECONNECTS`
77/// like every other failure mode, not a new silent-hang path.
78pub(super) const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
79
80/// Fixed backoff between SSE reconnect attempts. Not exponential — MVP
81/// scope (DOC-50 §5 Slice 3); a persistently-down daemon retries at a
82/// steady, human-visible cadence rather than hot-looping. Shared with
83/// `engine_state.rs` and `workstream_subscription.rs`.
84pub(super) const RECONNECT_BACKOFF: Duration = Duration::from_secs(2);
85
86/// How many times `EngineState::pump_session_events` reconnects before
87/// giving up and returning control to the caller (`handle_input` must
88/// eventually return so the REPL's input loop stays responsive — unlike the
89/// workstream-activation subscription, which is meant to run for the whole
90/// TUI session). Shared with `engine_state.rs`.
91pub(super) const SESSION_STREAM_MAX_RECONNECTS: u32 = 5;
92
93/// Whether `rest` (already trimmed) names the `/workstream`/`/ws`
94/// engine-routed command, and if so, what follows it (empty string if bare).
95///
96/// Why: kept pure (no `&self`) so slash-command recognition is unit
97/// testable without constructing an engine. Requires a word boundary after
98/// the command name (a bare `strip_prefix` would wrongly match
99/// `"/workstreamx"`).
100fn workstream_subcommand(line: &str) -> Option<&str> {
101 let trimmed = line.trim();
102 for prefix in ["/workstream", "/ws"] {
103 if trimmed == prefix {
104 return Some("");
105 }
106 if let Some(rest) = trimmed.strip_prefix(prefix)
107 && let Some(rest) = rest.strip_prefix(' ')
108 {
109 return Some(rest.trim());
110 }
111 }
112 None
113}
114
115/// The pooled `reqwest::Client` every `CodeEngine` call (discovery ping,
116/// `POST /rpc`, SSE) shares.
117///
118/// Why: `pub` since #4512 so `tcode tui`'s auto-spawn path — which resolves
119/// the daemon URL itself, then hands it to [`CodeEngine::with_daemon_url`] —
120/// builds its liveness-probe client with the SAME pool settings the engine
121/// would have used, rather than a second, divergent client.
122pub fn build_http_client() -> reqwest::Client {
123 reqwest::Client::builder()
124 .pool_idle_timeout(Duration::from_secs(90))
125 .connect_timeout(Duration::from_secs(5))
126 .build()
127 .unwrap_or_else(|_| reqwest::Client::new())
128}
129
130/// The `trusty_code_tui::TuiEngine` adapter for `tcode tui` — see module docs.
131pub struct CodeEngine {
132 state: Arc<EngineState>,
133}
134
135impl CodeEngine {
136 /// Discover a running `tcode serve --http` daemon (per
137 /// `crate::tui_client::discovery`'s priority) and build a `CodeEngine`
138 /// targeting it. `project_path` is forwarded to `session.create` in
139 /// `setup()` (mirrors `session::protocol::create`'s `project` param —
140 /// `None` is a fully valid, projectless session).
141 pub async fn discover(project_path: Option<PathBuf>) -> Result<Self, EngineError> {
142 let http = build_http_client();
143 let base_url = discover_daemon_url(&http).await?;
144 Ok(Self::with_daemon_url(http, base_url, project_path))
145 }
146
147 /// Build a `CodeEngine` targeting an explicit daemon URL, bypassing
148 /// discovery — the constructor every test in `tests/tui_client_engine.rs`
149 /// uses (against a `wiremock`-mocked daemon).
150 pub fn with_daemon_url(
151 http: reqwest::Client,
152 base_url: impl Into<String>,
153 project_path: Option<PathBuf>,
154 ) -> Self {
155 Self {
156 state: Arc::new(EngineState::new(
157 RpcHttpClient::new(http, base_url.into()),
158 project_path,
159 )),
160 }
161 }
162
163 /// The daemon URL this engine targets (test/debug convenience).
164 pub fn daemon_url(&self) -> &str {
165 self.state.rpc.base_url()
166 }
167}
168
169#[async_trait::async_trait]
170impl TuiEngine for CodeEngine {
171 async fn handle_input(
172 &self,
173 line: String,
174 tx: UnboundedSender<ReplEvent>,
175 ) -> anyhow::Result<bool> {
176 if let Some(rest) = workstream_subcommand(&line) {
177 self.state.handle_workstream_command(rest, &tx).await?;
178 return Ok(true);
179 }
180 self.state.run_chat_turn(line.trim(), &tx).await?;
181 Ok(true)
182 }
183
184 async fn setup(&self, tx: UnboundedSender<ReplEvent>) -> anyhow::Result<()> {
185 let result = self
186 .state
187 .rpc
188 .call(
189 "session.create",
190 json!({
191 "task": "tcode tui session",
192 "project": self.state.project_path,
193 }),
194 )
195 .await?;
196 let session_id = result
197 .get("id")
198 .and_then(Value::as_str)
199 .ok_or_else(|| EngineError::Malformed("session.create: response missing `id`".into()))?
200 .to_string();
201 *self
202 .state
203 .session_id
204 .lock()
205 .unwrap_or_else(|e| e.into_inner()) = Some(session_id.clone());
206
207 // `TuiEngine::commands()` cache — see `EngineState`'s struct docs.
208 // The one engine-routed command this MVP supports.
209 *self
210 .state
211 .commands_cache
212 .lock()
213 .unwrap_or_else(|e| e.into_inner()) = vec![CommandDescriptor {
214 name: "workstream".to_string(),
215 summary: "List or activate the daemon's workstreams".to_string(),
216 routing: CommandRouting::Engine,
217 args_hint: Some("[list | activate <id>]".to_string()),
218 }];
219
220 if let Some(ws) = self.state.refresh_workstream_cache().await {
221 let _ = tx.send(ReplEvent::WorkstreamUpdated(ws));
222 // Populate the status line's Workstream segment on first render
223 // (DOC-50 §5.3, Slice 6) — without this, the TUI would show a
224 // blank statusline until the background SSE subscription (which
225 // only starts after `setup` returns, see `run.rs::run`) happens
226 // to observe an activation change.
227 let _ = tx.send(ReplEvent::StatuslineUpdate(
228 self.state.statusline_segments(),
229 ));
230 }
231
232 let _ = tx.send(ReplEvent::StatusMessage(format!(
233 "connected to tcode daemon at {} (session {session_id})",
234 self.state.rpc.base_url(),
235 )));
236 Ok(())
237 }
238
239 async fn cancel_session(&self) -> anyhow::Result<()> {
240 let session_id = {
241 self.state
242 .session_id
243 .lock()
244 .unwrap_or_else(|e| e.into_inner())
245 .clone()
246 };
247 let Some(session_id) = session_id else {
248 return Ok(());
249 };
250 // Thin-client axiom (DOC-39 §2.1 C-2): the daemon performs the real
251 // cancellation via `session.cancel` — this call is not optional
252 // client-side render-stop.
253 self.state
254 .rpc
255 .call("session.cancel", json!({ "session_id": session_id }))
256 .await?;
257 Ok(())
258 }
259
260 async fn subscribe_workstream_events(
261 &self,
262 tx: UnboundedSender<ReplEvent>,
263 ) -> anyhow::Result<()> {
264 let current_id = {
265 self.state
266 .active_workstream
267 .lock()
268 .unwrap_or_else(|e| e.into_inner())
269 .clone()
270 }
271 .map(|ws| ws.id);
272 // No workstream is known yet: DOC-48 §5.3's SSE fan-out is scoped
273 // PER workstream id (there is no daemon-wide "tell me about any
274 // future activation" feed), so there is genuinely nothing to
275 // subscribe to until at least one workstream id is known. See this
276 // crate's PR description for this as a reported daemon-API gap
277 // rather than a client-side workaround — matches the default no-op
278 // `TuiEngine::subscribe_workstream_events` contract for engines with
279 // no push transport available right now.
280 let Some(current_id) = current_id else {
281 return Ok(());
282 };
283 tokio::spawn(run_workstream_subscription(
284 self.state.clone(),
285 current_id,
286 tx,
287 ));
288 Ok(())
289 }
290
291 async fn shutdown(&self) -> anyhow::Result<()> {
292 self.state.shutting_down.store(true, Ordering::SeqCst);
293 Ok(())
294 }
295
296 /// Engine-routed slash commands this MVP supports — served from the
297 /// cache `setup()` populates (`EngineState::commands_cache`). This is a
298 /// SYNCHRONOUS trait method (#3428) — the cache exists precisely so
299 /// this never needs to perform network I/O on the calling path; see
300 /// `EngineState::commands`'s docs for the `std::sync::Mutex` rationale.
301 fn commands(&self) -> Vec<CommandDescriptor> {
302 self.state.commands()
303 }
304
305 /// The `"workstream"` picker — served from the cache
306 /// `EngineState::refresh_workstream_cache` populates (in `setup()`,
307 /// after `/workstream activate`, and on every observed
308 /// `WorkstreamActivationChanged`). `None` for any other picker name
309 /// (this engine has exactly one) or before the cache has been
310 /// populated at least once. `dispatch_command` is `"/workstream
311 /// activate"` — matching `workstream_subcommand`'s parsing exactly, so
312 /// the shared event loop's `"{dispatch_command} {selected.id}"`
313 /// resubmission (`"/workstream activate <id>"`) round-trips through
314 /// `handle_input` correctly.
315 fn picker(&self, name: &str) -> Option<PickerRequest> {
316 if name != "workstream" {
317 return None;
318 }
319 let items = self.state.picker_items("workstream")?;
320 Some(PickerRequest {
321 title: "Workstreams".to_string(),
322 items,
323 dispatch_command: "/workstream activate".to_string(),
324 })
325 }
326}
327
328#[cfg(test)]
329#[path = "engine_tests.rs"]
330mod engine_tests;