//! The daemon: one unix socket, every pseudo-terminal, and the sample timer.//!//! ONE HOST PER DATA DIRECTORY. The socket is `<dataDir>/session-host.sock` at//! mode 0600, and a second daemon fails to BIND rather than unlinking the//! socket a live one is serving. A stale socket left by a crash is removed//! only after a connect to it is refused — which is the difference between//! "nobody is there" and "somebody is".//!//! **A restart ends the children.** Nothing re-parents a pseudo-terminal, so//! on the way up the host stamps every session the previous run left running//! as ended, with an unknown exit. See [`crate::index`].use std::collections::{BTreeMap, HashMap};use std::io::{ErrorKind, Writeas _};use std::os::unix::fs::{FileTypeExtas _, PermissionsExtas _};use std::path::Path;use std::sync::Arc;use std::time::Duration;use base64::Engineas _;use tokio::io::{AsyncBufReadExtas _, AsyncWriteExtas _, BufReader};use tokio::net::{UnixListener, UnixStream};use tokio::sync::{broadcast, mpsc, oneshot, Mutex};usecrate::adopted::{self, FileTranscripts, Roots, Watcher};usecrate::agents::{self, Launch};usecrate::binary::{self, Verdict};usecrate::clock::Clock;usecrate::data_dir::{Flavor, Layout, FLAVOR_ENV, SOCKET_MODE};usecrate::index::{Exit, Index, IndexEntry};usecrate::login_env::LoginEnv;usecrate::machine;usecrate::processes;usecrate::protocol::{ line, parse, Decision, Event, MachineSample, PermissionMode, Request, SessionState,SessionSummary, Tool, WaitingKind,};usecrate::pty::{PtySession, SpawnPlan, StopSchedule};usecrate::scrollback::{Scrollback, REPLAY_TAIL_BYTES};usecrate::utility;/// How many events a slow client may fall behind before it is dropped from the/// stream.////// A phone that cannot keep up is told it is catching up (phase 3); a/// subscriber that has stopped reading entirely must not hold terminal output/// in memory for ever.const EVENT_BACKLOG: usize = 1024;/// How long a `restart` waits for its own answer to leave the socket.////// The answer is handed to the connection's writer task, which is a separate/// task on the same runtime; `exit(0)` in the same breath would take the/// process down before that task ran. A quarter of a second is far above a/// loopback write and far below anything a person notices.const RESTART_FLUSH_MS: u64 = 250;/// What can go wrong bringing the daemon up.#[derive(Debug, thiserror::Error)]pubenumServeError {/// Another daemon holds this data directory's socket. #[error("another session host is already serving {path} — one host per data directory, the way there is one server per data directory")]AlreadyServing {/// The socket. path: String, },/// Something is at the socket's path and it is not a socket this host can/// reach.////// Named rather than unlinked: the one thing a host must never do is/// delete a file it does not understand out of the person's data/// directory. #[error("{path} is in the way and is not a session host socket — {said}")]SocketPathBlocked {/// The path. path: String,/// What the operating system said when the host tried to reach it. said: String, },/// The socket's path is longer than a unix socket address can hold.////// Named rather than left to the operating system, which says only/// *path must be shorter than SUN_LEN* — no path, no number and nothing to/// act on. The limit is the `sun_path` field of `sockaddr_un`, 104 bytes on/// macOS including its terminator, and it is reached by a data directory/// somebody pointed `COTTON_MAC_DATA_DIR` at rather than by `~/CottonDB`,/// which is short. So the refusal names the path, both numbers and the/// variable to move, because the fix is to point that variable somewhere/// shorter and nothing the host can do reaches it. #[error("{path} is {length} bytes and a unix socket path is at most {limit} — point COTTON_MAC_DATA_DIR at a shorter directory")]SocketPathTooLong {/// The socket the host would have bound. path: String,/// How long it is, in bytes. length: usize,/// The most `sun_path` holds on this platform, terminator included. limit: usize, },/// The socket, the directory, or the index. #[error("the session host could not start: {0}")]Io(#[from] std::io::Error),/// The index on disk. #[error(transparent)]Index(#[from] crate::index::IndexError),}/// The most bytes a unix socket path may be, this platform's terminator/// included.////// 104 on macOS and the BSDs, 108 on Linux; the smaller number is the one this/// host is held to, because the answer must not depend on which machine built/// it. `sockaddr_un.sun_path` is a fixed array and the kernel refuses anything/// that does not fit with room for a `\0`.pubconst SOCKET_PATH_MAX: usize = 104;/// The refusal a socket path earns for being too long, or `None`.////// Pure, so every arm is a test rather than a directory somebody has to make.pubfn socket_path_refusal(path: &std::path::Path) -> Option<ServeError> {let text = path.display().to_string();let length = path.as_os_str().as_encoded_bytes().len(); (length + 1 > SOCKET_PATH_MAX).then_some(ServeError::SocketPathTooLong { path: text, length, limit: SOCKET_PATH_MAX, })}/// One running session.structSession { summary: SessionSummary, tool: Tool, pty: Arc<PtySession>, scrollback: Arc<Mutex<Scrollback>>,/// Live terminal output for whoever is attached. data: broadcast::Sender<Vec<u8>>,/// Blocked permission hooks, by request id. pending: HashMap<String, oneshot::Sender<Decision>>,/// The next turn's number. turn_seq: u64,}/// One utility terminal — a command in a pseudo-terminal, and nothing else.////// It deliberately holds LESS than a [`Session`]: no tool, no pending/// permissions, no turn counter and no index entry, because none of those is/// true of a `curl | bash`. What it has is the two things a terminal view/// needs — a pseudo-terminal to write to and a ring to replay/// ([`crate::utility`]).structUtility { id: String, purpose: String, pty: Arc<PtySession>, scrollback: Arc<Mutex<Scrollback>>, data: broadcast::Sender<Vec<u8>>,/// Whether the process is still there. A finished utility is KEPT until a/// new one of its purpose replaces it, so the view that watched an install/// can still replay how it went. running: bool,}/// Everything the daemon holds.structHostState { index: Index, sessions: HashMap<String, Session>,/// Sessions this host FOUND rather than spawned, by their agent session/// id. No pseudo-terminal, no scrollback, nothing to answer — see/// [`crate::adopted`]. adopted: HashMap<String, SessionSummary>,/// The utility terminals this host is running, by id. **Never sessions**:/// nothing here reaches `index`, `list`, `sessions_running` or the/// transcript scan — see [`crate::utility`]. utilities: HashMap<String, Utility>,/// What the transcript scan has already said. watcher: Watcher,/// The last detection this host WROTE DOWN.////// Agents are installed, updated and removed while a `KeepAlive` daemon/// runs for weeks, so every sample re-detects them — and a line per agent/// every five minutes would be the only thing in the log. The line is/// written when the answer CHANGES, which is the only time it says/// anything. last_detected: Option<machine::Detected>,/// Who each agent said it was signed in as, on the last sample.////// Kept for two readers: the log line, written when the answer CHANGES/// (`last_detected`'s rule), and a usage reading that names no address,/// which is filed under the login its agent last reported. last_accounts: BTreeMap<String, crate::protocol::SignedIn>,/// **THE LARGEST EACH LIVE SESSION'S PROCESS TREE HAS BEEN MEASURED AT**,/// session id to gigabytes.////// A session that is reading a file this second still holds the build it/// will want back in a minute, so what a Mac promises a session is its/// peak and never its idle reading.////// THESE LIVE IN MEMORY AND A RESTART OF THIS HELPER BEGINS THE COUNT/// AGAIN. That is honest rather than persisted: a peak carried across a/// restart would outlive the session it measured. It is also exactly why/// [`session_peak_samples`](crate::protocol::MachineSample::session_peak_samples)/// is reported beside the peak — one reading of an idle session is not a/// budget, and the reader can tell. session_peaks: HashMap<String, f64>,/// How many session readings those peaks are drawn from — one per session/// per sample tick. session_peak_samples: u32,/// The largest Cotton's Chrome has been measured at, gigabytes — the/// browser tool's own peak, because Chrome is launchd's child and no/// session's tree holds it (`crate::browser::budget`). browser_peak_gb: f64,}implHostState {/// The pseudo-terminal behind an id, whichever kind of terminal it is.////// ONE lookup for both, so `write`, `resize` and `stop` cannot come to/// different conclusions about what an id names. A session first: a/// utility id is namespaced and cannot collide, and the order is only/// about which map is asked first.fn pty_of(&self, id: &str) -> Option<Arc<PtySession>> {self.sessions .get(id) .map(|held| Arc::clone(&held.pty)) .or_else(|| self.utilities.get(id).map(|held| Arc::clone(&held.pty))) }/// Everything an `attach` needs, for either kind of terminal. #[allow(clippy::type_complexity)]fn streamable( &self, id: &str, ) -> Option<(Arc<PtySession>,Arc<Mutex<Scrollback>>, broadcast::Receiver<Vec<u8>>, )> {ifletSome(session) = self.sessions.get(id) {returnSome((Arc::clone(&session.pty),Arc::clone(&session.scrollback), session.data.subscribe(), )); }let utility = self.utilities.get(id)?;Some((Arc::clone(&utility.pty),Arc::clone(&utility.scrollback), utility.data.subscribe(), )) }/// The utility of this purpose that is still running, if there is one.fn utility_running(&self, purpose: &str) -> Option<&str> {self.utilities.values().find_map(|held| { (held.running && held.purpose == purpose).then_some(held.id.as_str()) }) }}/// The daemon.pubstructHost { layout: Layout, flavor: Flavor, clock: Arc<dynClock>, host_binary: String,/// **THIS HOST'S OWN EXECUTABLE**, fingerprinted at `new` and re-read every/// minute by [`Self::run`]. A Sparkle update replaces the bundle under a/// `KeepAlive` daemon, and nothing else would ever end the process launchd/// would relaunch — see [`crate::binary`]. binary: Arc<binary::Watch>,/// **WHAT THIS MACHINE IS** — chip, OS version, the data volume's size —/// read once at `new` and carried on every sample ([`machine::Facts`]). facts: machine::Facts,/// Where the two agents keep their transcripts. `None` turns adoption off/// entirely — what a test that is about something else gets, and what a/// process with no `HOME` gets. adopted_roots: Option<Roots>, stop_schedule: StopSchedule, permission_timeout: Duration,/// The environment every agent is detected in and every pseudo-terminal/// runs in — see [`crate::login_env`]. Empty means inherit, which is what/// a test that is about something else gets. login_env: LoginEnv, state: Arc<Mutex<HostState>>, events: broadcast::Sender<Event>,}/// **SESSIONS MOVE OUT OF THE DATA FOLDER, once** (architect, 15 Oct 2026):/// a host that finds `<dataDir>/sessions` and no sessions folder of its own/// renames the old one into place — the index, every scrollback and every/// launch folder with it — so `list` keeps its history and nothing of a/// session stays in the data folder. Both folders are/// on the person's own disk, so a rename that fails is a refusal to start,/// never a quiet second copy.fn move_sessions_out_of_the_data_folder(layout: &Layout) -> std::io::Result<()> {let old = layout.sessions_in_the_data_folder();let new = layout.sessions_dir();if old == new || !old.is_dir() || new.exists() {returnOk(()); }ifletSome(parent) = new.parent() { std::fs::create_dir_all(parent)?; } std::fs::rename(&old, &new).map_err(|error| { std::io::Error::new(error.kind(), format!("the sessions in {} could not move to {} — {error}", old.display(), new.display())) })?; eprintln!("cotton-session-host: moved the sessions from {} to {}", old.display(), new.display());Ok(())}implHost {/// Bring a host up over a data directory.////// `host_binary` is this executable's own path: every hook command the/// adapters write re-invokes it, so a host running from a build directory/// and one running from the app bundle write different hook commands, each/// correct for itself.pubfn new( layout: Layout, clock: Arc<dynClock>, host_binary: String, flavor: Flavor, ) -> Result<Self, ServeError> { std::fs::create_dir_all(layout.own())?; move_sessions_out_of_the_data_folder(&layout)?; std::fs::create_dir_all(layout.sessions_dir())?;letmut index = Index::load(&layout.index())?;let ended = index.end_everything_left_running(&clock.now_rfc3339());if ended > 0 { index.save(&layout.index())?; }let (events, _) = broadcast::channel(EVENT_BACKLOG);// BEFORE the daemon serves anything: the identity is what the// executable was when this process started, and a fingerprint read// later would already be the replacement's.let binary = Arc::new(binary::Watch::of(&host_binary));// Once, here, for the same reason: what this machine IS is not a// reading, and the mirror writes it onto the device row once.let facts = machine::facts(layout.own());Ok(Self { layout, flavor, clock, host_binary, binary, facts, stop_schedule: StopSchedule::default(), permission_timeout: Duration::from_secs(agents::PERMISSION_TIMEOUT_SECONDS), login_env: LoginEnv::inherited(), adopted_roots: None, state: Arc::new(Mutex::new(HostState { index, sessions: HashMap::new(), adopted: HashMap::new(), utilities: HashMap::new(), watcher: Watcher::new(), last_detected: None, last_accounts: BTreeMap::new(), session_peaks: HashMap::new(), session_peak_samples: 0, browser_peak_gb: 0.0, })), events, }) }/// Watch these transcript directories for sessions this host did not/// spawn.////// The roots are the caller's because resolving them reads the/// environment, and `main.rs` is the one place in this crate that does.pubfn watching(mutself, roots: Roots) -> Self {self.adopted_roots = Some(roots);self }/// Detect agents in, and spawn every terminal in, this environment.////// The capture reads the process and runs a shell, so it is `main.rs`'s to/// make — the one place in this crate that reads the environment.pubfn in_login_env(mutself, env: LoginEnv) -> Self {self.login_env = env;self }/// Shorten the stop schedule and the permission wait — what a test does so/// the schedule is proved in milliseconds rather than in half an hour.pubfn with_schedules(mutself, stop: StopSchedule, permission: Duration) -> Self {self.stop_schedule = stop;self.permission_timeout = permission;self }/// Bind the socket, refusing to displace a host that is already serving.pubasyncfn bind(&self) -> Result<UnixListener, ServeError> {let path = self.layout.socket();// BEFORE ANYTHING TOUCHES THE PATH. A path too long for `sun_path` is// refused by `bind` with an error carrying neither the path nor the// limit, and it is refused by `connect` the same way — so the// already-serving check above would misread a long path as "nobody is// listening" and unlink a socket it had no business unlinking.ifletSome(refusal) = socket_path_refusal(&path) {returnErr(refusal); }if path.exists() {// WHAT IS THERE IS DECIDED BY THE FILE TYPE, NOT BY THE CONNECT.// Connecting to a path that is a regular file answers ECONNREFUSED// on Linux and ENOTSOCK on macOS, so the error cannot tell "a// crashed host's socket" from "somebody else's file" — and the// first of those is unlinked while the second must never be.let kind = std::fs::symlink_metadata(&path)?.file_type();if !kind.is_socket() {returnErr(ServeError::SocketPathBlocked { path: path.display().to_string(), said: "it is not a socket at all".to_string(), }); }// It is a socket. Somebody is listening on it, or a crash left the// node behind. Ask.matchUnixStream::connect(&path).await {Ok(_) => {returnErr(ServeError::AlreadyServing { path: path.display().to_string(), }) }Err(error) if error.kind() == ErrorKind::ConnectionRefused => { std::fs::remove_file(&path)?; }Err(error) => {returnErr(ServeError::SocketPathBlocked { path: path.display().to_string(), said: error.to_string(), }) } } }let listener = UnixListener::bind(&path)?; std::fs::set_permissions(&path, std::fs::Permissions::from_mode(SOCKET_MODE))?;Ok(listener) }/// Serve until the process is stopped.pubasyncfn run(self: Arc<Self>, listener: UnixListener) -> Result<(), ServeError> {let sampler = Arc::clone(&self); tokio::spawn(asyncmove {letmut ticks = tokio::time::interval(Duration::from_secs( machine::SAMPLE_EVERY_SECONDS, ));loop { ticks.tick().await;let sampling = Arc::clone(&sampler);let _ = writeln!(std::io::stderr(), "cotton-session-host: sample started");// A failed sample is one failed tick, never the end of reporting.match tokio::spawn(asyncmove { sampling.sample().await }).await {Ok(reading) => {let _ = writeln!(std::io::stderr(), "cotton-session-host: sample completed {}", reading.sampled_at);let _ = sampler.events.send(Event::Sample { sample: reading }); }Err(error) => {let _ = writeln!(std::io::stderr(), "cotton-session-host: sample failed; retry next tick — {error}"); } } } });// **THE SELF-WATCH.** One `stat(2)` a minute against the executable// this process started from. `KeepAlive` is what makes this helper// outlive the app; without this it is also what makes a stale helper// permanent, because nothing ever ends the process launchd would// relaunch (`crate::binary`, and the 2026-09-22 entry in// Cotton note "Repo landmines — why the build's rules exist").let watcher = Arc::clone(&self); tokio::spawn(asyncmove {letmut ticks = tokio::time::interval(Duration::from_secs(binary::CHECK_EVERY_SECONDS));// The first tick fires immediately, which is the right moment to// say what this host is running.letmut said: Option<Verdict> = None;loop { ticks.tick().await;let alive = watcher.host_owned_alive().await;let verdict = watcher.binary.check(alive);// A line per verdict, and the verdict changes rarely: this// loop runs for weeks, and `unchanged` sixty times an hour// would be the only thing in the log.if said != Some(verdict) { eprintln!("cotton-session-host: {}", watcher.binary.line(verdict, alive) ); said = Some(verdict); }if verdict == Verdict::Exit {// EXIT 0, never an abort: launchd reads a clean exit under// `KeepAlive` as "start it again", and what is at the path// now is the new bundle's binary. std::process::exit(0); } } });ifself.adopted_roots.is_some() {let scanner = Arc::clone(&self); tokio::spawn(asyncmove {letmut ticks = tokio::time::interval(Duration::from_secs( adopted::SCAN_EVERY_SECONDS, ));loop { ticks.tick().await; scanner.adopt_pass().await; } }); }loop {let (stream, _) = listener.accept().await?;let host = Arc::clone(&self); tokio::spawn(asyncmove {ifletErr(error) = host.serve_connection(stream).await {// A client that went away mid-message is ordinary; it is// logged rather than swallowed so a real protocol fault is// still visible in the host's own output. eprintln!("cotton-session-host: a connection ended — {error}"); } }); } }/// Read what this machine looks like right now.////// **THE AGENTS ARE RE-DETECTED ON EVERY SAMPLE**, not once at startup./// This daemon is `KeepAlive` and outlives the app; a person installs/// `codex`, or `claude` updates itself, while it runs — and a map read/// once at boot would answer "not installed" until somebody thought to/// restart a helper they do not know exists.pubasyncfn sample(&self) -> MachineSample {// Off the reactor: two `--version` subprocesses and a `ps`, on the// same runtime as every terminal's bytes.let env = self.login_env.clone();let (detected, accounts) = tokio::task::spawn_blocking(move || {let detected = machine::detect(&env);// ASKED ON EVERY SAMPLE, for the agents' own reason: a person// signs in, signs out or switches login while this daemon runs,// and the dispatcher places a session on what this says.let accounts = machine::signed_in(&env, &detected); (detected, accounts) }) .await .unwrap_or_default();// ONE reading of the process table for the whole tick, so every number// below describes the same instant. An empty table is a `ps` that did// not answer, and it reads as nothing measured.let rows = tokio::task::spawn_blocking(processes::snapshot) .await .unwrap_or_default();// ONE memory reading too, and the committed figure is computed from// it: the kernel already measures everything that is running —// simulators, builds, whatever holds the build lock — properly, shared// pages and all. What this host adds to it is the headroom its own// sessions have not asked for yet.let memory = tokio::task::spawn_blocking(machine::memory) .await .unwrap_or_default();let (running, measured) = {letmut state = self.state.lock().await;if state.last_detected.as_ref() != Some(&detected) {let _ = writeln!(std::io::stderr(), "cotton-session-host: agents — {}", machine::describe(&detected)); state.last_detected = Some(detected.clone()); }if state.last_accounts != accounts {let _ = writeln!( std::io::stderr(), "cotton-session-host: signed in — {}", describe_accounts(&accounts) ); state.last_accounts = accounts.clone(); }// THE ONES THIS HOST STILL OWNS A TERMINAL FOR, which is what the// field says it is. An ended session stays in the map so its// scrollback keeps answering, and counting it told the dispatcher// a Mac was full of sessions that had finished.let running = state .sessions .values() .filter(|held| held.summary.host_owned) .count() as u32;// Only a session this host still owns a terminal for has a tree to// measure: an adopted session is somebody else's process and an// ended one is nobody's.let live: Vec<(String, u32)> = state .sessions .iter() .filter(|(_, held)| held.summary.host_owned) .filter_map(|(id, held)| held.pty.pid().map(|pid| (id.clone(), pid))) .collect();if !rows.is_empty() {for (id, pid) in &live {let held_gb = processes::rss_gb(&rows, &processes::tree(&rows, *pid));let peak = state.session_peaks.entry(id.clone()).or_insert(0.0); *peak = peak.max(held_gb); state.session_peak_samples = state.session_peak_samples.saturating_add(1); } }let sessions: Vec<processes::SessionUsage> = live .iter() .map(|(id, pid)| processes::SessionUsage { root: *pid, peak_gb: state.session_peaks.get(id).copied().unwrap_or(0.0), }) .collect();// THE BROWSER TOOL'S CHROME, which no session's tree holds: its// own peak, and — while a live session could start it with one// tool call — what it is declared to cost before it runs.let could_start = !live.is_empty() && crate::browser::offer(&self.login_env, self.layout.root(), self.flavor).is_some();let chrome =crate::browser::chrome_pid(&crate::browser::profile_dir(&self.layout), &rows);let (browser_peak, browser_headroom) =crate::browser::budget(&rows, chrome, could_start, state.browser_peak_gb); state.browser_peak_gb = browser_peak;let measured = machine::Measured { memory, committed_gb: processes::committed_gb(&rows, &sessions, memory.used_gb()) + browser_headroom, session_peak_gb: state .session_peaks .values() .copied() .fold(None, |largest, peak| {Some(largest.map_or(peak, |held: f64| held.max(peak))) }), session_peak_samples: state.session_peak_samples, }; (running, measured) }; machine::sample(self.clock.as_ref(),self.layout.own(), running, detected.versions, accounts, machine::HandedIn { binary: self.binary.report(), measured, facts: &self.facts, }, ) }/// How many sessions this host still OWNS a pseudo-terminal for.////// Not `sessions.len()`: an ended session stays in the map so its/// scrollback and its summary keep answering, with `host_owned` false. The/// restart decision is about turns that would be cut short, so it counts/// the ones that are still running and nothing else.pubasyncfn host_owned_alive(&self) -> u32 {let state = self.state.lock().await; state .sessions .values() .filter(|held| held.summary.host_owned) .count() as u32 }/// The agent's own session id this host recorded for a session, if any.////// Read out of the INDEX rather than the live map, so it answers for a/// session that ended — which is the only kind anything asks about.pubasyncfn remembered_agent_session_id(&self, session_id: &str) -> Option<String> {let state = self.state.lock().await; state.index.agent_session_ids().get(session_id).cloned() }/// One pass of the transcript scan: adopt what is new, say what changed.////// Public so a test drives it by hand rather than waiting fifteen seconds/// for a timer — the same reason [`Self::sample`] is.pubasyncfn adopt_pass(&self) -> adopted::Observed {letSome(roots) = self.adopted_roots.clone() else {return adopted::Observed::default(); };// The walk is a few dozen `stat` calls on a disk; off the runtime's// reactor thread, because everything else on it is a terminal's bytes.// The user's own hooks are read with the walk, every pass: a hook// installed or removed while this host runs takes effect on the next.let (found, hooked) = tokio::task::spawn_blocking(move || { ( adopted::scan(&roots), adopted::hooked_tools(&roots), ) }) .await .unwrap_or_default();let now_rfc3339 = self.clock.now_rfc3339();let now_epoch = epoch_seconds(&now_rfc3339);let (events, observed) = {letmut state = self.state.lock().await;// A session this host SPAWNED writes a transcript in the same// directory. Its own events are the truth about it, so its file is// skipped rather than adopted into a second card.let owned: std::collections::BTreeSet<String> = state .sessions .values() .flat_map(|held| { [Some(held.summary.session_id.clone()), held.summary.agent_session_id.clone(), ] }) .flatten() .collect(); state.watcher.set_hooked(hooked);let (events, observed) = state .watcher .observe(now_epoch, &now_rfc3339, &found, &owned, &FileTranscripts);for event in &events {self.remember_adopted(&mut state, event); }if observed.adopted > 0 {let _ = state.index.save(&self.layout.index()); } (events, observed) };for event in events {let _ = self.events.send(event); } observed }/// Keep the summary and the index in step with what the scan just said.fn remember_adopted(&self, state: &mutHostState, event: &Event) {match event {Event::Adopted { session_id, tool, cwd, started_at, } => {let cwd = cwd.clone().unwrap_or_default(); state.adopted.insert( session_id.clone(),SessionSummary { session_id: session_id.clone(),// Nobody launched it. An invented launch id would be a// row pointing at a queue entry that does not exist. launch_id: String::new(), tool: *tool, agent_session_id: Some(session_id.clone()), cwd: cwd.clone(), started_at: started_at.clone(), ended_at: None, state: SessionState::Starting, waiting_kind: None, request_id: None, exit_code: None, exit_signal: None, host_owned: false, }, ); state.index.upsert(IndexEntry { id: session_id.clone(), tool: *tool, launch_id: String::new(), agent_session_id: Some(session_id.clone()), cwd, started_at: started_at.clone(), ended_at: None, exit: None, adopted: true, }); }Event::State { session_id, state: to, .. } => {ifletSome(held) = state.adopted.get_mut(session_id) { held.state = *to; } }Event::Exited { session_id, .. } => {let at = self.clock.now_rfc3339();ifletSome(held) = state.adopted.get_mut(session_id) { held.state = SessionState::Ended; held.ended_at = Some(at.clone()); } state.index.end( session_id, &at,Exit { code: None, signal: None, }, ); } _ => {} } }/// The refusal for something only the owner of a pseudo-terminal can do.////// An adopted session is a CARD, not a terminal: this host found it in a/// transcript and holds nothing of it. Named rather than answered with/// "no such session", because the two are different things to fix.asyncfn refuse(&self, session_id: &str) -> String {let state = self.state.lock().await; refusal_for(&state, session_id) }asyncfn serve_connection(self: &Arc<Self>, stream: UnixStream) -> Result<(), ServeError> {let (read, mut write) = stream.into_split();let (out, mut outbox) = mpsc::unbounded_channel::<String>();let writer = tokio::spawn(asyncmove {whileletSome(text) = outbox.recv().await {if write.write_all(text.as_bytes()).await.is_err() {return; } } });letmut lines = BufReader::new(read).lines();letmut streaming: Vec<tokio::task::JoinHandle<()>> = Vec::new();whileletSome(text) = lines.next_line().await? {if text.trim().is_empty() {continue; }let request: Request = match parse(&text) {Ok(request) => request,Err(error) => { send(&out, &Event::Error { message: error.to_string(), });continue; } };if matches!(request, Request::Detach) {for task in streaming.drain(..) { task.abort(); } send(&out, &Event::Ok);continue; }ifletSome(task) = self.handle(request, &out).await { streaming.push(task); } }for task in streaming { task.abort(); } drop(out);let _ = writer.await;Ok(()) }/// Answer one request. Returns a task when the connection became a stream.asyncfn handle(self: &Arc<Self>, request: Request, out: &mpsc::UnboundedSender<String>, ) -> Option<tokio::task::JoinHandle<()>> {match request {Request::Spawn { launch_id, session_id, tool, argv_extras, cwd, env, cols, rows, permission_mode, resume_from, } => {let session_id = session_id.unwrap_or_else(|| self.mint_session_id());matchself .spawn( launch_id.clone(), session_id.clone(), tool, argv_extras, cwd, env, cols, rows, permission_mode, resume_from, ) .await {Ok(pid) => send(out, &Event::Spawned { session_id, launch_id, pid, }),Err(message) => send(out, &Event::Error { message }), }None }Request::SpawnUtility { purpose, argv, cwd, env, cols, rows, } => {matchself .spawn_utility(purpose.clone(), argv, cwd, env, cols, rows) .await {Ok((id, pid)) => send(out, &Event::UtilityStarted { id, purpose, pid }),Err(message) => send(out, &Event::Error { message }), }None }Request::Attach { session_id, cols, rows, from_offset, } => self.attach(&session_id, cols, rows, from_offset, out).await,Request::Write { session_id, b } => {match base64::engine::general_purpose::STANDARD.decode(b.as_bytes()) {Ok(bytes) => {// A UTILITY IS WRITTEN TO LIKE ANY OTHER TERMINAL.// Signing an agent in is a browser flow with keystrokes// on either side of it, and a view that could show the// bytes but not answer them would be a screenshot.let pty = self.state.lock().await.pty_of(&session_id);match pty {Some(pty) => match pty.write(&bytes).await {Ok(()) => send(out, &Event::Ok),Err(error) => send(out, &Event::Error { message: error.to_string(), }), },None => send(out, &Event::Error { message: self.refuse(&session_id).await, }), } }Err(error) => send(out, &Event::Error { message: format!("the bytes on a write were not base64 — {error}"), }), }None }Request::Resize { session_id, cols, rows, } => {let pty = self.state.lock().await.pty_of(&session_id);match pty {Some(pty) => match pty.resize(cols, rows).await {Ok(()) => send(out, &Event::Ok),Err(error) => send(out, &Event::Error { message: error.to_string(), }), },None => send(out, &Event::Error { message: self.refuse(&session_id).await, }), }None }// Handled by the connection loop, which owns the streaming tasks.Request::Detach => None,Request::Stop { session_id } => {let pty = self.state.lock().await.pty_of(&session_id);match pty {Some(pty) => {let schedule = self.stop_schedule; tokio::spawn(asyncmove {let _ = pty.stop(schedule).await; }); send(out, &Event::Ok); }None => send(out, &Event::Error { message: self.refuse(&session_id).await, }), }None }Request::Decide { session_id, request_id, decision, } => {letmut state = self.state.lock().await;match state.sessions.get_mut(&session_id) {Some(session) => match session.pending.remove(&request_id) {Some(answer) => {let _ = answer.send(decision); session.summary.state = SessionState::Running; session.summary.waiting_kind = None; session.summary.request_id = None;let event = Event::State { session_id, state: SessionState::Running, waiting_kind: None, request_id: None, };let _ = self.events.send(event); send(out, &Event::Ok); }None => send(out, &Event::Error { message: format!("no permission request {request_id} is waiting on session {session_id} — it was answered already, or it timed out and the session fell back to its own prompt" ), }), },// NOT `self.refuse(…).await`: this arm is inside the state// lock, and asking for it a second time is a deadlock the// whole daemon stops on.None => {let message = refusal_for(&state, &session_id); send(out, &Event::Error { message }) } }None }Request::List => { send(out, &Event::Sessions { sessions: self.list().await, });None }Request::Subscribe => {letmut stream = self.events.subscribe();// **THE ACKNOWLEDGEMENT COMES FIRST, AND IT IS NOT OPTIONAL.**// `subscribe` turns a request/answer channel into a stream, and// a stream that opens with nothing on it is indistinguishable// from a socket nobody answered: the client's own dial// (`cotton_client::session_host::HostLink::connect`) asks for// this and waits `SUBSCRIBE_ANSWER_MS` for it. Measured// 2026-09-19 with no ack here: every dial timed out, the app// ran for ever unsubscribed, and every `state`, `turn`,// `usage`, `sample`, `adopted` and `exited` this host broadcast// reached nobody — while `spawn` kept working, because the// executor opens a connection of its own. So a session started// and then never moved off `starting`.//// BEFORE the forwarder is spawned, so it is the first line on// this connection whatever the broadcast is doing. send(out, &Event::Ok);// **AND THE ADOPTED SESSIONS 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 on every app start (daily,// on a Sparkle update) the subscriber that comes back has// missed every announcement there has ever been. Measured// 2026-09-19: a helper holding forty adopted sessions handed a// freshly started app none of them, and the phone's Code// screen showed only the sessions Cotton had launched itself.//// Re-announcing is safe by construction — the mirror dedupes on// `(tool, external_id)` and keeps the row's own history// (`cotton_client::session_host::mirror`) — and it is the same// promise `attach` keeps: a viewer that joins is told what it// missed rather than left to infer it.for summary inself.adopted_now().await { send(out, &Event::Adopted { session_id: summary.session_id.clone(), tool: summary.tool, cwd: (!summary.cwd.is_empty()).then(|| summary.cwd.clone()), started_at: summary.started_at.clone(), });// And where it had got to, so a replayed card is not stuck// at `starting` until the file next changes. send(out, &Event::State { session_id: summary.session_id.clone(), state: summary.state, waiting_kind: summary.waiting_kind, request_id: summary.request_id.clone(), }); }let out = out.clone();Some(tokio::spawn(asyncmove {whileletOk(event) = stream.recv().await {if out.send(match line(&event) {Ok(text) => text,Err(_) => continue, }) .is_err() {return; } } })) }Request::Sample => { send(out, &Event::Sample { sample: self.sample().await, });None }Request::Restart => {let alive = self.host_owned_alive().await;// NOT `binary.check(…)`: the asker has already decided this// helper is not the binary it ships, and the file on disk is// its evidence rather than ours. What this end decides is the// ONE rule a restart is subject to — a live session outranks// it.let restarting = alive == 0;if !restarting {self.binary.defer(); }// The ANSWER GOES FIRST, on this connection, and only then// does the process go: an asker that learned the outcome from// a socket that closed could not tell "it restarted" from "it// was never there". send(out, &Event::Restarting { restarting, sessions_running: alive, }); eprintln!("cotton-session-host: {}",self.binary.line(if restarting { Verdict::Exit } else { Verdict::Defer }, alive ) );if restarting {// The write is handed to the connection's own task, so// the exit waits a beat for it to leave the socket. tokio::spawn(asyncmove { tokio::time::sleep(Duration::from_millis(RESTART_FLUSH_MS)).await; std::process::exit(0); }); }None }Request::Hook { event, session_id, payload, } => self.hook(event, session_id, payload, out).await,Request::Statusline { session_id, payload, } => {self.usage_from(session_id, &payload).await; send(out, &Event::Ok);None } } }fn mint_session_id(&self) -> String {// The host's own id, when the caller did not bring one. Not a uuid// crate: the stamp plus this process's pid plus a counter is unique on// one Mac, which is the whole scope of a session id the host minted.use std::sync::atomic::{AtomicU64, Ordering};static NEXT: AtomicU64 = AtomicU64::new(1); format!("host-{}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed),self.clock.now_rfc3339().replace([':', '-'], "") ) } #[allow(clippy::too_many_arguments)]asyncfn spawn(self: &Arc<Self>, launch_id: String, session_id: String, tool: Tool, argv_extras: Vec<String>, cwd: String, env: std::collections::BTreeMap<String, String>, cols: u16, rows: u16, permission_mode: PermissionMode, resume_from: Option<String>, ) -> Result<Option<u32>, String> {// **WHICH AGENT SESSION THIS CONTINUES**, resolved HERE because this// is the only place that holds the mapping. `claude` was told to use// our id, so ours IS the agent's; `codex` minted its own and the// `SessionStart` hook wrote it onto the index entry, which the upsert// below is about to replace. A resume of a Codex session whose agent// id this host never learned falls back to the id it was given rather// than refusing — the agent says what it cannot resume far better than// a guess here would.let resume = match resume_from {None => None,Some(id) => match tool {Tool::Claude => Some(id),Tool::Codex => Some(self.remembered_agent_session_id(&id).await.unwrap_or(id)), }, };let launch_dir = self.layout.session_dir(&session_id); std::fs::create_dir_all(&launch_dir) .map_err(|error| format!("{} could not be made — {error}", launch_dir.display()))?;letmut env = self.login_env.merged(env);// Cotton hooks and MCP helpers serve this host, even when the login// shell or a session request carries the other app's flavor. env.insert(FLAVOR_ENV.to_string(), self.flavor.as_str().to_string());let launch = Launch { launch_id: launch_id.clone(), session_id: session_id.clone(), argv_extras, cwd: cwd.clone(),// THE PERSON'S OWN ENVIRONMENT, with the request's on top of it.// A session started by a launchd-run host would otherwise see// launchd's four-directory PATH, no locale and none of the shims a// person's toolchain hangs off — and the rule the Code tool is// built to is that both agents work exactly as they would in a// terminal. env, cols, rows, permission_mode, host_binary: self.host_binary.clone(), launch_dir: launch_dir.display().to_string(), resume: resume.clone(),// Asked at every launch rather than once at start: Chrome or Node// installed after the host started is offered to the next session. browser: crate::browser::offer(&self.login_env, self.layout.root(), self.flavor), };let adapter = agents::adapter(tool);for file in adapter.hook_files(&launch) { std::fs::write(&file.path, file.contents.as_bytes()) .map_err(|error| format!("{} could not be written — {error}", file.path))?; }letmut plan = adapter.spawn_plan(&launch);// The adapter names the agent (`claude`, `codex`); WHICH ONE is the// first on the PATH the child itself gets — the declared one with the// request's on top. A `Command` searches with the PATH it was given,// not the one it hands the child, so a plan left holding a bare name// would be looked up in launchd's.ifletSome(program) = plan.argv.first_mut() {let path = plan.env.get("PATH").map(String::as_str).unwrap_or("");ifletSome(found) = crate::login_env::resolve_program(path, program) { *program = found.display().to_string(); } }let (output, mut bytes) = mpsc::unbounded_channel();let pty = Arc::new(PtySession::spawn(&plan, output).map_err(|error| error.to_string())?);let pid = pty.pid();let scrollback = Arc::new(Mutex::new(Scrollback::open(self.layout.scrollback(&session_id)) .map_err(|error| format!("the scrollback for {session_id} — {error}"))?, ));let (data, _) = broadcast::channel(EVENT_BACKLOG);let started_at = self.clock.now_rfc3339();let summary = SessionSummary { session_id: session_id.clone(), launch_id: launch_id.clone(), tool, agent_session_id: match tool {// `claude` was told to use ours; `codex` mints its own and the// host learns it from the SessionStart hook. A RESUME already// knows it — it is the id the agent was asked to continue, and// dropping it here would make the next resume of the same// session a first start.Tool::Claude => Some(session_id.clone()),Tool::Codex => resume.clone(), }, cwd: cwd.clone(), started_at: started_at.clone(), ended_at: None, state: SessionState::Starting, waiting_kind: None, request_id: None, exit_code: None, exit_signal: None, host_owned: true, }; {letmut state = self.state.lock().await; state.index.upsert(IndexEntry { id: session_id.clone(), tool, launch_id: launch_id.clone(), agent_session_id: summary.agent_session_id.clone(), cwd, started_at, ended_at: None, exit: None, adopted: false, });let _ = state.index.save(&self.layout.index()); state.sessions.insert( session_id.clone(),Session { summary, tool, pty: Arc::clone(&pty), scrollback: Arc::clone(&scrollback), data: data.clone(), pending: HashMap::new(), turn_seq: 0, }, ); }// The pump: every byte the terminal writes lands in the ring and, when// anybody is attached, on the wire. A `send` with no receivers is not// an error — nobody is watching, and the ring is still the record.let pumping = session_id.clone();let tail = Arc::new(std::sync::Mutex::new(crate::exit_reason::Tail::default()));let said = Arc::clone(&tail);let born = std::time::Instant::now();let pump = tokio::spawn(asyncmove {whileletSome(chunk) = bytes.recv().await { said.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).push(&chunk);ifletErr(error) = scrollback.lock().await.append(&chunk) { eprintln!("cotton-session-host: the scrollback for {pumping} — {error}"); }let _ = data.send(chunk); } });let host = Arc::clone(self);let ending = session_id.clone(); tokio::spawn(asyncmove {let exit = pty.wait().await;let lived = born.elapsed();// The child's last words reach the tail before the row learns why// it ended; a grandchild still holding the terminal open bounds// the wait rather than holding the end back.let _ = tokio::time::timeout(Duration::from_secs(2), pump).await;let error = {let tail = tail.lock().unwrap_or_else(|poisoned| poisoned.into_inner());crate::exit_reason::exit_error(exit, lived, tail.last_line()) }; host.ended(&ending, exit.code, exit.signal, error).await; });Ok(pid) }/// Run a command in a pseudo-terminal, and nothing else.////// **EVERY WAY THIS IS NOT A SPAWN IS DELIBERATE.** No adapter, so no/// hook file is written and no hook can fire; no `IndexEntry`, so/// `sessions/index.json` never learns about it and a restart of the/// daemon does not stamp one as an ended session; nothing in/// `state.sessions`, so `list`, `sessions_running` and the transcript/// scan's own skip-list are all untouched. What a utility shares with a/// session is the pseudo-terminal, the scrollback ring and the attach/// path — which is the whole of what a terminal view needs/// ([`crate::utility`]).asyncfn spawn_utility(self: &Arc<Self>, purpose: String, argv: Vec<String>, cwd: Option<String>, env: std::collections::BTreeMap<String, String>, cols: Option<u16>, rows: Option<u16>, ) -> Result<(String, Option<u32>), String> {ifletSome(refusal) = utility::purpose_refusal(&purpose) {returnErr(refusal); }ifletSome(refusal) = utility::argv_refusal(&argv) {returnErr(refusal); }// **THE PROGRAM IS RESOLVED BEFORE ANYTHING IS OPENED.** `npm` on a// Mac with no Node is the case this exists for: a terminal that opened// and died with a shell's own wording would tell a person nothing they// could act on, and the panel's whole job is to say what to do next.let program = self.login_env.program_path(&argv[0]);if !Path::new(&program).is_absolute() {returnErr(utility::no_program_refusal(&argv[0])); }// **ONE LOCK FROM THE CHECK TO THE INSERT.** The one-at-a-time rule is// worth nothing if two buttons pressed together both read "nothing is// running" and then both start one. Every step below is synchronous —// a `stat`, a `remove_file`, `openpty` — so nothing awaits while it is// held.letmut state = self.state.lock().await;ifletSome(running) = state.utility_running(&purpose) {returnErr(utility::busy_refusal(&purpose, running)); }// The finished one of this purpose, if there is one, goes now: its// scrollback file is about to be written from the start, and an entry// pointing at a ring somebody else is filling would replay the wrong// install. state.utilities.retain(|_, held| held.purpose != purpose);let id = {use std::sync::atomic::{AtomicU64, Ordering};static NEXT: AtomicU64 = AtomicU64::new(1); utility::utility_id(&purpose, std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)) };letmut plan_argv = argv; plan_argv[0] = program;let plan = SpawnPlan { argv: plan_argv,// THE PERSON'S OWN ENVIRONMENT, exactly as a session gets it: an// installer that ran on launchd's four-directory PATH would put// the agent somewhere no session would ever find it. env: self.login_env.merged(env), cwd: cwd .filter(|path| !path.trim().is_empty()) .or_else(|| self.login_env.get("HOME").map(str::to_string)) .unwrap_or_else(|| "/".to_string()), cols: cols.unwrap_or(utility::UTILITY_COLS), rows: rows.unwrap_or(utility::UTILITY_ROWS), };// FROM THE START, not appended to the last run of this purpose: what// the view replays has to be this install, not this install after the// one that failed yesterday.let path = self.layout.utility_scrollback(&purpose);let _ = std::fs::remove_file(&path);let scrollback = Arc::new(Mutex::new(Scrollback::open(&path) .map_err(|error| format!("the scrollback for {purpose} — {error}"))?, ));let (output, mut bytes) = mpsc::unbounded_channel();let pty = Arc::new(PtySession::spawn(&plan, output).map_err(|error| error.to_string())?);let pid = pty.pid();let (data, _) = broadcast::channel(EVENT_BACKLOG); state.utilities.insert( id.clone(),Utility { id: id.clone(), purpose: purpose.clone(), pty: Arc::clone(&pty), scrollback: Arc::clone(&scrollback), data: data.clone(), running: true, }, ); drop(state);let pumping = purpose.clone(); tokio::spawn(asyncmove {whileletSome(chunk) = bytes.recv().await {ifletErr(error) = scrollback.lock().await.append(&chunk) { eprintln!("cotton-session-host: the scrollback for {pumping} — {error}"); }let _ = data.send(chunk); } });let host = Arc::clone(self);let ending = id.clone(); tokio::spawn(asyncmove {let exit = pty.wait().await; host.utility_ended(&ending, exit.code, exit.signal).await; });Ok((id, pid)) }/// A utility's process is gone.////// **AND THIS MAC IS SAMPLED AGAIN.** A utility is the one thing running/// on this Mac that changes what a sample SAYS — an install that just/// finished is an agent that is now installed, a sign-in is a login the/// next session will report — and the panel reads the sample, not the/// helper. Without this, a person who watched `claude` install would keep/// reading *not installed* for up to five minutes and conclude it had/// failed.asyncfn utility_ended(self: &Arc<Self>, id: &str, code: Option<i32>, signal: Option<i32>) {let at = self.clock.now_rfc3339();let purpose = {letmut state = self.state.lock().await;match state.utilities.get_mut(id) {Some(held) => { held.running = false; held.purpose.clone() }// Already replaced by a later utility of the same purpose.None => return, } };let _ = self.events.send(Event::UtilityEnded { id: id.to_string(), purpose, code, signal, at, });let reading = self.sample().await;let _ = self.events.send(Event::Sample { sample: reading }); }asyncfn ended(&self, session_id: &str, code: Option<i32>, signal: Option<i32>, error: Option<String>) {let at = self.clock.now_rfc3339();letmut state = self.state.lock().await;ifletSome(session) = state.sessions.get_mut(session_id) { session.summary.state = SessionState::Ended; session.summary.ended_at = Some(at.clone()); session.summary.exit_code = code; session.summary.exit_signal = signal; session.summary.host_owned = false; session.pending.clear(); }// The peak went with the process. What it promised is over, and a Mac// that kept it would refuse the next session on memory nothing holds. state.session_peaks.remove(session_id); state.index.end(session_id, &at, Exit { code, signal });let _ = state.index.save(&self.layout.index()); drop(state);let _ = self.events.send(Event::Exited { session_id: session_id.to_string(), code, signal,// THE SAME INSTANT THE INDEX JUST WROTE, not a second reading of// the clock: the row on the phone and the index on this Mac are// two spellings of one event, and two stamps a millisecond apart// would be two answers to when it ended. at: Some(at.clone()), error, }); }/// The sessions this host FOUND, as it holds them now.////// Separate from [`Self::list`], which answers every session the index/// remembers: what a new subscriber has to be told about is the adopted/// ones, because those are the only ones whose whole existence arrived as/// an event nothing replays.asyncfn adopted_now(&self) -> Vec<SessionSummary> {let state = self.state.lock().await; state.adopted.values().cloned().collect() }asyncfn list(&self) -> Vec<SessionSummary> {let state = self.state.lock().await; state .index .sessions .iter() .map(|entry| match state .sessions .get(&entry.id) .map(|session| session.summary.clone()) .or_else(|| state.adopted.get(&entry.id).cloned()) {Some(summary) => summary,// Remembered from a previous run of this daemon: the// scrollback is still readable, the agent is not.None => SessionSummary { session_id: entry.id.clone(), launch_id: entry.launch_id.clone(), tool: entry.tool, agent_session_id: entry.agent_session_id.clone(), cwd: entry.cwd.clone(), started_at: entry.started_at.clone(), ended_at: entry.ended_at.clone(), state: SessionState::Ended, waiting_kind: None, request_id: None, exit_code: entry.exit.and_then(|exit| exit.code), exit_signal: entry.exit.and_then(|exit| exit.signal), host_owned: false, }, }) .collect() }asyncfn attach( &self, session_id: &str, cols: u16, rows: u16, from_offset: Option<u64>, out: &mpsc::UnboundedSender<String>, ) -> Option<tokio::task::JoinHandle<()>> {let (pty, scrollback, data) = {let state = self.state.lock().await;// A SESSION OR A UTILITY, through the one lookup: the replay, the// live broadcast and the resize are identical for both, and a// second copy of this would be a utility terminal that behaved// subtly differently from the session terminal beside it.match state.streamable(session_id) {Some(found) => found,None => {let message = refusal_for(&state, session_id); drop(state); send(out, &Event::Error { message });returnNone; } } };let replay = match scrollback.lock().await.replay(from_offset, REPLAY_TAIL_BYTES) {Ok(replay) => replay,Err(error) => { send(out, &Event::Error { message: format!("the scrollback for {session_id} — {error}"), });returnNone; } }; send(out, &Event::Attached { session_id: session_id.to_string(), offset: replay.offset, });if !replay.bytes.is_empty() { send(out, &Event::Data { session_id: session_id.to_string(), b: base64::engine::general_purpose::STANDARD.encode(&replay.bytes), }); }// The viewer's window is the terminal's window from now on.let _ = pty.resize(cols, rows).await;let out = out.clone();let session_id = session_id.to_string();letmut data = data;Some(tokio::spawn(asyncmove {loop {match data.recv().await {Ok(chunk) => {let event = Event::Data { session_id: session_id.clone(), b: base64::engine::general_purpose::STANDARD.encode(&chunk), };letOk(text) = line(&event) else { return };if out.send(text).is_err() {return; } }// The viewer fell far enough behind that the host dropped// what it missed. It is TOLD, because a gap rendered as// continuity is a terminal that lies.Err(broadcast::error::RecvError::Lagged(missed)) => {let event = Event::Error { message: format!("this viewer fell behind and {missed} chunks of {session_id} were dropped — reattach with the offset you last saw" ), };letOk(text) = line(&event) else { return };if out.send(text).is_err() {return; } }Err(broadcast::error::RecvError::Closed) => return, } } })) }asyncfn hook(self: &Arc<Self>, event: String, session_id: Option<String>, payload: serde_json::Value, out: &mpsc::UnboundedSender<String>, ) -> Option<tokio::task::JoinHandle<()>> {letSome(session_id) = self.resolve_session(session_id, &payload).awaitelse {// A hook from a session this host did not spawn. Answered rather// than dropped: the hook is BLOCKING on us. send(out, &Event::Ok);returnNone; };match event.as_str() {"SessionStart" => {self.learn_agent_session_id(&session_id, &payload).await;self.set_state(&session_id, SessionState::Running, None, None) .await; send(out, &Event::Ok); }// A TURN BEGAN — the opening prompt, or a reply typed into the// terminal. `Stop` is what ends it."UserPromptSubmit" => {self.set_state(&session_id, SessionState::Running, None, None) .await; send(out, &Event::Ok); }"Stop" => {self.turn_from_transcript(&session_id, &payload).await;self.set_state(&session_id, SessionState::Idle, None, None) .await; send(out, &Event::Ok); }"SessionEnd" => {self.set_state(&session_id, SessionState::Ended, None, None) .await; send(out, &Event::Ok); }// The agent just rewrote its task list. Nothing about the session's// STATE changed — it is mid-turn, still running — so this arm says// the list and nothing else. event if event == crate::tasks::TASKS_EVENT => {self.tasks_from_tool_call(&session_id, &payload).await; send(out, &Event::Ok); }"Notification" => {let kind = notification_kind(&payload);self.set_state(&session_id, SessionState::Waiting, Some(kind), None) .await; send(out, &Event::Ok); }"PermissionRequest" => {returnSome(self.block_on_permission(session_id, payload, out.clone()).await) } other => send(out, &Event::Error { message: format!("this host registers no {other} hook — the events it handles are {:?}", agents::handled_hook_events()), }), }None }/// Hold the hook's connection open until the phone answers or the wait runs/// out.asyncfn block_on_permission(self: &Arc<Self>, session_id: String, payload: serde_json::Value, out: mpsc::UnboundedSender<String>, ) -> tokio::task::JoinHandle<()> {let request_id = permission_request_id(&payload);let (answer, wait) = oneshot::channel();let tool = {letmut state = self.state.lock().await;let tool = state.sessions.get(&session_id).map(|held| held.tool);ifletSome(session) = state.sessions.get_mut(&session_id) { session.pending.insert(request_id.clone(), answer); session.summary.state = SessionState::Waiting; session.summary.waiting_kind = Some(WaitingKind::Permission); session.summary.request_id = Some(request_id.clone()); } tool };let _ = self.events.send(Event::State { session_id: session_id.clone(), state: SessionState::Waiting, waiting_kind: Some(WaitingKind::Permission), request_id: Some(request_id.clone()), });let timeout = self.permission_timeout;let host = Arc::clone(self); tokio::spawn(asyncmove {let decided = tokio::time::timeout(timeout, wait).await;match (decided, tool) { (Ok(Ok(decision)), Some(tool)) => {let stdout = agents::adapter(tool).permission_reply(decision); send(&out, &Event::Decision { session_id, request_id, stdout, }); } _ => {// Nobody answered in time (or the session went away).// NOTHING is sent: the hook prints nothing and exits 0,// and the agent falls back to its own prompt in the TUI —// which is a session waiting on a person, not a session// that silently proceeded.letmut state = host.state.lock().await;ifletSome(session) = state.sessions.get_mut(&session_id) { session.pending.remove(&request_id); } send(&out, &Event::Ok); } } }) }asyncfn resolve_session( &self, session_id: Option<String>, payload: &serde_json::Value, ) -> Option<String> {let named = session_id.or_else(|| { payload .get("session_id") .and_then(serde_json::Value::as_str) .map(str::to_string) })?;let state = self.state.lock().await;if state.sessions.contains_key(&named) {returnSome(named); }// Codex mints its own id, so the hook names the AGENT's session and// the host has to look it up by that. state .sessions .iter() .find(|(_, held)| held.summary.agent_session_id.as_deref() == Some(named.as_str())) .map(|(id, _)| id.clone()) }asyncfn learn_agent_session_id(&self, session_id: &str, payload: &serde_json::Value) {letSome(agent) = payload .get("session_id") .and_then(serde_json::Value::as_str)else {return; };letmut state = self.state.lock().await;ifletSome(session) = state.sessions.get_mut(session_id) { session.summary.agent_session_id = Some(agent.to_string()); }let agent = agent.to_string();ifletSome(entry) = state .index .sessions .iter_mut() .find(|entry| entry.id == session_id) { entry.agent_session_id = Some(agent); }let _ = state.index.save(&self.layout.index()); }asyncfn set_state( &self, session_id: &str, to: SessionState, waiting_kind: Option<WaitingKind>, request_id: Option<String>, ) { {letmut state = self.state.lock().await;ifletSome(session) = state.sessions.get_mut(session_id) { session.summary.state = to; session.summary.waiting_kind = waiting_kind; session.summary.request_id = request_id.clone(); } }let _ = self.events.send(Event::State { session_id: session_id.to_string(), state: to, waiting_kind, request_id, }); }/// The session's task list out of the tool call that just wrote it.////// The list is the WHOLE list every time (see [`crate::tasks`]), so this/// emits a [`Event::Tasks`] that REPLACES what the row held — an empty one/// included. A payload that carries no list at all emits nothing: the/// reader has already said on stderr why, and clearing a person's task/// list because a shape moved is the silent fallback this repo does not/// allow.asyncfn tasks_from_tool_call(&self, session_id: &str, payload: &serde_json::Value) {letSome(tasks) = crate::tasks::tasks_from_hook(session_id, payload) else {return; };let _ = self.events.send(Event::Tasks { session_id: session_id.to_string(), tasks, }); }/// The last turn out of the agent's own transcript, said out loud when/// there is not one.////// **FOUR WAYS THIS ANSWERS NOTHING, AND EACH ONE SAYS SO.** All four used/// to be a bare `return`, so a card whose "last line" stayed empty gave a/// person no way at all to find out why — the silent fallback this repo/// bans, in the one place a format change at the agent's end lands first./// The parser is pinned to a recorded fixture per agent version/// (`tests/transcripts.rs`) so a shape it cannot read is loud rather than/// zero; this is the other half of that promise, on the machine.asyncfn turn_from_transcript(&self, session_id: &str, payload: &serde_json::Value) {letSome(path) = payload .get("transcript_path") .and_then(serde_json::Value::as_str)else { eprintln!("cotton-session-host: {session_id}: the Stop hook named no `transcript_path`, so there is no last turn to read" );return; };let text = match std::fs::read_to_string(Path::new(path)) {Ok(text) => text,Err(error) => { eprintln!("cotton-session-host: {session_id}: the transcript at {path} could not be read — {error}" );return; } };let (tool, seq) = {letmut state = self.state.lock().await;match state.sessions.get_mut(session_id) {Some(session) => { session.turn_seq += 1; (session.tool, session.turn_seq) }None => { eprintln!("cotton-session-host: {session_id}: a Stop hook for a session this host does not hold" );return; } } };// ONE SOURCE OF TURNS: a session the user's own Stop hook logs gets// its turns from that hook, numbered by transcript line, and only its// card's line from here (`adopted::hooked_tools`).let hooked = self .adopted_roots .as_ref() .is_some_and(|roots| adopted::hooked_tools(roots).contains(&tool));match agents::adapter(tool).read_last_turn(&text) {Some(turn) if hooked => {let _ = self.events.send(Event::Spoke { session_id: session_id.to_string(), role: turn.role, text: turn.text, }); }Some(turn) => {let _ = self.events.send(Event::Turn { session_id: session_id.to_string(), role: turn.role, text: turn.text, seq, }); }// The transcript was there and this adapter found no turn in it.// That is the agent having changed its own format, and it is the// failure the fixtures exist to make loud.None => eprintln!("cotton-session-host: {session_id}: no turn could be read out of {path} ({} bytes) — the {} transcript format may have moved", text.len(), tool.agent_key() ), } }/// The account's windows out of a status line, said out loud when there/// are none.////// **THREE WAYS THIS ANSWERS NOTHING, AND EACH ONE SAYS SO** — for the/// reason [`Self::turn_from_transcript`]'s do. A household whose devices/// page shows no login at all is the visible symptom, and it has three/// completely different causes: a status line whose session this host does/// not hold, one it cannot name a session for, and one the agent sent/// without its `rate_limits` (which Claude omits until the first API/// response of a Pro/Max session). Only the last of those is ordinary.asyncfn usage_from(&self, session_id: Option<String>, payload: &serde_json::Value) {letSome(session_id) = self.resolve_session(session_id, payload).awaitelse { eprintln!("cotton-session-host: a status line named no session this host could resolve, so no account reading was taken from it" );return; };let tool = {let state = self.state.lock().await;match state.sessions.get(&session_id) {Some(session) => session.tool,None => { eprintln!("cotton-session-host: {session_id}: a status line for a session this host does not hold" );return; } } };let now = self.clock.now_rfc3339();match agents::adapter(tool).read_usage(payload, &now) {Some(mut usage) => {// A STATUS LINE NAMES NO ADDRESS, and an account row's key is// the address — so every reading used to be dropped at the// far end and no login ever showed its windows. The reading// is about the login this agent is signed in as, and the// agent said who that is on the last sample.if usage.email.is_none() {let state = self.state.lock().await; usage.email = state .last_accounts .get(tool.agent_key()) .map(|account| account.email.clone()); }let _ = self.events.send(Event::Usage { usage }); }// NOT an error, and it is still worth saying: until this line stops// appearing for a session, the devices page has no windows to draw// and nobody can tell that from a login nothing has seen.None => eprintln!("cotton-session-host: {session_id}: the {} status line carried no usage windows", tool.agent_key() ), } }}/// One line saying who is signed in — for the host's log.////// The PROVIDER and the plan, never the address: this log is a file on a/// disk, and whose login it is belongs in the person's database and nowhere/// else.fn describe_accounts(accounts: &BTreeMap<String, crate::protocol::SignedIn>) -> String {if accounts.is_empty() {return"no agent on this Mac says anybody is signed in".to_string(); } accounts .iter() .map(|(agent, account)| match &account.plan {Some(plan) => format!("{agent} ({plan})"),None => agent.clone(), }) .collect::<Vec<_>>() .join(", ")}/// Which refusal an id has earned, decided from state already in hand.////// Takes the STATE rather than the host, so a caller that is already holding/// the lock can ask — `Request::Decide` is inside it, and a second `lock()`/// there is a deadlock the whole daemon stops on.fn refusal_for(state: &HostState, session_id: &str) -> String {if state.adopted.contains_key(session_id) {return adopted_refusal(session_id); }if utility::is_utility(session_id) {return unknown_utility(session_id); } unknown(session_id)}/// The refusal for something only a pseudo-terminal's owner can do, on a/// session this host merely found.fn adopted_refusal(session_id: &str) -> String { format!("session {session_id} was adopted from its own transcript, not started by Cotton — this host holds no terminal for it, so it cannot be attached to, written to, stopped or answered from here; start it from Cotton to get all four" )}/// Seconds since the epoch, out of the one stamp this crate writes.////// A stamp this host cannot parse is `0`, which makes every file look old and/// every adopted session read `idle` — the safe direction: a card that says/// idle when it is running is wrong and harmless, one that says running when/// the agent is gone is a person waiting on nothing.fn epoch_seconds(rfc3339: &str) -> i64 { chrono::DateTime::parse_from_rfc3339(rfc3339) .map(|at| at.timestamp()) .unwrap_or_default()}/// The refusal for a utility terminal this host is not holding.////// Separate from [`unknown`] because the two are different things to fix: a/// session id this host never had is a mirror out of step, and a utility id it/// no longer has is a terminal that finished and was replaced by the next one/// of its purpose.fn unknown_utility(id: &str) -> String { format!("this host holds no utility terminal {id} — it finished and was replaced by a later one \ of its purpose, or the helper has restarted since" )}/// The refusal for an id this host does not know.fn unknown(session_id: &str) -> String { format!("this host holds no session {session_id} — it was never spawned here, or the daemon has restarted since")}/// The notification's own kind, mapped to what the phone shows.fn notification_kind(payload: &serde_json::Value) -> WaitingKind {let named = payload .get("notification_type") .or_else(|| payload.get("matcher")) .and_then(serde_json::Value::as_str) .unwrap_or_default();match named {"permission_prompt" => WaitingKind::Permission,"agent_needs_input" | "elicitation_dialog" => WaitingKind::Question,// `idle_prompt`, and anything the agent adds later: the session wants// input and has not said what for. A named kind, not a guess at one. _ => WaitingKind::Input, }}/// The id this permission request is answered by.fn permission_request_id(payload: &serde_json::Value) -> String {for name in ["request_id", "permission_request_id", "tool_use_id"] {ifletSome(found) = payload.get(name).and_then(serde_json::Value::as_str) {return found.to_string(); } }// The agent named none, so the host names one: a request is answered by// exactly one `decide`, and an id nobody can guess is better than a// constant two concurrent requests would share.use std::sync::atomic::{AtomicU64, Ordering};static NEXT: AtomicU64 = AtomicU64::new(1); format!("host-request-{}", NEXT.fetch_add(1, Ordering::Relaxed))}fn send(out: &mpsc::UnboundedSender<String>, event: &Event) {ifletOk(text) = line(event) {let _ = out.send(text); }}#[cfg(test)]#[path = "serve_tests.rs"]mod serve_tests;