use std::time::Duration;
use serde_json::json;
use tokio::sync::mpsc::unbounded_channel;
use trusty_code::tui_client::CodeEngine;
use trusty_code::tui_client::discovery::DAEMON_URL_ENV;
use trusty_code_tui::{ReplEvent, TuiEngine};
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, Request, ResponseTemplate};
const SESSION_ID: &str = "sess-1";
const WS_1: &str = "ws-1";
const WS_2: &str = "ws-2";
struct RpcMethod(&'static str);
impl wiremock::Match for RpcMethod {
fn matches(&self, request: &Request) -> bool {
serde_json::from_slice::<serde_json::Value>(&request.body)
.ok()
.and_then(|v| v.get("method").and_then(|m| m.as_str()).map(str::to_string))
.as_deref()
== Some(self.0)
}
}
async fn mount_common(server: &MockServer) {
Mock::given(method("GET"))
.and(path("/health"))
.respond_with(ResponseTemplate::new(200))
.mount(server)
.await;
Mock::given(method("POST"))
.and(path("/rpc"))
.and(RpcMethod("session.create"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": 1,
"result": {"id": SESSION_ID, "task": "tcode tui session", "status": "running"},
})))
.mount(server)
.await;
Mock::given(method("POST"))
.and(path("/rpc"))
.and(RpcMethod("workstream.list"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": 1,
"result": {
"active_workstream_id": WS_1,
"workstreams": [{"id": WS_1, "name": "Feature X"}],
},
})))
.mount(server)
.await;
Mock::given(method("POST"))
.and(path("/rpc"))
.and(RpcMethod("task.run"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": 1,
"result": {"session_id": SESSION_ID, "status": "running"},
})))
.mount(server)
.await;
Mock::given(method("POST"))
.and(path("/rpc"))
.and(RpcMethod("session.cancel"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": 1,
"result": {},
})))
.mount(server)
.await;
Mock::given(method("POST"))
.and(path("/rpc"))
.and(RpcMethod("workstream.activate"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": 1,
"result": {"active_id": WS_2, "prior_id": WS_1},
})))
.mount(server)
.await;
}
fn session_events_body() -> String {
let tool_started = json!({
"session_id": SESSION_ID, "seq": 1, "at": "2026-07-20T00:00:00Z", "kind": "tool_started",
"event": {
"type": "tool_started", "session_id": SESSION_ID, "agent": "pm", "agent_id": "",
"tool": "bash", "call_id": "call-1", "args_preview": "ls",
},
});
let message = json!({
"session_id": SESSION_ID, "seq": 2, "at": "2026-07-20T00:00:01Z", "kind": "message",
"event": {"type": "message", "session_id": SESSION_ID, "text": "hello from the daemon"},
});
let done = json!({
"session_id": SESSION_ID, "seq": 3, "at": "2026-07-20T00:00:02Z", "kind": "session_done",
"event": {"type": "session_done", "session_id": SESSION_ID, "status": "finished"},
});
format!("data: {tool_started}\n\ndata: {message}\n\ndata: {done}\n\n")
}
fn workstream_activation_body() -> String {
let activation = json!({
"session_id": "",
"event_type": "workstream_activation_changed",
"payload": {
"type": "workstream_activation_changed",
"new_active_id": WS_2,
"prior_id": WS_1,
},
});
format!("data: {activation}\n\n")
}
fn workstream_deactivated_body() -> String {
let deactivated = json!({
"session_id": "",
"event_type": "workstream_activation_changed",
"payload": {
"type": "workstream_activation_changed",
"new_active_id": null,
"prior_id": WS_1,
},
});
format!("data: {deactivated}\n\n")
}
async fn count_rpc_calls(server: &MockServer, method: &str) -> usize {
server
.received_requests()
.await
.expect("received requests")
.iter()
.filter(|r| {
r.url.path() == "/rpc"
&& serde_json::from_slice::<serde_json::Value>(&r.body)
.ok()
.and_then(|v| v.get("method").and_then(|m| m.as_str()).map(str::to_string))
.as_deref()
== Some(method)
})
.count()
}
#[tokio::test]
async fn setup_creates_session_and_reports_active_workstream() {
let server = MockServer::start().await;
mount_common(&server).await;
let engine = CodeEngine::with_daemon_url(reqwest::Client::new(), server.uri(), None);
let (tx, mut rx) = unbounded_channel();
engine.setup(tx).await.expect("setup");
let mut saw_workstream_updated = false;
while let Ok(ev) = rx.try_recv() {
if let ReplEvent::WorkstreamUpdated(ws) = ev {
assert_eq!(ws.id, WS_1);
assert_eq!(ws.name, "Feature X");
saw_workstream_updated = true;
}
}
assert!(
saw_workstream_updated,
"setup must emit WorkstreamUpdated for the daemon's active workstream"
);
assert_eq!(
engine.commands().len(),
1,
"setup must populate the commands cache for TuiEngine::commands() (#3428)"
);
let picker = engine
.picker("workstream")
.expect("setup must populate the workstream picker cache for TuiEngine::picker() (#3428)");
assert_eq!(picker.items.len(), 1);
assert_eq!(picker.dispatch_command, "/workstream activate");
}
#[tokio::test]
async fn handle_input_streams_assistant_output_and_tool_invocation() {
let server = MockServer::start().await;
mount_common(&server).await;
Mock::given(method("GET"))
.and(path(format!("/sessions/{SESSION_ID}/events")))
.respond_with(
ResponseTemplate::new(200).set_body_raw(session_events_body(), "text/event-stream"),
)
.mount(&server)
.await;
let engine = CodeEngine::with_daemon_url(reqwest::Client::new(), server.uri(), None);
let (tx, mut rx) = unbounded_channel();
engine.setup(tx.clone()).await.expect("setup");
while rx.try_recv().is_ok() {}
let keep_going = engine
.handle_input("hello".to_string(), tx)
.await
.expect("handle_input");
assert!(
keep_going,
"handle_input must return Ok(true) to keep the REPL running"
);
let mut events = Vec::new();
while let Ok(ev) = rx.try_recv() {
events.push(ev);
}
assert!(
events.iter().any(|e| matches!(
e,
ReplEvent::ToolInvocation { id, tool_name, result: None, .. }
if id == "call-1" && tool_name == "bash"
)),
"expected a ToolInvocation for call-1/bash with no result yet; got {events:?}"
);
assert!(
events.iter().any(|e| matches!(
e,
ReplEvent::AssistantOutput { chunk, done: false, is_error: false }
if chunk == "hello from the daemon"
)),
"expected an in-progress AssistantOutput chunk; got {events:?}"
);
assert!(
events.iter().any(|e| matches!(
e,
ReplEvent::AssistantOutput {
done: true,
is_error: false,
..
}
)),
"expected a final AssistantOutput{{done: true}} on SessionDone; got {events:?}"
);
}
#[tokio::test]
async fn handle_input_surfaces_visible_error_after_exhausting_reconnects() {
let server = MockServer::start().await;
mount_common(&server).await;
Mock::given(method("GET"))
.and(path(format!("/sessions/{SESSION_ID}/events")))
.respond_with(ResponseTemplate::new(200).set_body_raw("", "text/event-stream"))
.mount(&server)
.await;
let engine = CodeEngine::with_daemon_url(reqwest::Client::new(), server.uri(), None);
let (tx, mut rx) = unbounded_channel();
engine.setup(tx.clone()).await.expect("setup");
while rx.try_recv().is_ok() {}
let result = tokio::time::timeout(
Duration::from_secs(30),
engine.handle_input("hello".to_string(), tx),
)
.await
.expect(
"handle_input must not hang — an un-exhaustible reconnect loop must fail this test \
deterministically, not hang the test binary forever",
);
assert!(
result.is_err(),
"handle_input must return Err once every reconnect attempt is exhausted with no \
terminal session event ever observed, not Ok(true)"
);
let mut saw_terminal_error = false;
while let Ok(ev) = rx.try_recv() {
if let ReplEvent::AssistantOutput {
done: true,
is_error: true,
..
} = ev
{
saw_terminal_error = true;
}
}
assert!(
saw_terminal_error,
"expected a done:true, is_error:true AssistantOutput before handle_input returned Err \
— otherwise the TUI stalls silently (busy stays true, no error text rendered)"
);
}
#[tokio::test]
async fn cancel_session_calls_session_cancel_rpc() {
let server = MockServer::start().await;
mount_common(&server).await;
let engine = CodeEngine::with_daemon_url(reqwest::Client::new(), server.uri(), None);
let (tx, _rx) = unbounded_channel();
engine.setup(tx).await.expect("setup");
engine.cancel_session().await.expect("cancel_session");
assert_eq!(
count_rpc_calls(&server, "session.cancel").await,
1,
"cancel_session must call the daemon's session.cancel RPC, not just stop client-side \
rendering (DOC-39 §2.1 C-2)"
);
}
#[tokio::test]
async fn subscribe_workstream_events_emits_activation_changed_with_wire_field_names() {
let server = MockServer::start().await;
mount_common(&server).await;
Mock::given(method("GET"))
.and(path(format!("/workstreams/{WS_1}/events")))
.respond_with(
ResponseTemplate::new(200)
.set_body_raw(workstream_activation_body(), "text/event-stream"),
)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path(format!("/workstreams/{WS_2}/events")))
.respond_with(ResponseTemplate::new(200).set_body_raw("", "text/event-stream"))
.mount(&server)
.await;
let engine = CodeEngine::with_daemon_url(reqwest::Client::new(), server.uri(), None);
let (tx, mut rx) = unbounded_channel();
engine.setup(tx.clone()).await.expect("setup");
while rx.try_recv().is_ok() {}
engine
.subscribe_workstream_events(tx)
.await
.expect("subscribe_workstream_events");
let events = tokio::time::timeout(Duration::from_secs(5), async {
let mut seen = Vec::new();
loop {
match rx.recv().await {
Some(ev @ ReplEvent::WorkstreamActivationChanged { .. }) => {
seen.push(ev);
return seen;
}
Some(ev) => seen.push(ev),
None => panic!("channel closed before observing WorkstreamActivationChanged"),
}
}
})
.await
.expect("timed out waiting for WorkstreamActivationChanged");
let activation = events
.iter()
.find(|e| matches!(e, ReplEvent::WorkstreamActivationChanged { .. }))
.expect("collected events must include WorkstreamActivationChanged");
match activation {
ReplEvent::WorkstreamActivationChanged {
new_active_id,
prior_id,
} => {
assert_eq!(new_active_id.as_deref(), Some(WS_2));
assert_eq!(prior_id.as_deref(), Some(WS_1));
}
other => panic!("unexpected {other:?}"),
}
assert!(
events
.iter()
.any(|e| matches!(e, ReplEvent::WorkstreamUpdated(_))),
"expected a WorkstreamUpdated alongside the activation change; got {events:?}"
);
assert!(
events.iter().any(|e| matches!(
e,
ReplEvent::StatuslineUpdate(segs)
if segs.iter().any(|s| matches!(s, trusty_code_tui::StatuslineSegment::Workstream { .. }))
)),
"expected a StatuslineUpdate carrying a Workstream segment; got {events:?}"
);
engine.shutdown().await.expect("shutdown");
}
#[tokio::test]
async fn subscribe_workstream_events_refreshes_cache_on_deactivation_with_no_replacement() {
let server = MockServer::start().await;
mount_common(&server).await;
Mock::given(method("GET"))
.and(path(format!("/workstreams/{WS_1}/events")))
.respond_with(
ResponseTemplate::new(200)
.set_body_raw(workstream_deactivated_body(), "text/event-stream"),
)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/rpc"))
.and(RpcMethod("workstream.list"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": 1,
"result": {
"active_workstream_id": WS_1,
"workstreams": [{"id": WS_1, "name": "Feature X"}],
},
})))
.up_to_n_times(1)
.with_priority(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/rpc"))
.and(RpcMethod("workstream.list"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": 1,
"result": {
"active_workstream_id": null,
"workstreams": [{"id": WS_1, "name": "Feature X"}],
},
})))
.with_priority(2)
.mount(&server)
.await;
let engine = CodeEngine::with_daemon_url(reqwest::Client::new(), server.uri(), None);
let (tx, mut rx) = unbounded_channel();
engine.setup(tx.clone()).await.expect("setup");
while rx.try_recv().is_ok() {}
let calls_before = count_rpc_calls(&server, "workstream.list").await;
assert_eq!(
calls_before, 1,
"setup must have called workstream.list exactly once so far"
);
engine
.subscribe_workstream_events(tx)
.await
.expect("subscribe_workstream_events");
tokio::time::timeout(Duration::from_secs(5), async {
loop {
if count_rpc_calls(&server, "workstream.list").await > calls_before {
return;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
})
.await
.expect("timed out waiting for refresh_workstream_cache to re-call workstream.list");
let events = tokio::time::timeout(Duration::from_secs(5), async {
let mut seen = Vec::new();
loop {
match rx.recv().await {
Some(ev @ ReplEvent::WorkstreamActivationChanged { .. }) => {
seen.push(ev);
return seen;
}
Some(ev) => seen.push(ev),
None => panic!("channel closed before observing the deactivation event"),
}
}
})
.await
.expect("timed out waiting for the deactivation event");
let activation = events
.iter()
.find(|e| matches!(e, ReplEvent::WorkstreamActivationChanged { .. }))
.expect("collected events must include WorkstreamActivationChanged");
match activation {
ReplEvent::WorkstreamActivationChanged {
new_active_id: None,
prior_id,
} => {
assert_eq!(
prior_id.as_deref(),
Some(WS_1),
"expected WorkstreamActivationChanged{{new_active_id: None, prior_id: Some(WS_1)}}"
);
}
other => panic!("expected new_active_id: None; got {other:?}"),
}
assert!(
events
.iter()
.any(|e| matches!(e, ReplEvent::StatuslineUpdate(segs) if segs.is_empty())),
"expected a StatuslineUpdate with an empty segment list clearing the Workstream segment \
on deactivation; got {events:?}"
);
engine.shutdown().await.expect("shutdown");
}
#[tokio::test]
async fn discover_finds_daemon_via_env_var_override() {
let server = MockServer::start().await;
mount_common(&server).await;
unsafe {
std::env::set_var(DAEMON_URL_ENV, server.uri());
}
let result = CodeEngine::discover(None).await;
unsafe {
std::env::remove_var(DAEMON_URL_ENV);
}
let engine = result.expect("discover must succeed against a live mock daemon");
assert_eq!(engine.daemon_url(), server.uri());
}