use std::os::unix::fs::PermissionsExt as _;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use serde_json::{Value, json};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::UnixListener;
use tokio::sync::mpsc::unbounded_channel;
use tokio::time::timeout;
use trusty_code_tui::ReplEvent;
use super::EngineState;
use crate::tui_client::uds_rpc::UdsRpcClient;
type SeenCursors = Arc<Mutex<Vec<Option<u64>>>>;
fn item_frame(id: &Value, seq: u64, event: Value) -> String {
let envelope = json!({
"session_id": "sess-1",
"seq": seq,
"at": "2026-09-08T00:00:00Z",
"kind": event["type"],
"event": event,
});
format!(
"{}\n",
json!({"jsonrpc": "2.0", "id": id, "stream": "item", "result": envelope})
)
}
async fn spawn_truncating_daemon(socket: PathBuf, seen: SeenCursors) {
let dir = socket.parent().expect("the socket has a parent");
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
.expect("harden the stub socket directory");
let listener = UnixListener::bind(&socket).expect("bind the stub socket");
std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600))
.expect("harden the stub socket");
tokio::spawn(async move {
let mut answered = 0u32;
loop {
let Ok((stream, _)) = listener.accept().await else {
return;
};
let seen = seen.clone();
let attempt = answered;
answered += 1;
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 id = request["id"].clone();
if request["method"] != "session.events" {
let body = format!("{}\n", json!({"jsonrpc": "2.0", "id": id, "result": {}}));
let _ = reader.get_mut().write_all(body.as_bytes()).await;
let _ = reader.get_mut().flush().await;
return;
}
seen.lock()
.unwrap_or_else(|e| e.into_inner())
.push(request["params"]["after_seq"].as_u64());
if attempt == 0 {
let frame = item_frame(
&id,
7,
json!({
"type": "session_input",
"session_id": "sess-1",
"input": "partial",
}),
);
let _ = reader.get_mut().write_all(frame.as_bytes()).await;
let _ = reader.get_mut().flush().await;
return;
}
let frame = item_frame(
&id,
8,
json!({"type": "session_done", "session_id": "sess-1", "status": "finished"}),
);
let _ = reader.get_mut().write_all(frame.as_bytes()).await;
let _ = reader.get_mut().flush().await;
let end = format!("{}\n", json!({"jsonrpc": "2.0", "id": id, "stream": "end"}));
let _ = reader.get_mut().write_all(end.as_bytes()).await;
let _ = reader.get_mut().flush().await;
});
}
});
}
#[tokio::test]
async fn stream_client_reconnects_after_a_truncated_tail() {
let dir = tempfile::tempdir().expect("socket tempdir");
let socket = dir.path().join("stub.sock");
let seen: SeenCursors = Arc::new(Mutex::new(Vec::new()));
spawn_truncating_daemon(socket.clone(), seen.clone()).await;
let state = EngineState::new(UdsRpcClient::new(socket), None, false);
let (tx, mut rx) = unbounded_channel();
timeout(
Duration::from_secs(30),
state.pump_session_events("sess-1", &tx),
)
.await
.expect("the pump must finish within the budget")
.expect("the reconnect must carry the turn to its terminal event");
let cursors = seen.lock().unwrap_or_else(|e| e.into_inner()).clone();
assert_eq!(
cursors,
vec![None, Some(7)],
"the first request opens bare and the reconnect resumes above the forwarded seq"
);
let mut saw_connection_lost = false;
while let Ok(event) = rx.try_recv() {
if matches!(event, ReplEvent::ConnectionLost { .. }) {
saw_connection_lost = true;
}
}
assert!(
saw_connection_lost,
"a truncated tail must render as ConnectionLost, not silently"
);
}
#[tokio::test]
async fn session_stream_silence_is_bounded_not_infinite() {
let dir = tempfile::tempdir().expect("socket tempdir");
let socket = dir.path().join("silent.sock");
std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700))
.expect("harden the silent socket directory");
let listener = UnixListener::bind(&socket).expect("bind the silent socket");
std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600))
.expect("harden the silent socket");
let accept_task = tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
std::mem::forget(stream);
}
});
let state = EngineState::new(
UdsRpcClient::new(socket).with_stream_frame_timeout(Duration::from_millis(200)),
None,
false,
);
let (tx, mut rx) = unbounded_channel();
let result = timeout(
Duration::from_secs(120),
state.pump_session_events("sess-1", &tx),
)
.await
.expect("the pump must return rather than hang");
assert!(
result.is_err(),
"exhausting the reconnect budget against a silent daemon must be an error"
);
let mut saw_connection_lost = false;
while let Ok(event) = rx.try_recv() {
if matches!(event, ReplEvent::ConnectionLost { .. }) {
saw_connection_lost = true;
}
}
assert!(
saw_connection_lost,
"a wedged daemon must surface as ConnectionLost rather than a silent hang"
);
accept_task.abort();
}