//! Adopted sessions, over real files and the real daemon. //! //! **Never the real transcript directory.** Every file here is one of this //! crate's own fixtures, copied into a temporary directory the test made — the //! transcripts under a person's own configuration are their work, not a test //! corpus, and the transcript-reads guard hook exists to keep a live //! session out of them. //! //! What this proves that `src/adopted_tests.rs` cannot: the walk finds the //! files where the two agents actually put them, the head and tail reads are //! bounded and still answer, and the daemon refuses the four things an adopted //! session cannot do with the sentence that says why. use std::path::Path; use std::sync::Arc; use cotton_session_host::adopted::{scan, FileTranscripts, Roots, Transcripts}; use cotton_session_host::agents::{claude::Claude, codex::Codex, Adapter}; use cotton_session_host::clock::FixedClock; use cotton_session_host::data_dir::Layout; use cotton_session_host::protocol::{line, parse, Event, Request, Tool}; use cotton_session_host::serve::Host; use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader}; use tokio::net::UnixStream; const CLAUDE_TRANSCRIPT: &str = include_str!("fixtures/claude-transcript.jsonl"); const CLAUDE_ENDED: &str = include_str!("fixtures/claude-transcript-ended.jsonl"); const CODEX_ROLLOUT: &str = include_str!("fixtures/codex-rollout.jsonl"); const CODEX_ENDED: &str = include_str!("fixtures/codex-rollout-ended.jsonl"); const CLAUDE_SESSION: &str = "11111111-2222-3333-4444-555555555555"; const CODEX_SESSION: &str = "019a0000-0000-7000-8000-000000000001"; const CLOCK: &str = "2026-09-18T09:00:00Z"; /// A home directory with both agents' transcript trees in it, made of fixtures. fn a_home_with_transcripts(home: &Path) { let claude = home.join(".claude/projects/-work-repo"); std::fs::create_dir_all(&claude).expect("the projects directory"); std::fs::write( claude.join(format!("{CLAUDE_SESSION}.jsonl")), CLAUDE_TRANSCRIPT, ) .expect("a transcript"); // Not a transcript: the directory holds other things, and the walk must // not read them as sessions. std::fs::write(claude.join("notes.md"), "not a transcript").expect("a note"); let codex = home.join(".codex/sessions/2026/09/18"); std::fs::create_dir_all(&codex).expect("the sessions directory"); std::fs::write( codex.join("rollout-2026-09-18T09-00-00-019a0000.jsonl"), CODEX_ROLLOUT, ) .expect("a rollout"); std::fs::write(codex.join("history.jsonl"), "{}\n").expect("not a rollout"); } #[test] fn the_walk_finds_both_agents_transcripts_where_they_actually_put_them() { let dir = tempfile::tempdir().expect("a scratch directory"); a_home_with_transcripts(dir.path()); let found = scan(&Roots::resolve(dir.path(), None, None)); assert_eq!(found.len(), 2, "two transcripts and two files that are not"); assert!(found.iter().any(|file| file.tool == Tool::Claude)); assert!(found.iter().any(|file| file.tool == Tool::Codex)); assert!( found.iter().all(|file| file.len > 0), "a scan reads the size it compares against" ); } #[test] fn roots_that_are_not_there_are_a_fact_about_the_mac_and_not_an_error() { let dir = tempfile::tempdir().expect("a scratch directory"); assert!(scan(&Roots::resolve(dir.path(), None, None)).is_empty()); } #[test] fn the_agents_own_overrides_move_the_roots() { let dir = tempfile::tempdir().expect("a scratch directory"); let elsewhere = dir.path().join("elsewhere"); a_home_with_transcripts(&elsewhere); let roots = Roots::resolve( dir.path(), Some(elsewhere.join(".claude").to_str().expect("utf-8")), Some(elsewhere.join(".codex").to_str().expect("utf-8")), ); assert_eq!(scan(&roots).len(), 2); } #[test] fn the_head_names_the_session_and_the_tail_says_what_it_last_did() { let dir = tempfile::tempdir().expect("a scratch directory"); a_home_with_transcripts(dir.path()); let found = scan(&Roots::resolve(dir.path(), None, None)); for file in &found { let head = FileTranscripts.head(&file.path).expect("a head"); let tail = FileTranscripts.tail(&file.path).expect("a tail"); let meta = match file.tool { Tool::Claude => Claude.read_adopted_meta(&head), Tool::Codex => Codex.read_adopted_meta(&head), } .expect("the head names a session"); assert!(meta.session_id == CLAUDE_SESSION || meta.session_id == CODEX_SESSION); assert!(meta.cwd.is_some(), "both fixtures carry a working directory"); let turn = match file.tool { Tool::Claude => Claude.read_last_turn(&tail), Tool::Codex => Codex.read_last_turn(&tail), } .expect("the tail carries a turn"); assert_eq!( turn.text, "I added two: one for the bound and one for the replay tail." ); } } #[test] fn each_adapter_reads_only_its_own_end_marker() { assert!(Claude.transcript_ended(CLAUDE_ENDED)); assert!(!Claude.transcript_ended(CLAUDE_TRANSCRIPT)); assert!(Codex.transcript_ended(CODEX_ENDED)); assert!(!Codex.transcript_ended(CODEX_ROLLOUT)); assert!( !Claude.transcript_ended(CODEX_ENDED) && !Codex.transcript_ended(CLAUDE_ENDED), "a marker in the other agent's dialect is not this agent's end" ); } #[test] fn a_transcript_that_names_no_session_is_no_adoption() { assert_eq!(Claude.read_adopted_meta("not json\n"), None); assert_eq!( Codex.read_adopted_meta(CLAUDE_TRANSCRIPT), None, "a Claude transcript has no session_meta record" ); } // ─── the daemon ───────────────────────────────────────────────────────────── struct Running { _dir: tempfile::TempDir, layout: Layout, host: Arc, /// What the FIRST adopt pass found — run by the fixture, before the host /// started serving, so it is the first pass by construction and not by /// luck (see `a_host_watching_fixtures`). first_pass: cotton_session_host::adopted::Observed, task: tokio::task::JoinHandle<()>, } impl Drop for Running { fn drop(&mut self) { self.task.abort(); } } async fn a_host_watching_fixtures() -> Running { let dir = tempfile::tempdir().expect("a scratch directory"); let home = dir.path().join("home"); a_home_with_transcripts(&home); 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") .watching(Roots::resolve(&home, None, None)), ); let listener = host.bind().await.expect("the socket binds"); // THE FIRST PASS IS THE FIXTURE'S, AND IT RUNS BEFORE `run`. `Host::run` // starts the host's own scanner, whose interval ticks at once — so a test // that ran its "first" pass after `run` was racing the host's, and on a // loaded builder lost: the host's pass adopted the two transcripts first // and the test's counted 0 or 1 (the Linux builder, 2026-09-28). With the // pass taken here, the host's own first tick is a second pass over an // unchanged directory, which adopts nothing — the property the second // test below holds. let first_pass = host.adopt_pass().await; let serving = Arc::clone(&host); let task = tokio::spawn(async move { let _ = serving.run(listener).await; }); Running { _dir: dir, layout, host, first_pass, task, } } async fn ask(running: &Running, request: &Request) -> Vec { let stream = UnixStream::connect(running.layout.socket()) .await .expect("the socket answers"); let (read, mut write) = stream.into_split(); write .write_all(line(request).expect("it encodes").as_bytes()) .await .expect("the request goes"); let mut lines = BufReader::new(read).lines(); let mut answers = Vec::new(); // One answer is enough for everything this file asks. if let Ok(Some(text)) = lines.next_line().await { answers.push(parse(&text).expect("the host speaks its own protocol")); } answers } #[tokio::test] async fn a_pass_adopts_both_transcripts_and_list_answers_for_them() { let running = a_host_watching_fixtures().await; let observed = &running.first_pass; assert_eq!(observed.adopted, 2); assert_eq!(observed.skipped, 0); let answers = ask(&running, &Request::List).await; let Event::Sessions { sessions } = &answers[0] else { panic!("list answers with sessions: {answers:?}"); }; assert_eq!(sessions.len(), 2); for session in sessions { assert!(!session.host_owned, "nobody here owns its terminal"); assert!( session.launch_id.is_empty(), "nobody launched it, so there is no launch id to point at" ); } assert!(sessions .iter() .any(|session| session.session_id == CLAUDE_SESSION)); assert!(sessions .iter() .any(|session| session.session_id == CODEX_SESSION)); } #[tokio::test] async fn a_second_pass_over_an_unchanged_directory_adopts_nothing_twice() { // The fixture's own pass is the first; this is the second. let running = a_host_watching_fixtures().await; let again = running.host.adopt_pass().await; assert_eq!(again.adopted, 0); } #[tokio::test] async fn attaching_to_an_adopted_session_is_refused_with_the_reason() { let running = a_host_watching_fixtures().await; let answers = ask( &running, &Request::Attach { session_id: CLAUDE_SESSION.to_string(), cols: 80, rows: 24, from_offset: None, }, ) .await; let Event::Error { message } = &answers[0] else { panic!("an adopted session has no terminal: {answers:?}"); }; assert!(message.contains("adopted from its own transcript"), "{message}"); assert!(message.contains(CLAUDE_SESSION), "{message}"); assert!( message.contains("start it from Cotton"), "the refusal says what to do instead — {message}" ); } #[tokio::test] async fn stopping_writing_to_and_deciding_for_an_adopted_session_are_refused_the_same_way() { let running = a_host_watching_fixtures().await; let refusals = [ Request::Stop { session_id: CLAUDE_SESSION.to_string(), }, Request::Write { session_id: CLAUDE_SESSION.to_string(), b: "aGk=".to_string(), }, Request::Resize { session_id: CLAUDE_SESSION.to_string(), cols: 100, rows: 40, }, Request::Decide { session_id: CLAUDE_SESSION.to_string(), request_id: "req-1".to_string(), decision: cotton_session_host::protocol::Decision::Allow, }, ]; for request in refusals { let answers = ask(&running, &request).await; let Event::Error { message } = &answers[0] else { panic!("expected a refusal for {request:?}, got {answers:?}"); }; assert!( message.contains("adopted from its own transcript"), "{request:?} — {message}" ); } } #[tokio::test] async fn a_session_id_this_host_has_never_heard_of_is_still_the_other_refusal() { let running = a_host_watching_fixtures().await; let answers = ask( &running, &Request::Stop { session_id: "nobody".to_string(), }, ) .await; let Event::Error { message } = &answers[0] else { panic!("expected a refusal: {answers:?}"); }; assert!( message.contains("holds no session nobody"), "an unknown session and an adopted one are different things to fix — {message}" ); } /// **A SUBSCRIBER THAT JOINS LATE IS TOLD WHAT THIS HOST ALREADY FOUND.** /// /// An `adopted` announcement goes out once, when the scan first sees a /// transcript, and nothing replays it — while this host outlives the app by /// design, so a subscriber that comes back after a Sparkle update has missed /// every announcement there has ever been. Measured 2026-09-19: a helper /// holding the sessions in `~/.claude/projects` handed a freshly started app /// none of them, and the phone's Code screen showed only what Cotton had /// launched itself. #[tokio::test] async fn subscribing_replays_the_adopted_sessions_this_host_already_holds() { let running = a_host_watching_fixtures().await; // The scan ran BEFORE anyone subscribed — which is the whole case. assert_eq!(running.first_pass.adopted, 2); let stream = UnixStream::connect(running.layout.socket()) .await .expect("the socket answers"); let (read, mut write) = stream.into_split(); write .write_all( line(&Request::Subscribe) .expect("it encodes") .as_bytes(), ) .await .expect("the request goes"); let mut lines = BufReader::new(read).lines(); // Five lines: the ack, then an `adopted` and a `state` for each of the two. let mut answers = Vec::new(); for _ in 0..5 { let Ok(Some(text)) = lines.next_line().await else { break; }; answers.push(parse(&text).expect("the host speaks its own protocol")); } assert!( matches!(answers.first(), Some(Event::Ok)), "the ack is still the first line: {answers:?}" ); let announced: Vec<&str> = answers .iter() .filter_map(|event| match event { Event::Adopted { session_id, .. } => Some(session_id.as_str()), _ => None, }) .collect(); assert!(announced.contains(&CLAUDE_SESSION), "{answers:?}"); assert!(announced.contains(&CODEX_SESSION), "{answers:?}"); assert_eq!( answers .iter() .filter(|event| matches!(event, Event::State { .. })) .count(), 2, "each replayed card carries where it had got to: {answers:?}" ); }