trusty_code/tui_client/engine.rs
1//! [`CodeEngine`]: the `trusty_code_tui::TuiEngine` adapter driving a long-lived
2//! `tcode serve` daemon over its Unix socket (issue #3415, DOC-50 §3.3/§3.4;
3//! retransported in #6637).
4//!
5//! Why: see `crate::tui_client`'s module docs for the ephemeral-`--stdio`
6//! vs. long-lived-daemon client distinction. This module is the `TuiEngine`
7//! impl itself — `uds_rpc` exists to support it. Split across sibling files
8//! (issue #610's 500-SLOC
9//! production-file cap): `engine_state.rs` holds [`super::engine_state::EngineState`]
10//! (the actual session/cache/streaming logic), `session_events.rs` holds
11//! the pure `Event` -> `ReplEvent` mapping, `workstream_subscription.rs`
12//! holds the background workstream-activation SSE loop, `splash.rs` holds
13//! the startup splash's pure text assembly (#8164). This file keeps
14//! only the public `CodeEngine` wrapper and the `TuiEngine` impl that
15//! delegates into `EngineState`.
16//! What: [`CodeEngine`] is a thin `Arc<EngineState>` wrapper so the
17//! background workstream-subscription task spawned by
18//! `subscribe_workstream_events` can share the SAME state (and refresh the
19//! SAME caches) without a second, divergent copy. `trusty-code-tui` Slice 1.5
20//! (#3428, merged) added the SYNCHRONOUS `TuiEngine::commands()`/
21//! `picker(name)` accessors this `impl TuiEngine` block implements directly
22//! (not as inherent methods — see the `impl TuiEngine for CodeEngine`
23//! block's `commands`/`picker` for why serving from `EngineState`'s
24//! `std::sync::Mutex`-guarded caches, populated during `setup()`, is the
25//! only way to satisfy a synchronous trait method with no I/O on the
26//! calling path).
27//! Test: `engine_tests::*` (in the sibling `engine_tests.rs`, included
28//! below) for the pure event-mapping/parsing helpers this module's siblings
29//! define; the full setup -> stream -> cancel -> workstream-activation flow
30//! against a real daemon socket lives in `tests/tui_client_engine.rs`.
31
32use std::path::PathBuf;
33use std::sync::Arc;
34use std::sync::atomic::Ordering;
35use std::time::Duration;
36
37use serde_json::{Value, json};
38use tokio::sync::mpsc::UnboundedSender;
39use trusty_code_tui::{
40 CancelReply, CommandDescriptor, CommandRouting, PermissionAnswer, PickerRequest, ReplEvent,
41 TuiEngine,
42};
43
44use crate::permissions::{PERMISSION_RESPOND_METHOD, PermissionDecision};
45
46use super::engine_state::EngineState;
47use super::error::EngineError;
48use super::splash::{SplashFacts, connect_line, splash_lines};
49use super::uds_rpc::UdsRpcClient;
50use super::workstream_subscription::run_workstream_subscription;
51
52/// How long [`CodeEngine::connect`] waits for the socket to accept a
53/// connection before reporting no daemon. Short and fixed: this runs once, at
54/// REPL startup, against a local inode.
55const DAEMON_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
56
57/// Fixed backoff between stream reconnect attempts. Not exponential — MVP
58/// scope (DOC-50 §5 Slice 3); a persistently-down daemon retries at a
59/// steady, human-visible cadence rather than hot-looping. Shared with
60/// `engine_state.rs` and `workstream_subscription.rs`.
61pub(super) const RECONNECT_BACKOFF: Duration = Duration::from_secs(2);
62
63/// How many times `EngineState::pump_session_events` reconnects before
64/// giving up and returning control to the caller (`handle_input` must
65/// eventually return so the REPL's input loop stays responsive — unlike the
66/// workstream-activation subscription, which is meant to run for the whole
67/// TUI session). Shared with `engine_state.rs`.
68pub(super) const SESSION_STREAM_MAX_RECONNECTS: u32 = 5;
69
70/// Whether `rest` (already trimmed) names the `/workstream`/`/ws`
71/// engine-routed command, and if so, what follows it (empty string if bare).
72///
73/// Why: kept pure (no `&self`) so slash-command recognition is unit
74/// testable without constructing an engine. Requires a word boundary after
75/// the command name (a bare `strip_prefix` would wrongly match
76/// `"/workstreamx"`).
77fn workstream_subcommand(line: &str) -> Option<&str> {
78 let trimmed = line.trim();
79 for prefix in ["/workstream", "/ws"] {
80 if trimmed == prefix {
81 return Some("");
82 }
83 if let Some(rest) = trimmed.strip_prefix(prefix)
84 && let Some(rest) = rest.strip_prefix(' ')
85 {
86 return Some(rest.trim());
87 }
88 }
89 None
90}
91
92/// The words for whether this session runs the solo agent or the delegating
93/// PM (#8184), shared by [`session_shape_summary`] and the connect line so
94/// the two can never disagree.
95///
96/// A missing or `false` `no_delegate` reads as the delegating PM, matching
97/// `Session::no_delegate`'s own `#[serde(default)]`.
98/// Test: `engine_tests::session_shape_summary_names_the_solo_agent_and_root`,
99/// `engine_tests::session_shape_summary_names_the_delegating_pm`.
100fn agent_label(session: &Value) -> &'static str {
101 if session
102 .get("no_delegate")
103 .and_then(Value::as_bool)
104 .unwrap_or(false)
105 {
106 "solo agent (no delegation)"
107 } else {
108 "delegating PM"
109 }
110}
111
112/// One line naming the agent shape and the working root of the session
113/// `session.create` just returned (#8184).
114///
115/// Why: the two facts that decide what a turn can actually do — whether the
116/// agent edits files itself or delegates, and WHERE its file tools are rooted — were
117/// invisible from the TUI, so a projectless session (which works in a
118/// throwaway scratch directory, never the launch directory) looked exactly
119/// like a bound one. Kept pure (no `&self`) so it is unit-testable without a
120/// daemon.
121/// What: reads `no_delegate` and `binding.root` off the returned `Session`.
122/// A missing/false `no_delegate` reads as the delegating PM, matching
123/// `Session::no_delegate`'s own `#[serde(default)]`.
124/// Test: `engine_tests::session_shape_summary_names_the_solo_agent_and_root`,
125/// `engine_tests::session_shape_summary_names_the_projectless_scratch_root`,
126/// `engine_tests::session_shape_summary_names_the_delegating_pm`.
127fn session_shape_summary(session: &Value) -> String {
128 let agent = agent_label(session);
129 match session
130 .get("binding")
131 .and_then(|b| b.get("root"))
132 .and_then(Value::as_str)
133 {
134 // #8184: "file tools rooted at", not "editing in" — `tools::fs` scopes
135 // its paths to this root, but `bash` only sets the child's working
136 // directory, so this states where the agent works, never a sandbox.
137 Some(root) => format!("{agent}, file tools rooted at {root}"),
138 None => format!("{agent}, projectless — file tools rooted at a scratch workspace"),
139 }
140}
141
142/// The `trusty_code_tui::TuiEngine` adapter for `tcode tui` — see module docs.
143pub struct CodeEngine {
144 state: Arc<EngineState>,
145}
146
147impl CodeEngine {
148 /// Build a `CodeEngine` dialling the daemon's well-known socket
149 /// ([`crate::serve::uds::socket_path`]).
150 ///
151 /// Why (#6637): this replaces `discover`, which raced a `TCODE_DAEMON_URL`
152 /// against an `http_addr` file and liveness-pinged whichever it found. The
153 /// socket path is derived from the data directory, so there is one answer
154 /// and nothing to choose between. `project_path` is forwarded to
155 /// `session.create` in `setup()` (mirrors `session::protocol::create`'s
156 /// `project` param — `None` is a fully valid, projectless session).
157 ///
158 /// # Errors
159 ///
160 /// [`EngineError::NoDaemon`] when nothing is answering on the socket. This
161 /// client does not start one — `tcode tui`'s auto-spawn owns that decision.
162 pub async fn connect(project_path: Option<PathBuf>) -> Result<Self, EngineError> {
163 let socket = crate::serve::uds::socket_path()
164 .map_err(|e| EngineError::Malformed(format!("resolve the daemon socket: {e:#}")))?;
165 if !trusty_common::uds::socket_is_serving(&socket, DAEMON_PROBE_TIMEOUT).await {
166 return Err(EngineError::NoDaemon { socket });
167 }
168 Ok(Self::with_socket(socket, project_path))
169 }
170
171 /// Build a `CodeEngine` dialling an explicit socket — the constructor
172 /// `tcode tui`'s auto-spawn path and every test in
173 /// `tests/tui_client_engine.rs` use.
174 ///
175 /// (#8184) The session this engine creates runs the SOLO agent — see
176 /// [`CodeEngine::with_socket_delegating`] for the PM opt-in.
177 pub fn with_socket(socket: impl Into<PathBuf>, project_path: Option<PathBuf>) -> Self {
178 Self::build(socket, project_path, false)
179 }
180
181 /// [`CodeEngine::with_socket`] for a session that runs the DELEGATING PM
182 /// — `tcode tui --delegate` (#8184).
183 ///
184 /// Why: the interactive default is the solo agent, so PM/delegation mode
185 /// needs one named surface to be asked for. A second constructor rather
186 /// than a third parameter: every other call site wants the default.
187 /// What: sends `session.create`'s `delegate: true` from `setup`.
188 /// Test: `tui_delegate_opt_in_creates_a_delegating_session` (in
189 /// `tests/tui_client_engine.rs`).
190 pub fn with_socket_delegating(
191 socket: impl Into<PathBuf>,
192 project_path: Option<PathBuf>,
193 ) -> Self {
194 Self::build(socket, project_path, true)
195 }
196
197 /// The shared body of both constructors above.
198 fn build(socket: impl Into<PathBuf>, project_path: Option<PathBuf>, delegate: bool) -> Self {
199 Self {
200 state: Arc::new(EngineState::new(
201 UdsRpcClient::new(socket),
202 project_path,
203 delegate,
204 )),
205 }
206 }
207
208 /// The socket this engine dials (test/debug convenience).
209 pub fn daemon_socket(&self) -> &std::path::Path {
210 self.state.rpc.socket()
211 }
212
213 /// Ask the daemon to cancel this session's run and report WHICH of the two
214 /// cancel outcomes came back (#8207).
215 ///
216 /// Why: the daemon answers a confirmed stop and an unconfirmed one with two
217 /// different things — a session snapshot and `-32010 cancel_unconfirmed` —
218 /// but [`TuiEngine::cancel_session`] returns `anyhow::Result<()>`, which
219 /// flattens the second into an opaque error string. That made the domain code
220 /// unreadable from the only client that reaches it, which is what the code was
221 /// minted to prevent. This is the typed half; the trait method below adapts it
222 /// to the signature `trusty-code-tui` owns, and the TUI's own
223 /// "still cancelling…" render is a separate change in that crate.
224 /// What: `-32010` becomes [`CancelOutcome::StillCancelling`] carrying the
225 /// daemon's own sentence. Every other RPC or transport failure stays an error,
226 /// and no session at all is [`CancelOutcome::NoSession`] — there was nothing
227 /// to stop.
228 ///
229 /// # Errors
230 ///
231 /// [`EngineError::Rpc`] for any daemon refusal other than `-32010`, and
232 /// [`EngineError::Transport`] for a socket failure.
233 /// Test: `engine_tests::cancel_unconfirmed_is_a_still_cancelling_outcome`,
234 /// `engine_tests::any_other_refusal_stays_an_error`.
235 pub async fn cancel_session_outcome(&self) -> Result<CancelOutcome, EngineError> {
236 let session_id = {
237 self.state
238 .session_id
239 .lock()
240 .unwrap_or_else(|e| e.into_inner())
241 .clone()
242 };
243 let Some(session_id) = session_id else {
244 return Ok(CancelOutcome::NoSession);
245 };
246 // Thin-client axiom (DOC-39 §2.1 C-2): the daemon performs the real
247 // cancellation via `session.cancel` — this call is not optional
248 // client-side render-stop.
249 match self
250 .state
251 .rpc
252 .call("session.cancel", json!({ "session_id": session_id }))
253 .await
254 {
255 Ok(_) => Ok(CancelOutcome::Stopped),
256 Err(err) => Ok(classify_cancel_error(err)?),
257 }
258 }
259}
260
261/// What a `session.cancel` achieved (#8207).
262///
263/// Why: "the run stopped" and "the run has not stopped yet" are both successful
264/// answers to the question the cancel asked, and the TUI has to render them
265/// differently — one ends the turn, the other keeps a cancelling state on screen.
266/// Collapsing the second into an error is what made `-32010` unreadable.
267/// Test: `engine_tests::cancel_unconfirmed_is_a_still_cancelling_outcome`.
268#[derive(Debug, PartialEq, Eq)]
269pub enum CancelOutcome {
270 /// The daemon confirmed the run has terminated.
271 Stopped,
272 /// The cancel was accepted; the run had not stopped within the daemon's
273 /// grace. `detail` is the daemon's own sentence, safe to show verbatim.
274 StillCancelling {
275 /// The daemon's account of what it is still waiting on.
276 detail: String,
277 },
278 /// `setup` has not minted a session yet, so there was nothing to cancel.
279 NoSession,
280}
281
282/// The JSON-RPC error code `RpcError::cancel_unconfirmed` carries (#8207) — the
283/// daemon-side constant lives in `crate::jsonrpc::error`, which does not export
284/// it as a named code.
285const CODE_CANCEL_UNCONFIRMED: i32 = -32010;
286
287/// Split a failed `session.cancel` into "still cancelling" and a real failure
288/// (#8207).
289///
290/// Why: exactly one code is not a failure, and keeping the test for it in one
291/// named function is what lets a unit test assert the split without a daemon.
292/// Test: `engine_tests::cancel_unconfirmed_is_a_still_cancelling_outcome`,
293/// `engine_tests::any_other_refusal_stays_an_error`.
294fn classify_cancel_error(err: EngineError) -> Result<CancelOutcome, EngineError> {
295 match err {
296 EngineError::Rpc { code, message, .. } if code == CODE_CANCEL_UNCONFIRMED => {
297 Ok(CancelOutcome::StillCancelling { detail: message })
298 }
299 other => Err(other),
300 }
301}
302
303/// Project a `session.cancel` result onto the TUI's [`CancelReply`] (#8207).
304///
305/// Why: this is where the wire vocabulary has to stop. [`CancelReply`]'s
306/// payloads are rendered to the user verbatim, and [`EngineError::Rpc`]'s own
307/// `Display` embeds the JSON-RPC code — the `daemon returned an error (-32003)`
308/// shape #8207 was filed about. A refusal is therefore reduced to the daemon's
309/// `message` HERE, where the code is still a separate field, rather than
310/// anywhere downstream where only a flattened string survives. Split out of
311/// [`TuiEngine::cancel_session_reply`] so all three arms are testable without a
312/// daemon socket, the same reason [`classify_cancel_error`] is its own function.
313/// What: [`CancelOutcome::NoSession`] reports `Stopped` — `setup` never minted a
314/// session, so nothing is running and input should reopen. A transport failure
315/// carries no code and is reported as written.
316/// Test: `engine_tests::cancel_reply_reports_a_confirmed_stop`,
317/// `engine_tests::cancel_reply_keeps_an_unconfirmed_cancel_distinct`,
318/// `engine_tests::cancel_reply_strips_the_rpc_code_from_a_refusal`.
319fn cancel_reply_from(outcome: Result<CancelOutcome, EngineError>) -> CancelReply {
320 match outcome {
321 Ok(CancelOutcome::Stopped | CancelOutcome::NoSession) => CancelReply::Stopped,
322 Ok(CancelOutcome::StillCancelling { detail }) => CancelReply::StillCancelling { detail },
323 Err(EngineError::Rpc { message, .. }) => CancelReply::Failed { error: message },
324 Err(other) => CancelReply::Failed {
325 error: other.to_string(),
326 },
327 }
328}
329
330#[async_trait::async_trait]
331impl TuiEngine for CodeEngine {
332 async fn handle_input(
333 &self,
334 line: String,
335 tx: UnboundedSender<ReplEvent>,
336 ) -> anyhow::Result<bool> {
337 if let Some(rest) = workstream_subcommand(&line) {
338 self.state.handle_workstream_command(rest, &tx).await?;
339 return Ok(true);
340 }
341 self.state.run_chat_turn(line.trim(), &tx).await?;
342 Ok(true)
343 }
344
345 async fn setup(&self, tx: UnboundedSender<ReplEvent>) -> anyhow::Result<()> {
346 let result = self
347 .state
348 .rpc
349 .call(
350 "session.create",
351 json!({
352 "task": "tcode tui session",
353 "project": self.state.project_path,
354 // #8184: an interactive session runs the solo agent —
355 // `false` here IS `session.create`'s own default, sent
356 // explicitly so this client's shape never depends on a
357 // daemon-side default drifting. `--delegate` flips it.
358 "delegate": self.state.delegate,
359 }),
360 )
361 .await?;
362 let session_id = result
363 .get("id")
364 .and_then(Value::as_str)
365 .ok_or_else(|| EngineError::Malformed("session.create: response missing `id`".into()))?
366 .to_string();
367 *self
368 .state
369 .session_id
370 .lock()
371 .unwrap_or_else(|e| e.into_inner()) = Some(session_id.clone());
372
373 // #8184: the daemon only prompts while someone is watching this
374 // session; claim that BEFORE any run can issue a gated tool call.
375 super::prompter_claim::hold_prompter_claim(self.state.clone(), session_id.clone()).await?;
376
377 // `TuiEngine::commands()` cache — see `EngineState`'s struct docs.
378 // The one engine-routed command this MVP supports.
379 *self
380 .state
381 .commands_cache
382 .lock()
383 .unwrap_or_else(|e| e.into_inner()) = vec![CommandDescriptor {
384 name: "workstream".to_string(),
385 summary: "List or activate the daemon's workstreams".to_string(),
386 routing: CommandRouting::Engine,
387 args_hint: Some("[list | activate <id>]".to_string()),
388 }];
389
390 if let Some(ws) = self.state.refresh_workstream_cache().await {
391 let _ = tx.send(ReplEvent::WorkstreamUpdated(ws));
392 // Populate the status line's Workstream segment on first render
393 // (DOC-50 §5.3, Slice 6) — without this, the TUI would show a
394 // blank statusline until the background SSE subscription (which
395 // only starts after `setup` returns, see `run.rs::run`) happens
396 // to observe an activation change.
397 let _ = tx.send(ReplEvent::StatuslineUpdate(
398 self.state.statusline_segments(),
399 ));
400 }
401
402 let shape = session_shape_summary(&result);
403
404 // #8164: the launch facts, as a splash that REPLACES the banner's
405 // generic identity row. `health` is best-effort — a daemon that
406 // cannot answer it still ran `session.create`, so a splash missing
407 // the daemon's build beats no splash at all.
408 let daemon = self.state.rpc.call("health", json!({})).await.ok();
409 let workstream = self
410 .state
411 .active_workstream
412 .lock()
413 .unwrap_or_else(|e| e.into_inner())
414 .as_ref()
415 .map(|ws| format!("{} ({})", ws.name, ws.id));
416 let project = self
417 .state
418 .project_path
419 .as_ref()
420 .map(|p| p.display().to_string());
421 let _ = tx.send(ReplEvent::SplashUpdated(splash_lines(&SplashFacts {
422 client_version: crate::build_info::LONG_VERSION,
423 client_build: crate::build_info::GIT_HASH,
424 daemon_version: daemon.as_ref().and_then(|d| d["version"].as_str()),
425 daemon_build: daemon.as_ref().and_then(|d| d["build"].as_str()),
426 socket: self.state.rpc.socket(),
427 project: project.as_deref(),
428 workstream: workstream.as_deref(),
429 shape: &shape,
430 })));
431
432 // #8164: one scrollback line naming the home directory the session
433 // actually got (the DAEMON's binding, not this client's request), the
434 // workstream, and the agent shape — and no session id (owner rule).
435 let _ = tx.send(ReplEvent::StatusMessage(connect_line(
436 self.state.rpc.socket(),
437 result
438 .get("binding")
439 .and_then(|b| b.get("root"))
440 .and_then(Value::as_str),
441 workstream.as_deref(),
442 agent_label(&result),
443 )));
444 Ok(())
445 }
446
447 /// #8207: the trait's `Result<()>` cannot carry the two-way outcome, so this
448 /// adapts [`CodeEngine::cancel_session_outcome`] to it. An unconfirmed cancel
449 /// stays an error — a cancel that did not land must not read as one that did —
450 /// but with the daemon's plain sentence rather than an opaque `-32010` dump.
451 /// The TUI reaches [`Self::cancel_session_reply`] instead, which keeps the
452 /// distinction; this one-state form remains for a caller that only needs to
453 /// know whether the request was delivered.
454 async fn cancel_session(&self) -> anyhow::Result<()> {
455 match self.cancel_session_outcome().await? {
456 CancelOutcome::Stopped | CancelOutcome::NoSession => Ok(()),
457 CancelOutcome::StillCancelling { detail } => {
458 Err(anyhow::anyhow!("still cancelling: {detail}"))
459 }
460 }
461 }
462
463 /// #8207: project [`CodeEngine::cancel_session_outcome`] onto the TUI's own
464 /// [`CancelReply`], which is the shape the TUI can render as three distinct
465 /// states instead of "cancelled or not".
466 ///
467 /// Why: this is the crate boundary where the wire vocabulary has to stop.
468 /// [`CancelReply`]'s payloads are shown to the user verbatim, and
469 /// [`EngineError::Rpc`]'s own `Display` embeds the JSON-RPC code — which is
470 /// exactly the `daemon returned an error (-32003)` shape #8207 was filed
471 /// about. So a refusal is reduced to the daemon's `message` here, where the
472 /// code is still a separate field, rather than anywhere downstream where
473 /// only a flattened string survives.
474 /// What: the projection itself is [`cancel_reply_from`], so every arm is
475 /// unit-testable without a daemon socket.
476 /// Test: `engine_tests::cancel_reply_reports_a_confirmed_stop`,
477 /// `engine_tests::cancel_reply_keeps_an_unconfirmed_cancel_distinct`,
478 /// `engine_tests::cancel_reply_strips_the_rpc_code_from_a_refusal`.
479 async fn cancel_session_reply(&self) -> CancelReply {
480 cancel_reply_from(self.cancel_session_outcome().await)
481 }
482
483 /// Answer one suspended permission request over
484 /// `session.permission.respond` (#3422).
485 ///
486 /// Why: an `ask` rule parks the tool call inside the daemon's gate
487 /// (`crate::permissions::gate`), and only the daemon's broker can release
488 /// it — same thin-client reasoning as `cancel_session` above (DOC-39
489 /// §2.1 C-2, ADR-0063). The TUI decided nothing; it named a button.
490 /// What: translates the shared crate's [`PermissionAnswer`] into this
491 /// daemon's own [`PermissionDecision`] and sends its wire word, so the
492 /// vocabulary has exactly one definition
493 /// (`crate::permissions::protocol`). With no session yet (`setup` has
494 /// not run) there is no request to answer, so this is a no-op rather
495 /// than an error.
496 ///
497 /// # Errors
498 ///
499 /// Propagates the RPC failure, including the daemon's `-32602` for a
500 /// `request_id` nobody is waiting on — an answer that did not land must
501 /// not read as one that did.
502 /// Test: `respond_permission_releases_a_suspended_call`,
503 /// `respond_permission_without_a_session_is_a_noop` (both in
504 /// `tests/tui_client_engine.rs`).
505 async fn respond_permission(
506 &self,
507 request_id: String,
508 answer: PermissionAnswer,
509 ) -> anyhow::Result<()> {
510 let session_id = {
511 self.state
512 .session_id
513 .lock()
514 .unwrap_or_else(|e| e.into_inner())
515 .clone()
516 };
517 let Some(session_id) = session_id else {
518 return Ok(());
519 };
520 let (decision, pattern) = match answer {
521 PermissionAnswer::AllowOnce => (PermissionDecision::AllowOnce, None),
522 PermissionAnswer::AllowForSession { pattern } => (
523 PermissionDecision::AllowForSession {
524 pattern: pattern.clone(),
525 },
526 pattern,
527 ),
528 PermissionAnswer::Deny => (PermissionDecision::Deny, None),
529 };
530 self.state
531 .rpc
532 .call(
533 PERMISSION_RESPOND_METHOD,
534 json!({
535 "session_id": session_id,
536 "request_id": request_id,
537 "decision": decision.as_str(),
538 "pattern": pattern,
539 }),
540 )
541 .await?;
542 Ok(())
543 }
544
545 async fn subscribe_workstream_events(
546 &self,
547 tx: UnboundedSender<ReplEvent>,
548 ) -> anyhow::Result<()> {
549 let current_id = {
550 self.state
551 .active_workstream
552 .lock()
553 .unwrap_or_else(|e| e.into_inner())
554 .clone()
555 }
556 .map(|ws| ws.id);
557 // No workstream is known yet: DOC-48 §5.3's SSE fan-out is scoped
558 // PER workstream id (there is no daemon-wide "tell me about any
559 // future activation" feed), so there is genuinely nothing to
560 // subscribe to until at least one workstream id is known. See this
561 // crate's PR description for this as a reported daemon-API gap
562 // rather than a client-side workaround — matches the default no-op
563 // `TuiEngine::subscribe_workstream_events` contract for engines with
564 // no push transport available right now.
565 let Some(current_id) = current_id else {
566 return Ok(());
567 };
568 tokio::spawn(run_workstream_subscription(
569 self.state.clone(),
570 current_id,
571 tx,
572 ));
573 Ok(())
574 }
575
576 async fn shutdown(&self) -> anyhow::Result<()> {
577 self.state.shutting_down.store(true, Ordering::SeqCst);
578 Ok(())
579 }
580
581 /// Engine-routed slash commands this MVP supports — served from the
582 /// cache `setup()` populates (`EngineState::commands_cache`). This is a
583 /// SYNCHRONOUS trait method (#3428) — the cache exists precisely so
584 /// this never needs to perform network I/O on the calling path; see
585 /// `EngineState::commands`'s docs for the `std::sync::Mutex` rationale.
586 fn commands(&self) -> Vec<CommandDescriptor> {
587 self.state.commands()
588 }
589
590 /// The `"workstream"` picker — served from the cache
591 /// `EngineState::refresh_workstream_cache` populates (in `setup()`,
592 /// after `/workstream activate`, and on every observed
593 /// `WorkstreamActivationChanged`). `None` for any other picker name
594 /// (this engine has exactly one) or before the cache has been
595 /// populated at least once. `dispatch_command` is `"/workstream
596 /// activate"` — matching `workstream_subcommand`'s parsing exactly, so
597 /// the shared event loop's `"{dispatch_command} {selected.id}"`
598 /// resubmission (`"/workstream activate <id>"`) round-trips through
599 /// `handle_input` correctly.
600 fn picker(&self, name: &str) -> Option<PickerRequest> {
601 if name != "workstream" {
602 return None;
603 }
604 let items = self.state.picker_items("workstream")?;
605 Some(PickerRequest {
606 title: "Workstreams".to_string(),
607 items,
608 dispatch_command: "/workstream activate".to_string(),
609 })
610 }
611}
612
613#[cfg(test)]
614#[path = "engine_tests.rs"]
615mod engine_tests;