the runtime your coding agents live on
Rust agentagent-orchestrationaiai-agentsclaude-codeclicodexcoding-agentsdeveloper-toolsdevtoolsmultiplexerrustterminalterminal-multiplexerterminal-uitmuxtuiworkspace-manager
perf: avoid unused terminal reads in client snapshots (#4847)
JJ Liebig5d78d05d7ff8
diff --git a/src/app/agents.rs b/src/app/agents.rsindex fd2a58edb..0aa26fb21 100644--- a/src/app/agents.rs+++ b/src/app/agents.rs@@ -374,7 +374,7 @@ impl App {if !terminal.is_agent_terminal() {return None;}- let pane = self.pane_info(ws_idx, pane_id)?;+ let pane = self.pane_metadata(ws_idx, pane_id)?;Some(crate::api::schema::AgentInfo {terminal_id: pane.terminal_id,name: terminal.agent_name.clone(),diff --git a/src/app/api/session.rs b/src/app/api/session.rsindex a7d14b3dd..acd65174a 100644--- a/src/app/api/session.rs+++ b/src/app/api/session.rs@@ -1,4 +1,4 @@-use crate::api::schema::{ResponseResult, SessionSnapshot};+use crate::api::schema::{PaneInfo, ResponseResult, SessionSnapshot};use crate::app::App;use super::responses::encode_success;@@ -14,6 +14,17 @@ impl App {}pub(crate) fn session_snapshot(&self) -> SessionSnapshot {+ self.session_snapshot_with_pane_info(Self::pane_info)+ }++ pub(crate) fn session_metadata_snapshot(&self) -> SessionSnapshot {+ self.session_snapshot_with_pane_info(Self::pane_metadata)+ }++ fn session_snapshot_with_pane_info(+ &self,+ pane_info: fn(&Self, usize, crate::layout::PaneId) -> Option<PaneInfo>,+ ) -> SessionSnapshot {let focused_workspace_id = self.state.active@@ -30,6 +41,7 @@ impl App {let mut workspaces = Vec::new();let mut tabs = Vec::new();let mut layouts = Vec::new();+ let mut panes = Vec::new();for (ws_idx, ws) in self.state.workspaces.iter().enumerate() {workspaces.push(self.workspace_info(ws_idx));for tab_idx in 0..ws.tabs.len() {@@ -39,6 +51,13 @@ impl App {if let Some(layout) = self.pane_layout_snapshot(ws_idx, tab_idx) {layouts.push(layout);}+ panes.extend(+ ws.tabs[tab_idx]+ .layout+ .pane_ids()+ .into_iter()+ .filter_map(|pane_id| pane_info(self, ws_idx, pane_id)),+ );}}@@ -50,7 +69,7 @@ impl App {focused_pane_id,workspaces,tabs,- panes: self.collect_panes_for_workspace(None).unwrap_or_default(),+ panes,layouts,agents: self.collect_agent_infos(),}diff --git a/src/app/creation.rs b/src/app/creation.rsindex 05736fe5e..db2b584de 100644--- a/src/app/creation.rs+++ b/src/app/creation.rs@@ -309,11 +309,8 @@ impl App {ws_idx: usize,pane_id: crate::layout::PaneId,) -> Option<crate::api::schema::PaneInfo> {- let ws = self.state.workspaces.get(ws_idx)?;- let pane = ws.pane_state(pane_id)?;- let terminal = self.state.terminals.get(&pane.attached_terminal_id)?;- let tab_idx = ws.find_tab_index_for_pane(pane_id)?;- let scroll = self+ let mut pane = self.pane_metadata(ws_idx, pane_id)?;+ pane.scroll = self.state.runtime_for_pane_in_workspace(&self.terminal_runtimes, ws_idx, pane_id).and_then(|runtime| runtime.scroll_metrics())@@ -322,6 +319,18 @@ impl App {max_offset_from_bottom: metrics.max_offset_from_bottom as u64,viewport_rows: metrics.viewport_rows as u64,});+ Some(pane)+ }++ pub(super) fn pane_metadata(+ &self,+ ws_idx: usize,+ pane_id: crate::layout::PaneId,+ ) -> Option<crate::api::schema::PaneInfo> {+ let ws = self.state.workspaces.get(ws_idx)?;+ let pane = ws.pane_state(pane_id)?;+ let terminal = self.state.terminals.get(&pane.attached_terminal_id)?;+ let tab_idx = ws.find_tab_index_for_pane(pane_id)?;let focused = self.state.active == Some(ws_idx)&& ws.active_tab == tab_idx&& ws@@ -351,7 +360,7 @@ impl App {state_labels: presentation.state_labels,tokens: terminal.metadata_tokens.values(),agent_session: terminal_agent_session_info(terminal),- scroll,+ scroll: None,revision: terminal.revision,})}diff --git a/src/pane.rs b/src/pane.rsindex 8fd8e3961..3518d11ed 100644--- a/src/pane.rs+++ b/src/pane.rs@@ -3743,6 +3743,13 @@ impl PaneRuntime {Self::test_with_scrollback_bytes(cols, rows, 0, bytes)}+ pub(crate) fn test_scroll_metrics_reads(&self) -> usize {+ self.terminal+ .ghostty+ .scroll_metrics_reads+ .load(Ordering::Relaxed)+ }+pub(crate) fn test_contend_during_dirty_collection(&self,bytes: Vec<u8>,diff --git a/src/pane/terminal.rs b/src/pane/terminal.rsindex 24379d222..0edd5b98c 100644--- a/src/pane/terminal.rs+++ b/src/pane/terminal.rs@@ -187,6 +187,8 @@ pub(crate) enum TerminalCompressionStep {pub(crate) struct GhosttyPaneTerminal {pub core: Mutex<GhosttyPaneCore>,+ #[cfg(test)]+ pub(super) scroll_metrics_reads: std::sync::atomic::AtomicUsize,key_encoder: Mutex<crate::ghostty::KeyEncoder>,pending_pty_responses: Arc<Mutex<Vec<Bytes>>>,}@@ -1172,6 +1174,8 @@ impl GhosttyPaneTerminal {crate::ghostty::KeyEncoder::new().map_err(|e| std::io::Error::other(e.to_string()))?;key_encoder.set_from_terminal(&terminal);Ok(Self {+ #[cfg(test)]+ scroll_metrics_reads: std::sync::atomic::AtomicUsize::new(0),core: Mutex::new(GhosttyPaneCore {#[cfg(test)]dirty_collection_hook: None,@@ -1805,6 +1809,9 @@ impl GhosttyPaneTerminal {}pub fn scroll_metrics(&self) -> Option<ScrollMetrics> {+ #[cfg(test)]+ self.scroll_metrics_reads+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);let Ok(core) = self.core.lock() else {return None;};diff --git a/src/server/client_shell.rs b/src/server/client_shell.rsindex d79c89cf5..0a98da097 100644--- a/src/server/client_shell.rs+++ b/src/server/client_shell.rs@@ -24,7 +24,7 @@ pub(super) fn snapshot_with_completions(protocol::ClientShellSnapshot,protocol::endpoint::EndpointAgentCompletions,) {- let snapshot = app.session_snapshot();+ let snapshot = app.session_metadata_snapshot();let completions = protocol::endpoint::EndpointAgentCompletions {boot_id: boot_id.to_owned(),revision,@@ -629,6 +629,94 @@ fn split_hit_rect(mod tests {use super::*;+ #[tokio::test(flavor = "current_thread")]+ async fn snapshot_metadata_skips_scroll_reads_and_preserves_public_session_data() {+ let (_api_tx, api_rx) = tokio::sync::mpsc::unbounded_channel();+ let mut app = crate::app::App::new(+ &crate::config::Config::default(),+ crate::app::AppPolicy::TEST,+ None,+ api_rx,+ crate::api::EventHub::default(),+ );+ let mut workspace = crate::workspace::Workspace::test_new("active");+ workspace.test_add_tab(None);+ app.state.workspaces = vec![workspace, crate::workspace::Workspace::test_new("hidden")];+ app.state.active = Some(0);+ app.state.ensure_test_terminals();+ let history = (0..40)+ .map(|line| format!("line-{line}\r\n"))+ .collect::<String>();+ for (index, terminal) in app.state.terminals.values_mut().enumerate() {+ if index < 2 {+ terminal.set_detected_state(+ Some(crate::detect::Agent::Pi),+ crate::detect::AgentState::Working,+ );+ terminal.agent_name = Some(format!("agent-{index}"));+ terminal.last_agent_state_change_seq = Some(5);+ terminal.last_agent_completion_seq = Some(7);+ }+ let runtime = crate::terminal::TerminalRuntime::test_with_scrollback_bytes(+ 20,+ 5,+ 1000,+ history.as_bytes(),+ );+ runtime.scroll_up(3);+ app.terminal_runtimes.insert(terminal.id.clone(), runtime);+ }++ let metadata = app.session_metadata_snapshot();+ assert_eq!(metadata.panes.len(), 3);+ assert_eq!(metadata.agents.len(), 2);+ assert!(metadata.panes.iter().all(|pane| pane.scroll.is_none()));+ assert!(app+ .terminal_runtimes+ .values()+ .all(|runtime| runtime.test_scroll_metrics_reads() == 0));++ let mut public = app.session_snapshot();+ for pane in &mut public.panes {+ let scroll = pane+ .scroll+ .take()+ .expect("public session must expose scroll");+ assert_eq!(scroll.offset_from_bottom, 3);+ assert!(scroll.max_offset_from_bottom >= 3);+ assert_eq!(scroll.viewport_rows, 5);+ }+ assert_eq!(metadata, public);+ assert!(app+ .terminal_runtimes+ .values()+ .all(|runtime| runtime.test_scroll_metrics_reads() == 1));++ let (shell, completions) = snapshot_with_completions(&app, "boot", 9, None, None);+ assert_eq!(shell.panes.len(), 3);+ assert_eq!(shell.agents.len(), 2);+ assert_eq!(shell.focused_pane_id, metadata.focused_pane_id);+ for (pane, public_pane) in shell.panes.iter().zip(&metadata.panes) {+ assert_eq!(pane.pane_id, public_pane.pane_id);+ assert_eq!(pane.workspace_id, public_pane.workspace_id);+ assert_eq!(pane.tab_id, public_pane.tab_id);+ assert_eq!(pane.cwd, public_pane.cwd);+ }+ for (agent, public_agent) in shell.agents.iter().zip(&metadata.agents) {+ assert_eq!(agent.pane_id, public_agent.pane_id);+ assert_eq!(agent.name, public_agent.name);+ assert_eq!(agent.agent_status, public_agent.agent_status);+ assert_eq!(agent.state_change_seq, 5);+ }+ assert_eq!(completions.revision, 9);+ assert_eq!(completions.completions.len(), 2);+ assert!(completions.completions.iter().all(|(_, seq)| *seq == 7));+ assert!(app+ .terminal_runtimes+ .values()+ .all(|runtime| runtime.test_scroll_metrics_reads() == 1));+ }+#[test]fn snapshot_projects_cached_release_and_update_facts() {let (_api_tx, api_rx) = tokio::sync::mpsc::unbounded_channel();diff --git a/src/server/render_scale_benchmark.rs b/src/server/render_scale_benchmark.rsindex 754c9dbcd..cba0cbfd8 100644--- a/src/server/render_scale_benchmark.rs+++ b/src/server/render_scale_benchmark.rs@@ -16,7 +16,6 @@ const ROWS: u16 = 40;const SAMPLE_COUNT: usize = 40;const WARMUP_COUNT: usize = 5;const CARDINALITIES: [usize; 3] = [1, 15, 50];-const CLIENT_CARDINALITIES: [usize; 2] = [1, 4];#[derive(Clone, Copy)]struct StageStats {@@ -233,7 +232,8 @@ fn profile_snapshot_encoding(build: fn(usize) -> Vec<Workspace>,count: usize,client_count: usize,-) -> StageStats {+ hidden_output: bool,+) -> (StageStats, StageStats) {let mut pipeline = RenderPipeline::new(build(count));pipeline.app.state.ensure_test_terminals();for terminal in pipeline.app.state.terminals.values_mut() {@@ -245,6 +245,23 @@ fn profile_snapshot_encoding(terminal.last_agent_completion_seq = Some(1);}let run = || {+ if hidden_output {+ for (workspace_index, workspace) in+ pipeline.app.state.workspaces.iter().enumerate().skip(1)+ {+ let pane_id = workspace.tabs[0].root_pane;+ pipeline+ .app+ .state+ .runtime_for_pane_in_workspace(+ &pipeline.app.terminal_runtimes,+ workspace_index,+ pane_id,+ )+ .unwrap()+ .test_process_pty_bytes(b"hidden output\r\n");+ }+ }let started = Instant::now();let (template, completions) = super::client_shell::snapshot_with_completions(&pipeline.app,@@ -253,6 +270,7 @@ fn profile_snapshot_encoding(None,None,);+ let construction_elapsed = started.elapsed();for client_index in 0..client_count {let mut snapshot = template.clone();snapshot.revision = client_index as u64 + 1;@@ -271,24 +289,31 @@ fn profile_snapshot_encoding(.expect("benchmark snapshot message should frame"),);}- started.elapsed()+ (construction_elapsed, started.elapsed())};for _ in 0..WARMUP_COUNT {black_box(run());}- summarize((0..SAMPLE_COUNT).map(|_| run()).collect())+ let (construction, total) = (0..SAMPLE_COUNT).map(|_| run()).unzip();+ (summarize(construction), summarize(total))}fn print_snapshot_encoding_profiles(label: &str, build: fn(usize) -> Vec<Workspace>) {println!("{label} populated agent snapshots + completions + JSON framing");- println!(" panes clients median_us p95_us max_us");- for count in CARDINALITIES {- for client_count in CLIENT_CARDINALITIES {- let stats = profile_snapshot_encoding(build, count, client_count);- println!(- " {count:>10} {client_count:>7} {:>9} {:>6} {:>6}",- stats.median_us, stats.p95_us, stats.max_us- );+ println!(" panes clients hidden_output construction_us median_us p95_us max_us");+ for count in [1, 15, 118] {+ for client_count in [1, 2] {+ for hidden_output in [false, true] {+ if hidden_output && label != "background workspaces" {+ continue;+ }+ let (construction, stats) =+ profile_snapshot_encoding(build, count, client_count, hidden_output);+ println!(+ " {count:>10} {client_count:>7} {hidden_output:>13} {:>15} {:>9} {:>6} {:>6}",+ construction.median_us, stats.median_us, stats.p95_us, stats.max_us+ );+ }}}}diff --git a/src/terminal/runtime.rs b/src/terminal/runtime.rsindex 917134090..39fc787dd 100644--- a/src/terminal/runtime.rs+++ b/src/terminal/runtime.rs@@ -601,6 +601,10 @@ impl TerminalRuntime {#[cfg(test)]impl TerminalRuntime {+ pub(crate) fn test_scroll_metrics_reads(&self) -> usize {+ self.0.test_scroll_metrics_reads()+ }+#[cfg(unix)]pub(crate) fn test_enable_kitty_source_forwarding(&self) {self.0.test_enable_kitty_source_forwarding();