A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
agent status GUI: Agents panel, settings, sounds, CLI; sidebar scroll rework
RoversX23bfd04667f8
diff --git a/ci/update-derived-files.sh b/ci/update-derived-files.shindex 4f11c1a2..e21a42ae 100755--- a/ci/update-derived-files.sh+++ b/ci/update-derived-files.sh@@ -38,6 +38,8 @@ donefor cmd in \activate-pane \+ agent \+ "agent list" \activate-pane-direction \adjust-pane-size \activate-tab \@@ -55,6 +57,7 @@ for cmd in \split-pane \zoom-pane \; do- fname="docs/examples/cmd-synopsis-wezterm-cli-${cmd}--help.txt"- cargo run --example narrow "$DEBUG_DIR/thinkterm" cli $cmd --help | "$DEBUG_DIR/strip-ansi-escapes" | trim_file > $fname+ # Nested subcommand groups ("agent list") hyphenate into the filename.+ fname="docs/examples/cmd-synopsis-wezterm-cli-${cmd// /-}--help.txt"+ cargo run --example narrow "$DEBUG_DIR/thinkterm" cli $cmd --help | "$DEBUG_DIR/strip-ansi-escapes" | trim_file > "$fname"donediff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.tomlindex d22c0e89..bf9a267b 100644--- a/wezterm-gui/Cargo.toml+++ b/wezterm-gui/Cargo.toml@@ -105,6 +105,7 @@ sys-locale.workspace = truetermwiz-funcs.workspace = truetermwiz.workspace = truetextwrap.workspace = true+thinkterm-proto.workspace = truethiserror.workspace = truetiny-skia.workspace = truethinkterm-syntax = { path = "../thinkterm-syntax" }diff --git a/wezterm-gui/i18n/en-US.ftl b/wezterm-gui/i18n/en-US.ftlindex 89842ed5..03a9d9f9 100644--- a/wezterm-gui/i18n/en-US.ftl+++ b/wezterm-gui/i18n/en-US.ftl@@ -470,3 +470,31 @@ onboarding-theme-light-note = Bold choice — most terminals never see daylight.onboarding-privacy = Nothing you open leaves this machine.onboarding-skip = Skiponboarding-start = Get Started++# Agent status detection + Agents panel+settings-agents-heading = Agents+settings-agent-panel = Agent Panel+settings-agent-panel-description = Detect coding agents (Claude Code, Codex, …) running in panes and show them in the right sidebar.+settings-agent-panel-enabled = Agent panel enabled.+settings-agent-panel-disabled = Agent panel disabled.+right-mode-agents = Agents+right-agents-empty = No agents detected+right-agents-empty-hint = Panes running Claude Code, Codex and other agents appear here.+right-agents-reload-rules = Reload detection rules+right-agents-rules-reloaded = Detection rules reloaded.+right-agents-state-working = Working+right-agents-state-blocked = Needs input+right-agents-state-idle = Idle+right-agents-state-unknown = Unknown+settings-section-agents = Agents+settings-agents-integrations-heading = Integrations+settings-integration-screen-active = Found on PATH; status is detected from its terminal UI (screen rules).+settings-integration-screen-missing = Not found on PATH; once installed, status is detected automatically.+settings-integration-native = Reports its own status over the ThinkTerm agent protocol; nothing to install.+settings-integration-pending = Deeper integration is planned; no status detection yet.+settings-agent-details-screen-detect = Detection: reads the bottom of the pane's live screen and the terminal title; nothing is installed or executed.+settings-agent-details-screen-override = Rules can be overridden at { $path }.+settings-agent-details-states = Recognized states: working, waiting for your input, idle.+settings-agent-details-native = Reports working / waiting / idle itself via the THINKTERM_AGENT protocol; full lifecycle, no gaps.+settings-agent-details-native-doc = Protocol reference: docs/agent-status.md in the ThinkTerm repository.+settings-agent-details-pending = No screen rules exist for this agent; a lifecycle adapter is planned. It runs fine — status just isn't shown yet.diff --git a/wezterm-gui/i18n/fr-FR.ftl b/wezterm-gui/i18n/fr-FR.ftlindex c38b1df9..dfbc821e 100644--- a/wezterm-gui/i18n/fr-FR.ftl+++ b/wezterm-gui/i18n/fr-FR.ftl@@ -470,3 +470,31 @@ onboarding-theme-light-note = Choix audacieux — la plupart des terminaux ne voonboarding-privacy = Rien de ce que vous ouvrez ne quitte cet appareil.onboarding-skip = Ignoreronboarding-start = Commencer++# Détection d'état des agents + panneau Agents+settings-agents-heading = Agents+settings-agent-panel = Panneau des agents+settings-agent-panel-description = Détecter les agents de codage (Claude Code, Codex, …) dans les panneaux et les afficher dans la barre latérale droite.+settings-agent-panel-enabled = Panneau des agents activé.+settings-agent-panel-disabled = Panneau des agents désactivé.+right-mode-agents = Agents+right-agents-empty = Aucun agent détecté+right-agents-empty-hint = Les panneaux exécutant Claude Code, Codex et d'autres agents apparaissent ici.+right-agents-reload-rules = Recharger les règles de détection+right-agents-rules-reloaded = Règles de détection rechargées.+right-agents-state-working = En cours+right-agents-state-blocked = Attend une réponse+right-agents-state-idle = Inactif+right-agents-state-unknown = Inconnu+settings-section-agents = Agents+settings-agents-integrations-heading = Intégrations+settings-integration-screen-active = Trouvé dans le PATH ; l'état est détecté depuis son interface terminal (règles d'écran).+settings-integration-screen-missing = Introuvable dans le PATH ; une fois installé, l'état sera détecté automatiquement.+settings-integration-native = Rapporte lui-même son état via le protocole natif ThinkTerm ; rien à installer.+settings-integration-pending = Une intégration plus poussée est prévue ; pas encore de détection d'état.+settings-agent-details-screen-detect = Détection : lit le bas de l'écran du panneau et le titre du terminal ; rien n'est installé ni exécuté.+settings-agent-details-screen-override = Les règles peuvent être remplacées dans { $path }.+settings-agent-details-states = États reconnus : en cours, en attente de votre réponse, inactif.+settings-agent-details-native = Rapporte lui-même en cours / en attente / inactif via le protocole THINKTERM_AGENT ; cycle de vie complet, sans angle mort.+settings-agent-details-native-doc = Référence du protocole : docs/agent-status.md dans le dépôt ThinkTerm.+settings-agent-details-pending = Pas encore de règles d'écran pour cet agent ; un adaptateur est prévu. Il fonctionne normalement, seul l'état n'est pas affiché.diff --git a/wezterm-gui/i18n/ja-JP.ftl b/wezterm-gui/i18n/ja-JP.ftlindex 49619eb9..c3e9fde9 100644--- a/wezterm-gui/i18n/ja-JP.ftl+++ b/wezterm-gui/i18n/ja-JP.ftl@@ -470,3 +470,31 @@ onboarding-theme-light-note = 勇気ある選択です。ほとんどの端末onboarding-privacy = 開いたものはこの端末の外に出ません。onboarding-skip = スキップonboarding-start = 使ってみる++# エージェント状態検出 + Agents パネル+settings-agents-heading = エージェント+settings-agent-panel = エージェントパネル+settings-agent-panel-description = ペインで動作するコーディングエージェント(Claude Code、Codex など)を検出し、右サイドバーに表示します。+settings-agent-panel-enabled = エージェントパネルを有効にしました。+settings-agent-panel-disabled = エージェントパネルを無効にしました。+right-mode-agents = エージェント+right-agents-empty = エージェントが見つかりません+right-agents-empty-hint = Claude Code や Codex などを実行中のペインがここに表示されます。+right-agents-reload-rules = 検出ルールを再読み込み+right-agents-rules-reloaded = 検出ルールを再読み込みしました。+right-agents-state-working = 作業中+right-agents-state-blocked = 入力待ち+right-agents-state-idle = アイドル+right-agents-state-unknown = 不明+settings-section-agents = エージェント+settings-agents-integrations-heading = 連携+settings-integration-screen-active = PATH 上で見つかりました。状態は端末画面(スクリーンルール)から識別します。+settings-integration-screen-missing = PATH 上に見つかりません。インストール後は自動的に状態を識別します。+settings-integration-native = ThinkTerm ネイティブプロトコルで自ら状態を報告します。インストール不要です。+settings-integration-pending = より深い連携を計画中です。現在は状態識別がありません。+settings-agent-details-screen-detect = 検出方法: ペイン画面下部のテキストと端末タイトルを読むだけです。何もインストール・実行しません。+settings-agent-details-screen-override = ルールは { $path } で上書きできます。+settings-agent-details-states = 認識する状態: 作業中、入力待ち、アイドル。+settings-agent-details-native = THINKTERM_AGENT プロトコルで自ら状態を報告します。完全なライフサイクルで盲点はありません。+settings-agent-details-native-doc = プロトコル資料: ThinkTerm リポジトリの docs/agent-status.md。+settings-agent-details-pending = このエージェントにはまだスクリーンルールがありません。アダプターを計画中です。動作には問題なく、状態表示だけ未対応です。diff --git a/wezterm-gui/i18n/zh-CN.ftl b/wezterm-gui/i18n/zh-CN.ftlindex 40038ff2..18d801d6 100644--- a/wezterm-gui/i18n/zh-CN.ftl+++ b/wezterm-gui/i18n/zh-CN.ftl@@ -470,3 +470,31 @@ onboarding-theme-light-note = 很有勇气 —— 大多数终端从不见光。onboarding-privacy = 你打开的一切都不会离开这台设备。onboarding-skip = 跳过onboarding-start = 开始使用++# Agent 状态检测 + Agents 面板+settings-agents-heading = Agent+settings-agent-panel = Agent 面板+settings-agent-panel-description = 检测 pane 中运行的编码 Agent(Claude Code、Codex 等)并显示在右侧栏。+settings-agent-panel-enabled = Agent 面板已开启。+settings-agent-panel-disabled = Agent 面板已关闭。+right-mode-agents = Agent+right-agents-empty = 未检测到 Agent+right-agents-empty-hint = 运行 Claude Code、Codex 等 Agent 的 pane 会显示在这里。+right-agents-reload-rules = 重载检测规则+right-agents-rules-reloaded = 检测规则已重载。+right-agents-state-working = 工作中+right-agents-state-blocked = 等待输入+right-agents-state-idle = 空闲+right-agents-state-unknown = 未知+settings-section-agents = Agent+settings-agents-integrations-heading = 集成+settings-integration-screen-active = 已在 PATH 中找到;状态通过其终端界面识别(屏幕规则)。+settings-integration-screen-missing = 未在 PATH 中找到;安装该工具后自动开始识别状态。+settings-integration-native = 通过 ThinkTerm 原生协议自行上报状态,无需安装。+settings-integration-pending = 深度集成开发中;暂不提供状态识别。+settings-agent-details-screen-detect = 检测方式:读取 pane 屏幕底部文字和终端标题;不安装、不执行任何东西。+settings-agent-details-screen-override = 规则可在 { $path } 覆盖。+settings-agent-details-states = 可识别状态:工作中、等待你输入、空闲。+settings-agent-details-native = 通过 THINKTERM_AGENT 协议自行上报 工作中/等待/空闲;完整生命周期,无盲区。+settings-agent-details-native-doc = 协议文档:ThinkTerm 仓库的 docs/agent-status.md。+settings-agent-details-pending = 该 agent 暂无屏幕规则;生命周期 adapter 在计划中。它可以正常运行,只是暂不显示状态。diff --git a/wezterm-gui/src/agent_status/mod.rs b/wezterm-gui/src/agent_status/mod.rsnew file mode 100644index 00000000..cb8eb6c2--- /dev/null+++ b/wezterm-gui/src/agent_status/mod.rs@@ -0,0 +1,446 @@+//! GUI facade over the agent-status core.+//!+//! Detection itself lives in `mux::agent_status` and runs in whichever+//! process *owns* a pane; this module only presents the results (panel+//! snapshots, settings-page metadata) and hosts the pieces that are+//! genuinely GUI concerns (the feature toggle, the login-shell PATH+//! probe, display names).+//!+//! Deliberately NOT re-exported: `engine::*`, `DetectionInput`,+//! `contract::parse`, `identify::*`. Only `mux::agent_status::reload_rules`+//! crosses the boundary (the panel's reload button). That makes GUI-side+//! 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};++use crate::workspace_threads::WorkspaceThreadWorkStatus;+use mux::pane::{Pane, PaneId};+use mux::Mux;+use std::collections::HashMap;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Mutex;+use std::time::{Duration, Instant};++/// Clickable controls in the Agents panel; carried by+/// `UIItemType::RightSidebarAgent`.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum AgentPanelAction {+ ReloadRules,+ /// Focus the pane running this agent (it lives in this window).+ Reveal(PaneId),+ /// The pane lives in another window: clicking deep-focuses its tab+ /// and pane, then activates the backing thread (workspace switch,+ /// window brought forward) via the left sidebar's activation path.+ RevealElsewhere(PaneId),+}++/// Snapshot of one agent pane for the Agents panel.+#[derive(Clone, Debug)]+pub(crate) struct AgentPaneStatus {+ pub pane_id: PaneId,+ /// Manifest/contract agent id, e.g. "claude".+ pub agent_id: String,+ pub state: AgentState,+ #[allow(dead_code)]+ pub evidence: AgentEvidence,+ /// Kept for the upcoming session-resume integration (spawn spec).+ #[allow(dead_code)]+ pub session_id: Option<String>,+ /// Pane title with any leading progress marker stripped.+ pub title: String,+ pub workspace: String,+ /// Mux window hosting the pane, resolved once per snapshot.+ pub window_id: Option<mux::window::WindowId>,+ /// Human place name ("Project · Thread"), falling back to the raw+ /// workspace string. Resolved once per snapshot: the paint loop must+ /// not walk the thread store per row per frame.+ pub place: String,+ /// Unix seconds when `state` last changed, on the detecting host's+ /// clock (approximate across hosts).+ #[allow(dead_code)]+ pub since_unix: u64,+}++/// One-line result of the last panel action, painted under the toolbar.+/// Expires on its own: the message is an acknowledgement, not a pinned+/// banner, and it is process-global (every window shows it).+static PANEL_STATUS: Mutex<Option<(String, Instant)>> = Mutex::new(None);+const PANEL_STATUS_TTL: Duration = Duration::from_secs(6);++pub(crate) fn panel_status() -> Option<String> {+ let guard = PANEL_STATUS.lock().ok()?;+ let (message, at) = guard.as_ref()?;+ (at.elapsed() < PANEL_STATUS_TTL).then(|| message.clone())+}++pub(crate) fn set_panel_status(message: String) {+ if let Ok(mut slot) = PANEL_STATUS.lock() {+ *slot = Some((message, Instant::now()));+ }+}++pub(crate) fn enabled() -> bool {+ // Both gates: without the Lua master switch the detector never runs,+ // and a permanently-empty panel would just look broken.+ crate::native_settings::agent_panel_enabled()+ && config::configuration().agent_status_detection+}++/// Per-pane work status for the sidebar thread scan. `None` when the pane+/// runs no known agent — callers fall back to the native title/progress+/// signals, so the flag-off path stays identical to pre-agent behavior.+pub(crate) fn agent_work_status(pane: &dyn Pane) -> Option<WorkspaceThreadWorkStatus> {+ let status = pane.agent_status()?;+ // Three cases where the agent status says nothing about the pane's+ // work, and pinning Idle would mask the native title/progress signals:+ // an ended session, an Unknown verdict, and the Fallback tier — the+ // latter means "recognized agent, but neither screen nor contract+ // spoke", and the pane's own OSC 9;4 / title spinner may know better.+ if status.ended+ || status.state == AgentState::Unknown+ || status.evidence == AgentEvidence::Fallback+ {+ return None;+ }+ Some(match status.state {+ AgentState::Working => WorkspaceThreadWorkStatus::Running,+ AgentState::Blocked => WorkspaceThreadWorkStatus::NeedsAttention,+ AgentState::Idle | AgentState::Unknown => WorkspaceThreadWorkStatus::Idle,+ })+}++/// While an agent spins, the panel repaints at animation rate; walking+/// 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);+const AGENT_PANES_TTL: Duration = Duration::from_millis(200);++/// Called from the AgentStatusChanged repaint path so a state change is+/// visible on the very next paint rather than a TTL later.+pub(crate) fn invalidate_agent_pane_cache() {+ if let Ok(mut slot) = AGENT_PANES_CACHE.lock() {+ *slot = None;+ }+}++/// Snapshot for the Agents panel: every pane in the mux with a known+/// 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> {+ 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();+ }+ }+ }+ let mux = Mux::get();+ // One pass over the window/tab topology instead of a full+ // `resolve_pane_id` scan per agent pane.+ let mut workspace_by_pane: HashMap<PaneId, (mux::window::WindowId, String)> = HashMap::new();+ for window_id in mux.iter_windows() {+ let Some(window) = mux.get_window(window_id) else {+ continue;+ };+ let workspace = window.get_workspace().to_string();+ for tab in window.iter() {+ for pane in tab.iter_all_panes() {+ workspace_by_pane.insert(pane.pane_id(), (window_id, workspace.clone()));+ }+ }+ }+ let panes: Vec<AgentPaneStatus> = mux+ .iter_panes()+ .into_iter()+ .filter_map(|pane| {+ let status = pane.agent_status()?;+ if status.ended {+ return None;+ }+ let (window_id, workspace) = match workspace_by_pane.get(&pane.pane_id()) {+ Some((window_id, workspace)) => (Some(*window_id), workspace.clone()),+ None => (None, String::new()),+ };+ let place = if workspace.is_empty() {+ String::new()+ } else {+ crate::workspace_threads::thread_display_name_for_workspace(&workspace)+ .unwrap_or_else(|| workspace.clone())+ };+ let raw_title = pane.get_title();+ let title =+ crate::termwindow::ui::status_icon::split_leading_legacy_progress_marker(+ &raw_title,+ )+ .unwrap_or(&raw_title)+ .to_string();+ Some(AgentPaneStatus {+ pane_id: pane.pane_id(),+ agent_id: status.agent_id,+ state: status.state,+ evidence: status.evidence,+ session_id: status.session_id,+ title,+ workspace,+ window_id,+ place,+ since_unix: status.since_unix,+ })+ })+ .collect();+ if let Ok(mut slot) = AGENT_PANES_CACHE.lock() {+ *slot = Some((Instant::now(), panes.clone()));+ }+ panes+}++pub(crate) fn display_name(agent_id: &str) -> String {+ match agent_id {+ "claude" => "Claude Code",+ "codex" => "Codex",+ "copilot" => "Copilot CLI",+ "cursor" => "Cursor Agent",+ "pi" => "Pi",+ "opencode" => "OpenCode",+ "kimi" => "Kimi Code",+ "omp" => "OMP",+ "soul" => "Soul",+ // A custom manifest or contract id has no curated name; the raw+ // id (title-cased) beats an indistinguishable generic "Agent".+ other => {+ let mut chars = other.chars();+ return match chars.next() {+ Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),+ None => "Agent".to_string(),+ };+ }+ }+ .to_string()+}++/// How each supported agent is covered, for the settings Integrations list.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum IntegrationKind {+ /// Covered by bundled screen-rule manifests; nothing to install.+ ScreenRules,+ /// Speaks the native `THINKTERM_AGENT` protocol itself.+ Native,+ /// Deeper integration planned; no screen rules yet.+ Pending,+}++/// The supported agents shown in Settings → Agents → Integrations, in+/// display order: (agent id, PATH probe names, coverage).+pub(crate) const SUPPORTED_AGENTS: &[(&str, &[&str], IntegrationKind)] = &[+ ("claude", &["claude"], IntegrationKind::ScreenRules),+ ("codex", &["codex"], IntegrationKind::ScreenRules),+ ("copilot", &["copilot"], IntegrationKind::ScreenRules),+ ("cursor", &["cursor-agent", "cursor"], IntegrationKind::ScreenRules),+ ("pi", &["pi"], IntegrationKind::ScreenRules),+ ("opencode", &["opencode"], IntegrationKind::ScreenRules),+ ("kimi", &["kimi"], IntegrationKind::ScreenRules),+ ("omp", &["omp"], IntegrationKind::Pending),+ ("soul", &["soul"], IntegrationKind::Native),+];++static PATH_PROBE: Mutex<Option<HashMap<&'static str, bool>>> = Mutex::new(None);++/// Directories searched when probing for agent executables. A GUI process+/// launched from Finder/Dock inherits launchd's minimal PATH (no+/// /opt/homebrew/bin, no ~/.local/bin), so the login shell's PATH is+/// merged in once per process, plus a few well-known install locations+/// as insurance for shells that only extend PATH interactively.+fn probe_dirs() -> &'static Vec<std::path::PathBuf> {+ use std::sync::OnceLock;+ static DIRS: OnceLock<Vec<std::path::PathBuf>> = OnceLock::new();+ DIRS.get_or_init(|| {+ let mut dirs: Vec<std::path::PathBuf> = Vec::new();+ let push_all = |value: &std::ffi::OsStr, dirs: &mut Vec<std::path::PathBuf>| {+ for dir in std::env::split_paths(value) {+ if !dir.as_os_str().is_empty() && !dirs.contains(&dir) {+ dirs.push(dir);+ }+ }+ };+ if let Some(path) = std::env::var_os("PATH") {+ push_all(&path, &mut dirs);+ }+ #[cfg(unix)]+ {+ // Not `$SHELL`: env-bootstrap unconditionally removes it at+ // startup (stale after `chsh`), so reading it here would run+ // `/bin/sh -l` forever and never see the PATH set up by the+ // user's real shell rc (mise/asdf/nvm installs). get_shell()+ // resolves from the password database instead.+ let shell = portable_pty::CommandBuilder::new_default_prog().get_shell();+ if let Some(path) = login_shell_path(&shell) {+ push_all(std::ffi::OsStr::new(path.trim()), &mut dirs);+ }+ for fallback in ["/opt/homebrew/bin", "/usr/local/bin"] {+ let dir = std::path::PathBuf::from(fallback);+ if !dirs.contains(&dir) {+ dirs.push(dir);+ }+ }+ let local_bin = config::HOME_DIR.join(".local").join("bin");+ if !dirs.contains(&local_bin) {+ dirs.push(local_bin);+ }+ }+ dirs+ })+}++/// The login shell's `$PATH`, bounded in time. Shell profiles can block+/// forever on interactive steps (`read`, a gpg pinentry, a keychain+/// unlock); an unbounded wait here would wedge the probe worker with the+/// `PATH_PROBE_RUNNING` latch held and hang every later `probe_dirs`+/// caller on the OnceLock, so a hung shell is killed and the fallback+/// dirs stand in.+#[cfg(unix)]+fn login_shell_path(shell: &str) -> Option<String> {+ use std::process::Stdio;+ use std::time::{Duration, Instant};+ const BUDGET: Duration = Duration::from_secs(5);++ let mut child = std::process::Command::new(shell)+ .args(["-l", "-c", "printf %s \"$PATH\""])+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()+ .ok()?;+ // Read on a helper thread: a profile can spawn a background process+ // that inherits the pipe's write end, in which case a post-exit read+ // would block even though the shell itself is done.+ let stdout = child.stdout.take();+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ let mut buf = String::new();+ if let Some(mut stdout) = stdout {+ use std::io::Read;+ let _ = stdout.read_to_string(&mut buf);+ }+ let _ = tx.send(buf);+ });+ let deadline = Instant::now() + BUDGET;+ loop {+ match child.try_wait() {+ Ok(Some(status)) => {+ if !status.success() {+ return None;+ }+ // Bounded even here, for the inherited-write-end case;+ // losing the answer beats blocking the probe worker.+ return rx.recv_timeout(Duration::from_millis(500)).ok();+ }+ Ok(None) => {+ if Instant::now() >= deadline {+ log::warn!(+ "login shell {shell} did not produce $PATH within {BUDGET:?} \+ (interactive profile step?); using fallback probe dirs"+ );+ let _ = child.kill();+ let _ = child.wait();+ return None;+ }+ std::thread::sleep(Duration::from_millis(50));+ }+ Err(_) => return None,+ }+ }+}++/// A PATH hit must be an executable *file*: a stray non-executable file+/// with an agent's name must not report the agent as installed.+fn is_executable_file(path: &std::path::Path) -> bool {+ let Ok(metadata) = path.metadata() else {+ return false;+ };+ if !metadata.is_file() {+ return false;+ }+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ metadata.permissions().mode() & 0o111 != 0+ }+ #[cfg(not(unix))]+ true+}++/// Whether this agent's executable is reachable on the probe path. A pure+/// cache read: painting must never run the login shell or stat files.+/// Answers `false` until `refresh_path_probe`'s worker has reported.+pub(crate) fn agent_on_path(agent_id: &str) -> bool {+ PATH_PROBE+ .lock()+ .ok()+ .and_then(|guard| guard.as_ref().and_then(|map| map.get(agent_id).copied()))+ .unwrap_or(false)+}++static PATH_PROBE_RUNNING: AtomicBool = AtomicBool::new(false);++/// Re-run the executable probe on a worker thread (the login-shell PATH+/// merge can take seconds under a heavy shell profile, and must never+/// block the UI thread). Repaints all windows when the result lands.+pub(crate) fn refresh_path_probe() {+ if PATH_PROBE_RUNNING.swap(true, Ordering::AcqRel) {+ return;+ }+ std::thread::spawn(|| {+ // The latch must clear even if the probe panics (a stuck `true`+ // would silently freeze the Integrations list for the process+ // lifetime), so it lives in a drop guard.+ struct ProbeLatch;+ impl Drop for ProbeLatch {+ fn drop(&mut self) {+ PATH_PROBE_RUNNING.store(false, Ordering::Release);+ }+ }+ let _latch = ProbeLatch;+ let dirs = probe_dirs();+ let mut map = HashMap::new();+ for (id, names, _) in SUPPORTED_AGENTS {+ let found = dirs.iter().any(|dir| {+ names.iter().any(|name| {+ let file = if cfg!(windows) {+ format!("{name}.exe")+ } else {+ (*name).to_string()+ };+ is_executable_file(&dir.join(file))+ })+ });+ map.insert(*id, found);+ }+ if let Ok(mut guard) = PATH_PROBE.lock() {+ *guard = Some(map);+ }+ promise::spawn::spawn_into_main_thread(async {+ // The settings window is the surface that reads this result,+ // and it is not in the frontend's known-windows list — it+ // must be invalidated explicitly.+ crate::settings_window::invalidate_open_settings_window();+ if let Some(front_end) = crate::frontend::try_front_end() {+ front_end.invalidate_all_windows();+ }+ })+ .detach();+ });+}++#[cfg(test)]+mod tests {+ use super::display_name;++ #[test]+ fn display_name_falls_back_to_the_raw_id() {+ assert_eq!(display_name("claude"), "Claude Code");+ assert_eq!(display_name("myagent"), "Myagent");+ assert_eq!(display_name(""), "Agent");+ }+}diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rsindex eb06fa25..fedd2e37 100644--- a/wezterm-gui/src/frontend.rs+++ b/wezterm-gui/src/frontend.rs@@ -193,6 +193,10 @@ impl GuiFrontEnd {spawn_malloc_pressure_relief_thread();let mux = Mux::get();+ // Agent detection schedules its safety tick and pane evaluations on+ // the GUI executor. Connection::init above installs that executor;+ // initializing it while the mux is first assembled is too early.+ mux::agent_status::initialize_mux(&mux);let client_id = mux.active_identity().expect("to have set my own id");let front_end = Rc::new(GuiFrontEnd {@@ -276,6 +280,7 @@ impl GuiFrontEnd {MuxNotification::PaneRemoved(_) => {}MuxNotification::WindowInvalidated(_) => {}MuxNotification::PaneOutput(_) => {}+ MuxNotification::AgentStatusChanged(_) => {}MuxNotification::PaneAdded(_) => {}MuxNotification::Alert {pane_id,diff --git a/wezterm-gui/src/i18n.rs b/wezterm-gui/src/i18n.rsindex 13b5a2f0..52891847 100644--- a/wezterm-gui/src/i18n.rs+++ b/wezterm-gui/src/i18n.rs@@ -326,4 +326,84 @@ mod tests {.contains("demo"));}}++ /// The parity test only compares the locale files to each other, so a+ /// tr() call whose key exists in *no* file sails through and renders+ /// as the raw key at runtime. Sweep the source for string-literal+ /// lookups and pin every one to a real en-US entry.+ #[test]+ fn every_translated_string_literal_has_a_definition() {+ let defined: std::collections::HashSet<&str> = EN_US+ .source+ .lines()+ .filter_map(|line| {+ let (key, rest) = line.split_once('=')?;+ let key = key.trim();+ (!key.is_empty()+ && rest.starts_with(' ')+ && key+ .chars()+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'))+ .then_some(key)+ })+ .collect();++ let mut missing = Vec::new();+ let mut stack = vec![std::path::PathBuf::from(concat!(+ env!("CARGO_MANIFEST_DIR"),+ "/src"+ ))];+ while let Some(dir) = stack.pop() {+ for entry in std::fs::read_dir(&dir).expect("src readable") {+ let path = entry.expect("entry").path();+ if path.is_dir() {+ stack.push(path);+ continue;+ }+ if path.extension().and_then(|e| e.to_str()) != Some("rs") {+ continue;+ }+ let text = std::fs::read_to_string(&path).expect("source readable");+ for (idx, _) in text.match_indices("tr(") {+ // Covers tr and the *_tr helpers: all funnel through a+ // fluent key as the first argument. Anything else whose+ // name merely ends in "tr" (push_str, …) is skipped by+ // requiring the identifier to be tr or *_tr. The key+ // may sit on the next line, so whitespace between the+ // paren and the literal is skipped.+ let ident_start = text[..idx]+ .rfind(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))+ .map(|p| p + 1)+ .unwrap_or(0);+ let ident = &text[ident_start..idx + 2];+ if ident != "tr" && !ident.ends_with("_tr") {+ continue;+ }+ let after_paren = &text[idx + 3..];+ let literal = after_paren.trim_start();+ let Some(literal) = literal.strip_prefix('"') else {+ continue;+ };+ let key: String = literal.chars().take_while(|c| *c != '"').collect();+ if key.is_empty()+ || !key+ .chars()+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')+ {+ continue;+ }+ if !defined.contains(key.as_str()) {+ missing.push(format!("{} (in {})", key, path.display()));+ }+ }+ }+ }+ missing.sort();+ missing.dedup();+ assert!(+ missing.is_empty(),+ "tr() keys with no en-US definition:\n{}",+ missing.join("\n")+ );+ }}diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex 05c7e6c0..0d7d6c00 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -35,6 +35,7 @@ use wezterm_gui_subcommands::*;use wezterm_mux_server_impl::update_mux_domains;use wezterm_toast_notification::*;+mod agent_status;mod bottom_quotes;mod colorease;mod commands;@@ -1143,6 +1144,11 @@ fn setup_mux() -> anyhow::Result<Arc<Mux>> {let mux = Arc::new(mux::Mux::new(Some(local_domain.clone())));Mux::set_mux(&mux);+ // The user-facing Agents toggle governs this process's own detector as+ // well as the panel; headless mux servers follow the Lua option alone.+ mux::agent_status::set_process_preference(|| {+ crate::native_settings::agent_panel_enabled()+ });let client_id = Arc::new(mux::client::generate_client_id());mux.register_client(client_id.clone());mux.replace_identity(Some(client_id));diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rsindex fc60be23..dd51edce 100644--- a/wezterm-gui/src/native_settings.rs+++ b/wezterm-gui/src/native_settings.rs@@ -237,6 +237,9 @@ pub(crate) struct NativeChromeSettings {/// Workspace-thread statuses hidden by the sidebar view-options filter,/// as stable keys ("idle", "running", "needs-attention", "finished").pub(crate) workspace_sidebar_hidden_statuses: Vec<String>,+ /// Feature toggle for agent status detection and the right-sidebar+ /// Agents panel. Off by default; absent in settings.json means off.+ pub(crate) agent_panel_enabled: bool,}#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]@@ -652,6 +655,12 @@ pub(crate) fn workspace_sidebar_hover_reveal_enabled() -> bool {.unwrap_or(true)}+/// Agent status detection + Agents panel feature toggle. Default off.+/// `load_shared`: asked once per work-status scan and once per sidebar frame.+pub(crate) fn agent_panel_enabled() -> bool {+ load_shared().chrome.agent_panel_enabled+}+pub(crate) fn right_sidebar_width() -> Option<usize> {load().chrome.right_sidebar_width}diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rsindex 49c5a1cc..7337e899 100644--- a/wezterm-gui/src/settings_window.rs+++ b/wezterm-gui/src/settings_window.rs@@ -113,6 +113,22 @@ fn next_settings_window_id() -> u64 {})}+/// Repaint the open settings window, if any. Worker-thread completion+/// callbacks (the agents PATH probe) need this because the settings+/// window is standalone — it is not in the frontend's known-windows+/// list, so `invalidate_all_windows` never reaches it. Main thread only.+pub(crate) fn invalidate_open_settings_window() {+ SETTINGS_WINDOW.with(|slot| {+ if let SettingsWindowSlot::Open { settings, .. } = &*slot.borrow() {+ if let Ok(settings) = settings.try_borrow() {+ if let Some(window) = settings.window.as_ref() {+ window.invalidate();+ }+ }+ }+ });+}+fn settings_window_for_instance(instance_id: u64) -> Option<Rc<RefCell<SettingsWindow>>> {SETTINGS_WINDOW.with(|slot| match &*slot.borrow() {SettingsWindowSlot::Open {@@ -145,6 +161,7 @@ enum SettingsSection {Appearance,Terminal,Workspaces,+ Agents,Keymap,Compatibility,Developer,@@ -158,6 +175,7 @@ const BASE_SECTIONS: &[SettingsSection] = &[SettingsSection::Appearance,SettingsSection::Terminal,SettingsSection::Workspaces,+ SettingsSection::Agents,SettingsSection::Keymap,SettingsSection::Compatibility,SettingsSection::Developer,@@ -166,6 +184,70 @@ const BASE_SECTIONS: &[SettingsSection] = &[const DEVELOPER_SECTIONS: &[SettingsSection] = &[SettingsSection::UiKit, SettingsSection::Memory];+/// The expandable per-agent explanation in the Integrations list.+fn agent_detail_lines(+ agent_id: &str,+ kind: crate::agent_status::IntegrationKind,+) -> Vec<String> {+ use crate::agent_status::IntegrationKind;+ match kind {+ IntegrationKind::ScreenRules => vec![+ crate::i18n::tr("settings-agent-details-screen-detect"),+ settings_tr(+ "settings-agent-details-screen-override",+ &[(+ "path",+ format!("~/.config/thinkterm/agent-detection/{agent_id}.toml"),+ )],+ ),+ crate::i18n::tr("settings-agent-details-states"),+ ],+ IntegrationKind::Native => vec![+ crate::i18n::tr("settings-agent-details-native"),+ crate::i18n::tr("settings-agent-details-native-doc"),+ ],+ IntegrationKind::Pending => vec![+ crate::i18n::tr("settings-agent-details-pending"),+ ],+ }+}++/// Debug affordance companion to `THINKTERM_SETTINGS_SECTION`: pre-expands+/// one Integrations row (e.g. for unattended UI captures).+fn initial_expanded_agent() -> Option<&'static str> {+ let name = std::env::var("THINKTERM_SETTINGS_EXPAND").ok()?;+ crate::agent_status::SUPPORTED_AGENTS+ .iter()+ .find(|(id, _, _)| *id == name)+ .map(|(id, _, _)| *id)+}++/// Debug affordance: `THINKTERM_SETTINGS_SECTION=<name>` selects that section+/// when the settings window opens (e.g. for unattended UI captures with+/// `THINKTERM_FRAME_DUMP`). Names match the enum variants, case-insensitive.+fn initial_section() -> SettingsSection {+ let Some(name) = std::env::var_os("THINKTERM_SETTINGS_SECTION") else {+ return SettingsSection::Appearance;+ };+ let name = name.to_string_lossy().to_ascii_lowercase();+ let section = match name.as_str() {+ "general" => SettingsSection::General,+ "appearance" => SettingsSection::Appearance,+ "terminal" => SettingsSection::Terminal,+ "workspaces" => SettingsSection::Workspaces,+ "agents" => SettingsSection::Agents,+ "keymap" => SettingsSection::Keymap,+ "compatibility" => SettingsSection::Compatibility,+ "developer" => SettingsSection::Developer,+ "about" => SettingsSection::About,+ _ => SettingsSection::Appearance,+ };+ if section == SettingsSection::Agents {+ crate::agent_status::refresh_path_probe();+ }+ section+}+impl SettingsSection {fn label(self) -> String {match self {@@ -173,6 +255,7 @@ impl SettingsSection {Self::Appearance => crate::i18n::tr("settings-section-appearance"),Self::Terminal => crate::i18n::tr("settings-section-terminal"),Self::Workspaces => crate::i18n::tr("settings-section-workspaces"),+ Self::Agents => crate::i18n::tr("settings-section-agents"),Self::Keymap => crate::i18n::tr("settings-section-keymap"),Self::Compatibility => crate::i18n::tr("settings-section-compatibility"),Self::Developer => crate::i18n::tr("settings-section-developer"),@@ -188,6 +271,7 @@ impl SettingsSection {Self::Appearance => SettingsIcon::Appearance,Self::Terminal => SettingsIcon::Terminal,Self::Workspaces => SettingsIcon::Workspaces,+ Self::Agents => SettingsIcon::Agents,Self::Keymap => SettingsIcon::Keymap,Self::Compatibility => SettingsIcon::Sync,Self::Developer => SettingsIcon::Developer,@@ -253,6 +337,19 @@ impl SettingsSection {"SFTP","Idle Timeout",],+ Self::Agents => &[+ "Agent",+ "Agents",+ "Agent Panel",+ "Integration",+ "Integrations",+ "Claude",+ "Claude Code",+ "Codex",+ "Copilot",+ "Cursor",+ "Detection Rules",+ ],Self::Keymap => &["Keymap", "Keyboard", "Shortcut", "Command Palette"],Self::Compatibility => &["ThinkTerm Config",@@ -388,6 +485,8 @@ enum SettingsAction {ToggleImportField(ImportFieldId),ToggleMainWindowFrameRestore,ToggleNotificationSounds,+ ToggleAgentPanel,+ ToggleAgentDetails(&'static str),ToggleDeveloperMode,ToggleFallbackContextMenu,ShowOnboardingNow,@@ -1384,6 +1483,7 @@ struct SettingsWindow {webgpu: Option<Rc<WebGpuState>>,appearance: Appearance,selected: SettingsSection,+ agents_expanded: Option<&'static str>,native_settings: ThinkTermNativeSettings,active_main_renderer: NativeRendererBackend,ui: SettingsUiState,@@ -1501,7 +1601,8 @@ impl SettingsWindow {render_state: None,webgpu: None,appearance,- selected: SettingsSection::Appearance,+ selected: initial_section(),+ agents_expanded: initial_expanded_agent(),native_settings,active_main_renderer,ui,@@ -2913,6 +3014,11 @@ impl SettingsWindow {self.selected = section;self.ui.content_scroll.reset();self.ui.open_dropdown = None;+ if section == SettingsSection::Agents {+ // Probe PATH on entry so painting never touches the+ // filesystem.+ crate::agent_status::refresh_path_probe();+ }}SettingsAction::OpenThinkTermConfigFile => {self.ui.open_dropdown = None;@@ -3239,6 +3345,38 @@ impl SettingsWindow {}}}+ SettingsAction::ToggleAgentPanel => {+ self.ui.open_dropdown = None;+ self.native_settings.chrome.agent_panel_enabled =+ !self.native_settings.chrome.agent_panel_enabled;+ match crate::native_settings::save(&self.native_settings) {+ Ok(()) => {+ // After the save so the detector's preference+ // closure reads the new shared value; without this+ // the gate waits for the next safety tick.+ mux::agent_status::refresh_enabled();+ self.status = if self.native_settings.chrome.agent_panel_enabled {+ crate::i18n::tr("settings-agent-panel-enabled")+ } else {+ crate::i18n::tr("settings-agent-panel-disabled")+ };+ if let Some(front_end) = crate::frontend::try_front_end() {+ front_end.invalidate_all_windows();+ }+ }+ Err(err) => {+ self.status = format!("Unable to save agent panel setting: {err:#}");+ }+ }+ }+ SettingsAction::ToggleAgentDetails(agent_id) => {+ self.ui.open_dropdown = None;+ self.agents_expanded = if self.agents_expanded == Some(agent_id) {+ None+ } else {+ Some(agent_id)+ };+ }SettingsAction::ShowOnboardingNow => {self.ui.open_dropdown = None;let Some(front_end) = crate::frontend::try_front_end() else {@@ -4105,6 +4243,7 @@ impl SettingsWindow {SettingsSection::General => self.paint_general(layers, x, max_width)?,SettingsSection::Terminal => self.paint_terminal(layers, x, max_width)?,SettingsSection::Workspaces => self.paint_workspaces(layers, x, max_width)?,+ SettingsSection::Agents => self.paint_agents(layers, x, max_width)?,SettingsSection::Keymap => self.paint_placeholder(layers,&ui_font,@@ -4502,6 +4641,239 @@ impl SettingsWindow {)}+ fn paint_agents(+ &mut self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ max_width: f32,+ ) -> anyhow::Result<()> {+ let palette = self.palette();+ let ui_font = Rc::clone(&self.ui_font);+ let scroll = self.ui.content_scroll.offset;+ let section_y = self.ui_px(CONTENT_SECTION_Y) - scroll;++ // Card 1: the panel/detection feature toggle.+ let toggle_row_count = 1;+ let (card_y, first_row_y) = self.settings_card_geometry(section_y, toggle_row_count);+ let card_height = self.settings_card_height(toggle_row_count);+ // Card 2: one row per supported agent. Clicking a row expands an+ // inset card explaining how that agent is covered; the outer card+ // grows by the detail block's height.+ let integrations_row_count = crate::agent_status::SUPPORTED_AGENTS.len();+ let padding = 36.0;+ let row_x = x + padding;+ let row_width = max_width - padding * 2.0;+ let cell_height = self.metrics.cell_size.height as f32;+ let row_step = self.settings_row_step();+ let detail_line_step = (cell_height + self.ui_px(8.0)).max(self.ui_px(24.0));+ let detail_text_inset = self.ui_px(16.0);+ // Wrapped detail lines for the expanded row, computed up front so+ // the card height is known before anything paints.+ let expanded_detail: Option<Vec<String>> = self.agents_expanded.and_then(|expanded| {+ crate::agent_status::SUPPORTED_AGENTS+ .iter()+ .find(|(id, _, _)| *id == expanded)+ .map(|(id, _, kind)| {+ agent_detail_lines(id, *kind)+ .iter()+ .flat_map(|text| {+ self.wrap_settings_text(+ &ui_font,+ text,+ row_width - detail_text_inset * 2.0,+ )+ })+ .collect()+ })+ });+ // Where the inset card sits relative to its row's top, and how much+ // taller the row becomes.+ let desc_offset = (cell_height + self.ui_px(8.0)).max(self.ui_px(34.0));+ let detail_block_rel_y = desc_offset + cell_height + self.ui_px(12.0);+ let detail_block_height = expanded_detail+ .as_ref()+ .map(|lines| lines.len() as f32 * detail_line_step + self.ui_px(22.0))+ .unwrap_or(0.0);+ let expanded_extra = expanded_detail+ .as_ref()+ .map(|_| {+ (detail_block_rel_y + detail_block_height + self.ui_px(18.0) - row_step).max(0.0)+ })+ .unwrap_or(0.0);+ let integrations_title_y = card_y + card_height + self.settings_section_card_gap();+ let integrations_card_y =+ integrations_title_y + self.settings_section_card_gap().min(54.0);+ let integrations_first_row_y = integrations_card_y + self.settings_card_top_padding();+ let mut integrations_card_height =+ self.settings_card_height(integrations_row_count) + expanded_extra;+ // The card budgets less than a full row_step for its final row, so+ // an expansion of the *last* row would overhang the card's bottom+ // border; grow the card to contain the block plus breathing room.+ let last_agent_expanded = self.agents_expanded.is_some()+ && self.agents_expanded+ == crate::agent_status::SUPPORTED_AGENTS+ .last()+ .map(|(id, _, _)| *id);+ if last_agent_expanded && expanded_detail.is_some() {+ let block_bottom = self.settings_card_top_padding()+ + integrations_row_count.saturating_sub(1) as f32 * row_step+ + detail_block_rel_y+ + detail_block_height;+ integrations_card_height =+ integrations_card_height.max(block_bottom + self.ui_px(18.0));+ }+ self.ui.content_scroll.set_extents(+ self.content_viewport_extent(),+ self.settings_content_extent(integrations_card_y + scroll + integrations_card_height),+ );++ self.draw_text(+ layers,+ &ui_font,+ x,+ section_y,+ &crate::i18n::tr("settings-agents-heading"),+ palette.muted_text,+ max_width,+ )?;+ self.paint_group_card(layers, x, card_y, max_width, card_height)?;+ self.paint_toggle_setting_row(+ layers,+ row_x,+ first_row_y,+ row_width,+ &crate::i18n::tr("settings-agent-panel"),+ &crate::i18n::tr("settings-agent-panel-description"),+ self.native_settings.chrome.agent_panel_enabled,+ SettingsAction::ToggleAgentPanel,+ // Sole row in its card: a top rule would just underline the+ // group heading for no reason.+ false,+ )?;++ self.draw_text(+ layers,+ &ui_font,+ x,+ integrations_title_y,+ &crate::i18n::tr("settings-agents-integrations-heading"),+ palette.muted_text,+ max_width,+ )?;+ self.paint_group_card(+ layers,+ x,+ integrations_card_y,+ max_width,+ integrations_card_height,+ )?;++ // One row per supported agent; every row expands on click with an+ // explanation of how that agent is covered. Nothing here is+ // installable: detection is screen-rule driven for everyone.+ use crate::agent_status::IntegrationKind;+ let mut row_y = integrations_first_row_y;+ let mut draw_top_rule = false;+ let mut prev_expanded = false;+ for (agent_id, _names, kind) in crate::agent_status::SUPPORTED_AGENTS {+ let expanded = self.agents_expanded == Some(*agent_id);+ let arrow = if expanded { "\u{25be}" } else { "\u{25b8}" };+ let label = format!(+ "{arrow} {}",+ crate::agent_status::display_name(agent_id)+ );+ let on_path = crate::agent_status::agent_on_path(agent_id);+ let description = match kind {+ IntegrationKind::Native => {+ crate::i18n::tr("settings-integration-native")+ }+ IntegrationKind::Pending => {+ crate::i18n::tr("settings-integration-pending")+ }+ IntegrationKind::ScreenRules if on_path => {+ crate::i18n::tr("settings-integration-screen-active")+ }+ IntegrationKind::ScreenRules => {+ crate::i18n::tr("settings-integration-screen-missing")+ }+ };+ // No separator right after an expanded row: `row_y` includes+ // the detail block, so the rule would cut across its card; the+ // frame itself already separates.+ if draw_top_rule && !prev_expanded {+ self.paint_separator(+ layers,+ row_x,+ row_y - self.ui_px(28.0),+ row_width,+ )?;+ }+ self.draw_text(+ layers,+ &ui_font,+ row_x,+ row_y,+ &label,+ palette.text,+ row_width,+ )?;+ self.draw_text(+ layers,+ &ui_font,+ row_x,+ self.settings_row_description_y(row_y),+ &description,+ palette.secondary_text,+ row_width,+ )?;+ self.ui_context.push(+ rect(+ row_x,+ row_y - self.ui_px(6.0),+ row_width,+ self.ui_px(56.0),+ ),+ crate::ui::WidgetKind::Button,+ SettingsAction::ToggleAgentDetails(agent_id),+ );+ let row_top = row_y;+ row_y += row_step;+ if expanded {+ if let Some(lines) = &expanded_detail {+ let block_y = row_top + detail_block_rel_y;+ self.draw_rounded_frame(+ layers,+ 0,+ row_x,+ block_y,+ row_width,+ detail_block_height,+ palette.control_bg,+ palette.rule,+ self.ui_px(10.0),+ )?;+ let mut detail_y = block_y + self.ui_px(12.0);+ for line in lines {+ self.draw_text(+ layers,+ &ui_font,+ row_x + detail_text_inset,+ detail_y,+ line,+ palette.secondary_text,+ row_width - detail_text_inset * 2.0,+ )?;+ detail_y += detail_line_step;+ }+ }+ row_y += expanded_extra;+ }+ draw_top_rule = true;+ prev_expanded = expanded;+ }+ Ok(())+ }+fn paint_terminal(&mut self,layers: &mut TripleLayerQuadAllocator<'_>,@@ -7882,6 +8254,55 @@ impl SettingsWindow {self.shape_cache.borrow_mut().clear();}+ /// Greedy word wrap against the shaped width; falls back to char-level+ /// breaking for unspaced (CJK) text or overlong tokens.+ fn wrap_settings_text(+ &self,+ font: &Rc<LoadedFont>,+ text: &str,+ max_width: f32,+ ) -> Vec<String> {+ let mut lines = Vec::new();+ let mut current = String::new();+ let push_wrapped_word = |word: &str, current: &mut String, lines: &mut Vec<String>| {+ let mut piece = String::new();+ for ch in word.chars() {+ let mut candidate = piece.clone();+ candidate.push(ch);+ if !piece.is_empty() && self.measure_text_width(font, &candidate) > max_width {+ lines.push(std::mem::take(&mut piece));+ piece.push(ch);+ } else {+ piece = candidate;+ }+ }+ *current = piece;+ };+ for word in text.split_whitespace() {+ let candidate = if current.is_empty() {+ word.to_string()+ } else {+ format!("{current} {word}")+ };+ if self.measure_text_width(font, &candidate) <= max_width {+ current = candidate;+ } else if current.is_empty() {+ push_wrapped_word(word, &mut current, &mut lines);+ } else {+ lines.push(std::mem::take(&mut current));+ if self.measure_text_width(font, word) <= max_width {+ current = word.to_string();+ } else {+ push_wrapped_word(word, &mut current, &mut lines);+ }+ }+ }+ if !current.is_empty() {+ lines.push(current);+ }+ lines+ }+fn measure_text_width(&self, font: &Rc<LoadedFont>, text: &str) -> f32 {self.shaped_text(font, text).map(|shaped| shaped.width)diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex ed9464d0..d9547d95 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -581,6 +581,8 @@ pub enum UIItemType {RightSidebarSnippetDelete(String),RightSidebarSnippetScrollTrack,RightSidebarSnippetScrollThumb,+ /// A control in the Agents panel.+ RightSidebarAgent(crate::agent_status::AgentPanelAction),RightSidebarNoteMenu,RightSidebarNoteChooseVault,RightSidebarNoteCreateVault,@@ -628,6 +630,9 @@ pub enum RightSidebarMode {Chat,Tasks,Snippets,+ /// Agent status panel; only offered while the agent-panel feature+ /// toggle is on (`crate::agent_status::enabled`).+ Agents,}#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -1949,6 +1954,7 @@ pub struct TermWindow {right_sidebar_width: usize,right_sidebar_collapsed: bool,right_sidebar_mode: RightSidebarMode,+ right_sidebar_agents_scroll: f32,right_sidebar_snippet_view: RightSidebarSnippetView,right_sidebar_snippet_focus: Option<RightSidebarSnippetField>,right_sidebar_snippet_search: TextInputState,@@ -2907,6 +2913,7 @@ impl TermWindow {right_sidebar_width: ui::right_sidebar_width_for_metrics(&render_metrics, dpi as usize),right_sidebar_collapsed: true,right_sidebar_mode: RightSidebarMode::Snippets,+ right_sidebar_agents_scroll: 0.0,right_sidebar_snippet_view: RightSidebarSnippetView::List,right_sidebar_snippet_focus: None,right_sidebar_snippet_search: TextInputState::new(),@@ -3795,6 +3802,20 @@ impl TermWindow {MuxNotification::PaneOutput(pane_id) => {self.mux_pane_output_event(pane_id);}+ MuxNotification::AgentStatusChanged(pane_id) => {+ // 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();+ }+ }+ }MuxNotification::WindowInvalidated(_) => {window.invalidate();self.update_title_post_status();@@ -4235,6 +4256,7 @@ impl TermWindow {}| MuxNotification::PaneFocused(pane_id)| MuxNotification::PaneRemoved(pane_id)+ | MuxNotification::AgentStatusChanged(pane_id)| MuxNotification::PaneOutput(pane_id) => {// Ideally we'd check to see if pane_id is part of this window,// but overlays may not be 100% associated with the windowdiff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex eb4b8d0b..d6a99bf2 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -1364,6 +1364,14 @@ impl super::TermWindow {context.invalidate();}}+ super::RightSidebarMode::Agents => {+ let old = self.right_sidebar_agents_scroll;+ self.right_sidebar_agents_scroll =+ (self.right_sidebar_agents_scroll + delta).max(0.0);+ if (old - self.right_sidebar_agents_scroll).abs() > f32::EPSILON {+ context.invalidate();+ }+ }}true}@@ -1414,6 +1422,7 @@ impl super::TermWindow {| UIItemType::RightSidebarFilePreviewResize| UIItemType::RightSidebarNotePaneResize| UIItemType::RightSidebarNotePaneToggle+ | UIItemType::RightSidebarAgent(_)| UIItemType::RightSidebarSnippetNew| UIItemType::RightSidebarSnippetBack| UIItemType::RightSidebarSnippetSave@@ -1526,6 +1535,7 @@ impl super::TermWindow {| UIItemType::RightSidebarFilePreviewResize| UIItemType::RightSidebarNotePaneResize| UIItemType::RightSidebarNotePaneToggle+ | UIItemType::RightSidebarAgent(_)| UIItemType::RightSidebarSnippetNew| UIItemType::RightSidebarSnippetBack| UIItemType::RightSidebarSnippetSave@@ -3567,6 +3577,9 @@ impl super::TermWindow {| UIItemType::RightSidebarSnippetDelete(_) => {self.mouse_event_right_sidebar_snippet(item.clone(), event, context);}+ UIItemType::RightSidebarAgent(_) => {+ self.mouse_event_right_sidebar_agent(item.clone(), event, context);+ }UIItemType::RightSidebarNoteMenu| UIItemType::RightSidebarNoteChooseVault| UIItemType::RightSidebarNoteCreateVault@@ -4108,6 +4121,9 @@ impl super::TermWindow {| UIItemType::RightSidebarSnippetDelete(_) => {self.mouse_event_right_sidebar_snippet(item.clone(), event, context);}+ UIItemType::RightSidebarAgent(_) => {+ self.mouse_event_right_sidebar_agent(item.clone(), event, context);+ }UIItemType::RightSidebarNoteMenu| UIItemType::RightSidebarNoteChooseVault| UIItemType::RightSidebarNoteCreateVaultdiff --git a/wezterm-gui/src/termwindow/ui/agent_panel.rs b/wezterm-gui/src/termwindow/ui/agent_panel.rsnew file mode 100644index 00000000..3c2b316c--- /dev/null+++ b/wezterm-gui/src/termwindow/ui/agent_panel.rs@@ -0,0 +1,759 @@+//! The right-sidebar Agents panel: lists panes running detected coding+//! agents with their live state. Painted only while the agent-panel+//! feature toggle is on; all data comes from `crate::agent_status`+//! snapshots — the paint path never triggers detection or filesystem+//! probes.++use crate::agent_status::{self, AgentPanelAction, AgentState};+use crate::quad::TripleLayerQuadAllocator;+use crate::termwindow::ui::icons::SvgIcon;+use crate::termwindow::ui::right_sidebar::{+ right_sidebar_file_row_metrics, sidebar_row_element_visible, FILE_SCROLL_FADE_HEIGHT,+};+use crate::termwindow::ui::tokens::{SIDEBAR_INSET, SIDEBAR_ROW_RADIUS};+use crate::termwindow::{TermWindow, TermWindowNotif, UIItem, UIItemType};+use crate::ui::UiPalette;+use crate::utilsprites::RenderMetrics;+use anyhow::Context;+use mux::pane::PaneId;+use mux::Mux;+use std::rc::Rc;+use wezterm_client::domain::FrontendRecoverySlot;+use wezterm_font::LoadedFont;+use window::color::LinearRgba;+use window::{MouseEvent, MouseEventKind as WMEK, MousePress, WindowOps};++impl TermWindow {+ /// Height of the strip above the list: the reload button, the optional+ /// status line, and the gap before the first row. The scroll mask covers+ /// exactly this, so the two must be derived from the same numbers.+ fn agents_toolbar_height(&self, cell_height: usize, has_status: bool) -> usize {+ let status_height = if has_status {+ self.ui_px(6) + cell_height+ } else {+ 0+ };+ // This strip doubles as the top scroll mask, and it only has to+ // swallow a single element's overflow -- the card behind them is+ // clipped geometrically -- so the ordinary gap is already tall enough.+ self.agents_toolbar_button_height(cell_height) + status_height + self.ui_px(8)+ }++ /// Two lines -- identity, then state and place -- with the same share of+ /// vertical padding a file row gives its single line.+ fn agents_row_height(&self, cell_height: usize) -> (usize, usize) {+ let line_gap = (cell_height * 3 / 10).max(1);+ let padding = (cell_height * 7 / 10).max(1);+ (cell_height * 2 + line_gap + padding, line_gap)+ }++ fn agents_toolbar_button_height(&self, cell_height: usize) -> usize {+ (cell_height + self.ui_px(12)).max(self.ui_px(28))+ }++ /// Painted on layer 2 *after* the rows: the rows are drawn unclipped and a+ /// mask erases whatever overflows above the list, so the toolbar has to go+ /// back on top of that mask.+ #[allow(clippy::too_many_arguments)]+ fn paint_agents_toolbar(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ ui_font: &Rc<LoadedFont>,+ ui_metrics: RenderMetrics,+ chrome: UiPalette,+ foreground: LinearRgba,+ muted_fg: LinearRgba,+ content_x: usize,+ content_top: usize,+ content_width: usize,+ status: Option<&str>,+ ) -> anyhow::Result<()> {+ let cell_height = ui_metrics.cell_size.height as usize;+ let button_height = self.agents_toolbar_button_height(cell_height);+ self.paint_snippet_button(+ layers,+ 2,+ ui_font,+ ui_metrics,+ chrome,+ foreground,+ muted_fg,+ content_x,+ content_top,+ content_width,+ button_height,+ Some(SvgIcon::RotateCw),+ &crate::i18n::tr("right-agents-reload-rules"),+ UIItemType::RightSidebarAgent(AgentPanelAction::ReloadRules),+ true,+ )?;+ if let Some(status) = status {+ // The acknowledgement expires by TTL, but expiry alone paints+ // nothing; keep a lazy repaint scheduled while it is visible.+ self.update_next_frame_time(Some(+ std::time::Instant::now() + std::time::Duration::from_millis(500),+ ));+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ status,+ content_x + self.ui_px(SIDEBAR_INSET),+ content_top + button_height + self.ui_px(6),+ content_width.saturating_sub(self.ui_px(SIDEBAR_INSET) * 2),+ muted_fg,+ )?;+ }+ Ok(())+ }++ #[allow(clippy::too_many_arguments)]+ pub(crate) fn paint_agents_sidebar(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ ui_font: &Rc<LoadedFont>,+ ui_metrics: RenderMetrics,+ chrome: UiPalette,+ foreground: LinearRgba,+ muted_fg: LinearRgba,+ content_x: usize,+ content_top: usize,+ content_width: usize,+ content_bottom: usize,+ ) -> anyhow::Result<()> {+ let cell_height = ui_metrics.cell_size.height as usize;+ let (row_height, line_gap) = self.agents_row_height(cell_height);+ // Read once: the status expires on a TTL, and asking twice could size+ // the toolbar for one layout and paint another.+ let status = agent_status::panel_status();+ let toolbar_height = self.agents_toolbar_height(cell_height, status.is_some());+ let list_top = content_top + toolbar_height;+ let inset = self.ui_px(SIDEBAR_INSET);++ let mut agents = agent_status::list_agent_panes();+ if agents.is_empty() {+ let card_height = (cell_height * 2 + self.ui_px(24))+ .min(content_bottom.saturating_sub(list_top + inset));+ if card_height > 0 {+ self.fill_rounded_rectangle_with_border(+ layers,+ 1,+ euclid::rect(+ content_x as f32,+ list_top as f32,+ content_width as f32,+ card_height as f32,+ ),+ chrome.sidebar_button_bg,+ chrome.control_border.mul_alpha(0.74),+ self.ui_f32(SIDEBAR_ROW_RADIUS) + 6.0,+ 1.0,+ )+ .context("agents empty state card")?;+ let pad = inset * 2;+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ &crate::i18n::tr("right-agents-empty"),+ content_x + pad,+ list_top + self.ui_px(10),+ content_width.saturating_sub(pad * 2),+ foreground,+ )?;+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ &crate::i18n::tr("right-agents-empty-hint"),+ content_x + pad,+ list_top + self.ui_px(12) + cell_height,+ content_width.saturating_sub(pad * 2),+ muted_fg,+ )?;+ }+ return self.paint_agents_toolbar(+ layers,+ ui_font,+ ui_metrics,+ chrome,+ foreground,+ muted_fg,+ content_x,+ content_top,+ content_width,+ status.as_deref(),+ );+ }++ // Rows for the current window's workspace first, then stable order.+ let current_workspace = Mux::get().active_workspace();+ agents.sort_by(|a, b| {+ let a_here = a.workspace == current_workspace;+ let b_here = b.workspace == current_workspace;+ b_here+ .cmp(&a_here)+ .then_with(|| a.agent_id.cmp(&b.agent_id))+ .then_with(|| a.pane_id.cmp(&b.pane_id))+ });++ // Borrow the file tree's row chrome wholesale so the two lists read as+ // one control: same height, same icon size, same gaps, all derived from+ // the font instead of from physical-pixel constants. Rows sit flush+ // against each other -- no gap, no card, no border.+ let metrics = right_sidebar_file_row_metrics(ui_metrics);+ // The panel's bottom padding, which doubles as the mask that keeps+ // rows out of it. Whatever overshoots it runs past the panel, where+ // the window edge cuts it -- unless a tab bar sits at the bottom:+ // its background is painted on layer 0 while these glyphs are on+ // layer 2, and layer index beats paint order, so overflow would land+ // *on top of* the bar. In that configuration the panel bottom+ // (already the tab bar's top edge, see right_sidebar_rect) must+ // bound the rows instead.+ let viewport_bottom = content_bottom.saturating_sub(inset * 2);+ let masked_below = self.show_tab_bar && self.config.tab_bar_at_bottom;+ let overflow_bottom = if masked_below {+ content_bottom+ } else {+ usize::MAX+ };+ // Unmasked, rows run to the window edge and are cut there; their+ // hover chrome must reach as far, or glyphs outrun their tint.+ let row_clip_bottom = if masked_below {+ viewport_bottom+ } else {+ content_bottom+ };+ // An element is painted while it straddles an edge, because something+ // cuts it: the header mask above, the window edge below. That is the+ // whole difference between this and withholding it until it fits,+ // which is what made the list step.+ let visible = |elem_y: usize, elem_height: usize| {+ sidebar_row_element_visible(elem_y, elem_height, content_top, list_top, overflow_bottom)+ };+ let visible_height = viewport_bottom.saturating_sub(list_top);+ let total_height = agents.len().saturating_mul(row_height);+ 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_height) as f32 - scroll;+ if row_top + row_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)+ 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,+ content_width,+ band.visible_height,+ );+ if hovered {+ self.fill_rounded_rectangle(+ layers,+ 1,+ euclid::rect(+ content_x as f32,+ band.visible_y as f32,+ content_width as f32,+ band.visible_height as f32,+ ),+ chrome.sidebar_button_hover_bg,+ self.ui_f32(SIDEBAR_ROW_RADIUS),+ )+ .context("agent row hover")?;+ }+ let in_this_window = agent.window_id == Some(self.mux_window_id);+ self.ui_items.push(UIItem {+ x: content_x,+ y: band.visible_y,+ width: content_width,+ height: band.visible_height,+ item_type: UIItemType::RightSidebarAgent(if in_this_window {+ AgentPanelAction::Reveal(agent.pane_id)+ } else {+ AgentPanelAction::RevealElsewhere(agent.pane_id)+ }),+ });++ 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) {+ self.paint_sidebar_icon(+ layers,+ SvgIcon::Bot,+ icon_x,+ icon_y,+ metrics.icon_size,+ muted_fg,+ )?;+ }++ // 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 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;+ let state_icon = match agent.state {+ AgentState::Working => Some((SvgIcon::LoaderCircle, foreground, true)),+ AgentState::Blocked => Some((SvgIcon::CircleAlert, foreground, false)),+ AgentState::Idle => Some((SvgIcon::CircleCheck, muted_fg, false)),+ AgentState::Unknown => None,+ };+ let has_state_icon = state_icon.is_some();+ if let Some((icon, color, spinning)) = state_icon.filter(|_| visible(state_y, state_size))+ {+ if spinning {+ self.paint_spinning_ui_icon(+ layers,+ 2,+ icon,+ state_x,+ state_y,+ state_size,+ color,+ )?;+ } else {+ self.paint_sidebar_icon(layers, icon, state_x, state_y, state_size, color)?;+ }+ }++ let text_x = icon_x + metrics.icon_size + metrics.icon_gap;+ let text_right = if has_state_icon {+ state_x.saturating_sub(metrics.icon_gap)+ } else {+ content_x + content_width - inset+ };+ let text_width = text_right.saturating_sub(text_x);+ let title_y = top + (row_height.saturating_sub(cell_height * 2 + line_gap)) / 2;+ let name = agent_status::display_name(&agent.agent_id);+ let title_line = if agent.title.is_empty() {+ name+ } else {+ format!("{name} · {}", agent.title)+ };+ if visible(title_y, cell_height) {+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ &title_line,+ text_x,+ title_y,+ text_width,+ 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"),+ };+ // 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() {+ state_label+ } else {+ format!("{state_label} · {}", agent.place)+ };+ let detail_y = title_y + cell_height + line_gap;+ if visible(detail_y, cell_height) {+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ &detail_line,+ text_x,+ detail_y,+ text_width,+ muted_fg,+ )?;+ }+ }++ let scrolled = max_scroll > 0.0 && scroll > 0.0;+ // Only a bottom tab bar needs protecting from row overflow; with+ // the window edge below, rows run to it and are cut there.+ if max_scroll > 0.0 && masked_below {+ self.paint_right_sidebar_file_mask(+ layers,+ chrome,+ content_x,+ viewport_bottom,+ content_width,+ content_bottom.saturating_sub(viewport_bottom),+ )?;+ }+ // Above the list sits the toolbar strip and nothing paints over it+ // afterwards: repaint it opaque, put the toolbar back on top, then+ // soften the cut.+ if scrolled {+ self.paint_right_sidebar_file_mask(+ layers,+ chrome,+ content_x,+ content_top,+ content_width,+ toolbar_height,+ )?;+ }+ self.paint_agents_toolbar(+ layers,+ ui_font,+ ui_metrics,+ chrome,+ foreground,+ muted_fg,+ content_x,+ content_top,+ content_width,+ status.as_deref(),+ )?;+ if scrolled {+ let fade_height = self+ .ui_px(FILE_SCROLL_FADE_HEIGHT)+ .min(viewport_bottom.saturating_sub(list_top));+ self.paint_right_sidebar_file_top_fade(+ layers,+ chrome,+ content_x,+ list_top,+ content_width,+ fade_height,+ )?;+ }++ Ok(())+ }++ pub(crate) fn mouse_event_right_sidebar_agent(+ &mut self,+ item: UIItem,+ event: MouseEvent,+ context: &dyn WindowOps,+ ) {+ let UIItemType::RightSidebarAgent(action) = item.item_type else {+ return;+ };+ context.set_cursor(Some(window::MouseCursor::Hand));+ if event.kind != WMEK::Press(MousePress::Left) {+ return;+ }+ match action {+ AgentPanelAction::ReloadRules => {+ // The reload reads manifest files; keep that off the GUI+ // thread and report completion when it lands.+ std::thread::spawn(|| {+ mux::agent_status::reload_rules();+ promise::spawn::spawn_into_main_thread(async {+ agent_status::set_panel_status(crate::i18n::tr(+ "right-agents-rules-reloaded",+ ));+ if let Some(front_end) = crate::frontend::try_front_end() {+ front_end.invalidate_all_windows();+ }+ })+ .detach();+ });+ }+ AgentPanelAction::Reveal(pane_id) => {+ self.reveal_agent_pane(pane_id);+ }+ AgentPanelAction::RevealElsewhere(pane_id) => {+ self.reveal_agent_pane_elsewhere(pane_id, context);+ }+ }+ context.invalidate();+ }++ /// The agent lives in another window: deep-focus its tab and pane in+ /// the owning mux window first, then activate the backing thread —+ /// the same path a left-sidebar thread click takes, which switches+ /// the workspace and brings the right window forward. The activated+ /// window then comes up already pointing at the agent.+ fn reveal_agent_pane_elsewhere(&mut self, pane_id: PaneId, context: &dyn WindowOps) {+ let mux = Mux::get();+ let Some((_domain, window_id, tab_id)) = mux.resolve_pane_id(pane_id) else {+ return;+ };+ let tab_idx = mux.get_window(window_id).and_then(|window| {+ (0..window.len()).find(|idx| {+ window+ .get_by_idx(*idx)+ .map(|tab| tab.tab_id() == tab_id)+ .unwrap_or(false)+ })+ });+ if let Some(idx) = tab_idx {+ if let Some(mut window) = mux.get_window_mut(window_id) {+ window.save_and_then_set_active(idx);+ }+ }+ if let (Some(tab), Some(pane)) = (mux.get_tab(tab_id), mux.get_pane(pane_id)) {+ tab.set_active_pane(&pane);+ }+ let Some(workspace) = mux+ .get_window(window_id)+ .map(|window| window.get_workspace().to_string())+ else {+ return;+ };+ if let Some(thread_id) =+ crate::workspace_threads::thread_id_for_workspace_any(&workspace)+ {+ // Only a thread of this Space (or one it references) can be+ // activated here; activate_workspace_thread's guard silently+ // drops anything else, which used to make these clicks no-ops.+ let home_space = crate::workspace_threads::thread_space_id(&thread_id);+ let in_this_space =+ home_space.as_deref() == Some(self.active_space_id.as_str());+ let referenced = !in_this_space+ && crate::workspace_threads::thread_ref_exists(+ &self.active_space_id,+ &thread_id,+ );+ if in_this_space || referenced {+ self.activate_workspace_thread(thread_id, context);+ return;+ }+ let Some(home_space) = home_space else {+ return;+ };+ // The thread belongs to another Space. Hand the activation to+ // the window owning that Space, inside that window's own event+ // loop -- the mux-window lookup would only find a window that+ // is already displaying this very thread, which is exactly the+ // case that cannot happen here. Same shape as live_overview's+ // open_thread_response.+ if let Some(target_owner_id) =+ crate::workspace_threads::window_owner_for_space(&home_space)+ {+ let Some(target) = crate::frontend::front_end()+ .gui_window_for_recovery_slot(FrontendRecoverySlot::Window(+ target_owner_id,+ ))+ else {+ return;+ };+ let target_window = target.window.clone();+ target.window.notify(TermWindowNotif::Apply(Box::new(+ move |target_term_window| {+ // Ownership can change between the click and this+ // callback; do not steal a Space on a stale lookup.+ if crate::workspace_threads::window_owner_for_space(&home_space)+ != Some(target_owner_id)+ || target_term_window.frontend_recovery_slot()+ != FrontendRecoverySlot::Window(target_owner_id)+ {+ return;+ }+ target_term_window+ .activate_workspace_thread(thread_id, &target_window);+ target_window.focus();+ },+ )));+ return;+ }+ // No window owns that Space: navigate this one there, exactly+ // as opening a windowless Space's thread does elsewhere.+ if let Some(window) = self.window.clone() {+ self.switch_space_to_thread(home_space, Some(thread_id), &window);+ }+ }+ }++ /// Focus the tab and pane hosting this agent, when it lives in this+ /// window.+ fn reveal_agent_pane(&mut self, pane_id: PaneId) {+ let mux = Mux::get();+ let Some((_domain, window_id, tab_id)) = mux.resolve_pane_id(pane_id) else {+ return;+ };+ if window_id != self.mux_window_id {+ return;+ }+ let tab_idx = {+ let Some(window) = mux.get_window(window_id) else {+ return;+ };+ (0..window.len()).find(|idx| {+ window+ .get_by_idx(*idx)+ .map(|tab| tab.tab_id() == tab_id)+ .unwrap_or(false)+ })+ };+ if let Some(idx) = tab_idx {+ if let Some(mut window) = mux.get_window_mut(window_id) {+ window.save_and_then_set_active(idx);+ }+ }+ if let (Some(tab), Some(pane)) = (mux.get_tab(tab_id), mux.get_pane(pane_id)) {+ tab.set_active_pane(&pane);+ }+ }+}++/// The slice of a list row that is actually inside the panel.+#[derive(Debug, PartialEq)]+struct AgentRowBand {+ /// Quantized top of the whole row, clipped or not. Row content is laid+ /// out from here so it keeps its place inside the card while the row+ /// scrolls under an edge.+ top: usize,+ /// Top of the part of the card that is inside `[clip_top, clip_bottom)`.+ visible_y: usize,+ visible_height: usize,+}++/// 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.+///+/// `row_top` is fractional so scrolling stays smooth, and goes negative once+/// a row has scrolled off the top. Returns `None` when no part of the row is+/// inside the band.+fn agent_row_visible_band(+ row_top: f32,+ row_height: usize,+ clip_top: usize,+ clip_bottom: usize,+) -> Option<AgentRowBand> {+ if row_height == 0 || clip_bottom <= clip_top {+ return None;+ }+ if row_top + row_height as f32 <= clip_top as f32 || row_top >= clip_bottom as f32 {+ return None;+ }+ // `max(0.0)` only bites when the list origin sits within one row height+ // of the window top, which the sidebar layout never does; it is here so+ // the cast of a negative top cannot wrap.+ let top = row_top.floor().max(0.0) as usize;+ let visible_y = top.max(clip_top);+ let visible_bottom = top.saturating_add(row_height).min(clip_bottom);+ let visible_height = visible_bottom.saturating_sub(visible_y);+ if visible_height == 0 {+ return None;+ }+ Some(AgentRowBand {+ top,+ visible_y,+ visible_height,+ })+}++#[cfg(test)]+mod tests {+ use super::{agent_row_visible_band, AgentRowBand};++ const H: usize = 52;+ const TOP: usize = 100;+ const BOTTOM: usize = 400;++ fn band(row_top: f32) -> Option<AgentRowBand> {+ agent_row_visible_band(row_top, H, TOP, BOTTOM)+ }++ #[test]+ fn fully_visible_row_is_unclipped() {+ assert_eq!(+ band(100.0),+ Some(AgentRowBand {+ top: 100,+ visible_y: 100,+ visible_height: 52+ })+ );+ }++ #[test]+ fn row_clipped_by_the_list_origin_keeps_its_content_anchor() {+ // `top` stays at the row's real top so the icons and text inside the+ // card do not slide while the row scrolls under the edge.+ assert_eq!(+ band(90.0),+ Some(AgentRowBand {+ top: 90,+ visible_y: 100,+ visible_height: 42+ })+ );+ }++ #[test]+ fn row_clipped_by_the_panel_edge() {+ assert_eq!(+ band(380.0),+ Some(AgentRowBand {+ top: 380,+ visible_y: 380,+ visible_height: 20+ })+ );+ }++ #[test]+ fn fractional_tops_quantize_down() {+ assert_eq!(+ band(100.6),+ Some(AgentRowBand {+ top: 100,+ visible_y: 100,+ visible_height: 52+ })+ );+ }++ #[test]+ fn rows_entirely_outside_the_band_are_dropped() {+ assert_eq!(band(48.0), None, "bottom edge exactly on clip_top");+ assert_eq!(band(47.0), None);+ assert_eq!(band(400.0), None, "top edge exactly on clip_bottom");+ assert_eq!(band(401.0), None);+ }++ #[test]+ fn a_row_taller_than_the_panel_fills_it() {+ assert_eq!(+ agent_row_visible_band(90.0, 500, TOP, BOTTOM),+ Some(AgentRowBand {+ top: 90,+ visible_y: 100,+ visible_height: 300+ })+ );+ }++ #[test]+ fn degenerate_inputs_paint_nothing() {+ assert_eq!(agent_row_visible_band(100.0, 0, TOP, BOTTOM), None);+ assert_eq!(agent_row_visible_band(100.0, H, BOTTOM, TOP), None);+ assert_eq!(agent_row_visible_band(100.0, H, TOP, TOP), None);+ }++ #[test]+ fn negative_tops_clamp_instead_of_wrapping() {+ assert_eq!(+ agent_row_visible_band(-10.0, H, 0, BOTTOM),+ Some(AgentRowBand {+ top: 0,+ visible_y: 0,+ visible_height: 52+ })+ );+ }+}diff --git a/wezterm-gui/src/termwindow/ui/icons.rs b/wezterm-gui/src/termwindow/ui/icons.rsindex 65a78595..55817dd6 100644--- a/wezterm-gui/src/termwindow/ui/icons.rs+++ b/wezterm-gui/src/termwindow/ui/icons.rs@@ -8,6 +8,7 @@ pub enum SvgIcon {ArrowLeft,ArrowRight,Bell,+ Bot,Braces,Check,ChevronDown,@@ -90,6 +91,7 @@ impl SvgIcon {include_bytes!("../../../../third_party/lucide/icons/arrow-right.svg")}Self::Bell => include_bytes!("../../../../third_party/lucide/icons/bell.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"),Self::ChevronDown => {diff --git a/wezterm-gui/src/termwindow/ui/mod.rs b/wezterm-gui/src/termwindow/ui/mod.rsindex c163d9f3..8fac2b0b 100644--- a/wezterm-gui/src/termwindow/ui/mod.rs+++ b/wezterm-gui/src/termwindow/ui/mod.rs@@ -1,3 +1,4 @@+pub mod agent_panel;pub mod context_menu;pub mod icons;pub mod platform_chrome;diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rsindex aa4c8867..c2f31406 100644--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs@@ -158,7 +158,7 @@ const FILE_FONT_MIN_SIZE: f64 = if cfg!(target_os = "macos") {};const FILE_FILTER_HEIGHT: usize = 66;const FILE_TREE_TOP_GAP: usize = 14;-const FILE_SCROLL_FADE_HEIGHT: usize = 32;+pub(crate) const FILE_SCROLL_FADE_HEIGHT: usize = 32;const FILE_PREVIEW_HEADER_HEIGHT: usize = 64;/// How many transfer rows the strip shows before it starts dropping the/// oldest finished ones. The strip eats into the tree, so it stays small;@@ -1098,12 +1098,12 @@ struct RightSidebarFileRoot {}#[derive(Debug, Clone, Copy, PartialEq, Eq)]-struct RightSidebarFileRowMetrics {- row_height: usize,- icon_size: usize,+pub(crate) struct RightSidebarFileRowMetrics {+ pub(crate) row_height: usize,+ pub(crate) icon_size: usize,chevron_size: usize,indent_step: usize,- icon_gap: usize,+ pub(crate) icon_gap: usize,}impl RightSidebarMode {@@ -1112,6 +1112,7 @@ impl RightSidebarMode {Self::Chat => SvgIcon::FolderTree,Self::Tasks => SvgIcon::NotebookTabs,Self::Snippets => SvgIcon::CodeXml,+ Self::Agents => SvgIcon::Bot,}}@@ -1120,6 +1121,7 @@ impl RightSidebarMode {Self::Chat => crate::i18n::tr("right-mode-files"),Self::Tasks => crate::i18n::tr("right-mode-notes"),Self::Snippets => crate::i18n::tr("right-mode-snippets"),+ Self::Agents => crate::i18n::tr("right-mode-agents"),}}}@@ -1667,6 +1669,7 @@ impl crate::TermWindow {RightSidebarMode::Chat => self.right_sidebar_file_focus.is_some(),RightSidebarMode::Snippets => self.right_sidebar_snippet_focus.is_some(),RightSidebarMode::Tasks => self.right_sidebar_note.view.focused,+ RightSidebarMode::Agents => false,}}@@ -4113,7 +4116,7 @@ impl crate::TermWindow {self.right_sidebar_snippet_scroll_offset = 0.0;}}- RightSidebarMode::Tasks => {}+ RightSidebarMode::Tasks | RightSidebarMode::Agents => {}}}@@ -5275,7 +5278,7 @@ impl crate::TermWindow {Some(RightSidebarSnippetField::Body) => Some(&self.right_sidebar_snippet_body),None => None,},- RightSidebarMode::Tasks => None,+ RightSidebarMode::Tasks | RightSidebarMode::Agents => None,}}@@ -5295,7 +5298,7 @@ impl crate::TermWindow {Some(RightSidebarSnippetField::Body) => Some(&mut self.right_sidebar_snippet_body),None => None,},- RightSidebarMode::Tasks => None,+ RightSidebarMode::Tasks | RightSidebarMode::Agents => None,}}@@ -6174,11 +6177,14 @@ impl crate::TermWindow {).context("right sidebar mode selector")?;- let modes = [+ let mut modes = vec![RightSidebarMode::Chat,RightSidebarMode::Tasks,RightSidebarMode::Snippets,];+ if crate::agent_status::enabled() {+ modes.push(RightSidebarMode::Agents);+ }const MODE_LABEL_CLIP_SLOP: usize = 4;let mode_icon_size = (ui_cell_height + self.ui_px(12)).clamp(self.ui_px(24), self.ui_px(30))@@ -6387,6 +6393,32 @@ impl crate::TermWindow {result?;return Ok(());}+ RightSidebarMode::Agents => {+ if !crate::agent_status::enabled() {+ // The toggle went off while the panel was open; fall+ // back rather than painting a stranded mode. This+ // frame's selector already painted for the old mode,+ // so request another paint or the body stays blank.+ self.right_sidebar_mode = RightSidebarMode::Chat;+ if let Some(win) = self.window.as_ref() {+ win.invalidate();+ }+ return Ok(());+ }+ self.paint_agents_sidebar(+ layers,+ &ui_font,+ ui_metrics,+ chrome,+ foreground,+ muted_fg,+ content_x,+ content_top,+ content_width,+ rect.y.saturating_add(rect.height),+ )?;+ return Ok(());+ }}}@@ -6753,6 +6785,7 @@ impl crate::TermWindow {let first_y = content_top + ui_metrics.cell_size.height as usize + self.ui_px(20);self.paint_snippet_button(layers,+ 1,ui_font,ui_metrics,chrome,@@ -6769,6 +6802,7 @@ impl crate::TermWindow {)?;self.paint_snippet_button(layers,+ 1,ui_font,ui_metrics,chrome,@@ -9659,10 +9693,11 @@ impl crate::TermWindow {muted_fg,)?;}- let fade_top = tree_top.saturating_sub(self.ui_px(FILE_TREE_TOP_GAP));+ // Full opacity exactly at the mask's bottom edge; see the+ // local tree above for why starting higher reads as a cut.+ let fade_top = tree_top;let fade_height = self- .ui_px(FILE_TREE_TOP_GAP)- .saturating_add(self.ui_px(FILE_SCROLL_FADE_HEIGHT))+ .ui_px(FILE_SCROLL_FADE_HEIGHT).min(viewport_bottom.saturating_sub(fade_top));self.paint_right_sidebar_file_top_fade(layers,@@ -13505,15 +13540,54 @@ impl crate::TermWindow {let row_metrics = right_sidebar_file_row_metrics(ui_metrics);// A copy started here must report itself here; the strip is shared// with the remote tree, so reserve its space the same way.+ // The transfer strip is the one thing that can sit under this list, and+ // it paints no background of its own, so rows must not run onto it.+ // With no strip there is nothing below at all: the panel ends at the+ // window edge, which cuts the overflow for free.let strip_rows = self.transfer_strip_rows(content_bottom.saturating_sub(tree_top).saturating_sub(self.ui_px(SIDEBAR_INSET)),row_metrics.row_height,);- let viewport_bottom = content_bottom+ let strip_top = content_bottom.saturating_sub(self.ui_px(SIDEBAR_INSET)).saturating_sub(strip_rows.saturating_mul(row_metrics.row_height));+ // The panel's bottom padding, which is also the mask that keeps rows+ // out of it. With a transfer strip below it has to swallow the row's+ // tallest element -- the inline rename box, `row_height - 4px` --+ // since anything it misses lands on the strip; without one the+ // window edge catches the rest, so plain padding is enough.+ let bottom_reserve = if strip_rows > 0 {+ (self.ui_px(SIDEBAR_INSET) * 2)+ .max(row_metrics.icon_size)+ .max(row_metrics.row_height.saturating_sub(self.ui_px(4)))+ } else {+ self.ui_px(SIDEBAR_INSET) * 2+ };+ let viewport_bottom = strip_top.saturating_sub(bottom_reserve);+ // How far a row may hang below the list: into the mask band while a+ // transfer strip is showing; otherwise as far as it likes -- unless+ // a bottom tab bar sits under the panel, whose layer-0 background+ // cannot cover these layer-2 glyphs, so the panel bottom must bound+ // them instead.+ let row_overflow_bottom = if strip_rows > 0 {+ strip_top+ } else if self.show_tab_bar && self.config.tab_bar_at_bottom {+ content_bottom+ } else {+ usize::MAX+ };+ // Whether anything below the list needs protecting from overflow.+ // Decides both the bottom mask and how far row chrome may extend:+ // unprotected, rows run to the window edge and are cut there.+ let masked_below =+ strip_rows > 0 || (self.show_tab_bar && self.config.tab_bar_at_bottom);+ let row_clip_bottom = if masked_below {+ viewport_bottom+ } else {+ content_bottom+ };let visible_height = viewport_bottom.saturating_sub(tree_top);let total_height = row_count.saturating_mul(row_metrics.row_height);let max_scroll = total_height.saturating_sub(visible_height) as f32;@@ -13568,16 +13642,21 @@ impl crate::TermWindow {&row,selected.as_ref(),tree_top,- viewport_bottom,+ row_clip_bottom,+ content_top,+ row_overflow_bottom,row_metrics,)?;}if max_scroll > 0.0 && scroll_offset > 0.0 {- let fade_top = content_top + self.ui_px(FILE_FILTER_HEIGHT);+ // The fade must take over exactly where the opaque mask ends+ // (tree_top), at full opacity. Starting it higher makes it+ // arrive at the mask edge already part-faded, which shows as+ // an alpha step -- a hard cut -- instead of a gradient.+ let fade_top = tree_top;let fade_height = self- .ui_px(FILE_TREE_TOP_GAP)- .saturating_add(self.ui_px(FILE_SCROLL_FADE_HEIGHT))+ .ui_px(FILE_SCROLL_FADE_HEIGHT).min(viewport_bottom.saturating_sub(fade_top));self.paint_right_sidebar_file_mask(layers,@@ -13626,6 +13705,22 @@ impl crate::TermWindow {)?;}+ // The bottom mask exists to keep overflow off whatever sits under+ // the list -- the transfer strip or a bottom tab bar. With neither+ // there is only the window edge below, and rows should run to it+ // and be cut there: slicing glyphs short of the edge and leaving a+ // dead band under the cut reads as a rendering bug, not padding.+ if max_scroll > 0.0 && masked_below {+ self.paint_right_sidebar_file_mask(+ layers,+ chrome,+ content_x,+ viewport_bottom,+ content_width,+ bottom_reserve,+ )?;+ }+self.paint_transfer_strip(layers,ui_font,@@ -13634,7 +13729,7 @@ impl crate::TermWindow {foreground,muted_fg,content_x,- viewport_bottom,+ strip_top,content_width,strip_rows,row_metrics,@@ -13726,7 +13821,7 @@ impl crate::TermWindow {)}- fn paint_right_sidebar_file_mask(+ pub(crate) fn paint_right_sidebar_file_mask(&mut self,layers: &mut TripleLayerQuadAllocator,chrome: UiPalette,@@ -13749,7 +13844,7 @@ impl crate::TermWindow {Ok(())}- fn paint_right_sidebar_file_top_fade(+ pub(crate) fn paint_right_sidebar_file_top_fade(&mut self,layers: &mut TripleLayerQuadAllocator,chrome: UiPalette,@@ -13793,6 +13888,11 @@ impl crate::TermWindow {selected: Option<&PathBuf>,clip_top: usize,clip_bottom: usize,+ // Bounds of the two opaque scroll masks. Row contents are quads that+ // cannot be scissored, so they are painted while they straddle an edge+ // and the mask cuts them; these say how far that is allowed to go.+ mask_top: usize,+ panel_bottom: usize,row_metrics: RightSidebarFileRowMetrics,) -> anyhow::Result<()> {let row_bottom = y.saturating_add(row_metrics.row_height);@@ -13836,6 +13936,9 @@ impl crate::TermWindow {item_type: UIItemType::RightSidebarFileRow(row.path.clone()),});+ let visible = |elem_y: usize, elem_height: usize| {+ sidebar_row_element_visible(elem_y, elem_height, mask_top, clip_top, panel_bottom)+ };let row_icon_size = row_metrics.icon_size;let chevron_size = row_metrics.chevron_size;let indent = row@@ -13845,7 +13948,7 @@ impl crate::TermWindow {let chevron_x = x + self.ui_px(SIDEBAR_INSET) + indent;let icon_y = y + (row_metrics.row_height.saturating_sub(row_icon_size)) / 2;let chevron_y = y + (row_metrics.row_height.saturating_sub(chevron_size)) / 2;- if row.is_dir {+ if row.is_dir && visible(chevron_y, chevron_size) {self.paint_sidebar_icon(layers,if row.is_expanded {@@ -13861,19 +13964,27 @@ impl crate::TermWindow {}let file_icon_x = chevron_x + chevron_size + row_metrics.icon_gap;- match file_icon_for_row(row) {- RightSidebarFileIcon::Material(icon) => {- self.paint_sidebar_material_icon(layers, icon, file_icon_x, icon_y, row_icon_size)?;- }- RightSidebarFileIcon::Svg(icon) => {- self.paint_sidebar_icon(- layers,- icon,- file_icon_x,- icon_y,- row_icon_size,- if row.is_dir { muted_fg } else { foreground },- )?;+ if visible(icon_y, row_icon_size) {+ match file_icon_for_row(row) {+ RightSidebarFileIcon::Material(icon) => {+ self.paint_sidebar_material_icon(+ layers,+ icon,+ file_icon_x,+ icon_y,+ row_icon_size,+ )?;+ }+ RightSidebarFileIcon::Svg(icon) => {+ self.paint_sidebar_icon(+ layers,+ icon,+ file_icon_x,+ icon_y,+ row_icon_size,+ if row.is_dir { muted_fg } else { foreground },+ )?;+ }}}let text_x = file_icon_x + row_icon_size + row_metrics.icon_gap;@@ -13881,42 +13992,49 @@ impl crate::TermWindow {.saturating_add(width).saturating_sub(text_x + self.ui_px(SIDEBAR_INSET));if let Some(input) = self.sidebar_file_rename_input(&row.path).cloned() {- self.paint_snippet_text_box(- layers,- 1,- ui_font,- ui_metrics,- chrome,- muted_fg,- text_x,- y + self.ui_px(2),- text_width,- row_metrics.row_height.saturating_sub(self.ui_px(4)),- None,- "",- &input,- true,- UIItemType::RightSidebarFileRow(row.path.clone()),- false,- )+ let box_y = y + self.ui_px(2);+ let box_height = row_metrics.row_height.saturating_sub(self.ui_px(4));+ if visible(box_y, box_height) {+ self.paint_snippet_text_box(+ layers,+ 1,+ ui_font,+ ui_metrics,+ chrome,+ muted_fg,+ text_x,+ box_y,+ text_width,+ box_height,+ None,+ "",+ &input,+ true,+ UIItemType::RightSidebarFileRow(row.path.clone()),+ false,+ )?;+ }+ Ok(())} else {- self.paint_sidebar_text(- layers,- ui_font,- ui_metrics,- &row.name,- text_x,- y + (row_metrics- .row_height- .saturating_sub(ui_metrics.cell_size.height as usize))- / 2,- text_width,- if row.is_dir || is_selected {- foreground- } else {- muted_fg- },- )+ let cell_height = ui_metrics.cell_size.height as usize;+ let text_y = y + (row_metrics.row_height.saturating_sub(cell_height)) / 2;+ if visible(text_y, cell_height) {+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ &row.name,+ text_x,+ text_y,+ text_width,+ if row.is_dir || is_selected {+ foreground+ } else {+ muted_fg+ },+ )?;+ }+ Ok(())}}@@ -14997,7 +15115,10 @@ impl crate::TermWindow {}#[allow(clippy::too_many_arguments)]- fn paint_snippets_list(+ /// The snippet list's fixed header. Painted on layer 2 *after* the cards,+ /// so it lands on top of the mask that erases their scroll overflow.+ #[allow(clippy::too_many_arguments)]+ fn paint_snippets_toolbar(&mut self,layers: &mut TripleLayerQuadAllocator,ui_font: &Rc<LoadedFont>,@@ -15008,8 +15129,6 @@ impl crate::TermWindow {content_x: usize,content_top: usize,content_width: usize,- content_bottom: usize,- icon_size: usize,) -> anyhow::Result<()> {let toolbar_y = content_top;let new_snippet_label = crate::i18n::tr("right-new-snippet");@@ -15040,6 +15159,7 @@ impl crate::TermWindow {};self.paint_snippet_button(layers,+ 2,ui_font,ui_metrics,chrome,@@ -15064,7 +15184,7 @@ impl crate::TermWindow {let search_input = self.right_sidebar_snippet_search.clone();self.paint_snippet_text_box(layers,- 1,+ 2,ui_font,ui_metrics,chrome,@@ -15082,7 +15202,24 @@ impl crate::TermWindow {)?;}- let list_top = toolbar_y+ Ok(())+ }++ fn paint_snippets_list(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ ui_font: &Rc<LoadedFont>,+ ui_metrics: RenderMetrics,+ chrome: UiPalette,+ foreground: LinearRgba,+ muted_fg: LinearRgba,+ content_x: usize,+ content_top: usize,+ content_width: usize,+ content_bottom: usize,+ icon_size: usize,+ ) -> anyhow::Result<()> {+ let list_top = content_top+ self.ui_px(SNIPPET_TOOLBAR_HEIGHT).max(self.ui_px(SNIPPET_SEARCH_HEIGHT))@@ -15101,7 +15238,11 @@ impl crate::TermWindow {}).collect();let row_height = self.ui_px(SNIPPET_CARD_HEIGHT) + self.ui_px(SNIPPET_ROW_GAP);- let visible_height = content_bottom.saturating_sub(list_top + self.ui_px(SIDEBAR_INSET));+ // The panel's bottom padding, which doubles as the mask that keeps+ // cards out of it; whatever overshoots it is cut by the window edge.+ // Matches the panel's own left and right margin.+ let bottom_reserve = self.ui_px(SIDEBAR_INSET) * 2;+ let visible_height = content_bottom.saturating_sub(list_top + bottom_reserve);let total_height = self.right_sidebar_snippet_scroll_height(snippets.len(), visible_height);let max_scroll = total_height.saturating_sub(visible_height) as f32;self.right_sidebar_snippet_scroll_offset = self@@ -15114,7 +15255,20 @@ impl crate::TermWindow {.ui_px(RIGHT_SIDEBAR_EMPTY_HEIGHT).min(content_bottom.saturating_sub(list_top + self.ui_px(SIDEBAR_INSET)));if empty_height == 0 {- return Ok(());+ // No room for the empty-state card, but the toolbar must+ // still paint: it holds the search box, and losing it here+ // would leave a non-matching filter impossible to clear.+ return self.paint_snippets_toolbar(+ layers,+ ui_font,+ ui_metrics,+ chrome,+ foreground,+ muted_fg,+ content_x,+ content_top,+ content_width,+ );}self.fill_rounded_rectangle_with_border(layers,@@ -15162,19 +15316,45 @@ impl crate::TermWindow {),muted_fg,)?;- return Ok(());+ return self.paint_snippets_toolbar(+ layers,+ ui_font,+ ui_metrics,+ chrome,+ foreground,+ muted_fg,+ content_x,+ content_top,+ content_width,+ );}let list_top_f = list_top as f32;- let content_bottom = content_bottom.saturating_sub(self.ui_px(SIDEBAR_INSET));- let content_bottom_f = content_bottom as f32;+ let viewport_bottom = content_bottom.saturating_sub(bottom_reserve);+ let viewport_bottom_f = viewport_bottom as f32;+ // Downward overflow past the panel is cut by the window edge --+ // except with a bottom tab bar, whose background lives on layer 0+ // under these layer-2 glyphs; then the panel bottom must bound it.+ let masked_below = self.show_tab_bar && self.config.tab_bar_at_bottom;+ let overflow_bottom = if masked_below {+ content_bottom+ } else {+ usize::MAX+ };+ // Unmasked, cards run to the window edge and are cut there; their+ // chrome must be allowed as far, or text outruns its card.+ let card_clip_bottom = if masked_below {+ viewport_bottom+ } else {+ content_bottom+ };for (idx, snippet) in snippets.into_iter().enumerate() {let row_top = list_top_f + (idx * row_height) as f32 - scroll_offset;let row_bottom = row_top + self.ui_px(SNIPPET_CARD_HEIGHT) as f32;if row_bottom <= list_top_f {continue;}- if row_top >= content_bottom_f {+ if row_top >= viewport_bottom_f {break;}let y = row_top.floor().max(0.0) as usize;@@ -15190,7 +15370,58 @@ impl crate::TermWindow {content_width,&snippet,list_top,- content_bottom,+ card_clip_bottom,+ content_top,+ overflow_bottom,+ )?;+ }++ // Only a bottom tab bar needs protecting from card overflow; with+ // the window edge below, cards run to it and are cut there.+ if max_scroll > 0.0 && masked_below {+ self.paint_right_sidebar_file_mask(+ layers,+ chrome,+ content_x,+ viewport_bottom,+ content_width,+ bottom_reserve,+ )?;+ }+ // Erase the overflow the cards were allowed to paint above the list,+ // then put the toolbar back on top of that mask.+ if max_scroll > 0.0 && scroll_offset > 0.0 {+ self.paint_right_sidebar_file_mask(+ layers,+ chrome,+ content_x,+ content_top,+ content_width,+ list_top.saturating_sub(content_top),+ )?;+ }+ self.paint_snippets_toolbar(+ layers,+ ui_font,+ ui_metrics,+ chrome,+ foreground,+ muted_fg,+ content_x,+ content_top,+ content_width,+ )?;+ if max_scroll > 0.0 && scroll_offset > 0.0 {+ let fade_height = self+ .ui_px(FILE_SCROLL_FADE_HEIGHT)+ .min(viewport_bottom.saturating_sub(list_top));+ self.paint_right_sidebar_file_top_fade(+ layers,+ chrome,+ content_x,+ list_top,+ content_width,+ fade_height,)?;}self.paint_right_sidebar_snippet_scrollbar(layers, chrome)?;@@ -15328,6 +15559,7 @@ impl crate::TermWindow {self.paint_snippet_button(layers,+ 1,ui_font,ui_metrics,chrome,@@ -15433,6 +15665,11 @@ impl crate::TermWindow {snippet: &crate::snippets::SnippetRecord,clip_top: usize,clip_bottom: usize,+ // Bounds of the two opaque scroll masks. Text is a quad the sidebar+ // cannot scissor, so a line is painted while it straddles an edge and+ // the mask cuts it; these say how far that may go.+ mask_top: usize,+ panel_bottom: usize,) -> anyhow::Result<()> {let card_bottom = y.saturating_add(self.ui_px(SNIPPET_CARD_HEIGHT));let visible_y = y.max(clip_top);@@ -15474,6 +15711,10 @@ impl crate::TermWindow {item_type: UIItemType::RightSidebarSnippetEdit(snippet.id.clone()),});+ let visible = |elem_y: usize, elem_height: usize| {+ sidebar_row_element_visible(elem_y, elem_height, mask_top, clip_top, panel_bottom)+ };+ let cell_height = ui_metrics.cell_size.height as usize;let card_pad = self.ui_px(SIDEBAR_INSET) * 2;let text_x = x + card_pad;let run_label = crate::i18n::tr("right-run");@@ -15494,7 +15735,7 @@ impl crate::TermWindow {0};let title_y = y + self.ui_px(SIDEBAR_INSET) * 2;- if title_y >= clip_top && title_y < clip_bottom {+ if visible(title_y, cell_height) {self.paint_sidebar_text(layers,ui_font,@@ -15507,9 +15748,8 @@ impl crate::TermWindow {)?;}let preview = snippet_preview(&snippet.body);- let preview_y =- y + self.ui_px(SIDEBAR_INSET) * 2 + ui_metrics.cell_size.height as usize + 8;- if preview_y >= clip_top && preview_y < clip_bottom {+ let preview_y = y + self.ui_px(SIDEBAR_INSET) * 2 + cell_height + 8;+ if visible(preview_y, cell_height) {self.paint_sidebar_text(layers,ui_font,@@ -15530,6 +15770,7 @@ impl crate::TermWindow {let action_y = y + self.ui_px(SIDEBAR_INSET) * 2 - 4;self.paint_snippet_button(layers,+ 1,ui_font,ui_metrics,chrome,@@ -15546,6 +15787,7 @@ impl crate::TermWindow {)?;self.paint_snippet_button(layers,+ 1,ui_font,ui_metrics,chrome,@@ -15811,9 +16053,12 @@ impl crate::TermWindow {}#[allow(clippy::too_many_arguments)]- fn paint_snippet_button(+ pub(crate) fn paint_snippet_button(&mut self,layers: &mut TripleLayerQuadAllocator,+ // Background layer. Callers that re-draw the button above a scroll+ // mask pass 2; everything else passes 1.+ layer: usize,ui_font: &Rc<LoadedFont>,ui_metrics: RenderMetrics,chrome: UiPalette,@@ -15842,7 +16087,7 @@ impl crate::TermWindow {};self.fill_rounded_rectangle_with_border(layers,- 1,+ layer,euclid::rect(x as f32, y as f32, width as f32, height as f32),fill,if hovered {@@ -16463,7 +16708,7 @@ fn preview_visible_line_range(start..end}-fn right_sidebar_file_row_metrics(ui_metrics: RenderMetrics) -> RightSidebarFileRowMetrics {+pub(crate) fn right_sidebar_file_row_metrics(ui_metrics: RenderMetrics) -> RightSidebarFileRowMetrics {// Font metrics already follow the window DPI. Derive the row chrome from// those metrics so the file tree keeps the same logical size across// displays instead of being pinned by physical-pixel clamps.@@ -16606,6 +16851,29 @@ fn open_with_candidate_rank(candidate: &wezterm_open_url::OpenWithCandidate) ->(rank, candidate.label.to_lowercase())}+/// Whether one element of a scrolling row -- an icon, a line of text -- may be+/// painted right now.+///+/// These are quads the sidebar cannot scissor, so a list hides their overflow+/// with opaque masks instead: one covering the strip above `list_top`, one+/// covering `panel_bottom` upwards. An element is therefore painted whenever+/// part of it is inside the list *and* whatever hangs outside lands in a mask.+/// That is what makes a list scroll steplessly: an element straddling an edge+/// is drawn and then cut, rather than withheld until it fits.+///+/// The two mask bands must each be at least as tall as the tallest element, or+/// the caller silently goes back to withholding elements near the edges.+pub(crate) fn sidebar_row_element_visible(+ elem_y: usize,+ elem_height: usize,+ mask_top: usize,+ list_top: usize,+ panel_bottom: usize,+) -> bool {+ let elem_bottom = elem_y.saturating_add(elem_height);+ elem_y >= mask_top && elem_bottom > list_top && elem_bottom <= panel_bottom+}+/// Where a tree row lands once the viewport is scrolled, or that it is outside/// the viewport entirely.#[derive(Debug, Clone, Copy, PartialEq)]@@ -18439,6 +18707,7 @@ mod tests {copy_entries_blocking, copy_file_chunked, download_name_candidates,encode_pasted_image_png, failed_folder_download, file_preview_close_requires_reflow,file_release_action, file_row_placement, full_line_colors_by_byte,+ sidebar_row_element_visible,image_pixels_within_preview_budget, load_file_preview, load_file_preview_image,naturalish_cmp, note_code_highlight_key, note_code_highlight_lines, note_code_row_height,note_image_display_size, note_open_pending_for_vault, note_release_action,@@ -19868,6 +20137,21 @@ mod tests {);}+ #[test]+ fn sidebar_row_elements_are_drawn_while_they_straddle_an_edge() {+ // mask strip 100..160, list 160..400, panel bottom 440 (a 40px bottom+ // mask). Elements are 30 tall.+ let vis = |y| sidebar_row_element_visible(y, 30, 100, 160, 440);+ assert!(vis(160), "fully inside");+ assert!(vis(140), "half out of the top -- drawn, then cut by the mask");+ assert!(vis(131), "one pixel of it still below list_top");+ assert!(!vis(130), "entirely above the list: nothing to show");+ assert!(vis(399), "half out of the bottom -- drawn, then cut");+ assert!(vis(410), "wholly inside the bottom mask, still safe to draw");+ assert!(!vis(411), "would cross the panel edge and escape the mask");+ assert!(!vis(99), "would escape above the top mask");+ }+#[test]fn visible_file_row_range_only_returns_rows_near_viewport() {let row_height = 44;diff --git a/wezterm-gui/src/termwindow/ui/status_icon.rs b/wezterm-gui/src/termwindow/ui/status_icon.rsindex 6c759d9d..8a3e215d 100644--- a/wezterm-gui/src/termwindow/ui/status_icon.rs+++ b/wezterm-gui/src/termwindow/ui/status_icon.rs@@ -52,9 +52,12 @@ pub fn split_leading_legacy_progress_marker(title: &str) -> Option<&str> {}fn is_legacy_progress_marker_char(ch: char) -> bool {+ // 0x25d0-0x25d3 are the half-circle busy spinner frames Claude Code+ // switched to in 2.1.228 (Braille before that). U+2733 ✳ is deliberately+ // absent: Claude uses it as the *idle* title marker.matches!(ch as u32,- 0x2800..=0x28ff | 0xf0130 | 0xf0a9e..=0xf0aa5 | 0xee00..=0xee0b+ 0x2800..=0x28ff | 0x25d0..=0x25d3 | 0xf0130 | 0xf0a9e..=0xf0aa5 | 0xee00..=0xee0b)}@@ -155,3 +158,47 @@ impl TermWindow {Ok(())}}++#[cfg(test)]+mod tests {+ use super::split_leading_legacy_progress_marker;++ #[test]+ fn braille_spinner_splits() {+ assert_eq!(split_leading_legacy_progress_marker("⠋ build"), Some("build"));+ }++ #[test]+ fn half_circle_spinner_splits() {+ // Claude Code >= 2.1.228 busy spinner frames.+ for frame in ['◐', '◑', '◒', '◓'] {+ let title = format!("{frame} fix the tests");+ assert_eq!(+ split_leading_legacy_progress_marker(&title),+ Some("fix the tests"),+ "frame {frame:?}"+ );+ }+ }++ #[test]+ fn nerd_font_and_private_use_markers_split() {+ assert_eq!(+ split_leading_legacy_progress_marker("\u{f0130} task"),+ Some("task")+ );+ assert_eq!(+ split_leading_legacy_progress_marker("\u{ee03} task"),+ Some("task")+ );+ }++ #[test]+ fn idle_marker_and_plain_text_do_not_split() {+ // ✳ is Claude's *idle* title marker; treating it as a busy spinner+ // would invert the state.+ assert_eq!(split_leading_legacy_progress_marker("✳ done"), None);+ assert_eq!(split_leading_legacy_progress_marker("zsh"), None);+ assert_eq!(split_leading_legacy_progress_marker(""), None);+ }+}diff --git a/wezterm-gui/src/ui/icons.rs b/wezterm-gui/src/ui/icons.rsindex 5a688e65..6c55eaee 100644--- a/wezterm-gui/src/ui/icons.rs+++ b/wezterm-gui/src/ui/icons.rs@@ -6,6 +6,7 @@ pub(crate) enum SettingsIcon {Appearance,Terminal,Workspaces,+ Agents,Keymap,Sync,Developer,@@ -24,6 +25,7 @@ impl SettingsIcon {Self::Appearance => SvgIcon::Palette,Self::Terminal => SvgIcon::Terminal,Self::Workspaces => SvgIcon::FolderOpen,+ Self::Agents => SvgIcon::Bot,Self::Keymap => SvgIcon::Keyboard,Self::Sync => SvgIcon::Cloud,Self::Developer => SvgIcon::Settings,diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rsindex 1197fb8b..ad93fb6e 100644--- a/wezterm-gui/src/workspace_threads.rs+++ b/wezterm-gui/src/workspace_threads.rs@@ -178,6 +178,17 @@ pub struct WorkspaceThread {pub work_is_running: bool,#[serde(skip)]pub work_needs_attention: bool,+ /// The user acknowledged the *current* waiting episode (any keypress in+ /// the active workspace does). The badge may relight silently while the+ /// agent is still waiting, but the needs-input sound must not replay+ /// until the state genuinely leaves and re-enters attention.+ #[serde(skip)]+ pub work_attention_acknowledged: bool,+ /// Panes whose waiting has already rung this episode. A pane newly+ /// joining the waiting set is a new question and rings even while+ /// others are still waiting; a pane merely re-observed stays quiet.+ #[serde(skip)]+ pub work_waiting_panes: std::collections::HashSet<PaneId>,#[serde(default)]pub work_finished_unseen: bool,}@@ -874,7 +885,32 @@ fn preserve_unreadable_workspace_thread_store() {}pub fn save_workspace_thread_store(store: &WorkspaceThreadStore) -> Result<()> {- save_workspace_thread_store_to_path(&workspace_thread_store_path(), store)+ let path = workspace_thread_store_path();+ // Once per process, preserve the store as it was before this session's+ // first write. A broken session (a launch that dies mid-restore, say)+ // must never be able to clobber the only copy of good data — that+ // once cost every open thread its working directory, unrecoverably.+ static BACKUP_ONCE: std::sync::Once = std::sync::Once::new();+ BACKUP_ONCE.call_once(|| rotate_store_backups(&path));+ save_workspace_thread_store_to_path(&path, store)+}++/// Keep the last few pre-session generations as `.json.bak1` (newest)+/// through `.json.bak5`. Failures are non-fatal: a backup must never+/// block the save itself.+fn rotate_store_backups(path: &Path) {+ const GENERATIONS: u32 = 5;+ if !path.exists() {+ return;+ }+ for i in (1..GENERATIONS).rev() {+ let from = path.with_extension(format!("json.bak{i}"));+ let to = path.with_extension(format!("json.bak{}", i + 1));+ if from.exists() {+ let _ = fs::rename(&from, &to);+ }+ }+ let _ = fs::copy(path, path.with_extension("json.bak1"));}pub fn save_workspace_thread_store_to_path(@@ -1811,6 +1847,40 @@ pub fn origin_space_for_ref_workspace(host_space_id: &str, workspace: &str) -> O})}+/// The human name for a thread-backed workspace ("Project · Thread"), or+/// `None` for workspaces no thread claims. Used wherever an internal+/// workspace id would otherwise leak into the UI (e.g. the Agents panel).+pub fn thread_display_name_for_workspace(workspace: &str) -> Option<String> {+ let store = THREAD_STORE.lock();+ store.projects.iter().find_map(|project| {+ project.threads.iter().find_map(|thread| {+ let matches = thread.materialized_workspace_name.as_deref() == Some(workspace)+ || workspace_name_for_thread(&project.id, &thread.id) == workspace;+ matches.then(|| {+ if project.name.is_empty() || project.name == thread.name {+ thread.name.clone()+ } else {+ format!("{} \u{b7} {}", project.name, thread.name)+ }+ })+ })+ })+}++/// The thread backing a workspace, searched across all Spaces. Used by+/// surfaces that list panes globally (the Agents panel) and need to jump+/// to the owning thread.+pub fn thread_id_for_workspace_any(workspace: &str) -> Option<WorkspaceThreadId> {+ let store = THREAD_STORE.lock();+ store.projects.iter().find_map(|project| {+ project.threads.iter().find_map(|thread| {+ let matches = thread.materialized_workspace_name.as_deref() == Some(workspace)+ || workspace_name_for_thread(&project.id, &thread.id) == workspace;+ matches.then(|| thread.id.clone())+ })+ })+}+pub fn workspace_has_thread_binding(workspace: &str) -> bool {let mut store = THREAD_STORE.lock();if store.normalize_after_load() {@@ -2299,11 +2369,13 @@ fn announce_work(announcement: WorkAnnouncement, finished_after: Option<Duration}pub fn refresh_thread_work_for_workspace(workspace: &str) -> bool {- let raw_observed = scan_workspace_work_status(workspace);+ let (raw_observed, waiting_panes) = scan_workspace_work_status(workspace);let observed = debounce_work_status(workspace, raw_observed);let change = {let mut store = THREAD_STORE.lock();- let Some(change) = store.observe_thread_work_for_workspace(workspace, observed) else {+ let Some(change) =+ store.observe_thread_work_for_workspace(workspace, observed, &waiting_panes)+ else {return false;};change@@ -5789,6 +5861,8 @@ impl WorkspaceThreadStore {remote_font_scales: HashMap<PaneId, f64>,work_is_running: bool,work_needs_attention: bool,+ work_attention_acknowledged: bool,+ work_waiting_panes: std::collections::HashSet<PaneId>,work_finished_unseen: bool,}@@ -5813,6 +5887,8 @@ impl WorkspaceThreadStore {remote_font_scales: thread.remote_font_scales.clone(),work_is_running: thread.work_is_running,work_needs_attention: thread.work_needs_attention,+ work_attention_acknowledged: thread.work_attention_acknowledged,+ work_waiting_panes: thread.work_waiting_panes.clone(),work_finished_unseen: thread.work_finished_unseen,},);@@ -5869,6 +5945,13 @@ impl WorkspaceThreadStore {work_is_running: state.map_or(false, |state| state.work_is_running),work_needs_attention: state.map_or(false, |state| state.work_needs_attention),+ work_attention_acknowledged: state+ .map_or(false, |state| state.work_attention_acknowledged),+ // Carried so a store rebuild does not make every+ // still-waiting pane look newly waiting and ring.+ work_waiting_panes: state+ .map(|state| state.work_waiting_panes.clone())+ .unwrap_or_default(),work_finished_unseen: state.map_or(false, |state| state.work_finished_unseen),}@@ -6000,6 +6083,7 @@ impl WorkspaceThreadStore {&mut self,workspace: &str,observed: WorkspaceThreadWorkStatus,+ waiting_panes: &[PaneId],) -> Option<WorkspaceThreadWorkChange> {for project in &mut self.projects {let project_id = project.id.clone();@@ -6009,7 +6093,7 @@ impl WorkspaceThreadStore {.clone().unwrap_or_else(|| workspace_name_for_thread(&project_id, &session.id));if session_workspace == workspace {- return Some(session.observe_work_status(observed));+ return Some(session.observe_work_status(observed, waiting_panes));}}}@@ -6033,6 +6117,12 @@ impl WorkspaceThreadStore {|| session.work_needs_attention|| session.work_finished_unseen;session.work_is_running = false;+ // The episode may still be live (an agent mid-question);+ // remember the acknowledgement so the badge can relight+ // without replaying the sound.+ if session.work_needs_attention {+ session.work_attention_acknowledged = true;+ }session.work_needs_attention = false;session.work_finished_unseen = false;return WorkspaceThreadWorkChange {@@ -6056,6 +6146,9 @@ impl WorkspaceThreadStore {if session.id == thread_id {let should_persist = session.work_finished_unseen;let changed = session.work_needs_attention || session.work_finished_unseen;+ if session.work_needs_attention {+ session.work_attention_acknowledged = true;+ }session.work_needs_attention = false;session.work_finished_unseen = false;return WorkspaceThreadWorkChange {@@ -6503,6 +6596,8 @@ impl WorkspaceThread {is_unread: false,work_is_running: false,work_needs_attention: false,+ work_attention_acknowledged: false,+ work_waiting_panes: Default::default(),work_finished_unseen: false,}}@@ -6525,6 +6620,8 @@ impl WorkspaceThread {is_unread: false,work_is_running: false,work_needs_attention: false,+ work_attention_acknowledged: false,+ work_waiting_panes: Default::default(),work_finished_unseen: false,}}@@ -6544,6 +6641,7 @@ impl WorkspaceThread {fn observe_work_status(&mut self,observed: WorkspaceThreadWorkStatus,+ waiting_panes: &[PaneId],) -> WorkspaceThreadWorkChange {match observed {WorkspaceThreadWorkStatus::Running => {@@ -6552,6 +6650,10 @@ impl WorkspaceThread {!self.work_is_running || self.work_needs_attention || self.work_finished_unseen;self.work_is_running = true;self.work_needs_attention = false;+ // A real state change ends the waiting episode: the next+ // NeedsAttention is a new question and may ring again.+ self.work_attention_acknowledged = false;+ self.work_waiting_panes.clear();self.work_finished_unseen = false;WorkspaceThreadWorkChange {changed,@@ -6562,12 +6664,21 @@ impl WorkspaceThread {WorkspaceThreadWorkStatus::NeedsAttention => {let changed = !self.work_needs_attention;self.work_needs_attention = true;+ // One ring per pane per waiting episode: a pane newly+ // joining the waiting set is a new question and rings even+ // while other agents are still waiting; a pane merely+ // re-observed stays quiet. That last part is load-bearing —+ // typing an answer into the agent's own question form+ // acknowledges and re-observes the same pane every scan,+ // and ringing there would ring on every keystroke.+ let new_waiter = waiting_panes+ .iter()+ .any(|pane| !self.work_waiting_panes.contains(pane));+ self.work_waiting_panes = waiting_panes.iter().copied().collect();WorkspaceThreadWorkChange {changed,should_persist: false,- // `changed` is already "this is the first time we have seen- // it waiting", which is exactly when it is worth saying.- announce: changed.then_some(WorkAnnouncement::NeedsInput),+ announce: new_waiter.then_some(WorkAnnouncement::NeedsInput),}}WorkspaceThreadWorkStatus::Idle | WorkspaceThreadWorkStatus::FinishedUnseen => {@@ -6585,6 +6696,8 @@ impl WorkspaceThread {}self.work_is_running = false;self.work_needs_attention = false;+ self.work_attention_acknowledged = false;+ self.work_waiting_panes.clear();WorkspaceThreadWorkChange {changed: was_running || had_attention,should_persist,@@ -7097,6 +7210,11 @@ fn working_dir_for_entry(.get(&entry.pane_id).and_then(|spec| spec.cwd.clone()).or_else(|| working_dir_from_entry(entry))+ // A stored cwd whose directory no longer exists (renamed project,+ // corrupted save) must not reach spawn: the callers' fallbacks —+ // the project path at the tab level, the neighboring pane's cwd+ // for splits — are all better answers than a failed chdir.+ .filter(|cwd| Path::new(cwd).is_dir())}fn spawn_domain_for_entry(@@ -7143,10 +7261,34 @@ fn initial_thread_id_for_workspace(project_id: &str, workspace: &str) -> Workspaformat!("thread-{hash:x}")}-fn scan_workspace_work_status(workspace: &str) -> WorkspaceThreadWorkStatus {+/// Work status derived from a pane's own escape-sequence signals (OSC 9;4+/// progress and the leading title spinner marker) with no knowledge of what+/// runs inside. NeedsAttention dominates at the workspace level, so folding+/// the signals into a single per-pane value is equivalent to the old+/// two-flag accumulation.+pub(crate) fn native_pane_work_status(pane: &dyn mux::pane::Pane) -> WorkspaceThreadWorkStatus {+ match pane.get_progress() {+ Progress::Error(_) => return WorkspaceThreadWorkStatus::NeedsAttention,+ Progress::Percentage(_) | Progress::Indeterminate => {+ return WorkspaceThreadWorkStatus::Running;+ }+ Progress::None => {}+ }+ if crate::termwindow::ui::status_icon::split_leading_legacy_progress_marker(&pane.get_title())+ .is_some()+ {+ return WorkspaceThreadWorkStatus::Running;+ }+ WorkspaceThreadWorkStatus::Idle+}++fn scan_workspace_work_status(workspace: &str) -> (WorkspaceThreadWorkStatus, Vec<PaneId>) {let mux = Mux::get();let mut running = false;- let mut needs_attention = false;+ // Which panes are waiting, not just whether any is: a pane newly+ // joining this set is a fresh question and earns its own ring.+ let mut waiting_panes = Vec::new();+ let agents_enabled = crate::agent_status::enabled();for window_id in mux.iter_windows_in_workspace(workspace) {let Some(window) = mux.get_window(window_id) else {continue;@@ -7158,29 +7300,29 @@ fn scan_workspace_work_status(workspace: &str) -> WorkspaceThreadWorkStatus {for tab in tabs {for pane in tab.iter_all_panes() {- match pane.get_progress() {- Progress::None => {}- Progress::Percentage(_) | Progress::Indeterminate => running = true,- Progress::Error(_) => needs_attention = true,- }- if crate::termwindow::ui::status_icon::split_leading_legacy_progress_marker(- &pane.get_title(),- )- .is_some()- {- running = true;+ let observed = agents_enabled+ .then(|| crate::agent_status::agent_work_status(pane.as_ref()))+ .flatten()+ .unwrap_or_else(|| native_pane_work_status(pane.as_ref()));+ match observed {+ WorkspaceThreadWorkStatus::NeedsAttention => {+ waiting_panes.push(pane.pane_id())+ }+ WorkspaceThreadWorkStatus::Running => running = true,+ _ => {}}}}}- if needs_attention {+ let status = if !waiting_panes.is_empty() {WorkspaceThreadWorkStatus::NeedsAttention} else if running {WorkspaceThreadWorkStatus::Running} else {WorkspaceThreadWorkStatus::Idle- }+ };+ (status, waiting_panes)}fn is_remote_project(project: &Project, spaces: &[Space]) -> bool {@@ -9066,6 +9208,60 @@ mod tests {assert_eq!(plan.workspace_name, expected_workspace);}+ /// Typing an answer into an agent's question must not ring per key:+ /// each keypress acknowledges the active workspace and the next scan+ /// re-observes the same still-waiting pane. Only a pane newly joining+ /// the waiting set may ring.+ #[test]+ fn acknowledged_waiting_episode_relights_silently() {+ let mut thread = WorkspaceThread::new(+ "project-1".to_string(),+ "main".to_string(),+ Some("workspace-1".to_string()),+ );+ let first = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &[7]);+ assert_eq!(first.announce, Some(WorkAnnouncement::NeedsInput));+ // Keypress: acknowledge clears the badge and marks the episode.+ if thread.work_needs_attention {+ thread.work_attention_acknowledged = true;+ }+ thread.work_needs_attention = false;+ // The agent is still waiting: badge relights, sound stays quiet.+ let relight = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &[7]);+ assert!(relight.changed);+ assert_eq!(relight.announce, None, "same pane must not re-ring");+ // The question is answered and a new one appears: rings again.+ thread.observe_work_status(WorkspaceThreadWorkStatus::Running, &[]);+ let next = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &[7]);+ assert_eq!(next.announce, Some(WorkAnnouncement::NeedsInput));+ }++ /// Two agents in one thread each earn a ring: the second question is+ /// as real as the first even though the thread is already waiting.+ #[test]+ fn each_newly_waiting_pane_rings_once() {+ let mut thread = WorkspaceThread::new(+ "project-1".to_string(),+ "main".to_string(),+ Some("workspace-1".to_string()),+ );+ let a = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &[1]);+ assert_eq!(a.announce, Some(WorkAnnouncement::NeedsInput));+ // A second agent starts waiting while the first still is.+ let b = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &[1, 2]);+ assert_eq!(b.announce, Some(WorkAnnouncement::NeedsInput));+ // Both merely still waiting: quiet.+ let held = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &[1, 2]);+ assert_eq!(held.announce, None);+ // One is answered while the other still waits: quiet.+ let fewer = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &[2]);+ assert_eq!(fewer.announce, None);+ // The answered one asks a new question: it left and re-joined the+ // waiting set, so it rings again.+ let again = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &[1, 2]);+ assert_eq!(again.announce, Some(WorkAnnouncement::NeedsInput));+ }+#[test]fn workspace_work_observation_transitions_to_finished_unseen() {let mut store = test_store();@@ -9082,7 +9278,11 @@ mod tests {));let change = store- .observe_thread_work_for_workspace("workspace-1", WorkspaceThreadWorkStatus::Running)+ .observe_thread_work_for_workspace(+ "workspace-1",+ WorkspaceThreadWorkStatus::Running,+ &[],+ ).unwrap();assert!(change.changed);assert!(!change.should_persist);@@ -9092,7 +9292,11 @@ mod tests {);let change = store- .observe_thread_work_for_workspace("workspace-1", WorkspaceThreadWorkStatus::Idle)+ .observe_thread_work_for_workspace(+ "workspace-1",+ WorkspaceThreadWorkStatus::Idle,+ &[],+ ).unwrap();assert!(change.changed);assert!(change.should_persist);@@ -9122,8 +9326,14 @@ mod tests {store: &mut WorkspaceThreadStore,status: WorkspaceThreadWorkStatus,) -> Option<WorkAnnouncement> {+ // NeedsAttention always arrives with the waiting panes in+ // production (the status IS "some pane waits"); mirror that.+ let waiting: &[PaneId] = match status {+ WorkspaceThreadWorkStatus::NeedsAttention => &[1],+ _ => &[],+ };store- .observe_thread_work_for_workspace("workspace-1", status)+ .observe_thread_work_for_workspace("workspace-1", status, waiting).unwrap().announce}diff --git a/wezterm/Cargo.toml b/wezterm/Cargo.tomlindex 2608015e..03d927be 100644--- a/wezterm/Cargo.toml+++ b/wezterm/Cargo.toml@@ -43,6 +43,7 @@ tempfile.workspace = truetermwiz-funcs.workspace = truetermwiz.workspace = truetextwrap.workspace =true+thinkterm-proto.workspace = truethinkterm-tui = { path = "../thinkterm-tui" }umask.workspace = trueurl.workspace = truediff --git a/wezterm/src/cli/agent.rs b/wezterm/src/cli/agent.rsnew file mode 100644index 00000000..e944e7e6--- /dev/null+++ b/wezterm/src/cli/agent.rs@@ -0,0 +1,152 @@+//! `thinkterm cli agent …`: query agent statuses from the mux.++use crate::cli::CliOutputFormatKind;+use clap::Parser;+use serde::Serializer as _;+use std::time::{SystemTime, UNIX_EPOCH};+use tabout::{tabulate_output, Alignment, Column};+use thinkterm_proto::{AgentEvidence, AgentState};+use wezterm_client::client::Client;++#[derive(Debug, Parser, Clone)]+pub struct AgentCommand {+ #[command(subcommand)]+ sub: AgentSubCommand,+}++#[derive(Debug, Parser, Clone)]+enum AgentSubCommand {+ /// List panes running detected coding agents+ #[command(name = "list")]+ List(AgentListCommand),+}++#[derive(Debug, Parser, Clone)]+struct AgentListCommand {+ /// Controls the output format.+ /// "table" and "json" are possible formats.+ #[arg(long = "format", default_value = "table")]+ format: CliOutputFormatKind,+}++impl AgentCommand {+ pub async fn run(&self, client: Client) -> anyhow::Result<()> {+ match &self.sub {+ AgentSubCommand::List(cmd) => cmd.run(client).await,+ }+ }+}++fn state_label(state: AgentState) -> &'static str {+ match state {+ AgentState::Working => "working",+ AgentState::Blocked => "blocked",+ AgentState::Idle => "idle",+ AgentState::Unknown => "unknown",+ }+}++fn evidence_label(evidence: AgentEvidence) -> &'static str {+ match evidence {+ AgentEvidence::Contract => "contract",+ AgentEvidence::Screen => "screen",+ AgentEvidence::Fallback => "fallback",+ }+}++// This will be serialized to JSON via the 'List' command.+// As such it is intended to be a stable output format,+// Do not remove or change the types of the fields.+#[derive(serde::Serialize)]+struct CliAgentResultItem {+ pane_id: mux::pane::PaneId,+ agent: String,+ state: String,+ evidence: String,+ session_id: Option<String>,+ /// Unix seconds of the last state change, on the detecting host's+ /// clock (approximate when that host's clock differs from ours).+ since_unix: u64,+ workspace: String,+ title: String,+}++impl AgentListCommand {+ async fn run(&self, client: Client) -> anyhow::Result<()> {+ let out = std::io::stdout();+ let response = client.get_agent_statuses().await?;+ match self.format {+ CliOutputFormatKind::Json => {+ let items = response.statuses.into_iter().map(|entry| CliAgentResultItem {+ pane_id: entry.pane_id,+ agent: entry.status.agent_id,+ state: state_label(entry.status.state).to_string(),+ evidence: evidence_label(entry.status.evidence).to_string(),+ session_id: entry.status.session_id,+ since_unix: entry.status.since_unix,+ workspace: entry.workspace,+ title: entry.title,+ });+ let mut writer = serde_json::Serializer::pretty(out.lock());+ writer.collect_seq(items)?;+ }+ CliOutputFormatKind::Table => {+ let now = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|d| d.as_secs())+ .unwrap_or(0);+ let cols = vec![+ Column {+ name: "PANEID".to_string(),+ alignment: Alignment::Right,+ },+ Column {+ name: "AGENT".to_string(),+ alignment: Alignment::Left,+ },+ Column {+ name: "STATE".to_string(),+ alignment: Alignment::Left,+ },+ Column {+ name: "EVIDENCE".to_string(),+ alignment: Alignment::Left,+ },+ Column {+ name: "AGE".to_string(),+ alignment: Alignment::Right,+ },+ Column {+ name: "WORKSPACE".to_string(),+ alignment: Alignment::Left,+ },+ Column {+ name: "TITLE".to_string(),+ alignment: Alignment::Left,+ },+ ];+ let data = response+ .statuses+ .iter()+ .map(|entry| {+ // Clock skew across hosts renders as a zero age.+ let age = now.saturating_sub(entry.status.since_unix);+ vec![+ entry.pane_id.to_string(),+ entry.status.agent_id.clone(),+ state_label(entry.status.state).to_string(),+ evidence_label(entry.status.evidence).to_string(),+ format!("{}", humantime::format_duration(+ std::time::Duration::from_secs(age)+ )),+ entry.workspace.clone(),+ entry.title.clone(),+ ]+ })+ .collect::<Vec<_>>();+ tabulate_output(&cols, &data, &mut out.lock())?;+ }+ }+ Ok(())+ }+}diff --git a/wezterm/src/cli/mod.rs b/wezterm/src/cli/mod.rsindex 353c9f7e..31730075 100644--- a/wezterm/src/cli/mod.rs+++ b/wezterm/src/cli/mod.rs@@ -7,6 +7,7 @@ mod activate_pane;mod activate_pane_direction;mod activate_tab;mod adjust_pane_size;+mod agent;mod get_pane_direction;mod get_text;mod kill_pane;@@ -163,6 +164,10 @@ Outputs the pane-id for the newly created pane on success"/// Zoom, unzoom, or toggle zoom state#[command(name = "zoom-pane", rename_all = "kebab")]ZoomPane(zoom_pane::ZoomPane),++ /// Query agent statuses+ #[command(name = "agent")]+ Agent(agent::AgentCommand),}async fn run_cli_async(opts: &crate::Opt, cli: CliCommand) -> anyhow::Result<()> {@@ -209,6 +214,7 @@ async fn run_cli_async(opts: &crate::Opt, cli: CliCommand) -> anyhow::Result<()>CliSubCommand::SetWindowTitle(cmd) => cmd.run(client).await,CliSubCommand::RenameWorkspace(cmd) => cmd.run(client).await,CliSubCommand::ZoomPane(cmd) => cmd.run(client).await,+ CliSubCommand::Agent(cmd) => cmd.run(client).await,}}