harness/harness.rs
1//! The neutral harness contract: the [`Harness`] trait, the run-control
2//! handle, the neutral request/metadata types, and the shared
3//! interactive-login helper.
4//!
5//! A *harness* is whatever actually answers the user's prompt — a CLI
6//! agent (bob / Claude Code / Codex today), a direct LLM API tomorrow,
7//! some other runner after that. A consumer only needs to: probe whether
8//! a harness is ready, run a one-time install if required, stream a run,
9//! and know which credential to ask for. This module is that seam.
10//!
11//! ## Design rules
12//!
13//! - **Object-safe trait.** Consumers hold `Box<dyn Harness>`; no
14//! generics leak across the seam.
15//! - **Arc callbacks, not generic closures.** Streaming methods take
16//! `Arc<dyn Fn(..) + Send + Sync>` so they stay object-safe and can be
17//! cloned onto the reader threads the subprocess engine uses.
18//! - **Normalize at the adapter, not the UI.** The event enums in
19//! [`crate::events`] are harness-neutral by intent; each adapter
20//! translates its CLI's wire format into them so the front-end consumes
21//! one shape regardless of which harness produced it.
22
23use std::path::PathBuf;
24use std::sync::{mpsc, Arc, Condvar, Mutex};
25
26use serde::{Deserialize, Serialize};
27
28use crate::events::RunEvent;
29use cli_stream::{spawn_streaming, InstallEvent, ProcessEvent, ProcessHandle};
30
31// --- Streaming callbacks --------------------------------------------
32
33/// Callback a harness invokes for each run event. `Arc<dyn Fn>` is
34/// `Clone + Send + Sync`, so it can be handed to the multiple reader
35/// threads a process-backed harness uses without the trait method
36/// needing to be generic.
37pub type RunCallback = Arc<dyn Fn(RunEvent) + Send + Sync>;
38
39/// Callback a harness invokes for each install event.
40pub type InstallCallback = Arc<dyn Fn(InstallEvent) + Send + Sync>;
41
42// --- Errors ---------------------------------------------------------
43
44/// A boxed, type-erased error source. The [`HarnessError`] variants carry one
45/// of these instead of `#[from]`-ing a single concrete type, because each
46/// *category* can be produced by more than one underlying error: a `Spawn`
47/// failure is a [`cli_stream::StreamError`] for the claude/codex adapters but a
48/// `bob_rs::BobError` for bob. The real error stays reachable through
49/// [`std::error::Error::source`] (and `downcast_ref`); the category is the
50/// variant.
51pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
52
53/// Why a [`Harness`] operation failed. Returned by `install` / `run` /
54/// `login` / [`RunControl::cancel`] so a consumer can branch on the *kind* of
55/// failure — offer install vs sign-in vs surface the message — instead of
56/// string-matching.
57///
58/// Each category carries the real underlying error as a [`source`] (via the
59/// [`BoxError`] field), so a consumer that wants more than the category can
60/// walk `.source()` or `downcast_ref::<cli_stream::StreamError>()` /
61/// `::<bob_rs::BobError>()`. The `Display` still flattens the source into the
62/// message (`"failed to start the agent: <source>"`), so a consumer that just
63/// stringifies at a boundary (e.g. a Tauri command's `.to_string()`) gets the
64/// same full message as before. `#[non_exhaustive]` so adding a variant later
65/// isn't a breaking change.
66///
67/// ```
68/// use harness::{HarnessError, StreamError};
69/// use std::error::Error;
70///
71/// // Box any typed source under a category constructor:
72/// let err = HarnessError::spawn(StreamError::PipeNotCaptured { stream: "stdout" });
73///
74/// // Stringifying at a boundary flattens the source into the message
75/// // (so a Tauri command's `.to_string()` keeps its full text)…
76/// assert!(err.to_string().starts_with("failed to start the agent: "));
77///
78/// // …while the real typed cause stays reachable for a consumer that wants
79/// // to branch on it rather than parse a string.
80/// let source = err.source().expect("Spawn carries a source");
81/// assert!(source.downcast_ref::<StreamError>().is_some());
82/// ```
83///
84/// [`source`]: std::error::Error::source
85#[derive(Debug, thiserror::Error)]
86#[non_exhaustive]
87pub enum HarnessError {
88 /// The harness's CLI couldn't be started — not installed, not on `PATH`,
89 /// or an OS-level spawn failure.
90 #[error("failed to start the agent: {0}")]
91 Spawn(#[source] BoxError),
92 /// A one-time install step failed.
93 #[error("install failed: {0}")]
94 Install(#[source] BoxError),
95 /// Interactive sign-in failed.
96 #[error("sign-in failed: {0}")]
97 Login(#[source] BoxError),
98 /// Cancelling an in-flight run failed.
99 #[error("cancel failed: {0}")]
100 Cancel(#[source] BoxError),
101 /// Any other adapter/runtime failure (e.g. a backend SDK error that
102 /// doesn't map onto the cases above). Carries a message rather than a
103 /// source — it's the catch-all when there's nothing typed to preserve.
104 #[error("{0}")]
105 Other(String),
106}
107
108impl HarnessError {
109 /// Categorize a source error as a [`Spawn`](HarnessError::Spawn) failure.
110 /// Accepts anything boxable — a typed `StreamError`/`BobError`, or a
111 /// `String`/`&str` for adapters with nothing typed to carry.
112 pub fn spawn(source: impl Into<BoxError>) -> Self {
113 Self::Spawn(source.into())
114 }
115 /// Categorize a source error as an [`Install`](HarnessError::Install) failure.
116 pub fn install(source: impl Into<BoxError>) -> Self {
117 Self::Install(source.into())
118 }
119 /// Categorize a source error as a [`Login`](HarnessError::Login) failure.
120 pub fn login(source: impl Into<BoxError>) -> Self {
121 Self::Login(source.into())
122 }
123 /// Categorize a source error as a [`Cancel`](HarnessError::Cancel) failure.
124 pub fn cancel(source: impl Into<BoxError>) -> Self {
125 Self::Cancel(source.into())
126 }
127}
128
129// --- Run control (cancellation) -------------------------------------
130
131/// Object-safe handle to an in-flight run. A process-backed harness
132/// cancels by signalling its child; a request-backed harness (a hosted
133/// LLM API) cancels by aborting its HTTP stream. The consumer only needs
134/// these two operations, so the concrete mechanism stays behind the trait.
135pub trait RunControl: Send + Sync {
136 /// Stop the run. Best-effort; idempotent.
137 fn cancel(&self) -> Result<(), HarnessError>;
138 /// Whether [`cancel`](RunControl::cancel) was called.
139 fn was_cancelled(&self) -> bool;
140}
141
142/// Boxed [`RunControl`] returned by [`Harness::run`].
143pub type RunHandle = Box<dyn RunControl>;
144
145// The engine's run handle is the canonical process-backed `RunControl`.
146// Both the trait and the handle live in this crate, so this impl is here
147// (orphan rule) rather than in any adapter crate.
148impl RunControl for ProcessHandle {
149 fn cancel(&self) -> Result<(), HarnessError> {
150 ProcessHandle::cancel(self).map_err(HarnessError::cancel)
151 }
152 fn was_cancelled(&self) -> bool {
153 ProcessHandle::was_cancelled(self)
154 }
155}
156
157// --- Neutral request / metadata shapes ------------------------------
158
159/// What the user wants the harness to do with the prompt. Mirrors
160/// the Ask / Edit split the comment bubble already exposes; adapters
161/// map it onto their own mode vocabulary.
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
163#[serde(rename_all = "snake_case")]
164pub enum RunMode {
165 /// Answer / discuss. No file edits expected.
166 Ask,
167 /// Propose edits to the workspace.
168 Edit,
169}
170
171/// How hard the model should think, in harness-neutral terms. Codex
172/// maps this onto `model_reasoning_effort`; Claude Code has no
173/// equivalent `-p` flag today and ignores it. Kept neutral so a future
174/// harness that exposes effort can honor the same field.
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
176#[serde(rename_all = "snake_case")]
177pub enum ReasoningEffort {
178 Minimal,
179 Low,
180 Medium,
181 High,
182}
183
184impl ReasoningEffort {
185 /// The CLI/config token for this level (e.g. codex's
186 /// `model_reasoning_effort="high"`).
187 pub fn as_cli_value(self) -> &'static str {
188 match self {
189 ReasoningEffort::Minimal => "minimal",
190 ReasoningEffort::Low => "low",
191 ReasoningEffort::Medium => "medium",
192 ReasoningEffort::High => "high",
193 }
194 }
195}
196
197/// User-chosen, harness-neutral run-shaping knobs. Every field is
198/// optional; each adapter maps the ones its CLI supports and ignores
199/// the rest (Claude has no reasoning-effort flag; Codex has no
200/// max-turns flag). Grouped into one struct so the neutral
201/// [`RunRequest`] stays open for extension — a new knob is a field
202/// here, not a new positional parameter threaded through every caller.
203#[derive(Debug, Clone, Default)]
204pub struct RunTuning {
205 /// Model id or alias passed verbatim to the CLI (`--model` /
206 /// `-m`). `None` → let the CLI use its configured default.
207 pub model: Option<String>,
208 /// Reasoning effort (Codex: `-c model_reasoning_effort`).
209 pub effort: Option<ReasoningEffort>,
210 /// Cap on agentic turns (Claude: `--max-turns`).
211 pub max_turns: Option<u32>,
212 /// Raw CLI args the host appends verbatim **after** the adapter's own,
213 /// so a host can add a flag (`--settings`, `--add-dir`) or override one
214 /// it already sets — for CLIs where a repeated flag is last-wins (e.g.
215 /// Claude Code / commander) — without editing the adapter. The host opts
216 /// into CLI-specific flag names when it uses this; keep cross-harness
217 /// knobs as their own typed fields above. Default empty.
218 pub extra_args: Vec<String>,
219}
220
221/// A harness-neutral run request. Adapter-specific knobs (bob's
222/// approval mode, coin budget, executable override) are filled in by
223/// the adapter from its own defaults; the user-facing tuning the
224/// picker exposes (model, effort, turn cap) rides on `tuning`.
225#[derive(Debug, Clone)]
226pub struct RunRequest {
227 /// Caller-chosen id used to correlate events with the handle.
228 pub run_id: String,
229 pub prompt: String,
230 /// Working directory for the run — the workspace path, so the
231 /// harness's tool calls land inside the user's vault.
232 pub cwd: Option<PathBuf>,
233 pub mode: RunMode,
234 /// Optional, harness-neutral run-shaping knobs (model, effort,
235 /// turn cap). Adapters honor the subset their CLI supports.
236 pub tuning: RunTuning,
237}
238
239/// Where a harness's secret lives in the OS keychain, and how to
240/// label it in the UI. Lets the front-end ask for the right
241/// credential per harness without hard-coding any one harness's slot.
242#[derive(Debug, Clone, Serialize)]
243#[serde(rename_all = "camelCase")]
244pub struct CredentialSpec {
245 /// Human label, e.g. "Bob API key" / "Anthropic API key".
246 pub label: String,
247 pub keychain_service: String,
248 pub keychain_account: String,
249 /// Whether the harness can run at all without this credential.
250 pub required: bool,
251}
252
253/// Harness-neutral readiness snapshot for the UI. `details` carries
254/// adapter-specific probes (bob's Node/npm) as free-form JSON so the
255/// trait stays generic.
256#[derive(Debug, Clone, Serialize)]
257#[serde(rename_all = "camelCase")]
258pub struct HarnessReadiness {
259 pub harness_id: String,
260 /// Installed *and* authenticated *and* able to run.
261 pub ready: bool,
262 pub installed: bool,
263 pub version: Option<String>,
264 pub auth_configured: bool,
265 pub error: Option<String>,
266 /// Adapter-specific extra fields (serialized harness snapshot).
267 pub details: serde_json::Value,
268}
269
270/// A model the harness can be pointed at, for the picker's model
271/// selector. `value` is passed verbatim to the CLI (`--model` / `-m`)
272/// via [`RunTuning::model`]; `label` is the human-facing name.
273#[derive(Debug, Clone, Serialize)]
274#[serde(rename_all = "camelCase")]
275pub struct HarnessModel {
276 pub value: String,
277 pub label: String,
278}
279
280/// What a harness supports, so every consumer (the picker, the options
281/// panel, the credential preflight, the chat availability gate) adapts
282/// to it *declaratively* instead of branching on the harness id. A new
283/// adapter that, say, needs a stored key just sets `credential_required:
284/// true` here — no `id == "bob"` checks to hunt down.
285#[derive(Debug, Clone, Serialize)]
286#[serde(rename_all = "camelCase")]
287pub struct HarnessCapabilities {
288 /// Compose stores this harness's credential (bob). When `false`,
289 /// the CLI owns its own login (claude/codex) and Compose runs no
290 /// credential/install preflight — a missing login surfaces as the
291 /// harness's own run error rather than a Compose prompt.
292 pub credential_required: bool,
293 /// Emits previewable suggested edits the user approves before they
294 /// apply (bob). When `false`, edits land on disk directly and the
295 /// file watcher reflects them (claude/codex).
296 pub previews_edits: bool,
297 /// Curated model choices for the picker's selector. Empty → no
298 /// curated list (rely on `allows_custom_model`).
299 pub models: Vec<HarnessModel>,
300 /// Whether a free-text model id is accepted beyond `models` (codex,
301 /// whose model names change frequently). Drives a text field vs a
302 /// fixed dropdown in the picker.
303 pub allows_custom_model: bool,
304 /// Honors [`RunTuning::effort`] (codex reasoning effort).
305 pub supports_effort: bool,
306 /// Honors [`RunTuning::max_turns`] (claude turn cap).
307 pub supports_max_turns: bool,
308 /// Supports an interactive [`Harness::login`] flow (the CLI's own
309 /// OAuth, e.g. `claude auth login` / `codex login`). Drives the
310 /// picker's "Sign in" affordance when installed-but-not-signed-in.
311 /// `false` for harnesses Compose authenticates itself (bob).
312 pub supports_login: bool,
313}
314
315/// Static metadata for the harness picker.
316#[derive(Debug, Clone, Serialize)]
317#[serde(rename_all = "camelCase")]
318pub struct HarnessInfo {
319 pub id: String,
320 pub display_name: String,
321 pub description: String,
322 /// True if the harness needs a one-time [`Harness::install`].
323 pub requires_install: bool,
324 /// Declarative capabilities — what the harness supports, so the UI
325 /// and run-gating never special-case its id.
326 pub capabilities: HarnessCapabilities,
327}
328
329// --- The trait ------------------------------------------------------
330
331/// A pluggable agent backend. Implementors are cheap to construct
332/// (they hold config, not connections) so a registry can hand out
333/// fresh boxes on demand.
334pub trait Harness: Send + Sync {
335 /// Static metadata for the UI.
336 fn info(&self) -> HarnessInfo;
337
338 /// Probe availability / version / auth. May shell out; callers
339 /// should treat it as blocking and run it off the UI thread.
340 fn readiness(&self) -> HarnessReadiness;
341
342 /// Stream a one-time install. Harnesses that need no install
343 /// (e.g. a hosted-API adapter) return `Ok(())` immediately.
344 fn install(&self, on_event: InstallCallback) -> Result<(), HarnessError>;
345
346 /// Start a run, streaming events through `on_event`. Returns a
347 /// handle immediately; work continues on background threads.
348 fn run(&self, request: RunRequest, on_event: RunCallback) -> Result<RunHandle, HarnessError>;
349
350 /// The credential this harness needs.
351 fn credential(&self) -> CredentialSpec;
352
353 /// Trigger the harness's own interactive sign-in (its CLI's OAuth),
354 /// streaming progress as [`InstallEvent`]s — the same subprocess
355 /// stream shape as [`install`](Harness::install). The flow opens the
356 /// user's browser; this blocks until the login process exits, then
357 /// `Done { ok }` reports success. Default: unsupported — harnesses
358 /// that Compose authenticates itself (bob, via its API key) keep it.
359 fn login(&self, _on_event: InstallCallback) -> Result<(), HarnessError> {
360 Err(HarnessError::login(
361 "This harness does not support interactive sign-in.",
362 ))
363 }
364
365 /// Convenience over [`run`](Harness::run) for callers that want to
366 /// *pull* events off a channel instead of supplying a push callback.
367 /// Forwards each [`RunEvent`] into an `mpsc` channel and hands the
368 /// receiver back alongside the run handle, so the caller can simply
369 /// `for event in rx { … }` rather than re-write the
370 /// `Arc::new(move |ev| tx.send(ev))` plumbing at every call site.
371 ///
372 /// The receiver hangs up when the run ends — and on its own, without
373 /// the caller dropping the [`RunHandle`] first. The forwarding callback
374 /// (and the `Sender` it owns) lives only on the engine's reader
375 /// threads; once the process exits and those threads finish, every
376 /// clone of the callback drops, the `Sender` drops, and the `for` loop
377 /// over `rx` terminates. (Dropping the handle never cancels a run — see
378 /// [`RunControl`] — so it is safe to drain `rx` to completion while
379 /// still holding the handle for a possible [`cancel`](RunControl::cancel).)
380 ///
381 /// Prefer [`run`](Harness::run) directly when you need push semantics —
382 /// e.g. forwarding straight onto a Tauri `Channel` or an SSE sink from
383 /// inside the callback — where an intermediate channel is just an extra
384 /// hop. This is a provided method (not overridable surface): adapters
385 /// implement only `run`, and every harness — built-in or third-party —
386 /// gets `run_channel` for free.
387 ///
388 /// ```no_run
389 /// use harness::{Claude, Harness, RunEvent, RunMode, RunRequest, RunTuning};
390 ///
391 /// # fn main() -> Result<(), harness::HarnessError> {
392 /// let (_handle, rx) = Claude::new().run_channel(RunRequest {
393 /// run_id: "demo".into(),
394 /// prompt: "Explain Markdown headings in one sentence.".into(),
395 /// cwd: None,
396 /// mode: RunMode::Ask,
397 /// tuning: RunTuning::default(),
398 /// })?;
399 /// for event in rx {
400 /// match event {
401 /// RunEvent::Text { delta, .. } => print!("{delta}"),
402 /// RunEvent::Exited { .. } => break,
403 /// _ => {}
404 /// }
405 /// }
406 /// # Ok(())
407 /// # }
408 /// ```
409 fn run_channel(
410 &self,
411 request: RunRequest,
412 ) -> Result<(RunHandle, mpsc::Receiver<RunEvent>), HarnessError> {
413 let (tx, rx) = mpsc::channel();
414 let handle = self.run(
415 request,
416 Arc::new(move |event| {
417 // A hung-up receiver (consumer stopped early) is not an
418 // error: the run keeps streaming; we just drop the event
419 // nobody is waiting for.
420 let _ = tx.send(event);
421 }),
422 )?;
423 Ok((handle, rx))
424 }
425}
426
427/// Run a harness's interactive sign-in command, streaming its output as
428/// [`InstallEvent`]s and blocking until it exits. Reuses
429/// [`spawn_streaming`] (PATH augmentation + reader threads, so a packaged
430/// `.app` finds the CLI), mapping its process events onto the
431/// install-stream shape (Step / Stdout / Stderr / Done). The login CLI
432/// opens the user's browser for OAuth; we surface its output (incl. any
433/// device-code URL) so the UI can show progress. Blocks on a condvar
434/// until the process exits — the caller is a Tauri `(async)` command on
435/// a worker thread, so the UI never blocks.
436pub fn run_login_command(
437 program: &str,
438 args: &[&str],
439 on_event: InstallCallback,
440) -> Result<(), HarnessError> {
441 (*on_event)(InstallEvent::Step {
442 text: "Opening your browser to sign in…".to_owned(),
443 });
444 let done = Arc::new((Mutex::new(false), Condvar::new()));
445 let done_cb = Arc::clone(&done);
446 let events_cb = Arc::clone(&on_event);
447 // Bound, not `_`, so the handle outlives the wait (dropping it could
448 // signal the child); by the time we return, the process has exited.
449 let _handle = spawn_streaming(
450 PathBuf::from(program),
451 args.iter().map(|s| (*s).to_owned()).collect(),
452 Vec::new(),
453 std::env::current_dir().unwrap_or_default(),
454 format!("login-{program}"),
455 move |event| match event {
456 ProcessEvent::Started { .. } => {}
457 ProcessEvent::Stdout { line, .. } => {
458 (*events_cb)(InstallEvent::Stdout { text: line });
459 }
460 ProcessEvent::Stderr { line, .. } => {
461 (*events_cb)(InstallEvent::Stderr { text: line });
462 }
463 ProcessEvent::Error { message, .. } => {
464 (*events_cb)(InstallEvent::Stderr { text: message });
465 }
466 ProcessEvent::Exited { exit_code, .. } => {
467 (*events_cb)(InstallEvent::Done {
468 exit_code,
469 ok: exit_code == Some(0),
470 });
471 let (lock, cvar) = &*done_cb;
472 // Recover from a poisoned lock instead of panicking on a
473 // reader thread: the guarded value is a plain bool, never in a
474 // half-updated state worth bailing on.
475 *lock.lock().unwrap_or_else(|p| p.into_inner()) = true;
476 cvar.notify_all();
477 }
478 // `ProcessEvent` is #[non_exhaustive]; ignore any future variant.
479 _ => {}
480 },
481 )
482 .map_err(HarnessError::login)?;
483 let (lock, cvar) = &*done;
484 let mut finished = lock.lock().unwrap_or_else(|p| p.into_inner());
485 while !*finished {
486 finished = cvar.wait(finished).unwrap_or_else(|p| p.into_inner());
487 }
488 Ok(())
489}
490
491/// Whether an API-key value an adapter pulled from the environment counts as
492/// authenticated — i.e. present and non-blank. Adapters OR this into their
493/// [`Harness::readiness`] so a key in the env (headless / CI / container)
494/// reports authenticated, not only the CLI's own interactive OAuth login —
495/// which can't complete where there's no browser. Pure (the env read stays at
496/// the call site) so it's unit-tested directly.
497///
498/// Only the claude/codex adapters OR this into readiness — bob reports auth via
499/// `bob-rs`'s own keychain source — so it's gated to those features. Without
500/// them (`--no-default-features`) it would be dead code, hence the `cfg`.
501#[cfg(any(feature = "claude", feature = "codex"))]
502pub(crate) fn api_key_value_usable(value: Option<String>) -> bool {
503 matches!(value, Some(v) if !v.trim().is_empty())
504}
505
506#[cfg(test)]
507mod tests {
508 use super::*;
509
510 // Gated like the fn it tests — `api_key_value_usable` only exists when a
511 // claude/codex adapter is compiled in.
512 #[cfg(any(feature = "claude", feature = "codex"))]
513 #[test]
514 fn api_key_value_usable_requires_a_nonblank_value() {
515 assert!(api_key_value_usable(Some("sk-abc".to_owned())));
516 assert!(!api_key_value_usable(Some(String::new())));
517 assert!(!api_key_value_usable(Some(" ".to_owned())));
518 assert!(!api_key_value_usable(None));
519 }
520
521 /// A no-op [`RunControl`] so the mock harness below can hand back a
522 /// [`RunHandle`] without a real process behind it.
523 struct NoopControl;
524 impl RunControl for NoopControl {
525 fn cancel(&self) -> Result<(), HarnessError> {
526 Ok(())
527 }
528 fn was_cancelled(&self) -> bool {
529 false
530 }
531 }
532
533 /// A minimal in-memory harness whose `run()` pushes a fixed event
534 /// sequence straight to the callback, synchronously, then returns —
535 /// dropping its only `RunCallback` clone. That's exactly the ownership
536 /// shape `run_channel` relies on, with no subprocess to spawn, so it
537 /// pins down the contract: events are forwarded, and the receiver hangs
538 /// up on its own once the run's callback ownership ends.
539 struct MockHarness {
540 events: Vec<RunEvent>,
541 }
542 impl Harness for MockHarness {
543 fn info(&self) -> HarnessInfo {
544 unreachable!("not exercised by run_channel")
545 }
546 fn readiness(&self) -> HarnessReadiness {
547 unreachable!("not exercised by run_channel")
548 }
549 fn install(&self, _on_event: InstallCallback) -> Result<(), HarnessError> {
550 Ok(())
551 }
552 fn run(
553 &self,
554 _request: RunRequest,
555 on_event: RunCallback,
556 ) -> Result<RunHandle, HarnessError> {
557 for event in &self.events {
558 on_event(event.clone());
559 }
560 // `on_event` (the lone RunCallback clone, owning the channel's
561 // Sender) drops as this returns → the receiver closes.
562 Ok(Box::new(NoopControl))
563 }
564 fn credential(&self) -> CredentialSpec {
565 unreachable!("not exercised by run_channel")
566 }
567 }
568
569 fn demo_request() -> RunRequest {
570 RunRequest {
571 run_id: "t".to_owned(),
572 prompt: "hi".to_owned(),
573 cwd: None,
574 mode: RunMode::Ask,
575 tuning: RunTuning::default(),
576 }
577 }
578
579 #[test]
580 fn run_channel_forwards_every_event_then_closes() {
581 let harness = MockHarness {
582 events: vec![
583 RunEvent::Text {
584 run_id: "t".to_owned(),
585 delta: "hello".to_owned(),
586 },
587 RunEvent::Exited {
588 run_id: "t".to_owned(),
589 exit_code: Some(0),
590 cancelled: false,
591 },
592 ],
593 };
594 let (_handle, rx) = harness.run_channel(demo_request()).expect("run_channel ok");
595 // Draining to completion *terminates* — proof the channel closed
596 // without us dropping the handle.
597 let collected: Vec<RunEvent> = rx.into_iter().collect();
598 assert_eq!(
599 collected,
600 vec![
601 RunEvent::Text {
602 run_id: "t".to_owned(),
603 delta: "hello".to_owned(),
604 },
605 RunEvent::Exited {
606 run_id: "t".to_owned(),
607 exit_code: Some(0),
608 cancelled: false,
609 },
610 ]
611 );
612 }
613
614 #[test]
615 fn run_channel_receiver_closes_even_with_no_events() {
616 let harness = MockHarness { events: Vec::new() };
617 let (_handle, rx) = harness.run_channel(demo_request()).expect("run_channel ok");
618 assert_eq!(rx.into_iter().count(), 0); // closes immediately, doesn't hang
619 }
620
621 #[test]
622 fn harness_error_preserves_typed_source_and_flattened_message() {
623 use std::error::Error;
624
625 // Categorize a real typed engine error as a Spawn failure.
626 let err = HarnessError::spawn(cli_stream::StreamError::PipeNotCaptured { stream: "stdout" });
627
628 // Display still flattens the source into the message, so a consumer
629 // that just `.to_string()`s at a boundary (a Tauri command) gets the
630 // category prefix *and* the full underlying detail — unchanged from
631 // when the variant held a String.
632 let message = err.to_string();
633 assert!(message.starts_with("failed to start the agent: "), "got {message:?}");
634 assert!(message.contains("stdout pipe was not captured"), "got {message:?}");
635
636 // And the real typed error is reachable via the source chain — the
637 // whole point of carrying a source instead of a flattened string.
638 let source = err.source().expect("HarnessError::Spawn has a source");
639 assert!(
640 source.downcast_ref::<cli_stream::StreamError>().is_some(),
641 "source should downcast back to the typed StreamError"
642 );
643 }
644}