the runtime your coding agents live on
Rust agentagent-orchestrationaiai-agentsclaude-codeclicodexcoding-agentsdeveloper-toolsdevtoolsmultiplexerrustterminalterminal-multiplexerterminal-uitmuxtuiworkspace-manager
perf: reuse unchanged windows shell detection text (#5091)
JJ Liebigfe935882f0cc
diff --git a/src/pane.rs b/src/pane.rsindex b0d6aab38..b0bceae36 100644--- a/src/pane.rs+++ b/src/pane.rs@@ -1172,8 +1172,8 @@ fn spawn_basic_detection_task(DetectionScreenReadDecision::Skip => continue,}- let content_changed =- last_detection_text.refresh(agent, &content_seq, || terminal.detection_text());+ let content_changed = last_detection_text+ .refresh(agent, &content_seq, || terminal.detection_text_for_cache());let content = &last_detection_text.text;last_screen_scan_detection_content_seq = current_detection_content_seq;let osc_title = terminal.agent_osc_title();@@ -3179,8 +3179,9 @@ impl PaneRuntime {}let content_changed =- last_detection_text- .refresh(agent, &text_content_seq, || terminal.detection_text());+ last_detection_text.refresh(agent, &text_content_seq, || {+ terminal.detection_text_for_cache()+ });let content = &last_detection_text.text;last_screen_scan_detection_content_seq = current_detection_content_seq;let osc_title = terminal.agent_osc_title();@@ -4073,7 +4074,6 @@ mod tests {use super::*;use std::ffi::OsStr;- #[cfg(unix)]#[tokio::test]async fn unidentified_text_cache_tracks_runtime_mutations_not_viewport_scroll() {let runtime = PaneRuntime::test_with_scrollback_bytes(@@ -4087,7 +4087,7 @@ mod tests {let refresh = |cache: &mut DetectionTextCache| {cache.refresh(None, &runtime.content_seq, || {reads.set(reads.get() + 1);- runtime.terminal.detection_text()+ runtime.terminal.detection_text_for_cache()})};assert!(diff --git a/src/pane/agent_detection.rs b/src/pane/agent_detection.rsindex 11ff0b4bd..f3edc6386 100644--- a/src/pane/agent_detection.rs+++ b/src/pane/agent_detection.rs@@ -123,13 +123,11 @@ impl DetectionTextCache {&mut self,agent: Option<Agent>,content_seq: &AtomicU64,- read: impl FnOnce() -> String,+ read: impl FnOnce() -> (String, bool),) -> bool {let before = content_seq.load(Ordering::Acquire);- // Windows blank reads can refresh deferred recent-history fallback.// Identified agents retain their existing screen-read behavior everywhere.- if cfg!(unix)- && agent.is_none()+ if agent.is_none()// The terminal accessor also returns empty on failure; keep retrying it.&& !self.text.is_empty()&& before.is_multiple_of(2)@@ -137,11 +135,11 @@ impl DetectionTextCache {{return false;}- let text = read();+ let (text, reusable) = read();let after = content_seq.load(Ordering::Acquire);// Writers announce themselves before touching the terminal. A read that// overlaps a writer must not bless either revision for future reuse.- self.revision = (before == after && before.is_multiple_of(2)).then_some(before);+ self.revision = (reusable && before == after && before.is_multiple_of(2)).then_some(before);let changed = text != self.text;self.text = text;changed@@ -393,80 +391,63 @@ pub(super) fn mark_detection_content_changed(detection_content_seq: &AtomicU64)mod tests {use super::*;- #[cfg(unix)]#[test]fn unidentified_text_cache_preserves_text_changes_and_forced_reads() {let sequence = AtomicU64::new(0);let mut cache = DetectionTextCache::default();- assert!(cache.refresh(None, &sequence, || "one".into()));+ assert!(cache.refresh(None, &sequence, || ("one".into(), true)));for _ in 0..20 {assert!(!cache.refresh(None, &sequence, || panic!("unchanged text was extracted")));}sequence.store(2, Ordering::Release);assert!(- !cache.refresh(None, &sequence, || "one".into()),+ !cache.refresh(None, &sequence, || ("one".into(), true)),"bytes are not text changes");sequence.store(4, Ordering::Release);- assert!(cache.refresh(None, &sequence, || "two".into()));+ assert!(cache.refresh(None, &sequence, || ("two".into(), true)));for _ in 0..2 {let mut read = false;assert!(!cache.refresh(Some(Agent::Codex), &sequence, || {read = true;- "two".into()+ ("two".into(), true)}));assert!(read, "identified agents must keep their existing reads");}cache.clear();- assert!(cache.refresh(None, &sequence, || "two".into()));+ assert!(cache.refresh(None, &sequence, || ("two".into(), true)));sequence.store(6, Ordering::Release);- assert!(cache.refresh(None, &sequence, String::new));- assert!(cache.refresh(None, &sequence, || "retry after empty read".into()));+ assert!(cache.refresh(None, &sequence, || (String::new(), false)));+ assert!(cache.refresh(None, &sequence, || ("retry after empty read".into(), true)));}- #[cfg(unix)]#[test]fn unidentified_text_cache_does_not_reuse_overlapping_writes() {let sequence = AtomicU64::new(0);let mut cache = DetectionTextCache::default();assert!(cache.refresh(None, &sequence, || {sequence.store(2, Ordering::Release);- "old".into()+ ("old".into(), true)}));assert_eq!(cache.revision, None,"old text must not acquire the new revision");- assert!(cache.refresh(None, &sequence, || "new".into()));+ assert!(cache.refresh(None, &sequence, || ("new".into(), true)));sequence.store(3, Ordering::Release);- assert!(cache.refresh(None, &sequence, || "during write".into()));+ assert!(cache.refresh(None, &sequence, || ("during write".into(), true)));assert_eq!(cache.revision, None,"an in-progress write cannot be reused");sequence.store(4, Ordering::Release);- assert!(cache.refresh(None, &sequence, || "completed write".into()));+ assert!(cache.refresh(None, &sequence, || ("completed write".into(), true)));assert!(!cache.refresh(None, &sequence, || panic!("completed revision should be reusable")));}- #[cfg(windows)]- #[test]- fn unidentified_text_cache_keeps_windows_fallback_reads() {- let sequence = AtomicU64::new(0);- let mut cache = DetectionTextCache::default();- for _ in 0..2 {- let mut read = false;- cache.refresh(None, &sequence, || {- read = true;- "nonempty fallback text".into()- });- assert!(read);- }- }-fn publish_state(state: AgentState) -> DetectionPublishState {DetectionPublishState {state,diff --git a/src/pane/terminal.rs b/src/pane/terminal.rsindex a1ba471fb..44d321147 100644--- a/src/pane/terminal.rs+++ b/src/pane/terminal.rs@@ -503,6 +503,11 @@ impl PaneTerminal {self.ghostty.detection_text()}+ /// The flag permits reuse only when a later read cannot refresh Windows fallback text.+ pub(crate) fn detection_text_for_cache(&self) -> (String, bool) {+ self.ghostty.detection_text_for_cache()+ }+pub(crate) fn try_compression_activity(&self) -> Result<Option<u64>, crate::ghostty::Error> {self.ghostty.try_compression_activity()}@@ -2171,13 +2176,17 @@ impl GhosttyPaneTerminal {}pub fn detection_text(&self) -> String {+ self.detection_text_for_cache().0+ }++ pub(crate) fn detection_text_for_cache(&self) -> (String, bool) {#[cfg(all(test, unix))]self.detection_text_reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);self.core.lock().ok()- .and_then(|mut core| ghostty_detection_text(&mut core).ok())+ .and_then(|mut core| ghostty_detection_text_for_cache(&mut core).ok()).unwrap_or_default()}@@ -2835,13 +2844,29 @@ fn ghostty_visible_ansi(core: &GhosttyPaneCore) -> Result<String, crate::ghostty}fn ghostty_detection_text(core: &mut GhosttyPaneCore) -> Result<String, crate::ghostty::Error> {+ ghostty_detection_text_for_cache(core).map(|(text, _)| text)+}++fn ghostty_detection_text_for_cache(+ core: &mut GhosttyPaneCore,+) -> Result<(String, bool), crate::ghostty::Error> {let lines = core.terminal.rows().ok().map(|rows| usize::from(rows).max(1)).unwrap_or(DEFAULT_DETECTION_ROWS);- ghostty_recent_text(core, lines)+ let text = ghostty_recent_text_for_terminal(&core.terminal, lines)?;+ Ok(finish_detection_text(core, text, lines))+}++fn finish_detection_text(core: &mut GhosttyPaneCore, text: String, lines: usize) -> (String, bool) {+ // Windows fallback reads may refresh deferred history without a content revision.+ let reusable = !cfg!(windows) || !text.trim().is_empty();+ (+ finish_recent_snapshot(core, text, lines, false).text,+ reusable,+ )}#[cfg(windows)]@@ -2907,13 +2932,6 @@ fn windows_powershell_prompt_line_cwd(line: &str) -> Option<std::path::PathBuf>(cwd.is_absolute() && cwd.is_dir()).then_some(cwd)}-fn ghostty_recent_text(- core: &mut GhosttyPaneCore,- lines: usize,-) -> Result<String, crate::ghostty::Error> {- ghostty_recent_text_snapshot(core, lines).map(|snapshot| snapshot.text)-}-fn ghostty_recent_text_snapshot(core: &mut GhosttyPaneCore,lines: usize,diff --git a/src/pane/terminal/windows_recent_fallback.rs b/src/pane/terminal/windows_recent_fallback.rsindex 7f632c08b..759e96b1d 100644--- a/src/pane/terminal/windows_recent_fallback.rs+++ b/src/pane/terminal/windows_recent_fallback.rs@@ -322,6 +322,8 @@ mod tests {#[test]fn deferred_refresh_replaces_visible_tail_after_repaint() {+ let sequence = std::sync::atomic::AtomicU64::new(0);+ let mut cache = crate::pane::agent_detection::DetectionTextCache::default();let (tx, _rx) = mpsc::channel(4);let terminal = crate::ghostty::Terminal::new(40, 3, 1024).unwrap();let pane = GhosttyPaneTerminal::new(terminal, tx.clone()).unwrap();@@ -329,19 +331,28 @@ mod tests {pane.process_pty_bytes(pane_id, 0, b"older", &tx);pane.process_pty_bytes(pane_id, 0, b"\r\nold\r\nprompt", &tx);let mut core = pane.core.lock().unwrap();- let _ = super::super::finish_recent_snapshot(&mut core, String::new(), 3, false);+ cache.refresh(None, &sequence, || {+ super::super::finish_detection_text(&mut core, String::new(), 3)+ });+ assert!(cache.text.contains("prompt"));drop(core);pane.resize(2, 40, 8, 16);pane.process_pty_bytes(pane_id, 0, b"\rupdated", &tx);let mut core = pane.core.lock().unwrap();- let resized = super::super::finish_recent_snapshot(&mut core, String::new(), 10, false);- assert_eq!(resized.text, "older\nold\nupdated\n");+ assert!(core.recent_fallback.needs_refresh);+ assert!(cache.refresh(None, &sequence, || {+ super::super::finish_detection_text(&mut core, String::new(), 10)+ }));+ assert!(!core.recent_fallback.needs_refresh);+ assert_eq!(cache.text, "older\nold\nupdated\n");drop(core);pane.process_pty_bytes(pane_id, 0, b"\x1b[2J\x1b[H", &tx);pane.process_pty_bytes(pane_id, 0, b"updated", &tx);let mut core = pane.core.lock().unwrap();- let refreshed = super::super::finish_recent_snapshot(&mut core, String::new(), 10, false);- assert_eq!(refreshed.text, "older\nupdated\n");+ assert!(cache.refresh(None, &sequence, || {+ super::super::finish_detection_text(&mut core, String::new(), 10)+ }));+ assert_eq!(cache.text, "older\nupdated\n");}#[test]