use tokio::sync::mpsc::unbounded_channel;
use super::*;
use crate::events::{Event, SessionEventEnvelope};
use crate::tui_client::session_events::{forward_session_event, terminal_stream_failure_event};
use crate::tui_client::workstream_subscription::parse_workstream_envelope;
use trusty_code_tui::{DelegationOutcome, 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: "error: the run ended with status `failed`".into(),
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::AgentOutput {
agent_id: "agent-1".into(),
turn_id: "turn-1".into(),
chunk: "Hello".into(),
done: 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::AgentOutput {
agent_id: "agent-1".into(),
turn_id: "turn-1".into(),
chunk: " world".into(),
done: true,
}
);
}
#[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::AgentOutput {
agent_id: "agent-1".into(),
turn_id: "turn-shared".into(),
chunk: "from-agent-1".into(),
done: false,
},
"agent-1's delta must keep its own agent_id, not merge with agent-2's"
);
assert_eq!(
rx.try_recv().expect("event"),
ReplEvent::AgentOutput {
agent_id: "agent-2".into(),
turn_id: "turn-shared".into(),
chunk: "from-agent-2".into(),
done: false,
},
"agent-2's delta must keep its own agent_id, not merge with agent-1's"
);
}
#[test]
fn forward_agent_spawned_opens_a_delegation() {
let (tx, mut rx) = unbounded_channel();
let terminal = forward_session_event(
envelope(Event::AgentSpawned {
session_id: "s-1".into(),
agent: "engineer".into(),
agent_id: "spawn-7".into(),
task_preview: "add the delegation renderer".into(),
}),
&tx,
);
assert!(!terminal);
assert_eq!(
rx.try_recv().expect("event"),
ReplEvent::DelegationStarted {
agent_id: "spawn-7".into(),
agent: "engineer".into(),
task: "add the delegation renderer".into(),
}
);
}
#[test]
fn forward_pm_delegating_opens_a_delegation_without_an_id() {
let (tx, mut rx) = unbounded_channel();
forward_session_event(
envelope(Event::PmDelegating {
session_id: "s-1".into(),
agent: "engineer".into(),
task_preview: "add the delegation renderer".into(),
}),
&tx,
);
assert_eq!(
rx.try_recv().expect("event"),
ReplEvent::DelegationStarted {
agent_id: String::new(),
agent: "engineer".into(),
task: "add the delegation renderer".into(),
}
);
}
#[test]
fn forward_agent_done_closes_the_delegation() {
let (tx, mut rx) = unbounded_channel();
let terminal = forward_session_event(
envelope(Event::AgentDone {
session_id: "s-1".into(),
agent: "engineer".into(),
agent_id: "spawn-7".into(),
status: "success".into(),
}),
&tx,
);
assert!(
!terminal,
"a delegation finishing must not end the session stream"
);
assert_eq!(
rx.try_recv().expect("event"),
ReplEvent::DelegationFinished {
agent_id: "spawn-7".into(),
agent: "engineer".into(),
outcome: DelegationOutcome::Finished("success".into()),
}
);
}
#[test]
fn forward_agent_failed_closes_with_the_error() {
let (tx, mut rx) = unbounded_channel();
forward_session_event(
envelope(Event::AgentFailed {
session_id: "s-1".into(),
agent: "engineer".into(),
agent_id: "spawn-7".into(),
error: "turn cap exceeded".into(),
}),
&tx,
);
assert_eq!(
rx.try_recv().expect("event"),
ReplEvent::DelegationFinished {
agent_id: "spawn-7".into(),
agent: "engineer".into(),
outcome: DelegationOutcome::Failed("turn cap exceeded".into()),
}
);
}
#[test]
fn forward_permission_requested_opens_the_prompt() {
let (tx, mut rx) = unbounded_channel();
forward_session_event(
envelope(Event::PermissionRequested {
session_id: "s-1".into(),
request_id: "req-9".into(),
agent: "python-engineer".into(),
agent_id: "spawn-7".into(),
tool: "bash".into(),
subject: "rm -rf build".into(),
rule: "bash[rm *]".into(),
}),
&tx,
);
assert_eq!(
rx.try_recv().expect("event"),
ReplEvent::PermissionRequested {
request_id: "req-9".into(),
agent: "python-engineer".into(),
agent_id: "spawn-7".into(),
tool: "bash".into(),
subject: "rm -rf build".into(),
rule: "bash[rm *]".into(),
}
);
}
#[test]
fn forward_permission_resolved_closes_the_prompt() {
let (tx, mut rx) = unbounded_channel();
forward_session_event(
envelope(Event::PermissionResolved {
session_id: "s-1".into(),
request_id: "req-9".into(),
agent: "python-engineer".into(),
agent_id: "spawn-7".into(),
decision: "allow_for_session".into(),
source: "client".into(),
}),
&tx,
);
assert_eq!(
rx.try_recv().expect("event"),
ReplEvent::PermissionResolved {
request_id: "req-9".into(),
agent: "python-engineer".into(),
agent_id: "spawn-7".into(),
decision: "allow_for_session".into(),
source: "client".into(),
}
);
}
fn agent_attributed_kind(event: &Event) -> Option<&'static str> {
match event {
Event::ToolStarted { .. }
| Event::ToolFinished { .. }
| Event::ToolError { .. }
| Event::SearchPerformed { .. }
| Event::MemoryRecalled { .. }
| Event::PmDelegating { .. }
| Event::AgentSpawned { .. }
| Event::AgentMessage { .. }
| Event::AgentMessageDelta { .. }
| Event::AgentDone { .. }
| Event::AgentFailed { .. }
| Event::PermissionRequested { .. }
| Event::PermissionResolved { .. }
| Event::TodosChanged { .. } => Some(event.kind()),
Event::AgentStarted { .. }
| Event::SessionStarted { .. }
| Event::SessionDone { .. }
| Event::SessionCancelled { .. }
| Event::SessionStatusChanged { .. }
| Event::SessionInput { .. }
| Event::Log { .. }
| Event::Progress { .. }
| Event::Message { .. }
| Event::PmThinking { .. }
| Event::ToolCalled { .. }
| Event::ToolResult { .. }
| Event::AstOperation { .. }
| Event::PhaseStarted { .. }
| Event::PhaseDone { .. }
| Event::PhaseSkipped { .. }
| Event::PersonaDetected { .. }
| Event::LlmRequested { .. }
| Event::LlmResponded { .. }
| Event::ReportGenerated { .. }
| Event::RecapGenerated { .. }
| Event::IndexReadiness { .. }
| Event::ContextBudget { .. }
| Event::SessionAdded { .. }
| Event::SessionActivityUpdate { .. }
| Event::WorkstreamActivationChanged { .. }
| Event::WorkstreamStateInferred { .. }
| Event::Ping => None,
}
}
const INTENTIONALLY_IGNORED: &[(&str, &str)] = &[
(
"search_performed",
"search telemetry; the tool_started/tool_finished pair for the same call already renders",
),
(
"memory_recalled",
"recall telemetry; same reason as search_performed",
),
(
"todos_changed",
"the checklist panel is #8182's work; until it lands this client has no \
ReplEvent to render a checklist into, and the roster read path \
(session.get_agents) carries the same list",
),
];
#[test]
fn every_agent_attributed_event_maps_or_is_explicitly_ignored() {
for event in delegation_event_samples() {
let Some(kind) = agent_attributed_kind(&event) else {
panic!("sample {} is not agent-attributed", event.kind());
};
let (tx, mut rx) = unbounded_channel();
forward_session_event(envelope(event), &tx);
let mapped = rx.try_recv().is_ok();
let ignored = INTENTIONALLY_IGNORED.iter().any(|(k, _)| *k == kind);
assert!(
mapped != ignored,
"`{kind}` must either map to a ReplEvent or be listed in INTENTIONALLY_IGNORED \
(mapped={mapped}, ignored={ignored})"
);
}
}
fn delegation_event_samples() -> Vec<Event> {
vec![
Event::PmDelegating {
session_id: "s-1".into(),
agent: "engineer".into(),
task_preview: "t".into(),
},
Event::AgentSpawned {
session_id: "s-1".into(),
agent: "engineer".into(),
agent_id: "spawn-1".into(),
task_preview: "t".into(),
},
Event::AgentMessage {
session_id: "s-1".into(),
agent: "engineer".into(),
text: "hi".into(),
},
Event::AgentMessageDelta {
session_id: "s-1".into(),
agent: "engineer".into(),
agent_id: "spawn-1".into(),
turn_id: "turn-1".into(),
delta: "hi".into(),
done: false,
},
Event::ToolStarted {
session_id: "s-1".into(),
agent: "engineer".into(),
agent_id: "spawn-1".into(),
tool: "bash".into(),
call_id: "c1".into(),
args_preview: "ls".into(),
},
Event::ToolFinished {
session_id: "s-1".into(),
agent: "engineer".into(),
agent_id: "spawn-1".into(),
tool: "bash".into(),
call_id: "c1".into(),
success: true,
result_preview: "ok".into(),
},
Event::ToolError {
session_id: "s-1".into(),
agent: "engineer".into(),
agent_id: "spawn-1".into(),
tool: "bash".into(),
call_id: "c1".into(),
error: "boom".into(),
},
Event::SearchPerformed {
session_id: "s-1".into(),
agent: "engineer".into(),
agent_id: "spawn-1".into(),
lane: "lexical".into(),
query: "q".into(),
hit_count: Some(1),
hits: vec![],
latency_ms: 1,
},
Event::MemoryRecalled {
session_id: "s-1".into(),
agent: "engineer".into(),
agent_id: "spawn-1".into(),
query: "q".into(),
results: vec![],
},
Event::AgentDone {
session_id: "s-1".into(),
agent: "engineer".into(),
agent_id: "spawn-1".into(),
status: "success".into(),
},
Event::AgentFailed {
session_id: "s-1".into(),
agent: "engineer".into(),
agent_id: "spawn-1".into(),
error: "boom".into(),
},
Event::PermissionRequested {
session_id: "s-1".into(),
request_id: "req-1".into(),
agent: "engineer".into(),
agent_id: "spawn-1".into(),
tool: "bash".into(),
subject: "rm -rf build".into(),
rule: "bash[rm *]".into(),
},
Event::PermissionResolved {
session_id: "s-1".into(),
request_id: "req-1".into(),
agent: "engineer".into(),
agent_id: "spawn-1".into(),
decision: "deny".into(),
source: "client".into(),
},
Event::TodosChanged {
session_id: "s-1".into(),
agent: "engineer".into(),
agent_id: "spawn-1".into(),
todos: vec![crate::events::TodoItem {
content: "write the test".into(),
status: crate::events::TodoStatus::InProgress,
}],
},
]
}
#[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 caches_are_empty_before_setup() {
let engine = CodeEngine::with_socket("/nonexistent/tcode.sock", 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_socket("/nonexistent/tcode.sock", None);
assert!(engine.picker("model").is_none());
}
#[test]
fn statusline_segments_reflect_active_workstream_and_clear_on_none() {
let state = EngineState::new(UdsRpcClient::new("/nonexistent/tcode.sock"), None, false);
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"
);
}
#[test]
fn session_shape_summary_names_the_solo_agent_and_root() {
let summary = session_shape_summary(&json!({
"no_delegate": true,
"binding": {"state": "directory", "root": "/tmp/proj"},
}));
assert_eq!(
summary,
"solo agent (no delegation), file tools rooted at /tmp/proj"
);
}
#[test]
fn session_shape_summary_names_the_projectless_scratch_root() {
let summary = session_shape_summary(&json!({
"no_delegate": true,
"binding": {"state": "projectless", "root": null},
}));
assert_eq!(
summary,
"solo agent (no delegation), projectless — file tools rooted at a scratch workspace"
);
}
#[test]
fn session_shape_summary_names_the_delegating_pm() {
let summary = session_shape_summary(&json!({
"no_delegate": false,
"binding": {"state": "git_repo", "root": "/tmp/repo"},
}));
assert_eq!(summary, "delegating PM, file tools rooted at /tmp/repo");
}
#[test]
fn cancel_unconfirmed_is_a_still_cancelling_outcome() {
let outcome = classify_cancel_error(EngineError::Rpc {
code: -32010,
message: "session s-1: cancellation requested but the task did not stop within 10s"
.to_string(),
data: None,
})
.expect("an unconfirmed cancel is an outcome, not a failure");
assert_eq!(
outcome,
CancelOutcome::StillCancelling {
detail: "session s-1: cancellation requested but the task did not stop within 10s"
.to_string()
}
);
}
#[test]
fn cancel_reply_reports_a_confirmed_stop() {
assert_eq!(
cancel_reply_from(Ok(CancelOutcome::Stopped)),
CancelReply::Stopped
);
assert_eq!(
cancel_reply_from(Ok(CancelOutcome::NoSession)),
CancelReply::Stopped
);
}
#[test]
fn cancel_reply_keeps_an_unconfirmed_cancel_distinct() {
let detail = "session s-1: cancellation requested but the task did not stop within 10s";
assert_eq!(
cancel_reply_from(Ok(CancelOutcome::StillCancelling {
detail: detail.to_string()
})),
CancelReply::StillCancelling {
detail: detail.to_string()
}
);
}
#[test]
fn cancel_reply_strips_the_rpc_code_from_a_refusal() {
let reply = cancel_reply_from(Err(EngineError::Rpc {
code: -32003,
message: "session s-1 already has a task running".to_string(),
data: None,
}));
assert_eq!(
reply,
CancelReply::Failed {
error: "session s-1 already has a task running".to_string()
}
);
let CancelReply::Failed { error } = &reply else {
panic!("a refusal is a failure: {reply:?}");
};
assert!(
!error.contains("-32003"),
"the wire code must not reach the user: {error}"
);
assert_eq!(
cancel_reply_from(Err(EngineError::NoSession)),
CancelReply::Failed {
error: EngineError::NoSession.to_string()
}
);
}
#[test]
fn any_other_refusal_stays_an_error() {
for code in [-32603, -32007, -32003] {
let err = classify_cancel_error(EngineError::Rpc {
code,
message: "nope".to_string(),
data: None,
})
.expect_err("only -32010 is an outcome");
assert!(
matches!(err, EngineError::Rpc { code: got, .. } if got == code),
"code {code} must pass through verbatim, got {err:?}"
);
}
}