//! The daemon, end to end over its own socket.//!//! **No real agent is ever started here, on any machine.** The child is a//! three-line shell script this test writes into a scratch directory and names//! `claude`, reached through a `PATH` the spawn request carries — so the argv//! the adapter builds really is handed to a program called `claude`, and the//! owner's subscription is never touched. The real binary is not on the Linux//! CI runner at all, and must not be run on the Mac where it is.//!//! What this proves is the seam phase 3 will build on: a spawn makes a real//! terminal, an attach replays the scrollback and then streams live, typing//! reaches the child, an exit is reported, a permission hook BLOCKS until the//! phone answers and gets back its agent's own dialect, and `list` still//! answers for a session after the process has gone.use std::collections::BTreeMap;use std::sync::Arc;use std::time::Duration;use base64::Engineas _;use cotton_session_host::clock::FixedClock;use cotton_session_host::data_dir::Layout;use cotton_session_host::login_env::LoginEnv;use cotton_session_host::protocol::{ line, parse, Decision, Event, PermissionMode, Request, SessionState, Task, TaskStatus, Tool,};use cotton_session_host::pty::StopSchedule;use cotton_session_host::serve::Host;use tokio::io::{AsyncBufReadExtas _, AsyncWriteExtas _, BufReader};use tokio::net::UnixStream;const CLOCK: &str = "2026-09-18T09:00:00Z";structRunning { dir: tempfile::TempDir, layout: Layout, task: tokio::task::JoinHandle<()>,}implDropforRunning {fn drop(&mutself) {self.task.abort(); }}asyncfn host_over(dir: tempfile::TempDir, layout: Layout) -> Running { host_over_in(dir, layout, LoginEnv::inherited()).await}asyncfn host_over_in(dir: tempfile::TempDir, layout: Layout, login: LoginEnv) -> Running { host_over_in_flavor(dir, layout, login, cotton_session_host::data_dir::Flavor::Dev).await}asyncfn host_over_in_flavor( dir: tempfile::TempDir, layout: Layout, login: LoginEnv, flavor: cotton_session_host::data_dir::Flavor,) -> Running {let host = Arc::new(Host::new( layout.clone(),Arc::new(FixedClock::at(CLOCK)),"/does/not/matter/cotton-session-host".to_string(), flavor, ) .expect("the host comes up") .in_login_env(login) .with_schedules(StopSchedule { interrupt_grace: Duration::from_millis(300), terminate_grace: Duration::from_millis(300), },Duration::from_millis(400), ), );let listener = host.bind().await.expect("the socket binds");let task = tokio::spawn(asyncmove {let _ = host.run(listener).await; });Running { dir, layout, task }}asyncfn start() -> Running {let dir = tempfile::tempdir().expect("a scratch directory");let layout = Layout::new(dir.path().join("CottonDB")); host_over(dir, layout).await}// RULE: A session request cannot change the host's flavor for Cotton hooks and helper descendants; the declared host flavor wins over login and request environments.#[tokio::test]asyncfn session_helpers_keep_the_hosts_flavor_over_the_request() {for flavor in cotton_session_host::data_dir::Flavor::ALL {let dir = tempfile::tempdir().unwrap();let layout = Layout::new(dir.path().join("invented-host"));let login = LoginEnv::from_vars(BTreeMap::from([ ("COTTON_FLAVOR".into(), flavor.other().as_str().into()), ]));let running = host_over_in_flavor(dir, layout, login, flavor).await;let bin = stand_in_agent(&running, "printf 'HELPER_FLAVOR=%s\\n' \"$COTTON_FLAVOR\"");letmut request = spawn_request("s-flavor", &bin);ifletRequest::Spawn { env, .. } = &mut request { env.insert("COTTON_FLAVOR".into(), flavor.other().as_str().into()); }letmut client = Client::connect(&running).await; client.send(&request).await; assert!(matches!(client.next("spawn").await, Event::Spawned { .. }));letmut viewer = Client::connect(&running).await; viewer.send(&Request::Attach { session_id: "s-flavor".into(), cols: 80, rows: 24, from_offset: None, }).await;let said = viewer.terminal_until("HELPER_FLAVOR=").await; assert!(said.contains(&format!("HELPER_FLAVOR={}", flavor.as_str())), "{said}"); }}/// A directory holding a program called `claude` that is a shell script.////// It is NOT Claude Code. It exists so the adapter's argv is handed to/// something named `claude` without a language model, a login or a minute of/// anybody's usage window on the other end of it.fn stand_in_agent(running: &Running, script: &str) -> String {let bin = running.dir.path().join("stand-in-bin"); std::fs::create_dir_all(&bin).expect("the stand-in directory is made");let path = bin.join("claude"); std::fs::write(&path, format!("#!/bin/sh\n{script}\n")).expect("the stand-in is written"); #[cfg(unix)] {use std::os::unix::fs::PermissionsExtas _; std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)) .expect("the stand-in is executable"); } bin.display().to_string()}fn spawn_request(session_id: &str, bin: &str) -> Request {Request::Spawn { resume_from: None, launch_id: "launch-1".to_string(), session_id: Some(session_id.to_string()), tool: Tool::Claude, argv_extras: Vec::new(), cwd: "/".to_string(),// The PATH the CHILD resolves its program on, with the stand-in// directory FIRST — which is what keeps the real `claude` out of this// suite even on a Mac that has one. The two system directories are// named rather than inherited, so the stand-in's own `sleep` resolves// the same way on the Mac and on the Linux `rust` job; `/usr/bin` has// no `sleep` on macOS and `/bin` may be a symlink into `/usr/bin` on// Linux, so both are listed and one of them always answers. env: BTreeMap::from([ ("PATH".to_string(), format!("{bin}:/usr/bin:/bin")), ("TERM".to_string(), "xterm-256color".to_string()), ]), cols: 80, rows: 24, permission_mode: PermissionMode::Bypass, }}/// One connection, with a line reader on it.structClient { write: tokio::net::unix::OwnedWriteHalf, lines: tokio::io::Lines<BufReader<tokio::net::unix::OwnedReadHalf>>,}implClient {asyncfn connect(running: &Running) -> Self {let stream = UnixStream::connect(running.layout.socket()) .await .expect("a client connects");let (read, write) = stream.into_split();Self { write, lines: BufReader::new(read).lines(), } }asyncfn send(&mutself, request: &Request) {let text = line(request).expect("the request encodes");self.write .write_all(text.as_bytes()) .await .expect("the request is written");self.write.flush().await.expect("it flushes"); }asyncfn next(&mutself, waiting_for: &str) -> Event {let text = tokio::time::timeout(Duration::from_secs(15), self.lines.next_line()) .await .unwrap_or_else(|_| panic!("nothing arrived while waiting for {waiting_for}")) .expect("the socket is readable") .unwrap_or_else(|| panic!("the host hung up while waiting for {waiting_for}")); parse(&text).unwrap_or_else(|error| panic!("{text} is not an event — {error}")) }asyncfn next_matching(&mutself, waiting_for: &str, wanted: implFn(&Event) -> bool) -> Event {loop {let event = self.next(waiting_for).await;if wanted(&event) {return event; } } }/// Everything the attached terminal says, until `wanted` appears in it.asyncfn terminal_until(&mutself, wanted: &str) -> String {letmut seen = String::new();for _ in0..200 {ifletEvent::Data { b, .. } = self .next_matching("terminal output", |event| { matches!(event, Event::Data { .. }) }) .await {let bytes = base64::engine::general_purpose::STANDARD .decode(b.as_bytes()) .expect("terminal bytes are base64"); seen.push_str(&String::from_utf8_lossy(&bytes));if seen.contains(wanted) {return seen; } } } panic!("{wanted:?} never appeared — the terminal said {seen:?}"); }}#[tokio::test]asyncfn a_second_host_over_the_same_data_directory_is_refused_rather_than_displacing_the_first() {let running = start().await;let second = Host::new( running.layout.clone(),Arc::new(FixedClock::at(CLOCK)),"/does/not/matter/cotton-session-host".to_string(), cotton_session_host::data_dir::Flavor::Dev, ) .expect("a second host is constructible");let error = second.bind().await.expect_err("but it may not bind"); assert!( error.to_string().contains("already serving"),"the refusal says who is there — got {error}" );}#[tokio::test]asyncfn the_socket_is_the_owner_s_alone() {let running = start().await;use std::os::unix::fs::PermissionsExtas _;let mode = std::fs::metadata(running.layout.socket()) .expect("the socket is there") .permissions() .mode() & 0o777; assert_eq!( mode, 0o600,"anything that can write this socket can run a process as the person" );}/// The socket node a `kill -9` leaves behind: bound, then closed, never/// unlinked.////// **BOUND AND NEVER LISTENED — and never through a `UnixListener`.** This/// test binary forks: every `spawn` in the tests beside this one goes through/// `pty-process`, whose `pre_exec` makes `std` `fork(2)` the whole process,/// and between the fork and the `exec` the child holds a copy of EVERY open/// descriptor — close-on-exec closes them at the exec, not at the fork. A/// listener bound here and dropped is still a live listener in a child that/// has not exec'd yet, and on a loaded machine that window is wide enough for/// the connect in `Host::bind` to land in it and answer "somebody is serving"/// (Cotton note "Repo landmines — why the build's rules exist", the fork-window entry). A socket that/// never called `listen(2)` is refused by the kernel whoever holds it —/// `ECONNREFUSED` on macOS and Linux both — so this leaves exactly a crash's/// node and nothing a fork can keep alive. `std` has no bound-only stream/// socket, hence the three libc calls.fn leave_a_stale_socket_node(path: &std::path::Path) {use std::os::unix::ffi::OsStrExtas _;let bytes = path.as_os_str().as_bytes();// SAFETY: `sockaddr_un` is plain data, so all-zero is a valid value; the// path is checked to fit `sun_path` with its terminating zero; `fd` is a// descriptor this function opened and closes before returning.unsafe {letmut addr: libc::sockaddr_un = std::mem::zeroed(); addr.sun_family = libc::AF_UNIX as libc::sa_family_t; assert!( bytes.len() < addr.sun_path.len(),"the scratch path fits a unix socket address" );for (slot, byte) in addr.sun_path.iter_mut().zip(bytes) { *slot = *byte as libc::c_char; }let fd = libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0); assert!(fd >= 0, "a socket: {}", std::io::Error::last_os_error());let bound = libc::bind( fd, std::ptr::addr_of!(addr).cast::<libc::sockaddr>(), std::mem::size_of::<libc::sockaddr_un>() as libc::socklen_t, ); assert_eq!(bound, 0, "a bind: {}", std::io::Error::last_os_error()); libc::close(fd); }}#[tokio::test]asyncfn a_stale_socket_left_by_a_crash_is_reclaimed_but_a_live_one_never_is() {let dir = tempfile::tempdir().expect("a scratch directory");let layout = Layout::new(dir.path().join("CottonDB")); std::fs::create_dir_all(layout.root()).expect("the directory is made"); leave_a_stale_socket_node(&layout.socket()); assert!(layout.socket().exists());let host = Host::new( layout.clone(),Arc::new(FixedClock::at(CLOCK)),"/does/not/matter".to_string(), cotton_session_host::data_dir::Flavor::Dev, ) .expect("the host comes up"); drop(host.bind().await.expect("the stale node is reclaimed"));}#[tokio::test]asyncfn something_that_is_not_a_socket_in_the_way_is_named_never_deleted() {let dir = tempfile::tempdir().expect("a scratch directory");let layout = Layout::new(dir.path().join("CottonDB")); std::fs::create_dir_all(layout.root()).expect("the directory is made"); std::fs::write(layout.socket(), b"somebody else's file").expect("it is written");let host = Host::new( layout.clone(),Arc::new(FixedClock::at(CLOCK)),"/does/not/matter".to_string(), cotton_session_host::data_dir::Flavor::Dev, ) .expect("the host comes up");let error = host.bind().await.expect_err("it refuses"); assert!( error.to_string().contains("is in the way"),"the refusal names the path — got {error}" ); assert!( layout.socket().exists(),"a host never deletes a file it does not understand out of the data directory" );}#[tokio::test]asyncfn a_spawn_makes_a_real_terminal_and_an_attach_replays_then_streams_it() {let running = start().await;let bin = stand_in_agent( &running,"echo ready-for-work\nread line\necho \"you-said-$line\"\nexit 0", );letmut client = Client::connect(&running).await; client.send(&spawn_request("s-1", &bin)).await;letEvent::Spawned { session_id, pid, .. } = client.next("the spawn's answer").awaitelse { panic!("a spawn answers `spawned`"); }; assert_eq!(session_id, "s-1"); assert!(pid.is_some(), "a spawned session has a process");// A SECOND connection attaches, the way the app's terminal tab will.letmut viewer = Client::connect(&running).await; viewer .send(&Request::Attach { session_id: "s-1".to_string(), cols: 100, rows: 30, from_offset: None, }) .await;letEvent::Attached { offset, .. } = viewer .next_matching("the attach", |event| matches!(event, Event::Attached { .. })) .awaitelse { panic!("an attach answers `attached`"); }; assert_eq!(offset, 0, "the first viewer starts at the beginning"); assert!(viewer.terminal_until("ready-for-work").await.contains("ready-for-work"));// Typing on the first connection reaches the child, and the SECOND// connection sees it — one terminal, many viewers. client .send(&Request::Write { session_id: "s-1".to_string(), b: base64::engine::general_purpose::STANDARD.encode(b"cotton\n"), }) .await; assert!(viewer.terminal_until("you-said-cotton").await.contains("you-said-cotton"));}#[tokio::test]asyncfn a_second_attach_replays_the_scrollback_it_missed() {let running = start().await;let bin = stand_in_agent(&running, "echo said-before-anyone-looked\nsleep 20");letmut client = Client::connect(&running).await; client.send(&spawn_request("s-1", &bin)).await; assert!(matches!( client.next("the spawn's answer").await,Event::Spawned { .. } ));// Wait for the line to be in the ring before anybody attaches.letmut first = Client::connect(&running).await; first .send(&Request::Attach { session_id: "s-1".to_string(), cols: 80, rows: 24, from_offset: None, }) .await; first.terminal_until("said-before-anyone-looked").await;// Now a viewer that was never here at all gets the same bytes replayed.letmut late = Client::connect(&running).await; late.send(&Request::Attach { session_id: "s-1".to_string(), cols: 80, rows: 24, from_offset: None, }) .await; assert!(matches!( late.next_matching("the attach", |event| matches!(event, Event::Attached { .. })) .await,Event::Attached { .. } )); assert!(late .terminal_until("said-before-anyone-looked") .await .contains("said-before-anyone-looked"));}#[tokio::test]asyncfn a_subscriber_is_told_when_a_session_exits_and_the_index_remembers_how() {let running = start().await;let bin = stand_in_agent(&running, "exit 5");letmut watcher = Client::connect(&running).await; watcher.send(&Request::Subscribe).await;letmut client = Client::connect(&running).await; client.send(&spawn_request("s-1", &bin)).await; assert!(matches!( client.next("the spawn's answer").await,Event::Spawned { .. } ));letEvent::Exited { code, .. } = watcher .next_matching("the exit", |event| matches!(event, Event::Exited { .. })) .awaitelse { panic!("an exit is an exit event"); }; assert_eq!(code, Some(5)); client.send(&Request::List).await;letEvent::Sessions { sessions } = client .next_matching("the session list", |event| { matches!(event, Event::Sessions { .. }) }) .awaitelse { panic!("a list answers with sessions"); }; assert_eq!(sessions.len(), 1); assert_eq!(sessions[0].state, SessionState::Ended); assert_eq!(sessions[0].exit_code, Some(5)); assert_eq!(sessions[0].ended_at.as_deref(), Some(CLOCK));}/// RULE: A session that ends within a second of starting is reported with an error — the child's last line, or that it printed nothing — never as a bare end, so a launch that died says why on its row.#[tokio::test]asyncfn a_session_that_dies_at_once_is_reported_with_its_last_line() {for (script, wanted) in [ ("echo 'starting' ; echo 'Error: Cannot use settings file: Refusing to read a file whose path could not be vetted' >&2 ; exit 1",Some("Error: Cannot use settings file: Refusing to read a file whose path could not be vetted")), ("exit 0", None), ] {let running = start().await;let bin = stand_in_agent(&running, script);letmut watcher = Client::connect(&running).await; watcher.send(&Request::Subscribe).await;letmut client = Client::connect(&running).await; client.send(&spawn_request("s-quick", &bin)).await; assert!(matches!(client.next("the spawn's answer").await, Event::Spawned { .. }));letEvent::Exited { error, .. } = watcher .next_matching("the exit", |event| matches!(event, Event::Exited { .. })) .awaitelse { panic!("an exit is an exit event"); };let error = error.unwrap_or_else(|| panic!("{script}: a session that ended at once recorded no error"));match wanted {Some(line) => assert_eq!(error, line),None => assert!(error.contains("printed nothing"), "{error}"), } }}#[tokio::test]asyncfn a_stop_ends_a_running_session() {let running = start().await;// `exec`, so the signal lands on the process it was aimed at. Without it// the stand-in is a SHELL waiting on a child, and a shell's answer to// SIGINT is its own: `bash` re-raises it and dies by signal 2, `dash`// reports 130 as an exit code — which made this case pass on the Mac and// fail on the Linux `rust` job.let bin = stand_in_agent(&running, "exec sleep 60");letmut watcher = Client::connect(&running).await; watcher.send(&Request::Subscribe).await;letmut client = Client::connect(&running).await; client.send(&spawn_request("s-1", &bin)).await; assert!(matches!( client.next("the spawn's answer").await,Event::Spawned { .. } )); client .send(&Request::Stop { session_id: "s-1".to_string(), }) .await;letEvent::Exited { code, signal, .. } = watcher .next_matching("the exit", |event| matches!(event, Event::Exited { .. })) .awaitelse { panic!("a stopped session exits"); }; assert_eq!( signal,Some(2),"SIGINT was enough for a sleeping child — it exited {code:?}/{signal:?} instead" );}#[tokio::test]asyncfn a_permission_hook_blocks_until_the_phone_answers_and_gets_claude_s_dialect_back() {let running = start().await;let bin = stand_in_agent(&running, "sleep 60");letmut watcher = Client::connect(&running).await; watcher.send(&Request::Subscribe).await;letmut client = Client::connect(&running).await; client.send(&spawn_request("s-1", &bin)).await; assert!(matches!( client.next("the spawn's answer").await,Event::Spawned { .. } ));// The hook, on its own connection, the way the subcommand opens one.letmut hook = Client::connect(&running).await; hook.send(&Request::Hook { event: "PermissionRequest".to_string(), session_id: Some("s-1".to_string()), payload: serde_json::json!({"request_id": "req-1", "hook_event_name": "PermissionRequest"}), }) .await;// The phone is told the session is waiting, and on what.letEvent::State { state, waiting_kind, request_id, .. } = watcher .next_matching("the waiting state", |event| { matches!(event, Event::State { state, .. } if *state == SessionState::Waiting) }) .awaitelse { panic!("a blocked permission is a waiting state"); }; assert_eq!(state, SessionState::Waiting); assert_eq!( waiting_kind,Some(cotton_session_host::protocol::WaitingKind::Permission) ); assert_eq!(request_id.as_deref(), Some("req-1")); client .send(&Request::Decide { session_id: "s-1".to_string(), request_id: "req-1".to_string(), decision: Decision::Allow, }) .await;letEvent::Decision { stdout, .. } = hook .next_matching("the decision", |event| { matches!(event, Event::Decision { .. }) }) .awaitelse { panic!("an answered permission is a decision"); }; assert_eq!( stdout["hookSpecificOutput"]["permissionDecision"], "allow","the host encoded the reply in the SESSION's own agent dialect" ); assert_eq!( stdout["hookSpecificOutput"]["hookEventName"], "PermissionRequest" );}#[tokio::test]asyncfn a_permission_hook_nobody_answers_falls_back_rather_than_waiting_for_ever() {let running = start().await;letmut hook = Client::connect(&running).await; hook.send(&Request::Hook { event: "PermissionRequest".to_string(), session_id: Some("not-here".to_string()), payload: serde_json::json!({"request_id": "req-1"}), }) .await;// The wait is 400 ms in this host, so an unanswered request must come back// well inside the fifteen seconds `next` allows. assert!( matches!(hook.next("the permission hook's answer").await, Event::Ok),"an unanswered permission hook gets no decision, which is what makes the agent prompt in its own TUI" );}#[tokio::test]asyncfn a_stop_hook_reads_the_transcript_and_the_turn_reaches_a_subscriber() {let running = start().await;let bin = stand_in_agent(&running, "sleep 60");let transcript = running.dir.path().join("transcript.jsonl"); std::fs::write( &transcript,"{\"type\":\"assistant\",\"message\":{\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"the tests are green\"}]}}\n", ) .expect("the transcript is written");letmut watcher = Client::connect(&running).await; watcher.send(&Request::Subscribe).await;letmut client = Client::connect(&running).await; client.send(&spawn_request("s-1", &bin)).await; assert!(matches!( client.next("the spawn's answer").await,Event::Spawned { .. } )); client .send(&Request::Hook { event: "Stop".to_string(), session_id: Some("s-1".to_string()), payload: serde_json::json!({"hook_event_name": "Stop","transcript_path": transcript.display().to_string() }), }) .await;letEvent::Turn { text, seq, .. } = watcher .next_matching("the turn", |event| matches!(event, Event::Turn { .. })) .awaitelse { panic!("a Stop hook makes a turn"); }; assert_eq!(text, "the tests are green"); assert_eq!(seq, 1, "turns are numbered from one, per session");}/// RULE: A hosted session whose turns the user's own Stop hook logs gets `spoke` from its Stop and never `turn`, so the hook stays that session's one source of turns.#[tokio::test]asyncfn a_stop_for_a_session_the_turn_log_hook_logs_says_spoke() {let dir = tempfile::tempdir().expect("a scratch directory");let home = dir.path().join("home"); std::fs::create_dir_all(home.join(".claude")).expect("the settings folder is made"); std::fs::write( home.join(".claude/settings.json"),r#"{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"bash \"$HOME/.claude/scripts/cotton-session-log.sh\" || true"}]}]}}"#, ) .expect("the settings are written");// A hook counts only when it could post (`adopted::hooked_tools`): its// own credentials name a live endpoint and a token. Without this file the// hook exits silently, the host rightly files the turn itself, and this// test would be asserting about an unhooked session. std::fs::create_dir_all(home.join(".config/tinmen")).expect("the hook's config folder is made"); std::fs::write( home.join(".config/tinmen/memory-mirror.json"),r#"{"endpoint":"https://example.test/mcp","token":"t"}"#, ) .expect("the hook's credentials are written");let layout = Layout::new(dir.path().join("CottonDB"));let host = Arc::new(Host::new( layout.clone(),Arc::new(FixedClock::at(CLOCK)),"/does/not/matter/cotton-session-host".to_string(), cotton_session_host::data_dir::Flavor::Dev, ) .expect("the host comes up") .in_login_env(LoginEnv::inherited()) .watching(cotton_session_host::adopted::Roots::resolve(&home, None, None)), );let listener = host.bind().await.expect("the socket binds");let task = tokio::spawn(asyncmove {let _ = host.run(listener).await; });let running = Running { dir, layout, task };let bin = stand_in_agent(&running, "sleep 60");let transcript = running.dir.path().join("transcript.jsonl"); std::fs::write( &transcript,"{\"type\":\"assistant\",\"message\":{\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"the hook has the turn\"}]}}\n", ) .expect("the transcript is written");letmut watcher = Client::connect(&running).await; watcher.send(&Request::Subscribe).await;letmut client = Client::connect(&running).await; client.send(&spawn_request("s-1", &bin)).await; assert!(matches!( client.next("the spawn's answer").await,Event::Spawned { .. } )); client .send(&Request::Hook { event: "Stop".to_string(), session_id: Some("s-1".to_string()), payload: serde_json::json!({"hook_event_name": "Stop","transcript_path": transcript.display().to_string() }), }) .await;let said = watcher .next_matching("the turn's line", |event| { matches!(event, Event::Turn { .. } | Event::Spoke { .. }) }) .await; assert!( matches!(&said, Event::Spoke { text, .. } if text == "the hook has the turn"),"a hooked session's Stop says spoke, got {said:?}" );}/// RULE: A session that is working on a reply says it is running, not idle — so nobody is offered Reply to a session that is busy with the last one.#[tokio::test]asyncfn a_prompt_after_a_finished_turn_puts_the_session_back_to_running() {let running = start().await;let bin = stand_in_agent(&running, "sleep 60");letmut watcher = Client::connect(&running).await; watcher.send(&Request::Subscribe).await;letmut client = Client::connect(&running).await; client.send(&spawn_request("s-1", &bin)).await; assert!(matches!( client.next("the spawn's answer").await,Event::Spawned { .. } ));// The opening turn ends… client .send(&Request::Hook { event: "Stop".to_string(), session_id: Some("s-1".to_string()), payload: serde_json::json!({ "hook_event_name": "Stop" }), }) .await; watcher .next_matching("idle", |event| { matches!(event, Event::State { state: SessionState::Idle, .. }) }) .await;// …and a reply typed into the terminal begins the next one. client .send(&Request::Hook { event: "UserPromptSubmit".to_string(), session_id: Some("s-1".to_string()), payload: serde_json::json!({"hook_event_name": "UserPromptSubmit","prompt": "and the second thing" }), }) .await;letEvent::State { session_id, state, waiting_kind, .. } = watcher .next_matching("running again", |event| { matches!(event, Event::State { state: SessionState::Running, .. }) }) .awaitelse { panic!("a prompt makes a state"); }; assert_eq!(session_id, "s-1"); assert_eq!(state, SessionState::Running); assert_eq!(waiting_kind, None);}#[tokio::test]asyncfn a_task_list_tool_call_carries_the_whole_list_to_a_subscriber_and_leaves_the_state_alone() {let running = start().await;let bin = stand_in_agent(&running, "sleep 60");letmut watcher = Client::connect(&running).await; watcher.send(&Request::Subscribe).await;letmut client = Client::connect(&running).await; client.send(&spawn_request("s-1", &bin)).await; assert!(matches!( client.next("the spawn's answer").await,Event::Spawned { .. } )); client .send(&Request::Hook { event: "PostToolUse".to_string(), session_id: Some("s-1".to_string()), payload: serde_json::json!({"hook_event_name": "PostToolUse","tool_name": "TodoWrite","tool_input": {"todos": [ {"content": "read the brief", "status": "completed", "activeForm": "reading the brief"}, {"content": "write the hook", "status": "in_progress", "activeForm": "writing the hook"} ]} }), }) .await;letEvent::Tasks { session_id, tasks } = watcher .next_matching("the task list", |event| matches!(event, Event::Tasks { .. })) .awaitelse { panic!("a TodoWrite hook makes a task list"); }; assert_eq!(session_id, "s-1"); assert_eq!( tasks, vec![Task { seq: 0, text: "read the brief".to_string(), status: TaskStatus::Done },Task { seq: 1, text: "write the hook".to_string(), status: TaskStatus::Active }, ] );// The task list moved NOTHING: the session is exactly where the spawn left// it (no SessionStart hook has run in this test), because a list is not a// state.letmut asking = Client::connect(&running).await; asking.send(&Request::List).await;letEvent::Sessions { sessions } = asking.next("the list").awaitelse { panic!("list answers with sessions"); }; assert_eq!( sessions .iter() .find(|held| held.session_id == "s-1") .map(|held| held.state),Some(SessionState::Starting) );}#[tokio::test]asyncfn a_status_line_carries_the_account_s_windows_to_a_subscriber() {let running = start().await;let bin = stand_in_agent(&running, "sleep 60");letmut watcher = Client::connect(&running).await; watcher.send(&Request::Subscribe).await;letmut client = Client::connect(&running).await; client.send(&spawn_request("s-1", &bin)).await; assert!(matches!( client.next("the spawn's answer").await,Event::Spawned { .. } )); client .send(&Request::Statusline { session_id: Some("s-1".to_string()), payload: serde_json::json!({"session_id": "s-1","model": {"display_name": "claude-opus-5"},"rate_limits": {"five_hour": {"used_percentage": 61.0, "resets_at": "2026-09-18T13:00:00Z"},"seven_day": {"used_percentage": 18.5, "resets_at": "2026-09-22T00:00:00Z"} } }), }) .await;letEvent::Usage { usage } = watcher .next_matching("the usage", |event| matches!(event, Event::Usage { .. })) .awaitelse { panic!("a status line carries usage"); }; assert_eq!(usage.five_hour_pct, Some(61.0)); assert_eq!(usage.weekly_pct, Some(18.5));}#[tokio::test]asyncfn list_answers_for_a_session_the_previous_daemon_left_behind() {let dir = tempfile::tempdir().expect("a scratch directory");let layout = Layout::new(dir.path().join("CottonDB"));// The previous daemon kept its sessions in the data folder; the host moves// them out (the agent is denied the data folder whole) and lists them still.let before = layout.sessions_in_the_data_folder();let index = layout.index(); std::fs::create_dir_all(&before).expect("the directory is made"); std::fs::write( before.join("index.json"), serde_json::to_vec_pretty(&serde_json::json!({"sessions": [{"id": "s-from-before","tool": "claude","launch_id": "launch-0","cwd": "/work/repo","started_at": "2026-09-17T09:00:00Z" }] })) .expect("the index encodes"), ) .expect("the index is written");let running = host_over(dir, layout).await;letmut client = Client::connect(&running).await; client.send(&Request::List).await;letEvent::Sessions { sessions } = client.next("the session list").awaitelse { panic!("a list answers with sessions"); }; assert_eq!(sessions.len(), 1); assert_eq!(sessions[0].session_id, "s-from-before"); assert!(!before.exists() && index.exists(), "the sessions moved out of the data folder"); assert_eq!( sessions[0].state,SessionState::Ended,"a restart ends the children, and the list says so rather than showing it running" ); assert!(!sessions[0].host_owned); assert_eq!( sessions[0].ended_at.as_deref(),Some(CLOCK),"it was stamped on the way up, from the injected clock" ); assert_eq!( sessions[0].exit_code, None,"nobody reaped it, so the exit is unknown — never a fabricated 0" );}#[tokio::test]asyncfn a_sample_over_the_socket_reads_this_machine_and_is_stamped_from_the_clock() {let running = start().await;letmut client = Client::connect(&running).await; client.send(&Request::Sample).await;letEvent::Sample { sample } = client.next("the sample").awaitelse { panic!("a sample answers with a sample"); }; assert_eq!(sample.sampled_at, CLOCK); assert_eq!(sample.sessions_running, 0); assert!(sample.cpu_count >= 1); assert_eq!(sample.host_version, cotton_session_host::HOST_VERSION);}#[tokio::test]asyncfn a_line_the_host_does_not_speak_is_refused_by_name_and_the_connection_lives_on() {let running = start().await;letmut client = Client::connect(&running).await; client .write .write_all(b"{\"t\":\"teleport\"}\n") .await .expect("the line is written");letEvent::Error { message } = client.next("the refusal").awaitelse { panic!("an unknown verb is refused"); }; assert!(message.contains("understand"), "got {message}"); client.send(&Request::List).await; assert!(matches!( client.next("the session list").await,Event::Sessions { .. } ));}#[tokio::test]asyncfn attaching_to_a_session_this_host_never_had_says_so_rather_than_hanging() {let running = start().await;letmut client = Client::connect(&running).await; client .send(&Request::Attach { session_id: "nobody".to_string(), cols: 80, rows: 24, from_offset: None, }) .await;letEvent::Error { message } = client.next("the refusal").awaitelse { panic!("attaching to nothing is refused"); }; assert!(message.contains("nobody"), "got {message}");}#[tokio::test]asyncfn deciding_a_permission_nobody_is_waiting_on_says_why_rather_than_pretending() {let running = start().await;letmut client = Client::connect(&running).await; client .send(&Request::Decide { session_id: "nobody".to_string(), request_id: "req-1".to_string(), decision: Decision::Allow, }) .await;letEvent::Error { message } = client.next("the refusal").awaitelse { panic!("deciding nothing is refused"); }; assert!(message.contains("nobody"), "got {message}");}#[tokio::test]asyncfn a_hook_for_a_session_this_host_never_had_is_still_answered_because_it_is_blocking_on_us() {let running = start().await;letmut client = Client::connect(&running).await; client .send(&Request::Hook { event: "Notification".to_string(), session_id: Some("not-here".to_string()), payload: serde_json::json!({"notification_type": "idle_prompt"}), }) .await; assert!(matches!(client.next("the hook's answer").await, Event::Ok));}#[tokio::test]asyncfn a_detach_ends_the_stream_without_ending_the_connection() {let running = start().await;letmut client = Client::connect(&running).await; client.send(&Request::Subscribe).await; client.send(&Request::Detach).await; assert!(matches!( client .next_matching("the detach's answer", |event| matches!(event, Event::Ok)) .await,Event::Ok )); client.send(&Request::List).await; assert!(matches!( client .next_matching("the session list", |event| matches!( event,Event::Sessions { .. } )) .await,Event::Sessions { .. } ));}#[tokio::test]asyncfn a_write_whose_bytes_are_not_base64_is_refused_by_name() {let running = start().await;letmut client = Client::connect(&running).await; client .send(&Request::Write { session_id: "whatever".to_string(), b: "this is not base64!!".to_string(), }) .await;letEvent::Error { message } = client.next("the refusal").awaitelse { panic!("bad base64 is refused"); }; assert!(message.contains("base64"), "got {message}");}/// **A SUBSCRIBE IS ACKNOWLEDGED, AND THE ACK IS THE FIRST LINE.**////// `subscribe` turns this connection into a stream, and the client's own dial/// (`cotton_client::session_host::HostLink::connect`) sends it as a REQUEST and/// waits for an answer before it believes it is subscribed. Measured on a Mac/// 2026-09-19 with no ack here: every dial timed out at five seconds, the app/// ran unsubscribed for ever, and every `state`, `turn`, `usage`, `sample`,/// `adopted` and `exited` this host broadcast reached nobody — while `spawn`/// went on working, because the executor opens a connection of its own. A/// session started from the phone came up and then never moved off `starting`.#[tokio::test]asyncfn a_subscribe_is_acknowledged_before_the_stream_starts() {let running = start().await;letmut watcher = Client::connect(&running).await; watcher.send(&Request::Subscribe).await; assert!( matches!(watcher.next("the subscribe's answer").await, Event::Ok),"a subscribe answers `ok`, and it is the first line on the connection" );// And the stream really is live afterwards: the ack did not consume the// subscription it acknowledges.let bin = stand_in_agent(&running, "exit 7");letmut client = Client::connect(&running).await; client.send(&spawn_request("s-ack", &bin)).await; assert!(matches!( client.next("the spawn's answer").await,Event::Spawned { .. } ));letEvent::Exited { code, .. } = watcher .next_matching("the exit", |event| matches!(event, Event::Exited { .. })) .awaitelse { panic!("an exit is an exit event"); }; assert_eq!(code, Some(7));}/// **THE LAUNCHD DEFECT, END TO END.**////// Measured 2026-09-19 on all three host Macs: the packaged helper is started/// by launchd with `PATH=/usr/bin:/bin:/usr/sbin:/sbin` and nothing else, so/// a session it spawned would have run in that — no `~/.local/bin`, no/// locale, none of a person's shims. Here the host is given a login/// environment and the spawn request carries NO environment at all, which is/// what the app sends: everything the child sees came from the capture.#[tokio::test]asyncfn a_session_runs_in_the_person_s_login_environment_not_the_one_this_process_was_given() {let dir = tempfile::tempdir().expect("a scratch directory");let layout = Layout::new(dir.path().join("CottonDB"));// The stand-in agent, on the LOGIN environment's PATH rather than on the// request's — so finding it at all is the thing this test proves.let bin = dir.path().join("login-bin"); std::fs::create_dir_all(&bin).expect("the stand-in directory is made");let program = bin.join("claude"); std::fs::write( &program,"#!/bin/sh\nprintf 'PATH=%s LANG=%s TERM=%s\\n' \"$PATH\" \"$LANG\" \"$TERM\"\nexit 0\n", ) .expect("the stand-in is written"); {use std::os::unix::fs::PermissionsExtas _; std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)) .expect("the stand-in is executable"); }let login = LoginEnv::from_vars(BTreeMap::from([ ("PATH".to_string(), format!("{}:/usr/bin:/bin", bin.display())), ("LANG".to_string(), "en_IN.UTF-8".to_string()), ("TERM".to_string(), "xterm-256color".to_string()), ]));let running = host_over_in(dir, layout, login).await;letmut client = Client::connect(&running).await; client .send(&Request::Spawn { resume_from: None, launch_id: "launch-1".to_string(), session_id: Some("s-env".to_string()), tool: Tool::Claude, argv_extras: Vec::new(), cwd: "/".to_string(), env: BTreeMap::new(), cols: 80, rows: 24, permission_mode: PermissionMode::Bypass, }) .await;letEvent::Spawned { session_id, .. } = client.next("the spawn's answer").awaitelse { panic!("a spawn answers `spawned`"); }; assert_eq!(session_id, "s-env");letmut viewer = Client::connect(&running).await; viewer .send(&Request::Attach { session_id: "s-env".to_string(), cols: 80, rows: 24, from_offset: None, }) .await;let said = viewer.terminal_until("LANG=").await; assert!( said.contains(&format!("PATH={}", bin.display())),"the child ran on the captured PATH — it said {said:?}" ); assert!( said.contains("LANG=en_IN.UTF-8"),"the person's locale reached the child — it said {said:?}" ); assert!( said.contains("TERM=xterm-256color"),"a terminal UI needs a TERM — it said {said:?}" );}/// What the request asks for still wins over what the login shell said.#[tokio::test]asyncfn a_launch_s_own_environment_is_on_top_of_the_captured_one() {let dir = tempfile::tempdir().expect("a scratch directory");let layout = Layout::new(dir.path().join("CottonDB"));let bin = dir.path().join("login-bin"); std::fs::create_dir_all(&bin).expect("the stand-in directory is made");let program = bin.join("claude"); std::fs::write( &program,"#!/bin/sh\nprintf 'LANG=%s MARK=%s\\n' \"$LANG\" \"$MARK\"\nexit 0\n", ) .expect("the stand-in is written"); {use std::os::unix::fs::PermissionsExtas _; std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)) .expect("the stand-in is executable"); }let login = LoginEnv::from_vars(BTreeMap::from([ ("PATH".to_string(), format!("{}:/usr/bin:/bin", bin.display())), ("LANG".to_string(), "en_IN.UTF-8".to_string()), ]));let running = host_over_in(dir, layout, login).await;letmut client = Client::connect(&running).await; client .send(&Request::Spawn { resume_from: None, launch_id: "launch-1".to_string(), session_id: Some("s-over".to_string()), tool: Tool::Claude, argv_extras: Vec::new(), cwd: "/".to_string(), env: BTreeMap::from([ ("LANG".to_string(), "C".to_string()), ("MARK".to_string(), "from-the-request".to_string()), ]), cols: 80, rows: 24, permission_mode: PermissionMode::Bypass, }) .await;let _ = client.next("the spawn's answer").await;letmut viewer = Client::connect(&running).await; viewer .send(&Request::Attach { session_id: "s-over".to_string(), cols: 80, rows: 24, from_offset: None, }) .await;let said = viewer.terminal_until("MARK=").await; assert!(said.contains("LANG=C"), "the request's own wins — {said:?}"); assert!(said.contains("MARK=from-the-request"), "{said:?}");}/// **AGENTS ARE RE-DETECTED ON EVERY SAMPLE**, because this daemon outlives/// every install and update on the Mac it runs on.#[tokio::test]asyncfn an_agent_installed_while_the_host_runs_is_in_the_next_sample() {let dir = tempfile::tempdir().expect("a scratch directory");let layout = Layout::new(dir.path().join("CottonDB"));let bin = dir.path().join("login-bin"); std::fs::create_dir_all(&bin).expect("the stand-in directory is made");let write_agent = |name: &str, version: &str| {let path = bin.join(name); std::fs::write(&path, format!("#!/bin/sh\necho '{version}'\n")).expect("written");use std::os::unix::fs::PermissionsExtas _; std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).expect("executable"); };let login = LoginEnv::from_vars(BTreeMap::from([("PATH".to_string(), bin.display().to_string(), )]));let host = Arc::new(Host::new( layout.clone(),Arc::new(FixedClock::at(CLOCK)),"/does/not/matter/cotton-session-host".to_string(), cotton_session_host::data_dir::Flavor::Dev, ) .expect("the host comes up") .in_login_env(login), );// Prime discovery before the stand-in is installed; system agent locations// may already hold other agents on the machine running this test.let _ = host.sample().await; write_agent("claude", "9.9.9 (Claude Code)");let after = host.sample().await; assert_eq!( after.agents.get("claude-code").map(String::as_str),Some("9.9.9"),"a host that detected once at boot would still be answering `agents: {{}}`" ); write_agent("codex", "codex-cli 0.55.0");let later = host.sample().await; assert_eq!(later.agents.get("codex").map(String::as_str), Some("0.55.0")); drop(dir);}/// **A RESTART WAITS FOR THE SESSIONS.**////// The other half — a restart with nothing running — is `exit(0)`, which a/// test process cannot survive and does not need to: the decision is pure and/// `src/binary_tests.rs` holds every arm of it. What can only be proved/// against a running daemon is that a LIVE session is what stops it, and that/// the deferral then shows up in every sample.#[tokio::test]asyncfn a_restart_defers_while_a_session_is_alive_and_says_so_in_the_next_sample() {let running = start().await;let bin = stand_in_agent(&running, "sleep 30");letmut client = Client::connect(&running).await;// Nothing is waiting on this sample: it is the BEFORE, and it must not// already be claiming a pending update. client.send(&Request::Sample).await;letEvent::Sample { sample } = client.next("the first sample").awaitelse { panic!("a sample answers a sample"); }; assert!(!sample.update_pending, "nothing has been asked yet"); client.send(&spawn_request("s-restart", &bin)).await;let spawned = client .next_matching("the spawn", |event| matches!(event, Event::Spawned { .. })) .await; assert!(matches!(spawned, Event::Spawned { .. })); client.send(&Request::Restart).await;let answer = client .next_matching("the restart", |event| { matches!(event, Event::Restarting { .. }) }) .await; assert_eq!( answer,Event::Restarting { restarting: false, sessions_running: 1 },"one live session is one reason not to go" );// AND EVERY SAMPLE SAYS SO from here on — which is how the phone and the// app learn that this Mac is holding a helper it means to replace. client.send(&Request::Sample).await;letEvent::Sample { sample } = client .next_matching("the second sample", |event| { matches!(event, Event::Sample { .. }) }) .awaitelse { panic!("a sample answers a sample"); }; assert!(sample.update_pending, "the deferral is in the sample");// The process is still here: a deferred restart ends nobody's turn. client.send(&Request::List).await;letEvent::Sessions { sessions } = client .next_matching("the list", |event| matches!(event, Event::Sessions { .. })) .awaitelse { panic!("a list answers a list"); };let held = sessions .iter() .find(|summary| summary.session_id == "s-restart") .expect("the session is still listed"); assert!(held.host_owned, "and this host still owns its terminal"); client.send(&Request::Stop { session_id: "s-restart".to_string(), }) .await;}// ─── utility terminals ──────────────────────────────────────────────────────/// A utility request for `/bin/sh -c <script>`.////// `/bin/sh` by absolute path: the helper resolves `argv[0]` against the/// captured login PATH, and a test that inherits the runner's environment must/// not depend on what happens to be on it.fn utility(purpose: &str, script: &str) -> Request {Request::SpawnUtility { purpose: purpose.to_string(), argv: vec!["/bin/sh".to_string(),"-c".to_string(), script.to_string(), ], cwd: None, env: BTreeMap::new(), cols: Some(100), rows: Some(30), }}#[tokio::test]asyncfn a_utility_terminal_runs_a_command_is_attachable_and_is_reaped_when_it_exits() {let running = start().await;letmut client = Client::connect(&running).await;// SUBSCRIBED, because the end of a utility is a broadcast: the helper// outlives the app and the app is a subscriber, exactly as it is for a// session's `exited`. client.send(&Request::Subscribe).await; assert_eq!(client.next("the subscribe").await, Event::Ok); client.send(&utility("install-claude", "echo hi; sleep 30")).await;letEvent::UtilityStarted { id, purpose, pid } = client .next_matching("the utility", |event| { matches!(event, Event::UtilityStarted { .. }) }) .awaitelse { panic!("a spawn_utility answers utility_started"); }; assert_eq!(purpose, "install-claude"); assert!(id.starts_with("util:"), "{id} is not namespaced"); assert!(pid.is_some(), "a real process was started");// ATTACHED THROUGH THE SAME PATH A SESSION TAKES — the terminal view on// the Serving page is the same view, pointed at this id.letmut viewer = Client::connect(&running).await; viewer .send(&Request::Attach { session_id: id.clone(), cols: 100, rows: 30, from_offset: None, }) .await;let attached = viewer .next_matching("the attach", |event| matches!(event, Event::Attached { .. })) .await; assert!(matches!(attached, Event::Attached { .. })); assert!(viewer.terminal_until("hi").await.contains("hi"));// **AND IT IS NOT A SESSION.** Nothing about it reaches the list, which is// what every row-writing path downstream reads. client.send(&Request::List).await;letEvent::Sessions { sessions } = client .next_matching("the list", |event| matches!(event, Event::Sessions { .. })) .awaitelse { panic!("a list answers a list"); }; assert!( !sessions.iter().any(|held| held.session_id == id),"a utility terminal was listed as a session" );// Stopping it is the same verb too, and the exit is reported by name. client.send(&Request::Stop { session_id: id.clone(), }) .await;let ended = client .next_matching("the utility's end", |event| { matches!(event, Event::UtilityEnded { .. }) }) .await;letEvent::UtilityEnded { id: ended_id, purpose: ended_purpose, .. } = endedelse { panic!("the end of a utility is a utility_ended"); }; assert_eq!(ended_id, id); assert_eq!(ended_purpose, "install-claude");}#[tokio::test]asyncfn a_second_utility_of_one_purpose_is_refused_while_the_first_is_running() {let running = start().await;letmut client = Client::connect(&running).await; client.send(&utility("install-claude", "sleep 30")).await;letEvent::UtilityStarted { id, .. } = client.next("the first utility").awaitelse { panic!("a spawn_utility answers utility_started"); }; client.send(&utility("install-claude", "sleep 30")).await;letEvent::Error { message } = client.next("the refusal").awaitelse { panic!("a second utility of one purpose is refused, not started beside the first"); }; assert!(message.contains("install-claude"), "{message}"); assert!(message.contains(&id), "the refusal names the one running — {message}");// A DIFFERENT purpose is a different terminal, and runs. client.send(&utility("sign-in-claude", "sleep 30")).await;let second = client.next("the other purpose").await; assert!( matches!(second, Event::UtilityStarted { .. }),"a different purpose is a different terminal — got {second:?}" ); client.send(&Request::Stop { session_id: id }).await;}#[tokio::test]asyncfn a_utility_that_names_a_program_this_mac_does_not_have_is_refused_by_name() {let running = start().await;letmut client = Client::connect(&running).await; client .send(&Request::SpawnUtility { purpose: "install-codex".to_string(), argv: vec!["npm-that-is-not-here".to_string(), "--version".to_string()], cwd: None, env: BTreeMap::new(), cols: None, rows: None, }) .await;letEvent::Error { message } = client.next("the refusal").awaitelse { panic!("a program that is not on the PATH is refused rather than opened and dropped"); }; assert!(message.contains("npm-that-is-not-here"), "{message}");}#[tokio::test]asyncfn a_finished_utility_still_replays_what_it_said_until_the_next_one_of_its_purpose() {let running = start().await;letmut client = Client::connect(&running).await; client.send(&Request::Subscribe).await; assert_eq!(client.next("the subscribe").await, Event::Ok); client .send(&utility("command-line-tools", "echo the-tools-are-here")) .await;letEvent::UtilityStarted { id, .. } = client .next_matching("the utility", |event| { matches!(event, Event::UtilityStarted { .. }) }) .awaitelse { panic!("a spawn_utility answers utility_started"); };let ended = client .next_matching("the utility's end", |event| { matches!(event, Event::UtilityEnded { .. }) }) .await; assert!(matches!(ended, Event::UtilityEnded { code: Some(0), .. }), "{ended:?}");// The person looks at the panel after it finished: the output is still// there, because the entry is kept until a new one of its purpose replaces// it.letmut viewer = Client::connect(&running).await; viewer .send(&Request::Attach { session_id: id, cols: 100, rows: 30, from_offset: None, }) .await; assert!(viewer .terminal_until("the-tools-are-here") .await .contains("the-tools-are-here"));}