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
feat(agents): show the status programs report about themselves
RoversXa6eeda76602a
diff --git a/codec/src/lib.rs b/codec/src/lib.rsindex f489cf61..0c2da875 100644--- a/codec/src/lib.rs+++ b/codec/src/lib.rs@@ -819,7 +819,9 @@ macro_rules! pdu {/// 76: Source-independent session import requests with explicit import modes./// 77: Discover and preview import sessions on their owning mux server./// 78: Durable import request identities and reconnectable result queries.-pub const CODEC_VERSION: usize = 78;+/// 79: Agent statuses carry programs' own OSC 7501 reports and an error state;+/// MarkProgramStatusSeen.+pub const CODEC_VERSION: usize = 79;// Defines the Pdu enum.// Each struct has an explicit identifying number.@@ -928,6 +930,7 @@ pdu! {PreviewImportSessionResponse: 108,GetImportSessionStatus: 109,GetImportSessionStatusResponse: 110,+ MarkProgramStatusSeen: 111,}impl Pdu {@@ -1864,6 +1867,15 @@ pub struct PluginFrame {pub data: Vec<u8>,}+/// Someone looked at a pane: retire the finished or failed results its+/// programs reported with OSC 7501. Only the mux that owns the pane keeps+/// them, and a client's focus does not always reach it -- a client does not+/// refocus the pane it already focused when the user comes back to it.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug)]+pub struct MarkProgramStatusSeen {+ pub pane_id: PaneId,+}+#[derive(Deserialize, Serialize, PartialEq, Debug)]pub struct SetPaneZoomed {pub containing_tab_id: TabId,@@ -3038,13 +3050,17 @@ mod test {}#[test]- fn agent_status_protocol_round_trip_at_version_61() {- // The agent-status protocol arrived at 61 and is unchanged since.- // The exact assertion is the tripwire: whoever bumps the codec must- // come here, confirm the round-trips still cover the new version,- // and advance it deliberately.- assert_eq!(CODEC_VERSION, 78);- use thinkterm_proto::{AgentEvidence, AgentState, AgentStatus};+ fn agent_status_protocol_round_trip_at_version_79() {+ // The agent-status protocol arrived at 61; 79 added programs' own+ // OSC 7501 reports and the error state. The exact assertion is the+ // tripwire: whoever bumps the codec must come here, confirm the+ // round-trips still cover the new version, and advance it+ // deliberately.+ assert_eq!(CODEC_VERSION, 79);+ use thinkterm_proto::{+ AgentEvidence, AgentState, AgentStatus, ProgramBlockedKind, ProgramReport,+ ProgramReportChild, ProgramReportState,+ };fn round_trip(pdu: Pdu) {let mut encoded = Vec::new();@@ -3061,16 +3077,42 @@ mod test {session_id: Some("abc-123".to_string()),since_unix: 1_756_000_000,ended: false,+ report: None,};round_trip(Pdu::AgentStatusChanged(AgentStatusChanged {pane_id: 7,status: Some(status.clone()),}));+ round_trip(Pdu::AgentStatusChanged(AgentStatusChanged {+ pane_id: 7,+ status: Some(AgentStatus {+ state: AgentState::Error,+ evidence: AgentEvidence::Report,+ report: Some(ProgramReport {+ state: ProgramReportState::Blocked,+ kind: Some(ProgramBlockedKind::Permission),+ progress: Some(40),+ app: Some("claude-code".to_string()),+ title: None,+ msg: Some("Bash: npm test".to_string()),+ children: vec![ProgramReportChild {+ id: "plan".to_string(),+ state: ProgramReportState::Done,+ kind: None,+ progress: None,+ title: Some("Plan".to_string()),+ msg: None,+ }],+ }),+ ..status.clone()+ }),+ }));round_trip(Pdu::AgentStatusChanged(AgentStatusChanged {pane_id: 7,status: None,}));round_trip(Pdu::GetAgentStatuses(GetAgentStatuses {}));+ round_trip(Pdu::MarkProgramStatusSeen(MarkProgramStatusSeen { pane_id: 7 }));round_trip(Pdu::GetAgentStatusesResponse(GetAgentStatusesResponse {statuses: vec![AgentStatusEntry {pane_id: 7,@@ -3084,7 +3126,7 @@ mod test {#[test]fn foreground_program_protocol_round_trip_at_version_74() {// Same tripwire as the agent-status test above.- assert_eq!(CODEC_VERSION, 78);+ assert_eq!(CODEC_VERSION, 79);use thinkterm_proto::ForegroundProgram;fn round_trip(pdu: &Pdu) -> Pdu {@@ -3186,7 +3228,7 @@ mod test {fn frame_control_extension_round_trips_without_changing_legacy_version() {// The extension is asked for, so it needed no bump of its own; 74// is the foreground program's, which a server sends unasked.- assert_eq!(CODEC_VERSION, 78);+ assert_eq!(CODEC_VERSION, 79);for pdu in [Pdu::GetKittyImage(GetKittyImage { pane_id: 3, image_id: 7, data_hash: [9; 32], have_frames: 2, image_epoch: Some(4) }),Pdu::GetKittyFrameSelections(GetKittyFrameSelections { pane_id: 3, subscribe: true }),@@ -3644,6 +3686,7 @@ mod agent_budget_tests {evidence: AgentEvidence::Contract,since_unix: 42,ended: false,+ report: None,}}fn assert_stream_survives(message: Pdu, expected: Pdu) {diff --git a/mux/src/agent_status/hysteresis.rs b/mux/src/agent_status/hysteresis.rsindex d5eca568..5e6fd22e 100644--- a/mux/src/agent_status/hysteresis.rs+++ b/mux/src/agent_status/hysteresis.rs@@ -65,7 +65,9 @@ impl Pending {evidence: AgentEvidence,now: Instant,) -> bool {- if raw == published || evidence == AgentEvidence::Contract {+ // A program's own word is not a guess about a half-drawn screen:+ // neither the contract nor an OSC 7501 report is held back.+ if raw == published || matches!(evidence, AgentEvidence::Contract | AgentEvidence::Report) {self.clear();return false;}diff --git a/mux/src/agent_status/mod.rs b/mux/src/agent_status/mod.rsindex 5f97ad61..9edab76d 100644--- a/mux/src/agent_status/mod.rs+++ b/mux/src/agent_status/mod.rs@@ -33,7 +33,11 @@ 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};+use thinkterm_proto::{+ AgentEvidence, AgentState, AgentStatus, ProgramBlockedKind, ProgramReport, ProgramReportChild,+ ProgramReportState,+};+use wezterm_term::program_status::{ProgramState, ProgramStatusRecord};/// Minimum interval between screen reads for one pane even while output/// is flowing. Must be comfortably larger than EVAL_INTERVAL to do@@ -94,6 +98,10 @@ struct AgentPaneRecord {/// alive when the contract itself has gone stale.contract_raw: Option<String>,contract_leader: Option<String>,+ /// Source of the last accepted report, so an unnamed successor cannot+ /// inherit this pane's previous program name.+ report_process_group: Option<u32>,+ report_orphaned: bool,}lazy_static::lazy_static! {@@ -104,6 +112,11 @@ lazy_static::lazy_static! {static ref LAST_EVAL: Mutex<HashMap<PaneId, Instant>> = Mutex::new(HashMap::new());static ref PROCESS_PREFERENCE: RwLock<Option<Box<dyn Fn() -> bool + Send + Sync>>> =RwLock::new(None);+ /// Who filed each pane's OSC 7501 root. Kept apart from the registry:+ /// a report must stay pinned to its program across the records the+ /// registry drops and makes. A pane's entry goes when its root does, or+ /// with the pane.+ static ref REPORT_FILERS: Mutex<HashMap<PaneId, ReportFiler>> = Mutex::new(HashMap::new());}static TICK_SCHEDULED: AtomicBool = AtomicBool::new(false);static INSTALLED: AtomicBool = AtomicBool::new(false);@@ -113,6 +126,43 @@ static INSTALLED: AtomicBool = AtomicBool::new(false);/// safety tick, config reload, the settings toggle).static ENABLED: AtomicBool = AtomicBool::new(false);+/// What a painter needs of an agent's status every frame, without its+/// report's text.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct AgentStatusSummary {+ pub state: AgentState,+ pub evidence: AgentEvidence,+ pub ended: bool,+ /// The program's own word on its state, when it gave one.+ pub report_state: Option<ProgramReportState>,+ /// A finished or failed result nobody has looked at yet.+ pub unseen_result: bool,+}++impl AgentStatusSummary {+ pub fn of(status: &AgentStatus) -> Self {+ Self {+ state: status.state,+ evidence: status.evidence,+ ended: status.ended,+ report_state: status.report.as_ref().map(|report| report.state),+ unseen_result: status+ .report+ .as_ref()+ .is_some_and(ProgramReport::has_unseen_result),+ }+ }+}++/// [`status_for_pane`] summarised, copying no text.+pub fn summary_for_pane(pane_id: PaneId) -> Option<AgentStatusSummary> {+ REGISTRY+ .read()+ .get(&pane_id)+ .and_then(|record| record.published.as_ref())+ .map(AgentStatusSummary::of)+}+/// 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> {@@ -275,6 +325,12 @@ fn mark_dirty(pane_id: PaneId) {.detach();}+/// Re-judge a pane soon: something its status depends on changed without+/// any output, such as focus retiring a finished program's OSC 7501 result.+pub fn nudge(pane_id: PaneId) {+ mark_dirty(pane_id);+}+/// 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@@ -312,6 +368,7 @@ pub fn reload_rules() -> usize {fn evict_pane(pane_id: PaneId) -> bool {identify::forget_pane(pane_id);LAST_EVAL.lock().remove(&pane_id);+ REPORT_FILERS.lock().remove(&pane_id);REGISTRY.write().remove(&pane_id)@@ -363,6 +420,7 @@ fn drain_and_evaluate() {// PaneRemoved is ignored while detection is off, so this sweep is// the only place orphaned timestamps get reclaimed.LAST_EVAL.lock().clear();+ REPORT_FILERS.lock().clear();return;}let dirty: Vec<PaneId> = PENDING.lock().drain().collect();@@ -466,6 +524,64 @@ fn evaluate_pane(pane: &dyn Pane) -> bool {let process_agent = identify::identify_by_process(pane);let process_backed = process_agent.is_some();let leader = identify::leader_path(pane);++ // OSC 7501. A return from another process group to the shell ends that+ // program's reports. The shell can itself be running a builtin or a+ // function, so holding the foreground alone does not mean it is idle.+ let mut program = pane.program_status();+ let foreground = pane.foreground_process_group();+ let unsettled: Vec<_> = program+ .root+ .iter()+ .chain(&program.children)+ .filter(|record| !record.orphaned)+ .collect();+ let returned_to_shell = !unsettled.is_empty()+ && unsettled.iter().all(|record| {+ matches!((record.process_group, foreground), (Some(then), Some(now)) if then != now)+ })+ && pane.shell_is_foreground() == Some(true);+ if returned_to_shell {+ // Only what was taken in before the look: a report the next command+ // files meanwhile is that command's, and alive.+ pane.end_program_status(program.latest_serial);+ program = pane.program_status();+ }+ // A live root speaks with its own sub-tasks only: results an earlier+ // program left behind are not this one's to show.+ let mut children: Vec<ProgramStatusRecord> = match &program.root {+ Some(root) if !root.orphaned => program+ .children+ .iter()+ .filter(|child| !child.orphaned)+ .cloned()+ .collect(),+ _ => program.children.clone(),+ };+ // A root can go while its sub-tasks' results stay -- a prompt drops a+ // working root and keeps a failed child -- and the pane then speaks+ // through them.+ let root = program+ .root+ .clone()+ .or_else(|| root_from_children(&children));+ // Who filed it matters only while the root is live: a result left+ // behind speaks for nobody running, whatever holds the foreground.+ let from_foreground = match root.as_ref() {+ Some(root) if !root.orphaned => report_from_foreground(+ pane_id,+ root,+ foreground,+ pane.root_process_id(),+ ),+ _ => {+ REPORT_FILERS.lock().remove(&pane_id);+ true+ }+ };+ if let Some(root) = root.as_ref().filter(|root| !root.orphaned) {+ retain_report_children(pane_id, root, &mut children, pane.root_process_id());+ }let contract_identity = parsed_contract.as_ref().and_then(|c| {if c.ended || process_agent.is_some() {return None;@@ -510,7 +626,39 @@ fn evaluate_pane(pane: &dyn Pane) -> bool {}Some(c.agent_id.clone())});- let agent_id = process_agent.or(contract_identity);+ let report = root.filter(|root| {+ report_applies(+ root,+ process_agent.as_deref(),+ contract_identity.is_some(),+ from_foreground,+ )+ });+ let report_state = report.as_ref().map(|root| match root.state {+ ProgramState::Working => AgentState::Working,+ ProgramState::Blocked => AgentState::Blocked,+ ProgramState::Error => AgentState::Error,+ ProgramState::Idle | ProgramState::Done | ProgramState::Clear => AgentState::Idle,+ });+ // R4: a program that reports its own state counts whatever it is. A+ // report naming no program keeps an earlier name only when its source+ // is still the same observed process group. An orphan cannot name the+ // next live program, and an unknown source cannot establish continuity.+ let report_identity = report.as_ref().map(|root| match root.app.as_deref() {+ Some(app) => agent_id_for_app(Some(app)),+ None => REGISTRY+ .read()+ .get(&pane_id)+ .filter(|record| {+ record.evidence == AgentEvidence::Report+ && root.process_group.is_some()+ && record.report_process_group == root.process_group+ && (!record.report_orphaned || root.orphaned)+ })+ .map(|record| record.agent_id.clone())+ .unwrap_or_else(|| agent_id_for_app(None)),+ });+ let agent_id = process_agent.or(contract_identity).or(report_identity);let Some(agent_id) = agent_id else {let removed = REGISTRY.write().remove(&pane_id);@@ -606,8 +754,10 @@ fn evaluate_pane(pane: &dyn Pane) -> bool {progress.clear();}- // Phase 2, no lock: the screen read and the manifest scan.+ // Phase 2, no lock: the screen read and the manifest scan -- unless the+ // program has said where it is, which no screen rule can overrule.let (verdict, fresh_cache) = match reused_verdict {+ _ if report_state.is_some() => (CachedVerdict::NoMatch, None),Some(verdict) => (verdict, None),None => {let screen = read_screen_tail(pane);@@ -678,12 +828,18 @@ fn evaluate_pane(pane: &dyn Pane) -> bool {pending: Default::default(),contract_raw: None,contract_leader: None,+ report_process_group: None,+ report_orphaned: false,},);}}let (state, evidence) = match verdict {+ _ if report_state.is_some() => (+ report_state.unwrap_or(AgentState::Idle),+ AgentEvidence::Report,+ ),CachedVerdict::State(state) => (state, AgentEvidence::Screen),CachedVerdict::Freeze => match previous_state {Some(state) => (state, AgentEvidence::Screen),@@ -710,8 +866,12 @@ fn evaluate_pane(pane: &dyn Pane) -> bool {pending: Default::default(),contract_raw: None,contract_leader: None,+ report_process_group: None,+ report_orphaned: false,});record.agent_id = agent_id;+ record.report_process_group = report.as_ref().and_then(|root| root.process_group);+ record.report_orphaned = report.as_ref().is_some_and(|root| root.orphaned);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".@@ -756,6 +916,7 @@ fn evaluate_pane(pane: &dyn Pane) -> bool {session_id: record.session_id.clone(),since_unix: record.since_unix,ended: record.ended,+ report: program_report(report.as_ref(), &children),};if record.published.as_ref() == Some(&status) {false@@ -765,6 +926,231 @@ fn evaluate_pane(pane: &dyn Pane) -> bool {}}+/// The agent id an OSC 7501 `app` stands for: the id ThinkTerm already+/// knows an agent by where the two differ, the app's own name otherwise.+fn agent_id_for_app(app: Option<&str>) -> String {+ match app {+ Some("claude-code") => "claude".to_string(),+ Some(app) => app.to_string(),+ None => "program".to_string(),+ }+}++/// The process group a pane's OSC 7501 root came from.+struct ReportFiler {+ /// Each receipt counts, including an identical payload sent again.+ serial: u64,+ /// The group in the foreground then; `None` where none could be seen.+ group: Option<u32>,+ /// The foreground last compared with `group`, and whether it descends+ /// from it: walking the process table once per change, not per round.+ checked: Option<(u32, bool)>,+ /// Only groups in the current snapshot (at most MAX_RECORDS); replaced+ /// on every evaluation and released with this root or pane.+ children: Vec<(Option<u32>, bool)>,+}++/// Whether a pane's OSC 7501 root speaks for whatever holds the foreground+/// now: the program that was in front when the root was filed, or one it+/// handed the foreground to -- a pager, an editor. A root does not speak+/// for an unrelated program that took its place, named in it or not.+fn report_from_foreground(+ pane_id: PaneId,+ root: &ProgramStatusRecord,+ foreground: Option<u32>,+ pane_root: Option<u32>,+) -> bool {+ let mut filers = REPORT_FILERS.lock();+ if !filers.get(&pane_id).is_some_and(|filer| filer.serial == root.serial) {+ // The parser recorded the foreground before this deferred evaluation.+ // The current foreground may already belong to the next command.+ filers.insert(+ pane_id,+ ReportFiler {+ serial: root.serial,+ group: root.process_group,+ checked: None,+ children: Vec::new(),+ },+ );+ }+ let Some(filer) = filers.get_mut(&pane_id) else {+ return true;+ };+ match (filer.group, foreground) {+ (Some(group), Some(now)) if group != now => match filer.checked {+ Some((seen, verdict)) if seen == now => verdict,+ _ => {+ let verdict = descends_from(now, group, pane_root);+ filer.checked = Some((now, verdict));+ verdict+ }+ },+ _ => true,+ }+}++fn retain_report_children(+ pane_id: PaneId,+ root: &ProgramStatusRecord,+ children: &mut Vec<ProgramStatusRecord>,+ pane_root: Option<u32>,+) {+ let mut filers = REPORT_FILERS.lock();+ let Some(filer) = filers.get_mut(&pane_id) else {+ return;+ };+ let mut checked: Vec<(Option<u32>, bool)> = Vec::with_capacity(children.len());+ children.retain(|child| {+ if let Some((_, belongs)) = checked.iter().find(|(group, _)| *group == child.process_group) {+ return *belongs;+ }+ let belongs = filer.children+ .iter()+ .find(|(group, _)| *group == child.process_group)+ .map(|(_, belongs)| *belongs)+ .unwrap_or_else(|| match (root.process_group, child.process_group) {+ (Some(root), Some(child)) if root != child => {+ descends_from(child, root, pane_root) || descends_from(root, child, pane_root)+ }+ _ => true,+ });+ checked.push((child.process_group, belongs));+ belongs+ });+ filer.children = checked;+}++/// Whether process `pid` is `ancestor` or descends from it, walking up+/// from `pid`: a step per parent, where walking down would collect the+/// ancestor's whole tree. The pane's own first process, `stop`, is as high+/// as a program the pane runs can reach.+#[cfg(not(test))]+fn descends_from(pid: u32, ancestor: u32, stop: Option<u32>) -> bool {+ let mut at = pid;+ // Deep enough for any wrapper chain; a loop in a racing table ends.+ for _ in 0..16 {+ if at == ancestor {+ return true;+ }+ if Some(at) == stop || at <= 1 {+ return false;+ }+ match procinfo::LocalProcessInfo::with_root_pid(at) {+ Some(info) => at = info.ppid,+ None => return false,+ }+ }+ false+}++#[cfg(test)]+fn descends_from(pid: u32, ancestor: u32, _stop: Option<u32>) -> bool {+ tests::fake_descends_from(pid, ancestor)+}++/// Whether a pane's OSC 7501 report speaks for what runs in it now.+fn report_applies(+ root: &ProgramStatusRecord,+ process_agent: Option<&str>,+ contract: bool,+ from_foreground: bool,+) -> bool {+ // A result left behind by a program that has gone describes nothing+ // running now: it speaks only while no agent does.+ if root.orphaned {+ return process_agent.is_none() && !contract;+ }+ // A report that names another program is not about this one.+ if let (Some(agent), Some(app)) = (process_agent, root.app.as_deref()) {+ if agent_id_for_app(Some(app)) != agent {+ return false;+ }+ }+ from_foreground+}++/// A pane's report when only sub-tasks are left: the most pressing of them+/// -- an error before a wait before work before a result -- stands in for+/// the root.+fn root_from_children(children: &[ProgramStatusRecord]) -> Option<ProgramStatusRecord> {+ let rank = |state: ProgramState| match state {+ ProgramState::Error => 0,+ ProgramState::Blocked => 1,+ ProgramState::Working => 2,+ ProgramState::Done => 3,+ ProgramState::Idle | ProgramState::Clear => 4,+ };+ // Live sub-tasks speak before results left behind, never mixed with+ // them: the stand-in is left behind only when every one of them is.+ let live = children.iter().any(|child| !child.orphaned);+ let children: Vec<&ProgramStatusRecord> = children+ .iter()+ .filter(|child| !live || !child.orphaned)+ .collect();+ let child = children.iter().copied().min_by_key(|child| rank(child.state))?;+ Some(ProgramStatusRecord {+ serial: child.serial,+ process_group: child.process_group,+ id: None,+ state: child.state,+ kind: child.kind,+ progress: None,+ app: child.app.clone(),+ title: None,+ msg: child.msg.clone().or_else(|| child.title.clone()),+ orphaned: !live,+ })+}++/// A pane's OSC 7501 records in the shape every consumer receives them.+fn program_report(+ root: Option<&ProgramStatusRecord>,+ children: &[ProgramStatusRecord],+) -> Option<ProgramReport> {+ fn state(state: ProgramState) -> ProgramReportState {+ match state {+ ProgramState::Working => ProgramReportState::Working,+ ProgramState::Done => ProgramReportState::Done,+ ProgramState::Blocked => ProgramReportState::Blocked,+ ProgramState::Error => ProgramReportState::Error,+ ProgramState::Idle | ProgramState::Clear => ProgramReportState::Idle,+ }+ }+ fn kind(kind: wezterm_term::program_status::ProgramBlockedKind) -> ProgramBlockedKind {+ use wezterm_term::program_status::ProgramBlockedKind as Kind;+ match kind {+ Kind::Permission => ProgramBlockedKind::Permission,+ Kind::Question => ProgramBlockedKind::Question,+ Kind::Auth => ProgramBlockedKind::Auth,+ }+ }+ let root = root?;+ Some(ProgramReport {+ state: state(root.state),+ kind: root.kind.map(kind),+ progress: root.progress,+ app: root.app.clone(),+ title: root.title.clone(),+ msg: root.msg.clone(),+ children: children+ .iter()+ .take(ProgramReport::MAX_CHILDREN)+ .filter_map(|child| {+ Some(ProgramReportChild {+ id: child.id.clone()?,+ state: state(child.state),+ kind: child.kind.map(kind),+ progress: child.progress,+ title: child.title.clone(),+ msg: child.msg.clone(),+ })+ })+ .take(ProgramReport::MAX_CHILDREN)+ .collect(),+ })+}+/// 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.@@ -802,6 +1188,25 @@ mod tests {static NEXT_PANE_ID: AtomicUsize = AtomicUsize::new(9000);+ lazy_static::lazy_static! {+ /// A process table for the tests: child pid to parent pid.+ static ref FAKE_PARENTS: Mutex<HashMap<u32, u32>> = Mutex::new(HashMap::new());+ }++ pub(super) fn fake_descends_from(pid: u32, ancestor: u32) -> bool {+ let parents = FAKE_PARENTS.lock();+ let mut at = pid;+ loop {+ if at == ancestor {+ return true;+ }+ match parents.get(&at) {+ Some(parent) => at = *parent,+ None => return false,+ }+ }+ }+lazy_static::lazy_static! {static ref PUBLISH_LOG: parking_lot::Mutex<Vec<PaneId>> =parking_lot::Mutex::new(Vec::new());@@ -866,6 +1271,11 @@ mod tests {swap_after_read: parking_lot::Mutex<Option<String>>,/// The parser holds the terminal: reading the pane would wait.contended: AtomicBool,+ program: parking_lot::Mutex<wezterm_term::program_status::ProgramStatusRecords>,+ /// What `shell_is_foreground` answers.+ shell_foreground: parking_lot::Mutex<Option<bool>>,+ /// What `foreground_process_group` answers.+ foreground_group: parking_lot::Mutex<Option<u32>>,}impl FakeAgentPane {@@ -885,9 +1295,41 @@ mod tests {dead: AtomicBool::new(false),swap_after_read: parking_lot::Mutex::new(None),contended: AtomicBool::new(false),+ program: parking_lot::Mutex::new(Default::default()),+ shell_foreground: parking_lot::Mutex::new(None),+ foreground_group: parking_lot::Mutex::new(None),})}+ /// Put process group `group` in the foreground, with whether it is+ /// the pane's own shell.+ fn set_foreground(&self, group: u32, shell: bool) {+ *self.foreground_group.lock() = Some(group);+ *self.shell_foreground.lock() = Some(shell);+ }++ /// File an OSC 7501 report, as the program in the pane would.+ fn report(+ &self,+ state: ProgramState,+ app: Option<&str>,+ edit: impl FnOnce(&mut wezterm_term::program_status::ProgramStatusReport),+ ) {+ let mut report = wezterm_term::program_status::ProgramStatusReport {+ state,+ id: None,+ kind: None,+ progress: None,+ app: app.map(str::to_string),+ title: None,+ msg: None,+ };+ edit(&mut report);+ let group = *self.foreground_group.lock();+ self.program.lock().apply_from(report, group);+ self.seqno.fetch_add(1, Ordering::SeqCst);+ }+fn set_screen(&self, text: &str) {*self.screen.lock() = text.to_string();self.seqno.fetch_add(1, Ordering::SeqCst);@@ -1005,6 +1447,20 @@ mod tests {fn clear_agent_osc_evidence(&self) {*self.osc_evidence.lock() = Default::default();}+ fn program_status(&self) -> wezterm_term::program_status::ProgramStatusSnapshot {+ self.program+ .lock()+ .snapshot(wezterm_term::program_status::ProgramStatusRecords::MAX_RECORDS)+ }+ fn end_program_status(&self, through: u64) {+ self.program.lock().end_of_program_through(through);+ }+ fn shell_is_foreground(&self) -> Option<bool> {+ *self.shell_foreground.lock()+ }+ fn foreground_process_group(&self) -> Option<u32> {+ *self.foreground_group.lock()+ }fn copy_user_vars(&self) -> HashMap<String, String> {self.user_vars.lock().clone()}@@ -1098,6 +1554,331 @@ mod tests {evict_pane(pane.pane_id());}+ #[test]+ fn any_program_that_reports_its_state_counts() {+ let pane = FakeAgentPane::new(Some("/opt/homebrew/bin/brew"));+ pane.report(ProgramState::Working, Some("brew"), |report| {+ report.progress = Some(25);+ report.msg = Some("Upgrading 3 of 12".to_string());+ report.id = None;+ });+ pane.program.lock().apply(wezterm_term::program_status::ProgramStatusReport {+ state: ProgramState::Blocked,+ id: Some("fetch".to_string()),+ kind: Some(wezterm_term::program_status::ProgramBlockedKind::Auth),+ progress: None,+ app: None,+ title: Some("Fetch".to_string()),+ msg: None,+ });+ assert!(evaluate_pane(pane.as_ref() as &dyn Pane));+ let status = status_for_pane(pane.pane_id()).expect("classified");+ assert_eq!(status.agent_id, "brew");+ assert_eq!(status.state, AgentState::Working);+ assert_eq!(status.evidence, AgentEvidence::Report);+ let report = status.report.expect("the report travels with it");+ assert_eq!(report.progress, Some(25));+ assert_eq!(report.msg.as_deref(), Some("Upgrading 3 of 12"));+ assert_eq!(report.children.len(), 1);+ assert_eq!(report.children[0].kind, Some(ProgramBlockedKind::Auth));+ evict_pane(pane.pane_id());+ }++ #[test]+ fn a_program_report_outranks_the_screen() {+ let pane = FakeAgentPane::new(Some("/usr/local/bin/claude"));+ pane.set_screen("✻ Thinking… (esc to interrupt)\n");+ pane.report(ProgramState::Blocked, Some("claude-code"), |report| {+ report.kind = Some(wezterm_term::program_status::ProgramBlockedKind::Permission);+ report.msg = Some("Bash: npm test".to_string());+ });+ 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::Blocked);+ assert_eq!(status.evidence, AgentEvidence::Report);+ assert_eq!(+ status.report.and_then(|report| report.kind),+ Some(ProgramBlockedKind::Permission)+ );++ // An error is its own state, not a flavour of waiting.+ pane.report(ProgramState::Error, Some("claude-code"), |_| {});+ assert!(evaluate_pane(pane.as_ref() as &dyn Pane));+ assert_eq!(+ status_for_pane(pane.pane_id()).map(|status| status.state),+ Some(AgentState::Error)+ );+ evict_pane(pane.pane_id());+ }++ /// A report outlives its program only as a result left behind: once+ /// the pane's shell has the foreground back, what was in progress is+ /// over, and the result speaks only while nothing else runs.+ #[test]+ fn only_an_unseen_result_outlives_the_program_that_reported_it() {+ // zsh is 9100; brew 9101 runs a pager 9102.+ FAKE_PARENTS.lock().insert(9102, 9101);+ let pane = FakeAgentPane::new(Some("/opt/homebrew/bin/brew"));+ pane.set_foreground(9101, false);+ pane.report(ProgramState::Working, Some("brew"), |_| {});+ assert!(evaluate_pane(pane.as_ref() as &dyn Pane));++ // brew hands the foreground to its pager: it is still going.+ pane.set_process(Some("/usr/bin/less"));+ pane.set_foreground(9102, false);+ evaluate_pane(pane.as_ref() as &dyn Pane);+ assert_eq!(+ status_for_pane(pane.pane_id()).map(|status| status.state),+ Some(AgentState::Working)+ );++ // brew exits and the shell is back: nothing is in progress any more.+ pane.set_process(Some("/bin/zsh"));+ pane.set_foreground(9100, true);+ assert!(evaluate_pane(pane.as_ref() as &dyn Pane));+ assert!(status_for_pane(pane.pane_id()).is_none());+ assert_eq!(pane.program_status(), Default::default());++ // A failed result stays, as brew's own...+ pane.set_process(Some("/opt/homebrew/bin/brew"));+ pane.set_foreground(9101, false);+ pane.report(ProgramState::Error, Some("brew"), |report| {+ report.msg = Some("Download failed".to_string());+ });+ assert!(evaluate_pane(pane.as_ref() as &dyn Pane));+ pane.set_process(Some("/bin/zsh"));+ pane.set_foreground(9100, true);+ evaluate_pane(pane.as_ref() as &dyn Pane);+ let status = status_for_pane(pane.pane_id()).expect("the result stays");+ assert_eq!(status.agent_id, "brew");+ assert_eq!(status.state, AgentState::Error);++ // ...but does not speak for the agent started next in the pane.+ pane.set_process(Some("/usr/local/bin/claude"));+ pane.set_foreground(9103, false);+ evaluate_pane(pane.as_ref() as &dyn Pane);+ let status = status_for_pane(pane.pane_id()).expect("claude is running");+ assert_eq!(status.agent_id, "claude");+ assert_ne!(status.state, AgentState::Error);+ assert_ne!(status.evidence, AgentEvidence::Report);+ assert!(status.report.is_none());+ evict_pane(pane.pane_id());+ }++ /// A program that left without the shell ever getting the foreground+ /// back -- the next command of a chain took it straight away -- leaves+ /// a report that names nobody. It is still not the new program's.+ #[test]+ fn an_unnamed_report_does_not_speak_for_a_program_that_took_its_place() {+ let pane = FakeAgentPane::new(Some("/usr/local/bin/tool"));+ pane.set_foreground(9201, false);+ pane.report(ProgramState::Done, None, |report| {+ report.msg = Some("Built".to_string());+ });+ evaluate_pane(pane.as_ref() as &dyn Pane);++ pane.set_process(Some("/usr/local/bin/claude"));+ pane.set_foreground(9202, false);+ evaluate_pane(pane.as_ref() as &dyn Pane);+ let status = status_for_pane(pane.pane_id()).expect("claude is running");+ assert_eq!(status.agent_id, "claude");+ assert_ne!(status.evidence, AgentEvidence::Report);+ assert!(status.report.is_none());++ // Its own report speaks at once.+ pane.report(ProgramState::Working, Some("claude-code"), |_| {});+ evaluate_pane(pane.as_ref() as &dyn Pane);+ let status = status_for_pane(pane.pane_id()).expect("claude reports");+ assert_eq!(status.state, AgentState::Working);+ assert_eq!(status.evidence, AgentEvidence::Report);+ evict_pane(pane.pane_id());+ }++ /// Sub-tasks an earlier program left behind are not the next agent's.+ #[test]+ fn left_behind_sub_tasks_stay_out_of_the_next_agents_report() {+ let pane = FakeAgentPane::new(Some("/opt/homebrew/bin/brew"));+ pane.set_foreground(9401, false);+ pane.report(ProgramState::Working, None, |_| {});+ pane.report(ProgramState::Error, None, |report| {+ report.id = Some("fetch".to_string());+ });+ evaluate_pane(pane.as_ref() as &dyn Pane);+ pane.set_process(Some("/bin/zsh"));+ pane.set_foreground(9400, true);+ evaluate_pane(pane.as_ref() as &dyn Pane);++ pane.set_process(Some("/usr/local/bin/claude"));+ pane.set_foreground(9402, false);+ pane.report(ProgramState::Working, Some("claude-code"), |_| {});+ evaluate_pane(pane.as_ref() as &dyn Pane);+ let status = status_for_pane(pane.pane_id()).expect("claude reports");+ assert_eq!(status.evidence, AgentEvidence::Report);+ let report = status.report.expect("published");+ assert!(report.children.is_empty(), "{:?}", report.children);+ evict_pane(pane.pane_id());+ }++ #[test]+ fn a_shell_builtin_keeps_its_report_until_the_prompt() {+ let pane = FakeAgentPane::new(Some("/bin/sh"));+ pane.set_foreground(9800, true);+ pane.report(ProgramState::Blocked, Some("example"), |_| {});+ evaluate_pane(pane.as_ref());+ assert_eq!(status_for_pane(pane.id).unwrap().state, AgentState::Blocked);+ assert!(!pane.program_status().root.unwrap().orphaned);++ // OSC 133's prompt marker is an explicit end even when the shell+ // never handed its process group to an external command.+ pane.program.lock().end_of_program();+ evaluate_pane(pane.as_ref());+ assert!(status_for_pane(pane.id).is_none());+ evict_pane(pane.id);+ }++ #[test]+ fn a_command_chain_does_not_attach_old_children_to_the_next_root() {+ let pane = FakeAgentPane::new(Some("/usr/bin/example"));+ pane.set_foreground(9811, false);+ pane.report(ProgramState::Working, Some("example"), |_| {});+ for n in 0..ProgramReport::MAX_CHILDREN {+ pane.report(ProgramState::Blocked, None, |report| {+ report.id = Some(format!("old-{n:02}"));+ });+ }+ evaluate_pane(pane.as_ref());++ // The next command reports before a prompt or an evaluator tick.+ pane.set_process(Some("/usr/local/bin/claude"));+ pane.set_foreground(9812, false);+ pane.report(ProgramState::Working, Some("claude-code"), |_| {});+ pane.report(ProgramState::Working, None, |report| {+ report.id = Some("task".to_string());+ });+ evaluate_pane(pane.as_ref());+ let report = status_for_pane(pane.id).unwrap().report.unwrap();+ assert_eq!(report.children.len(), 1);+ assert_eq!(report.children[0].id, "task");+ // A cached decision has the same ownership boundary.+ evaluate_pane(pane.as_ref());+ assert_eq!(status_for_pane(pane.id).unwrap().report.unwrap().children.len(), 1);+ evict_pane(pane.id);+ assert!(!REPORT_FILERS.lock().contains_key(&pane.id));+ }++ #[test]+ fn children_reported_by_a_descendant_stay_with_the_root() {+ FAKE_PARENTS.lock().insert(9822, 9821);+ let pane = FakeAgentPane::new(Some("/usr/bin/example"));+ pane.set_foreground(9821, false);+ pane.report(ProgramState::Working, Some("example"), |_| {});+ pane.set_foreground(9822, false);+ pane.report(ProgramState::Blocked, None, |report| {+ report.id = Some("task".to_string());+ });+ evaluate_pane(pane.as_ref());+ assert_eq!(status_for_pane(pane.id).unwrap().report.unwrap().children.len(), 1);+ evict_pane(pane.id);+ }++ /// A program that names itself in some reports only keeps its name.+ #[test]+ fn a_report_naming_nobody_keeps_the_name_the_program_gave() {+ let pane = FakeAgentPane::new(Some("/opt/homebrew/bin/brew"));+ pane.set_foreground(9831, false);+ pane.report(ProgramState::Working, Some("brew"), |_| {});+ evaluate_pane(pane.as_ref() as &dyn Pane);+ pane.report(ProgramState::Working, None, |report| {+ report.progress = Some(40);+ });+ evaluate_pane(pane.as_ref() as &dyn Pane);+ let status = status_for_pane(pane.pane_id()).expect("still brew");+ assert_eq!(status.agent_id, "brew");+ assert_eq!(status.report.and_then(|report| report.progress), Some(40));+ evict_pane(pane.pane_id());+ }++ #[test]+ fn an_unnamed_successor_does_not_borrow_the_previous_programs_name() {+ let pane = FakeAgentPane::new(Some("/usr/bin/example"));+ pane.set_foreground(9841, false);+ pane.report(ProgramState::Working, Some("tool-a"), |_| {});+ evaluate_pane(pane.as_ref());+ assert_eq!(status_for_pane(pane.id).unwrap().agent_id, "tool-a");++ pane.set_foreground(9842, false);+ pane.report(ProgramState::Working, None, |_| {});+ evaluate_pane(pane.as_ref());+ let status = status_for_pane(pane.id).unwrap();+ assert_eq!(status.agent_id, "program");+ assert_eq!(status.evidence, AgentEvidence::Report);+ assert_eq!(status.state, AgentState::Working);+ evict_pane(pane.id);+ }++ #[test]+ fn an_unknown_report_source_cannot_inherit_a_program_name() {+ let pane = FakeAgentPane::new(None);+ pane.report(ProgramState::Working, Some("tool-a"), |_| {});+ evaluate_pane(pane.as_ref());+ pane.report(ProgramState::Working, None, |_| {});+ evaluate_pane(pane.as_ref());+ assert_eq!(status_for_pane(pane.id).unwrap().agent_id, "program");+ evict_pane(pane.id);+ }++ #[test]+ fn an_orphaned_result_cannot_name_a_new_report_from_the_shell() {+ let pane = FakeAgentPane::new(Some("/bin/sh"));+ pane.set_foreground(9851, true);+ pane.report(ProgramState::Done, Some("tool-a"), |_| {});+ evaluate_pane(pane.as_ref());+ pane.program.lock().end_of_program();+ evaluate_pane(pane.as_ref());+ pane.report(ProgramState::Working, None, |_| {});+ evaluate_pane(pane.as_ref());+ assert_eq!(status_for_pane(pane.id).unwrap().agent_id, "program");+ evict_pane(pane.id);+ }++ #[test]+ fn a_report_naming_another_program_does_not_speak_for_the_agent() {+ let pane = FakeAgentPane::new(Some("/usr/local/bin/claude"));+ pane.report(ProgramState::Done, Some("make"), |_| {});+ evaluate_pane(pane.as_ref() as &dyn Pane);+ let status = status_for_pane(pane.pane_id()).expect("claude is running");+ assert_eq!(status.agent_id, "claude");+ assert_ne!(status.evidence, AgentEvidence::Report);+ assert!(status.report.is_none());+ evict_pane(pane.pane_id());+ }++ #[test]+ fn sub_task_results_speak_once_the_root_has_gone() {+ let pane = FakeAgentPane::new(Some("/usr/local/bin/tool"));+ pane.set_foreground(9301, false);+ pane.report(ProgramState::Working, Some("tool"), |_| {});+ pane.report(ProgramState::Error, None, |report| {+ report.id = Some("fetch".to_string());+ report.msg = Some("404 Not Found".to_string());+ });+ assert!(evaluate_pane(pane.as_ref() as &dyn Pane));++ // The shell is back: the working root goes, the failed sub-task+ // stays, and still answers to its program's name.+ pane.set_process(Some("/bin/zsh"));+ pane.set_foreground(9300, true);+ evaluate_pane(pane.as_ref() as &dyn Pane);+ let status = status_for_pane(pane.pane_id()).expect("the sub-task's result");+ assert_eq!(status.agent_id, "tool");+ assert_eq!(status.state, AgentState::Error);+ let report = status.report.expect("published");+ assert_eq!(report.msg.as_deref(), Some("404 Not Found"));+ assert_eq!(report.children.len(), 1);+ evict_pane(pane.pane_id());+ }+#[test]fn contract_only_pane_classifies_from_user_var() {let pane = FakeAgentPane::new(None);@@ -1740,4 +2521,58 @@ mod tests {);evict_pane(pane.pane_id());}++ #[test]+ fn an_identical_report_from_the_next_process_is_a_new_emission() {+ let pane = FakeAgentPane::new(Some("/usr/bin/example"));+ pane.set_foreground(9501, false);+ pane.report(ProgramState::Working, Some("example"), |_| {});+ evaluate_pane(pane.as_ref());+ assert_eq!(status_for_pane(pane.id).unwrap().state, AgentState::Working);+ // The next command in a chain reports the same initial state.+ pane.set_process(Some("/usr/bin/example"));+ pane.set_foreground(9502, false);+ pane.report(ProgramState::Working, Some("example"), |_| {});+ evaluate_pane(pane.as_ref());+ assert_eq!(+ status_for_pane(pane.id).map(|s| s.state),+ Some(AgentState::Working),+ "the new program emitted its own report"+ );+ evict_pane(pane.id);+ }++ #[test]+ fn a_report_received_before_process_turnover_is_not_rebound_on_first_poll() {+ let pane = FakeAgentPane::new(Some("/usr/bin/example"));+ pane.set_foreground(9601, false);+ pane.report(ProgramState::Done, None, |_| {});+ // The short command exits before the evaluator gets a turn.+ pane.set_process(Some("/usr/local/bin/claude"));+ pane.set_foreground(9602, false);+ pane.set_screen("some output\n⏵⏵ Cooking… (esc to interrupt · 12s)\n");+ evaluate_pane(pane.as_ref());+ let status = status_for_pane(pane.id).unwrap();+ assert_eq!(status.agent_id, "claude");+ assert_eq!(+ status.state,+ AgentState::Working,+ "the report was emitted by the previous command"+ );+ evict_pane(pane.id);+ }++ #[test]+ fn an_anonymous_result_does_not_override_a_working_successor() {+ let pane = FakeAgentPane::new(Some("/usr/bin/example"));+ pane.set_foreground(9701, false);+ pane.report(ProgramState::Done, None, |_| {});+ evaluate_pane(pane.as_ref());+ pane.set_process(Some("/usr/local/bin/claude"));+ pane.set_foreground(9702, false);+ pane.set_screen("some output\n⏵⏵ Cooking… (esc to interrupt · 12s)\n");+ evaluate_pane(pane.as_ref());+ assert_eq!(status_for_pane(pane.id).unwrap().state, AgentState::Working);+ evict_pane(pane.id);+ }}diff --git a/mux/src/localpane.rs b/mux/src/localpane.rsindex 6eb0c30d..69a0c504 100644--- a/mux/src/localpane.rs+++ b/mux/src/localpane.rs@@ -303,7 +303,7 @@ pub struct LocalPane {pane_id: PaneId,terminal: Mutex<Terminal>,process: Mutex<ProcessState>,- pty: Mutex<Box<dyn MasterPty>>,+ pty: Arc<Mutex<Box<dyn MasterPty>>>,writer: Mutex<Box<dyn Write + Send>>,domain_id: DomainId,tmux_domain: Mutex<Option<Arc<TmuxDomainState>>>,@@ -330,6 +330,12 @@ pub struct LocalPane {/// focusing a pane is what a person does right before typing into it,/// and the main thread must not wait on that pane's parser for it.pending_focus: Mutex<Option<bool>>,+ /// A look at the pane the terminal has yet to hear of, as+ /// `pending_focus`: it retires finished programs' OSC 7501 results.+ pending_seen: Mutex<bool>,+ /// Whether the pane's root was a shell without children, and when:+ /// finding out walks the process table, so the answer stands a moment.+ shell_idle: Mutex<Option<(Instant, bool)>>,/// The progress the terminal last reported, for `get_progress` while/// the parser holds the terminal.last_progress: Mutex<Progress>,@@ -833,6 +839,83 @@ impl Pane for LocalPane {self.terminal.lock().clear_agent_osc_state();}+ fn program_status(&self) -> wezterm_term::program_status::ProgramStatusSnapshot {+ let exited = !matches!(&*self.process.lock(), ProcessState::Running { .. });+ let mut term = self.terminal.lock();+ if exited {+ // Held panes remain visible after their child exits. Finalize+ // each read, including any last reports parsed after the exit.+ term.end_program_status(u64::MAX);+ }+ term.program_status(wezterm_term::program_status::ProgramStatusRecords::MAX_RECORDS)+ }++ fn end_program_status(&self, through: u64) {+ self.terminal.lock().end_program_status(through);+ }++ fn program_status_seen(&self) {+ // Never waits on the parser, as `focus_changed` does not, and probes+ // again after leaving the mark: the parser may have made its last+ // check for pending work in between.+ match self.terminal.try_lock() {+ Some(mut term) => self.retire_seen_results(&mut term),+ None => {+ *self.pending_seen.lock() = true;+ if let Some(mut term) = self.terminal.try_lock() {+ self.apply_pending_focus(&mut term);+ }+ }+ }+ }++ fn foreground_process_group(&self) -> Option<u32> {+ #[cfg(unix)]+ {+ // Only ever positive: the pty answers `None` for anything else.+ self.pty.lock().process_group_leader().map(|pid| pid as u32)+ }+ #[cfg(not(unix))]+ None+ }++ fn shell_is_foreground(&self) -> Option<bool> {+ #[cfg(unix)]+ {+ let leader = self.pty.lock().process_group_leader()?;+ let root = self.root_process_id()?;+ if leader as u32 != root {+ return Some(false);+ }+ // The pane's first process holds the foreground: a shell at its+ // prompt -- or the program the pane was opened on, or a shell+ // running a script or a `-c` command, which without job control+ // keeps its child in its own group. A childless shell may still+ // be executing a builtin: callers must also check who reported.+ const SHELL_IDLE_TTL: Duration = Duration::from_secs(2);+ let now = Instant::now();+ if let Some((at, idle)) = *self.shell_idle.lock() {+ if now.duration_since(at) < SHELL_IDLE_TTL {+ return Some(idle);+ }+ }+ let path = procinfo::LocalProcessInfo::executable_path(root)?;+ let name = path.file_name()?.to_string_lossy();+ let shell = matches!(+ name.as_ref(),+ "sh" | "bash" | "zsh" | "fish" | "dash" | "ash" | "busybox" | "ksh" | "mksh"+ | "tcsh" | "csh" | "nu" | "elvish" | "xonsh" | "pwsh"+ );+ let idle = shell+ && procinfo::LocalProcessInfo::with_root_pid(root)+ .is_some_and(|info| info.children.is_empty());+ *self.shell_idle.lock() = Some((now, idle));+ Some(idle)+ }+ #[cfg(not(unix))]+ None+ }+fn palette(&self) -> ColorPalette {self.terminal.lock().palette()}@@ -1474,6 +1557,14 @@ impl LocalPane {tmux_domain: None,}));terminal.set_notification_handler(Box::new(LocalPaneNotifHandler { pane_id }));+ let pty = Arc::new(Mutex::new(pty));+ #[cfg(unix)]+ {+ let source = Arc::clone(&pty);+ terminal.set_program_status_process_group(Box::new(move || {+ source.lock().process_group_leader().map(|pid| pid as u32)+ }));+ }let last_summary = Mutex::new(PaneSummary::from_terminal(&mut terminal, false));let config = Mutex::new(terminal.get_config());@@ -1486,7 +1577,7 @@ impl LocalPane {signaller,killed: false,}),- pty: Mutex::new(pty),+ pty,writer: Mutex::new(writer),domain_id,tmux_domain: Mutex::new(None),@@ -1499,6 +1590,8 @@ impl LocalPane {config,pending_config: Mutex::new(None),pending_focus: Mutex::new(None),+ pending_seen: Mutex::new(false),+ shell_idle: Mutex::new(None),last_progress: Mutex::new(Progress::default()),}}@@ -1510,6 +1603,19 @@ impl LocalPane {if let Some(focused) = pending {term.focus_changed(focused);}+ if std::mem::take(&mut *self.pending_seen.lock()) {+ self.retire_seen_results(term);+ }+ }++ /// Someone has looked: retire the finished or failed results programs+ /// reported, and have the pane re-judged at once if any went. Asked by+ /// a frontend that showed the pane to a person -- never by focus alone,+ /// which code also moves with nobody looking.+ fn retire_seen_results(&self, term: &mut Terminal) {+ if term.program_status_seen() {+ crate::agent_status::nudge(self.pane_id);+ }}/// Everything the terminal has yet to take, applied under the guard@@ -1526,6 +1632,7 @@ impl LocalPane {self.pending_resize.lock().is_some()|| self.pending_config.lock().is_some()|| self.pending_focus.lock().is_some()+ || *self.pending_seen.lock()}/// Give the terminal a configuration `set_config` could not, with the@@ -1770,8 +1877,8 @@ mod summary_tests {}}- /// A pty that only remembers the sizes it was given.- struct RecordingPty(Arc<StdMutex<Vec<PtySize>>>);+ /// A pty that remembers its sizes and reports a chosen foreground group.+ struct RecordingPty(Arc<StdMutex<Vec<PtySize>>>, Option<u32>);impl MasterPty for RecordingPty {fn resize(&self, size: PtySize) -> anyhow::Result<()> {@@ -1789,7 +1896,7 @@ mod summary_tests {}#[cfg(unix)]fn process_group_leader(&self) -> Option<libc::pid_t> {- None+ self.1.map(|pid| pid as libc::pid_t)}#[cfg(unix)]fn as_raw_fd(&self) -> Option<std::os::unix::io::RawFd> {@@ -1840,7 +1947,7 @@ mod summary_tests {1,terminal,Box::new(SleepingChild(exit_rx)),- Box::new(RecordingPty(Arc::clone(&sizes))),+ Box::new(RecordingPty(Arc::clone(&sizes), None)),Box::new(Vec::new()),0,"test".into(),@@ -1865,6 +1972,65 @@ mod summary_tests {drop(guard);}+ #[cfg(unix)]+ #[test]+ fn program_status_keeps_the_process_group_observed_by_the_parser() {+ let (pane, sizes, _exit) = pane();+ let report = || {+ let mut parser = termwiz::escape::parser::Parser::new();+ let mut actions = vec![];+ parser.parse(b"\x1b]7501;state=working:app=example\x1b\\", |a| {+ actions.push(a)+ });+ actions+ };+ *pane.pty.lock() = Box::new(RecordingPty(Arc::clone(&sizes), Some(9101)));+ pane.perform_actions(report());+ *pane.pty.lock() = Box::new(RecordingPty(sizes, Some(9102)));+ let first = pane.program_status().root.unwrap();+ assert_eq!(first.process_group, Some(9101));+ pane.perform_actions(report());+ let second = pane.program_status().root.unwrap();+ assert_eq!(second.process_group, Some(9102));+ assert_ne!(second.serial, first.serial);+ }++ #[test]+ fn a_held_exited_pane_retires_active_reports_including_trailing_output() {+ use wezterm_term::program_status::ProgramState;+ let (pane, _sizes, _exit) = pane();+ let report = |state: &str, id: &str| {+ let mut parser = termwiz::escape::parser::Parser::new();+ let mut actions = vec![];+ let osc = format!("\x1b]7501;state={state}:id={id}:app=example\x1b\\");+ parser.parse(osc.as_bytes(), |action| actions.push(action));+ pane.perform_actions(actions);+ };+ report("working", "work");+ report("blocked", "input");+ report("done", "result");+ assert_eq!(pane.program_status().children.len(), 3);++ // Both Hold and a failed CloseOnCleanExit retain this pane state.+ *pane.process.lock() = ProcessState::DeadPendingClose { killed: false };+ assert!(!pane.is_dead());+ assert!(pane.root_process_id().is_none());+ let snapshot = pane.program_status();+ assert_eq!(snapshot.children.len(), 1);+ assert_eq!(snapshot.children[0].state, ProgramState::Done);+ assert!(snapshot.children[0].orphaned);++ // The reader may still be draining bytes after the child exits.+ report("working", "late-work");+ report("error", "late-result");+ let snapshot = pane.program_status();+ assert_eq!(snapshot.children.len(), 2);+ assert!(snapshot.children.iter().all(|child| child.orphaned));+ assert!(snapshot.children.iter().all(|child| {+ matches!(child.state, ProgramState::Done | ProgramState::Error)+ }));+ }+#[test]fn a_resize_while_the_terminal_is_held_reaches_the_pty_now_and_the_terminal_later() {let (pane, sizes, _exit) = pane();diff --git a/mux/src/pane.rs b/mux/src/pane.rsindex 3ddc2454..97d3a88c 100644--- a/mux/src/pane.rs+++ b/mux/src/pane.rs@@ -536,6 +536,12 @@ pub trait Pane: Downcast + Send + Sync {crate::agent_status::status_for_pane(self.pane_id())}+ /// [`agent_status`](Self::agent_status) without its report's text: what+ /// a painter asking every frame needs, without copying the rest.+ fn agent_status_summary(&self) -> Option<crate::agent_status::AgentStatusSummary> {+ crate::agent_status::summary_for_pane(self.pane_id())+ }+/// The program leading this pane's terminal, as observed by the mux/// that owns it. Same shape as `agent_status`: locally-owned panes/// answer from this process's observer, ClientPane from its server.@@ -556,6 +562,36 @@ pub trait Pane: Downcast + Send + Sync {/// inherit the previous agent's signals. No-op by default.fn clear_agent_osc_evidence(&self) {}+ /// What programs in this pane have reported about themselves with+ /// OSC 7501. Empty by default: remote mirrors are never classified+ /// locally.+ fn program_status(&self) -> wezterm_term::program_status::ProgramStatusSnapshot {+ Default::default()+ }++ /// The program behind the pane's OSC 7501 records has gone: drop all+ /// but the results nobody has seen yet, among the records received up+ /// to serial `through` -- a snapshot's `latest_serial`. No-op by default.+ fn end_program_status(&self, _through: u64) {}++ /// Someone has looked at the pane: retire the finished or failed+ /// results its programs reported. No-op by default.+ fn program_status_seen(&self) {}++ /// Whether the pane's own shell holds the foreground without child+ /// processes. This does not establish that it is at a prompt: builtins+ /// and functions can run in the shell itself. `None` where the platform+ /// cannot tell.+ fn shell_is_foreground(&self) -> Option<bool> {+ None+ }++ /// The process group holding the pane's foreground, asked fresh. `None`+ /// where the platform has no such thing or cannot tell.+ fn foreground_process_group(&self) -> Option<u32> {+ None+ }+fn get_foreground_process_name(&self, _policy: CachePolicy) -> Option<String> {None}diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftlindex 0b751026..d66019f0 100644--- a/thinkterm-i18n/i18n/de-DE.ftl+++ b/thinkterm-i18n/i18n/de-DE.ftl@@ -157,6 +157,8 @@ settings-remote-drop-destination-description = Wohin Dateien hochgeladen werden,settings-notifications-heading = Mitteilungensettings-notification-sounds = Mitteilungstönesettings-notification-sounds-description = Spielt einen kurzen Ton ab, wenn ein Thread fertig ist oder auf Sie zu warten beginnt.+settings-system-notifications = Systembenachrichtigungen+settings-system-notifications-description = Benachrichtigt, solange ThinkTerm im Hintergrund ist, wenn ein Thread fertig ist, Sie braucht oder mit einem Fehler anhält.settings-remote-update-keep-sessions = Sitzungen beim Update eines Remote-Servers behaltensettings-remote-update-keep-sessions-description = Der laufende Server übergibt seine Panes an die neue Version, statt zu stoppen; nichts, was darin läuft, endet.settings-local-sessions-via-mux = Lokale Terminals in einem Hintergrund-Sitzungsserver halten@@ -713,6 +715,8 @@ right-agents-state-working = Arbeitetright-agents-state-blocked = Braucht Eingaberight-agents-state-idle = Inaktivright-agents-state-unknown = Unbekannt+right-agents-state-error = Fehler+right-agents-state-done = Fertigright-agents-none = Keine Agents erkanntright-agents-detection-off = Agent-Erkennung ist aus — Einstellungen öffnenright-agents-count-working = { $count } arbeiten@@ -722,6 +726,30 @@ right-agents-count-blocked = { $count ->}right-agents-count-idle = { $count } inaktivright-agents-count-unknown = { $count } unbekannt+right-agents-count-error = { $count ->+ [one] 1 Fehler+ *[other] { $count } Fehler+ }+right-agents-more-subtasks = { $count } weitere+right-agents-subtasks = { $count ->+ [one] 1 Unteraufgabe+ *[other] { $count } Unteraufgaben+ }+agent-kind-permission = Berechtigung+agent-kind-question = Frage+agent-kind-auth = Anmeldung+notification-thread-finished = Fertig+notification-thread-needs-input = Braucht Sie+notification-thread-error = Mit einem Fehler angehalten+settings-agent-status-heading = Statusanzeige+settings-agent-status-description = Beschreibung+settings-agent-status-description-description = Was ein Programm gerade tut, was es fertiggestellt hat oder warum es angehalten hat.+settings-agent-status-reason = Wartegrund+settings-agent-status-reason-description = Ob es auf eine Berechtigung, eine Antwort oder eine Anmeldung wartet.+settings-agent-status-progress = Fortschritt+settings-agent-status-progress-description = Wie weit es ist, als Balken im Agenten-Bereich.+settings-agent-status-subtasks = Unteraufgaben+settings-agent-status-subtasks-description = Hintergrundaufgaben und Unteragenten: eine Zeile im Agenten-Bereich, die sich zur Liste öffnen lässt.settings-section-agents = Agentssettings-agents-integrations-heading = Integrationensettings-integration-screen-active = Im PATH gefunden; der Status wird aus seiner Terminaloberfläche erkannt (Bildschirmregeln).diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftlindex 01d32891..0f12864d 100644--- a/thinkterm-i18n/i18n/en-US.ftl+++ b/thinkterm-i18n/i18n/en-US.ftl@@ -157,6 +157,8 @@ settings-remote-drop-destination-description = Where files dropped onto a remotesettings-notifications-heading = Notificationssettings-notification-sounds = Notification Soundssettings-notification-sounds-description = Play a short sound when a thread finishes or starts waiting on you.+settings-system-notifications = System Notifications+settings-system-notifications-description = While ThinkTerm is in the background, notify when a thread finishes, needs you, or stops on an error.settings-remote-update-keep-sessions = Keep sessions when updating a remote serversettings-remote-update-keep-sessions-description = The running server hands its panes to the new version instead of stopping; nothing running in them ends.settings-local-sessions-via-mux = Keep local terminals in a background session server@@ -713,6 +715,8 @@ right-agents-state-working = Workingright-agents-state-blocked = Needs inputright-agents-state-idle = Idleright-agents-state-unknown = Unknown+right-agents-state-error = Error+right-agents-state-done = Doneright-agents-none = No agents detectedright-agents-detection-off = Agent detection is off — open settingsright-agents-count-working = { $count } working@@ -722,6 +726,30 @@ right-agents-count-blocked = { $count ->}right-agents-count-idle = { $count } idleright-agents-count-unknown = { $count } unknown+right-agents-count-error = { $count ->+ [one] 1 error+ *[other] { $count } errors+ }+right-agents-more-subtasks = { $count } more+right-agents-subtasks = { $count ->+ [one] 1 sub-task+ *[other] { $count } sub-tasks+ }+agent-kind-permission = Permission+agent-kind-question = Question+agent-kind-auth = Sign-in+notification-thread-finished = Finished+notification-thread-needs-input = Needs you+notification-thread-error = Stopped on an error+settings-agent-status-heading = Status Display+settings-agent-status-description = Description+settings-agent-status-description-description = What a program is doing, what it finished, or why it stopped.+settings-agent-status-reason = Waiting Reason+settings-agent-status-reason-description = Whether it waits for a permission, an answer or a sign-in.+settings-agent-status-progress = Progress+settings-agent-status-progress-description = How far along it is, as a bar in the Agents panel.+settings-agent-status-subtasks = Sub-tasks+settings-agent-status-subtasks-description = Background tasks and sub-agents: one line in the Agents panel that opens into the list.settings-section-agents = Agentssettings-agents-integrations-heading = Integrationssettings-integration-screen-active = Found on PATH; status is detected from its terminal UI (screen rules).diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftlindex 2fdbe512..b7240dbd 100644--- a/thinkterm-i18n/i18n/fr-FR.ftl+++ b/thinkterm-i18n/i18n/fr-FR.ftl@@ -157,6 +157,8 @@ settings-remote-drop-destination-description = Emplacement d’envoi des fichiersettings-notifications-heading = Notificationssettings-notification-sounds = Sons de notificationsettings-notification-sounds-description = Émettre un son bref lorsqu’une session se termine ou attend une réponse.+settings-system-notifications = Notifications système+settings-system-notifications-description = Quand ThinkTerm est en arrière-plan, prévenir lorsqu’une session se termine, vous attend ou s’arrête sur une erreur.settings-remote-update-keep-sessions = Conserver les sessions lors de la mise à jour d’un serveur distantsettings-remote-update-keep-sessions-description = Le serveur en cours transmet ses panneaux à la nouvelle version au lieu de s’arrêter ; rien de ce qui y tourne ne s’interrompt.settings-local-sessions-via-mux = Garder les terminaux locaux dans un serveur de sessions en arrière-plan@@ -713,12 +715,35 @@ right-agents-state-working = En coursright-agents-state-blocked = Attend une réponseright-agents-state-idle = Inactifright-agents-state-unknown = Inconnu+right-agents-state-error = Erreur+right-agents-state-done = Terminéright-agents-none = Aucun agent détectéright-agents-detection-off = Détection des agents désactivée — ouvrir les réglagesright-agents-count-working = { $count } en coursright-agents-count-blocked = { $count } en attenteright-agents-count-idle = { $count } inactif(s)right-agents-count-unknown = { $count } inconnu(s)+right-agents-count-error = { $count } en erreur+right-agents-more-subtasks = { $count } de plus+right-agents-subtasks = { $count ->+ [one] 1 sous-tâche+ *[other] { $count } sous-tâches+ }+agent-kind-permission = Autorisation+agent-kind-question = Question+agent-kind-auth = Connexion+notification-thread-finished = Terminé+notification-thread-needs-input = Vous attend+notification-thread-error = Arrêté sur une erreur+settings-agent-status-heading = Affichage de l’état+settings-agent-status-description = Description+settings-agent-status-description-description = Ce que fait un programme, ce qu’il a terminé ou pourquoi il s’est arrêté.+settings-agent-status-reason = Raison de l’attente+settings-agent-status-reason-description = S’il attend une autorisation, une réponse ou une connexion.+settings-agent-status-progress = Progression+settings-agent-status-progress-description = Où il en est, sous forme de barre dans le panneau Agents.+settings-agent-status-subtasks = Sous-tâches+settings-agent-status-subtasks-description = Tâches d’arrière-plan et sous-agents : une ligne du panneau Agents qui s’ouvre sur la liste.settings-section-agents = Agentssettings-agents-integrations-heading = Intégrationssettings-integration-screen-active = Trouvé dans le PATH ; l'état est détecté depuis son interface terminal (règles d'écran).diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftlindex f9cd423d..e578be70 100644--- a/thinkterm-i18n/i18n/ja-JP.ftl+++ b/thinkterm-i18n/i18n/ja-JP.ftl@@ -154,6 +154,8 @@ settings-remote-drop-destination-description = リモートターミナルへドsettings-notifications-heading = 通知settings-notification-sounds = 通知音settings-notification-sounds-description = スレッドが完了したとき、または入力待ちになったときに短い音を鳴らします。+settings-system-notifications = システム通知+settings-system-notifications-description = ThinkTerm がバックグラウンドにあるとき、スレッドが完了した・対応待ちになった・エラーで止まったときに通知します。settings-remote-update-keep-sessions = リモートサーバー更新時にセッションを維持settings-remote-update-keep-sessions-description = 実行中のサーバーは停止せず、ペインを新しいバージョンに引き継ぎます。実行中の処理は中断されません。settings-local-sessions-via-mux = ローカル端末をバックグラウンドのセッションサーバーに置く@@ -695,12 +697,32 @@ right-agents-state-working = 作業中right-agents-state-blocked = 入力待ちright-agents-state-idle = アイドルright-agents-state-unknown = 不明+right-agents-state-error = エラー+right-agents-state-done = 完了right-agents-none = エージェントは検出されていませんright-agents-detection-off = エージェント検出はオフです — 設定を開くright-agents-count-working = { $count } 件が作業中right-agents-count-blocked = { $count } 件が入力待ちright-agents-count-idle = { $count } 件が待機中right-agents-count-unknown = { $count } 件が不明+right-agents-count-error = { $count } 件がエラー+right-agents-more-subtasks = ほか { $count } 件+right-agents-subtasks = サブタスク { $count } 件+agent-kind-permission = 許可待ち+agent-kind-question = 質問+agent-kind-auth = サインイン+notification-thread-finished = 完了しました+notification-thread-needs-input = 対応待ち+notification-thread-error = エラーで停止しました+settings-agent-status-heading = 状態の表示+settings-agent-status-description = 説明+settings-agent-status-description-description = プログラムが何をしているか、何を終えたか、なぜ止まったか。+settings-agent-status-reason = 待っている理由+settings-agent-status-reason-description = 許可、回答、サインインのどれを待っているか。+settings-agent-status-progress = 進捗+settings-agent-status-progress-description = どこまで進んだかを、エージェントパネルのバーで表示します。+settings-agent-status-subtasks = サブタスク+settings-agent-status-subtasks-description = バックグラウンドタスクとサブエージェント。エージェントパネルでは 1 行にまとめ、クリックで一覧を開きます。settings-section-agents = エージェントsettings-agents-integrations-heading = 連携settings-integration-screen-active = PATH 上で見つかりました。状態は端末画面(スクリーンルール)から識別します。diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftlindex 80cc876d..c7b61e04 100644--- a/thinkterm-i18n/i18n/zh-CN.ftl+++ b/thinkterm-i18n/i18n/zh-CN.ftl@@ -154,6 +154,8 @@ settings-remote-drop-destination-description = 拖到远程终端的文件上传settings-notifications-heading = 通知settings-notification-sounds = 提示音settings-notification-sounds-description = Thread 完成或等待你输入时播放提示音。+settings-system-notifications = 系统通知+settings-system-notifications-description = ThinkTerm 在后台时,线程做完、等你处理或出错停下时发系统通知。settings-remote-update-keep-sessions = 更新远端 server 时保留会话settings-remote-update-keep-sessions-description = 运行中的 server 把 pane 交给新版本而不是停掉,里面跑的程序不会中断。settings-local-sessions-via-mux = 本地终端放在后台会话 server 里@@ -695,12 +697,32 @@ right-agents-state-working = 工作中right-agents-state-blocked = 等待输入right-agents-state-idle = 空闲right-agents-state-unknown = 未知+right-agents-state-error = 出错+right-agents-state-done = 已完成right-agents-none = 未检测到 Agentright-agents-detection-off = Agent 检测已关闭 — 打开设置right-agents-count-working = { $count } 个运行中right-agents-count-blocked = { $count } 个等待输入right-agents-count-idle = { $count } 个空闲right-agents-count-unknown = { $count } 个状态未知+right-agents-count-error = { $count } 个出错+right-agents-more-subtasks = 还有 { $count } 个+right-agents-subtasks = { $count } 个子任务+agent-kind-permission = 要权限+agent-kind-question = 要回答+agent-kind-auth = 要登录+notification-thread-finished = 已完成+notification-thread-needs-input = 等你处理+notification-thread-error = 出错停下了+settings-agent-status-heading = 状态显示+settings-agent-status-description = 说明+settings-agent-status-description-description = 程序在做什么、做完了什么,或者为什么停下。+settings-agent-status-reason = 等待原因+settings-agent-status-reason-description = 它在等你批权限、回答问题,还是登录。+settings-agent-status-progress = 进度+settings-agent-status-progress-description = 做到哪了,在 Agent 面板里显示成进度条。+settings-agent-status-subtasks = 子任务+settings-agent-status-subtasks-description = 后台任务和子 Agent,在 Agent 面板里折成一行,点开看列表。settings-section-agents = Agentsettings-agents-integrations-heading = 集成settings-integration-screen-active = 已在 PATH 中找到;状态通过其终端界面识别(屏幕规则)。diff --git a/thinkterm-proto/src/agent.rs b/thinkterm-proto/src/agent.rsindex 17a1386b..98317378 100644--- a/thinkterm-proto/src/agent.rs+++ b/thinkterm-proto/src/agent.rs@@ -15,6 +15,8 @@ pub enum AgentState {Blocked,Idle,Unknown,+ /// Stopped on a failure it reported itself (OSC 7501 `error`).+ Error,}#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]@@ -26,6 +28,8 @@ pub enum AgentEvidence {/// No rule matched and no fresh contract: the known-agent Idle/// fallback (never produces Blocked).Fallback,+ /// The program's own OSC 7501 report, which outranks everything else.+ Report,}#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]@@ -46,6 +50,85 @@ pub struct AgentStatus {/// defensively (hide from lists, fall back to native signals) but/// should not rely on ever observing it.pub ended: bool,+ /// What the program said about itself with OSC 7501, when it did.+ pub report: Option<ProgramReport>,+}++/// A program's own account of itself (OSC 7501), as the owning mux read it+/// from the pane: its root record and the records filed under it.+#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]+pub struct ProgramReport {+ pub state: ProgramReportState,+ /// Only while `Blocked`.+ pub kind: Option<ProgramBlockedKind>,+ /// 0 to 100; `None` is indeterminate.+ pub progress: Option<u8>,+ /// Machine-readable program name, such as `claude-code`.+ pub app: Option<String>,+ pub title: Option<String>,+ /// What it is doing, what it finished, or why it stopped.+ pub msg: Option<String>,+ /// Sub-tasks, in id order; at most [`ProgramReport::MAX_CHILDREN`].+ pub children: Vec<ProgramReportChild>,+}++#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]+pub struct ProgramReportChild {+ pub id: String,+ pub state: ProgramReportState,+ pub kind: Option<ProgramBlockedKind>,+ pub progress: Option<u8>,+ pub title: Option<String>,+ pub msg: Option<String>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]+pub enum ProgramReportState {+ Idle,+ Working,+ /// Finished, and nobody has looked at the result yet.+ Done,+ Blocked,+ Error,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]+pub enum ProgramBlockedKind {+ Permission,+ Question,+ Auth,+}++impl ProgramReport {+ /// The protocol lets a terminal keep hundreds of records; an agent's+ /// panel has room for this many, and every status change carries them.+ pub const MAX_CHILDREN: usize = 32;+ /// The protocol's own ceilings on decoded text and names.+ pub const MAX_TITLE_BYTES: usize = 192;+ pub const MAX_MSG_BYTES: usize = 2048;+ pub const MAX_NAME_BYTES: usize = 32;+ pub const MAX_ID_BYTES: usize = 128;++ /// Whether it holds a finished or failed result nobody has looked at+ /// yet -- its own or a sub-task's. What decides that a look at the pane+ /// must be passed on to the mux that keeps the records.+ pub fn has_unseen_result(&self) -> bool {+ let unseen = |state| matches!(state, ProgramReportState::Done | ProgramReportState::Error);+ unseen(self.state) || self.children.iter().any(|child| unseen(child.state))+ }++ pub fn within_budget(&self) -> bool {+ let text_fits = |title: &Option<String>, msg: &Option<String>| {+ title.as_ref().is_none_or(|t| t.len() <= Self::MAX_TITLE_BYTES)+ && msg.as_ref().is_none_or(|m| m.len() <= Self::MAX_MSG_BYTES)+ };+ text_fits(&self.title, &self.msg)+ && self.app.as_ref().is_none_or(|app| app.len() <= Self::MAX_NAME_BYTES)+ && self.children.len() <= Self::MAX_CHILDREN+ && self.children.iter().all(|child| {+ child.id.len() <= Self::MAX_ID_BYTES && text_fits(&child.title, &child.msg)+ })+ }}impl AgentStatus {@@ -56,5 +139,6 @@ impl AgentStatus {.session_id.as_ref().is_none_or(|id| id.len() <= wezterm_term::agent_contract::MAX_AGENT_SESSION_BYTES)+ && self.report.as_ref().is_none_or(ProgramReport::within_budget)}}diff --git a/thinkterm-proto/src/lib.rs b/thinkterm-proto/src/lib.rsindex 6b44d216..44f52eb3 100644--- a/thinkterm-proto/src/lib.rs+++ b/thinkterm-proto/src/lib.rs@@ -23,7 +23,10 @@ pub mod program;pub mod renderable;pub mod split;-pub use agent::{AgentEvidence, AgentState, AgentStatus};+pub use agent::{+ AgentEvidence, AgentState, AgentStatus, ProgramBlockedKind, ProgramReport, ProgramReportChild,+ ProgramReportState,+};pub use client::{ClientId, ClientInfo};pub use command::{CommandSpec, EnvVar};pub use keyassignment::{PaneDirection, ScrollbackEraseMode, SpawnTabDomain};diff --git a/thinkterm-web/src/agents.rs b/thinkterm-web/src/agents.rsindex 44ab7443..2f43eacd 100644--- a/thinkterm-web/src/agents.rs+++ b/thinkterm-web/src/agents.rs@@ -5,7 +5,9 @@use crate::tree::TreeModel;use serde::Serialize;use thinkterm_i18n::{tr, tr_args, FluentArgs};-use thinkterm_proto::{AgentState, PaneId, WindowId};+use thinkterm_proto::{+ AgentState, PaneId, ProgramBlockedKind, ProgramReportChild, ProgramReportState, WindowId,+};#[derive(Debug, Clone, PartialEq, Serialize)]pub struct AgentRow {@@ -22,6 +24,66 @@ pub struct AgentRow {pub place: String,/// The brand or fallback icon the page draws.pub icon: &'static str,+ /// What the program said about itself (OSC 7501): what it waits for,+ /// what it is doing or why it stopped, how far it got, its sub-tasks.+ pub kind: Option<String>,+ pub said: Option<String>,+ pub progress: Option<u8>,+ /// "7 sub-tasks · 5 working": the one line the sub-tasks fold into,+ /// as on the desktop; empty when there are none.+ pub subtasks_summary: String,+ /// Whether that line is open, listing them.+ pub subtasks_open: bool,+ /// While it is open: the sub-tasks listed, and how many more there are.+ pub subtasks: Vec<AgentSubtask>,+ pub more_subtasks: usize,+}++/// One of a program's sub-tasks, as the desktop's panel lists them.+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct AgentSubtask {+ pub state: &'static str,+ pub label: String,+}++/// Sub-tasks a row lists before it says how many more there are, as the+/// desktop's `AGENT_SUBTASKS_SHOWN`.+const SUBTASKS_SHOWN: usize = 5;++/// The line a row's sub-tasks fold into, worded as the desktop's panel+/// words it: how many, and how many of them are working.+fn subtasks_summary(children: &[ProgramReportChild]) -> String {+ if children.is_empty() {+ return String::new();+ }+ let count = |key: &str, n: usize| {+ let mut args = FluentArgs::new();+ args.set("count", n as i64);+ tr_args(key, &args)+ };+ let all = count("right-agents-subtasks", children.len());+ match children.iter().filter(|child| child.state == ProgramReportState::Working).count() {+ 0 => all,+ working => format!("{all} · {}", count("right-agents-count-working", working)),+ }+}++fn kind_label(kind: ProgramBlockedKind) -> String {+ tr(match kind {+ ProgramBlockedKind::Permission => "agent-kind-permission",+ ProgramBlockedKind::Question => "agent-kind-question",+ ProgramBlockedKind::Auth => "agent-kind-auth",+ })+}++fn report_state_name(state: ProgramReportState) -> &'static str {+ match state {+ ProgramReportState::Working => "working",+ ProgramReportState::Blocked => "blocked",+ ProgramReportState::Error => "error",+ ProgramReportState::Done => "done",+ ProgramReportState::Idle => "idle",+ }}/// One tab of the right panel's selector, as the desktop lists them@@ -165,17 +227,32 @@ fn state_key(state: AgentState) -> (&'static str, &'static str) {AgentState::Blocked => ("blocked", "right-agents-state-blocked"),AgentState::Idle => ("idle", "right-agents-state-idle"),AgentState::Unknown => ("unknown", "right-agents-state-unknown"),+ AgentState::Error => ("error", "right-agents-state-error"),}}/// The rows, sorted as the desktop sorts them: by place, agent, pane --/// never floating the current window, so a switch does not reorder them.-pub fn rows(tree: &TreeModel, current_window: WindowId, title_of: impl Fn(PaneId) -> Option<String>) -> Vec<AgentRow> {+/// `open` says whose sub-task lists are open; the rest stay folded.+pub fn rows(+ tree: &TreeModel,+ current_window: WindowId,+ title_of: impl Fn(PaneId) -> Option<String>,+ open: impl Fn(PaneId) -> bool,+) -> Vec<AgentRow> {let mut rows: Vec<AgentRow> = tree.agent_entries().map(|(pane, agent_id, state, title)| {let (place, window) = tree.place_of_pane(pane);- let (state_name, state_label) = state_key(state);+ let report = tree.agent_report(pane);+ // A result nobody has seen is its own word, not merely idle.+ let (state_name, state_label) = match (state, report.map(|r| r.state)) {+ (AgentState::Idle, Some(ProgramReportState::Done)) => ("done", "right-agents-state-done"),+ _ => state_key(state),+ };+ let children = report.map(|r| r.children.as_slice()).unwrap_or_default();+ let subtasks_open = !children.is_empty() && open(pane);+ let listed = if subtasks_open { children } else { &[] };AgentRow {pane,window,@@ -187,6 +264,26 @@ pub fn rows(tree: &TreeModel, current_window: WindowId, title_of: impl Fn(PaneIdplace,icon: icon(agent_id),agent_id: agent_id.to_string(),+ kind: report.and_then(|r| r.kind).map(kind_label),+ said: report.and_then(|r| r.msg.clone()),+ progress: report.and_then(|r| r.progress),+ subtasks_summary: subtasks_summary(children),+ subtasks_open,+ subtasks: listed+ .iter()+ .take(SUBTASKS_SHOWN)+ .map(|child| {+ let name = child.title.as_deref().or(child.msg.as_deref()).unwrap_or(&child.id);+ AgentSubtask {+ state: report_state_name(child.state),+ label: match child.kind {+ Some(kind) => format!("{name} · {}", kind_label(kind)),+ None => name.to_string(),+ },+ }+ })+ .collect(),+ more_subtasks: listed.len().saturating_sub(SUBTASKS_SHOWN),}}).collect();@@ -204,7 +301,10 @@ pub fn rows(tree: &TreeModel, current_window: WindowId, title_of: impl Fn(PaneId/// else "No agents detected".pub fn summary(rows: &[AgentRow]) -> String {let count = |s: &str| rows.iter().filter(|r| r.state == s).count();- let (working, blocked, idle, unknown) = (count("working"), count("blocked"), count("idle"), count("unknown"));+ // A finished result is idle to the counts, as the desktop's tally has it.+ let (working, blocked, idle, unknown) =+ (count("working"), count("blocked"), count("idle") + count("done"), count("unknown"));+ let errored = count("error");if rows.is_empty() {return tr("right-agents-none");}@@ -220,6 +320,9 @@ pub fn summary(rows: &[AgentRow]) -> String {if blocked > 0 {parts.push(part("right-agents-count-blocked", blocked));}+ if errored > 0 {+ parts.push(part("right-agents-count-error", errored));+ }if parts.is_empty() {if idle > 0 {parts.push(part("right-agents-count-idle", idle));@@ -247,6 +350,13 @@ mod tests {state_label: String::new(),place: place.into(),icon: icon(agent),+ kind: None,+ said: None,+ progress: None,+ subtasks_summary: String::new(),+ subtasks_open: false,+ subtasks: Vec::new(),+ more_subtasks: 0,}}@@ -258,6 +368,55 @@ mod tests {assert_eq!(icon("gemini"), "bot");}+ /// Sub-tasks fold to the one line that counts them, as on the desktop;+ /// only an open list carries them.+ #[test]+ fn sub_tasks_fold_to_one_line_until_opened() {+ use thinkterm_proto::{AgentEvidence, AgentStatus, ProgramReport};+ let child = |n: usize, state| ProgramReportChild {+ id: format!("task-{n}"),+ state,+ kind: None,+ progress: None,+ title: None,+ msg: None,+ };+ let mut children: Vec<_> = (0..5).map(|n| child(n, ProgramReportState::Working)).collect();+ children.extend((5..7).map(|n| child(n, ProgramReportState::Done)));+ let mut tree = TreeModel::default();+ tree.apply_agent(+ 5,+ Some(&AgentStatus {+ agent_id: "claude".into(),+ state: AgentState::Working,+ evidence: AgentEvidence::Report,+ session_id: None,+ since_unix: 0,+ ended: false,+ report: Some(ProgramReport {+ state: ProgramReportState::Working,+ kind: None,+ progress: None,+ app: None,+ title: None,+ msg: None,+ children,+ }),+ }),+ );++ let folded = rows(&tree, 1, |_| None, |_| false).remove(0);+ assert!(!folded.subtasks_open);+ assert!(folded.subtasks.is_empty() && folded.more_subtasks == 0);+ let line = &folded.subtasks_summary;+ assert!(line.contains('7') && line.contains('5'), "{line}");++ let open = rows(&tree, 1, |_| None, |pane| pane == 5).remove(0);+ assert!(open.subtasks_open);+ assert_eq!((open.subtasks.len(), open.more_subtasks), (5, 2));+ assert_eq!(open.subtasks_summary, folded.subtasks_summary);+ }+#[test]fn the_summary_counts_like_the_desktop() {assert_eq!(summary(&[]), "No agents detected");@@ -265,5 +424,10 @@ mod tests {assert_eq!(summary(&rows), "2 working · 1 needs input");let quiet = vec![row(1, "claude", "idle", "a"), row(2, "codex", "unknown", "a"), row(3, "pi", "unknown", "a")];assert_eq!(summary(&quiet), "1 idle · 2 unknown");+ // A finished result counts as idle; an error is named.+ let done = vec![row(1, "claude", "done", "a")];+ assert_eq!(summary(&done), "1 idle");+ let failed = vec![row(1, "claude", "error", "a"), row(2, "codex", "working", "a")];+ assert_eq!(summary(&failed), "1 working · 1 error");}}diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rsindex a0aaef34..107a06f2 100644--- a/thinkterm-web/src/app.rs+++ b/thinkterm-web/src/app.rs@@ -442,6 +442,10 @@ pub struct Inner<P: Platform, L: Link> {/// whether the page has the panel up at all.right_panel: String,right_panel_shown: bool,+ /// Agents whose sub-task list is open in the Agents panel; folded is+ /// the default, as on the desktop. Each look at the panel drops the+ /// ones with no sub-tasks left.+ open_subtasks: std::collections::HashSet<PaneId>,/// The plugin panel on show in the right panel, while one is.plugin_panel: Option<crate::plugin_panel::PanelModel>,/// What the page last said of the room a plugin panel has: its size,@@ -715,6 +719,7 @@ impl<P: Platform, L: Link> App<P, L> {claim: Claim::Idle,right_panel: "agents".to_string(),right_panel_shown: false,+ open_subtasks: Default::default(),plugin_panel: None,plugin_panel_env: None,plugin_extended: None,@@ -816,6 +821,8 @@ impl<P: Platform, L: Link> App<P, L> {pub fn visibility_changed(self: &Rc<Self>, visible: bool) {self.animations_visible.set(visible);if visible {+ // Coming back to the page is looking at the pane on show.+ self.mark_focused_program_status_seen();self.request_frame();} else {self.schedule_animation(None);@@ -1460,6 +1467,8 @@ impl<P: Platform, L: Link> App<P, L> {drop(inner);self.inner.borrow_mut().tree.apply_agent(pane_id, status.as_ref());Self::render_strip(&self.inner.borrow());+ // A result that lands in the pane on show is seen as it lands.+ self.mark_seen(pane_id);}Pdu::ForegroundProgramChanged(codec::ForegroundProgramChanged { pane_id, program }) => {drop(inner);@@ -2424,7 +2433,12 @@ impl<P: Platform, L: Link> App<P, L> {pub fn focus_pane(self: &Rc<Self>, pane_id: PaneId, advise: bool) {let link = {let mut inner = self.inner.borrow_mut();- if !inner.panes.contains_key(&pane_id) || inner.focused_pane == pane_id {+ if !inner.panes.contains_key(&pane_id) {+ return;+ }+ if inner.focused_pane == pane_id {+ drop(inner);+ self.mark_seen(pane_id);return;}inner.focused_pane = pane_id;@@ -2440,6 +2454,43 @@ impl<P: Platform, L: Link> App<P, L> {if advise {Self::advise_focus(&self.platform, link.0, pane_id, link.1);}+ self.mark_seen(pane_id);+ }++ /// A machine or tab has come on show, including one whose focus stayed put.+ pub fn mark_focused_program_status_seen(self: &Rc<Self>) {+ let focused = self.inner.borrow().focused_pane;+ self.mark_seen(focused);+ }++ /// Tell the server a pane has been looked at, when a program in it left+ /// a finished or failed result: only the mux that owns the pane keeps+ /// those, and it hears of a look no other way. Sent and forgotten.+ fn mark_seen(self: &Rc<Self>, pane_id: PaneId) {+ if self.retired.get() || !self.animations_visible.get() || !self.platform.shown() {+ return;+ }+ let link = {+ let inner = self.inner.borrow();+ if inner.focused_pane != pane_id+ || !inner.panes.contains_key(&pane_id)+ || !inner.tree.has_unseen_result(pane_id)+ {+ return;+ }+ inner.link.clone()+ };+ self.platform.spawn(Box::pin(async move {+ let pdu = Pdu::MarkProgramStatusSeen(codec::MarkProgramStatusSeen { pane_id });+ if let Err(err) = thinkterm_session::host::request(&link, pdu, |p| match p {+ Pdu::UnitResponse(_) => Ok(()),+ other => Err(other),+ })+ .await+ {+ log::warn!("result not marked seen: {err:#}");+ }+ }));}/// Tell the server (and so the desktop) which pane has the focus.@@ -3116,7 +3167,7 @@ impl<P: Platform, L: Link> App<P, L> {match agents {Ok(entries) => {let mut inner = app.inner.borrow_mut();- inner.tree.agents.clear();+ inner.tree.clear_agents();for e in entries {inner.tree.apply_agent(e.pane_id, Some(&e.status));inner.tree.record_agent_details(e.pane_id, &e.status.agent_id, &e.title);@@ -3124,6 +3175,7 @@ impl<P: Platform, L: Link> App<P, L> {}Err(err) => log::warn!("fetching agent statuses: {err:#}"),}+ app.mark_focused_program_status_seen();let programs = thinkterm_session::host::request(&link, Pdu::GetForegroundPrograms(codec::GetForegroundPrograms {}), |p| match p {Pdu::GetForegroundProgramsResponse(r) => Ok(r.programs),other => Err(other),@@ -3733,6 +3785,7 @@ impl<P: Platform, L: Link> App<P, L> {Self::render_strip(&inner);(fresh, changed, first_layout)};+ self.mark_focused_program_status_seen();// A pane's first push comes when something asks after it: one// liveness poll each, and the answer is not waited for.self.sync_frame_control();@@ -4268,10 +4321,20 @@ impl<P: Platform, L: Link> App<P, L> {/// The Agents panel: every pane an agent runs in, and the summary line.pub fn agents_view(&self) -> crate::agents::AgentsView {- let inner = self.inner.borrow();- let rows = crate::agents::rows(&inner.tree, inner.window_id, |pane| {- inner.panes.get(&pane).map(|c| crate::navbar::display_title(&c.title).0)- });+ let mut inner = self.inner.borrow_mut();+ let inner = &mut *inner;+ // An open list lasts as long as its sub-tasks: the next batch+ // starts folded, as on the desktop.+ let tree = &inner.tree;+ inner+ .open_subtasks+ .retain(|pane| tree.agent_report(*pane).is_some_and(|r| !r.children.is_empty()));+ let rows = crate::agents::rows(+ &inner.tree,+ inner.window_id,+ |pane| inner.panes.get(&pane).map(|c| crate::navbar::display_title(&c.title).0),+ |pane| inner.open_subtasks.contains(&pane),+ );let summary = crate::agents::summary(&rows);let tabs = Self::panel_tabs(&inner);let labeled = crate::agents::labeled(&tabs);@@ -5265,6 +5328,15 @@ impl<P: Platform, L: Link> App<P, L> {true}+ /// Open or fold an agent's sub-task list in the Agents panel.+ pub fn agent_toggle_subtasks(&self, pane: PaneId) -> bool {+ let mut inner = self.inner.borrow_mut();+ if !inner.open_subtasks.remove(&pane) {+ inner.open_subtasks.insert(pane);+ }+ true+ }+/// Bring an agent's pane on show: switch to it here, or open the/// thread that holds it when it is in another window.pub fn agent_reveal(self: &Rc<Self>, pane: PaneId) -> bool {diff --git a/thinkterm-web/src/bridge.rs b/thinkterm-web/src/bridge.rsindex f64fd7ab..358955b0 100644--- a/thinkterm-web/src/bridge.rs+++ b/thinkterm-web/src/bridge.rs@@ -84,6 +84,7 @@ impl Client {pub fn set_shown(&self, shown: bool) {self.app.platform.set_shown(shown);if shown {+ self.app.mark_focused_program_status_seen();self.app.resize();self.app.request_frame();// Listed again now, so a tab it shows is claimed as on any@@ -152,6 +153,11 @@ impl Client {self.app.agent_reveal(pane as usize)}+ /// Open or fold an agent's sub-task list.+ pub fn agent_toggle_subtasks(&self, pane: u32) -> bool {+ self.app.agent_toggle_subtasks(pane as usize)+ }+/// Show the right panel's tab `id` ("agents", "snippets"). False for/// one the page does not offer.pub fn set_right_panel(&self, id: String) -> bool {diff --git a/thinkterm-web/src/tree.rs b/thinkterm-web/src/tree.rsindex 65e81831..303466b5 100644--- a/thinkterm-web/src/tree.rs+++ b/thinkterm-web/src/tree.rs@@ -10,7 +10,7 @@use codec::{ListPanesResponse, ThinkTermSessionState, ThinkTermSessionThread, ThinkTermTree, TreeOp};use std::collections::{HashMap, HashSet};-use thinkterm_proto::{AgentState, AgentStatus, PaneId, TabId, WindowId};+use thinkterm_proto::{AgentState, AgentStatus, PaneId, ProgramReport, TabId, WindowId};#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]pub enum Status {@@ -107,6 +107,8 @@ pub struct TreeModel {agent_details: HashMap<PaneId, (String, String)>,/// Panes whose agent reported its own end.agents_ended: HashSet<PaneId>,+ /// What each pane's program said about itself (OSC 7501), when it did.+ agent_reports: HashMap<PaneId, ProgramReport>,pub collapsed: HashSet<String>,pub archived_open: bool,/// The Space the sidebar shows; the first one until chosen.@@ -176,15 +178,48 @@ impl TreeModel {} else {self.agents_ended.remove(&pane_id);}+ match &s.report {+ Some(report) => {+ self.agent_reports.insert(pane_id, report.clone());+ }+ None => {+ self.agent_reports.remove(&pane_id);+ }+ }}None => {self.agents.remove(&pane_id);self.agent_details.remove(&pane_id);self.agents_ended.remove(&pane_id);+ self.agent_reports.remove(&pane_id);}}}+ /// What a pane's program said about itself, when it did.+ pub fn agent_report(&self, pane_id: PaneId) -> Option<&ProgramReport> {+ self.agent_reports.get(&pane_id)+ }++ /// Whether a program in the pane left a finished or failed result+ /// nobody has seen yet.+ pub fn has_unseen_result(&self, pane_id: PaneId) -> bool {+ self.agents.contains_key(&pane_id)+ && self+ .agent_reports+ .get(&pane_id)+ .is_some_and(ProgramReport::has_unseen_result)+ }++ /// Forget every agent, before a fresh list replaces them: what a pane+ /// lost while the page was away must not linger in any of the maps.+ pub fn clear_agents(&mut self) {+ self.agents.clear();+ self.agent_details.clear();+ self.agents_ended.clear();+ self.agent_reports.clear();+ }+/// The agent a pane runs, by id, until it reports its own end: what/// picks the pane's tab icon, as on the desktop.pub fn agent_id(&self, pane_id: PaneId) -> Option<&str> {@@ -347,7 +382,9 @@ impl TreeModel {let mut working = false;for state in agents {match state {- AgentState::Blocked => return Status::NeedsAttention,+ // A program stopped on an error wants a look as much as one+ // that asked something, as the desktop's sidebar has it.+ AgentState::Blocked | AgentState::Error => return Status::NeedsAttention,AgentState::Working => working = true,_ => {}}@@ -905,6 +942,34 @@ mod tests {assert_eq!(m.selected_thread(99, "ws-b"), Some("b"));}+ #[test]+ fn a_resync_forgets_what_the_agents_reported() {+ use thinkterm_proto::{AgentEvidence, ProgramReport, ProgramReportState};+ let mut m = TreeModel::default();+ let status = AgentStatus {+ agent_id: "claude".into(),+ state: AgentState::Idle,+ evidence: AgentEvidence::Report,+ session_id: None,+ since_unix: 0,+ ended: false,+ report: Some(ProgramReport {+ state: ProgramReportState::Done,+ kind: None,+ progress: None,+ app: None,+ title: None,+ msg: None,+ children: vec![],+ }),+ };+ m.apply_agent(5, Some(&status));+ assert!(m.has_unseen_result(5));+ m.clear_agents();+ assert!(!m.has_unseen_result(5));+ assert!(m.agent_report(5).is_none());+ }+#[test]fn status_is_the_worst_of_the_panes_and_the_server_s_word() {let mut m = TreeModel::default();@@ -914,6 +979,9 @@ mod tests {assert_eq!(m.status_of(&t), Status::Running);m.agents.insert(11, AgentState::Blocked);assert_eq!(m.status_of(&t), Status::NeedsAttention);+ // A program stopped on an error wants a look as well.+ m.agents.insert(11, AgentState::Error);+ assert_eq!(m.status_of(&t), Status::NeedsAttention);m.agents.clear();t.work_status = ThinkTermSessionWorkStatus::FinishedUnseen;assert_eq!(m.status_of(&t), Status::Done);diff --git a/thinkterm-web/src/views.rs b/thinkterm-web/src/views.rsindex ef869a73..865cb75e 100644--- a/thinkterm-web/src/views.rs+++ b/thinkterm-web/src/views.rs@@ -286,7 +286,7 @@ pub fn strings() -> std::collections::BTreeMap<&'static str, String> {/// Labels with a number in them: sent with `COUNT_SLOT` where it goes, for/// the page to fill in (`sCount` in client.svelte.ts).-pub const COUNTED_KEYS: &[&str] = &["ssh-system-hosts"];+pub const COUNTED_KEYS: &[&str] = &["ssh-system-hosts", "right-agents-more-subtasks"];pub const COUNT_SLOT: &str = "{count}";#[cfg(test)]diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rsindex c8e38b04..3d4982b1 100644--- a/wezterm-client/src/client.rs+++ b/wezterm-client/src/client.rs@@ -2739,6 +2739,7 @@ impl Client {rpc!(write_to_pane, WriteToPane, UnitResponse);rpc!(send_paste, SendPaste, UnitResponse);rpc!(key_down, SendKeyDown, UnitResponse);+ rpc!(mark_program_status_seen, MarkProgramStatusSeen, UnitResponse);rpc!(mouse_event, SendMouseEvent, UnitResponse);rpc!(resize, Resize, UnitResponse);rpc!(set_zoomed, SetPaneZoomed, UnitResponse);diff --git a/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rsindex 232dcf57..2a8adb8a 100644--- a/wezterm-client/src/pane/clientpane.rs+++ b/wezterm-client/src/pane/clientpane.rs@@ -823,6 +823,13 @@ impl Pane for ClientPane {self.agent_status.lock().clone()}+ fn agent_status_summary(&self) -> Option<mux::agent_status::AgentStatusSummary> {+ self.agent_status+ .lock()+ .as_ref()+ .map(mux::agent_status::AgentStatusSummary::of)+ }+fn foreground_program(&self) -> Option<thinkterm_proto::ForegroundProgram> {self.foreground_program.lock().clone()}@@ -1130,6 +1137,29 @@ impl Pane for ClientPane {}}+ fn program_status_seen(&self) {+ // The records live with the mux that owns the pane; tell it only+ // when there is a result to retire.+ let unseen = self+ .agent_status+ .lock()+ .as_ref()+ .and_then(|status| status.report.as_ref())+ .is_some_and(thinkterm_proto::ProgramReport::has_unseen_result);+ if !unseen || self.client.remote_tab_input_is_blocked() {+ return;+ }+ let client = Arc::clone(&self.client);+ let pane_id = self.remote_pane_id;+ promise::spawn::spawn(async move {+ client+ .client+ .mark_program_status_seen(codec::MarkProgramStatusSeen { pane_id })+ .await+ })+ .detach();+ }+fn is_remote_mirror(&self) -> bool {true}diff --git a/wezterm-gui/src/agent_status/mod.rs b/wezterm-gui/src/agent_status/mod.rsindex d0e787e9..3ffc19ff 100644--- a/wezterm-gui/src/agent_status/mod.rs+++ b/wezterm-gui/src/agent_status/mod.rs@@ -12,7 +12,9 @@//! double detection structurally impossible — a pane's status has exactly//! one producer, the mux that owns it. Do not widen this surface.-pub(crate) use thinkterm_proto::{AgentEvidence, AgentState};+pub(crate) use thinkterm_proto::{+ AgentEvidence, AgentState, ProgramBlockedKind, ProgramReport, ProgramReportState,+};use crate::termwindow::ui::icons::BrandIcon;use crate::ui::icons::SvgIcon;@@ -40,6 +42,9 @@ pub enum AgentPanelAction {/// and pane, then activates the backing thread (workspace switch,/// window brought forward) via the left sidebar's activation path.RevealElsewhere(PaneId),+ /// Open or fold the sub-task list of the agent in this pane. Folded+ /// is the default: one line that counts them.+ ToggleSubtasks(PaneId),}/// Snapshot of one agent pane for the Agents panel.@@ -62,6 +67,10 @@ pub(crate) struct AgentPaneStatus {/// workspace string. Resolved once per snapshot: the paint loop must/// not walk the thread store per row per frame.pub place: String,+ /// The workspace the pane belongs to, as the thread store names it.+ pub workspace: String,+ /// What the program said about itself with OSC 7501, when it did.+ pub report: Option<ProgramReport>,/// Unix seconds when `state` last changed, on the detecting host's/// clock (approximate across hosts).#[allow(dead_code)]@@ -111,7 +120,9 @@ pub(crate) fn agent_work_status(pane: &dyn Pane) -> Option<WorkspaceThreadWorkSt}Some(match status.state {AgentState::Working => WorkspaceThreadWorkStatus::Running,- AgentState::Blocked => WorkspaceThreadWorkStatus::NeedsAttention,+ // A program stopped on an error wants a look as much as one that+ // asked a question; the sidebar tells the two apart by colour.+ AgentState::Blocked | AgentState::Error => WorkspaceThreadWorkStatus::NeedsAttention,AgentState::Idle | AgentState::Unknown => WorkspaceThreadWorkStatus::Idle,})}@@ -120,7 +131,8 @@ pub(crate) fn agent_work_status(pane: &dyn Pane) -> Option<WorkspaceThreadWorkSt/// every window's every tab per frame is wasted work when nothing/// changed. Status changes call [`invalidate_agent_pane_cache`], so the/// TTL only bounds staleness of titles/workspaces.-static AGENT_PANES_CACHE: Mutex<Option<(Instant, Vec<AgentPaneStatus>)>> = Mutex::new(None);+static AGENT_PANES_CACHE: Mutex<Option<(Instant, std::sync::Arc<Vec<AgentPaneStatus>>)>> =+ Mutex::new(None);const AGENT_PANES_TTL: Duration = Duration::from_millis(200);/// Called from the AgentStatusChanged repaint path so a state change is@@ -135,10 +147,16 @@ pub(crate) fn invalidate_agent_pane_cache() {/// agent status — locally detected or mirrored from a remote server —/// minus sessions that reported their own end.pub(crate) fn list_agent_panes() -> Vec<AgentPaneStatus> {+ agent_panes().as_ref().clone()+}++/// The snapshot behind [`list_agent_panes`], shared rather than copied:+/// for the callers that only look.+fn agent_panes() -> std::sync::Arc<Vec<AgentPaneStatus>> {if let Ok(guard) = AGENT_PANES_CACHE.lock() {if let Some((at, cached)) = guard.as_ref() {if at.elapsed() < AGENT_PANES_TTL {- return cached.clone();+ return std::sync::Arc::clone(cached);}}}@@ -191,16 +209,139 @@ pub(crate) fn list_agent_panes() -> Vec<AgentPaneStatus> {title,window_id,place,+ workspace,+ report: status.report,since_unix: status.since_unix,})}).collect();+ let panes = std::sync::Arc::new(panes);if let Ok(mut slot) = AGENT_PANES_CACHE.lock() {- *slot = Some((Instant::now(), panes.clone()));+ *slot = Some((Instant::now(), std::sync::Arc::clone(&panes)));}panes}+/// The agents running in one workspace -- one thread's panes -- that+/// `keep` accepts, in display order. Served from the panel snapshot, and+/// only those kept are copied.+pub(crate) fn agents_in_workspace(+ workspace: &str,+ keep: impl Fn(&AgentPaneStatus) -> bool,+) -> Vec<AgentPaneStatus> {+ let mut agents: Vec<AgentPaneStatus> = agent_panes()+ .iter()+ .filter(|agent| agent.workspace == workspace && keep(agent))+ .cloned()+ .collect();+ sort_for_display(&mut agents);+ agents+}++/// Whether some agent in a workspace satisfies `test`, copying nothing:+/// asked per sidebar row per frame.+pub(crate) fn any_agent_in_workspace(+ workspace: &str,+ test: impl Fn(&AgentPaneStatus) -> bool,+) -> bool {+ agent_panes()+ .iter()+ .any(|agent| agent.workspace == workspace && test(agent))+}++/// Whether a pane holds a finished or failed result its program reported+/// that nobody has seen yet.+pub(crate) fn has_unseen_result(pane: &dyn Pane) -> bool {+ pane.agent_status_summary()+ .is_some_and(|summary| summary.unseen_result)+}++/// The state a panel row, a tab or a card shows for an agent: its own+/// report's finer word where it gave one -- `done` is a result waiting to be+/// seen, not merely idle.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum ShownState {+ Working,+ Blocked,+ Error,+ Done,+ Idle,+ Unknown,+}++impl AgentPaneStatus {+ pub(crate) fn shown_state(&self) -> ShownState {+ match self.state {+ AgentState::Working => ShownState::Working,+ AgentState::Blocked => ShownState::Blocked,+ AgentState::Error => ShownState::Error,+ AgentState::Unknown => ShownState::Unknown,+ AgentState::Idle => match self.report.as_ref().map(|report| report.state) {+ Some(ProgramReportState::Done) => ShownState::Done,+ _ => ShownState::Idle,+ },+ }+ }+}++/// One line on why a program is waiting, failed or what it finished --+/// the reason the bell, a card and a notification give -- shaped by the+/// user's choice of what to show. `None` when there is nothing to say.+pub(crate) fn reason_line(agent: &AgentPaneStatus) -> Option<String> {+ let report = agent.report.as_ref()?;+ let show = crate::native_settings::agent_status_display();+ let kind = report+ .kind+ .filter(|_| show.reason)+ .map(|kind| crate::i18n::tr(blocked_kind_key(kind)));+ let msg = report.msg.clone().filter(|_| show.description);+ match (kind, msg) {+ (Some(kind), Some(msg)) => Some(format!("{kind} · {msg}")),+ (Some(text), None) | (None, Some(text)) => Some(text),+ (None, None) => None,+ }+}++/// Why a thread wants a look, in its most pressing program's own words --+/// an error before a wait before a finished result. For the bell's list and+/// the system notification; `None` when no program in it said anything.+pub(crate) fn thread_reason(thread_id: &str) -> Option<String> {+ workspace_reason(&crate::workspace_threads::thread_workspace_name(thread_id)?)+}++/// [`thread_reason`], for the thread a workspace backs.+pub(crate) fn workspace_reason(workspace: &str) -> Option<String> {+ /// Long enough for a command line, short enough for a menu.+ const MAX_CHARS: usize = 80;+ let rank = |agent: &AgentPaneStatus| match agent.shown_state() {+ ShownState::Error => 0,+ ShownState::Blocked => 1,+ ShownState::Done => 2,+ _ => 3,+ };+ // The most pressing agent that said something: one that did not --+ // waiting by the look of its screen alone -- must not silence another+ // that did.+ let mut agents = agents_in_workspace(workspace, |agent| rank(agent) < 3);+ agents.sort_by_key(|agent| rank(agent));+ let reason = agents.iter().find_map(reason_line)?;+ Some(if reason.chars().count() > MAX_CHARS {+ let mut cut: String = reason.chars().take(MAX_CHARS - 1).collect();+ cut.push('…');+ cut+ } else {+ reason+ })+}++pub(crate) fn blocked_kind_key(kind: ProgramBlockedKind) -> &'static str {+ match kind {+ ProgramBlockedKind::Permission => "agent-kind-permission",+ ProgramBlockedKind::Question => "agent-kind-question",+ ProgramBlockedKind::Auth => "agent-kind-auth",+ }+}+/// Display order for the Agents panel: stable, and independent of which/// Space is frontmost. An earlier version floated the active workspace's/// rows to the top, which meant every Space switch reshuffled the list —@@ -571,10 +712,45 @@ mod tests {title: String::new(),window_id: None,place: place.to_string(),+ workspace: String::new(),+ report: None,since_unix: 0,}}+ /// A program's own report decides what the row says: `done` is a result+ /// to look at, not idle, and the reason leads with what it waits for.+ #[test]+ fn a_report_names_the_state_and_the_reason() {+ use thinkterm_proto::ProgramReport;+ let mut agent = row("alpha", "claude", 1);+ assert_eq!(agent.shown_state(), super::ShownState::Idle);+ assert_eq!(super::reason_line(&agent), None);++ let report = |state, kind, msg: Option<&str>| ProgramReport {+ state,+ kind,+ progress: None,+ app: Some("claude-code".to_string()),+ title: None,+ msg: msg.map(str::to_string),+ children: Vec::new(),+ };+ agent.report = Some(report(super::ProgramReportState::Done, None, Some("Fixed it")));+ assert_eq!(agent.shown_state(), super::ShownState::Done);+ assert_eq!(super::reason_line(&agent).as_deref(), Some("Fixed it"));++ agent.state = super::AgentState::Blocked;+ agent.report = Some(report(+ super::ProgramReportState::Blocked,+ Some(super::ProgramBlockedKind::Permission),+ Some("Bash: npm test"),+ ));+ assert_eq!(agent.shown_state(), super::ShownState::Blocked);+ let reason = super::reason_line(&agent).unwrap();+ assert!(reason.ends_with(" · Bash: npm test"), "{}", reason);+ }+/// The panel order must not depend on which Space is frontmost:/// switching Spaces used to float that workspace's rows to the top,/// and the reshuffle read as agents changing state.diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rsindex 4e2011fb..80c80b55 100644--- a/wezterm-gui/src/native_settings.rs+++ b/wezterm-gui/src/native_settings.rs@@ -660,6 +660,8 @@ pub(crate) struct NativeChromeSettings {/// Agents panel. Absent means on -- it was off by default while the/// detection was new, and is a panel toggle like the three above now.pub(crate) agent_panel_enabled: Option<bool>,+ /// What is shown of the state programs report about themselves.+ pub(crate) agent_status_display: NativeAgentStatusDisplay,/// The panels plugins add to the right sidebar, as the plugin host last/// listed them (`plugins::follow_panels`): offered from the start,/// before the host is asked.@@ -772,6 +774,33 @@ impl Default for NativeWindowSettings {}}++/// What the sidebar's thread cards, the bell and the Agents panel show of+/// the state programs report about themselves (OSC 7501). All of it, unless+/// the user turned a part off in Settings › Agents.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]+#[serde(default)]+pub(crate) struct NativeAgentStatusDisplay {+ /// What it is doing, what it finished, or why it stopped.+ pub(crate) description: bool,+ /// Whether it waits for a permission, an answer or a sign-in.+ pub(crate) reason: bool,+ pub(crate) progress: bool,+ /// Background tasks and sub-agents, in the Agents panel.+ pub(crate) subtasks: bool,+}++impl Default for NativeAgentStatusDisplay {+ fn default() -> Self {+ Self {+ description: true,+ reason: true,+ progress: true,+ subtasks: true,+ }+ }+}+pub(crate) const DEFAULT_REMOTE_SFTP_IDLE_MINUTES: u32 = 15;#[derive(Debug, Clone, Deserialize, Serialize)]@@ -789,6 +818,9 @@ pub(crate) struct NativeWorkspaceSettings {/// Play a short sound when a thread you are not watching finishes, or when/// one starts waiting on you.pub(crate) notification_sounds_enabled: bool,+ /// While ThinkTerm is in the background, tell the system when a thread+ /// finishes, starts waiting on you, or stops on an error.+ pub(crate) system_notifications_enabled: bool,/// Updating a remote mux server hands its sessions to the new version/// instead of stopping it; off, the update asks whether to stop it.pub(crate) remote_update_keeps_sessions: bool,@@ -805,6 +837,7 @@ impl Default for NativeWorkspaceSettings {remote_download_directory: String::new(),remote_drop_destination: String::new(),notification_sounds_enabled: true,+ system_notifications_enabled: true,remote_update_keeps_sessions: true,// Preserve the behavior of older settings files without this field.// Fresh installs enable it in ThinkTermNativeSettings::for_new_install.@@ -2327,6 +2360,16 @@ pub(crate) fn notification_sounds_enabled() -> bool {load().workspaces.notification_sounds_enabled}+pub(crate) fn system_notifications_enabled() -> bool {+ load_shared().workspaces.system_notifications_enabled+}++/// What is shown of programs' own status reports. `load_shared`: asked+/// while painting.+pub(crate) fn agent_status_display() -> NativeAgentStatusDisplay {+ load_shared().chrome.agent_status_display+}+pub(crate) fn remote_update_keeps_sessions() -> bool {load().workspaces.remote_update_keeps_sessions}diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex b080fd49..9b2738a0 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -1958,6 +1958,74 @@ pub fn tooltip_left_aligns(item_type: &UIItemType) -> bool {)}+/// The window holding the keyboard focus, if a ThinkTerm window does.+/// Held by the window's `space_owner_id`: its mux window id changes with+/// every thread or Space it switches to, and the holder must still match+/// when that window loses focus or goes away.+static FOCUSED_WINDOW: parking_lot::Mutex<Option<u64>> = parking_lot::Mutex::new(None);++impl TermWindow {+ /// The pane in front of someone has been seen. Whenever the active pane+ /// of a focused window changes -- a click, a tab or thread switch, a+ /// pane closing beside it -- or the window regains focus, retire the+ /// results its programs left. Every one of those shows up as a paint;+ /// focus alone does not count, for code moves it with nobody looking.+ pub(crate) fn note_active_pane_seen(&mut self) {+ if self.focused.is_none() {+ return;+ }+ let Some(pane) = self.get_active_pane_no_overlay() else {+ return;+ };+ if self.seen_active_pane == Some(pane.pane_id()) {+ return;+ }+ self.seen_active_pane = Some(pane.pane_id());+ if crate::agent_status::has_unseen_result(pane.as_ref()) {+ pane.program_status_seen();+ }+ }+}++/// Whether someone is looking at ThinkTerm: a system notification about a+/// thread is for when nobody is.+pub(crate) fn app_has_focus() -> bool {+ FOCUSED_WINDOW.lock().is_some()+}++/// The agents a thread row's hover card lists: those in the thread's+/// workspace that are up to something. Empty means the row gets no card.+pub(crate) fn thread_card_agents(item_type: &UIItemType) -> Vec<crate::agent_status::AgentPaneStatus> {+ let UIItemType::WorkspaceThread(thread_id) = item_type else {+ return Vec::new();+ };+ if !crate::agent_status::enabled() {+ return Vec::new();+ }+ let Some(workspace) = crate::workspace_threads::thread_workspace_name(thread_id) else {+ return Vec::new();+ };+ crate::agent_status::agents_in_workspace(&workspace, |agent| {+ agent.shown_state() != crate::agent_status::ShownState::Unknown+ })+}++/// Whether a thread row has a hover card to show: [`thread_card_agents`]+/// without copying the agents out, for the pointer's every move.+pub(crate) fn thread_has_card(item_type: &UIItemType) -> bool {+ let UIItemType::WorkspaceThread(thread_id) = item_type else {+ return false;+ };+ if !crate::agent_status::enabled() {+ return false;+ }+ crate::workspace_threads::thread_workspace_name(thread_id).is_some_and(|workspace| {+ crate::agent_status::any_agent_in_workspace(&workspace, |agent| {+ agent.shown_state() != crate::agent_status::ShownState::Unknown+ })+ })+}+/// The tag to show for an item whose own text cannot say enough: an icon-only/// button (no text at all) or a row whose label is cut to fit the sidebar./// `None` for everything that already reads in full.@@ -2066,6 +2134,51 @@ fn pane_output_needs_repaint(current: u64, presented: u64) -> bool {current != presented}+fn agent_status_change_is_visible(+ window_id: MuxWindowId,+ pane_window_id: Option<MuxWindowId>,+ presented_right_sidebar: Option<RightSidebarMode>,+ sidebar_contains_thread: bool,+ preview_contains_pane: bool,+) -> bool {+ pane_window_id == Some(window_id)+ || presented_right_sidebar == Some(RightSidebarMode::Agents)+ || sidebar_contains_thread+ || preview_contains_pane+}++#[cfg(test)]+mod agent_status_repaint_tests {+ use super::{agent_status_change_is_visible, RightSidebarMode};++ #[test]+ fn status_changes_repaint_only_windows_that_display_them() {+ // One pane's owner, an unrelated Snippets panel, an open global Agents+ // panel, a sidebar referencing the thread, and an overview preview.+ let windows = [+ (1, None, false, false),+ (2, Some(RightSidebarMode::Snippets), false, false),+ (3, Some(RightSidebarMode::Agents), false, false),+ (4, None, true, false),+ (5, None, false, true),+ (6, None, false, false),+ ];+ let repaint: Vec<_> = windows.iter().copied()+ .filter_map(|(id, panel, sidebar, preview)| {+ agent_status_change_is_visible(id, Some(1), panel, sidebar, preview).then_some(id)+ })+ .collect();+ assert_eq!(repaint, [1, 3, 4, 5]);++ // Closing the global panel removes the unrelated window's reason+ // to paint. A vanished pane still updates an open global panel.+ assert!(!agent_status_change_is_visible(3, Some(1), None, false, false));+ assert!(agent_status_change_is_visible(+ 3, None, Some(RightSidebarMode::Agents), false, false,+ ));+ }+}+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]pub(crate) struct PaintOutcome {draw_submitted: bool,@@ -2581,6 +2694,9 @@ pub struct TermWindow {os_parameters: Option<parameters::Parameters>,/// When we most recently received keyboard focuspub focused: Option<Instant>,+ /// The active pane last shown to someone in this window while it had+ /// focus, so that a pane's results are seen once per showing.+ seen_active_pane: Option<PaneId>,/// When the window stopped being visible to the user (fully covered,/// minimized, on another macOS Space, app hidden). None while/// visible. The timestamp doubles as the start of the grace period@@ -3027,6 +3143,10 @@ pub struct TermWindow {right_sidebar_collapsed: bool,right_sidebar_mode: RightSidebarMode,right_sidebar_agents_scroll: f32,+ /// Agents whose sub-task list is open in the Agents panel; folded is+ /// the default. Each paint of the panel drops the ones with no+ /// sub-tasks left, so the next batch starts folded again.+ right_sidebar_agents_open_subtasks: HashSet<PaneId>,right_sidebar_snippet_view: RightSidebarSnippetView,right_sidebar_snippet_focus: Option<RightSidebarSnippetField>,right_sidebar_snippet_search: TextInputState,@@ -4041,6 +4161,17 @@ impl TermWindow {}log::trace!("Setting focus to {:?}", focused);self.focused = if focused { Some(Instant::now()) } else { None };+ {+ let mut holder = FOCUSED_WINDOW.lock();+ if focused {+ *holder = Some(self.space_owner_id);+ } else if *holder == Some(self.space_owner_id) {+ *holder = None;+ }+ }+ // Back in front of someone: the active pane is looked at afresh on+ // the next paint.+ self.seen_active_pane = None;if focused {// Focus implies visible; belt-and-braces cover for a lost// occlusion edge (the window backend re-posts rather than@@ -4393,6 +4524,7 @@ impl TermWindow {settings_opacity_overrides,palette: None,focused: None,+ seen_active_pane: None,occluded: None,occlusion_released: false,occlusion_last_release: None,@@ -4605,6 +4737,7 @@ impl TermWindow {right_sidebar_collapsed: true,right_sidebar_mode: RightSidebarMode::Snippets,right_sidebar_agents_scroll: 0.0,+ right_sidebar_agents_open_subtasks: HashSet::new(),right_sidebar_snippet_view: RightSidebarSnippetView::List,right_sidebar_snippet_focus: None,right_sidebar_snippet_search: TextInputState::new(),@@ -5730,18 +5863,22 @@ impl TermWindow {// The panel snapshot is cached briefly; a real change// must not wait out that TTL.crate::agent_status::invalidate_agent_pane_cache();- self.refresh_thread_work_for_pane(pane_id);- if self.right_sidebar_mode == RightSidebarMode::Agents {- // The thread status may be unchanged while the- // per-pane chip flipped (e.g. Idle→Working inside an- // already-Running thread); repaint the open panel.- if let Some(win) = self.window.as_ref() {- win.invalidate();+ // A result that lands in the pane in front of the user is+ // seen as it lands: it must not turn up later as unseen.+ if self.focused.is_some() {+ if let Some(active) = self.get_active_pane_no_overlay() {+ if active.pane_id() == pane_id+ && crate::agent_status::has_unseen_result(active.as_ref())+ {+ active.program_status_seen();+ }}- } else {- // An agent starting or leaving changes its tab's icon.- self.invalidate_if_pane_tab_shown(pane_id);}+ crate::workspace_threads::refresh_thread_work_for_pane(pane_id);+ // Waiting -> error leaves the aggregate NeedsAttention+ // unchanged, but changes its icon. Decide from what this+ // window displays, not from the aggregate's changed bit.+ self.invalidate_window_if(self.agent_status_change_is_visible(pane_id));}MuxNotification::ForegroundProgramChanged(pane_id) => {self.invalidate_if_pane_tab_shown(pane_id);@@ -6219,6 +6356,29 @@ impl TermWindow {}}+ fn agent_status_change_is_visible(&self, pane_id: PaneId) -> bool {+ let mux = Mux::get();+ let pane_window_id = mux.resolve_pane_id(pane_id).map(|(_, window_id, _)| window_id);+ let sidebar_contains_thread = self.workspace_sidebar_is_presented()+ && pane_window_id+ .and_then(|window_id| {+ mux.get_window(window_id).map(|window| window.get_workspace().to_string())+ })+ .is_some_and(|workspace| {+ let space = self.workspace_sidebar_space_id();+ crate::workspace_threads::thread_id_for_workspace(space, &workspace).is_some()+ || crate::workspace_threads::origin_space_for_ref_workspace(space, &workspace)+ .is_some()+ });+ agent_status_change_is_visible(+ self.mux_window_id,+ pane_window_id,+ self.right_sidebar_presented().then_some(self.right_sidebar_mode),+ sidebar_contains_thread,+ self.active_content_view().is_some_and(|view| view.wants_pane_output(pane_id)),+ )+ }+fn schedule_status_update(&self) {if let Some(window) = self.window.as_ref() {window.notify(TermWindowNotif::EmitStatusUpdate);@@ -11841,6 +12001,14 @@ impl Drop for TermWindow {// from leaving its Space permanently marked as occupied.crate::workspace_threads::release_window_space(self.space_owner_id);crate::input_diagnostics::remove_gauges_for_source(self.space_owner_id);+ // A window torn down without losing focus first must not leave+ // ThinkTerm counted as looked at.+ {+ let mut holder = FOCUSED_WINDOW.lock();+ if *holder == Some(self.space_owner_id) {+ *holder = None;+ }+ }self.close_plugin_panel();self.clear_gui_recovery_intent();gpu_debug(format!(diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex 6ab1ac95..47e24c8e 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -1691,7 +1691,10 @@ impl super::TermWindow {/// clears `has_animation` on entry and would discard a deadline set here.fn update_hover_tooltip(&mut self, item: Option<&UIItem>) {let labelled = item- .filter(|item| crate::termwindow::tooltip_label_for(&item.item_type).is_some())+ .filter(|item| {+ crate::termwindow::tooltip_label_for(&item.item_type).is_some()+ || crate::termwindow::thread_has_card(&item.item_type)+ })// The dynamic half of the rule: no tag over a live rename// editor, and none for a file row whose label already reads in// full. `paint_hover_tooltip` re-checks the same predicate.@@ -6201,12 +6204,18 @@ impl super::TermWindow {}_ => ContextMenuIcon::Check,};- let label = format!(- "{} — {} · {}",- notification.thread_name,- notification.project_name,- notification.space_name- );+ // What the thread's program said beats where the thread+ // lives: the reason is what decides which to open first.+ let label = match crate::agent_status::thread_reason(¬ification.thread_id)+ {+ Some(reason) => format!("{} — {reason}", notification.thread_name),+ None => format!(+ "{} — {} · {}",+ notification.thread_name,+ notification.project_name,+ notification.space_name+ ),+ };self.context_menu_application_item_with_icon(label,icon,diff --git a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rsindex ac8673a3..469f833f 100644--- a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs+++ b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs@@ -852,7 +852,7 @@ impl crate::TermWindow {// draw it; the tab's status keeps its own place after it either way.let icon_right = match crate::tab_icons::resolve_window_tab() {Some(icon) => {- self.paint_tab_circle_icon(layers, &icon, tab_surface_y, button_size, false)?+ self.paint_tab_circle_icon(layers, &icon, tab_surface_y, button_size, false, None)?}None => {let icon_x = self.ui_px(TAB_CONTENT_INSET);diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rsindex 8a4fb435..bf87118a 100644--- a/wezterm-gui/src/termwindow/render/paint.rs+++ b/wezterm-gui/src/termwindow/render/paint.rs@@ -1058,6 +1058,7 @@ impl crate::TermWindow {let start = Instant::now();self.advance_tab_scroll_animation(start);+ self.note_active_pane_seen();{let diff = start.duration_since(self.last_fps_check_time);@@ -3388,6 +3389,10 @@ impl crate::TermWindow {if !self.hover_tooltip_allowed(&hover.item.item_type) {return Ok(());}+ let agents = crate::termwindow::thread_card_agents(&hover.item.item_type);+ if !agents.is_empty() {+ return self.paint_thread_agent_card(&hover.item, &agents);+ }let Some(label) = crate::termwindow::tooltip_label_for(&hover.item.item_type) else {return Ok(());};@@ -3471,6 +3476,165 @@ impl crate::TermWindow {Ok(())}+ /// A thread row's hover card: each agent in the thread, its state, and+ /// -- where its program said -- why it waits, how far it got and what it+ /// is doing. Beside the row rather than above it: the card is taller+ /// than a tag, and the rows above are the ones being read.+ fn paint_thread_agent_card(+ &mut self,+ item: &crate::termwindow::UIItem,+ agents: &[crate::agent_status::AgentPaneStatus],+ ) -> anyhow::Result<()> {+ use crate::agent_status::{self, ShownState};+ use crate::termwindow::ui::agent_panel::{agent_state_icon, agent_state_key};++ let settings = crate::native_settings::load_shared();+ let font_size = crate::native_settings::home_font_size(&settings);+ let ui_font = self+ .fonts+ .title_font_with_size(font_size)+ .context("thread card font")?;+ let metrics = crate::utilsprites::RenderMetrics::with_font_metrics(&ui_font.metrics());+ let line = metrics.cell_size.height as f32;+ let chrome = self.chrome();+ let show = settings.chrome.agent_status_display;++ // Per agent: its state, a heading, and what it said, if anything.+ let entries: Vec<(ShownState, String, Option<(String, LinearRgba)>)> = agents+ .iter()+ .map(|agent| {+ let shown = agent.shown_state();+ let mut heading = format!(+ "{} · {}",+ agent_status::display_name(&agent.agent_id),+ crate::i18n::tr(agent_state_key(shown))+ );+ let report = agent.report.as_ref();+ if let Some(kind) = report.and_then(|report| report.kind).filter(|_| show.reason) {+ heading.push_str(" · ");+ heading.push_str(&crate::i18n::tr(agent_status::blocked_kind_key(kind)));+ }+ if let Some(progress) = report+ .and_then(|report| report.progress)+ .filter(|_| show.progress)+ {+ heading.push_str(&format!(" · {progress}%"));+ }+ let said = report+ .and_then(|report| report.msg.clone())+ .filter(|_| show.description)+ .map(|msg| {+ let color = if shown == ShownState::Error {+ chrome.danger+ } else {+ chrome.secondary_text+ };+ (msg, color)+ });+ (shown, heading, said)+ })+ .collect();++ let gl_state = self.render_state.as_ref().unwrap();+ let layer = gl_state+ .layer_for_zindex(crate::termwindow::TOOLTIP_ZINDEX)+ .context("thread card layer")?;+ let mut layers = layer.quad_allocator();+ let ctx = DrawContext::new(gl_state, self.dimensions, &metrics);++ let pad = self.ui_f32(12.0);+ let gap = self.ui_f32(8.0);+ let icon = (line * 0.9).round().max(1.0);+ let max_text = (self.dimensions.pixel_width as f32 * 0.32).max(160.0);+ let text_width = entries+ .iter()+ .flat_map(|(_, heading, said)| {+ std::iter::once(heading.as_str()).chain(said.iter().map(|(text, _)| text.as_str()))+ })+ .map(|text| ctx.measure_text_width(&ui_font, text))+ .fold(0.0f32, f32::max)+ .min(max_text);+ let entry_height = |said: bool| line + if said { line + self.ui_f32(2.0) } else { 0.0 };+ let card_w = pad * 2.0 + icon + gap + text_width;+ let card_h = pad * 2.0+ + entries+ .iter()+ .map(|(_, _, said)| entry_height(said.is_some()))+ .sum::<f32>()+ + gap * entries.len().saturating_sub(1) as f32;++ let window_w = self.dimensions.pixel_width as f32;+ let window_h = self.dimensions.pixel_height as f32;+ let right_of_row = item.x as f32 + item.width as f32 + gap;+ let x = if right_of_row + card_w <= window_w {+ right_of_row+ } else {+ (item.x as f32 - gap - card_w).max(0.0)+ };+ let y = (item.y as f32).min(window_h - card_h).max(0.0);++ self.fill_rounded_rectangle_with_border(+ &mut layers,+ 0,+ euclid::rect(x, y, card_w, card_h),+ chrome.control_bg,+ chrome.control_border,+ self.ui_f32(10.0),+ 1.0,+ )+ .context("thread card background")?;++ let text_x = x + pad + icon + gap;+ let mut entry_y = y + pad;+ for (shown, heading, said) in &entries {+ if let Some((glyph, color, spinning)) =+ agent_state_icon(*shown, chrome, chrome.muted_text)+ {+ let icon_x = (x + pad).round() as usize;+ let icon_y = (entry_y + (line - icon) / 2.0).round() as usize;+ if spinning {+ self.paint_spinning_ui_icon(+ &mut layers,+ 2,+ glyph,+ icon_x,+ icon_y,+ icon as usize,+ color,+ )?;+ } else {+ self.paint_sidebar_icon(&mut layers, glyph, icon_x, icon_y, icon as usize, color)?;+ }+ }+ ctx.draw_text_on_layer(+ &mut layers,+ 2,+ &ui_font,+ text_x,+ entry_y,+ heading,+ chrome.text,+ text_width,+ )+ .context("thread card heading")?;+ if let Some((text, color)) = said {+ ctx.draw_text_on_layer(+ &mut layers,+ 2,+ &ui_font,+ text_x,+ entry_y + line + self.ui_f32(2.0),+ text,+ *color,+ text_width,+ )+ .context("thread card description")?;+ }+ entry_y += entry_height(said.is_some()) + gap;+ }+ Ok(())+ }+fn paint_drag_ghost_pill(&mut self,label: &str,diff --git a/wezterm-gui/src/termwindow/render/pane.rs b/wezterm-gui/src/termwindow/render/pane.rsindex beb818c8..66405eb1 100644--- a/wezterm-gui/src/termwindow/render/pane.rs+++ b/wezterm-gui/src/termwindow/render/pane.rs@@ -9,6 +9,8 @@ use crate::termwindow::render::{same_hyperlink, CursorProperties, LineQuadCacheKey, LineQuadCacheValue, LineToEleShapeCacheKey,RenderScreenLineParams,};+use crate::agent_status::{AgentEvidence, AgentState, ProgramReportState};+use crate::termwindow::ui::agent_panel::{AGENT_BLOCKED_COLOR, AGENT_DONE_COLOR};use crate::termwindow::ui::icons::SvgIcon;use crate::termwindow::ui::status_icon::{split_leading_legacy_progress_marker, UiStatusKind};use crate::termwindow::ui::tokens::{@@ -686,6 +688,8 @@ impl crate::TermWindow {icon_size,status.is_some(),this_tab_fg,+ tab_surface_color,+ selected_tab && self.focused.is_some(),)?;let close_slot_reserved = !is_renaming_tab;@@ -1074,6 +1078,8 @@ impl crate::TermWindow {icon_size,status.is_some(),this_tab_fg,+ tab_surface_color,+ selected_tab && self.focused.is_some(),)?;let close_slot_reserved = !is_renaming_tab;@@ -1332,9 +1338,39 @@ impl crate::TermWindow {icon_size: usize,running: bool,color: LinearRgba,+ surface: LinearRgba,+ watched: bool,) -> anyhow::Result<usize> {- let icon = Mux::get()- .get_pane(pane_id)+ let pane = Mux::get().get_pane(pane_id);+ // What an agent in the pane is up to: a working one spins the icon,+ // and one waiting on you, stopped on an error, or done with a result+ // nobody has seen yet gets a dot on the icon's shoulder.+ // The summary, not the status: this runs for every tab every frame,+ // and the status carries the report's text.+ let agent = pane+ .as_ref()+ .and_then(|pane| pane.agent_status_summary())+ .filter(|status| !status.ended && status.evidence != AgentEvidence::Fallback);+ let running = running+ || agent+ .as_ref()+ .is_some_and(|status| status.state == AgentState::Working);+ let badge = agent+ .as_ref()+ .and_then(|status| match status.state {+ AgentState::Blocked => Some(AGENT_BLOCKED_COLOR),+ AgentState::Error => Some(self.chrome().danger),+ // A result is unseen only while nobody is looking at it.+ AgentState::Idle+ if !watched && status.report_state == Some(ProgramReportState::Done) =>+ {+ Some(AGENT_DONE_COLOR)+ }+ _ => None,+ })+ .map(|dot| (dot, surface));+ let icon = pane+ .as_ref().and_then(|pane| crate::tab_icons::resolve(pane.as_ref()));let Some(icon) = icon else {let x = self.ui_px(TAB_CONTENT_INSET);@@ -1344,9 +1380,44 @@ impl crate::TermWindow {} else {self.paint_pane_nav_icon(layers, SvgIcon::SquareTerminal, x, y, icon_size, color)?;}+ if let Some(badge) = badge {+ self.paint_tab_icon_badge(layers, x, y, icon_size, badge)?;+ }return Ok(x + icon_size);};- self.paint_tab_circle_icon(layers, &icon, tab_y, tab_height, running)+ self.paint_tab_circle_icon(layers, &icon, tab_y, tab_height, running, badge)+ }++ /// The dot on a tab icon's top-right shoulder, in `badge.0`, set off+ /// from the icon by a ring of the tab's own surface, `badge.1`.+ fn paint_tab_icon_badge(+ &self,+ layers: &mut TripleLayerQuadAllocator,+ icon_x: usize,+ icon_y: usize,+ icon_size: usize,+ badge: (LinearRgba, LinearRgba),+ ) -> anyhow::Result<()> {+ let dot = (icon_size as f32 * 0.38).round().max(4.0);+ let ring = (dot * 0.25).round().max(1.0);+ let x = icon_x as f32 + icon_size as f32 - dot * 0.8;+ let y = icon_y as f32 - dot * 0.2;+ self.fill_rounded_rectangle(+ layers,+ 2,+ euclid::rect(x - ring, y - ring, dot + ring * 2.0, dot + ring * 2.0),+ badge.1,+ dot / 2.0 + ring,+ )+ .context("tab icon badge ring")?;+ self.fill_rounded_rectangle(+ layers,+ 2,+ euclid::rect(x, y, dot, dot),+ badge.0,+ dot / 2.0,+ )+ .context("tab icon badge")}/// A tab icon's circle, concentric with the rounded left end of the pill@@ -1360,6 +1431,7 @@ impl crate::TermWindow {tab_y: usize,tab_height: usize,running: bool,+ badge: Option<(LinearRgba, LinearRgba)>,) -> anyhow::Result<usize> {let inset = self.ui_px(TAB_ICON_CIRCLE_INSET).min(tab_height / 4);let diameter = tab_height.saturating_sub(inset * 2).max(1);@@ -1405,6 +1477,9 @@ impl crate::TermWindow {icon.glyph_color.linear(),)?;}+ if let Some(badge) = badge {+ self.paint_tab_icon_badge(layers, x, y, diameter, badge)?;+ }Ok(x + diameter)}diff --git a/wezterm-gui/src/termwindow/ui/agent_panel.rs b/wezterm-gui/src/termwindow/ui/agent_panel.rsindex b64089df..ec09f4b8 100644--- a/wezterm-gui/src/termwindow/ui/agent_panel.rs+++ b/wezterm-gui/src/termwindow/ui/agent_panel.rs@@ -4,7 +4,7 @@//! snapshots — the paint path never triggers detection or filesystem//! probes.-use crate::agent_status::{self, AgentIcon, AgentPanelAction, AgentState};+use crate::agent_status::{self, AgentIcon, AgentPanelAction, AgentState, ProgramReportState};use crate::quad::TripleLayerQuadAllocator;use crate::termwindow::ui::icons::SvgIcon;use crate::termwindow::ui::right_sidebar::{@@ -30,7 +30,15 @@ const AGENT_WORKING_COLOR: LinearRgba = LinearRgba::with_components(0.12, 0.48,/// An agent waiting on the user: amber, matching the sidebar's other/// "needs a human" signal. Deliberately not the notification red, which is/// reserved for something being wrong rather than something being asked.-const AGENT_BLOCKED_COLOR: LinearRgba = LinearRgba::with_components(0.86, 0.45, 0.12, 1.0);+pub(crate) const AGENT_BLOCKED_COLOR: LinearRgba = LinearRgba::with_components(0.86, 0.45, 0.12, 1.0);+/// A finished result nobody has looked at yet: the green the left sidebar+/// gives a finished thread, the same constant so the two cannot drift.+pub(crate) const AGENT_DONE_COLOR: LinearRgba =+ crate::termwindow::ui::sidebar::SESSION_STATUS_DONE_COLOR;+/// The progress bar under a row's description.+const AGENT_PROGRESS_HEIGHT: usize = 6;+/// Sub-task lines a row shows before it says how many more there are.+const AGENT_SUBTASKS_SHOWN: usize = 5;/// What the toolbar line reports when the list is not empty.#[derive(Clone, Copy, Default)]@@ -38,6 +46,7 @@ pub(crate) struct AgentCounts {total: usize,working: usize,blocked: usize,+ errored: usize,idle: usize,unknown: usize,}@@ -52,6 +61,7 @@ impl AgentCounts {match agent.state {AgentState::Working => counts.working += 1,AgentState::Blocked => counts.blocked += 1,+ AgentState::Error => counts.errored += 1,AgentState::Idle => counts.idle += 1,AgentState::Unknown => counts.unknown += 1,}@@ -77,6 +87,9 @@ impl AgentCounts {if self.blocked > 0 {parts.push(Self::count_text("right-agents-count-blocked", self.blocked));}+ if self.errored > 0 {+ parts.push(Self::count_text("right-agents-count-error", self.errored));+ }if parts.is_empty() {if self.idle > 0 || self.unknown == 0 {parts.push(Self::count_text("right-agents-count-idle", self.idle));@@ -217,6 +230,17 @@ impl TermWindow {let inset = self.ui_px(SIDEBAR_INSET);let mut agents = agent_status::list_agent_panes();+ // An open list lasts as long as its sub-tasks: the next batch starts+ // folded, and an agent that has gone leaves nothing behind.+ self.right_sidebar_agents_open_subtasks.retain(|pane_id| {+ agents.iter().any(|agent| {+ agent.pane_id == *pane_id+ && agent+ .report+ .as_ref()+ .is_some_and(|report| !report.children.is_empty())+ })+ });let counts = AgentCounts::tally(&agents);if agents.is_empty() {// Nothing but the toolbar: an empty-state card here is a large@@ -261,36 +285,53 @@ impl TermWindow {sidebar_row_element_visible(elem_y, elem_height, content_top, list_top, overflow_bottom)};let visible_height = viewport_bottom.saturating_sub(list_top);- // Rows are spaced like snippet cards: the painted row is- // `row_height`, and each one starts a gap further down. The last- // row has no trailing gap, so it is not part of the scrollable- // height either.+ // Rows are spaced like snippet cards: each one starts a gap below the+ // last, and the last has no trailing gap, so it is not part of the+ // scrollable height either. A row is two lines tall, and grows below+ // them by what its program reported, as far as the user chose to+ // see it.let row_gap = self.ui_px(SNIPPET_ROW_GAP);- let row_pitch = row_height + row_gap;- let total_height = agents- .len()- .saturating_mul(row_pitch)+ let show = crate::native_settings::agent_status_display();+ let bar_height = self.ui_px(AGENT_PROGRESS_HEIGHT);+ let layouts: Vec<AgentRowLayout> = agents+ .iter()+ .map(|agent| {+ AgentRowLayout::of(+ agent,+ show,+ self.right_sidebar_agents_open_subtasks+ .contains(&agent.pane_id),+ row_height,+ cell_height + line_gap,+ bar_height + line_gap,+ )+ })+ .collect();+ let total_height = layouts+ .iter()+ .map(|layout| layout.height + row_gap)+ .sum::<usize>().saturating_sub(row_gap);let max_scroll = total_height.saturating_sub(visible_height) as f32;self.right_sidebar_agents_scroll = self.right_sidebar_agents_scroll.clamp(0.0, max_scroll);let scroll = self.right_sidebar_agents_scroll;- for (idx, agent) in agents.iter().enumerate() {- let row_top = list_top as f32 + (idx * row_pitch) as f32 - scroll;- if row_top + row_height as f32 <= list_top as f32 {+ let mut offset = 0usize;+ for (agent, layout) in agents.iter().zip(&layouts) {+ let row_top = list_top as f32 + offset as f32 - scroll;+ offset += layout.height + row_gap;+ if row_top + layout.height as f32 <= list_top as f32 {continue;}if row_top >= viewport_bottom as f32 {- // Rows are laid out top-down, so nothing below is visible.break;}- let Some(band) = agent_row_visible_band(row_top, row_height, list_top, row_clip_bottom)+ let Some(band) =+ agent_row_visible_band(row_top, layout.height, list_top, row_clip_bottom)else {continue;};let top = band.top;- // Only the hover tint is clipped -- it is the one thing that would- // look wrong bleeding past the list, since it reads as a control.let hovered = self.is_pointer_over_ui_rect(content_x,band.visible_y,@@ -308,8 +349,6 @@ impl TermWindow {band.visible_height as f32,),chrome.sidebar_button_hover_bg,- // Same corner as a snippet card, so the two lists read- // as one control set rather than two designs.self.ui_f32(SIDEBAR_ROW_RADIUS) + 10.0,).context("agent row hover")?;@@ -327,11 +366,11 @@ impl TermWindow {}),});+ // The icons stay beside the two lines every row has, however far+ // the row grows below them.let icon_x = content_x + inset;let icon_y = top + (row_height.saturating_sub(metrics.icon_size)) / 2;if visible(icon_y, metrics.icon_size) {- // The brand mark when we have one; agents with no logo- // (and any id from a custom manifest) keep the generic bot.match agent_status::brand_icon(&agent.agent_id,crate::native_settings::effective_appearance(),@@ -362,22 +401,11 @@ impl TermWindow {}}- // State chip: spinner while working, alert while blocked. `None`- // reserves no width on the right either, so an Unknown agent gets- // the whole line for its title.+ let shown = agent.shown_state();let state_size = metrics.icon_size;let state_x = content_x + content_width - inset - state_size;let state_y = top + (row_height.saturating_sub(state_size)) / 2;- // The same three status colors the left sidebar gives a thread,- // so "working" and "waiting on you" mean the same thing in both- // places: blue for in progress, amber for needs input, and a- // muted tick for idle, which must not compete for attention.- let state_icon = match agent.state {- AgentState::Working => Some((SvgIcon::LoaderCircle, AGENT_WORKING_COLOR, true)),- AgentState::Blocked => Some((SvgIcon::CircleAlert, AGENT_BLOCKED_COLOR, false)),- AgentState::Idle => Some((SvgIcon::CircleCheck, muted_fg, false)),- AgentState::Unknown => None,- };+ let state_icon = agent_state_icon(shown, chrome, muted_fg);let has_state_icon = state_icon.is_some();if let Some((icon, color, spinning)) =state_icon.filter(|_| visible(state_y, state_size))@@ -417,12 +445,7 @@ impl TermWindow {foreground,)?;}- let state_label = match agent.state {- AgentState::Working => crate::i18n::tr("right-agents-state-working"),- AgentState::Blocked => crate::i18n::tr("right-agents-state-blocked"),- AgentState::Idle => crate::i18n::tr("right-agents-state-idle"),- AgentState::Unknown => crate::i18n::tr("right-agents-state-unknown"),- };+ let state_label = crate::i18n::tr(agent_state_key(shown));// The thread's human name, resolved once per snapshot -- never the// internal workspace id, and never a per-frame store walk.let detail_line = if agent.place.is_empty() {@@ -443,6 +466,200 @@ impl TermWindow {muted_fg,)?;}++ let Some(report) = agent.report.as_ref() else {+ continue;+ };+ let mut line_y = detail_y + cell_height + line_gap;+ if layout.message {+ if visible(line_y, cell_height) {+ let mut x = text_x;+ if let Some(kind) = report.kind.filter(|_| show.reason) {+ let label = crate::i18n::tr(agent_status::blocked_kind_key(kind));+ x = self.paint_agent_kind_pill(+ layers, ui_font, ui_metrics, &label, x, line_y, text_right,+ )?;+ }+ if let Some(msg) = report.msg.as_deref().filter(|_| show.description) {+ let color = if shown == agent_status::ShownState::Error {+ chrome.danger+ } else {+ chrome.secondary_text+ };+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ msg,+ x,+ line_y,+ text_right.saturating_sub(x),+ color,+ )?;+ }+ }+ line_y += cell_height + line_gap;+ }+ if let Some(progress) = layout.progress {+ if visible(line_y, bar_height) {+ let radius = bar_height as f32 / 2.0;+ self.fill_rounded_rectangle(+ layers,+ 1,+ euclid::rect(+ text_x as f32,+ line_y as f32,+ text_width as f32,+ bar_height as f32,+ ),+ chrome.separator,+ radius,+ )+ .context("agent progress track")?;+ let filled = (text_width as f32 * f32::from(progress) / 100.0).round();+ if filled >= bar_height as f32 {+ self.fill_rounded_rectangle(+ layers,+ 1,+ euclid::rect(text_x as f32, line_y as f32, filled, bar_height as f32),+ chrome.accent,+ radius,+ )+ .context("agent progress")?;+ }+ }+ line_y += bar_height + line_gap;+ }+ let sub_icon = (cell_height * 4 / 5).max(1);+ let sub_text_gap = sub_icon + self.ui_px(SIDEBAR_ICON_GAP) / 2;+ if layout.subtask_count > 0 {+ // The fold line is its own target over the row's: a click on+ // it opens or folds the list rather than revealing the pane.+ let hit_top = line_y.max(band.visible_y);+ let hit_bottom = (line_y + cell_height + line_gap)+ .min(band.visible_y + band.visible_height);+ let mut fold_hovered = false;+ if hit_bottom > hit_top {+ fold_hovered = self.is_pointer_over_ui_rect(+ content_x,+ hit_top,+ content_width,+ hit_bottom - hit_top,+ );+ self.ui_items.push(UIItem {+ x: content_x,+ y: hit_top,+ width: content_width,+ height: hit_bottom - hit_top,+ item_type: UIItemType::RightSidebarAgent(+ AgentPanelAction::ToggleSubtasks(agent.pane_id),+ ),+ });+ }+ if visible(line_y, cell_height) {+ let chevron = if layout.subtasks > 0 {+ SvgIcon::ChevronDown+ } else {+ SvgIcon::ChevronRight+ };+ let icon_y = line_y + (cell_height.saturating_sub(sub_icon)) / 2;+ self.paint_sidebar_icon(layers, chevron, text_x, icon_y, sub_icon, muted_fg)?;+ let mut args = fluent_bundle::FluentArgs::new();+ args.set("count", layout.subtask_count);+ let mut line = crate::i18n::tr_args("right-agents-subtasks", &args);+ let working = report+ .children+ .iter()+ .filter(|child| matches!(child.state, ProgramReportState::Working))+ .count();+ if working > 0 {+ let mut args = fluent_bundle::FluentArgs::new();+ args.set("count", working);+ let working = crate::i18n::tr_args("right-agents-count-working", &args);+ line = format!("{line} · {working}");+ }+ let line_x = text_x + sub_text_gap;+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ &line,+ line_x,+ line_y,+ text_right.saturating_sub(line_x),+ if fold_hovered {+ foreground+ } else {+ chrome.secondary_text+ },+ )?;+ }+ line_y += cell_height + line_gap;+ }+ // An open list sits under the fold line's words, a level in.+ let list_x = text_x + sub_text_gap;+ for child in report.children.iter().take(layout.subtasks) {+ if visible(line_y, cell_height) {+ let child_state = match child.state {+ ProgramReportState::Working => agent_status::ShownState::Working,+ ProgramReportState::Blocked => agent_status::ShownState::Blocked,+ ProgramReportState::Error => agent_status::ShownState::Error,+ ProgramReportState::Done => agent_status::ShownState::Done,+ ProgramReportState::Idle => agent_status::ShownState::Idle,+ };+ let icon_y = line_y + (cell_height.saturating_sub(sub_icon)) / 2;+ if let Some((icon, color, spinning)) =+ agent_state_icon(child_state, chrome, muted_fg)+ {+ if spinning {+ self.paint_spinning_ui_icon(+ layers, 2, icon, list_x, icon_y, sub_icon, color,+ )?;+ } else {+ self.paint_sidebar_icon(layers, icon, list_x, icon_y, sub_icon, color)?;+ }+ }+ let name = child+ .title+ .as_deref()+ .or(child.msg.as_deref())+ .unwrap_or(&child.id);+ let line = match child.kind.filter(|_| show.reason) {+ Some(kind) => format!(+ "{name} · {}",+ crate::i18n::tr(agent_status::blocked_kind_key(kind))+ ),+ None => name.to_string(),+ };+ let line_x = list_x + sub_text_gap;+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ &line,+ line_x,+ line_y,+ text_right.saturating_sub(line_x),+ chrome.secondary_text,+ )?;+ }+ line_y += cell_height + line_gap;+ }+ if layout.more_subtasks > 0 && visible(line_y, cell_height) {+ let mut args = fluent_bundle::FluentArgs::new();+ args.set("count", layout.more_subtasks);+ let more = crate::i18n::tr_args("right-agents-more-subtasks", &args);+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ &more,+ list_x,+ line_y,+ text_right.saturating_sub(list_x),+ muted_fg,+ )?;+ }}let scrolled = max_scroll > 0.0 && scroll > 0.0;@@ -489,6 +706,44 @@ impl TermWindow {Ok(())}+ /// The pill naming what a blocked program waits for. Returns where the+ /// text after it starts.+ #[allow(clippy::too_many_arguments)]+ fn paint_agent_kind_pill(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ ui_font: &Rc<LoadedFont>,+ ui_metrics: RenderMetrics,+ label: &str,+ x: usize,+ y: usize,+ right: usize,+ ) -> anyhow::Result<usize> {+ let cell_height = ui_metrics.cell_size.height as usize;+ let pad = self.ui_px(10);+ let width = (self.sidebar_text_width(ui_font, label)?.ceil() as usize + pad * 2)+ .min(right.saturating_sub(x));+ self.fill_rounded_rectangle(+ layers,+ 1,+ euclid::rect(x as f32, y as f32, width as f32, cell_height as f32),+ AGENT_BLOCKED_COLOR.mul_alpha(0.18),+ cell_height as f32 / 2.0,+ )+ .context("agent waiting reason")?;+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ label,+ x + pad,+ y,+ width.saturating_sub(pad * 2),+ AGENT_BLOCKED_COLOR,+ )?;+ Ok(x + width + self.ui_px(SIDEBAR_ICON_GAP))+ }+pub(crate) fn mouse_event_right_sidebar_agent(&mut self,item: UIItem,@@ -533,6 +788,11 @@ impl TermWindow {AgentPanelAction::RevealElsewhere(pane_id) => {self.reveal_agent_pane_elsewhere(pane_id, context);}+ AgentPanelAction::ToggleSubtasks(pane_id) => {+ if !self.right_sidebar_agents_open_subtasks.remove(&pane_id) {+ self.right_sidebar_agents_open_subtasks.insert(pane_id);+ }+ }}context.invalidate();}@@ -668,6 +928,94 @@ struct AgentRowBand {visible_height: usize,}+/// Which of a row's optional lines it has, and how tall that makes it.+struct AgentRowLayout {+ height: usize,+ /// The description, with the waiting reason in front of it.+ message: bool,+ progress: Option<u8>,+ /// The sub-tasks the folded line counts; none when they are not shown.+ subtask_count: usize,+ /// While the list is open: the sub-task lines it lists, then how many+ /// more there are.+ subtasks: usize,+ more_subtasks: usize,+}++impl AgentRowLayout {+ fn of(+ agent: &agent_status::AgentPaneStatus,+ show: crate::native_settings::NativeAgentStatusDisplay,+ open: bool,+ base_height: usize,+ line: usize,+ bar: usize,+ ) -> Self {+ let Some(report) = agent.report.as_ref() else {+ return Self {+ height: base_height,+ message: false,+ progress: None,+ subtask_count: 0,+ subtasks: 0,+ more_subtasks: 0,+ };+ };+ let message = (show.description && report.msg.is_some())+ || (show.reason && report.kind.is_some());+ let progress = report.progress.filter(|_| show.progress);+ let subtask_count = if show.subtasks {+ report.children.len()+ } else {+ 0+ };+ let listed = if open { subtask_count } else { 0 };+ let subtasks = listed.min(AGENT_SUBTASKS_SHOWN);+ let more_subtasks = listed - subtasks;+ let height = base_height+ + if message { line } else { 0 }+ + if progress.is_some() { bar } else { 0 }+ + (usize::from(subtask_count > 0) + subtasks + usize::from(more_subtasks > 0)) * line;+ Self {+ height,+ message,+ progress,+ subtask_count,+ subtasks,+ more_subtasks,+ }+ }+}++/// The icon a state is shown with: glyph, colour, and whether it spins.+pub(crate) fn agent_state_icon(+ state: agent_status::ShownState,+ chrome: UiPalette,+ muted_fg: LinearRgba,+) -> Option<(SvgIcon, LinearRgba, bool)> {+ use agent_status::ShownState;+ match state {+ ShownState::Working => Some((SvgIcon::LoaderCircle, AGENT_WORKING_COLOR, true)),+ ShownState::Blocked => Some((SvgIcon::CircleAlert, AGENT_BLOCKED_COLOR, false)),+ ShownState::Error => Some((SvgIcon::CircleX, chrome.danger, false)),+ ShownState::Done => Some((SvgIcon::CircleCheck, AGENT_DONE_COLOR, false)),+ ShownState::Idle => Some((SvgIcon::CircleCheck, muted_fg, false)),+ ShownState::Unknown => None,+ }+}++pub(crate) fn agent_state_key(state: agent_status::ShownState) -> &'static str {+ use agent_status::ShownState;+ match state {+ ShownState::Working => "right-agents-state-working",+ ShownState::Blocked => "right-agents-state-blocked",+ ShownState::Error => "right-agents-state-error",+ ShownState::Done => "right-agents-state-done",+ ShownState::Idle => "right-agents-state-idle",+ ShownState::Unknown => "right-agents-state-unknown",+ }+}+/// Clip one list row to the panel, the way `paint_snippet_card` clips a/// snippet card: rows scroll under both edges, so a row can be cut by the/// list origin above and by the panel edge below.@@ -805,6 +1153,68 @@ mod tests {);}+ /// Sub-tasks fold to the one line that counts them: only an open list+ /// adds its lines, and with sub-tasks switched off there is no line.+ #[test]+ fn sub_tasks_fold_to_one_line_until_opened() {+ use super::AgentRowLayout;+ use crate::agent_status::{+ AgentEvidence, AgentPaneStatus, AgentState, ProgramReport, ProgramReportState,+ };+ use crate::native_settings::NativeAgentStatusDisplay;+ use thinkterm_proto::ProgramReportChild;++ let child = |n: usize| ProgramReportChild {+ id: format!("task-{n}"),+ state: ProgramReportState::Working,+ kind: None,+ progress: None,+ title: None,+ msg: None,+ };+ let agent = AgentPaneStatus {+ pane_id: 1,+ agent_id: "claude".to_string(),+ state: AgentState::Working,+ evidence: AgentEvidence::Report,+ session_id: None,+ title: String::new(),+ window_id: None,+ place: String::new(),+ workspace: String::new(),+ report: Some(ProgramReport {+ state: ProgramReportState::Working,+ kind: None,+ progress: None,+ app: None,+ title: None,+ msg: None,+ children: (0..7).map(child).collect(),+ }),+ since_unix: 0,+ };+ let show = NativeAgentStatusDisplay::default();+ let (base, line) = (40, 10);++ let folded = AgentRowLayout::of(&agent, show, false, base, line, 4);+ assert_eq!(+ (folded.subtask_count, folded.subtasks, folded.more_subtasks),+ (7, 0, 0)+ );+ assert_eq!(folded.height, base + line);++ let open = AgentRowLayout::of(&agent, show, true, base, line, 4);+ assert_eq!((open.subtasks, open.more_subtasks), (5, 2));+ assert_eq!(open.height, base + line * 7, "fold line, five, and the rest");++ let hidden = NativeAgentStatusDisplay {+ subtasks: false,+ ..show+ };+ let off = AgentRowLayout::of(&agent, hidden, true, base, line, 4);+ assert_eq!((off.subtask_count, off.height), (0, base));+ }+/// The toolbar line is the only thing explaining a quiet panel, so it/// must never come back blank, and must name what is actually/// happening rather than reciting every state.diff --git a/wezterm-gui/src/termwindow/ui/icons.rs b/wezterm-gui/src/termwindow/ui/icons.rsindex 0b06af37..ebb64067 100644--- a/wezterm-gui/src/termwindow/ui/icons.rs+++ b/wezterm-gui/src/termwindow/ui/icons.rs@@ -12,6 +12,7 @@ pub enum SvgIcon {ArrowRight,ArrowUp,Bell,+ BellRing,Bot,Braces,Bug,@@ -89,6 +90,7 @@ pub enum SvgIcon {Shrink,CircleAlert,CircleCheck,+ CircleX,CirclePlus,SquarePlus,Square,@@ -207,6 +209,7 @@ impl SvgIcon {include_bytes!("../../../../third_party/lucide/icons/arrow-up.svg")}Self::Bell => include_bytes!("../../../../third_party/lucide/icons/bell.svg"),+ Self::BellRing => include_bytes!("../../../../third_party/lucide/icons/bell-ring.svg"),Self::Bot => include_bytes!("../../../../third_party/lucide/icons/bot.svg"),Self::Braces => include_bytes!("../../../../third_party/lucide/icons/braces.svg"),Self::Check => include_bytes!("../../../../third_party/lucide/icons/check.svg"),@@ -332,6 +335,7 @@ impl SvgIcon {Self::CircleCheck => {include_bytes!("../../../../third_party/lucide/icons/circle-check.svg")}+ Self::CircleX => include_bytes!("../../../../third_party/lucide/icons/circle-x.svg"),Self::CirclePlus => {include_bytes!("../../../../third_party/lucide/icons/circle-plus.svg")}@@ -830,6 +834,7 @@ mod tests {SvgIcon::ArchiveRestore,SvgIcon::ArrowLeft,SvgIcon::Bell,+ SvgIcon::BellRing,SvgIcon::Braces,SvgIcon::Server,SvgIcon::ExternalLink,@@ -874,6 +879,7 @@ mod tests {SvgIcon::Shrink,SvgIcon::CircleAlert,SvgIcon::CircleCheck,+ SvgIcon::CircleX,SvgIcon::CirclePlus,SvgIcon::Square,SvgIcon::SquareTerminal,diff --git a/wezterm-gui/src/termwindow/ui/sidebar.rs b/wezterm-gui/src/termwindow/ui/sidebar.rsindex 81a820ab..6bfb2d6f 100644--- a/wezterm-gui/src/termwindow/ui/sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs@@ -67,7 +67,7 @@ const SESSION_ACTION_ICON_INSET: usize = 12;const SESSION_STATUS_DOT_SIZE: usize = 10;const SESSION_STATUS_ICON_SIZE: usize = 20;const SESSION_STATUS_ACTIVE_ICON_SIZE: usize = 26;-const SESSION_STATUS_DONE_COLOR: LinearRgba = LinearRgba::with_components(0.20, 0.78, 0.36, 1.0);+pub(crate) const SESSION_STATUS_DONE_COLOR: LinearRgba = LinearRgba::with_components(0.20, 0.78, 0.36, 1.0);const SESSION_STATUS_OPEN_COLOR: LinearRgba = LinearRgba::with_components(0.12, 0.48, 1.0, 1.0);const SPACE_DISCONNECTED_COLOR: LinearRgba = LinearRgba::with_components(0.86, 0.45, 0.12, 1.0);const NOTIFICATION_BADGE_COLOR: LinearRgba = LinearRgba::with_components(0.96, 0.16, 0.22, 1.0);@@ -145,6 +145,15 @@ pub fn workspace_sidebar_width_for_metrics(render_metrics: &RenderMetrics, dpi:.clamp(min_width, max_width)}+/// Whether a program in the thread reported that it stopped on an error.+fn thread_has_errored_agent(thread_id: &str) -> bool {+ workspace_threads::thread_workspace_name(thread_id).is_some_and(|workspace| {+ crate::agent_status::any_agent_in_workspace(&workspace, |agent| {+ agent.state == crate::agent_status::AgentState::Error+ })+ })+}+fn centered_inner_start(origin: usize, outer: usize, inner: usize) -> usize {if inner <= outer {origin + (outer - inner) / 2@@ -697,6 +706,9 @@ impl crate::TermWindow {SESSION_STATUS_DONE_COLOR} else if session.is_active && !suppress_active {foreground+ } else if status == UiStatusKind::NeedsAttention {+ // The amber the Agents panel and the tabs use for a wait.+ crate::termwindow::ui::agent_panel::AGENT_BLOCKED_COLOR} else {self.sidebar_thread_dot_color(session, chrome, foreground, suppress_active)}@@ -723,6 +735,20 @@ impl crate::TermWindow {) -> anyhow::Result<()> {let icon_y = y + ((row_height.saturating_sub(self.ui_px(SESSION_STATUS_ICON_SIZE))) / 2);if let Some(status) = self.sidebar_thread_status_kind(session) {+ // A thread one of whose programs stopped on an error is marked as+ // the Agents panel marks it: a red cross, not a wait.+ if status == UiStatusKind::NeedsAttention && thread_has_errored_agent(&session.id) {+ let size = self.ui_px(SESSION_STATUS_ICON_SIZE);+ return self.paint_ui_icon(+ layers,+ 2,+ SvgIcon::CircleX,+ x,+ centered_inner_start(y, row_height, size),+ size,+ chrome.danger,+ );+ }let status_size = if matches!(status, UiStatusKind::Running | UiStatusKind::Done) {self.ui_px(SESSION_STATUS_ACTIVE_ICON_SIZE)} else {diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rsindex 2247c255..36cc3d25 100644--- a/wezterm-gui/src/workspace_threads.rs+++ b/wezterm-gui/src/workspace_threads.rs@@ -2927,6 +2927,65 @@ fn announce_work(announcement: WorkAnnouncement, finished_after: Option<Duration}}+/// How soon one thread may raise another system notification: a program+/// flapping between states must not turn into a stream of banners.+const SYSTEM_NOTIFICATION_INTERVAL: Duration = Duration::from_secs(30);++lazy_static::lazy_static! {+ /// When each thread, by workspace, last raised a system notification.+ /// Entries past the interval are dropped whenever one is added.+ static ref SYSTEM_NOTIFIED: Mutex<HashMap<String, std::time::Instant>> =+ Mutex::new(HashMap::new());+}++/// Whether the system will take a notification from this process. On macOS+/// it must be an app bundle: UNUserNotificationCenter throws for a bare+/// binary -- a development build -- and takes the whole app down with it.+fn can_notify_system() -> bool {+ !cfg!(target_os = "macos")+ || std::env::current_exe()+ .is_ok_and(|exe| exe.to_string_lossy().contains(".app/Contents/MacOS/"))+}++/// Tell the system a thread wants a look -- it finished, it waits on you, or+/// its program stopped on an error -- when nobody is looking at ThinkTerm.+/// The same moments the sounds mark, with the program's own words when it+/// gave any.+fn notify_system(workspace: &str, announcement: WorkAnnouncement, finished_after: Option<Duration>) {+ if std::env::var_os(DISABLE_SOUND_ENV).is_some()+ || crate::frontend::try_front_end().is_none()+ || !can_notify_system()+ || !crate::native_settings::system_notifications_enabled()+ || crate::termwindow::app_has_focus()+ || !should_play_work_sound(announcement, finished_after)+ {+ return;+ }+ {+ let now = std::time::Instant::now();+ let mut notified = SYSTEM_NOTIFIED.lock();+ if notified+ .get(workspace)+ .is_some_and(|at| now.duration_since(*at) < SYSTEM_NOTIFICATION_INTERVAL)+ {+ return;+ }+ notified.retain(|_, at| now.duration_since(*at) < SYSTEM_NOTIFICATION_INTERVAL);+ notified.insert(workspace.to_string(), now);+ }+ let errored = crate::agent_status::any_agent_in_workspace(workspace, |agent| {+ agent.state == crate::agent_status::AgentState::Error+ });+ let state = crate::i18n::tr(match announcement {+ WorkAnnouncement::Finished => "notification-thread-finished",+ WorkAnnouncement::NeedsInput if errored => "notification-thread-error",+ WorkAnnouncement::NeedsInput => "notification-thread-needs-input",+ });+ let thread = thread_display_name_for_workspace(workspace).unwrap_or_else(|| workspace.to_string());+ let reason = crate::agent_status::workspace_reason(workspace).unwrap_or_default();+ wezterm_toast_notification::persistent_toast_notification(&format!("{thread} · {state}"), &reason);+}+pub fn refresh_thread_work_for_workspace(workspace: &str) -> bool {let (raw_observed, waiting_panes) = scan_workspace_work_status(workspace);let observed = debounce_work_status(workspace, raw_observed);@@ -2950,6 +3009,7 @@ pub fn refresh_thread_work_for_workspace(workspace: &str) -> bool {};if let Some(announcement) = change.announce {announce_work(announcement, finished_after);+ notify_system(workspace, announcement, finished_after);}if change.should_persist {schedule_workspace_thread_store_persist();diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rsindex 3c8697ea..ad0b3a13 100644--- a/wezterm-mux-server-impl/src/sessionhandler.rs+++ b/wezterm-mux-server-impl/src/sessionhandler.rs@@ -1110,6 +1110,7 @@ fn web_peer_may_send(pdu: &Pdu) -> bool {| Pdu::ListPanes(_)| Pdu::WriteToPane(_)| Pdu::SendKeyDown(_)+ | Pdu::MarkProgramStatusSeen(_)| Pdu::SendMouseEvent(_)| Pdu::SendPaste(_)| Pdu::Resize(_)@@ -1813,6 +1814,23 @@ impl SessionHandler {.detach();}+ Pdu::MarkProgramStatusSeen(MarkProgramStatusSeen { pane_id }) => {+ spawn_into_main_thread(async move {+ catch(+ move || {+ let mux = Mux::get();+ let pane = mux+ .get_pane(pane_id)+ .ok_or_else(|| anyhow!("no such pane {}", pane_id))?;+ pane.program_status_seen();+ Ok(Pdu::UnitResponse(UnitResponse {}))+ },+ send_response,+ )+ })+ .detach();+ }+Pdu::GetPaneDirection(GetPaneDirection { pane_id, direction }) => {spawn_into_main_thread(async move {catch(diff --git a/wezterm/src/cli/agent.rs b/wezterm/src/cli/agent.rsindex c77f785b..28a66498 100644--- a/wezterm/src/cli/agent.rs+++ b/wezterm/src/cli/agent.rs@@ -43,6 +43,7 @@ fn state_label(state: AgentState) -> &'static str {AgentState::Blocked => "blocked",AgentState::Idle => "idle",AgentState::Unknown => "unknown",+ AgentState::Error => "error",}}@@ -51,6 +52,7 @@ fn evidence_label(evidence: AgentEvidence) -> &'static str {AgentEvidence::Contract => "contract",AgentEvidence::Screen => "screen",AgentEvidence::Fallback => "fallback",+ AgentEvidence::Report => "report",}}