A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
agent status: detection engine, terminal evidence, and protocol types
RoversXc1bd03806b39
diff --git a/Cargo.lock b/Cargo.lockindex 039ad9d1..da31dfdf 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3805,6 +3805,7 @@ dependencies = ["procinfo","promise","rangeset",+ "regex","serde","serial2","shell-words",@@ -3815,6 +3816,7 @@ dependencies = ["textwrap","thinkterm-proto","thiserror 1.0.69",+ "toml 0.8.23","url","wezterm-dynamic 0.2.1","wezterm-ssh",@@ -7704,6 +7706,7 @@ dependencies = ["termwiz 0.24.0","termwiz-funcs","textwrap",+ "thinkterm-proto","thinkterm-tui","umask","url",@@ -7814,6 +7817,7 @@ dependencies = ["tempfile","termwiz 0.24.0","textwrap",+ "thinkterm-proto","thiserror 1.0.69","umask","url",@@ -8045,6 +8049,7 @@ dependencies = ["termwiz-funcs","textwrap","thinkterm-core",+ "thinkterm-proto","thinkterm-syntax","thiserror 1.0.69","tiny-skia",diff --git a/NOTICE b/NOTICEnew file mode 100644index 00000000..2c4b7430--- /dev/null+++ b/NOTICE@@ -0,0 +1,8 @@+This product bundles agent-detection manifest files under+mux/src/agent_status/manifests/ that are sourced from the herdr+project (https://github.com/herdrdev/herdr), copyright the herdr+contributors, and licensed under the Apache License, Version 2.0+(http://www.apache.org/licenses/LICENSE-2.0). A copy of that license is+included at mux/src/agent_status/manifests/LICENSE. Each bundled file+carries an attribution header naming the upstream commit it was taken+from.diff --git a/codec/src/lib.rs b/codec/src/lib.rsindex 1f585db2..1c6725f4 100644--- a/codec/src/lib.rs+++ b/codec/src/lib.rs@@ -482,7 +482,10 @@ macro_rules! pdu {/// 60: Spawn PDUs carry a portable CommandSpec instead of CommandBuilder;/// argv, env and cwd travel as byte strings rather than OsString, and/// the umask field exists on every platform instead of only unix.-pub const CODEC_VERSION: usize = 60;+/// 61: Agent status is classified by the mux that owns the pane and pushed+/// to clients (AgentStatusChanged), with a request/response pair for+/// cold-start delivery and for `thinkterm cli agent list`.+pub const CODEC_VERSION: usize = 61;// Defines the Pdu enum.// Each struct has an explicit identifying number.@@ -560,6 +563,9 @@ pdu! {SetClientView: 77,SetFrontendAccessMode: 78,FrontendAccessState: 79,+ AgentStatusChanged: 80,+ GetAgentStatuses: 81,+ GetAgentStatusesResponse: 82,}impl Pdu {@@ -678,6 +684,7 @@ impl Pdu {| Pdu::NotifyAlert(NotifyAlert { pane_id, .. })| Pdu::SetClipboard(SetClipboard { pane_id, .. })| Pdu::PaneFocused(PaneFocused { pane_id })+ | Pdu::AgentStatusChanged(AgentStatusChanged { pane_id, .. })| Pdu::PaneRemoved(PaneRemoved { pane_id }) => Some(*pane_id),_ => None,}@@ -1017,6 +1024,36 @@ pub enum ThinkTermSessionWorkStatus {#[derive(Deserialize, Serialize, PartialEq, Eq, Debug)]pub struct GetThinkTermSessionState {}+/// Unilateral: the mux that owns `pane_id` re-classified its agent status.+/// `None` means the pane is no longer running a recognized agent.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct AgentStatusChanged {+ pub pane_id: PaneId,+ pub status: Option<thinkterm_proto::AgentStatus>,+}++/// Ask a mux for the agent status of every pane it knows about — detected+/// locally or mirrored from a chained server. Serves cold-start delivery+/// on attach and `thinkterm cli agent list`.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug)]+pub struct GetAgentStatuses {}++#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct AgentStatusEntry {+ pub pane_id: PaneId,+ pub status: thinkterm_proto::AgentStatus,+ /// Server-side title and workspace, so a one-shot client (the CLI)+ /// needs no second ListPanes round trip. The GUI ignores both: it+ /// already mirrors the pane objects these were read from.+ pub title: String,+ pub workspace: String,+}++#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct GetAgentStatusesResponse {+ pub statuses: Vec<AgentStatusEntry>,+}+/// Select an existing authoritative Thread, or create the canonical/// Default/Home/main landing when the server has no usable Thread, and make/// sure that the selected Thread has a live terminal. The server validates the@@ -2005,8 +2042,47 @@ mod test {}#[test]- fn thinkterm_session_viewport_and_landing_protocol_round_trip_at_version_60() {- assert_eq!(CODEC_VERSION, 60);+ fn agent_status_protocol_round_trip_at_version_61() {+ assert_eq!(CODEC_VERSION, 61);+ use thinkterm_proto::{AgentEvidence, AgentState, AgentStatus};++ fn round_trip(pdu: Pdu) {+ let mut encoded = Vec::new();+ pdu.encode(&mut encoded, 0x61).unwrap();+ let decoded = Pdu::decode(encoded.as_slice()).unwrap();+ assert_eq!(decoded.serial, 0x61);+ assert_eq!(decoded.pdu, pdu);+ }++ let status = AgentStatus {+ agent_id: "claude".to_string(),+ state: AgentState::Blocked,+ evidence: AgentEvidence::Screen,+ session_id: Some("abc-123".to_string()),+ since_unix: 1_756_000_000,+ ended: false,+ };+ round_trip(Pdu::AgentStatusChanged(AgentStatusChanged {+ pane_id: 7,+ status: Some(status.clone()),+ }));+ round_trip(Pdu::AgentStatusChanged(AgentStatusChanged {+ pane_id: 7,+ status: None,+ }));+ round_trip(Pdu::GetAgentStatuses(GetAgentStatuses {}));+ round_trip(Pdu::GetAgentStatusesResponse(GetAgentStatusesResponse {+ statuses: vec![AgentStatusEntry {+ pane_id: 7,+ status,+ title: "claude".to_string(),+ workspace: "default".to_string(),+ }],+ }));+ }++ #[test]+ fn thinkterm_session_viewport_and_landing_protocol_round_trip() {let size = TerminalSize {rows: 40,cols: 132,diff --git a/config/src/config.rs b/config/src/config.rsindex 6321b19d..d65ca74d 100644--- a/config/src/config.rs+++ b/config/src/config.rs@@ -855,6 +855,13 @@ pub struct Config {#[dynamic(default = "default_true")]pub unzoom_on_switch_pane: bool,+ /// Whether this process classifies its panes as running coding agents+ /// (Claude Code, Codex, …). Turning it off stops all screen-rule and+ /// contract evaluation here; a mux server and its clients each obey+ /// their own setting, because detection happens where the pane lives.+ #[dynamic(default = "default_true")]+ pub agent_status_detection: bool,+#[dynamic(default = "default_max_fps")]pub max_fps: u64,diff --git a/mux/Cargo.toml b/mux/Cargo.tomlindex f1619aed..41e55926 100644--- a/mux/Cargo.toml+++ b/mux/Cargo.toml@@ -35,6 +35,7 @@ portable-pty = { workspace=true, features = ["serde_support"]}procinfo.workspace = truepromise.workspace = truerangeset.workspace = true+regex.workspace = trueserde = {workspace=true, features = ["rc", "derive"]}serial2.workspace = trueshell-words.workspace = true@@ -45,6 +46,7 @@ termwiz.workspace = truetextwrap.workspace = truethinkterm-proto = { workspace = true, features = ["lua"] }thiserror.workspace = true+toml.workspace = trueurl.workspace = truewezterm-dynamic.workspace = truewezterm-ssh.workspace = truediff --git a/mux/src/agent_status/contract.rs b/mux/src/agent_status/contract.rsnew file mode 100644index 00000000..b34269c8--- /dev/null+++ b/mux/src/agent_status/contract.rs@@ -0,0 +1,175 @@+//! The `THINKTERM_AGENT` user-var contract.+//!+//! Agents (or hook scripts acting for them) report identity and state by+//! emitting `OSC 1337 ; SetUserVar=THINKTERM_AGENT=<base64 value> ST` into+//! their own pane. The terminal layer stores the decoded value in the+//! pane's user vars (mirrored across mux domains), and this module parses+//! it.+//!+//! Value grammar, version 1:+//!+//! ```text+//! v1;agent=claude;state=working;session=<id>;pid=<n>;ts=<unix-seconds>[;ended=1]+//! ```+//!+//! One variable rather than several so state and session can never be+//! observed torn. Unknown keys are ignored; an unknown *state* parses as+//! `Unknown`; an unrecognized major version invalidates the whole value.++use thinkterm_proto::AgentState;++pub const USER_VAR_NAME: &str = "THINKTERM_AGENT";++/// How old a non-idle contract may be before it is disregarded. Long on+/// purpose: it only exists to shed reports from long-dead sessions on+/// mux-server panes that survive GUI restarts.+pub(crate) const CONTRACT_MAX_AGE_SECS: u64 = 6 * 60 * 60;+/// Clock skew tolerated before a future timestamp stops counting as fresh.+const FUTURE_SKEW_ALLOWANCE_SECS: u64 = 300;++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct AgentContract {+ pub agent_id: String,+ pub state: AgentState,+ pub session_id: Option<String>,+ /// Unix seconds at emission time, from the reporter's clock.+ pub ts: Option<u64>,+ /// The session announced its own end. Reserved for native emitters;+ /// today's detection evicts an ended session's pane instead of+ /// publishing it, so a surviving `ended=1` only reaches consumers+ /// while the emitting process is still alive (where it is ignored).+ pub ended: bool,+}++pub fn parse(value: &str) -> Option<AgentContract> {+ let mut fields = value.split(';');+ let version = fields.next()?.trim();+ // "v1" or a future minor like "v1.1" stays parseable; any other major+ // means a new incompatible grammar and the value is ignored.+ if version != "v1" && !version.starts_with("v1.") {+ return None;+ }++ let mut agent_id = None;+ let mut state = None;+ let mut session_id = None;+ let mut ts = None;+ let mut ended = false;+ for field in fields {+ let Some((key, val)) = field.split_once('=') else {+ continue;+ };+ match key.trim() {+ "agent" => agent_id = Some(val.trim().to_string()),+ "state" => {+ state = Some(match val.trim() {+ "working" => AgentState::Working,+ "idle" => AgentState::Idle,+ "blocked" => AgentState::Blocked,+ _ => AgentState::Unknown,+ })+ }+ "session" => {+ let val = val.trim();+ if !val.is_empty() {+ session_id = Some(val.to_string());+ }+ }+ "ts" => ts = val.trim().parse::<u64>().ok(),+ "ended" => ended = val.trim() == "1",+ // pid= and unknown future keys are diagnostic only.+ _ => {}+ }+ }++ let agent_id = agent_id.filter(|id| !id.is_empty())?;+ let state = state?;+ Some(AgentContract {+ agent_id,+ state,+ session_id,+ ts,+ ended,+ })+}++/// A non-idle report older than `CONTRACT_MAX_AGE_SECS` no longer counts as+/// a state authority (identity is still honored by the caller).+pub fn state_is_fresh(contract: &AgentContract, now_unix: u64) -> bool {+ if contract.state == AgentState::Idle {+ return true;+ }+ match contract.ts {+ // A timestamp from the future (broken clock, crafted var) must+ // not be eternally fresh; allow modest skew only.+ Some(ts) if ts > now_unix + FUTURE_SKEW_ALLOWANCE_SECS => false,+ Some(ts) => now_unix.saturating_sub(ts) <= CONTRACT_MAX_AGE_SECS,+ // No timestamp: trust it; pane-death and screen contradiction are+ // the remaining guards.+ None => true,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn full_value_parses() {+ let parsed =+ parse("v1;agent=claude;state=working;session=abc-123;pid=42;ts=1700000000").unwrap();+ assert_eq!(parsed.agent_id, "claude");+ assert_eq!(parsed.state, AgentState::Working);+ assert_eq!(parsed.session_id.as_deref(), Some("abc-123"));+ assert_eq!(parsed.ts, Some(1_700_000_000));+ assert!(!parsed.ended);+ }++ #[test]+ fn empty_session_and_unknown_keys_are_tolerated() {+ let parsed = parse("v1;agent=soul;state=idle;session=;future_key=zzz;ended=1").unwrap();+ assert_eq!(parsed.agent_id, "soul");+ assert_eq!(parsed.state, AgentState::Idle);+ assert_eq!(parsed.session_id, None);+ assert!(parsed.ended);+ }++ #[test]+ fn unknown_state_is_unknown_but_valid() {+ let parsed = parse("v1;agent=claude;state=thinking").unwrap();+ assert_eq!(parsed.state, AgentState::Unknown);+ }++ #[test]+ fn wrong_major_version_or_missing_fields_reject() {+ assert_eq!(parse("v2;agent=claude;state=working"), None);+ assert_eq!(parse("v1;state=working"), None);+ assert_eq!(parse("v1;agent=claude"), None);+ assert_eq!(parse("garbage"), None);+ assert_eq!(parse(""), None);+ }++ #[test]+ fn freshness_gate() {+ let now = 2_000_000_000u64;+ let stale = parse("v1;agent=claude;state=working;ts=1700000000").unwrap();+ assert!(!state_is_fresh(&stale, now));+ let fresh = parse(&format!("v1;agent=claude;state=working;ts={}", now - 60)).unwrap();+ assert!(state_is_fresh(&fresh, now));+ // Idle never goes stale; no ts means trusted.+ let idle_stale = parse("v1;agent=claude;state=idle;ts=1700000000").unwrap();+ assert!(state_is_fresh(&idle_stale, now));+ let no_ts = parse("v1;agent=claude;state=working").unwrap();+ assert!(state_is_fresh(&no_ts, now));++ // A future timestamp beyond skew allowance must not be eternally+ // fresh: a broken clock or crafted var would otherwise pin the+ // reported state forever.+ let mut future = fresh.clone();+ future.ts = Some(now + 10_000);+ assert!(!state_is_fresh(&future, now));+ let mut skewed = fresh.clone();+ skewed.ts = Some(now + 60);+ assert!(state_is_fresh(&skewed, now));+ }+}diff --git a/mux/src/agent_status/engine.rs b/mux/src/agent_status/engine.rsnew file mode 100644index 00000000..03581b23--- /dev/null+++ b/mux/src/agent_status/engine.rs@@ -0,0 +1,779 @@+//! Manifest-driven screen detection engine.+//!+//! Evaluates per-agent TOML rule manifests against a snapshot of a pane's+//! live screen tail plus its OSC title/progress state. The manifest format+//! is compatible with herdr's agent-detection manifests+//! (<https://github.com/herdrdev/herdr>, Apache-2.0) so their maintained+//! rule files can be dropped in unchanged; this engine implements the+//! feature subset those files use.++use regex::Regex;+use serde::Deserialize;+use std::collections::HashMap;+use parking_lot::RwLock;+use thinkterm_proto::AgentState;++/// Everything a manifest evaluation can look at. OSC regions source from+/// their dedicated fields; all other regions slice `screen`.+pub struct DetectionInput<'a> {+ pub screen: &'a str,+ pub osc_title: &'a str,+ pub osc_progress: &'a str,+}++/// Outcome of running one agent's manifest over a snapshot.+pub enum ScreenVerdict {+ /// A rule matched and assigns a state.+ State(AgentState),+ /// A `skip_state_update` rule matched (transcript viewer and friends):+ /// keep whatever state was published before.+ Freeze,+ /// No rule matched. Known agents fall back towards Idle at the caller's+ /// discretion (never Blocked), mirroring herdr's+ /// `default_known_agent_idle_fallback`.+ NoMatch,+}++#[derive(Deserialize)]+struct ManifestFile {+ id: String,+ #[allow(dead_code)]+ version: Option<String>,+ min_engine_version: Option<u32>,+ #[allow(dead_code)]+ updated_at: Option<String>,+ #[serde(default)]+ aliases: Vec<String>,+ #[serde(default)]+ rules: Vec<ManifestRule>,+}++#[derive(Deserialize, Clone)]+struct ManifestRule {+ id: String,+ state: Option<ManifestState>,+ #[serde(default)]+ priority: i32,+ #[serde(default = "default_region")]+ region: String,+ #[serde(default)]+ skip_state_update: bool,+ // Parsed for manifest compatibility; the arbitration layer does not+ // consume the visibility hints yet.+ #[serde(default)]+ #[allow(dead_code)]+ visible_idle: bool,+ #[serde(default)]+ #[allow(dead_code)]+ visible_blocker: bool,+ #[serde(default)]+ #[allow(dead_code)]+ visible_working: bool,+ #[serde(default)]+ all: Vec<ManifestGate>,+ #[serde(default)]+ any: Vec<ManifestGate>,+ #[serde(default, rename = "not")]+ not_gate: Vec<ManifestGate>,+ #[serde(default)]+ contains: Vec<String>,+ #[serde(default)]+ regex: Vec<String>,+ #[serde(default)]+ line_regex: Vec<String>,+}++#[derive(Deserialize, Clone)]+struct ManifestGate {+ #[serde(default)]+ all: Vec<ManifestGate>,+ #[serde(default)]+ any: Vec<ManifestGate>,+ #[serde(default, rename = "not")]+ not_gate: Vec<ManifestGate>,+ #[serde(default)]+ contains: Vec<String>,+ #[serde(default)]+ regex: Vec<String>,+ #[serde(default)]+ line_regex: Vec<String>,+}++#[derive(Deserialize, Clone, Copy)]+#[serde(rename_all = "snake_case")]+enum ManifestState {+ Idle,+ Working,+ Blocked,+ Unknown,+}++impl From<ManifestState> for AgentState {+ fn from(value: ManifestState) -> Self {+ match value {+ ManifestState::Idle => AgentState::Idle,+ ManifestState::Working => AgentState::Working,+ ManifestState::Blocked => AgentState::Blocked,+ ManifestState::Unknown => AgentState::Unknown,+ }+ }+}++fn default_region() -> String {+ "whole_recent".to_string()+}++struct CompiledGate {+ all: Vec<CompiledGate>,+ any: Vec<CompiledGate>,+ not_gate: Vec<CompiledGate>,+ /// Pre-lowercased needles matched against the lowercased region text.+ contains: Vec<String>,+ regex: Vec<Regex>,+ line_regex: Vec<Regex>,+}++struct CompiledRule {+ #[allow(dead_code)]+ id: String,+ state: Option<AgentState>,+ priority: i32,+ region: String,+ skip_state_update: bool,+ gate: CompiledGate,+}++pub(crate) struct CompiledManifest {+ pub(crate) id: String,+ pub(crate) aliases: Vec<String>,+ rules: Vec<CompiledRule>,+}++/// Bundled manifests, taken from herdr's maintained agent-detection set+/// (Apache-2.0; see the attribution header inside each file).+const BUNDLED_MANIFESTS: &[&str] = &[+ include_str!("manifests/claude.toml"),+ include_str!("manifests/codex.toml"),+ include_str!("manifests/github-copilot.toml"),+ include_str!("manifests/cursor.toml"),+ include_str!("manifests/pi.toml"),+ include_str!("manifests/opencode.toml"),+ include_str!("manifests/kimi.toml"),+];++static MANIFESTS: RwLock<Option<HashMap<String, CompiledManifest>>> = RwLock::new(None);+/// Bumped whenever the manifest map is (re)loaded. Cached screen verdicts+/// record the generation they were computed under, so a reload invalidates+/// them even when a racing evaluation re-caches after the cache sweep.+static MANIFEST_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);++pub(crate) fn manifest_generation() -> u64 {+ MANIFEST_GENERATION.load(std::sync::atomic::Ordering::Acquire)+}++/// The user-override directory: a `<id>.toml` here replaces the bundled+/// manifest with the same id wholesale. Lives next to settings.json (see+/// `native_settings::settings_path`).+fn override_dir() -> std::path::PathBuf {+ // Unit tests must not read the developer's real override directory: a+ // legitimately installed user override (the exact file the settings+ // page tells users to create) would silently change every bundled-+ // manifest assertion and turn the suite red on that machine only.+ #[cfg(test)]+ {+ return std::path::PathBuf::from("/nonexistent-thinkterm-test-agent-detection");+ }+ #[cfg(not(test))]+ config::HOME_DIR+ .join(".config")+ .join("thinkterm")+ .join("agent-detection")+}++/// The manifest feature set this engine implements; the herdr manifests+/// we bundle declare requirements up to this.+const ENGINE_VERSION: u32 = 3;++fn compile_manifest(text: &str, origin: &str) -> Option<CompiledManifest> {+ let file: ManifestFile = match toml::from_str(text) {+ Ok(file) => file,+ Err(err) => {+ log::error!("agent manifest {origin} failed to parse: {err:#}");+ return None;+ }+ };+ if let Some(required) = file.min_engine_version {+ if required > ENGINE_VERSION {+ // Evaluating a manifest that needs features we lack would+ // produce silently wrong verdicts, which is worse than no+ // manifest at all.+ log::warn!(+ "agent manifest {origin} requires engine version {required} \+ but this build implements {ENGINE_VERSION}; skipping it"+ );+ return None;+ }+ }+ let mut rules = Vec::with_capacity(file.rules.len());+ for rule in &file.rules {+ let gate = match compile_gate(&ManifestGate {+ all: rule.all.clone(),+ any: rule.any.clone(),+ not_gate: rule.not_gate.clone(),+ contains: rule.contains.clone(),+ regex: rule.regex.clone(),+ line_regex: rule.line_regex.clone(),+ }) {+ Ok(gate) => gate,+ Err(err) => {+ log::error!(+ "agent manifest {origin} rule {} failed to compile: {err}",+ rule.id+ );+ continue;+ }+ };+ rules.push(CompiledRule {+ id: rule.id.clone(),+ state: rule.state.map(AgentState::from),+ priority: rule.priority,+ region: rule.region.trim().to_string(),+ skip_state_update: rule.skip_state_update,+ gate,+ });+ }+ Some(CompiledManifest {+ id: file.id,+ aliases: file.aliases,+ rules,+ })+}++fn compile_gate(gate: &ManifestGate) -> Result<CompiledGate, String> {+ Ok(CompiledGate {+ all: gate+ .all+ .iter()+ .map(compile_gate)+ .collect::<Result<_, _>>()?,+ any: gate+ .any+ .iter()+ .map(compile_gate)+ .collect::<Result<_, _>>()?,+ not_gate: gate+ .not_gate+ .iter()+ .map(compile_gate)+ .collect::<Result<_, _>>()?,+ contains: gate.contains.iter().map(|s| s.to_lowercase()).collect(),+ regex: gate+ .regex+ .iter()+ .map(|p| Regex::new(p).map_err(|e| e.to_string()))+ .collect::<Result<_, _>>()?,+ line_regex: gate+ .line_regex+ .iter()+ .map(|p| Regex::new(p).map_err(|e| e.to_string()))+ .collect::<Result<_, _>>()?,+ })+}++fn load_all() -> HashMap<String, CompiledManifest> {+ let mut map = HashMap::new();+ for text in BUNDLED_MANIFESTS {+ if let Some(compiled) = compile_manifest(text, "bundled") {+ map.insert(compiled.id.clone(), compiled);+ }+ }+ let dir = override_dir();+ if let Ok(entries) = std::fs::read_dir(&dir) {+ for entry in entries.flatten() {+ let path = entry.path();+ if path.extension().and_then(|e| e.to_str()) != Some("toml") {+ continue;+ }+ let Ok(text) = std::fs::read_to_string(&path) else {+ continue;+ };+ if let Some(compiled) = compile_manifest(&text, &path.display().to_string()) {+ log::info!("agent detection override loaded for {}", compiled.id);+ map.insert(compiled.id.clone(), compiled);+ }+ }+ }+ map+}++fn ensure_loaded() {+ let loaded = MANIFESTS.read().is_some();+ if !loaded {+ let map = load_all();+ let mut slot = MANIFESTS.write();+ if slot.is_none() {+ *slot = Some(map);+ MANIFEST_GENERATION.fetch_add(1, std::sync::atomic::Ordering::AcqRel);+ }+ }+}++/// Load the manifests if they are not loaded yet. Called once at detector+/// startup so the evaluation path never does filesystem IO.+pub(crate) fn warm() {+ ensure_loaded();+}++/// Reload bundled + override files. Builds the replacement map before+/// swapping it in, so concurrent evaluations never observe an empty+/// window and the caller can run this on a worker thread.+pub(crate) fn reload_manifests() {+ let map = load_all();+ *MANIFESTS.write() = Some(map);+ MANIFEST_GENERATION.fetch_add(1, std::sync::atomic::Ordering::AcqRel);+}++pub(crate) fn with_manifests<R>(f: impl FnOnce(&HashMap<String, CompiledManifest>) -> R) -> R {+ ensure_loaded();+ let guard = MANIFESTS.read();+ match guard.as_ref() {+ Some(map) => f(map),+ None => f(&HashMap::new()),+ }+}++/// Find the manifest id whose id or aliases match a process basename.+pub(crate) fn manifest_id_for_alias(name: &str) -> Option<String> {+ with_manifests(|map| {+ if map.contains_key(name) {+ return Some(name.to_string());+ }+ // Deterministic across runs: HashMap order is randomized, so an+ // alias claimed by two manifests must not flip between them.+ let mut ids: Vec<&String> = map+ .values()+ .filter(|m| m.aliases.iter().any(|a| a == name))+ .map(|m| &m.id)+ .collect();+ ids.sort();+ ids.first().map(|id| (*id).clone())+ })+}++/// Run one agent's rules over the snapshot. Highest priority match wins;+/// on a priority tie the earlier rule in the file wins (herdr semantics).+pub fn evaluate(agent_id: &str, input: &DetectionInput) -> ScreenVerdict {+ with_manifests(|map| {+ let Some(manifest) = map.get(agent_id) else {+ return ScreenVerdict::NoMatch;+ };+ let lower_screen = input.screen.to_lowercase();+ let mut matched: Option<&CompiledRule> = None;+ for rule in &manifest.rules {+ let region_text = region(input, &rule.region);+ // The lowercase haystack is only pre-computed for the whole+ // screen; sliced regions are small, so lowercasing them per+ // rule is cheap and keeps slicing byte-exact.+ let lower_region: std::borrow::Cow<str> = if rule.region == "whole_recent" {+ std::borrow::Cow::Borrowed(&lower_screen)+ } else {+ std::borrow::Cow::Owned(region_text.to_lowercase())+ };+ if !gate_matches(&rule.gate, region_text, &lower_region) {+ continue;+ }+ match matched {+ Some(previous) if previous.priority >= rule.priority => {}+ _ => matched = Some(rule),+ }+ }+ match matched {+ Some(rule) if rule.skip_state_update => ScreenVerdict::Freeze,+ Some(rule) => ScreenVerdict::State(rule.state.unwrap_or(AgentState::Unknown)),+ None => ScreenVerdict::NoMatch,+ }+ })+}++fn gate_matches(gate: &CompiledGate, text: &str, lower_text: &str) -> bool {+ if !gate+ .contains+ .iter()+ .all(|needle| lower_text.contains(needle))+ {+ return false;+ }+ if !gate.regex.iter().all(|regex| regex.is_match(text)) {+ return false;+ }+ if !gate+ .line_regex+ .iter()+ .all(|regex| text.lines().any(|line| regex.is_match(line)))+ {+ return false;+ }+ if !gate+ .all+ .iter()+ .all(|nested| gate_matches(nested, text, lower_text))+ {+ return false;+ }+ if !gate.any.is_empty()+ && !gate+ .any+ .iter()+ .any(|nested| gate_matches(nested, text, lower_text))+ {+ return false;+ }+ if gate+ .not_gate+ .iter()+ .any(|nested| gate_matches(nested, text, lower_text))+ {+ return false;+ }+ true+}++// ---------------------------------------------------------------------------+// Regions. Behaviour matches herdr's region resolvers so their manifests+// keep their meaning.+// ---------------------------------------------------------------------------++fn region<'a>(input: &DetectionInput<'a>, spec: &str) -> &'a str {+ match spec {+ "osc_title" => return input.osc_title,+ "osc_progress" => return input.osc_progress,+ _ => {}+ }+ let content = input.screen;+ match spec {+ "whole_recent" => content,+ "after_last_prompt_marker" => after_last_prompt_marker(content),+ "prompt_box_body" => prompt_box_body(content).unwrap_or(""),+ "last_non_empty_above_prompt_box" => last_non_empty_line(above_prompt_box(content)),+ "after_last_horizontal_rule" => after_last_horizontal_rule(content),+ _ => {+ if let Some(count) = region_count(spec, "bottom_non_empty_lines") {+ bottom_non_empty_lines(content, count)+ } else if let Some(count) = region_count(spec, "bottom_lines") {+ bottom_lines(content, count)+ } else if let Some(count) = region_count(spec, "top_non_empty_lines") {+ top_non_empty_lines(content, count)+ } else {+ log::warn!("unknown agent manifest region {spec:?}");+ ""+ }+ }+ }+}++fn region_count(spec: &str, name: &str) -> Option<usize> {+ let count = spec+ .strip_prefix(name)?+ .strip_prefix('(')?+ .strip_suffix(')')?;+ if count.is_empty() || count.starts_with('0') || !count.bytes().all(|b| b.is_ascii_digit()) {+ return None;+ }+ count+ .parse::<usize>()+ .ok()+ .filter(|c| *c <= u16::MAX as usize)+}++fn line_start_offset(content: &str, lines: &[&str], index: usize) -> usize {+ lines[..index.min(lines.len())]+ .iter()+ .map(|line| line.len() + 1)+ .sum::<usize>()+ .min(content.len())+}++fn slice_from_line_index<'a>(content: &'a str, lines: &[&str], index: usize) -> &'a str {+ &content[line_start_offset(content, lines, index)..]+}++fn bottom_lines(content: &str, count: usize) -> &str {+ let lines: Vec<&str> = content.lines().collect();+ let start = lines.len().saturating_sub(count);+ slice_from_line_index(content, &lines, start)+}++fn bottom_non_empty_lines(content: &str, count: usize) -> &str {+ let lines: Vec<&str> = content.lines().collect();+ let Some(start_index) = lines+ .iter()+ .enumerate()+ .rev()+ .filter(|(_, line)| !line.trim().is_empty())+ .take(count)+ .last()+ .map(|(index, _)| index)+ else {+ return "";+ };+ slice_from_line_index(content, &lines, start_index)+}++fn top_non_empty_lines(content: &str, count: usize) -> &str {+ let lines: Vec<&str> = content.lines().collect();+ let Some(end_index) = lines+ .iter()+ .enumerate()+ .filter(|(_, line)| !line.trim().is_empty())+ .take(count)+ .last()+ .map(|(index, _)| index)+ else {+ return "";+ };+ let byte_offset = line_start_offset(content, &lines, end_index + 1);+ &content[..byte_offset]+}++/// Codex draws its prompt as a `›` line; the region is everything after the+/// last one.+fn after_last_prompt_marker(content: &str) -> &str {+ let lines: Vec<&str> = content.lines().collect();+ let Some(index) = lines+ .iter()+ .rposition(|line| *line == "›" || line.starts_with("› "))+ else {+ return content;+ };+ slice_from_line_index(content, &lines, index + 1)+}++/// The body of the bottom prompt box: between the second-to-last and last+/// horizontal rules.+fn prompt_box_body(content: &str) -> Option<&str> {+ let lines: Vec<&str> = content.lines().collect();+ let top = prompt_box_top_border_index(&lines)?;+ let start = line_start_offset(content, &lines, top + 1);+ let end_index = lines[top + 1..]+ .iter()+ .position(|line| is_horizontal_rule(line))+ .map(|relative| top + 1 + relative)+ .unwrap_or(lines.len());+ let end = line_start_offset(content, &lines, end_index);+ Some(&content[start..end.max(start)])+}++fn above_prompt_box(content: &str) -> &str {+ let lines: Vec<&str> = content.lines().collect();+ let Some(top) = prompt_box_top_border_index(&lines) else {+ return content;+ };+ let end = line_start_offset(content, &lines, top);+ &content[..end]+}++fn after_last_horizontal_rule(content: &str) -> &str {+ let mut last_rule_end = 0usize;+ let mut offset = 0usize;+ for line in content.lines() {+ let next_offset = offset + line.len() + 1;+ if is_horizontal_rule(line) {+ last_rule_end = next_offset.min(content.len());+ }+ offset = next_offset;+ }+ &content[last_rule_end..]+}++fn last_non_empty_line(content: &str) -> &str {+ content+ .lines()+ .rev()+ .find(|line| !line.trim().is_empty())+ .unwrap_or("")+}++fn prompt_box_top_border_index(lines: &[&str]) -> Option<usize> {+ let mut border_count = 0;+ for index in (0..lines.len()).rev() {+ if is_horizontal_rule(lines[index]) {+ border_count += 1;+ if border_count == 2 {+ return Some(index);+ }+ }+ }+ None+}++/// A run of `─` counts as a horizontal rule when nothing follows it, or when+/// it is at least three characters long (borders often carry a suffix such+/// as a hint label).+fn is_horizontal_rule(line: &str) -> bool {+ let trimmed = line.trim();+ if trimmed.is_empty() {+ return false;+ }+ let rule_chars = trimmed.chars().take_while(|&ch| ch == '─').count();+ if rule_chars == 0 {+ return false;+ }+ let rule_bytes = trimmed+ .char_indices()+ .nth(rule_chars)+ .map(|(index, _)| index)+ .unwrap_or(trimmed.len());+ let suffix = trimmed[rule_bytes..].trim_start();+ suffix.is_empty() || rule_chars >= 3+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn bundled_manifests_all_compile() {+ for text in BUNDLED_MANIFESTS {+ let raw_file: ManifestFile = toml::from_str(text).expect("parses");+ assert!(+ raw_file.min_engine_version.unwrap_or(0) <= ENGINE_VERSION,+ "bundled manifest {} demands a newer engine",+ raw_file.id+ );+ let compiled = compile_manifest(text, "test").expect("manifest parses");+ assert!(!compiled.id.is_empty());+ assert!(!compiled.rules.is_empty(), "{} has rules", compiled.id);+ // Every rule must have compiled; compile_manifest drops broken+ // ones, so compare against a fresh parse of the raw file.+ let raw: toml::Value = toml::from_str(text).expect("raw toml");+ let raw_rules = raw+ .get("rules")+ .and_then(|r| r.as_array())+ .map(|a| a.len())+ .unwrap_or(0);+ assert_eq!(+ compiled.rules.len(),+ raw_rules,+ "{}: all rules compile",+ compiled.id+ );+ }+ }++ #[test]+ fn alias_lookup_matches_id_and_alias() {+ assert_eq!(manifest_id_for_alias("claude").as_deref(), Some("claude"));+ assert_eq!(+ manifest_id_for_alias("claude-code").as_deref(),+ Some("claude")+ );+ assert_eq!(manifest_id_for_alias("definitely-not-an-agent"), None);+ }++ fn eval_claude(screen: &str, title: &str, progress: &str) -> ScreenVerdict {+ evaluate(+ "claude",+ &DetectionInput {+ screen,+ osc_title: title,+ osc_progress: progress,+ },+ )+ }++ #[test]+ fn claude_title_spinner_is_working() {+ let verdict = eval_claude("", "◐ fix the tests", "");+ assert!(matches!(verdict, ScreenVerdict::State(AgentState::Working)));+ let verdict = eval_claude("", "⠋ fix the tests", "");+ assert!(matches!(verdict, ScreenVerdict::State(AgentState::Working)));+ }++ #[test]+ fn claude_esc_to_interrupt_is_working() {+ let screen = "some output\n⏵⏵ Cooking… (esc to interrupt · 12s)\n";+ let verdict = eval_claude(screen, "", "");+ assert!(matches!(verdict, ScreenVerdict::State(AgentState::Working)));+ }++ #[test]+ fn claude_permission_prompt_is_blocked() {+ let screen = "\+Bash command++──────────────────────────────+Do you want to proceed?+❯ 1. Yes+ 2. No+Esc to cancel+";+ let verdict = eval_claude(screen, "", "");+ assert!(matches!(verdict, ScreenVerdict::State(AgentState::Blocked)));+ }++ #[test]+ fn claude_prompt_box_is_idle() {+ let screen = "\+previous output+──────────────────────────────+❯+──────────────────────────────+ ? for shortcuts+";+ let verdict = eval_claude(screen, "", "");+ assert!(matches!(verdict, ScreenVerdict::State(AgentState::Idle)));+ }++ #[test]+ fn claude_transcript_viewer_freezes() {+ let screen = "\+transcript line+Showing detailed transcript+ctrl+o to toggle+";+ let verdict = eval_claude(screen, "", "");+ assert!(matches!(verdict, ScreenVerdict::Freeze));+ }++ #[test]+ fn empty_screen_no_signals_is_progress_idle() {+ // osc_progress "4;0" hits claude's osc_progress_idle rule.+ let verdict = eval_claude("", "", "4;0");+ assert!(matches!(verdict, ScreenVerdict::State(AgentState::Idle)));+ }++ #[test]+ fn shell_prompt_without_box_is_no_match() {+ let verdict = eval_claude("~/src\n❯ \n", "", "");+ assert!(matches!(verdict, ScreenVerdict::NoMatch));+ }++ #[test]+ fn codex_action_required_title_is_blocked() {+ let verdict = evaluate(+ "codex",+ &DetectionInput {+ screen: "",+ osc_title: "Action Required - approve the command",+ osc_progress: "",+ },+ );+ assert!(matches!(verdict, ScreenVerdict::State(AgentState::Blocked)));+ }++ #[test]+ fn regions_slice_as_documented() {+ let content = "a\n\nb\nc\n";+ assert_eq!(bottom_non_empty_lines(content, 2), "b\nc\n");+ assert_eq!(top_non_empty_lines(content, 1), "a\n");+ assert_eq!(bottom_lines(content, 1), "c\n");+ let boxed = "x\n───\nbody\n───\n";+ assert_eq!(prompt_box_body(boxed), Some("body\n"));+ assert_eq!(above_prompt_box(boxed), "x\n");+ assert_eq!(after_last_horizontal_rule(boxed), "");+ assert_eq!(last_non_empty_line("a\nb\n\n"), "b");+ assert!(is_horizontal_rule("──────"));+ assert!(is_horizontal_rule("─── hint"));+ assert!(!is_horizontal_rule("- - -"));+ }+}diff --git a/mux/src/agent_status/hysteresis.rs b/mux/src/agent_status/hysteresis.rsnew file mode 100644index 00000000..d5eca568--- /dev/null+++ b/mux/src/agent_status/hysteresis.rs@@ -0,0 +1,200 @@+//! Transition hysteresis for published agent states.+//!+//! TUI agents redraw their screens non-atomically, and an evaluation that+//! lands mid-redraw sees a frame with no matching rule. Publishing that+//! transient (Blocked → Idle → Blocked within 300ms) makes every consumer+//! misfire: the GUI replays its needs-input sound on each re-entry and+//! announces premature completion. Modeled on herdr's pending-idle+//! confirmation (https://github.com/herdrdev/herdr, src/pane/agent_detection.rs),+//! extended to+//! also guard leaving Blocked, which herdr's fixed 300ms sampling merely+//! makes unlikely to flap.+//!+//! Only two transitions require confirmation:+//! - **Blocked → anything**: a waiting form disappearing for one frame is+//! almost always a redraw, and "still waiting" is the state whose flap+//! is loudest.+//! - **Working → Idle**: the gap between a turn ending on screen and the+//! next signal appearing, herdr's original case.+//!+//! Everything else publishes immediately — in particular `* → Blocked`,+//! because entering Blocked is the alert the user is waiting on, and+//! contract-driven transitions, which are explicit reports rather than+//! screen guesses.++use std::time::{Duration, Instant};+use thinkterm_proto::{AgentEvidence, AgentState};++/// Consistent observations required before a guarded transition is+/// published. With the 150ms evaluation cadence this is ~450ms of+/// stability.+pub(super) const RECHECK_CONFIRMATIONS: u8 = 3;+/// Hard ceiling on how long a guarded transition may be held when+/// evaluations are sparse (a quiet pane falls back to the safety tick).+pub(super) const HOLD_CAP: Duration = Duration::from_millis(700);++#[derive(Default)]+pub(super) struct Pending {+ /// The state the observations are converging on.+ target: Option<AgentState>,+ /// When the guarded transition was first observed. Deliberately kept+ /// across target flips so a flapping pane still resolves within+ /// [`HOLD_CAP`].+ first_seen: Option<Instant>,+ confirmations: u8,+}++impl Pending {+ /// Whether a guarded transition is currently being confirmed. Open+ /// panes are re-marked dirty by the drain so confirmation does not+ /// stall waiting for output.+ pub(super) fn is_open(&self) -> bool {+ self.first_seen.is_some()+ }++ fn clear(&mut self) {+ *self = Default::default();+ }++ /// Decide whether to keep publishing `published` instead of `raw`.+ /// Call once per evaluation; `now` is passed in for testability.+ pub(super) fn should_hold(+ &mut self,+ published: AgentState,+ raw: AgentState,+ evidence: AgentEvidence,+ now: Instant,+ ) -> bool {+ if raw == published || evidence == AgentEvidence::Contract {+ self.clear();+ return false;+ }+ let guarded = published == AgentState::Blocked+ || (published == AgentState::Working && raw == AgentState::Idle);+ if !guarded {+ self.clear();+ return false;+ }+ let Some(first_seen) = self.first_seen else {+ self.target = Some(raw);+ self.first_seen = Some(now);+ self.confirmations = 0;+ return true;+ };+ if now.duration_since(first_seen) >= HOLD_CAP {+ self.clear();+ return false;+ }+ if self.target != Some(raw) {+ self.target = Some(raw);+ self.confirmations = 0;+ return true;+ }+ self.confirmations = self.confirmations.saturating_add(1);+ if self.confirmations >= RECHECK_CONFIRMATIONS {+ self.clear();+ return false;+ }+ true+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn hold(p: &mut Pending, published: AgentState, raw: AgentState, now: Instant) -> bool {+ p.should_hold(published, raw, AgentEvidence::Screen, now)+ }++ #[test]+ fn same_state_never_holds() {+ let mut p = Pending::default();+ let now = Instant::now();+ assert!(!hold(&mut p, AgentState::Blocked, AgentState::Blocked, now));+ assert!(!p.is_open());+ }++ #[test]+ fn entering_blocked_publishes_immediately() {+ let mut p = Pending::default();+ let now = Instant::now();+ assert!(!hold(&mut p, AgentState::Working, AgentState::Blocked, now));+ assert!(!hold(&mut p, AgentState::Idle, AgentState::Blocked, now));+ }++ #[test]+ fn leaving_blocked_needs_confirmations() {+ let mut p = Pending::default();+ let now = Instant::now();+ assert!(hold(&mut p, AgentState::Blocked, AgentState::Idle, now), "opens");+ assert!(hold(&mut p, AgentState::Blocked, AgentState::Idle, now));+ assert!(hold(&mut p, AgentState::Blocked, AgentState::Idle, now));+ assert!(+ !hold(&mut p, AgentState::Blocked, AgentState::Idle, now),+ "third consistent recheck releases"+ );+ assert!(!p.is_open());+ }++ #[test]+ fn returning_to_published_cancels_the_hold() {+ let mut p = Pending::default();+ let now = Instant::now();+ assert!(hold(&mut p, AgentState::Blocked, AgentState::Idle, now));+ // The redraw finished and the form is back: nothing to publish,+ // nothing pending.+ assert!(!hold(&mut p, AgentState::Blocked, AgentState::Blocked, now));+ assert!(!p.is_open());+ }++ #[test]+ fn working_to_idle_is_guarded_but_working_to_blocked_is_not() {+ let mut p = Pending::default();+ let now = Instant::now();+ assert!(hold(&mut p, AgentState::Working, AgentState::Idle, now));+ assert!(!hold(&mut p, AgentState::Working, AgentState::Blocked, now));+ }++ #[test]+ fn target_flips_keep_the_original_window() {+ let mut p = Pending::default();+ let t0 = Instant::now();+ assert!(hold(&mut p, AgentState::Blocked, AgentState::Idle, t0));+ assert!(hold(&mut p, AgentState::Blocked, AgentState::Working, t0));+ // The cap is measured from the first observation, not the flip.+ assert!(!hold(+ &mut p,+ AgentState::Blocked,+ AgentState::Working,+ t0 + HOLD_CAP+ ));+ }++ #[test]+ fn hold_releases_at_cap() {+ let mut p = Pending::default();+ let t0 = Instant::now();+ assert!(hold(&mut p, AgentState::Blocked, AgentState::Idle, t0));+ assert!(!hold(+ &mut p,+ AgentState::Blocked,+ AgentState::Idle,+ t0 + HOLD_CAP+ ));+ assert!(!p.is_open());+ }++ #[test]+ fn contract_transitions_bypass_hysteresis() {+ let mut p = Pending::default();+ let now = Instant::now();+ assert!(!p.should_hold(+ AgentState::Blocked,+ AgentState::Idle,+ AgentEvidence::Contract,+ now+ ));+ assert!(!p.is_open());+ }+}diff --git a/mux/src/agent_status/identify.rs b/mux/src/agent_status/identify.rsnew file mode 100644index 00000000..46382eef--- /dev/null+++ b/mux/src/agent_status/identify.rs@@ -0,0 +1,207 @@+//! pane → agent identification.+//!+//! The contract user-var is authoritative when present. Otherwise, for+//! local panes, the foreground process basename is matched against the+//! manifest id/alias table. Remote (mux-mirror) panes have no process+//! visibility, so they identify through the contract only.++use crate::pane::{CachePolicy, Pane};+use std::collections::HashMap;+use parking_lot::Mutex;+use std::time::{Duration, Instant};++/// How long a process-based identification result (positive or negative)+/// is trusted before the foreground process is consulted again.+const IDENT_TTL: Duration = Duration::from_secs(5);++#[derive(Clone)]+struct CachedIdent {+ at: Instant,+ /// The tty's foreground process-group-leader path as last probed.+ leader_path: Option<String>,+ /// The manifest id that path resolves to, if any.+ agent: Option<String>,+}++static IDENT_CACHE: Mutex<Option<HashMap<crate::pane::PaneId, CachedIdent>>> = Mutex::new(None);++/// One probe serves both questions about a pane's foreground leader; the+/// result is cached for [`IDENT_TTL`]. The lock is never held across the+/// process probe, which can block on the process table.+fn probe(pane: &dyn Pane) -> CachedIdent {+ let pane_id = pane.pane_id();+ let now = Instant::now();++ let seeded = {+ let mut guard = IDENT_CACHE.lock();+ let cache = guard.get_or_insert_with(HashMap::new);+ match cache.get(&pane_id) {+ Some(cached) if now.duration_since(cached.at) < IDENT_TTL => {+ return cached.clone();+ }+ Some(_) => true,+ None => false,+ }+ };++ // The first probe per pane forces a fetch: on a headless mux server+ // nothing else ever warms the process-info cache, so AllowStale would+ // answer None forever. Once seeded, AllowStale suffices — its stale+ // path refreshes on a worker thread instead of blocking this one.+ let policy = if seeded {+ CachePolicy::AllowStale+ } else {+ CachePolicy::FetchImmediate+ };+ let leader_path = pane.get_foreground_process_name(policy);+ let resolved = CachedIdent {+ at: now,+ agent: leader_path+ .as_deref()+ .and_then(identify_from_process_path),+ leader_path,+ };++ let mut guard = IDENT_CACHE.lock();+ let cache = guard.get_or_insert_with(HashMap::new);+ cache.insert(pane_id, resolved.clone());+ // Opportunistic bound rather than tracking pane lifetimes. Never+ // clear wholesale: on a server with thousands of panes that would+ // wipe every live entry each sweep and degrade every probe to a+ // blocking FetchImmediate on the main thread. Expired entries go+ // first; if the cache is still over the cap, that many panes are+ // genuinely live, so shed the oldest half and keep the hot rest.+ const CACHE_CAP: usize = 4096;+ if cache.len() > CACHE_CAP {+ cache.retain(|_, cached| now.duration_since(cached.at) < IDENT_TTL);+ }+ if cache.len() > CACHE_CAP {+ let mut ages: Vec<Instant> = cache.values().map(|cached| cached.at).collect();+ ages.sort_unstable();+ let cutoff = ages[ages.len() / 2];+ cache.retain(|_, cached| cached.at >= cutoff);+ }+ resolved+}++/// Identify which agent manifest applies to this pane based on its+/// foreground process. Returns the manifest id.+pub fn identify_by_process(pane: &dyn Pane) -> Option<String> {+ if pane.is_remote_mirror() {+ return None;+ }+ probe(pane).agent+}++/// The pane's foreground process-group-leader path. The leader stays the+/// agent while it runs tool subprocesses and reverts to the shell when+/// the agent exits, which makes "the contract's emitter is gone"+/// detectable without guessing at a re-report cadence.+pub fn leader_path(pane: &dyn Pane) -> Option<String> {+ if pane.is_remote_mirror() {+ return None;+ }+ probe(pane).leader_path+}++pub fn forget_pane(pane_id: crate::pane::PaneId) {+ if let Some(cache) = IDENT_CACHE.lock().as_mut() {+ cache.remove(&pane_id);+ }+}++/// Match a foreground executable path to a manifest id: by basename, and+/// failing that by the last few directory components. Version-managed+/// launchers exec a binary named after the version — e.g. Claude Code runs+/// as `~/.local/share/claude/versions/2.1.239` — so the agent's name only+/// appears as a parent directory.+fn identify_from_process_path(path: &str) -> Option<String> {+ let name = basename(path).to_lowercase();+ if let Some(id) = super::engine::manifest_id_for_alias(&name) {+ return Some(id);+ }+ // Directory components only vouch for a *versioned launcher* layout+ // (`~/.local/share/claude/versions/2.1.239`). Without the version-like+ // basename gate, any executable under an alias-named directory would+ // be misidentified — e.g. everything in `/home/pi/.local/bin`.+ if !looks_like_version(&name) {+ return None;+ }+ path.rsplit(['/', '\\'])+ .skip(1)+ .take(2)+ .find_map(|component| super::engine::manifest_id_for_alias(&component.to_lowercase()))+}++/// A launcher-style version basename: starts with a digit, rest is+/// digits/letters/dots/dashes ("2.1.239", "1.0.0-rc1").+fn looks_like_version(name: &str) -> bool {+ let mut chars = name.chars();+ matches!(chars.next(), Some(c) if c.is_ascii_digit())+ && chars.all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')+}++fn basename(path: &str) -> &str {+ let name = path.rsplit(['/', '\\']).next().unwrap_or(path);+ name.strip_suffix(".exe").unwrap_or(name)+}++#[cfg(test)]+mod tests {+ use super::basename;++ #[test]+ fn basenames() {+ assert_eq!(basename("/usr/local/bin/claude"), "claude");+ assert_eq!(basename("codex"), "codex");+ assert_eq!(basename("C:\\tools\\codex.exe"), "codex");+ }++ #[test]+ fn versioned_launcher_paths_identify_by_parent_directory() {+ assert_eq!(+ super::identify_from_process_path("/Users/x/.local/share/claude/versions/2.1.239")+ .as_deref(),+ Some("claude")+ );+ assert_eq!(+ super::identify_from_process_path("/usr/local/bin/claude").as_deref(),+ Some("claude")+ );+ assert_eq!(super::identify_from_process_path("/bin/zsh"), None);+ // The component match only looks at the trailing directories, so a+ // deep unrelated prefix cannot misidentify.+ assert_eq!(+ super::identify_from_process_path("/home/claude/projects/tool/bin/node"),+ None+ );+ }++ /// Directory names vouch only for versioned launchers: an ordinary+ /// binary living under an alias-named directory (a user named `pi`,+ /// say) must not be misidentified.+ #[test]+ fn alias_named_directories_do_not_claim_ordinary_binaries() {+ assert_eq!(+ super::identify_from_process_path("/home/pi/.local/bin/htop"),+ None+ );+ // Even a version-like basename doesn't help when the alias is a+ // grandparent past the two-component window — `pi` here is the+ // user's home, not a launcher directory.+ assert_eq!(+ super::identify_from_process_path("/home/pi/.local/bin/2.0.1"),+ None+ );+ // A real launcher layout for the same agent still identifies.+ assert_eq!(+ super::identify_from_process_path("/home/x/pi/versions/2.0.1").as_deref(),+ Some("pi")+ );+ // The gate also bounds the walk to the last two directories.+ assert_eq!(+ super::identify_from_process_path("/opt/claude/deep/nested/2.1.0"),+ None+ );+ }+}diff --git a/mux/src/agent_status/manifests/LICENSE b/mux/src/agent_status/manifests/LICENSEnew file mode 100644index 00000000..760b8659--- /dev/null+++ b/mux/src/agent_status/manifests/LICENSE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++END OF TERMS AND CONDITIONS++APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++Copyright herdr (https://github.com/herdrdev/herdr)++Licensed under the Apache License, Version 2.0 (the "License");+you may not use this file except in compliance with the License.+You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++Unless required by applicable law or agreed to in writing, software+distributed under the License is distributed on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+See the License for the specific language governing permissions and+limitations under the License.diff --git a/mux/src/agent_status/manifests/claude.toml b/mux/src/agent_status/manifests/claude.tomlnew file mode 100644index 00000000..b80e271d--- /dev/null+++ b/mux/src/agent_status/manifests/claude.toml@@ -0,0 +1,211 @@+# Sourced from herdr (https://github.com/herdrdev/herdr) at commit d6dae88.+# Licensed under the Apache License 2.0; see NOTICE at the repository root.+# Local changes: attribution header added.++id = "claude"+version = "2026.08.21.1"+min_engine_version = 2+updated_at = "2026-08-21T00:00:00Z"+aliases = ["claude-code"]++[[rules]]+id = "osc_title_working"+state = "working"+priority = 1100+region = "osc_title"+visible_working = true+# Braille covers <= 2.1.227; half-circles are the 2.1.228 busy spinner.+regex = ['^[\x{2800}-\x{28FF}\x{25D0}-\x{25D3}] ']++[[rules]]+id = "live_turn_working"+state = "working"+priority = 970+region = "bottom_non_empty_lines(12)"+visible_working = true+any = [+ { line_regex = ['^\s*[⏸⏵].*esc to interrupt(?:\s|·|$)'] },+ { line_regex = ['^\s*[\x{002A}\x{00B7}\x{2722}\x{2736}\x{273B}\x{273D}]\s+\S.*…(?:\s+\(\d+[smh](?:\s|·)|\s*$)'] },+]++[[rules]]+id = "background_shell_working"+state = "working"+priority = 965+region = "bottom_non_empty_lines(5)"+visible_working = true+line_regex = ['^\s*[⏸⏵].*·\s+[1-9]\d*\s+shells?\s+(?:·|$)']++[[rules]]+id = "background_agents_working"+state = "working"+priority = 965+region = "last_non_empty_above_prompt_box"+visible_working = true+line_regex = ['^\s*[\x{002A}\x{00B7}\x{2722}\x{2736}\x{273B}\x{273D}]\s+Waiting for [1-9]\d* background agents? to finish\s*$']++[[rules]]+id = "background_mcp_task_working"+state = "working"+priority = 965+region = "bottom_non_empty_lines(12)"+visible_working = true+# Claude renders activity summaries at column zero; wrapped continuations are indented.+# Keeping that shape prevents user prompt text from impersonating this signal.+regex = ['(?m)^[\x{002A}\x{00B7}\x{2722}\x{2736}\x{273B}\x{273D}][ \t]+\S[^\n]*?(?:\n[ \t]+[^\n]*?){0,3}·(?:[ \t]+|\n[ \t]*)[1-9]\d*(?:[ \t]+|\n[ \t]*)MCP(?:[ \t]+|\n[ \t]*)tasks?(?:[ \t]+|\n[ \t]*)still(?:[ \t]+|\n[ \t]*)running[ \t]*$']+not = [+ { contains = ["do you want to proceed?"] },+ { contains = ["esc to cancel"] },+ { contains = ["waiting for permission"] },+ { contains = ["do you want to allow this connection?"] },+ { contains = ["tab to amend"] },+ { contains = ["ctrl+e to explain"] },+]++[[rules]]+id = "btw_overlay_working"+state = "working"+priority = 975+region = "bottom_non_empty_lines(5)"+visible_working = true+line_regex = [+ '^\s*/btw(?:\s|$)',+ '(?i)esc to close\s*$',+]++[[rules]]+id = "transcript_viewer"+state = "unknown"+priority = 1000+region = "bottom_non_empty_lines(3)"+skip_state_update = true+contains = ["showing detailed transcript"]+any = [+ { contains = ["ctrl+o", "to toggle"] },+ { contains = ["ctrl+e", "show all"] },+ { contains = ["ctrl+e", "collapse"] },+ { contains = ["↑↓ scroll"] },+ { contains = ["? for shortcuts"] },+]++[[rules]]+id = "live_blocked_form"+state = "blocked"+priority = 980+region = "after_last_horizontal_rule"+visible_blocker = true+contains = ["esc to cancel"]+any = [+ { contains = ["enter to confirm"] },+ { contains = ["enter to select"], any = [+ { contains = ["tab/arrow keys to navigate"] },+ { contains = ["arrow keys to navigate"] },+ { contains = ["arrows to navigate"] },+ { contains = ["↑/↓ to navigate"] },+ { contains = ["↑↓ to navigate"] },+ ] },+]++[[rules]]+id = "dynamic_workflow_prompt"+state = "blocked"+priority = 980+region = "whole_recent"+visible_blocker = true+contains = ["run a dynamic workflow?", "esc to cancel"]++[[rules]]+id = "live_prompt_box"+state = "idle"+priority = 950+region = "prompt_box_body"+visible_idle = true+line_regex = ['^\s*❯']+not = [+ { contains = ["enter to select"] },+ { contains = ["esc to cancel"] },+ { contains = ["tab/arrow keys"] },+ { contains = ["arrow keys to navigate"] },+ { contains = ["↑/↓ to navigate"] },+]++[[rules]]+id = "model_picker_menu"+state = "unknown"+priority = 900+region = "whole_recent"+skip_state_update = true+contains = ["select model", "enter to set as default", "esc to cancel"]+not = [+ { contains = ["do you want to proceed?"] },+ { contains = ["enter to select"] },+]++[[rules]]+id = "bash_permission_prompt"+state = "blocked"+priority = 850+region = "whole_recent"+visible_blocker = true+contains = ["do you want to proceed?"]+any = [+ { contains = ["bash command"] },+ { contains = ["bash("] },+ { contains = ["contains expansion"] },+ { contains = ["tab to amend"] },+ { contains = ["ctrl+e to explain"] },+]+all = [+ { any = [{ line_regex = ['(?i)^\s*❯?\s*yes\b'] }, { line_regex = ['(?i)^\s*1\.\s*yes\b'] }, { line_regex = ['(?i)^\s*2\.\s*no\b'] }] },+]++[[rules]]+id = "generic_permission_prompt"+state = "blocked"+priority = 840+region = "after_last_horizontal_rule"+visible_blocker = true+contains = ["do you want to proceed?", "esc to cancel"]+all = [+ { any = [+ { line_regex = ['(?i)^\s*❯?\s*1\.\s*yes\b'] },+ { line_regex = ['(?i)^\s*2\.\s*yes\b'] },+ { line_regex = ['(?i)^\s*2\.\s*no\b'] },+ { line_regex = ['(?i)^\s*3\.\s*no\b'] },+ ] },+]++[[rules]]+id = "legacy_no_prompt_blocker"+state = "blocked"+priority = 300+region = "whole_recent"+any = [+ { contains = ["do you want to"], any = [{ contains = ["yes"] }, { contains = ["❯"] }] },+ { contains = ["would you like to"], any = [{ contains = ["yes"] }, { contains = ["❯"] }] },+ { contains = ["waiting for permission"] },+ { contains = ["do you want to allow this connection?"] },+ { contains = ["tab to amend"] },+ { contains = ["ctrl+e to explain"] },+ { contains = ["do you want to proceed?", "esc to cancel"] },+ { contains = ["review your answers"] },+ { contains = ["skip interview and plan immediately"] },+]+not = [+ { regex = ['(?m)^\s*❯\s*$'] },+]++[[rules]]+id = "osc_title_idle"+state = "idle"+priority = 250+region = "osc_title"+visible_idle = true+regex = ['^\x{2733} ']++[[rules]]+id = "osc_progress_idle"+state = "idle"+priority = 250+region = "osc_progress"+regex = ['^4;0']diff --git a/mux/src/agent_status/manifests/codex.toml b/mux/src/agent_status/manifests/codex.tomlnew file mode 100644index 00000000..b8cffeb6--- /dev/null+++ b/mux/src/agent_status/manifests/codex.toml@@ -0,0 +1,93 @@+# Sourced from herdr (https://github.com/herdrdev/herdr) at commit d6dae88.+# Licensed under the Apache License 2.0; see NOTICE at the repository root.+# Local changes: attribution header added.++id = "codex"+version = "2026.08.09.1"+min_engine_version = 3+updated_at = "2026-08-09T00:00:00Z"++[[rules]]+id = "osc_title_blocked"+state = "blocked"+priority = 1100+region = "osc_title"+visible_blocker = true+contains = ["Action Required"]++[[rules]]+id = "osc_title_working"+state = "working"+priority = 1050+region = "osc_title"+visible_working = true+regex = ['(?:^| )[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏](?: |$)']++[[rules]]+id = "transcript_viewer"+state = "unknown"+priority = 1000+region = "after_last_prompt_marker"+skip_state_update = true+contains = ["↑/↓ to scroll", "pgup/pgdn to", "home/end to jump", "q to quit"]+any = [+ { contains = ["esc to edit prev"] },+ { contains = ["esc/← to edit prev"] },+]++[[rules]]+id = "trust_directory"+state = "blocked"+priority = 950+region = "top_non_empty_lines(20)"+visible_blocker = true+all = [+ { regex = ['\A> You are in [^\r\n]+(?:\r?\n|$)'] },+ { regex = ['(?s)Do\s+you\s+trust\s+the\s+contents\s+of\s+this\s+directory\?'] },+]++[[rules]]+id = "live_strong_blocker"+state = "blocked"+priority = 900+region = "after_last_prompt_marker"+visible_blocker = true+any = [+ { contains = ["press enter to confirm or esc to cancel"] },+ { contains = ["enter to submit answer"] },+ { contains = ["enter to submit all"] },+ { contains = ["allow command?"] },+]++[[rules]]+id = "weak_blocker"+state = "blocked"+priority = 600+region = "whole_recent"+any = [+ { contains = ["[y/n]"] },+ { contains = ["yes (y)"] },+ { contains = ["do you want to"], any = [{ contains = ["yes"] }, { contains = ["❯"] }] },+ { contains = ["would you like to"], any = [{ contains = ["yes"] }, { contains = ["❯"] }] },+]++[[rules]]+id = "screen_working_fallback"+state = "working"+priority = 500+region = "bottom_non_empty_lines(3)"+visible_working = true+line_regex = ['^[•◦]\s+Working \([^)]*esc to interrupt\)(?: · .*)?$']+not = [{ contains = ["■ Conversation interrupted"] }]++[[rules]]+id = "osc_title_idle"+state = "idle"+priority = 100+region = "osc_title"+visible_idle = true+regex = ['\S']+not = [+ { regex = ['(?:^| )[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏](?: |$)'] },+ { contains = ["Action Required"] },+]diff --git a/mux/src/agent_status/manifests/cursor.toml b/mux/src/agent_status/manifests/cursor.tomlnew file mode 100644index 00000000..ddb96bfb--- /dev/null+++ b/mux/src/agent_status/manifests/cursor.toml@@ -0,0 +1,61 @@+# Sourced from herdr (https://github.com/herdrdev/herdr) at commit d6dae88.+# Licensed under the Apache License 2.0; see NOTICE at the repository root.+# Local changes: attribution header added.++id = "cursor"+version = "2026.08.03.1"+min_engine_version = 1+updated_at = "2026-08-03T01:08:04Z"+aliases = ["cursor-agent"]++[[rules]]+id = "write_file_approval"+state = "blocked"+priority = 320+region = "bottom_non_empty_lines(8)"+visible_blocker = true+contains = ["write to this file?", "proceed (y)"]+any = [+ { contains = ["reject & propose changes"] },+ { contains = ["esc or n or p"] },+ { contains = ["add write("] },+]++[[rules]]+id = "approval_prompt"+state = "blocked"+priority = 300+region = "whole_recent"+visible_blocker = true+any = [+ { contains = ["waiting for approval", "run this command?"], any = [{ contains = ["run (once) (y)"] }, { contains = ["skip (esc or n)"] }] },+ { contains = ["(y) (enter)"] },+ { line_regex = ['(?i)^\s*allow .*\(y\)'] },+ { contains = ["keep (n)"] },+ { contains = ["skip (esc or n)"] },+ { line_regex = ['(?i)^\s*(?:→\s*)?run .*\(y\)'] },+]++[[rules]]+id = "stop_hint_working"+state = "working"+priority = 100+region = "bottom_non_empty_lines(6)"+visible_working = true+contains = ["ctrl+c to stop"]++[[rules]]+id = "background_task_status_working"+state = "working"+priority = 95+region = "bottom_non_empty_lines(5)"+visible_working = true+line_regex = ['(?i)\b[1-9][0-9]*\s+background\s+tasks?\b']++[[rules]]+id = "spinner_working"+state = "working"+priority = 90+region = "bottom_non_empty_lines(8)"+visible_working = true+line_regex = ['^\s*(⬡|⬢|[\u2800-\u28FF]+)\s+\p{Alphabetic}+\w*ing\b']diff --git a/mux/src/agent_status/manifests/github-copilot.toml b/mux/src/agent_status/manifests/github-copilot.tomlnew file mode 100644index 00000000..456a3b0c--- /dev/null+++ b/mux/src/agent_status/manifests/github-copilot.toml@@ -0,0 +1,41 @@+# Sourced from herdr (https://github.com/herdrdev/herdr) at commit d6dae88.+# Licensed under the Apache License 2.0; see NOTICE at the repository root.+# Local changes: attribution header added.++id = "copilot"+version = "2026.07.07.1"+min_engine_version = 1+updated_at = "2026-07-07T14:15:00Z"+aliases = ["github-copilot", "ghcs"]++[[rules]]+id = "selection_blocker"+state = "blocked"+priority = 300+region = "whole_recent"+visible_blocker = true+all = [+ { any = [+ { contains = ["esc to cancel"] },+ { contains = ["esc cancel"] },+ ] },+ { any = [+ { contains = ["enter to select"] },+ { contains = ["enter to confirm"] },+ { contains = ["enter to submit"] },+ { contains = ["enter accept"] },+ ] },+]++[[rules]]+id = "working_cancel_hint"+state = "working"+priority = 100+region = "whole_recent"+visible_working = true+any = [+ { contains = ["esc to cancel"] },+ { contains = ["esc cancel"] },+ { contains = ["esc again to cancel"] },+ { contains = ["esc interrupt"] }+]diff --git a/mux/src/agent_status/manifests/kimi.toml b/mux/src/agent_status/manifests/kimi.tomlnew file mode 100644index 00000000..d5588f1d--- /dev/null+++ b/mux/src/agent_status/manifests/kimi.toml@@ -0,0 +1,81 @@+# Sourced from herdr (https://github.com/herdrdev/herdr) at commit d6dae88.+# Licensed under the Apache License 2.0; see NOTICE at the repository root.+# Local changes: attribution header added.++id = "kimi"+version = "2026.06.10.1"+min_engine_version = 1+updated_at = "2026-06-10T00:00:00Z"+aliases = ["kimi-code", "kimi code"]++[[rules]]+id = "current_approval_panel"+state = "blocked"+priority = 400+region = "whole_recent"+visible_blocker = true+contains = ["↵ confirm"]+any = [+ { contains = ["run this command?"] },+ { contains = ["write this file?"] },+ { contains = ["apply these edits?"] },+ { contains = ["stop this task?"] },+ { contains = ["ready to build with this plan?"] },+ { line_regex = ['(?i)^\s*▶?\s*approve .*\?$'] },+]+all = [+ { contains = [" choose"] },+ { any = [{ contains = ["approve"] }, { contains = ["reject"] }, { contains = ["revise"] }] },+]++[[rules]]+id = "question_panel"+state = "blocked"+priority = 390+region = "whole_recent"+visible_blocker = true+contains = ["↑↓ select", "esc cancel"]+line_regex = ['^\s*question\s*$', '^\s*\? ']+any = [+ { contains = ["↵ choose"] },+ { contains = ["↵ toggle"] },+ { contains = ["↵ save"] },+]++[[rules]]+id = "legacy_approval_panel"+state = "blocked"+priority = 300+region = "whole_recent"+contains = ["requesting approval", "reject"]+any = [+ { contains = ["approve once"] },+ { contains = ["approve for this session"] },+]+all = [+ { any = [{ contains = ["1/2/3/4 choose"] }, { contains = ["↵ confirm"] }] },+]++[[rules]]+id = "background_agent_status_working"+state = "working"+priority = 120+region = "bottom_non_empty_lines(3)"+visible_working = true+line_regex = ['(?i)\bkimi[-\w.]*\s+thinking\b.*\[[1-9][0-9]*\s+agents?\s+running\]']++[[rules]]+id = "moon_spinner_working"+state = "working"+priority = 100+region = "whole_recent"+visible_working = true+line_regex = ['^\s*(🌕|🌖|🌗|🌘|🌑|🌒|🌓|🌔)\s*$']++[[rules]]+id = "braille_spinner_working"+state = "working"+priority = 90+region = "whole_recent"+visible_working = true+line_regex = ['(?i)^\s*[\u2800-\u28FF]+\s*(thinking\.\.\.|working\.\.\.|using )']diff --git a/mux/src/agent_status/manifests/opencode.toml b/mux/src/agent_status/manifests/opencode.tomlnew file mode 100644index 00000000..51814765--- /dev/null+++ b/mux/src/agent_status/manifests/opencode.toml@@ -0,0 +1,41 @@+# Sourced from herdr (https://github.com/herdrdev/herdr) at commit d6dae88.+# Licensed under the Apache License 2.0; see NOTICE at the repository root.+# Local changes: attribution header added.++id = "opencode"+version = "2026.06.10.1"+min_engine_version = 1+updated_at = "2026-06-10T00:00:00Z"+aliases = ["open-code", "herdr:opencode"]++[[rules]]+id = "permission_required"+state = "blocked"+priority = 300+region = "whole_recent"+visible_blocker = true+any = [+ { contains = ["△ Permission required"] },+ { contains = ["esc dismiss"], any = [{ contains = ["enter confirm"] }, { contains = ["enter submit"] }, { contains = ["enter toggle"] }], all = [{ any = [{ contains = ["↑↓ select"] }, { contains = ["⇆ tab"] }] }] },+]++[[rules]]+id = "interrupt_hint_working"+state = "working"+priority = 110+region = "whole_recent"+visible_working = true+any = [+ { contains = ["esc to interrupt"] },+ { contains = ["ctrl+c to interrupt"] },+ { contains = ["press esc to interrupt"] },+ { line_regex = ['(?i).*opencode.*esc (again to )?interrupt'] },+]++[[rules]]+id = "progress_bar_working"+state = "working"+priority = 100+region = "whole_recent"+visible_working = true+regex = ['(■|⬝){4,}']diff --git a/mux/src/agent_status/manifests/pi.toml b/mux/src/agent_status/manifests/pi.tomlnew file mode 100644index 00000000..badfa3fa--- /dev/null+++ b/mux/src/agent_status/manifests/pi.toml@@ -0,0 +1,17 @@+# Sourced from herdr (https://github.com/herdrdev/herdr) at commit d6dae88.+# Licensed under the Apache License 2.0; see NOTICE at the repository root.+# Local changes: attribution header added.++id = "pi"+version = "2026.06.10.1"+min_engine_version = 1+updated_at = "2026-06-10T00:00:00Z"+aliases = ["herdr:pi"]++[[rules]]+id = "working_literal"+state = "working"+priority = 100+region = "whole_recent"+visible_working = true+contains = ["Working..."]diff --git a/mux/src/agent_status/mod.rs b/mux/src/agent_status/mod.rsnew file mode 100644index 00000000..fd4cc008--- /dev/null+++ b/mux/src/agent_status/mod.rs@@ -0,0 +1,1461 @@+//! Agent status detection core.+//!+//! Classifies panes that run coding agents (Claude Code, Codex, …) as+//! Working / Blocked / Idle by arbitrating three signal layers:+//!+//! 1. the `THINKTERM_AGENT` user-var contract ([`contract`]) — the agent+//! (or its hook script) reports identity, session, and state;+//! 2. manifest-driven screen rules ([`engine`]) — the pane's live screen+//! tail plus OSC title/progress, evaluated against herdr-compatible+//! rule files. A matching rule outranks the contract's *state*, because+//! the two known contract gaps (Esc interrupt, permission-prompt+//! cancel) both look like "contract says working, screen shows idle";+//! 3. nothing: when neither speaks, a known agent settles to Idle (never+//! Blocked).+//!+//! Detection runs in the process that **owns** the pane: the predicate is+//! `!is_remote_mirror() && !is_dead()`. A mux server therefore classifies+//! all of its panes (full screen-rule coverage for remote clients), the+//! GUI's embedded mux classifies its local panes, and a ClientPane answers+//! [`Pane::agent_status`] from whatever the owning server pushed. That one+//! predicate is the whole no-double-detection story.++pub mod contract;+pub mod engine;+mod hysteresis;+pub mod identify;++use crate::pane::{Pane, PaneId};+use crate::{Mux, MuxNotification};+use parking_lot::{Mutex, RwLock};+use std::collections::{HashMap, HashSet};+use std::sync::atomic::{AtomicBool, Ordering};+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};+use thinkterm_proto::{AgentEvidence, AgentState, AgentStatus};++/// Minimum interval between screen reads for one pane even while output+/// is flowing.+const SCREEN_READ_FLOOR: Duration = Duration::from_millis(150);+/// How many rows from the bottom of the live screen the rules may see.+/// Large enough to cover a whole typical viewport: manifests address the+/// top of the screen too (`top_non_empty_lines`), and a prompt drawn up+/// there is invisible to every rule if the slice stops short of it.+const TAIL_ROWS: isize = 64;+/// At most one evaluation pass per this interval, process-wide. A leading+/// edge throttle rather than a trailing debounce: an agent that prints+/// continuously must still be classified while it streams.+const EVAL_INTERVAL: Duration = Duration::from_millis(150);+/// Quiet panes emit no PaneOutput, but contract freshness expiry, agents+/// exiting back to a shell, and pane death still need a pulse.+const SAFETY_TICK: Duration = Duration::from_secs(2);++struct ScreenCache {+ seqno: termwiz::surface::SequenceNo,+ title: String,+ progress: String,+ at: Instant,+ /// Manifest generation the verdict was computed under; a rules reload+ /// invalidates it even if this cache was written after the reload's+ /// sweep by a racing evaluation.+ generation: u64,+ verdict: CachedVerdict,+}++#[derive(Clone, Copy)]+enum CachedVerdict {+ State(AgentState),+ Freeze,+ NoMatch,+}++struct AgentPaneRecord {+ agent_id: String,+ session_id: Option<String>,+ state: AgentState,+ evidence: AgentEvidence,+ since_unix: u64,+ ended: bool,+ screen_cache: Option<ScreenCache>,+ /// What consumers currently see; publication notifies only on change.+ published: Option<AgentStatus>,+ /// Confirmation window for guarded transitions; see [`hysteresis`].+ pending: hysteresis::Pending,+ /// The raw contract string last seen, and the foreground leader+ /// observed when it changed: together they prove the emitter is still+ /// alive when the contract itself has gone stale.+ contract_raw: Option<String>,+ contract_leader: Option<String>,+}++lazy_static::lazy_static! {+ static ref REGISTRY: RwLock<HashMap<PaneId, AgentPaneRecord>> = RwLock::new(HashMap::new());+ static ref PENDING: Mutex<HashSet<PaneId>> = Mutex::new(HashSet::new());+ static ref PROCESS_PREFERENCE: RwLock<Option<Box<dyn Fn() -> bool + Send + Sync>>> =+ RwLock::new(None);+}+static TICK_SCHEDULED: AtomicBool = AtomicBool::new(false);+static INSTALLED: AtomicBool = AtomicBool::new(false);+/// Cached gate consulted on every notification: the full computation+/// (config lookup + preference closure) is too heavy for the pty parser+/// threads' hot path, so it runs only on the refresh points (init, the+/// safety tick, config reload, the settings toggle).+static ENABLED: AtomicBool = AtomicBool::new(false);++/// The status the owning process last published for this pane, if any.+/// This is what `Pane::agent_status`'s default body answers with.+pub fn status_for_pane(pane_id: PaneId) -> Option<AgentStatus> {+ REGISTRY+ .read()+ .get(&pane_id)+ .and_then(|record| record.published.clone())+}++/// Install a process-local veto consulted alongside the Lua config option.+/// The GUI wires its native-settings toggle through this so the user-facing+/// switch governs the GUI's own detector; headless servers install nothing+/// and follow `agent_status_detection` alone.+pub fn set_process_preference(preference: impl Fn() -> bool + Send + Sync + 'static) {+ *PROCESS_PREFERENCE.write() = Some(Box::new(preference));+ refresh_enabled();+}++fn compute_enabled() -> bool {+ if !config::configuration().agent_status_detection {+ return false;+ }+ PROCESS_PREFERENCE.read().as_ref().map(|f| f()).unwrap_or(true)+}++/// Re-evaluate the gate. Call after anything it depends on changes: the+/// GUI's settings toggle does, config reload and the safety tick do.+pub fn refresh_enabled() {+ ENABLED.store(compute_enabled(), Ordering::Release);+}++pub fn detection_enabled() -> bool {+ ENABLED.load(Ordering::Acquire)+}++/// Install the process-wide detector: one mux subscription plus the safety+/// tick. Idempotent; the GUI and standalone server call this only after their+/// main-thread scheduler is ready. CLI proxy and TUI processes never call it.+pub fn initialize_mux(mux: &Mux) {+ // Keep a future call-site regression from taking down the whole app. Do+ // not claim INSTALLED here: the owner can retry once its scheduler exists.+ if !promise::spawn::is_scheduler_configured() {+ log::error!("agent status detector initialization deferred: no scheduler is configured");+ return;+ }+ if INSTALLED.swap(true, Ordering::AcqRel) {+ return;+ }+ refresh_enabled();+ std::mem::forget(config::subscribe_to_config_reload(|| {+ // Deferred, never inline: this callback runs while the config+ // reload still holds the global config mutex, and refresh_enabled+ // -> config::configuration() would re-lock it — a same-thread+ // deadlock that freezes the whole process. Every config+ // subscriber in the tree defers for exactly this reason.+ promise::spawn::spawn_into_main_thread(async {+ refresh_enabled();+ })+ .detach();+ true+ }));+ // Load the manifests now, off the evaluation path: the first+ // evaluation must not do filesystem IO on the main thread.+ engine::warm();+ mux.subscribe(|notification| {+ // The flag-off promise is byte-identical behavior: one atomic+ // read per notification and nothing else.+ if !detection_enabled() {+ return true;+ }+ match notification {+ MuxNotification::PaneOutput(pane_id) | MuxNotification::PaneAdded(pane_id) => {+ mark_dirty(pane_id)+ }+ MuxNotification::Alert { pane_id, alert } if alert_is_interesting(&alert) => {+ mark_dirty(pane_id)+ }+ // Evict only, never publish: this closure runs inside+ // Mux::notify, and clients already learn of the pane's demise+ // from PaneRemoved itself — a trailing AgentStatusChanged for a+ // pane they just unmapped would only trigger wasted resyncs.+ MuxNotification::PaneRemoved(pane_id) => {+ evict_pane(pane_id);+ }+ _ => {}+ }+ true+ });+ promise::spawn::spawn_into_main_thread(async {+ loop {+ smol::Timer::after(SAFETY_TICK).await;+ // This loop is the only pulse quiet panes get; a panic below+ // (including inside the config read) must re-arm the tick, not+ // silently end detection for the remaining process lifetime.+ let tick = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ refresh_enabled();+ if detection_enabled() {+ let Some(mux) = Mux::try_get() else {+ return;+ };+ for pane in mux.iter_panes() {+ mark_dirty(pane.pane_id());+ }+ // Also pulse registry entries whose pane the mux no+ // longer knows: a PaneRemoved eviction that raced an+ // in-flight evaluation can resurrect a record, and+ // the drain's get_pane miss is what cleans it up.+ let ghosts: Vec<PaneId> = REGISTRY.read().keys().copied().collect();+ for pane_id in ghosts {+ mark_dirty(pane_id);+ }+ } else {+ // Quiet panes produce no output to trigger the+ // enabled→disabled sweep; run it from here so remote+ // clients are not left frozen on stale statuses.+ drain_and_evaluate();+ }+ }));+ if tick.is_err() {+ log::error!("agent status safety tick panicked; detection continues");+ }+ }+ })+ .detach();+}++fn alert_is_interesting(alert: &wezterm_term::Alert) -> bool {+ use wezterm_term::Alert;+ matches!(+ alert,+ Alert::SetUserVar { .. }+ | Alert::Progress(_)+ | Alert::WindowTitleChanged(_)+ | Alert::TabTitleChanged(_)+ | Alert::IconTitleChanged(_)+ )+}++fn mark_dirty(pane_id: PaneId) {+ if !detection_enabled() {+ return;+ }+ PENDING.lock().insert(pane_id);+ if TICK_SCHEDULED.swap(true, Ordering::AcqRel) {+ return;+ }+ // spawn_into_main_thread, not spawn: PaneOutput notifications arrive on+ // the pty parser threads, where no local scheduler exists. The timer+ // then runs on the main executor alongside everything else.+ promise::spawn::spawn_into_main_thread(async {+ smol::Timer::after(EVAL_INTERVAL).await;+ TICK_SCHEDULED.store(false, Ordering::Release);+ // The flag is already reset, so a panic here self-heals on the next+ // mark_dirty; catch it anyway so the executor task dies quietly and+ // the failure is visible in the log.+ if std::panic::catch_unwind(std::panic::AssertUnwindSafe(drain_and_evaluate)).is_err() {+ log::error!("agent status evaluation panicked; detection continues");+ }+ })+ .detach();+}++/// Reload the screen-rule manifests and re-judge every known pane. The+/// engine swap alone is not enough: a pane whose screen has not changed+/// since its last evaluation keeps serving a cached verdict (the+/// seqno-equality reuse), which was computed under the *old* rules and+/// would survive indefinitely. Safe to call from any thread; the caller+/// may run it on a worker since loading reads manifest files.+pub fn reload_rules() {+ engine::reload_manifests();+ let panes: Vec<PaneId> = {+ let mut registry = REGISTRY.write();+ for record in registry.values_mut() {+ record.screen_cache = None;+ }+ registry.keys().copied().collect()+ };+ for pane_id in panes {+ mark_dirty(pane_id);+ }+}++/// Drop a pane's state without telling anyone. Returns whether a published+/// status was dropped so callers outside the notify path can decide to+/// publish the eviction. Deliberately never notifies: the PaneRemoved+/// subscriber runs inside `Mux::notify`, where a synchronous nested notify+/// re-enters the subscriber lock and deadlocks the process.+///+/// Invariant note: every other mutation of a published status enqueues a+/// trailing AgentStatusChanged, which is what lets the client's+/// authoritative snapshot fetch converge against live pushes. This+/// silent path is safe only because the PaneRemoved PDU itself follows+/// on the same dispatch channel; do not add further silent mutations.+fn evict_pane(pane_id: PaneId) -> bool {+ identify::forget_pane(pane_id);+ REGISTRY+ .write()+ .remove(&pane_id)+ .and_then(|record| record.published)+ .is_some()+}++/// Notify consumers that a pane's status changed. Always deferred to a+/// fresh main-thread task, never synchronous: publish sites are reachable+/// from inside Mux subscriber callbacks, and a synchronous notify there+/// re-enters the subscriber lock (see `evict_pane`). Unit tests have no+/// scheduler and record into a log instead.+fn publish_change(pane_id: PaneId) {+ #[cfg(test)]+ {+ tests::record_publish(pane_id);+ }+ #[cfg(not(test))]+ promise::spawn::spawn_into_main_thread(async move {+ if let Some(mux) = Mux::try_get() {+ mux.notify(MuxNotification::AgentStatusChanged(pane_id));+ }+ })+ .detach();+}++fn drain_and_evaluate() {+ if !detection_enabled() {+ // Enabled→disabled edge: evict everything, loudly.+ let ids: Vec<PaneId> = REGISTRY.read().keys().copied().collect();+ for pane_id in ids {+ if evict_pane(pane_id) {+ publish_change(pane_id);+ }+ }+ PENDING.lock().clear();+ return;+ }+ let dirty: Vec<PaneId> = PENDING.lock().drain().collect();+ let Some(mux) = Mux::try_get() else {+ return;+ };+ for pane_id in dirty {+ let Some(pane) = mux.get_pane(pane_id) else {+ if evict_pane(pane_id) {+ publish_change(pane_id);+ }+ continue;+ };+ if pane.is_remote_mirror() {+ continue;+ }+ if pane.is_dead() {+ if evict_pane(pane_id) {+ publish_change(pane_id);+ }+ continue;+ }+ if evaluate_pane(pane.as_ref()) {+ publish_change(pane_id);+ }+ }+ // Panes mid-confirmation must not stall until the next output or the+ // 2s safety tick: re-mark them so the next 150ms round re-checks.+ let confirming: Vec<PaneId> = REGISTRY+ .read()+ .iter()+ .filter(|(_, record)| record.pending.is_open())+ .map(|(id, _)| *id)+ .collect();+ for pane_id in confirming {+ mark_dirty(pane_id);+ }+}++/// Classify one pane and update the registry. Returns whether the+/// published status changed.+fn evaluate_pane(pane: &dyn Pane) -> bool {+ let pane_id = pane.pane_id();++ let user_vars = pane.copy_user_vars();+ let contract_raw = user_vars.get(contract::USER_VAR_NAME).cloned();+ let parsed_contract = contract_raw.as_deref().and_then(contract::parse);++ let now_unix = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|d| d.as_secs())+ .unwrap_or(0);++ // Identity, in strict priority order:+ // R1: a live foreground process matching a manifest — ground truth+ // for what is running *now*; a user var is a message from the+ // past and never overrides it.+ // R2: otherwise, a contract that has not declared `ended` — either+ // still fresh, or (for long-silent native emitters) proven live+ // because the pane's foreground leader is unchanged since the+ // contract was last emitted.+ // R3: otherwise no agent: the record is evicted, so a pane that ran+ // claude once stops being classified the moment claude is gone,+ // and `cat` output can no longer impersonate a permission+ // prompt.+ let process_agent = identify::identify_by_process(pane);+ let process_backed = process_agent.is_some();+ let leader = identify::leader_path(pane);+ let contract_identity = parsed_contract.as_ref().and_then(|c| {+ if c.ended || process_agent.is_some() {+ return None;+ }+ match REGISTRY.read().get(&pane_id) {+ // A known pane must still have the emitter as its foreground+ // leader — freshness alone is not liveness. An idle contract+ // stays fresh forever and a working one for hours; without+ // this check an agent that died without saying `ended=1`+ // would pin its identity onto the shell. Only a definite+ // mismatch (both sides observed, different) kills the+ // identity: a transient probe failure must not evict.+ Some(record) if record.agent_id == c.agent_id => {+ let emitter_gone = matches!(+ (&record.contract_leader, &leader),+ (Some(recorded), Some(current)) if recorded != current+ );+ if emitter_gone {+ return None;+ }+ }+ // No history for this agent to validate against: only a+ // fresh contract may establish identity, so a relic var+ // cannot resurrect.+ _ => {+ if !contract::state_is_fresh(c, now_unix) {+ return None;+ }+ }+ }+ Some(c.agent_id.clone())+ });+ let agent_id = process_agent.or(contract_identity);++ let Some(agent_id) = agent_id else {+ let removed = REGISTRY.write().remove(&pane_id);+ let had_record = removed.is_some();+ let had_published = removed.and_then(|record| record.published).is_some();+ if had_record {+ // An agent just left: drop its identity cache entry so the+ // next occupant is probed fresh, and clear its retained OSC+ // signals so they cannot leak into whatever runs next. For a+ // pane that never was an agent, the negative identification+ // stays cached for its TTL — dropping it here would force a+ // synchronous process probe per shell pane per round.+ identify::forget_pane(pane_id);+ pane.clear_agent_osc_evidence();+ }+ return had_published;+ };++ // Real emissions only: `get_title`/`get_progress` substitute display+ // defaults (process basename, cleared progress) that would make the+ // manifests' idle rules match unconditionally.+ let osc = pane.agent_osc_evidence();+ let mut title = osc.title.unwrap_or_default();+ let mut progress = osc.progress.unwrap_or_default();+ let now = Instant::now();++ // Phase 1, read lock only: occupant turnover and verdict reuse. The+ // write lock must not be held across the screen read and the manifest+ // scan — `Pane::agent_status` is answered from dispatch and session+ // handlers that must not stall behind another pane's evaluation.+ // Read the seqno before taking the registry lock: get_current_seqno+ // takes the terminal lock, and holding registry-then-terminal here+ // would be a lock-order trap for any future terminal-then-registry+ // path.+ let current_seqno = pane.get_current_seqno();+ let (turnover, reused_verdict) = {+ let registry = REGISTRY.read();+ let record = registry.get(&pane_id);+ // A different agent or session replaces the record wholesale so+ // nothing from the previous occupant carries over — including its+ // retained OSC evidence, which the terminal still holds and which+ // must not classify the new occupant for even one round.+ let turnover = record+ .map(|record| {+ record.agent_id != agent_id+ || parsed_contract+ .as_ref()+ .map(|c| {+ // Only a contract describing *this* agent can+ // declare a session change; a relic var from a+ // previous occupant must not tear the record+ // down every round (which would also destroy+ // the hysteresis window and the OSC evidence).+ c.agent_id == record.agent_id+ && c.session_id.is_some()+ && record.session_id != c.session_id+ })+ .unwrap_or(false)+ })+ .unwrap_or(false);+ let reused_verdict = if turnover {+ None+ } else {+ record.and_then(|record| {+ // While a guarded transition is being confirmed, the+ // age-based reuse clause is suspended: counting a cached+ // verdict as a confirmation would confirm against a stale+ // observation and halve the effective debounce. Reuse on+ // an unchanged seqno stays — an unmoved screen genuinely+ // is evidence of stability.+ let confirming = record.pending.is_open();+ record+ .screen_cache+ .as_ref()+ .filter(|c| {+ c.generation == engine::manifest_generation()+ && c.title == title+ && c.progress == progress+ && (c.seqno == current_seqno+ || (!confirming+ && now.duration_since(c.at) < SCREEN_READ_FLOOR))+ })+ .map(|c| c.verdict)+ })+ };+ (turnover, reused_verdict)+ };++ if turnover {+ REGISTRY.write().remove(&pane_id);+ pane.clear_agent_osc_evidence();+ title.clear();+ progress.clear();+ }++ // Phase 2, no lock: the screen read and the manifest scan.+ let (verdict, fresh_cache) = match reused_verdict {+ Some(verdict) => (verdict, None),+ None => {+ let screen = read_screen_tail(pane);+ let verdict = match engine::evaluate(+ &agent_id,+ &engine::DetectionInput {+ screen: &screen,+ osc_title: &title,+ osc_progress: &progress,+ },+ ) {+ engine::ScreenVerdict::State(state) => CachedVerdict::State(state),+ engine::ScreenVerdict::Freeze => CachedVerdict::Freeze,+ engine::ScreenVerdict::NoMatch => CachedVerdict::NoMatch,+ };+ // Stamped with the seqno captured *before* the read: output+ // landing during evaluation must invalidate this verdict, and+ // a pane that then blocks on input never advances the seqno+ // again, so a post-read stamp would pin the stale verdict for+ // good.+ let cache = ScreenCache {+ seqno: current_seqno,+ title: title.clone(),+ progress: progress.clone(),+ at: now,+ generation: engine::manifest_generation(),+ verdict,+ };+ (verdict, Some(cache))+ }+ };++ let contract_state = parsed_contract.as_ref().filter(|c| c.agent_id == agent_id).and_then(|c| {+ if c.ended {+ Some(AgentState::Idle)+ } else if c.state != AgentState::Unknown && contract::state_is_fresh(c, now_unix) {+ Some(c.state)+ } else {+ None+ }+ });++ // Phase 3, write lock: apply. The registry may have changed while+ // unlocked (a PaneRemoved eviction from another thread); re-fetching+ // here keeps the apply self-consistent. A lost race can re-create a+ // record for a removed pane; the safety tick pulses every registry id,+ // so the next drain's get_pane miss evicts it.+ let mut registry = REGISTRY.write();+ let registry = &mut *registry;+ // Before the placeholder insert below: a brand-new pane must present+ // as "no previous state", not as the placeholder's Unknown.+ let previous_state = registry.get(&pane_id).map(|r| r.state);+ if let Some(cache) = fresh_cache {+ if let Some(record) = registry.get_mut(&pane_id) {+ record.screen_cache = Some(cache);+ } else {+ registry.insert(+ pane_id,+ AgentPaneRecord {+ agent_id: agent_id.clone(),+ session_id: None,+ state: AgentState::Unknown,+ evidence: AgentEvidence::Fallback,+ since_unix: now_unix,+ ended: false,+ screen_cache: Some(cache),+ published: None,+ pending: Default::default(),+ contract_raw: None,+ contract_leader: None,+ },+ );+ }+ }++ let (state, evidence) = match verdict {+ CachedVerdict::State(state) => (state, AgentEvidence::Screen),+ CachedVerdict::Freeze => match previous_state {+ Some(state) => (state, AgentEvidence::Screen),+ None => match contract_state {+ Some(state) => (state, AgentEvidence::Contract),+ None => (AgentState::Idle, AgentEvidence::Fallback),+ },+ },+ CachedVerdict::NoMatch => match contract_state {+ Some(state) => (state, AgentEvidence::Contract),+ None => (AgentState::Idle, AgentEvidence::Fallback),+ },+ };++ let record = registry.entry(pane_id).or_insert_with(|| AgentPaneRecord {+ agent_id: agent_id.clone(),+ session_id: None,+ state,+ evidence,+ since_unix: now_unix,+ ended: false,+ screen_cache: None,+ published: None,+ pending: Default::default(),+ contract_raw: None,+ contract_leader: None,+ });+ record.agent_id = agent_id;+ if record.contract_raw != contract_raw {+ // A (re-)emission: snapshot who the foreground leader was, so a+ // later staleness check can tell "silent but alive" from "gone".+ record.contract_raw = contract_raw;+ record.contract_leader = leader;+ }+ match parsed_contract.as_ref() {+ // Contract fields describe *this* agent only; a relic var from a+ // previous occupant must not decorate the new one.+ Some(c) if c.agent_id == record.agent_id => {+ if c.session_id.is_some() {+ record.session_id = c.session_id.clone();+ }+ // A live process outranks a claimed ending: `ended` is a+ // farewell, and the process still being foreground means it+ // was premature or belongs to a finished sub-session.+ record.ended = c.ended && !process_backed;+ }+ _ => {}+ }+ // Guarded transitions keep publishing the held state until the raw+ // observation proves stable; the first classification is never held.+ let (state, evidence) = if record.published.is_some()+ && record.pending.should_hold(record.state, state, evidence, now)+ {+ (record.state, record.evidence)+ } else {+ (state, evidence)+ };+ if record.state != state {+ record.state = state;+ record.since_unix = now_unix;+ }+ record.evidence = evidence;++ let status = AgentStatus {+ agent_id: record.agent_id.clone(),+ state: record.state,+ evidence: record.evidence,+ session_id: record.session_id.clone(),+ since_unix: record.since_unix,+ ended: record.ended,+ };+ if record.published.as_ref() == Some(&status) {+ false+ } else {+ record.published = Some(status);+ true+ }+}++/// The pane's live screen bottom, independent of the user's scroll+/// position: scrollback sits below `physical_top`, so slicing from the+/// physical screen ignores the viewport.+fn read_screen_tail(pane: &dyn Pane) -> String {+ let dims = pane.get_dimensions();+ if dims.cols == 0 || dims.viewport_rows == 0 {+ return String::new();+ }+ let last = dims.physical_top + dims.viewport_rows as isize;+ let start = (last - TAIL_ROWS).max(dims.physical_top);+ let (_first, lines) = pane.get_lines(start..last);+ let mut text = String::new();+ for line in &lines {+ text.push_str(&line.as_str());+ text.push('\n');+ }+ text+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::pane::{CachePolicy, ForEachPaneLogicalLine, LogicalLine, WithPaneLines};+ use crate::renderable::*;+ use crate::DomainId;+ use parking_lot::MappedMutexGuard;+ use rangeset::RangeSet;+ use std::ops::Range;+ use std::sync::atomic::AtomicUsize;+ use std::sync::Arc;+ use termwiz::surface::{Line, SequenceNo};+ use url::Url;+ use wezterm_term::color::ColorPalette;+ use wezterm_term::{KeyCode, KeyModifiers, MouseEvent, StableRowIndex, TerminalSize};++ static NEXT_PANE_ID: AtomicUsize = AtomicUsize::new(9000);++ lazy_static::lazy_static! {+ static ref PUBLISH_LOG: parking_lot::Mutex<Vec<PaneId>> =+ parking_lot::Mutex::new(Vec::new());+ }++ /// Test sink for `publish_change`: no scheduler exists under+ /// `cargo test`, so publications are recorded instead of notified.+ pub(super) fn record_publish(pane_id: PaneId) {+ PUBLISH_LOG.lock().push(pane_id);+ }++ /// Tests run in parallel and share the log; filter by the caller's+ /// unique pane id.+ fn publishes_for(pane_id: PaneId) -> usize {+ PUBLISH_LOG.lock().iter().filter(|id| **id == pane_id).count()+ }++ /// One dirty-pane step exactly as `drain_and_evaluate` performs it.+ fn drain_step(pane: &dyn Pane) {+ if evaluate_pane(pane) {+ publish_change(pane.pane_id());+ }+ }++ /// Sequence tests run in microseconds, so the `SCREEN_READ_FLOOR`+ /// reuse clause would serve every frame from cache and mask the very+ /// transitions under test. Age the cache as a real 150ms round gap+ /// would, then step.+ fn drain_step_next_round(pane: &dyn Pane) {+ if let Some(cache) = REGISTRY+ .write()+ .get_mut(&pane.pane_id())+ .and_then(|record| record.screen_cache.as_mut())+ {+ if let Some(aged) = cache.at.checked_sub(SCREEN_READ_FLOOR * 2) {+ cache.at = aged;+ }+ }+ drain_step(pane);+ }++ struct FakeAgentPane {+ id: PaneId,+ screen: parking_lot::Mutex<String>,+ title: parking_lot::Mutex<String>,+ osc_evidence: parking_lot::Mutex<wezterm_term::AgentOscEvidence>,+ user_vars: parking_lot::Mutex<HashMap<String, String>>,+ seqno: AtomicUsize,+ process: parking_lot::Mutex<Option<String>>,+ probes: AtomicUsize,+ remote_mirror: bool,+ dead: AtomicBool,+ /// When set, the next `get_lines` returns the current screen and+ /// then applies this content and bumps the seqno -- emulating+ /// output that lands while an evaluation is still running.+ swap_after_read: parking_lot::Mutex<Option<String>>,+ }++ impl FakeAgentPane {+ fn new(process: Option<&str>) -> Arc<Self> {+ Arc::new(Self {+ id: NEXT_PANE_ID.fetch_add(1, Ordering::SeqCst),+ screen: parking_lot::Mutex::new(String::new()),+ title: parking_lot::Mutex::new(String::new()),+ osc_evidence: parking_lot::Mutex::new(Default::default()),+ user_vars: parking_lot::Mutex::new(HashMap::new()),+ seqno: AtomicUsize::new(1),+ process: parking_lot::Mutex::new(process.map(|p| p.to_string())),+ probes: AtomicUsize::new(0),+ remote_mirror: false,+ dead: AtomicBool::new(false),+ swap_after_read: parking_lot::Mutex::new(None),+ })+ }++ fn set_screen(&self, text: &str) {+ *self.screen.lock() = text.to_string();+ self.seqno.fetch_add(1, Ordering::SeqCst);+ }++ fn set_contract(&self, value: &str) {+ self.user_vars+ .lock()+ .insert(contract::USER_VAR_NAME.to_string(), value.to_string());+ self.seqno.fetch_add(1, Ordering::SeqCst);+ }++ fn clear_contract(&self) {+ self.user_vars.lock().remove(contract::USER_VAR_NAME);+ self.seqno.fetch_add(1, Ordering::SeqCst);+ }++ fn set_osc_title(&self, title: &str) {+ self.osc_evidence.lock().title = Some(title.to_string());+ self.seqno.fetch_add(1, Ordering::SeqCst);+ }++ /// Arrange for `text` to land on the screen immediately after the+ /// next `get_lines`, as terminal output arriving during an+ /// evaluation does.+ fn set_screen_after_next_read(&self, text: &str) {+ *self.swap_after_read.lock() = Some(text.to_string());+ }++ /// Change the foreground process and drop the identity cache's+ /// memory of this pane, as the 5s TTL would in real time.+ fn set_process(&self, process: Option<&str>) {+ *self.process.lock() = process.map(|p| p.to_string());+ identify::forget_pane(self.id);+ self.seqno.fetch_add(1, Ordering::SeqCst);+ }+ }++ impl Pane for FakeAgentPane {+ fn pane_id(&self) -> PaneId {+ self.id+ }+ fn get_cursor_position(&self) -> StableCursorPosition {+ StableCursorPosition::default()+ }+ fn get_current_seqno(&self) -> SequenceNo {+ self.seqno.load(Ordering::SeqCst)+ }+ fn get_changed_since(+ &self,+ _lines: Range<StableRowIndex>,+ _: SequenceNo,+ ) -> RangeSet<StableRowIndex> {+ unimplemented!();+ }+ fn with_lines_mut(+ &self,+ _stable_range: Range<StableRowIndex>,+ _with_lines: &mut dyn WithPaneLines,+ ) {+ unimplemented!();+ }+ fn for_each_logical_line_in_stable_range_mut(+ &self,+ _lines: Range<StableRowIndex>,+ _for_line: &mut dyn ForEachPaneLogicalLine,+ ) {+ unimplemented!();+ }+ fn get_lines(&self, lines: Range<StableRowIndex>) -> (StableRowIndex, Vec<Line>) {+ let all: Vec<Line> = self+ .screen+ .lock()+ .lines()+ .map(|l| Line::from_text(l, &Default::default(), 1, None))+ .collect();+ let start = lines.start.max(0) as usize;+ let out: Vec<Line> = all+ .into_iter()+ .skip(start)+ .take((lines.end - lines.start).max(0) as usize)+ .collect();+ if let Some(next) = self.swap_after_read.lock().take() {+ *self.screen.lock() = next;+ self.seqno.fetch_add(1, Ordering::SeqCst);+ }+ (lines.start, out)+ }+ fn get_logical_lines(&self, _lines: Range<StableRowIndex>) -> Vec<LogicalLine> {+ unimplemented!();+ }+ fn get_dimensions(&self) -> RenderableDimensions {+ let rows = self.screen.lock().lines().count().max(1);+ RenderableDimensions {+ cols: 120,+ viewport_rows: rows,+ scrollback_rows: rows,+ physical_top: 0,+ scrollback_top: 0,+ ..Default::default()+ }+ }+ fn get_title(&self) -> String {+ self.title.lock().clone()+ }+ fn agent_osc_evidence(&self) -> wezterm_term::AgentOscEvidence {+ self.osc_evidence.lock().clone()+ }+ fn clear_agent_osc_evidence(&self) {+ *self.osc_evidence.lock() = Default::default();+ }+ fn copy_user_vars(&self) -> HashMap<String, String> {+ self.user_vars.lock().clone()+ }+ fn get_foreground_process_name(&self, _policy: CachePolicy) -> Option<String> {+ self.probes.fetch_add(1, Ordering::SeqCst);+ self.process.lock().clone()+ }+ fn send_paste(&self, _text: &str) -> anyhow::Result<()> {+ unimplemented!();+ }+ fn reader(&self) -> anyhow::Result<Option<Box<dyn std::io::Read + Send>>> {+ unimplemented!();+ }+ fn writer(&self) -> MappedMutexGuard<'_, dyn std::io::Write> {+ unimplemented!();+ }+ fn resize(&self, _size: TerminalSize) -> anyhow::Result<()> {+ unimplemented!();+ }+ fn key_down(&self, _key: KeyCode, _mods: KeyModifiers) -> anyhow::Result<()> {+ unimplemented!();+ }+ fn key_up(&self, _: KeyCode, _: KeyModifiers) -> anyhow::Result<()> {+ unimplemented!();+ }+ fn mouse_event(&self, _event: MouseEvent) -> anyhow::Result<()> {+ unimplemented!();+ }+ fn is_dead(&self) -> bool {+ self.dead.load(Ordering::SeqCst)+ }+ fn palette(&self) -> ColorPalette {+ unimplemented!();+ }+ fn domain_id(&self) -> DomainId {+ 0+ }+ fn is_remote_mirror(&self) -> bool {+ self.remote_mirror+ }+ fn is_mouse_grabbed(&self) -> bool {+ false+ }+ fn is_alt_screen_active(&self) -> bool {+ false+ }+ fn get_current_working_dir(&self, _policy: CachePolicy) -> Option<Url> {+ None+ }+ }++ fn now_unix() -> u64 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_secs()+ }++ #[test]+ fn contract_only_pane_classifies_from_user_var() {+ let pane = FakeAgentPane::new(None);+ pane.set_contract(&format!(+ "v1;agent=soul;state=working;session=s-1;ts={}",+ now_unix()+ ));+ assert!(evaluate_pane(pane.as_ref() as &dyn Pane));+ let status = status_for_pane(pane.pane_id()).expect("classified");+ assert_eq!(status.agent_id, "soul");+ assert_eq!(status.state, AgentState::Working);+ assert_eq!(status.evidence, AgentEvidence::Contract);+ assert_eq!(status.session_id.as_deref(), Some("s-1"));+ evict_pane(pane.pane_id());+ }++ #[test]+ fn screen_rules_classify_a_process_identified_pane() {+ let pane = FakeAgentPane::new(Some("/usr/local/bin/claude"));+ pane.set_screen("some output\n⏵⏵ Cooking… (esc to interrupt · 12s)\n");+ assert!(evaluate_pane(pane.as_ref() as &dyn Pane));+ let status = status_for_pane(pane.pane_id()).expect("classified");+ assert_eq!(status.agent_id, "claude");+ assert_eq!(status.state, AgentState::Working);+ assert_eq!(status.evidence, AgentEvidence::Screen);+ evict_pane(pane.pane_id());+ }++ /// codex draws its trust prompt near the top of the screen and leaves+ /// the rest blank; on a 40-row terminal the prompt must still reach+ /// the `top_non_empty_lines` rules rather than falling outside the+ /// slice of the screen the engine is given.+ #[test]+ fn tall_screen_top_prompt_reaches_top_region_rules() {+ let pane = FakeAgentPane::new(Some("/usr/local/bin/codex"));+ let mut screen = String::from(+ "> You are in /Users/someone/project\n\+ \n\+ Do you trust the contents of this directory?\n\+ \n\+ > 1. Yes, continue\n\+ 2. No, quit\n",+ );+ screen.push_str(&"\n".repeat(34));+ pane.set_screen(&screen);+ drain_step(pane.as_ref() as &dyn Pane);+ let status = status_for_pane(pane.pane_id()).expect("classified");+ assert_eq!(+ status.state,+ AgentState::Blocked,+ "a trust prompt at the top of a tall screen must classify as blocked"+ );+ evict_pane(pane.pane_id());+ }++ /// Output that lands between the screen read and the verdict being+ /// cached must not pin the stale verdict to the post-write seqno: a+ /// pane that then blocks waiting for input emits nothing further, so+ /// the seqno never moves again and the reuse clause would serve the+ /// stale verdict forever.+ #[test]+ fn output_landing_during_evaluation_does_not_pin_stale_verdict() {+ let blocked_screen = "Do you want to proceed?\n> 1. Yes\n2. No, and esc to cancel\n";+ // Sanity: the prompt text below classifies as blocked when read+ // normally, so a later failure means staleness, not a bad fixture.+ let probe = FakeAgentPane::new(Some("/usr/local/bin/claude"));+ probe.set_screen(blocked_screen);+ drain_step(probe.as_ref() as &dyn Pane);+ assert_eq!(+ status_for_pane(probe.pane_id()).expect("probe classified").state,+ AgentState::Blocked+ );+ evict_pane(probe.pane_id());++ let pane = FakeAgentPane::new(Some("/usr/local/bin/claude"));+ pane.set_screen("some output\n⏵⏵ Cooking… (esc to interrupt · 12s)\n");+ // The prompt lands while the engine is still evaluating the old+ // screen: the read returns the working screen, then the write+ // applies and the seqno advances before the verdict is cached.+ pane.set_screen_after_next_read(blocked_screen);+ drain_step(pane.as_ref() as &dyn Pane);+ // This round legitimately reports the pre-write screen.+ assert_eq!(+ status_for_pane(pane.pane_id()).expect("classified").state,+ AgentState::Working+ );+ // The pane now waits for input and emits nothing further. Later+ // rounds must notice the prompt instead of serving the stale+ // verdict; allow a few rounds for any guarded transition.+ let mut state = AgentState::Working;+ for _ in 0..4 {+ drain_step_next_round(pane.as_ref() as &dyn Pane);+ state = status_for_pane(pane.pane_id()).expect("classified").state;+ if state == AgentState::Blocked {+ break;+ }+ }+ assert_eq!(+ state,+ AgentState::Blocked,+ "the stale pre-write verdict must not survive on an unmoving seqno"+ );+ evict_pane(pane.pane_id());+ }++ #[test]+ fn screen_verdict_overrides_contract_working() {+ let pane = FakeAgentPane::new(None);+ pane.set_contract(&format!(+ "v1;agent=claude;state=working;ts={}",+ now_unix()+ ));+ // The Esc-interrupt / permission-cancel shape: contract says+ // working, the screen shows the idle prompt box.+ pane.set_screen(+ "previous output\n──────────────────────────────\n❯\n──────────────────────────────\n ? for shortcuts\n",+ );+ evaluate_pane(pane.as_ref() as &dyn Pane);+ let status = status_for_pane(pane.pane_id()).expect("classified");+ assert_eq!(status.state, AgentState::Idle);+ assert_eq!(status.evidence, AgentEvidence::Screen);+ evict_pane(pane.pane_id());+ }++ #[test]+ fn unidentified_pane_is_never_classified() {+ let pane = FakeAgentPane::new(Some("/bin/zsh"));+ pane.set_screen("~/src\n❯ \n");+ assert!(!evaluate_pane(pane.as_ref() as &dyn Pane));+ assert!(status_for_pane(pane.pane_id()).is_none());+ }++ #[test]+ fn evict_pane_clears_the_registry() {+ let pane = FakeAgentPane::new(None);+ pane.set_contract(&format!("v1;agent=soul;state=idle;ts={}", now_unix()));+ evaluate_pane(pane.as_ref() as &dyn Pane);+ assert!(status_for_pane(pane.pane_id()).is_some());+ assert!(evict_pane(pane.pane_id()), "a published record was dropped");+ assert!(status_for_pane(pane.pane_id()).is_none());+ }++ /// The PaneRemoved subscriber must evict silently: the notification+ /// already tells clients, and publishing from inside Mux::notify+ /// deadlocks the subscriber lock.+ #[test]+ fn pane_removed_evicts_without_publishing() {+ let pane = FakeAgentPane::new(None);+ pane.set_contract(&format!("v1;agent=soul;state=working;ts={}", now_unix()));+ drain_step(pane.as_ref() as &dyn Pane);+ assert_eq!(publishes_for(pane.pane_id()), 1);+ // The subscriber body: evict and deliberately drop the result.+ evict_pane(pane.pane_id());+ assert_eq!(publishes_for(pane.pane_id()), 1, "eviction must not publish");+ assert!(status_for_pane(pane.pane_id()).is_none());+ }++ const CODEX_QUESTION: &str = "\u{203a} fix the bug\n\n Which approach?\n \u{276f} 1. A\n 2. B\n\n press enter to confirm or esc to cancel\n";+ const CLAUDE_QUESTION: &str = "\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\n Do you want to proceed?\n \u{276f} 1. Yes\n 2. No\n esc to cancel \u{b7} enter to confirm\n";+ const CLAUDE_PROMPT_BOX: &str = "previous output\n\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\n\u{276f}\n\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\n ? for shortcuts\n";+ const CLAUDE_WORKING: &str = "some output\n\u{23f5}\u{23f5} Cooking\u{2026} (esc to interrupt \u{b7} 12s)\n";++ /// The user's original bug: switching an option in codex's question+ /// form redraws the widget, one evaluation lands on the half-drawn+ /// frame, and the published state used to flap Blocked→Idle→Blocked —+ /// replaying the needs-input sound each time.+ #[test]+ fn codex_option_switch_stays_blocked() {+ let pane = FakeAgentPane::new(Some("/opt/homebrew/bin/codex"));+ pane.set_screen(CODEX_QUESTION);+ drain_step(pane.as_ref() as &dyn Pane);+ assert_eq!(publishes_for(pane.pane_id()), 1);+ assert_eq!(+ status_for_pane(pane.pane_id()).map(|s| s.state),+ Some(AgentState::Blocked)+ );+ // Mid-redraw frame: the widget is briefly absent.+ pane.set_screen("\u{203a} fix the bug\n");+ drain_step_next_round(pane.as_ref() as &dyn Pane);+ assert_eq!(publishes_for(pane.pane_id()), 1, "transient frame is held");+ assert_eq!(+ status_for_pane(pane.pane_id()).map(|s| s.state),+ Some(AgentState::Blocked)+ );+ // Redraw complete: same question, still one waiting episode.+ pane.set_screen(CODEX_QUESTION);+ drain_step_next_round(pane.as_ref() as &dyn Pane);+ assert_eq!(publishes_for(pane.pane_id()), 1, "no republish, no re-ring");+ assert_eq!(+ status_for_pane(pane.pane_id()).map(|s| s.state),+ Some(AgentState::Blocked)+ );+ evict_pane(pane.pane_id());+ }++ /// Answering a claude permission form passes through a frame that+ /// reads as idle before the spinner appears; that frame must never be+ /// published (it used to clear the GUI's attention latch and announce+ /// premature completion).+ #[test]+ fn claude_answer_completion_never_publishes_idle() {+ let pane = FakeAgentPane::new(Some("/usr/local/bin/claude"));+ pane.set_screen(CLAUDE_QUESTION);+ drain_step(pane.as_ref() as &dyn Pane);+ assert_eq!(publishes_for(pane.pane_id()), 1);+ assert_eq!(+ status_for_pane(pane.pane_id()).map(|s| s.state),+ Some(AgentState::Blocked)+ );+ pane.set_screen(CLAUDE_PROMPT_BOX);+ drain_step_next_round(pane.as_ref() as &dyn Pane);+ assert_eq!(publishes_for(pane.pane_id()), 1, "idle frame is held");+ for _ in 0..4 {+ pane.set_screen(CLAUDE_WORKING);+ drain_step_next_round(pane.as_ref() as &dyn Pane);+ assert_ne!(+ status_for_pane(pane.pane_id()).map(|s| s.state),+ Some(AgentState::Idle),+ "idle must never surface"+ );+ }+ assert_eq!(+ status_for_pane(pane.pane_id()).map(|s| s.state),+ Some(AgentState::Working)+ );+ assert_eq!(publishes_for(pane.pane_id()), 2, "exactly blocked then working");+ evict_pane(pane.pane_id());+ }++ /// The claude-relic case behind the `cat` misreport: once the agent+ /// process is gone and no contract vouches for the pane, it must stop+ /// being classified entirely.+ #[test]+ fn process_gone_without_contract_is_evicted() {+ let pane = FakeAgentPane::new(Some("/usr/local/bin/claude"));+ pane.set_screen("some output\n\u{23f5}\u{23f5} Cooking\u{2026} (esc to interrupt \u{b7} 12s)\n");+ drain_step(pane.as_ref() as &dyn Pane);+ assert_eq!(publishes_for(pane.pane_id()), 1);+ // claude exits; the shell takes the foreground back and prints+ // text that would match claude's blocked rules.+ pane.set_process(Some("/bin/zsh"));+ pane.set_screen("do you want to proceed? yes\nwaiting for permission\n");+ drain_step(pane.as_ref() as &dyn Pane);+ assert_eq!(publishes_for(pane.pane_id()), 2, "eviction is published");+ assert!(status_for_pane(pane.pane_id()).is_none());+ }++ /// A live process is ground truth: a relic contract from a previous+ /// occupant neither renames the agent nor decorates it with sessions.+ #[test]+ fn process_identity_overrides_contract_agent() {+ let pane = FakeAgentPane::new(Some("/opt/homebrew/bin/codex"));+ pane.set_contract(&format!(+ "v1;agent=soul;state=working;session=s-9;ts={}",+ now_unix()+ ));+ drain_step(pane.as_ref() as &dyn Pane);+ let status = status_for_pane(pane.pane_id()).expect("classified");+ assert_eq!(status.agent_id, "codex");+ assert_eq!(status.session_id, None);+ evict_pane(pane.pane_id());+ }++ /// An `ended=1` farewell is ignored while the process is still the+ /// pane's foreground: it was premature, and hiding a live agent from+ /// the panel would be wrong.+ #[test]+ fn ended_contract_with_live_process_keeps_screen_rules() {+ let pane = FakeAgentPane::new(Some("/usr/local/bin/claude"));+ pane.set_contract(&format!("v1;agent=claude;state=idle;ts={};ended=1", now_unix()));+ pane.set_screen("some output\n\u{23f5}\u{23f5} Cooking\u{2026} (esc to interrupt \u{b7} 12s)\n");+ drain_step(pane.as_ref() as &dyn Pane);+ let status = status_for_pane(pane.pane_id()).expect("classified");+ assert_eq!(status.state, AgentState::Working);+ assert!(!status.ended);+ evict_pane(pane.pane_id());+ }++ /// The soul case: a native emitter may sit silent long past contract+ /// freshness. Its identity survives while the pane's foreground+ /// leader is unchanged, and dies with it.+ #[test]+ fn contract_survives_while_leader_is_unchanged() {+ let pane = FakeAgentPane::new(Some("/usr/local/bin/soul"));+ pane.set_contract(&format!("v1;agent=soul;state=working;ts={}", now_unix()));+ drain_step(pane.as_ref() as &dyn Pane);+ assert_eq!(+ status_for_pane(pane.pane_id()).map(|s| s.agent_id),+ Some("soul".to_string())+ );+ // Hours pass: the contract re-states something ancient, but the+ // same soul binary still owns the pty.+ pane.set_contract(&format!(+ "v1;agent=soul;state=working;ts={}",+ now_unix() - 8 * 60 * 60+ ));+ drain_step(pane.as_ref() as &dyn Pane);+ assert_eq!(+ status_for_pane(pane.pane_id()).map(|s| s.agent_id),+ Some("soul".to_string()),+ "unchanged leader keeps the stale contract's identity alive"+ );+ // soul exits: the shell is foreground again, the stale contract+ // is now a relic.+ pane.set_process(Some("/bin/zsh"));+ drain_step(pane.as_ref() as &dyn Pane);+ assert!(status_for_pane(pane.pane_id()).is_none());+ }++ /// A contract-backed agent that dies without `ended=1` must not pin+ /// its identity onto the shell: even a *fresh* contract (idle ones+ /// never expire) dies with its recorded foreground leader.+ #[test]+ fn fresh_idle_contract_dies_with_its_leader() {+ let pane = FakeAgentPane::new(Some("/usr/local/bin/soul"));+ pane.set_contract(&format!("v1;agent=soul;state=idle;ts={}", now_unix()));+ drain_step(pane.as_ref() as &dyn Pane);+ assert!(status_for_pane(pane.pane_id()).is_some());+ // soul crashes; the shell takes the foreground back.+ pane.set_process(Some("/bin/zsh"));+ drain_step(pane.as_ref() as &dyn Pane);+ assert!(+ status_for_pane(pane.pane_id()).is_none(),+ "a dead emitter's contract must not survive on freshness alone"+ );+ }++ /// A transient probe failure (leader reads as None) must not evict:+ /// only a definite leader change is proof the emitter is gone.+ #[test]+ fn probe_failure_does_not_evict_a_contract_identity() {+ let pane = FakeAgentPane::new(Some("/usr/local/bin/soul"));+ pane.set_contract(&format!("v1;agent=soul;state=working;ts={}", now_unix()));+ drain_step(pane.as_ref() as &dyn Pane);+ assert!(status_for_pane(pane.pane_id()).is_some());+ pane.set_process(None);+ drain_step(pane.as_ref() as &dyn Pane);+ assert!(+ status_for_pane(pane.pane_id()).is_some(),+ "an unobservable leader is unknown, not dead"+ );+ }++ /// Reloading rules must drop cached screen verdicts: an unchanged+ /// screen (same seqno) would otherwise keep serving conclusions+ /// computed under the old rules indefinitely.+ #[test]+ fn reload_rules_clears_cached_screen_verdicts() {+ let pane = FakeAgentPane::new(Some("/usr/local/bin/claude"));+ pane.set_screen(CLAUDE_WORKING);+ drain_step(pane.as_ref() as &dyn Pane);+ assert!(REGISTRY+ .read()+ .get(&pane.pane_id())+ .and_then(|r| r.screen_cache.as_ref())+ .is_some());+ reload_rules();+ assert!(+ REGISTRY+ .read()+ .get(&pane.pane_id())+ .and_then(|r| r.screen_cache.as_ref())+ .is_none(),+ "old-rule verdicts must not survive a reload"+ );+ evict_pane(pane.pane_id());+ }++ /// A relic contract from a previous occupant must not tear the record+ /// down every round: that would republish per round and destroy the+ /// hysteresis window, resurrecting the repeated needs-input ring.+ #[test]+ fn relic_contract_does_not_thrash_the_record() {+ let pane = FakeAgentPane::new(Some("/opt/homebrew/bin/codex"));+ pane.set_contract(&format!(+ "v1;agent=soul;state=working;session=s-9;ts={}",+ now_unix() - 60+ ));+ pane.set_screen(CODEX_QUESTION);+ drain_step(pane.as_ref() as &dyn Pane);+ assert_eq!(publishes_for(pane.pane_id()), 1);+ // The mid-redraw frame must still be held: the relic contract's+ // session must not have destroyed the pending window.+ pane.set_screen("\u{203a} fix the bug\n");+ drain_step_next_round(pane.as_ref() as &dyn Pane);+ assert_eq!(publishes_for(pane.pane_id()), 1, "hysteresis survives the relic");+ pane.set_screen(CODEX_QUESTION);+ drain_step_next_round(pane.as_ref() as &dyn Pane);+ assert_eq!(publishes_for(pane.pane_id()), 1, "no per-round republish");+ assert_eq!(+ status_for_pane(pane.pane_id()).map(|s| s.state),+ Some(AgentState::Blocked)+ );+ evict_pane(pane.pane_id());+ }++ /// A pane that never runs an agent keeps its negative identification+ /// cached: repeated evaluations must not re-probe the process table.+ #[test]+ fn non_agent_pane_probes_are_cached() {+ let pane = FakeAgentPane::new(Some("/bin/zsh"));+ for _ in 0..3 {+ drain_step(pane.as_ref() as &dyn Pane);+ }+ assert_eq!(+ pane.probes.load(Ordering::SeqCst),+ 1,+ "negative identification is cached for the TTL"+ );+ }++ /// Working → Idle publishes only after consecutive confirmations.+ #[test]+ fn working_to_idle_confirms_before_publishing() {+ let pane = FakeAgentPane::new(Some("/usr/local/bin/claude"));+ pane.set_screen(CLAUDE_WORKING);+ drain_step(pane.as_ref() as &dyn Pane);+ assert_eq!(publishes_for(pane.pane_id()), 1);+ for expect_published in [1, 1, 1, 2] {+ pane.set_screen(CLAUDE_PROMPT_BOX);+ drain_step_next_round(pane.as_ref() as &dyn Pane);+ assert_eq!(publishes_for(pane.pane_id()), expect_published);+ }+ assert_eq!(+ status_for_pane(pane.pane_id()).map(|s| s.state),+ Some(AgentState::Idle)+ );+ evict_pane(pane.pane_id());+ }++ /// A displayable title exists on every pane, but only real OSC+ /// emissions may drive the manifests' title/progress rules: with zero+ /// evidence and an empty screen, claude must fall through to the+ /// Idle fallback (leaving the contract tier reachable), and codex's+ /// `osc_title_idle` (`\S`) must not fire.+ #[test]+ fn empty_osc_evidence_reaches_the_fallback_tier() {+ for process in ["/usr/local/bin/claude", "/opt/homebrew/bin/codex"] {+ let pane = FakeAgentPane::new(Some(process));+ *pane.title.lock() = "zsh".to_string();+ evaluate_pane(pane.as_ref() as &dyn Pane);+ let status = status_for_pane(pane.pane_id()).expect("classified");+ assert_eq!(status.evidence, AgentEvidence::Fallback, "{process}");+ assert_eq!(status.state, AgentState::Idle, "{process}");+ evict_pane(pane.pane_id());+ }+ }++ /// The same codex pane with a real (spinner-free) OSC title hits the+ /// manifest's `osc_title_idle` rule: evidence flows once it exists.+ #[test]+ fn real_osc_title_feeds_the_screen_rules() {+ let pane = FakeAgentPane::new(Some("/opt/homebrew/bin/codex"));+ pane.set_osc_title("auto_order_sys");+ evaluate_pane(pane.as_ref() as &dyn Pane);+ let status = status_for_pane(pane.pane_id()).expect("classified");+ assert_eq!(status.evidence, AgentEvidence::Screen);+ assert_eq!(status.state, AgentState::Idle);+ evict_pane(pane.pane_id());+ }++ /// A pane whose agent goes away publishes the eviction exactly once+ /// when it happens through the evaluation path.+ #[test]+ fn dropped_agent_publishes_once() {+ let pane = FakeAgentPane::new(None);+ pane.set_contract(&format!("v1;agent=soul;state=working;ts={}", now_unix()));+ drain_step(pane.as_ref() as &dyn Pane);+ assert_eq!(publishes_for(pane.pane_id()), 1);+ pane.clear_contract();+ drain_step(pane.as_ref() as &dyn Pane);+ assert_eq!(publishes_for(pane.pane_id()), 2, "the drop is published");+ drain_step(pane.as_ref() as &dyn Pane);+ assert_eq!(publishes_for(pane.pane_id()), 2, "and only once");+ assert!(status_for_pane(pane.pane_id()).is_none());+ }++ #[test]+ fn republish_only_on_change() {+ let pane = FakeAgentPane::new(None);+ pane.set_contract(&format!("v1;agent=soul;state=working;ts={}", now_unix()));+ assert!(evaluate_pane(pane.as_ref() as &dyn Pane));+ // Same inputs, same status: no republish.+ assert!(!evaluate_pane(pane.as_ref() as &dyn Pane));+ pane.set_contract(&format!("v1;agent=soul;state=blocked;ts={}", now_unix()));+ assert!(evaluate_pane(pane.as_ref() as &dyn Pane));+ assert_eq!(+ status_for_pane(pane.pane_id()).map(|s| s.state),+ Some(AgentState::Blocked)+ );+ evict_pane(pane.pane_id());+ }+}diff --git a/mux/src/lib.rs b/mux/src/lib.rsindex bbd58eac..189a991d 100644--- a/mux/src/lib.rs+++ b/mux/src/lib.rs@@ -37,6 +37,7 @@ use wezterm_term::{use winapi::um::winsock2::{SOL_SOCKET, SO_RCVBUF, SO_SNDBUF};pub mod activity;+pub mod agent_status;pub mod client;pub mod command_spec;pub mod connui;@@ -64,6 +65,9 @@ pub enum MuxNotification {PaneOutput(PaneId),PaneAdded(PaneId),PaneRemoved(PaneId),+ /// The mux that owns this pane re-classified its agent status; read+ /// the fresh value via `Pane::agent_status`.+ AgentStatusChanged(PaneId),WindowCreated(WindowId),WindowRemoved(WindowId),WindowInvalidated(WindowId),@@ -2067,6 +2071,31 @@ impl Mux {}fn notify_immediate(&self, notification: MuxNotification) {+ thread_local! {+ static NOTIFY_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };+ }+ // The subscriber map is held (exclusively) while callbacks run, and+ // the lock is not re-entrant: a subscriber that calls notify()+ // synchronously deadlocks in release builds. Turn that hang into a+ // debug panic with a stack trace; the fix is always to defer the+ // nested notify via spawn_into_main_thread.+ NOTIFY_DEPTH.with(|depth| {+ debug_assert_eq!(+ depth.get(),+ 0,+ "re-entrant Mux::notify: a subscriber called notify() while \+ the subscriber map was locked; defer the nested notify via \+ spawn_into_main_thread (in release this deadlocks)"+ );+ depth.set(depth.get() + 1);+ });+ struct DepthGuard;+ impl Drop for DepthGuard {+ fn drop(&mut self) {+ NOTIFY_DEPTH.with(|depth| depth.set(depth.get().saturating_sub(1)));+ }+ }+ let _guard = DepthGuard;let mut subscribers = self.subscribers.write();subscribers.retain(|_, notify| notify(notification.clone()));}@@ -2190,7 +2219,11 @@ impl Mux {self.palette_advisories.lock().remove_pane(pane_id);crate::pane::set_frontend_cell_metrics(pane_id, None);let mut changed = false;- if let Some(pane) = self.panes.write().remove(&pane_id).clone() {+ // Bind the removal first: in edition 2018 the `if let` scrutinee's+ // temporary (the panes write guard) would otherwise live across the+ // notify below, deadlocking any subscriber that touches the pane map.+ let removed = self.panes.write().remove(&pane_id);+ if let Some(pane) = removed {log::debug!("killing pane {}", pane_id);pane.kill();self.notify(MuxNotification::PaneRemoved(pane_id));@@ -2518,11 +2551,11 @@ impl Mux {pub fn resolve_pane_id(&self, pane_id: PaneId) -> Option<(DomainId, WindowId, TabId)> {let mut ids = None;- for tab in self.tabs.read().values() {+ 'tabs: for tab in self.tabs.read().values() {for pane in tab.iter_all_panes() {if pane.pane_id() == pane_id {ids = Some((tab.tab_id(), pane.domain_id()));- break;+ break 'tabs;}}}@@ -4155,4 +4188,20 @@ mod tests {assert_eq!(context.size, requested_size);assert!(context.term_config.is_none());}++ /// A subscriber that calls notify() synchronously re-enters the+ /// subscriber lock and would deadlock a release build; debug builds+ /// turn it into this assertion.+ #[cfg(debug_assertions)]+ #[test]+ #[should_panic(expected = "re-entrant Mux::notify")]+ fn notify_is_not_reentrant() {+ let mux = Arc::new(Mux::new(None));+ let inner = Arc::clone(&mux);+ mux.subscribe(move |_| {+ inner.notify(MuxNotification::PaneRemoved(999_999));+ true+ });+ mux.notify(MuxNotification::PaneRemoved(999_998));+ }}diff --git a/mux/src/localpane.rs b/mux/src/localpane.rsindex 03b5fe6c..81ff7234 100644--- a/mux/src/localpane.rs+++ b/mux/src/localpane.rs@@ -482,6 +482,14 @@ impl Pane for LocalPane {self.terminal.lock().get_progress()}+ fn agent_osc_evidence(&self) -> wezterm_term::AgentOscEvidence {+ self.terminal.lock().agent_osc_evidence()+ }++ fn clear_agent_osc_evidence(&self) {+ self.terminal.lock().clear_agent_osc_state();+ }+fn palette(&self) -> ColorPalette {self.terminal.lock().palette()}diff --git a/mux/src/pane.rs b/mux/src/pane.rsindex ebb7c7a4..292c094a 100644--- a/mux/src/pane.rs+++ b/mux/src/pane.rs@@ -357,6 +357,27 @@ pub trait Pane: Downcast + Send + Sync {}fn get_current_working_dir(&self, policy: CachePolicy) -> Option<Url>;++ /// The agent (if any) this pane is running, as classified by the mux+ /// that owns it. Locally-owned panes answer from this process's+ /// detector; ClientPane overrides with what the owning server pushed.+ fn agent_status(&self) -> Option<thinkterm_proto::AgentStatus> {+ crate::agent_status::status_for_pane(self.pane_id())+ }++ /// OSC title/progress the application actually emitted, retained for+ /// agent detection. Deliberately not `get_title`/`get_progress`, which+ /// exist for display and substitute defaults (process basename, "4;0")+ /// that would make idle screen rules match unconditionally. The default+ /// is empty: remote mirrors are never detected locally.+ fn agent_osc_evidence(&self) -> wezterm_term::AgentOscEvidence {+ Default::default()+ }++ /// Drop retained agent OSC evidence so a pane's next occupant does not+ /// inherit the previous agent's signals. No-op by default.+ fn clear_agent_osc_evidence(&self) {}+fn get_foreground_process_name(&self, _policy: CachePolicy) -> Option<String> {None}diff --git a/term/src/terminalstate/mod.rs b/term/src/terminalstate/mod.rsindex fdbfef1f..58870094 100644--- a/term/src/terminalstate/mod.rs+++ b/term/src/terminalstate/mod.rs@@ -244,6 +244,18 @@ impl ScreenOrAlt {}}+/// OSC signals retained verbatim for agent detection: `None` until the+/// application actually emits them. See+/// [`TerminalState::agent_osc_evidence`].+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct AgentOscEvidence {+ /// The raw OSC 0/1/2 title payload, or `None` if never set.+ pub title: Option<String>,+ /// The raw OSC 9;4 payload in `4;<state>[;<progress>]` shape, or+ /// `None` if never set.+ pub progress: Option<String>,+}+/// Manages the state for the terminalpub struct TerminalState {config: Arc<dyn TerminalConfiguration>,@@ -337,6 +349,16 @@ pub struct TerminalState {/// The icon title string (OSC 1)icon_title: Option<String>,progress: Progress,+ /// The raw OSC title payload the application most recently emitted,+ /// retained for agent detection. Unlike `title`, this is never+ /// synthesized from a default or a process name: `None` means the+ /// app has not spoken.+ agent_osc_title: Option<String>,+ /// The raw OSC 9;4 progress payload most recently emitted, in the+ /// `4;<state>[;<progress>]` shape agent manifests match, retained+ /// before any display flattening (Paused stays distinct). `None`+ /// means the app has not spoken.+ agent_osc_progress: Option<String>,palette: Option<ColorPalette>,@@ -611,6 +633,8 @@ impl TerminalState {bidi_enabled: None,bidi_hint: None,progress: Progress::default(),+ agent_osc_title: None,+ agent_osc_progress: None,}}@@ -676,6 +700,25 @@ impl TerminalState {self.progress.clone()}+ /// The OSC evidence retained for agent detection: what the app+ /// actually emitted, or empty if it never spoke. Deliberately+ /// separate from `get_title`/`get_progress`, which exist for+ /// display and cannot distinguish "never reported" from defaults.+ pub fn agent_osc_evidence(&self) -> AgentOscEvidence {+ AgentOscEvidence {+ title: self.agent_osc_title.clone(),+ progress: self.agent_osc_progress.clone(),+ }+ }++ /// Drop retained agent OSC evidence, e.g. when the foreground agent+ /// changes so a new occupant does not inherit the old one's signals.+ /// Display state (`title`, `progress`) is untouched.+ pub fn clear_agent_osc_state(&mut self) {+ self.agent_osc_title = None;+ self.agent_osc_progress = None;+ }+/// Returns the current working directory associated with the/// terminal session. The working directory can be changed by/// the applicaiton using the OSC 7 escape sequence.diff --git a/term/src/terminalstate/performer.rs b/term/src/terminalstate/performer.rsindex a7daa8ee..b69cfab4 100644--- a/term/src/terminalstate/performer.rs+++ b/term/src/terminalstate/performer.rs@@ -716,6 +716,8 @@ impl<'a> Performer<'a> {self.suppress_initial_title_change = false;self.accumulating_title.take();self.progress = Progress::default();+ self.agent_osc_title = None;+ self.agent_osc_progress = None;// Before the screen is torn down, while the placement rows// still refer to real lines. The soft reset (DECSTR) already@@ -748,6 +750,11 @@ impl<'a> Performer<'a> {match osc {OperatingSystemCommand::SetIconNameSun(title)| OperatingSystemCommand::SetIconName(title) => {+ // Deliberately not recorded as agent title evidence: OSC 1+ // only names the icon, and shells emit it freely -- letting+ // it overwrite (or, when empty, erase) the window-title+ // evidence would wipe what an agent said via OSC 0/2 while+ // the displayed title is untouched.if title.is_empty() {self.icon_title = None;} else {@@ -759,6 +766,11 @@ impl<'a> Performer<'a> {}}OperatingSystemCommand::SetIconNameAndWindowTitle(title) => {+ self.agent_osc_title = if title.is_empty() {+ None+ } else {+ Some(title.clone())+ };self.icon_title.take();self.title = title.clone();if let Some(handler) = self.alert_handler.as_mut() {@@ -769,6 +781,11 @@ impl<'a> Performer<'a> {OperatingSystemCommand::SetWindowTitleSun(title)| OperatingSystemCommand::SetWindowTitle(title) => {+ self.agent_osc_title = if title.is_empty() {+ None+ } else {+ Some(title.clone())+ };self.title = title.clone();if let Some(handler) = self.alert_handler.as_mut() {handler.alert(Alert::WindowTitleChanged(title));@@ -1085,6 +1102,17 @@ impl<'a> Performer<'a> {}OperatingSystemCommand::ConEmuProgress(prog) => {use wezterm_escape_parser::osc::Progress as TProg;+ // Retained before the display flattening below (which folds+ // Paused into None) and before the no-change early-out: a+ // repeated identical payload is still evidence that the app+ // is speaking.+ self.agent_osc_progress = Some(match &prog {+ TProg::None => "4;0".to_string(),+ TProg::SetPercentage(p) => format!("4;1;{p}"),+ TProg::SetError(p) => format!("4;2;{p}"),+ TProg::SetIndeterminate => "4;3".to_string(),+ TProg::Paused => "4;4".to_string(),+ });let prog = match prog {TProg::None => Progress::None,TProg::SetPercentage(p) => Progress::Percentage(p),diff --git a/term/src/test/mod.rs b/term/src/test/mod.rsindex f0d5abe2..d7d43770 100644--- a/term/src/test/mod.rs+++ b/term/src/test/mod.rs@@ -199,6 +199,62 @@ impl DerefMut for TestTerm {}}+#[test]+fn agent_osc_evidence_tracks_only_real_emissions() {+ let mut term = TestTerm::new(4, 20, 0);++ // A fresh terminal has a displayable title but zero evidence: the+ // distinction is the whole point of the evidence channel.+ let fresh = term.agent_osc_evidence();+ assert_eq!(fresh.title, None);+ assert_eq!(fresh.progress, None);+ assert!(!term.get_title().is_empty());++ term.print("\x1b]0;\u{25d0} fix the tests\x07");+ assert_eq!(+ term.agent_osc_evidence().title.as_deref(),+ Some("\u{25d0} fix the tests")+ );++ // OSC 1 names only the icon and shells emit it freely: it must not+ // create evidence, and an empty one must not erase what an agent+ // said via OSC 0/2.+ term.print("\x1b]1;shell-icon\x07");+ assert_eq!(+ term.agent_osc_evidence().title.as_deref(),+ Some("\u{25d0} fix the tests")+ );+ term.print("\x1b]1;\x07");+ assert_eq!(+ term.agent_osc_evidence().title.as_deref(),+ Some("\u{25d0} fix the tests")+ );++ term.print("\x1b]9;4;3\x07");+ assert_eq!(term.agent_osc_evidence().progress.as_deref(), Some("4;3"));+ // Explicit clear is retained as "4;0" — distinct from never-reported.+ term.print("\x1b]9;4;0\x07");+ assert_eq!(term.agent_osc_evidence().progress.as_deref(), Some("4;0"));+ // A pause is retained pre-flattening even though the display path+ // folds it into Progress::None.+ term.print("\x1b]9;4;4\x07");+ assert_eq!(term.agent_osc_evidence().progress.as_deref(), Some("4;4"));++ // Clearing evidence leaves the display title alone.+ let shown = term.get_title().to_string();+ term.clear_agent_osc_state();+ let cleared = term.agent_osc_evidence();+ assert_eq!(cleared.title, None);+ assert_eq!(cleared.progress, None);+ assert_eq!(term.get_title(), shown);++ // Hard reset drops evidence too.+ term.print("\x1b]2;busy\x07\x1b]9;4;3\x07");+ assert!(term.agent_osc_evidence().title.is_some());+ term.print("\x1bc");+ assert_eq!(term.agent_osc_evidence(), Default::default());+}+#[test]fn application_palette_override_tracks_osc_set_query_and_reset() {let mut term = TestTerm::new(4, 8, 0);diff --git a/thinkterm-proto/src/agent.rs b/thinkterm-proto/src/agent.rsnew file mode 100644index 00000000..fd9c235f--- /dev/null+++ b/thinkterm-proto/src/agent.rs@@ -0,0 +1,49 @@+//! Agent status wire types.+//!+//! A pane running a coding agent (Claude Code, Codex, …) is classified by+//! the mux that *owns* the pane; the result travels to clients over the+//! mux protocol and mirrors onto their ClientPanes.+//!+//! Varbincode is positional: **field and enum-variant order is the wire+//! contract**. Bump the codec version when changing anything here.++use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]+pub enum AgentState {+ Working,+ Blocked,+ Idle,+ Unknown,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]+pub enum AgentEvidence {+ /// The agent's own report via the THINKTERM_AGENT user-var contract.+ Contract,+ /// A screen-manifest rule matched the pane's live screen or OSC state.+ Screen,+ /// No rule matched and no fresh contract: the known-agent Idle+ /// fallback (never produces Blocked).+ Fallback,+}++#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]+pub struct AgentStatus {+ /// Manifest/contract agent id, e.g. "claude".+ pub agent_id: String,+ pub state: AgentState,+ pub evidence: AgentEvidence,+ /// The agent's native session id, when its integration reports one.+ pub session_id: Option<String>,+ /// Unix seconds when `state` last changed, on the detecting host's+ /// clock. Cross-host skew makes derived ages approximate; render a+ /// negative age as zero.+ pub since_unix: u64,+ /// The session reported its own end. Reserved on the wire for native+ /// emitters: the current detection pipeline evicts ended sessions+ /// instead of publishing them, so consumers treat a `true` here+ /// defensively (hide from lists, fall back to native signals) but+ /// should not rely on ever observing it.+ pub ended: bool,+}diff --git a/thinkterm-proto/src/lib.rs b/thinkterm-proto/src/lib.rsindex c13d1363..b46dad96 100644--- a/thinkterm-proto/src/lib.rs+++ b/thinkterm-proto/src/lib.rs@@ -12,6 +12,7 @@//! 32-bit peer (wasm) caps out at `u32::MAX` of them per session — accepted//! deliberately; they are per-session counters and never get near that.+pub mod agent;pub mod client;pub mod command;pub mod keyassignment;@@ -20,6 +21,7 @@ pub mod pane;pub mod renderable;pub mod split;+pub use agent::{AgentEvidence, AgentState, AgentStatus};pub use client::{ClientId, ClientInfo};pub use command::{CommandSpec, EnvVar};pub use keyassignment::{PaneDirection, ScrollbackEraseMode, SpawnTabDomain};