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
add input diagnostics
RoversX29e81f506afe
diff --git a/wezterm-gui/src/input_diagnostics.rs b/wezterm-gui/src/input_diagnostics.rsnew file mode 100644index 00000000..d4ac0419--- /dev/null+++ b/wezterm-gui/src/input_diagnostics.rs@@ -0,0 +1,362 @@+use std::collections::{HashMap, VecDeque};+use std::sync::OnceLock;+use std::time::{Duration, Instant};++use parking_lot::Mutex;++const RECENT_LIMIT: usize = 2048;++static STATE: OnceLock<Mutex<InputDiagnosticsState>> = OnceLock::new();++fn state() -> &'static Mutex<InputDiagnosticsState> {+ STATE.get_or_init(|| Mutex::new(InputDiagnosticsState::default()))+}++#[derive(Debug, Clone)]+pub(crate) struct InputDiagnosticsSnapshot {+ pub(crate) enabled: bool,+ pub(crate) started_ago: Option<Duration>,+ pub(crate) key_events: u64,+ pub(crate) key_down_events: u64,+ pub(crate) key_up_events: u64,+ pub(crate) modifier_events: u64,+ pub(crate) handled_events: u64,+ pub(crate) total_duration: Duration,+ pub(crate) max_duration: Duration,+ pub(crate) recent_p95: Duration,+ pub(crate) slowest_stage: Option<StageSnapshot>,+ pub(crate) stages: Vec<StageSnapshot>,+}++#[derive(Debug, Clone)]+pub(crate) struct StageSnapshot {+ pub(crate) name: &'static str,+ pub(crate) count: u64,+ pub(crate) success: u64,+ pub(crate) total_duration: Duration,+ pub(crate) max_duration: Duration,+ pub(crate) recent_p95: Duration,+}++impl InputDiagnosticsSnapshot {+ pub(crate) fn average_duration(&self) -> Duration {+ avg_duration(self.total_duration, self.key_events)+ }++ pub(crate) fn summary_lines(&self) -> Vec<String> {+ let mut lines = vec![+ "ThinkTerm Input Diagnostics".to_string(),+ format!("status: {}", if self.enabled { "running" } else { "off" }),+ ];+ if let Some(started_ago) = self.started_ago {+ lines.push(format!("started: {} ago", format_duration(started_ago)));+ }+ lines.push(format!("key_events: {}", self.key_events));+ lines.push(format!("key_down_events: {}", self.key_down_events));+ lines.push(format!("key_up_events: {}", self.key_up_events));+ lines.push(format!("modifier_events: {}", self.modifier_events));+ lines.push(format!("handled_events: {}", self.handled_events));+ lines.push(format!(+ "key_event_avg: {}",+ format_duration(self.average_duration())+ ));+ lines.push(format!(+ "key_event_p95_recent: {}",+ format_duration(self.recent_p95)+ ));+ lines.push(format!(+ "key_event_max: {}",+ format_duration(self.max_duration)+ ));+ if let Some(stage) = &self.slowest_stage {+ lines.push(format!(+ "slowest_stage: {} max={} p95={} count={}",+ stage.name,+ format_duration(stage.max_duration),+ format_duration(stage.recent_p95),+ stage.count+ ));+ }+ for stage in &self.stages {+ lines.push(format!(+ "stage.{}: count={} success={} avg={} p95={} max={}",+ stage.name,+ stage.count,+ stage.success,+ format_duration(avg_duration(stage.total_duration, stage.count)),+ format_duration(stage.recent_p95),+ format_duration(stage.max_duration),+ ));+ }+ lines+ }+}++#[derive(Debug)]+pub(crate) struct KeyEventTrace {+ enabled: bool,+ started: Instant,+ key_down: bool,+ modifier: bool,+ handled: bool,+}++impl KeyEventTrace {+ pub(crate) fn begin(key_down: bool, modifier: bool) -> Self {+ Self {+ enabled: enabled(),+ started: Instant::now(),+ key_down,+ modifier,+ handled: false,+ }+ }++ pub(crate) fn handled(&mut self) {+ self.handled = true;+ }+}++impl Drop for KeyEventTrace {+ fn drop(&mut self) {+ if !self.enabled {+ return;+ }+ state().lock().record_key_event(+ self.started.elapsed(),+ self.key_down,+ self.modifier,+ self.handled,+ );+ }+}++#[derive(Debug)]+pub(crate) struct StageTimer {+ enabled: bool,+ name: &'static str,+ started: Instant,+}++impl StageTimer {+ pub(crate) fn begin(name: &'static str) -> Self {+ Self {+ enabled: enabled(),+ name,+ started: Instant::now(),+ }+ }++ pub(crate) fn finish(self, success: bool) {+ if self.enabled {+ state()+ .lock()+ .record_stage(self.name, self.started.elapsed(), success);+ }+ }+}++#[derive(Debug)]+struct InputDiagnosticsState {+ enabled: bool,+ started_at: Option<Instant>,+ key_events: u64,+ key_down_events: u64,+ key_up_events: u64,+ modifier_events: u64,+ handled_events: u64,+ total_duration: Duration,+ max_duration: Duration,+ recent: VecDeque<Duration>,+ stages: HashMap<&'static str, StageStats>,+}++impl Default for InputDiagnosticsState {+ fn default() -> Self {+ Self {+ enabled: false,+ started_at: None,+ key_events: 0,+ key_down_events: 0,+ key_up_events: 0,+ modifier_events: 0,+ handled_events: 0,+ total_duration: Duration::ZERO,+ max_duration: Duration::ZERO,+ recent: VecDeque::with_capacity(RECENT_LIMIT),+ stages: HashMap::new(),+ }+ }+}++impl InputDiagnosticsState {+ fn clear_stats(&mut self) {+ self.key_events = 0;+ self.key_down_events = 0;+ self.key_up_events = 0;+ self.modifier_events = 0;+ self.handled_events = 0;+ self.total_duration = Duration::ZERO;+ self.max_duration = Duration::ZERO;+ self.recent.clear();+ self.stages.clear();+ }++ fn set_enabled(&mut self, enabled: bool) {+ if self.enabled == enabled {+ return;+ }+ self.enabled = enabled;+ if enabled {+ self.started_at = Some(Instant::now());+ self.clear_stats();+ }+ }++ fn record_key_event(+ &mut self,+ duration: Duration,+ key_down: bool,+ modifier: bool,+ handled: bool,+ ) {+ if !self.enabled {+ return;+ }+ self.key_events += 1;+ if key_down {+ self.key_down_events += 1;+ } else {+ self.key_up_events += 1;+ }+ if modifier {+ self.modifier_events += 1;+ }+ if handled {+ self.handled_events += 1;+ }+ self.total_duration += duration;+ self.max_duration = self.max_duration.max(duration);+ push_recent(&mut self.recent, duration);+ }++ fn record_stage(&mut self, name: &'static str, duration: Duration, success: bool) {+ if !self.enabled {+ return;+ }+ self.stages+ .entry(name)+ .or_default()+ .record(duration, success);+ }++ fn snapshot(&self) -> InputDiagnosticsSnapshot {+ let mut stages = self+ .stages+ .iter()+ .map(|(name, stats)| stats.snapshot(name))+ .collect::<Vec<_>>();+ stages.sort_by(|a, b| b.max_duration.cmp(&a.max_duration));+ let slowest_stage = stages.first().cloned();+ InputDiagnosticsSnapshot {+ enabled: self.enabled,+ started_ago: self.started_at.map(|started| started.elapsed()),+ key_events: self.key_events,+ key_down_events: self.key_down_events,+ key_up_events: self.key_up_events,+ modifier_events: self.modifier_events,+ handled_events: self.handled_events,+ total_duration: self.total_duration,+ max_duration: self.max_duration,+ recent_p95: percentile_duration(&self.recent, 0.95),+ slowest_stage,+ stages,+ }+ }+}++#[derive(Debug, Default)]+struct StageStats {+ count: u64,+ success: u64,+ total_duration: Duration,+ max_duration: Duration,+ recent: VecDeque<Duration>,+}++impl StageStats {+ fn record(&mut self, duration: Duration, success: bool) {+ self.count += 1;+ if success {+ self.success += 1;+ }+ self.total_duration += duration;+ self.max_duration = self.max_duration.max(duration);+ push_recent(&mut self.recent, duration);+ }++ fn snapshot(&self, name: &'static str) -> StageSnapshot {+ StageSnapshot {+ name,+ count: self.count,+ success: self.success,+ total_duration: self.total_duration,+ max_duration: self.max_duration,+ recent_p95: percentile_duration(&self.recent, 0.95),+ }+ }+}++pub(crate) fn enabled() -> bool {+ state().lock().enabled+}++pub(crate) fn set_enabled(enabled: bool) {+ state().lock().set_enabled(enabled);+}++pub(crate) fn reset() {+ let mut state = state().lock();+ state.clear_stats();+ if state.enabled {+ state.started_at = Some(Instant::now());+ }+}++pub(crate) fn snapshot() -> InputDiagnosticsSnapshot {+ state().lock().snapshot()+}++fn push_recent(recent: &mut VecDeque<Duration>, duration: Duration) {+ if recent.len() == RECENT_LIMIT {+ recent.pop_front();+ }+ recent.push_back(duration);+}++fn percentile_duration(values: &VecDeque<Duration>, percentile: f64) -> Duration {+ if values.is_empty() {+ return Duration::ZERO;+ }+ let mut values = values.iter().copied().collect::<Vec<_>>();+ values.sort_unstable();+ let idx = ((values.len() - 1) as f64 * percentile).round() as usize;+ values[idx.min(values.len() - 1)]+}++fn avg_duration(total: Duration, count: u64) -> Duration {+ if count == 0 {+ Duration::ZERO+ } else {+ Duration::from_secs_f64(total.as_secs_f64() / count as f64)+ }+}++pub(crate) fn format_duration(duration: Duration) -> String {+ let micros = duration.as_secs_f64() * 1_000_000.0;+ if micros >= 1000.0 {+ format!("{:.2} ms", micros / 1000.0)+ } else {+ format!("{micros:.0} us")+ }+}diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex 3c74fcb0..f348f9b6 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -40,6 +40,7 @@ mod customglyph;mod download;mod frontend;mod glyphcache;+mod input_diagnostics;mod inputmap;mod native_settings;mod overlay;diff --git a/wezterm-gui/src/project_sessions.rs b/wezterm-gui/src/project_sessions.rsindex 21472b9c..8b4cc1a0 100644--- a/wezterm-gui/src/project_sessions.rs+++ b/wezterm-gui/src/project_sessions.rs@@ -13,7 +13,9 @@ use std::collections::HashMap;use std::fs;use std::io::Write;use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;+use std::time::Duration;use wezterm_term::TerminalConfiguration;use wezterm_term::TerminalSize;@@ -118,6 +120,13 @@ pub enum SessionWorkStatus {FinishedUnseen,}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+struct SessionWorkChange {+ status: SessionWorkStatus,+ changed: bool,+ should_persist: bool,+}+#[derive(Debug, Clone, PartialEq, Eq)]pub struct ActivationPlan {pub project_id: ProjectId,@@ -149,6 +158,9 @@ lazy_static::lazy_static! {}));}+static SESSION_STORE_PERSIST_SCHEDULED: AtomicBool = AtomicBool::new(false);+static SESSION_STORE_PERSIST_DIRTY: AtomicBool = AtomicBool::new(false);+pub fn session_store_path() -> PathBuf {config::DATA_DIR.join("thinkterm").join("sessions.json")}@@ -391,20 +403,29 @@ pub fn activate_session_record(pub fn observe_session_work(session_id: &str, is_working: bool) -> Option<SessionWorkStatus> {let mut store = SESSION_STORE.lock();- let (status, changed) = store.observe_session_work(session_id, is_working)?;- if changed {+ let change = store.observe_session_work(session_id, is_working)?;+ if change.should_persist {persist_locked(&store);}- Some(status)+ Some(change.status)}pub fn acknowledge_session_work_for_workspace(workspace: &str) -> bool {let mut store = SESSION_STORE.lock();- let changed = store.acknowledge_session_work_for_workspace(workspace);- if changed {+ let change = store.acknowledge_session_work_for_workspace(workspace);+ if change.should_persist {persist_locked(&store);}- changed+ change.changed+}++pub fn acknowledge_session_work_for_workspace_deferred(workspace: &str) -> bool {+ let mut store = SESSION_STORE.lock();+ let change = store.acknowledge_session_work_for_workspace(workspace);+ if change.should_persist {+ schedule_session_store_persist();+ }+ change.changed}pub fn snapshot_workspace_layout_with_font_scales<F>(@@ -969,7 +990,7 @@ impl SessionStore {&mut self,session_id: &str,is_working: bool,- ) -> Option<(SessionWorkStatus, bool)> {+ ) -> Option<SessionWorkChange> {for project in &mut self.projects {if let Some(session) = project.sessions@@ -977,14 +998,21 @@ impl SessionStore {.find(|session| session.id == session_id){if is_working {+ let should_persist = session.work_finished_unseen;let changed = !session.work_is_running || session.work_finished_unseen;session.work_is_running = true;session.work_finished_unseen = false;- return Some((SessionWorkStatus::Running, changed));+ return Some(SessionWorkChange {+ status: SessionWorkStatus::Running,+ changed,+ should_persist,+ });}+ let mut should_persist = false;let changed = if session.work_is_running {session.work_is_running = false;+ should_persist = !session.work_finished_unseen;session.work_finished_unseen = true;true} else {@@ -995,13 +1023,17 @@ impl SessionStore {} else {SessionWorkStatus::Idle};- return Some((status, changed));+ return Some(SessionWorkChange {+ status,+ changed,+ should_persist,+ });}}None}- fn acknowledge_session_work_for_workspace(&mut self, workspace: &str) -> bool {+ fn acknowledge_session_work_for_workspace(&mut self, workspace: &str) -> SessionWorkChange {for project in &mut self.projects {let project_id = project.id.clone();for session in &mut project.sessions {@@ -1010,14 +1042,23 @@ impl SessionStore {.clone().unwrap_or_else(|| workspace_name_for_session(&project_id, &session.id));if session_workspace == workspace {+ let should_persist = session.work_finished_unseen;let changed = session.work_is_running || session.work_finished_unseen;session.work_is_running = false;session.work_finished_unseen = false;- return changed;+ return SessionWorkChange {+ status: SessionWorkStatus::Idle,+ changed,+ should_persist,+ };}}}- false+ SessionWorkChange {+ status: SessionWorkStatus::Idle,+ changed: false,+ should_persist: false,+ }}fn archive_session(&mut self, session_id: &str) -> bool {@@ -1165,6 +1206,32 @@ fn persist_locked(store: &SessionStore) {}}+fn schedule_session_store_persist() {+ SESSION_STORE_PERSIST_DIRTY.store(true, Ordering::Release);+ if SESSION_STORE_PERSIST_SCHEDULED.swap(true, Ordering::AcqRel) {+ return;+ }++ std::thread::spawn(|| loop {+ std::thread::sleep(Duration::from_millis(50));++ if SESSION_STORE_PERSIST_DIRTY.swap(false, Ordering::AcqRel) {+ let store = SESSION_STORE.lock().clone();+ persist_locked(&store);+ continue;+ }++ SESSION_STORE_PERSIST_SCHEDULED.store(false, Ordering::Release);+ if SESSION_STORE_PERSIST_DIRTY.load(Ordering::Acquire)+ && !SESSION_STORE_PERSIST_SCHEDULED.swap(true, Ordering::AcqRel)+ {+ continue;+ }++ break;+ });+}+fn snapshot_window_layout<F>(window_id: MuxWindowId,pane_font_scale: &F,@@ -1673,6 +1740,36 @@ mod tests {assert!(!loaded.projects[0].sessions[0].work_finished_unseen);}+ #[test]+ fn acknowledged_finished_work_persists_but_runtime_running_state_does_not() {+ let mut store = SessionStore::default();+ let mut session = Session::new(+ "project-1".to_string(),+ "main".to_string(),+ Some("workspace-1".to_string()),+ );+ session.work_finished_unseen = true;+ store.projects.push(Project {+ id: "project-1".to_string(),+ name: "thinkterm".to_string(),+ path: PathBuf::from("/tmp/thinkterm"),+ sessions: vec![session],+ active_session_id: None,+ sessions_collapsed: false,+ });++ let change = store.acknowledge_session_work_for_workspace("workspace-1");+ assert!(change.changed);+ assert!(change.should_persist);+ assert!(!store.projects[0].sessions[0].work_finished_unseen);++ store.projects[0].sessions[0].work_is_running = true;+ let change = store.acknowledge_session_work_for_workspace("workspace-1");+ assert!(change.changed);+ assert!(!change.should_persist);+ assert!(!store.projects[0].sessions[0].work_is_running);+ }+#[test]fn inactive_session_activation_materializes_once() {let mut store = SessionStore::default();diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rsindex 71784ecb..788997e0 100644--- a/wezterm-gui/src/settings_window.rs+++ b/wezterm-gui/src/settings_window.rs@@ -176,6 +176,7 @@ impl SettingsSection {"Diagnostics","Debug Pages","Memory Diagnostics",+ "Input Diagnostics","UI Kit",],Self::UiKit => &[@@ -201,6 +202,10 @@ impl SettingsSection {"IOAccelerator","IOSurface","Graphics",+ "Input",+ "Latency",+ "Key Events",+ "P95",],Self::About => &["About", "Version", "ThinkTerm"],}@@ -222,6 +227,9 @@ enum SettingsAction {ToggleMemoryMonitoring,RefreshMemorySnapshot,CopyMemorySnapshot,+ ToggleInputDiagnostics,+ ResetInputDiagnostics,+ CopyInputDiagnostics,ToggleThemeModeMenu,SetThemeMode(NativeThemeMode),ToggleAppIconMenu,@@ -630,6 +638,7 @@ struct SettingsUiState {memory_snapshot: Option<MemorySnapshot>,main_window_resource_lines: Vec<String>,memory_snapshot_copied_until: Option<Instant>,+ input_diagnostics_copied_until: Option<Instant>,sidebar_scrollbar_visible_until: Option<Instant>,content_scrollbar_visible_until: Option<Instant>,}@@ -657,6 +666,7 @@ impl SettingsUiState {memory_snapshot: None,main_window_resource_lines: Vec::new(),memory_snapshot_copied_until: None,+ input_diagnostics_copied_until: None,sidebar_scrollbar_visible_until: None,content_scrollbar_visible_until: None,}@@ -1452,6 +1462,14 @@ impl SettingsWindow {settings.ui.memory_snapshot_copied_until = None;window.invalidate();}+ if settings+ .ui+ .input_diagnostics_copied_until+ .is_some_and(|until| Instant::now() >= until)+ {+ settings.ui.input_diagnostics_copied_until = None;+ window.invalidate();+ }});}).detach();@@ -2119,6 +2137,12 @@ impl SettingsWindow {let mut summary = snapshot.summary_for_clipboard();summary.push_str("\n\nThinkTerm Resource Stats\n");summary.push_str(&self.memory_resource_lines().join("\n"));+ summary.push_str("\n\n");+ summary.push_str(+ &crate::input_diagnostics::snapshot()+ .summary_lines()+ .join("\n"),+ );window.set_clipboard(Clipboard::Clipboard, summary);self.request_main_window_resource_stats();self.ui.memory_snapshot_copied_until =@@ -2127,6 +2151,35 @@ impl SettingsWindow {self.schedule_copied_state_clear(window);}}+ SettingsAction::ToggleInputDiagnostics => {+ self.ui.open_dropdown = None;+ let enabled = !crate::input_diagnostics::enabled();+ crate::input_diagnostics::set_enabled(enabled);+ self.status = if enabled {+ "Input diagnostics started. Leave this running while you reproduce typing lag."+ .to_string()+ } else {+ "Input diagnostics stopped.".to_string()+ };+ }+ SettingsAction::ResetInputDiagnostics => {+ self.ui.open_dropdown = None;+ crate::input_diagnostics::reset();+ self.status = "Input diagnostics reset.".to_string();+ }+ SettingsAction::CopyInputDiagnostics => {+ self.ui.open_dropdown = None;+ window.set_clipboard(+ Clipboard::Clipboard,+ crate::input_diagnostics::snapshot()+ .summary_lines()+ .join("\n"),+ );+ self.ui.input_diagnostics_copied_until =+ Some(Instant::now() + Duration::from_millis(1400));+ self.status = "Input diagnostics copied.".to_string();+ self.schedule_copied_state_clear(window);+ }SettingsAction::ToggleThemeModeMenu => {self.ui.open_dropdown =if self.ui.open_dropdown == Some(SettingsDropdown::ThemeMode) {@@ -3007,9 +3060,9 @@ impl SettingsWindow {first_row_y + row_step,row_width,"Visible Developer Tabs",- "UI Kit and Memory tabs are shown here; diagnostics do not run automatically.",+ "UI Kit and Memory/Input tabs are shown here; diagnostics do not run automatically.",if self.developer_mode_enabled() {- "UI Kit, Memory"+ "UI Kit, Memory/Input"} else {"Hidden"},@@ -3291,7 +3344,7 @@ impl SettingsWindow {let scroll = self.ui.content_scroll.offset;let row_step = self.settings_row_step();let section_y = CONTENT_SECTION_Y - scroll;- let row_count = 11;+ let row_count = 15;let (card_y, first_row_y) = self.settings_card_geometry(section_y, row_count);let card_height = self.settings_card_height(row_count);let button_y = card_y + card_height + self.settings_section_card_gap();@@ -3301,7 +3354,7 @@ impl SettingsWindow {&ui_font,x,section_y,- "Memory diagnostics are manual. Developer mode only reveals this page; sampling starts when you enable it here.",+ "Memory and input diagnostics are manual. Developer mode only reveals this page; sampling starts when you enable it here.",palette.secondary_text,max_width,)?;@@ -3359,8 +3412,25 @@ impl SettingsWindow {} else {"Off"};+ let input = crate::input_diagnostics::snapshot();+ let input_state = if input.enabled { "Running" } else { "Off" };+ let input_events = format!("{} events", input.key_events);+ let input_p95 = crate::input_diagnostics::format_duration(input.recent_p95);+ let input_avg = crate::input_diagnostics::format_duration(input.average_duration());+ let input_slowest = input+ .slowest_stage+ .as_ref()+ .map(|stage| {+ format!(+ "{} {}",+ stage.name,+ crate::input_diagnostics::format_duration(stage.max_duration)+ )+ })+ .unwrap_or_else(|| "No stage samples".to_string());let resource_lines = self.memory_resource_lines();- let resource_card_y = button_y + CONTROL_HEIGHT + self.settings_section_card_gap();+ let input_button_y = button_y + CONTROL_HEIGHT + 16.0;+ let resource_card_y = input_button_y + CONTROL_HEIGHT + self.settings_section_card_gap();let resource_line_height = 30.0;let resource_card_height = 88.0 + resource_line_height * resource_lines.len() as f32;self.ui.content_scroll.set_extents(@@ -3482,12 +3552,52 @@ impl SettingsWindow {&text,true,)?;+ self.paint_setting_row(+ layers,+ row_x,+ first_row_y + row_step * 11.0,+ row_width,+ "Input Diagnostics",+ "Manual tracing for long-running typing latency. No key text is stored.",+ input_state,+ true,+ )?;+ self.paint_setting_row(+ layers,+ row_x,+ first_row_y + row_step * 12.0,+ row_width,+ "Key Event Samples",+ "Counts events seen since diagnostics started or reset.",+ &input_events,+ true,+ )?;+ self.paint_setting_row(+ layers,+ row_x,+ first_row_y + row_step * 13.0,+ row_width,+ "Input Event Avg / P95",+ "Wall time spent in the key event path.",+ &format!("{input_avg} / {input_p95}"),+ true,+ )?;+ self.paint_setting_row(+ layers,+ row_x,+ first_row_y + row_step * 14.0,+ row_width,+ "Slowest Stage",+ "The slowest recorded sub-stage so far.",+ &input_slowest,+ true,+ )?;if let Some(error) = &snapshot.vmmap_error {self.draw_text(layers,&ui_font,row_x,- first_row_y + row_step * 11.0,+ first_row_y + row_step * 15.0,error,palette.muted_text,row_width,@@ -3529,6 +3639,42 @@ impl SettingsWindow {copy_label,SettingsAction::CopyMemorySnapshot,)?;+ let input_primary_label = if input.enabled {+ "Stop Input Trace"+ } else {+ "Start Input Trace"+ };+ self.draw_button(+ layers,+ x,+ input_button_y,+ self.button_width_for_label(input_primary_label, 250.0),+ input_primary_label,+ SettingsAction::ToggleInputDiagnostics,+ )?;+ let reset_input_x = x + self.button_width_for_label(input_primary_label, 250.0) + 16.0;+ self.draw_button(+ layers,+ reset_input_x,+ input_button_y,+ self.button_width_for_label("Reset Input", 190.0),+ "Reset Input",+ SettingsAction::ResetInputDiagnostics,+ )?;+ let input_copied = self+ .ui+ .input_diagnostics_copied_until+ .is_some_and(|until| Instant::now() < until);+ let input_copy_label = if input_copied { "Copied" } else { "Copy Input" };+ let copy_input_x = reset_input_x + self.button_width_for_label("Reset Input", 190.0) + 16.0;+ self.draw_button(+ layers,+ copy_input_x,+ input_button_y,+ self.button_width_for_label(input_copy_label, 180.0),+ input_copy_label,+ SettingsAction::CopyInputDiagnostics,+ )?;self.paint_group_card(layers, x, resource_card_y, max_width, resource_card_height)?;self.draw_text(diff --git a/wezterm-gui/src/termwindow/keyevent.rs b/wezterm-gui/src/termwindow/keyevent.rsindex 8ff085f6..7084a4fd 100644--- a/wezterm-gui/src/termwindow/keyevent.rs+++ b/wezterm-gui/src/termwindow/keyevent.rs@@ -516,14 +516,19 @@ impl super::TermWindow {}self.key_table_state.did_process_key();- let handled = match self.perform_key_assignment(&pane, &entry.action) {+ let stage = crate::input_diagnostics::StageTimer::begin("key_assignment");+ let assignment_result = self.perform_key_assignment(&pane, &entry.action);+ stage.finish(assignment_result.is_ok());+ let handled = match assignment_result {Ok(PerformAssignmentResult::Handled) => true,Err(_) => true,Ok(_) => false,};if handled {+ let stage = crate::input_diagnostics::StageTimer::begin("key_invalidate");context.invalidate();+ stage.finish(true);if leader_active {// A successful leader key-lookup cancels the leader@@ -577,19 +582,29 @@ impl super::TermWindow {if self.config.debug_key_events {log::info!("win32: Encoded input as {:?}", encoded);}- pane.writer()+ let stage = crate::input_diagnostics::StageTimer::begin(+ "process_encoded_writer_write",+ );+ let res = pane+ .writer().write_all(encoded.as_bytes())- .context("sending win32-input-mode encoded data")- .ok();+ .context("sending win32-input-mode encoded data");+ stage.finish(res.is_ok());+ res.ok();did_encode = true;} else if let Some(encoded) = self.encode_kitty_input(&pane, &key_event) {if self.config.debug_key_events {log::info!("kitty: Encoded input as {:?}", encoded);}- pane.writer()+ let stage = crate::input_diagnostics::StageTimer::begin(+ "process_encoded_writer_write",+ );+ let res = pane+ .writer().write_all(encoded.as_bytes())- .context("sending kitty encoded data")- .ok();+ .context("sending kitty encoded data");+ stage.finish(res.is_ok());+ res.ok();did_encode = true;}};@@ -604,12 +619,14 @@ impl super::TermWindow {);}- did_encode = if is_down {+ let stage = crate::input_diagnostics::StageTimer::begin("process_pane_key");+ let res = if is_down {pane.key_down(term_key, tw_raw_modifiers)} else {pane.key_up(term_key, tw_raw_modifiers)- }- .is_ok();+ };+ stage.finish(res.is_ok());+ did_encode = res.is_ok();};if did_encode {@@ -617,16 +634,26 @@ impl super::TermWindow {&& !keycode.is_modifier()&& self.pane_state(pane.pane_id()).overlay.is_none(){+ let stage = crate::input_diagnostics::StageTimer::begin(+ "scroll_to_bottom_for_input",+ );self.maybe_scroll_to_bottom_for_input(&pane);+ stage.finish(true);}if is_down&& self.config.hide_mouse_cursor_when_typing&& !keycode.is_modifier(){+ let stage =+ crate::input_diagnostics::StageTimer::begin("set_cursor_none");context.set_cursor(None);+ stage.finish(true);}if !keycode.is_modifier() {+ let stage =+ crate::input_diagnostics::StageTimer::begin("key_invalidate");context.invalidate();+ stage.finish(true);}return true;@@ -639,6 +666,8 @@ impl super::TermWindow {}pub fn raw_key_event_impl(&mut self, key: RawKeyEvent, context: &dyn WindowOps) {+ let mut input_trace =+ crate::input_diagnostics::KeyEventTrace::begin(key.key_is_down, key.key.is_modifier());// The leader key is a kind of modal modifier key.// It is allowed to be active for up to the leader timeout duration,// after which it auto-deactivates.@@ -669,7 +698,10 @@ impl super::TermWindow {self.schedule_next_status_update();}- let pane = match self.get_active_pane_or_overlay() {+ let stage = crate::input_diagnostics::StageTimer::begin("get_active_pane");+ let pane = self.get_active_pane_or_overlay();+ stage.finish(pane.is_some());+ let pane = match pane {Some(pane) => pane,None => return,};@@ -681,7 +713,8 @@ impl super::TermWindow {};if let Some(phys_key) = &phys_key {- if self.process_key(+ let stage = crate::input_diagnostics::StageTimer::begin("raw_process_key");+ let handled = self.process_key(&pane,context,&phys_key,@@ -691,7 +724,10 @@ impl super::TermWindow {OnlyKeyBindings::Yes,key.key_is_down,None,- ) {+ );+ stage.finish(handled);+ if handled {+ input_trace.handled();key.set_handled();return;}@@ -702,7 +738,8 @@ impl super::TermWindow {raw @ KeyCode::RawCode(_) => raw.clone(),_ => KeyCode::RawCode(key.raw_code),};- if self.process_key(+ let stage = crate::input_diagnostics::StageTimer::begin("raw_process_key");+ let handled = self.process_key(&pane,context,&raw_key,@@ -712,7 +749,10 @@ impl super::TermWindow {OnlyKeyBindings::Yes,key.key_is_down,None,- ) {+ );+ stage.finish(handled);+ if handled {+ input_trace.handled();key.set_handled();return;}@@ -723,7 +763,8 @@ impl super::TermWindow {return;}- if self.process_key(+ let stage = crate::input_diagnostics::StageTimer::begin("raw_process_key");+ let handled = self.process_key(&pane,context,&key.key,@@ -733,7 +774,10 @@ impl super::TermWindow {OnlyKeyBindings::Yes,key.key_is_down,None,- ) {+ );+ stage.finish(handled);+ if handled {+ input_trace.handled();key.set_handled();}}@@ -811,8 +855,15 @@ impl super::TermWindow {if self.handle_inline_tab_rename_key(&window_key, context) {return;}+ let mut input_trace = crate::input_diagnostics::KeyEventTrace::begin(+ window_key.key_is_down,+ window_key.key.is_modifier(),+ );- let pane = match self.get_active_pane_or_overlay() {+ let stage = crate::input_diagnostics::StageTimer::begin("get_active_pane");+ let pane = self.get_active_pane_or_overlay();+ stage.finish(pane.is_some());+ let pane = match pane {Some(pane) => pane,None => return,};@@ -842,18 +893,28 @@ impl super::TermWindow {}let modifiers = window_key.modifiers;+ let stage = crate::input_diagnostics::StageTimer::begin("translate_key_code");let key = self.win_key_code_to_termwiz_key_code(&window_key.key);+ stage.finish(true);let should_acknowledge_session_work = window_key.key_is_down&& match &key {Key::Code(key) => !key.is_modifier(),Key::Composed(_) => true,Key::None => false,};- if should_acknowledge_session_work && self.acknowledge_active_workspace_session_work() {- context.invalidate();+ if should_acknowledge_session_work {+ let stage = crate::input_diagnostics::StageTimer::begin("ack_session_work");+ let should_invalidate = self.acknowledge_active_workspace_session_work_deferred();+ stage.finish(should_invalidate);+ if should_invalidate {+ let stage = crate::input_diagnostics::StageTimer::begin("key_invalidate");+ context.invalidate();+ stage.finish(true);+ }}- if self.process_key(+ let stage = crate::input_diagnostics::StageTimer::begin("process_key");+ let handled = self.process_key(&pane,context,&window_key.key,@@ -863,7 +924,10 @@ impl super::TermWindow {OnlyKeyBindings::No,window_key.key_is_down,Some(&window_key),- ) {+ );+ stage.finish(handled);+ if handled {+ input_trace.handled();return;}@@ -871,7 +935,9 @@ impl super::TermWindow {// any key table rules. Therefore, we should pop all `until_unknown`// entries from the stack.if window_key.key_is_down {+ let stage = crate::input_diagnostics::StageTimer::begin("key_table_pop_unknown");self.key_table_state.pop_until_unknown();+ stage.finish(true);}match key {@@ -882,6 +948,7 @@ impl super::TermWindow {// a registered key binding; swallow this event and cancel// the leader modifier.self.leader_done();+ input_trace.handled();return;}self.key_table_state.did_process_key();@@ -891,6 +958,7 @@ impl super::TermWindow {if window_key.key_is_down {modal.key_down(key, modifiers, self).ok();}+ input_trace.handled();return;}@@ -898,16 +966,24 @@ impl super::TermWindow {if self.config.debug_key_events {log::info!("win32: Encoded input as {:?}", encoded);}- pane.writer()+ let stage = crate::input_diagnostics::StageTimer::begin("encoded_writer_write");+ let res = pane+ .writer().write_all(encoded.as_bytes())- .context("sending win32-input-mode encoded data")+ .context("sending win32-input-mode encoded data");+ stage.finish(res.is_ok());+ res} else if let Some(encoded) = self.encode_kitty_input(&pane, &window_key) {if self.config.debug_key_events {log::info!("kitty: Encoded input as {:?}", encoded);}- pane.writer()+ let stage = crate::input_diagnostics::StageTimer::begin("encoded_writer_write");+ let res = pane+ .writer().write_all(encoded.as_bytes())- .context("sending kitty encoded data")+ .context("sending kitty encoded data");+ stage.finish(res.is_ok());+ res} else {if self.config.debug_key_events {log::info!(@@ -918,28 +994,40 @@ impl super::TermWindow {);}- if window_key.key_is_down {+ let stage = crate::input_diagnostics::StageTimer::begin("pane_key");+ let res = if window_key.key_is_down {pane.key_down(key, modifiers)} else {pane.key_up(key, modifiers)- }+ };+ stage.finish(res.is_ok());+ res};if res.is_ok() {+ input_trace.handled();if window_key.key_is_down&& !key.is_modifier()&& self.pane_state(pane.pane_id()).overlay.is_none(){+ let stage = crate::input_diagnostics::StageTimer::begin(+ "scroll_to_bottom_for_input",+ );self.maybe_scroll_to_bottom_for_input(&pane);+ stage.finish(true);}if window_key.key_is_down&& self.config.hide_mouse_cursor_when_typing&& !key.is_modifier(){+ let stage = crate::input_diagnostics::StageTimer::begin("set_cursor_none");context.set_cursor(None);+ stage.finish(true);}if !key.is_modifier() {+ let stage = crate::input_diagnostics::StageTimer::begin("key_invalidate");context.invalidate();+ stage.finish(true);}}}@@ -952,15 +1040,25 @@ impl super::TermWindow {// a registered key binding; swallow this event and cancel// the leader modifier.self.leader_done();+ input_trace.handled();return;}self.key_table_state.did_process_key();if self.config.debug_key_events {log::info!("send to pane string={:?}", s);}- pane.writer().write_all(s.as_bytes()).ok();+ let stage = crate::input_diagnostics::StageTimer::begin("composed_writer_write");+ let res = pane.writer().write_all(s.as_bytes());+ stage.finish(res.is_ok());+ res.ok();+ input_trace.handled();+ let stage =+ crate::input_diagnostics::StageTimer::begin("scroll_to_bottom_for_input");self.maybe_scroll_to_bottom_for_input(&pane);+ stage.finish(true);+ let stage = crate::input_diagnostics::StageTimer::begin("key_invalidate");context.invalidate();+ stage.finish(true);}Key::None => {}}diff --git a/wezterm-gui/src/termwindow/ui/sidebar.rs b/wezterm-gui/src/termwindow/ui/sidebar.rsindex df5d7460..1d6672dd 100644--- a/wezterm-gui/src/termwindow/ui/sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs@@ -96,6 +96,14 @@ impl crate::TermWindow {project_sessions::acknowledge_session_work_for_workspace(window.get_workspace())}+ pub(crate) fn acknowledge_active_workspace_session_work_deferred(&self) -> bool {+ let mux = Mux::get();+ let Some(window) = mux.get_window(self.mux_window_id) else {+ return false;+ };+ project_sessions::acknowledge_session_work_for_workspace_deferred(window.get_workspace())+ }+pub fn workspace_sidebar_width(&self) -> usize {if self.workspace_sidebar_collapsed {0