use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use serde_json::{Value, json};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
use tokio::sync::oneshot;
use tokio::time::timeout;
use trusty_code::binding::ProjectBinding;
use trusty_code::tui_client::CodeEngine;
use trusty_code::tui_client::uds_rpc::UdsRpcClient;
use trusty_code_tui::{PermissionAnswer, ReplEvent, TuiEngine};
const WS_NAME: &str = "Feature X";
struct RealDaemon {
socket: PathBuf,
project: PathBuf,
stop: Option<oneshot::Sender<()>>,
_sockets: tempfile::TempDir,
_data: tempfile::TempDir,
_project_dir: tempfile::TempDir,
}
impl RealDaemon {
async fn start() -> Self {
let sockets = tempfile::tempdir().expect("socket tempdir");
let data = tempfile::tempdir().expect("data tempdir");
let project_dir = tempfile::tempdir().expect("project tempdir");
let socket = sockets.path().join("tcode.sock");
let project = project_dir
.path()
.canonicalize()
.expect("canonicalize project");
let binding = ProjectBinding::resolve(Some(project.clone())).expect("tempdir must bind");
let (stop, stopped) = oneshot::channel();
let serve_socket = socket.clone();
let serve_data = data.path().to_path_buf();
tokio::spawn(async move {
trusty_code::serve::uds::run_daemon_on(
binding,
&serve_socket,
Some(&serve_data),
async move {
let _ = stopped.await;
},
)
.await
});
wait_until_serving(&socket).await;
Self {
socket,
project,
stop: Some(stop),
_sockets: sockets,
_data: data,
_project_dir: project_dir,
}
}
fn engine(&self) -> CodeEngine {
CodeEngine::with_socket(self.socket.clone(), Some(self.project.clone()))
}
fn delegating_engine(&self) -> CodeEngine {
CodeEngine::with_socket_delegating(self.socket.clone(), Some(self.project.clone()))
}
fn projectless_engine(&self) -> CodeEngine {
CodeEngine::with_socket(self.socket.clone(), None)
}
fn client(&self) -> UdsRpcClient {
UdsRpcClient::new(self.socket.clone())
}
}
async fn only_session(daemon: &RealDaemon) -> Value {
let listed = daemon
.client()
.call("session.list", json!({}))
.await
.expect("session.list over the socket");
let sessions = listed["sessions"]
.as_array()
.expect("session.list returns an array")
.clone();
assert_eq!(sessions.len(), 1, "setup must have created one session");
sessions[0].clone()
}
fn splash_text(rx: &mut UnboundedReceiver<ReplEvent>) -> String {
drain(rx)
.iter()
.find_map(|event| match event {
ReplEvent::SplashUpdated(lines) => Some(lines.join("\n")),
_ => None,
})
.expect("setup must publish a startup splash")
}
fn connect_line(rx: &mut UnboundedReceiver<ReplEvent>) -> String {
drain(rx)
.iter()
.find_map(|event| match event {
ReplEvent::StatusMessage(text) if text.contains("connected to tcode daemon") => {
Some(text.clone())
}
_ => None,
})
.expect("setup must report the daemon it connected to")
}
impl Drop for RealDaemon {
fn drop(&mut self) {
if let Some(stop) = self.stop.take() {
let _ = stop.send(());
}
}
}
async fn wait_until_serving(socket: &Path) {
for _ in 0..200 {
if trusty_common::uds::socket_is_serving(socket, Duration::from_millis(200)).await {
return;
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
panic!("the daemon never began serving {}", socket.display());
}
fn drain(rx: &mut UnboundedReceiver<ReplEvent>) -> Vec<ReplEvent> {
let mut events = Vec::new();
while let Ok(event) = rx.try_recv() {
events.push(event);
}
events
}
#[tokio::test]
async fn tui_engine_end_to_end_with_http_port_closed() {
let daemon = RealDaemon::start().await;
let engine = daemon.engine();
let (tx, mut rx) = unbounded_channel();
engine.setup(tx).await.expect("setup over the socket");
let events = drain(&mut rx);
let session_line = events
.iter()
.find_map(|event| match event {
ReplEvent::StatusMessage(text) if text.contains("connected to tcode daemon") => {
Some(text.clone())
}
_ => None,
})
.expect("setup must report the daemon it connected to");
assert!(
session_line.contains(&daemon.socket.display().to_string()),
"the status line must name the socket, not a URL: {session_line}"
);
let client = daemon.client();
let listed = client
.call("session.list", json!({}))
.await
.expect("session.list over the socket");
let sessions = listed["sessions"]
.as_array()
.expect("session.list returns an array");
assert_eq!(sessions.len(), 1, "setup must have created one session");
let session_id = sessions[0]["id"]
.as_str()
.expect("a session carries an id")
.to_string();
let mut stream = client
.open_stream::<Value>("session.events", json!({"session_id": session_id}))
.await
.expect("session.events must open");
client
.call(
"session.send",
json!({"session_id": session_id, "input": "over the socket"}),
)
.await
.expect("session.send over the socket");
let mut saw_input = false;
for _ in 0..10 {
let frame = timeout(Duration::from_secs(10), stream.next_frame())
.await
.expect("a frame must arrive within the budget")
.expect("the stream must still be open")
.expect("the frame must not be a terminal error");
if frame.to_string().contains("over the socket") {
saw_input = true;
break;
}
}
assert!(saw_input, "the tail must carry the input that was sent");
engine
.cancel_session()
.await
.expect("cancel_session over the socket");
let status = client
.call("session.status", json!({"session_id": session_id}))
.await
.expect("session.status over the socket");
assert_eq!(
status["status"], "cancelled",
"the daemon performs the cancellation, not the client (DOC-39 §2.1 C-2)"
);
}
#[tokio::test]
async fn setup_creates_session_and_reports_active_workstream() {
let daemon = RealDaemon::start().await;
let client = daemon.client();
let created = client
.call("workstream.create", json!({"name": WS_NAME}))
.await
.expect("workstream.create over the socket");
let ws_id = created["id"].as_str().expect("a workstream carries an id");
client
.call("workstream.activate", json!({"id": ws_id}))
.await
.expect("workstream.activate over the socket");
let engine = daemon.engine();
let (tx, mut rx) = unbounded_channel();
engine.setup(tx).await.expect("setup");
let events = drain(&mut rx);
let updated = events
.iter()
.any(|event| matches!(event, ReplEvent::WorkstreamUpdated(ws) if ws.name == WS_NAME));
assert!(
updated,
"setup must report the active workstream: {events:?}"
);
assert!(
!engine.commands().is_empty(),
"setup must populate the commands cache"
);
assert!(
engine.picker("workstream").is_some(),
"setup must populate the workstream picker cache"
);
let line = events
.iter()
.find_map(|event| match event {
ReplEvent::StatusMessage(text) if text.contains("connected to tcode daemon") => {
Some(text.clone())
}
_ => None,
})
.expect("setup must report the daemon it connected to");
assert!(
line.contains(&format!("workstream {WS_NAME}")),
"the connect line must name the active workstream: {line}"
);
}
struct StubDaemon {
socket: PathBuf,
_dir: tempfile::TempDir,
seen: Arc<Mutex<Vec<String>>>,
requests: Arc<Mutex<Vec<Value>>>,
}
impl StubDaemon {
fn start(answers: Value, stream_frames: Vec<Value>) -> Self {
Self::start_inner(answers, stream_frames, true)
}
fn start_refusing_the_claim(answers: Value) -> Self {
Self::start_inner(answers, Vec::new(), false)
}
fn start_inner(answers: Value, stream_frames: Vec<Value>, serve_claim: bool) -> Self {
let dir = tempfile::tempdir().expect("socket tempdir");
let (listener, socket) = trusty_common::uds::test_support::bind_hardened_stub(dir.path())
.expect("bind the hardened stub socket");
let seen: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
let recorded = seen.clone();
let requests: Arc<Mutex<Vec<Value>>> = Arc::new(Mutex::new(Vec::new()));
let recorded_requests = requests.clone();
tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
let answers = answers.clone();
let frames = stream_frames.clone();
let serve_claim = serve_claim;
let recorded = recorded.clone();
let recorded_requests = recorded_requests.clone();
tokio::spawn(async move {
let mut reader = BufReader::new(stream);
let mut line = String::new();
if reader.read_line(&mut line).await.unwrap_or(0) == 0 {
return;
}
let request: Value = match serde_json::from_str(&line) {
Ok(request) => request,
Err(_) => return,
};
let method = request["method"].as_str().unwrap_or_default().to_string();
recorded
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(method.clone());
recorded_requests
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(request.clone());
let id = request["id"].clone();
if request["stream"] == json!(true) {
let is_claim = method == "session.events"
&& request["params"].get("after_seq").is_none();
let frames = if is_claim {
if serve_claim {
vec![json!({"session_id": "sess-1", "seq": 1})]
} else {
Vec::new()
}
} else {
frames
};
for frame in frames {
let body = format!(
"{}\n",
json!({
"jsonrpc": "2.0",
"id": id,
"stream": "item",
"result": frame,
})
);
let _ = reader.get_mut().write_all(body.as_bytes()).await;
}
let _ = reader.get_mut().flush().await;
return;
}
let result = answers.get(&method).cloned().unwrap_or_else(|| json!({}));
let body = format!(
"{}\n",
json!({"jsonrpc": "2.0", "id": id, "result": result})
);
let _ = reader.get_mut().write_all(body.as_bytes()).await;
let _ = reader.get_mut().flush().await;
});
}
});
Self {
socket,
_dir: dir,
seen,
requests,
}
}
fn engine(&self) -> CodeEngine {
CodeEngine::with_socket(self.socket.clone(), None)
}
fn seen(&self) -> Vec<String> {
self.seen.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
fn request_for(&self, method: &str) -> Option<Value> {
self.requests
.lock()
.unwrap_or_else(|e| e.into_inner())
.iter()
.find(|r| r["method"] == method)
.cloned()
}
}
fn stub_answers(active: Option<&str>) -> Value {
json!({
"session.create": {"id": "sess-1", "task": "tcode tui session", "status": "running"},
"task.run": {"session_id": "sess-1", "status": "running"},
"session.cancel": {},
"workstream.list": {
"active_workstream_id": active,
"workstreams": [{"id": "ws-1", "name": WS_NAME}],
},
})
}
#[tokio::test]
async fn handle_input_surfaces_visible_error_after_exhausting_reconnects() {
let stub = StubDaemon::start(stub_answers(Some("ws-1")), Vec::new());
let engine = stub.engine();
let (tx, mut rx) = unbounded_channel();
engine.setup(tx.clone()).await.expect("setup");
let result = timeout(
Duration::from_secs(60),
engine.handle_input("hello".to_string(), tx),
)
.await
.expect("handle_input must return rather than loop forever");
assert!(
result.is_err(),
"exhausting the reconnect budget must surface as an error"
);
let events = drain(&mut rx);
assert!(
events.iter().any(|event| matches!(
event,
ReplEvent::AssistantOutput {
done: true,
is_error: true,
..
}
)),
"the TUI must receive a visible terminal error, not just ConnectionLost: {events:?}"
);
}
#[tokio::test]
async fn subscribe_workstream_events_emits_activation_changed_with_wire_field_names() {
let frame = json!({
"session_id": "sess-1",
"event_type": "workstream_activation_changed",
"payload": {
"type": "workstream_activation_changed",
"new_active_id": "ws-2",
"prior_id": "ws-1",
},
});
let stub = StubDaemon::start(stub_answers(Some("ws-1")), vec![frame]);
let engine = stub.engine();
let (tx, mut rx) = unbounded_channel();
engine.setup(tx.clone()).await.expect("setup");
engine
.subscribe_workstream_events(tx)
.await
.expect("subscribe");
let observed = timeout(Duration::from_secs(20), async {
loop {
match rx.recv().await {
Some(ReplEvent::WorkstreamActivationChanged {
new_active_id,
prior_id,
}) => return (new_active_id, prior_id),
Some(_) => continue,
None => panic!("the event channel closed before the activation arrived"),
}
}
})
.await
.expect("an activation change must be forwarded");
assert_eq!(observed.0.as_deref(), Some("ws-2"));
assert_eq!(observed.1.as_deref(), Some("ws-1"));
assert!(
stub.seen().iter().any(|m| m == "workstream.events"),
"the subscription must call the stream method: {:?}",
stub.seen()
);
}
#[tokio::test]
async fn deactivation_with_no_replacement_refreshes_and_is_surfaced() {
let frame = json!({
"session_id": "sess-1",
"event_type": "workstream_activation_changed",
"payload": {
"type": "workstream_activation_changed",
"new_active_id": null,
"prior_id": "ws-1",
},
});
let stub = StubDaemon::start(stub_answers(Some("ws-1")), vec![frame]);
let engine = stub.engine();
let (tx, mut rx) = unbounded_channel();
engine.setup(tx.clone()).await.expect("setup");
engine
.subscribe_workstream_events(tx)
.await
.expect("subscribe");
let observed = timeout(Duration::from_secs(20), async {
loop {
match rx.recv().await {
Some(ReplEvent::WorkstreamActivationChanged {
new_active_id,
prior_id,
}) => return (new_active_id, prior_id),
Some(_) => continue,
None => panic!("the event channel closed before the deactivation arrived"),
}
}
})
.await
.expect("a deactivation must be forwarded");
assert_eq!(observed.0, None, "deactivation carries no new active id");
assert_eq!(observed.1.as_deref(), Some("ws-1"));
let calls = stub.seen();
let refreshes = calls.iter().filter(|m| *m == "workstream.list").count();
assert!(
refreshes >= 2,
"the cache must be refreshed beyond setup's own call: {calls:?}"
);
}
#[tokio::test]
async fn respond_permission_releases_a_suspended_call() {
let mut answers = stub_answers(Some("ws-1"));
answers["session.permission.respond"] = json!({"accepted": true});
let stub = StubDaemon::start(answers, Vec::new());
let engine = stub.engine();
let (tx, _rx) = unbounded_channel();
engine.setup(tx).await.expect("setup");
engine
.respond_permission(
"req-1".to_string(),
PermissionAnswer::AllowForSession {
pattern: Some("git *".to_string()),
},
)
.await
.expect("respond_permission");
let request = stub
.request_for("session.permission.respond")
.expect("the answer must reach the daemon");
let params = &request["params"];
assert_eq!(params["session_id"], "sess-1", "{request}");
assert_eq!(params["request_id"], "req-1", "{request}");
assert_eq!(
params["decision"], "allow_for_session",
"the daemon's own wire word, not a TUI-local spelling: {request}"
);
assert_eq!(
params["pattern"], "git *",
"an explicit grant width must cross verbatim: {request}"
);
}
#[tokio::test]
async fn respond_permission_without_a_session_is_a_noop() {
let stub = StubDaemon::start(stub_answers(Some("ws-1")), Vec::new());
let engine = stub.engine();
engine
.respond_permission("req-1".to_string(), PermissionAnswer::Deny)
.await
.expect("must not error without a session");
assert!(
stub.request_for("session.permission.respond").is_none(),
"no session means nothing to answer: {:?}",
stub.seen()
);
}
#[tokio::test]
async fn setup_opens_a_prompter_claim_stream() {
let stub = StubDaemon::start(stub_answers(Some("ws-1")), vec![json!({"seq": 1})]);
let engine = stub.engine();
let (tx, _rx) = unbounded_channel();
engine.setup(tx).await.expect("setup against the stub");
let seen = stub.seen();
assert_eq!(
seen.first().map(String::as_str),
Some("session.create"),
"the session must exist before anything can watch it: {seen:?}"
);
let claim = seen
.iter()
.position(|m| m == "session.events")
.unwrap_or_else(|| panic!("setup must open the prompter-claim stream: {seen:?}"));
assert_eq!(
claim, 1,
"the claim must be the FIRST thing after the session is created, so no \
run can precede it: {seen:?}"
);
assert!(
!seen.contains(&"task.run".to_string()),
"setup must not run anything: {seen:?}"
);
}
#[tokio::test]
async fn setup_fails_when_the_claim_stream_is_refused() {
let stub = StubDaemon::start_refusing_the_claim(stub_answers(None));
let engine = stub.engine();
let (tx, _rx) = unbounded_channel();
let err = engine
.setup(tx)
.await
.expect_err("an unwatchable session must not report a successful setup");
let rendered = format!("{err:#}");
assert!(
rendered.contains("closed"),
"the failure must name the stream that never opened: {rendered}"
);
assert!(
stub.seen().contains(&"session.events".to_string()),
"the claim must have been attempted: {:?}",
stub.seen()
);
}
#[tokio::test]
async fn tui_default_session_runs_the_solo_agent() {
let daemon = RealDaemon::start().await;
let engine = daemon.engine();
let (tx, mut rx) = unbounded_channel();
engine.setup(tx).await.expect("setup over the socket");
let session = only_session(&daemon).await;
assert_eq!(
session["no_delegate"],
json!(true),
"a default TUI session runs the solo agent: {session}"
);
assert_eq!(
session["binding"]["root"],
json!(daemon.project.display().to_string()),
"the session must be scoped to the bound project root: {session}"
);
let line = connect_line(&mut rx);
assert!(
line.contains("solo agent (no delegation)"),
"the connect line must state the agent shape: {line}"
);
let leaf = daemon
.project
.file_name()
.expect("a tempdir has a final component")
.to_string_lossy()
.to_string();
assert!(line.contains("home "), "{line}");
assert!(
line.contains(&leaf),
"the connect line must name the working root: {line}"
);
assert!(
!line.contains("session "),
"the session id is internal and must never be displayed: {line}"
);
}
#[tokio::test]
async fn tui_delegate_opt_in_creates_a_delegating_session() {
let daemon = RealDaemon::start().await;
let engine = daemon.delegating_engine();
let (tx, mut rx) = unbounded_channel();
engine.setup(tx).await.expect("setup over the socket");
let session = only_session(&daemon).await;
assert_eq!(
session["no_delegate"],
json!(false),
"--delegate must mint the PM shape: {session}"
);
let line = connect_line(&mut rx);
assert!(
line.contains("delegating PM"),
"the connect line must state the agent shape: {line}"
);
}
#[tokio::test]
async fn tui_projectless_default_session_runs_solo_in_a_scratch_root() {
let daemon = RealDaemon::start().await;
let engine = daemon.projectless_engine();
let (tx, mut rx) = unbounded_channel();
engine
.setup(tx)
.await
.expect("a projectless setup must succeed");
let session = only_session(&daemon).await;
assert_eq!(session["binding"]["state"], json!("projectless"));
assert_eq!(
session["no_delegate"],
json!(true),
"a projectless TUI session runs solo too: {session}"
);
let line = connect_line(&mut rx);
assert!(
line.contains("home projectless"),
"the connect line must say the session is unbound: {line}"
);
}
#[tokio::test]
async fn setup_publishes_a_splash_naming_the_project() {
let daemon = RealDaemon::start().await;
let engine = daemon.engine();
let (tx, mut rx) = unbounded_channel();
engine.setup(tx).await.expect("setup over the socket");
let session = only_session(&daemon).await;
let session_id = session["id"].as_str().expect("a session carries an id");
let splash = splash_text(&mut rx);
assert!(
splash.starts_with("🤖🤖🤖 tcode v"),
"the splash must lead with the robot header and the BINARY version: {splash}"
);
assert!(
splash.contains(&format!("({})", trusty_code::build_info::GIT_HASH)),
"the daemon must report its build sha over `health`: {splash}"
);
assert!(
!splash.contains(session_id),
"the session id is internal and must never be displayed: {splash}"
);
assert!(
splash.contains(&format!("project {}", daemon.project.display())),
"the splash must name the bound project: {splash}"
);
assert!(
splash.contains("agent solo agent (no delegation)"),
"the splash must name the delegation shape: {splash}"
);
assert!(
!splash.contains("warning:"),
"client and daemon are the same build here, so nothing must warn: {splash}"
);
}
#[tokio::test]
async fn setup_splash_says_projectless_when_unbound() {
let daemon = RealDaemon::start().await;
let engine = daemon.projectless_engine();
let (tx, mut rx) = unbounded_channel();
engine.setup(tx).await.expect("setup over the socket");
let splash = splash_text(&mut rx);
assert!(
splash.contains("project projectless"),
"an unbound session must say so: {splash}"
);
}