use tokio::sync::mpsc::unbounded_channel;
use super::*;
use crate::events::{Event, SessionEventEnvelope};
use crate::tui_client::session_events::{
forward_session_event, is_retryable_status, terminal_stream_failure_event,
};
use crate::tui_client::workstream_subscription::parse_workstream_envelope;
use trusty_code_tui::{StatuslineSegment, WorkstreamSummary};
fn envelope(event: Event) -> SessionEventEnvelope {
SessionEventEnvelope::new("s-1".to_string(), 1, chrono::Utc::now(), event)
}
#[test]
fn forward_message_emits_assistant_output_chunk_not_done() {
let (tx, mut rx) = unbounded_channel();
let terminal = forward_session_event(
envelope(Event::Message {
session_id: "s-1".into(),
text: "hi".into(),
}),
&tx,
);
assert!(!terminal);
assert_eq!(
rx.try_recv().expect("event"),
ReplEvent::AssistantOutput {
chunk: "hi".into(),
done: false,
is_error: false,
}
);
}
#[test]
fn forward_tool_started_emits_tool_invocation_with_call_id() {
let (tx, mut rx) = unbounded_channel();
let terminal = forward_session_event(
envelope(Event::ToolStarted {
session_id: "s-1".into(),
agent: "pm".into(),
agent_id: String::new(),
tool: "bash".into(),
call_id: "call-1".into(),
args_preview: "ls".into(),
}),
&tx,
);
assert!(!terminal);
match rx.try_recv().expect("event") {
ReplEvent::ToolInvocation {
id,
tool_name,
result,
..
} => {
assert_eq!(id, "call-1");
assert_eq!(tool_name, "bash");
assert!(result.is_none());
}
other => panic!("unexpected {other:?}"),
}
}
#[test]
fn forward_tool_finished_carries_result_and_shares_call_id() {
let (tx, mut rx) = unbounded_channel();
forward_session_event(
envelope(Event::ToolFinished {
session_id: "s-1".into(),
agent: "pm".into(),
agent_id: String::new(),
tool: "bash".into(),
call_id: "call-1".into(),
success: true,
result_preview: "done".into(),
}),
&tx,
);
match rx.try_recv().expect("event") {
ReplEvent::ToolInvocation { id, result, .. } => {
assert_eq!(id, "call-1");
assert_eq!(result.as_deref(), Some("done"));
}
other => panic!("unexpected {other:?}"),
}
}
#[test]
fn forward_session_done_is_terminal() {
let (tx, mut rx) = unbounded_channel();
let terminal = forward_session_event(
envelope(Event::SessionDone {
session_id: "s-1".into(),
status: "finished".into(),
}),
&tx,
);
assert!(terminal);
assert_eq!(
rx.try_recv().expect("event"),
ReplEvent::AssistantOutput {
chunk: String::new(),
done: true,
is_error: false,
}
);
}
#[test]
fn forward_session_done_failed_marks_is_error() {
let (tx, mut rx) = unbounded_channel();
forward_session_event(
envelope(Event::SessionDone {
session_id: "s-1".into(),
status: "failed".into(),
}),
&tx,
);
assert_eq!(
rx.try_recv().expect("event"),
ReplEvent::AssistantOutput {
chunk: String::new(),
done: true,
is_error: true,
}
);
}
#[test]
fn forward_session_cancelled_is_terminal() {
let (tx, mut rx) = unbounded_channel();
let terminal = forward_session_event(
envelope(Event::SessionCancelled {
session_id: "s-1".into(),
}),
&tx,
);
assert!(terminal);
assert!(rx.try_recv().is_ok());
}
#[test]
fn forward_unrelated_event_is_ignored() {
let (tx, mut rx) = unbounded_channel();
let terminal = forward_session_event(envelope(Event::Ping), &tx);
assert!(!terminal);
assert!(rx.try_recv().is_err());
}
#[test]
fn forward_agent_message_delta_not_done_appends() {
let (tx, mut rx) = unbounded_channel();
let terminal = forward_session_event(
envelope(Event::AgentMessageDelta {
session_id: "s-1".into(),
agent: "coder".into(),
agent_id: "agent-1".into(),
turn_id: "turn-1".into(),
delta: "Hello".into(),
done: false,
}),
&tx,
);
assert!(!terminal);
assert_eq!(
rx.try_recv().expect("event"),
ReplEvent::AssistantOutput {
chunk: "Hello".into(),
done: false,
is_error: false,
}
);
}
#[test]
fn forward_agent_message_delta_done_finalizes() {
let (tx, mut rx) = unbounded_channel();
let terminal = forward_session_event(
envelope(Event::AgentMessageDelta {
session_id: "s-1".into(),
agent: "coder".into(),
agent_id: "agent-1".into(),
turn_id: "turn-1".into(),
delta: " world".into(),
done: true,
}),
&tx,
);
assert!(
!terminal,
"an agent turn finishing must not end the SSE pump"
);
assert_eq!(
rx.try_recv().expect("event"),
ReplEvent::AssistantOutput {
chunk: " world".into(),
done: true,
is_error: false,
}
);
}
#[test]
fn forward_agent_message_delta_distinct_agent_ids_not_merged() {
let (tx, mut rx) = unbounded_channel();
forward_session_event(
envelope(Event::AgentMessageDelta {
session_id: "s-1".into(),
agent: "coder".into(),
agent_id: "agent-1".into(),
turn_id: "turn-shared".into(),
delta: "from-agent-1".into(),
done: false,
}),
&tx,
);
forward_session_event(
envelope(Event::AgentMessageDelta {
session_id: "s-1".into(),
agent: "reviewer".into(),
agent_id: "agent-2".into(),
turn_id: "turn-shared".into(),
delta: "from-agent-2".into(),
done: false,
}),
&tx,
);
assert_eq!(
rx.try_recv().expect("event"),
ReplEvent::AssistantOutput {
chunk: "from-agent-1".into(),
done: false,
is_error: false,
},
"agent-1's delta must forward as its own message, not merged with agent-2's"
);
assert_eq!(
rx.try_recv().expect("event"),
ReplEvent::AssistantOutput {
chunk: "from-agent-2".into(),
done: false,
is_error: false,
},
"agent-2's delta must forward as its own message, not merged with agent-1's"
);
}
#[test]
fn workstream_subcommand_parses_list_and_activate() {
assert_eq!(workstream_subcommand("/workstream list"), Some("list"));
assert_eq!(
workstream_subcommand("/ws activate abc-123"),
Some("activate abc-123")
);
assert_eq!(workstream_subcommand("/workstream"), Some(""));
assert_eq!(workstream_subcommand("/workstreamx foo"), None);
assert_eq!(workstream_subcommand("hello"), None);
}
#[test]
fn parse_workstream_envelope_round_trips_activation_changed() {
let json = serde_json::json!({
"session_id": "",
"event_type": "workstream_activation_changed",
"payload": {
"type": "workstream_activation_changed",
"new_active_id": "ws-2",
"prior_id": "ws-1",
},
})
.to_string();
let env = parse_workstream_envelope(&json).expect("parse");
match env.payload {
Event::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:?}"),
}
}
#[test]
fn terminal_stream_failure_event_is_a_done_error_output() {
let event = terminal_stream_failure_event("daemon unreachable".to_string());
assert_eq!(
event,
ReplEvent::AssistantOutput {
chunk: "connection lost: daemon unreachable".to_string(),
done: true,
is_error: true,
}
);
}
#[test]
fn is_retryable_status_covers_502_and_503_only() {
assert!(is_retryable_status(reqwest::StatusCode::BAD_GATEWAY));
assert!(is_retryable_status(
reqwest::StatusCode::SERVICE_UNAVAILABLE
));
assert!(!is_retryable_status(reqwest::StatusCode::NOT_FOUND));
}
#[test]
fn caches_are_empty_before_setup() {
let engine = CodeEngine::with_daemon_url(reqwest::Client::new(), "http://127.0.0.1:1", None);
assert!(engine.commands().is_empty());
assert!(engine.picker("workstream").is_none());
}
#[test]
fn workstream_picker_dispatch_command_round_trips_through_workstream_subcommand() {
let dispatch_command = "/workstream activate";
let resubmitted = format!("{dispatch_command} ws-1");
assert_eq!(workstream_subcommand(&resubmitted), Some("activate ws-1"));
}
#[test]
fn picker_unknown_name_is_none() {
let engine = CodeEngine::with_daemon_url(reqwest::Client::new(), "http://127.0.0.1:1", None);
assert!(engine.picker("model").is_none());
}
#[test]
fn statusline_segments_reflect_active_workstream_and_clear_on_none() {
let state = EngineState::new(
RpcHttpClient::new(reqwest::Client::new(), "http://127.0.0.1:1".to_string()),
None,
);
assert!(
state.statusline_segments().is_empty(),
"no active workstream observed yet -> no segments"
);
*state.active_workstream.lock().unwrap() = Some(WorkstreamSummary {
id: "ws-1".to_string(),
name: "Feature X".to_string(),
});
assert_eq!(
state.statusline_segments(),
vec![StatuslineSegment::Workstream {
id: "ws-1".to_string(),
name: "Feature X".to_string(),
}]
);
*state.active_workstream.lock().unwrap() = None;
assert!(
state.statusline_segments().is_empty(),
"deactivation must clear the segment, not leave a stale one"
);
}
#[tokio::test]
async fn events_connect_hang_is_bounded_by_connect_timeout_not_infinite() {
let std_listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
std_listener.set_nonblocking(true).expect("set_nonblocking");
let listener = tokio::net::TcpListener::from_std(std_listener).expect("tokio listener");
let addr = listener.local_addr().expect("local_addr");
let (accepted_tx, mut accepted_rx) = unbounded_channel();
let accept_task = tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
let _ = accepted_tx.send(());
std::mem::forget(stream);
}
});
let state = EngineState::new(
RpcHttpClient::new(reqwest::Client::new(), format!("http://{addr}")),
None,
);
let (tx, mut rx) = unbounded_channel();
let pump_task = tokio::spawn(async move { state.pump_session_events("s-1", &tx).await });
accepted_rx
.recv()
.await
.expect("listener must accept the pump's connection");
tokio::time::pause();
match tokio::time::timeout(CONNECT_TIMEOUT + Duration::from_secs(10), rx.recv()).await {
Ok(Some(ReplEvent::ConnectionLost { reason })) => {
assert!(
reason.contains("connection failed"),
"expected a transport-error ConnectionLost from the timed-out connect, got: \
{reason}"
);
}
Ok(Some(other)) => panic!("expected ConnectionLost, got {other:?}"),
Ok(None) => panic!("channel closed with no event — pump_session_events exited silently"),
Err(_) => panic!(
"no ConnectionLost observed within CONNECT_TIMEOUT + slack — the initial connect \
attempt hung past CONNECT_TIMEOUT (issue #3494 regression)"
),
}
pump_task.abort();
accept_task.abort();
}