use super::*;
use tokio::sync::mpsc;
use trusty_mcp::Request;
fn test_ctx() -> ConnectionContext {
let (tx, _rx) = mpsc::unbounded_channel();
ConnectionContext::new(tx)
}
#[tokio::test]
async fn register_wires_every_session_method() {
let registry = Arc::new(SessionRegistry::new());
let mut router = Router::new();
register(
&mut router,
registry.clone(),
crate::workstreams::test_shared_store().await,
);
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let cases: &[(&str, Value)] = &[
("session.list", json!({})),
("session.status", json!({"session_id": session.id})),
(
"session.send",
json!({"session_id": session.id, "input": "hi"}),
),
("session.attach", json!({"session_id": session.id})),
("session.detach", json!({"session_id": session.id})),
("session.get_transcript", json!({"session_id": session.id})),
("session.get_goals", json!({"session_id": session.id})),
("session.get_readiness", json!({"session_id": session.id})),
("session.get_agents", json!({"session_id": session.id})),
(
"session.get_context_budget",
json!({"session_id": session.id}),
),
(
"session.get_search_audit",
json!({"session_id": session.id}),
),
];
for (method, params) in cases {
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: method.to_string(),
params: Some(params.clone()),
};
let resp = router.dispatch(req, &test_ctx()).await;
assert!(
resp.error.is_none(),
"{method} should succeed, got {:?}",
resp.error
);
}
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: "session.cancel".to_string(),
params: Some(json!({"session_id": session.id})),
};
let resp = router.dispatch(req, &test_ctx()).await;
assert!(
resp.error.is_none(),
"session.cancel should succeed, got {:?}",
resp.error
);
}
#[tokio::test]
async fn register_wires_set_goal_and_clear_goal() {
let registry = Arc::new(SessionRegistry::new());
let mut router = Router::new();
register(
&mut router,
registry.clone(),
crate::workstreams::test_shared_store().await,
);
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
for method in ["session.set_goal", "session.clear_goal"] {
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: method.to_string(),
params: Some(json!({"session_id": session.id, "slot": 1, "text": "x"})),
};
let resp = router.dispatch(req, &test_ctx()).await;
let error = resp
.error
.unwrap_or_else(|| panic!("{method} must error (no transcript yet)"));
assert_eq!(error.code, -32003, "{method} wrong error code");
}
}
#[tokio::test]
async fn create_rejects_empty_task() {
let registry = SessionRegistry::new();
let workstreams = crate::workstreams::test_shared_store().await;
let err = create(®istry, &workstreams, json!({"task": " "}), test_ctx())
.await
.unwrap_err();
assert_eq!(err.code, -32003);
}
#[tokio::test]
async fn create_defaults_to_the_solo_agent() {
let registry = SessionRegistry::new();
let workstreams = crate::workstreams::test_shared_store().await;
let value = create(
®istry,
&workstreams,
json!({"task": "add a doc comment to fn X"}),
test_ctx(),
)
.await
.expect("create must succeed");
assert_eq!(
value["no_delegate"],
json!(true),
"an interactive session defaults to the solo agent; got {value}"
);
}
#[tokio::test]
async fn create_with_delegate_true_keeps_the_delegating_pm() {
let registry = SessionRegistry::new();
let workstreams = crate::workstreams::test_shared_store().await;
let value = create(
®istry,
&workstreams,
json!({"task": "ship the feature", "delegate": true}),
test_ctx(),
)
.await
.expect("create must succeed");
assert_eq!(
value["no_delegate"],
json!(false),
"delegate: true must mint the PM shape; got {value}"
);
}
#[tokio::test]
async fn create_without_project_defaults_to_the_solo_agent() {
let registry = SessionRegistry::new();
let workstreams = crate::workstreams::test_shared_store().await;
let value = create(
®istry,
&workstreams,
json!({"task": "just chat"}),
test_ctx(),
)
.await
.expect("a projectless create must stay valid");
assert_eq!(value["binding"]["state"], "projectless");
assert_eq!(
value["no_delegate"],
json!(true),
"a projectless session runs solo against the scratch root; got {value}"
);
}
#[tokio::test]
async fn create_returns_running_session() {
let registry = SessionRegistry::new();
let workstreams = crate::workstreams::test_shared_store().await;
let result = create(
®istry,
&workstreams,
json!({"task": "do it"}),
test_ctx(),
)
.await
.unwrap();
assert_eq!(result["status"], "running");
assert_eq!(result["task"], "do it");
}
#[tokio::test]
async fn list_returns_sessions_key() {
let registry = SessionRegistry::new();
registry.create("a".to_string(), None, crate::binding::ProjectBinding::None);
let result = list(®istry, Value::Null, test_ctx()).await.unwrap();
assert_eq!(result["sessions"].as_array().unwrap().len(), 1);
}
#[tokio::test]
async fn status_unknown_session_maps_to_session_not_found() {
let registry = SessionRegistry::new();
let err = status(®istry, json!({"session_id": "nope"}), test_ctx())
.await
.unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn get_transcript_unknown_session_maps_to_session_not_found() {
let registry = SessionRegistry::new();
let err = get_transcript(®istry, json!({"session_id": "nope"}), test_ctx())
.await
.unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn get_transcript_on_never_run_session_is_empty() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let result = get_transcript(®istry, json!({"session_id": session.id}), test_ctx())
.await
.unwrap();
assert_eq!(result["session_id"], session.id);
assert_eq!(result["turns"].as_array().unwrap().len(), 0);
assert_eq!(result["cost_usd"], Value::Null);
}
#[tokio::test]
async fn send_unknown_session_maps_to_session_not_found() {
let registry = SessionRegistry::new();
let err = send(
®istry,
json!({"session_id": "nope", "input": "hi"}),
test_ctx(),
)
.await
.unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn attach_unknown_session_maps_to_session_not_found() {
let registry = SessionRegistry::new();
let err = attach(®istry, json!({"session_id": "nope"}), test_ctx())
.await
.unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn detach_unknown_session_maps_to_session_not_found() {
let registry = SessionRegistry::new();
let err = detach(®istry, json!({"session_id": "nope"}), test_ctx())
.await
.unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn cancel_unknown_session_maps_to_session_not_found() {
let registry = SessionRegistry::new();
let err = cancel(®istry, json!({"session_id": "nope"}), test_ctx())
.await
.unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn cancel_executing_session_requests_cooperative_cancel() {
let registry = Arc::new(SessionRegistry::new());
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let flag = registry.begin_execution(&session.id).unwrap();
spawn_flag_watching_run(®istry, &session.id, Arc::clone(&flag));
cancel(®istry, json!({"session_id": &session.id}), test_ctx())
.await
.unwrap();
assert!(
flag.load(std::sync::atomic::Ordering::Relaxed),
"the shared cancel flag must have been set"
);
}
fn spawn_flag_watching_run(
registry: &Arc<SessionRegistry>,
session_id: &str,
flag: Arc<std::sync::atomic::AtomicBool>,
) {
let registry_for_task = Arc::clone(registry);
let id = session_id.to_string();
let handle = tokio::spawn(async move {
while !flag.load(std::sync::atomic::Ordering::Relaxed) {
tokio::time::sleep(Duration::from_millis(5)).await;
}
let _ = registry_for_task.finish(&id, crate::session::SessionStatus::Cancelled);
registry_for_task.finish_execution(&id);
});
registry.attach_execution_handle(session_id, handle);
}
#[tokio::test]
async fn cancel_waits_for_the_task_to_stop_before_reporting() {
let registry = Arc::new(SessionRegistry::new());
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let flag = registry.begin_execution(&session.id).unwrap();
spawn_flag_watching_run(®istry, &session.id, Arc::clone(&flag));
cancel(®istry, json!({"session_id": &session.id}), test_ctx())
.await
.unwrap();
assert!(
!registry.is_executing(&session.id),
"cancel must not return while the daemon-side task is still running"
);
}
#[tokio::test]
async fn a_prompt_right_after_cancel_is_accepted_not_rejected() {
let registry = Arc::new(SessionRegistry::new());
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let flag = registry.begin_execution(&session.id).unwrap();
spawn_flag_watching_run(®istry, &session.id, Arc::clone(&flag));
cancel(®istry, json!({"session_id": &session.id}), test_ctx())
.await
.unwrap();
assert!(
!registry.is_executing(&session.id),
"the cancelled run must have released its execution slot"
);
assert_eq!(
registry.status(&session.id).unwrap().status.as_str(),
"cancelled",
"the run really did land Cancelled — that is the state the next prompt \
has to be accepted from"
);
let started = registry.begin_execution(&session.id);
assert!(
started.is_ok(),
"a prompt on the SAME session right after cancel must start, got {:?}",
started.err()
);
assert_eq!(
registry.status(&session.id).unwrap().status.as_str(),
"running",
"resuming must publish the same Running transition every other resume does"
);
}
#[tokio::test]
async fn cancel_that_cannot_confirm_the_stop_is_an_error() {
let registry = Arc::new(SessionRegistry::new());
let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let _flag = registry.begin_execution(&session.id).unwrap();
let err = cancel(®istry, json!({"session_id": &session.id}), test_ctx())
.await
.expect_err("an unconfirmable stop must not report success");
assert_eq!(err.code, -32010, "unexpected error shape: {err:?}");
assert_eq!(
err.data,
Some(json!({"error_type": "cancel_unconfirmed"})),
"an unconfirmed cancel must be distinguishable from a daemon fault"
);
let status = registry.status(&session.id).unwrap();
assert_ne!(
status.status.as_str(),
"cancelled",
"a cancel that could not be confirmed must not claim the session stopped"
);
}
#[test]
fn the_cancel_grace_fits_inside_the_clients_call_budget() {
for (client, budget) in [
(
"tui_client::uds_rpc",
crate::tui_client::uds_rpc::DEFAULT_CALL_TIMEOUT,
),
(
"cli_client::stdio",
crate::cli_client::stdio::DEFAULT_CALL_TIMEOUT,
),
] {
assert!(
CANCEL_CONFIRM_GRACE < budget,
"{client}: the daemon's answer must arrive inside the client's call \
budget: grace {CANCEL_CONFIRM_GRACE:?} vs budget {budget:?}"
);
assert!(
CANCEL_CONFIRM_GRACE + CANCEL_ANSWER_HEADROOM <= budget,
"{client}: the grace must leave headroom for the reply itself: \
grace {CANCEL_CONFIRM_GRACE:?} + headroom {CANCEL_ANSWER_HEADROOM:?} \
vs budget {budget:?}"
);
}
}