Skip to content

armgit / herdr

Public Imported from GitHub
0

the runtime your coding agents live on

perf: reuse unchanged shell detection text (#5085)

akbashcce57bc32c44
diff --git a/src/app/api.rs b/src/app/api.rs
index 9bc373632..dd87c508b 100644
--- a/src/app/api.rs
+++ b/src/app/api.rs
@@ -1588,8 +1588,17 @@ mod tests {
.attached_terminal_id
.clone();
let (runtime, _rx) = crate::terminal::TerminalRuntime::test_with_channel(80, 24);
+ #[cfg(unix)]
+ let (runtime, _detection_events) = {
+ let mut runtime = runtime;
+ runtime.test_process_pty_bytes(b"shell prompt");
+ let events = runtime.test_start_basic_detection();
+ runtime.test_wait_for_detection_reads(1).await;
+ (runtime, events)
+ };
+ #[cfg(not(unix))]
let reset_notify = runtime.agent_detection_reset_notify_for_test();
- app.terminal_runtimes.insert(terminal_id, runtime);
+ app.terminal_runtimes.insert(terminal_id.clone(), runtime);
let response = app.handle_api_request(crate::api::schema::Request {
id: "reload_manifests".into(),
@@ -1604,6 +1613,13 @@ mod tests {
.unwrap()
.is_empty());
+ #[cfg(unix)]
+ app.terminal_runtimes
+ .get(&terminal_id)
+ .unwrap()
+ .test_wait_for_detection_reads(2)
+ .await;
+ #[cfg(not(unix))]
tokio::time::timeout(
std::time::Duration::from_millis(50),
reset_notify.notified(),
diff --git a/src/pane.rs b/src/pane.rs
index ef354c769..b0d6aab38 100644
--- a/src/pane.rs
+++ b/src/pane.rs
@@ -38,8 +38,8 @@ use self::agent_detection::{
codex_prompt_ready, decide_detection_screen_read, decide_screen_detection_publish,
detection_update_for_publish_with_osc, mark_detection_content_changed,
observe_detection_content_change, DetectionPublishDecision, DetectionScreenReadDecision,
- DetectionScreenReadInput, PendingIdleConfirmation, ScreenDetectionPublishInput,
- AGENT_PENDING_IDLE_RECHECK, AGENT_STARTUP_GRACE_WINDOW,
+ DetectionScreenReadInput, DetectionTextCache, PendingIdleConfirmation,
+ ScreenDetectionPublishInput, AGENT_PENDING_IDLE_RECHECK, AGENT_STARTUP_GRACE_WINDOW,
};
use self::background_agent::{AgentJobStatus, AgentJobTracker};
#[cfg(test)]
@@ -924,10 +924,13 @@ fn probe_foreground_process(pid: u32, foreground_pgid: Option<u32>) -> ProcessPr
}
#[cfg(unix)]
+// Handoff detection needs both the write-bracketed text revision and detection epoch.
+#[allow(clippy::too_many_arguments)]
fn spawn_basic_detection_task(
pane_id: PaneId,
child_pid: Arc<AtomicU32>,
terminal: Arc<PaneTerminal>,
+ content_seq: Arc<AtomicU64>,
detection_content_seq: Arc<AtomicU64>,
full_lifecycle_authority_active: Arc<AtomicBool>,
self_reported_agent_active: Arc<AtomicBool>,
@@ -957,7 +960,7 @@ fn spawn_basic_detection_task(
let mut pending_foreground_shell_clear = false;
let mut foreground_shell_exit_reported = false;
let mut release_was_active = false;
- let mut last_detection_text = String::new();
+ let mut last_detection_text = DetectionTextCache::default();
let mut last_screen_scan_detection_content_seq = None;
let mut agent_startup_grace_until = None;
let mut pending_idle = PendingIdleConfirmation::default();
@@ -1169,15 +1172,15 @@ fn spawn_basic_detection_task(
DetectionScreenReadDecision::Skip => continue,
}
- let content = terminal.detection_text();
+ let content_changed =
+ last_detection_text.refresh(agent, &content_seq, || terminal.detection_text());
+ let content = &last_detection_text.text;
last_screen_scan_detection_content_seq = current_detection_content_seq;
- let content_changed = content != last_detection_text;
- last_detection_text.clone_from(&content);
let osc_title = terminal.agent_osc_title();
let osc_progress = terminal.agent_osc_progress();
let screen_detection = detection_update_for_publish_with_osc(
agent,
- &content,
+ content,
&osc_title,
&osc_progress,
process_exited,
@@ -1186,7 +1189,7 @@ fn spawn_basic_detection_task(
&state_events,
pane_id,
agent,
- &content,
+ content,
screen_detection.as_ref(),
process_exited,
&mut last_codex_prompt_ready,
@@ -2648,6 +2651,7 @@ impl PaneRuntime {
pane_id,
child_pid.clone(),
terminal.clone(),
+ content_seq.clone(),
detection_content_seq.clone(),
full_lifecycle_authority_active.clone(),
self_reported_agent_active.clone(),
@@ -2851,6 +2855,7 @@ impl PaneRuntime {
let child_pid = child_pid.clone();
let terminal = terminal.clone();
let state_events = events.clone();
+ let text_content_seq = content_seq.clone();
let detection_content_seq = detection_content_seq.clone();
let full_lifecycle_authority_active_for_task = full_lifecycle_authority_active.clone();
let self_reported_agent_active_for_task = self_reported_agent_active.clone();
@@ -2880,7 +2885,7 @@ impl PaneRuntime {
let mut last_visible_blocker = false;
let mut last_visible_working = false;
let mut last_visible_signal_refresh = None;
- let mut last_detection_text = String::new();
+ let mut last_detection_text = DetectionTextCache::default();
let mut last_screen_scan_detection_content_seq = None;
let mut agent_startup_grace_until = None;
let mut pending_idle = PendingIdleConfirmation::default();
@@ -3173,15 +3178,16 @@ impl PaneRuntime {
DetectionScreenReadDecision::Skip => continue,
}
- let content = terminal.detection_text();
+ let content_changed =
+ last_detection_text
+ .refresh(agent, &text_content_seq, || terminal.detection_text());
+ let content = &last_detection_text.text;
last_screen_scan_detection_content_seq = current_detection_content_seq;
- let content_changed = content != last_detection_text;
- last_detection_text.clone_from(&content);
let osc_title = terminal.agent_osc_title();
let osc_progress = terminal.agent_osc_progress();
let screen_detection = detection_update_for_publish_with_osc(
agent,
- &content,
+ content,
&osc_title,
&osc_progress,
process_exited,
@@ -3190,7 +3196,7 @@ impl PaneRuntime {
&state_events,
pane_id,
agent,
- &content,
+ content,
screen_detection.as_ref(),
process_exited,
&mut last_codex_prompt_ready,
@@ -3890,6 +3896,45 @@ impl PaneRuntime {
Self::test_with_scrollback_bytes(cols, rows, 0, bytes)
}
+ #[cfg(unix)]
+ pub(crate) fn test_start_basic_detection(&mut self) -> mpsc::Receiver<AppEvent> {
+ if let Some(handle) = self.detect_handle.take() {
+ handle.abort();
+ }
+ let (events, receiver) = mpsc::channel(8);
+ let (handle, reset, release) = spawn_basic_detection_task(
+ self.pane_id,
+ self.child_pid.clone(),
+ self.terminal.clone(),
+ self.content_seq.clone(),
+ self.detection_content_seq.clone(),
+ self.full_lifecycle_authority_active.clone(),
+ self.self_reported_agent_active.clone(),
+ events,
+ );
+ self.detect_handle = Some(handle);
+ self.detect_reset_notify = reset;
+ self.pending_release = release;
+ receiver
+ }
+
+ #[cfg(unix)]
+ pub(crate) async fn test_wait_for_detection_reads(&self, expected: usize) {
+ tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ while self
+ .terminal
+ .ghostty
+ .detection_text_reads
+ .load(Ordering::Relaxed)
+ < expected
+ {
+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;
+ }
+ })
+ .await
+ .expect("detection task should extract fresh text");
+ }
+
pub(crate) fn test_scroll_metrics_reads(&self) -> usize {
self.terminal
.ghostty
@@ -4028,6 +4073,141 @@ 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(
+ 12,
+ 3,
+ 100_000,
+ b"old\r\nold\r\nabcdefghijklmnop\r\nprompt",
+ );
+ let mut cache = DetectionTextCache::default();
+ let reads = Cell::new(0);
+ let refresh = |cache: &mut DetectionTextCache| {
+ cache.refresh(None, &runtime.content_seq, || {
+ reads.set(reads.get() + 1);
+ runtime.terminal.detection_text()
+ })
+ };
+ assert!(
+ refresh(&mut cache),
+ "seeded history must be read at revision zero"
+ );
+ assert_eq!(reads.get(), 1);
+ runtime.scroll_up(2);
+ assert!(!refresh(&mut cache));
+ assert_eq!(
+ reads.get(),
+ 1,
+ "viewport scrolling must not rebuild bottom text"
+ );
+ assert_eq!(cache.text, runtime.detection_text());
+
+ // Control-only and fragmented output still invalidate the physical read,
+ // but do not manufacture a text change for acquisition scheduling.
+ runtime.test_process_pty_bytes(b"\x1b]0;title\x07\x1b[");
+ assert!(!refresh(&mut cache));
+ assert_eq!(reads.get(), 2);
+ runtime.test_process_pty_bytes(b"2J\x1b[Hupdated");
+ assert!(refresh(&mut cache));
+ assert_eq!(reads.get(), 3);
+ assert_eq!(cache.text, runtime.detection_text());
+
+ runtime.resize(4, 8, 0, 0);
+ refresh(&mut cache);
+ assert_eq!(reads.get(), 4);
+ assert_eq!(cache.text, runtime.detection_text());
+ runtime.clear_screen().unwrap();
+ refresh(&mut cache);
+ assert_eq!(reads.get(), 5);
+ assert_eq!(cache.text, runtime.detection_text());
+ runtime.test_process_pty_bytes(b"\x1b[?1049halt");
+ assert!(refresh(&mut cache));
+ assert_eq!(reads.get(), 6);
+ assert_eq!(cache.text, runtime.detection_text());
+ assert!(!refresh(&mut cache));
+ assert_eq!(reads.get(), 6);
+ runtime.test_process_pty_bytes(b"\x1b[?1049l");
+ assert!(refresh(&mut cache));
+ assert_eq!(reads.get(), 7);
+ assert_eq!(cache.text, runtime.detection_text());
+ assert!(!cache.text.contains("alt"));
+ assert!(!refresh(&mut cache));
+ assert_eq!(reads.get(), 7);
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn unidentified_text_cache_resets_with_adopted_runtime_and_recreation() {
+ let mut runtime = PaneRuntime::test_with_screen_bytes(20, 4, b"first runtime");
+ let _events = runtime.test_start_basic_detection();
+ runtime.test_wait_for_detection_reads(1).await;
+ let revision = runtime.content_seq();
+ runtime.reset_agent_detection();
+ runtime.test_wait_for_detection_reads(2).await;
+ assert_eq!(
+ runtime.content_seq(),
+ revision,
+ "reset does not require output"
+ );
+ drop(runtime);
+
+ // A new runtime can reuse both the pane identity and revision zero. Its
+ // detector must not inherit the previous runtime's text or revision.
+ let mut recreated = PaneRuntime::test_with_screen_bytes(20, 4, b"second runtime");
+ assert_eq!(recreated.content_seq(), revision);
+ let _events = recreated.test_start_basic_detection();
+ recreated.test_wait_for_detection_reads(1).await;
+ assert!(recreated.visible_text().contains("second runtime"));
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn unidentified_text_cache_resets_in_spawned_runtime_without_output() {
+ let (events, _event_rx) = mpsc::channel(8);
+ let runtime = PaneRuntime::spawn_shell_command(
+ PaneId::from_raw(42),
+ 4,
+ 20,
+ std::env::temp_dir(),
+ "printf 'cache-ready'; exec sleep 30",
+ &PaneLaunchEnv::default(),
+ AgentDetection::Enabled,
+ 0,
+ crate::terminal_theme::TerminalTheme::default(),
+ None,
+ events,
+ Arc::new(Notify::new()),
+ Arc::new(RenderSignal::new()),
+ )
+ .unwrap();
+ tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ while !runtime.visible_text().contains("cache-ready") {
+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;
+ }
+ })
+ .await
+ .expect("shell should populate the terminal");
+ // The first reset guarantees a populated read even if the initial tick
+ // preceded shell output. The second proves that a warm cache is cleared.
+ let revision = {
+ let _write = runtime.content_write_lock.lock().unwrap();
+ runtime.content_seq()
+ };
+ for _ in 0..2 {
+ let reads = runtime
+ .terminal
+ .ghostty
+ .detection_text_reads
+ .load(Ordering::Relaxed);
+ runtime.reset_agent_detection();
+ runtime.test_wait_for_detection_reads(reads + 1).await;
+ }
+ assert_eq!(runtime.content_seq(), revision);
+ runtime.shutdown();
+ }
+
#[tokio::test]
async fn clear_pane_preserves_wrapped_input_and_unfinished_vt_sequence() {
let (runtime, mut rx) = PaneRuntime::test_with_channel_and_scrollback_bytes(
diff --git a/src/pane/agent_detection.rs b/src/pane/agent_detection.rs
index e37aec3b3..11ff0b4bd 100644
--- a/src/pane/agent_detection.rs
+++ b/src/pane/agent_detection.rs
@@ -104,6 +104,50 @@ pub(super) fn should_skip_idle_screen_scan(input: IdleScreenScanSkipInput) -> bo
&& input.last_screen_scan_detection_content_seq == input.current_detection_content_seq
}
+/// Retains text, not a classification: callers still evaluate discovery and
+/// lifecycle bookkeeping on every scheduled observation.
+#[derive(Default)]
+pub(super) struct DetectionTextCache {
+ pub(super) text: String,
+ revision: Option<u64>,
+}
+
+impl DetectionTextCache {
+ pub(super) fn clear(&mut self) {
+ self.text.clear();
+ self.revision = None;
+ }
+
+ /// Returns whether the extracted text changed, not whether PTY bytes arrived.
+ pub(super) fn refresh(
+ &mut self,
+ agent: Option<Agent>,
+ content_seq: &AtomicU64,
+ read: impl FnOnce() -> String,
+ ) -> 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()
+ // The terminal accessor also returns empty on failure; keep retrying it.
+ && !self.text.is_empty()
+ && before.is_multiple_of(2)
+ && self.revision == Some(before)
+ {
+ return false;
+ }
+ let text = 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);
+ let changed = text != self.text;
+ self.text = text;
+ changed
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum DetectionScreenReadDecision {
Read,
@@ -349,6 +393,80 @@ 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()));
+ 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()),
+ "bytes are not text changes"
+ );
+ sequence.store(4, Ordering::Release);
+ assert!(cache.refresh(None, &sequence, || "two".into()));
+ for _ in 0..2 {
+ let mut read = false;
+ assert!(!cache.refresh(Some(Agent::Codex), &sequence, || {
+ read = true;
+ "two".into()
+ }));
+ assert!(read, "identified agents must keep their existing reads");
+ }
+ cache.clear();
+ assert!(cache.refresh(None, &sequence, || "two".into()));
+ sequence.store(6, Ordering::Release);
+ assert!(cache.refresh(None, &sequence, String::new));
+ assert!(cache.refresh(None, &sequence, || "retry after empty read".into()));
+ }
+
+ #[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()
+ }));
+ assert_eq!(
+ cache.revision, None,
+ "old text must not acquire the new revision"
+ );
+ assert!(cache.refresh(None, &sequence, || "new".into()));
+
+ sequence.store(3, Ordering::Release);
+ assert!(cache.refresh(None, &sequence, || "during write".into()));
+ 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, || 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.rs
index c5d6d85f1..a1ba471fb 100644
--- a/src/pane/terminal.rs
+++ b/src/pane/terminal.rs
@@ -189,6 +189,8 @@ pub(crate) struct GhosttyPaneTerminal {
pub core: Mutex<GhosttyPaneCore>,
#[cfg(test)]
pub(super) scroll_metrics_reads: std::sync::atomic::AtomicUsize,
+ #[cfg(all(test, unix))]
+ pub(super) detection_text_reads: std::sync::atomic::AtomicUsize,
key_encoder: Mutex<crate::ghostty::KeyEncoder>,
pending_pty_responses: Arc<Mutex<Vec<Bytes>>>,
}
@@ -1172,6 +1174,8 @@ impl GhosttyPaneTerminal {
Ok(Self {
#[cfg(test)]
scroll_metrics_reads: std::sync::atomic::AtomicUsize::new(0),
+ #[cfg(all(test, unix))]
+ detection_text_reads: std::sync::atomic::AtomicUsize::new(0),
core: Mutex::new(GhosttyPaneCore {
#[cfg(test)]
dirty_collection_hook: None,
@@ -2167,6 +2171,9 @@ impl GhosttyPaneTerminal {
}
pub fn detection_text(&self) -> String {
+ #[cfg(all(test, unix))]
+ self.detection_text_reads
+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
self.core
.lock()
.ok()
diff --git a/src/terminal/runtime.rs b/src/terminal/runtime.rs
index 39fc787dd..682aaae2d 100644
--- a/src/terminal/runtime.rs
+++ b/src/terminal/runtime.rs
@@ -601,6 +601,16 @@ impl TerminalRuntime {
#[cfg(test)]
impl TerminalRuntime {
+ #[cfg(unix)]
+ pub(crate) fn test_start_basic_detection(&mut self) -> mpsc::Receiver<crate::events::AppEvent> {
+ self.0.test_start_basic_detection()
+ }
+
+ #[cfg(unix)]
+ pub(crate) async fn test_wait_for_detection_reads(&self, expected: usize) {
+ self.0.test_wait_for_detection_reads(expected).await;
+ }
+
pub(crate) fn test_scroll_metrics_reads(&self) -> usize {
self.0.test_scroll_metrics_reads()
}