//! Application orchestration. //! //! - `state.rs` — AppState, Mode, and pure data structs //! - `actions.rs` — state mutations (testable without PTYs/async) //! - `input.rs` — key/mouse → action translation pub(crate) mod actions; mod agents; mod api; mod api_helpers; mod config_io; mod creation; mod ids; mod input; mod runtime; mod session; pub mod state; mod terminal_targets; mod theme_sync; use std::collections::{HashMap, HashSet}; use std::future::pending; use std::io::{self, Write}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant}; const MIN_RENDER_INTERVAL: Duration = Duration::from_millis(16); pub(crate) const ANIMATION_INTERVAL: Duration = Duration::from_millis(16); pub(crate) const HEADLESS_ANIMATION_INTERVAL: Duration = Duration::from_millis(128); pub(crate) const HEADLESS_ANIMATION_TICK_STEP: u32 = 8; pub(crate) const SELECTION_AUTOSCROLL_INTERVAL: Duration = Duration::from_millis(30); const RESIZE_POLL_INTERVAL: Duration = Duration::from_millis(100); const GIT_REMOTE_STATUS_REFRESH_INTERVAL: Duration = Duration::from_millis(1500); const AUTO_UPDATE_CHECK_INTERVAL: Duration = Duration::from_secs(30 * 60); const SESSION_SAVE_DEBOUNCE: Duration = Duration::from_secs(5); const SIDEBAR_DOUBLE_CLICK_WINDOW: Duration = Duration::from_millis(350); use crossterm::{ event::{DisableMouseCapture, EnableMouseCapture}, execute, terminal, }; use ratatui::layout::Rect; use ratatui::DefaultTerminal; use tokio::sync::{mpsc, Notify}; use tracing::info; use crate::config::Config; use crate::events::AppEvent; pub use state::{AppState, Mode, ToastKind, ViewState}; /// Full application: AppState + runtime concerns (event channels, async I/O). #[derive(Debug, Clone)] pub(crate) struct OverlayPaneState { ws_idx: usize, tab_idx: usize, previous_focus: crate::layout::PaneId, previous_zoomed: bool, temp_files: Vec, } pub struct App { pub state: AppState, pub event_tx: mpsc::Sender, pub(crate) event_rx: mpsc::Receiver, pub(crate) api_rx: tokio::sync::mpsc::UnboundedReceiver, pub(crate) event_hub: crate::api::EventHub, pub(crate) last_focus: Option<(usize, crate::layout::PaneId)>, pub(crate) no_session: bool, pub(crate) input_rx: Option>, pub(crate) last_terminal_size: Option<(u16, u16)>, pub(crate) config_diagnostic_deadline: Option, pub(crate) toast_deadline: Option, pub(crate) last_git_remote_status_refresh: Instant, pub(crate) git_refresh_in_flight: bool, pub(crate) last_sidebar_divider_click: Option, pub(crate) next_resize_poll: Instant, pub(crate) next_animation_tick: Option, pub(crate) next_auto_update_check: Option, pub(crate) selection_autoscroll_deadline: Option, pub(crate) session_save_deadline: Option, pub(crate) last_render_at: Option, pub(crate) suppressed_repeat_keys: HashSet<(crossterm::event::KeyCode, crossterm::event::KeyModifiers)>, pub render_notify: Arc, pub render_dirty: Arc, pub(crate) full_redraw_pending: bool, pub(crate) overlay_panes: HashMap, pub(crate) local_terminal_notifications: bool, } pub(crate) enum LoopEvent { Timer, Internal(AppEvent), Api(crate::api::ApiRequestMessage), RawInput(crate::raw_input::RawInputEvent), InputClosed, RenderRequested, } struct SyncOutputGuard; impl SyncOutputGuard { fn begin() -> io::Result { let mut stdout = io::stdout().lock(); stdout.write_all(b"\x1b[?2026h")?; stdout.flush()?; Ok(Self) } } impl Drop for SyncOutputGuard { fn drop(&mut self) { let mut stdout = io::stdout().lock(); let _ = stdout.write_all(b"\x1b[?2026l"); let _ = stdout.flush(); } } async fn recv_raw_input_or_pending( input_rx: Option<&mut mpsc::Receiver>, ) -> Option { match input_rx { Some(rx) => rx.recv().await, None => pending().await, } } async fn sleep_until_or_pending(deadline: Option) { match deadline { Some(deadline) => tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)).await, None => pending().await, } } fn repeat_key_identity( key: &crate::input::TerminalKey, ) -> (crossterm::event::KeyCode, crossterm::event::KeyModifiers) { (key.code, key.modifiers) } fn auto_updates_enabled(no_session: bool) -> bool { !no_session && !cfg!(debug_assertions) } fn agent_panel_scope_from_config( scope: crate::config::AgentPanelScopeConfig, ) -> state::AgentPanelScope { match scope { crate::config::AgentPanelScopeConfig::Current => state::AgentPanelScope::CurrentWorkspace, crate::config::AgentPanelScopeConfig::All => state::AgentPanelScope::AllWorkspaces, } } /// Resolve the palette from config: base theme + optional custom overrides. fn resolve_palette(config: &crate::config::Config) -> state::Palette { resolve_palette_with_legacy_accent(config, true) } fn resolve_palette_with_legacy_accent( config: &crate::config::Config, use_legacy_ui_accent: bool, ) -> state::Palette { // Start with the named theme (default: catppuccin) let base_name = config.theme.name.as_deref().unwrap_or("catppuccin"); let mut palette = state::Palette::from_name(base_name).unwrap_or_else(|| { tracing::warn!( theme = base_name, "unknown theme, falling back to catppuccin" ); state::Palette::catppuccin() }); // Apply custom overrides if present if let Some(custom) = &config.theme.custom { palette = palette.with_overrides(custom); } // Legacy: if ui.accent is set and no theme.custom.accent, use it for compat if use_legacy_ui_accent && config.ui.accent != "cyan" && config .theme .custom .as_ref() .and_then(|c| c.accent.as_ref()) .is_none() { palette.accent = crate::config::parse_color(&config.ui.accent); } palette } impl App { pub fn new( config: &Config, no_session: bool, config_diagnostic: Option, api_rx: tokio::sync::mpsc::UnboundedReceiver, event_hub: crate::api::EventHub, ) -> Self { let (prefix_code, prefix_mods) = config.prefix_key(); crate::kitty_graphics::set_enabled(config.experimental.kitty_graphics); let (event_tx, event_rx) = mpsc::channel::(64); let render_notify = Arc::new(Notify::new()); let render_dirty = Arc::new(AtomicBool::new(false)); // Try to restore previous session let mut restored_terminals = std::collections::HashMap::new(); let mut restored_terminal_runtimes = std::collections::HashMap::new(); let ( workspaces, active, selected, _restored_agent_panel_scope, sidebar_width, sidebar_width_source, sidebar_section_split, ) = if no_session { ( Vec::new(), None, 0, state::AgentPanelScope::CurrentWorkspace, config.ui.sidebar_width, state::SidebarWidthSource::ConfigDefault, 0.5_f32, ) } else if let Some(snap) = crate::persist::load() { let (ws, terminals, terminal_runtimes) = crate::persist::restore( &snap, 24, 80, config.advanced.scrollback_limit_bytes, &config.terminal.default_shell, event_tx.clone(), render_notify.clone(), render_dirty.clone(), ); restored_terminals = terminals; restored_terminal_runtimes = terminal_runtimes; if ws.is_empty() { crate::logging::session_restored(0, "empty"); ( Vec::new(), None, 0, snap.agent_panel_scope, snap.sidebar_width.unwrap_or(config.ui.sidebar_width), if snap.sidebar_width.is_some() { state::SidebarWidthSource::Persisted } else { state::SidebarWidthSource::ConfigDefault }, snap.sidebar_section_split.unwrap_or(0.5), ) } else { crate::logging::session_restored(ws.len(), "ok"); let active = snap.active.filter(|&i| i < ws.len()); let selected = snap.selected.min(ws.len().saturating_sub(1)); ( ws, active, selected, snap.agent_panel_scope, snap.sidebar_width.unwrap_or(config.ui.sidebar_width), if snap.sidebar_width.is_some() { state::SidebarWidthSource::Persisted } else { state::SidebarWidthSource::ConfigDefault }, snap.sidebar_section_split.unwrap_or(0.5), ) } } else { ( Vec::new(), None, 0, state::AgentPanelScope::CurrentWorkspace, config.ui.sidebar_width, state::SidebarWidthSource::ConfigDefault, 0.5_f32, ) }; let agent_panel_scope = agent_panel_scope_from_config(config.ui.agent_panel_scope); // Validate sidebar bounds before they reach any `u16::clamp(min, max)` // call: `clamp` panics when `min > max`. On bad config, fall back to // the built-in defaults rather than crashing on the first render. let (sidebar_min_width, sidebar_max_width) = crate::config::validated_sidebar_bounds( config.ui.sidebar_min_width, config.ui.sidebar_max_width, ) .unwrap_or_else(|| { tracing::warn!( min = config.ui.sidebar_min_width, max = config.ui.sidebar_max_width, "ui.sidebar_min_width is greater than sidebar_max_width; falling back to default bounds (18, 36)" ); (18, 36) }); info!( pane_scrollback_limit_bytes = config.advanced.scrollback_limit_bytes, "using pane scrollback configuration" ); let latest_release_notes = crate::release_notes::load_latest(); let update_available = latest_release_notes .as_ref() .filter(|notes| notes.preview) .map(|notes| notes.version.clone()); let latest_release_notes_available = latest_release_notes.is_some(); let update_install_command = crate::update::update_install_command().to_string(); let startup_product_announcement = crate::product_announcements::load_unseen_for_current_version(); let mode = if config.should_show_onboarding() { state::Mode::Onboarding } else if startup_product_announcement.is_some() { state::Mode::ProductAnnouncement } else if active.is_some() { state::Mode::Terminal } else { state::Mode::Navigate }; let mut state = AppState { terminals: std::collections::HashMap::new(), terminal_runtimes: std::collections::HashMap::new(), direct_attach_resize_locks: std::collections::HashSet::new(), workspaces, active, selected, mode, should_quit: false, quit_detaches: !no_session, detach_requested: false, request_new_workspace: false, request_new_tab: false, request_reload_config: false, request_client_sound_config_reload: false, request_clipboard_write: None, creating_new_tab: false, requested_new_tab_name: None, rename_pane_target: None, request_complete_onboarding: false, name_input: String::new(), name_input_replace_on_type: false, release_notes: None, product_announcement: startup_product_announcement.map(|announcement| { state::ProductAnnouncementState { version: announcement.version, id: announcement.id, title: announcement.title, body: announcement.body, scroll: 0, preview: announcement.preview, } }), keybind_help: state::KeybindHelpState { scroll: 0 }, workspace_scroll: 0, agent_panel_scroll: 0, tab_scroll: 0, tab_scroll_follow_active: true, mobile_switcher_scroll: 0, view: state::ViewState { layout: state::ViewLayout::Desktop, sidebar_rect: Rect::default(), workspace_card_areas: Vec::new(), tab_bar_rect: Rect::default(), tab_hit_areas: Vec::new(), tab_scroll_left_hit_area: Rect::default(), tab_scroll_right_hit_area: Rect::default(), new_tab_hit_area: Rect::default(), terminal_area: Rect::default(), mobile_header_rect: Rect::default(), mobile_menu_hit_area: Rect::default(), toast_hit_area: Rect::default(), pane_infos: Vec::new(), split_borders: Vec::new(), }, drag: None, workspace_press: None, tab_press: None, selection: None, selection_autoscroll: None, context_menu: None, update_available, update_install_command, latest_release_notes_available, update_dismissed: false, config_diagnostic, toast: None, outer_terminal_focus: None, prefix_code, prefix_mods, default_sidebar_width: config.ui.sidebar_width, sidebar_width, sidebar_min_width, sidebar_max_width, sidebar_width_source, sidebar_width_auto: false, sidebar_collapsed: false, sidebar_section_split, agent_panel_scope, mouse_capture: config.ui.mouse_capture, confirm_close: config.ui.confirm_close, prompt_new_tab_name: config.ui.prompt_new_tab_name, show_agent_labels_on_pane_borders: config.ui.show_agent_labels_on_pane_borders, kitty_graphics_enabled: config.experimental.kitty_graphics, default_shell: config.terminal.default_shell.clone(), pane_scrollback_limit_bytes: config.advanced.scrollback_limit_bytes, accent: crate::config::parse_color(&config.ui.accent), sound: config.ui.sound.clone(), local_sound_playback: true, toast_config: config.ui.toast.clone(), keybinds: config.keybinds(), spinner_tick: 0, palette: resolve_palette(config), theme_name: config .theme .name .clone() .unwrap_or_else(|| "catppuccin".to_string()), settings: state::SettingsState { section: state::SettingsSection::Theme, list: state::SelectionListState::new(0), original_palette: None, original_theme: None, }, integration_recommendations: crate::integration::integration_recommendations(), integration_install_messages: Vec::new(), global_menu: state::MenuListState::new(0), host_terminal_theme: crate::terminal_theme::TerminalTheme::default(), session_dirty: false, }; state.terminals = restored_terminals; state.terminal_runtimes = restored_terminal_runtimes; for ws_idx in 0..state.workspaces.len() { let cwd = state.workspaces[ws_idx] .resolved_identity_cwd_from(&state.terminals, &state.terminal_runtimes); state.workspaces[ws_idx].cached_git_branch = cwd.as_deref().and_then(crate::workspace::git_branch); } // Background auto-update is disabled in monolithic no-session mode // and in debug/test builds so local development never mutates the // running binary out from under spawned test processes. if auto_updates_enabled(no_session) { let update_tx = event_tx.clone(); std::thread::spawn(move || crate::update::auto_update(update_tx)); } let last_focus = state.active.and_then(|idx| { state .workspaces .get(idx) .and_then(|ws| ws.focused_pane_id().map(|pane_id| (idx, pane_id))) }); Self { config_diagnostic_deadline: state .config_diagnostic .as_ref() .map(|_| Instant::now() + Duration::from_secs(8)), toast_deadline: None, state, event_tx, event_rx, last_git_remote_status_refresh: Instant::now() - GIT_REMOTE_STATUS_REFRESH_INTERVAL, git_refresh_in_flight: false, last_sidebar_divider_click: None, next_resize_poll: Instant::now() + RESIZE_POLL_INTERVAL, next_animation_tick: None, next_auto_update_check: auto_updates_enabled(no_session) .then_some(Instant::now() + AUTO_UPDATE_CHECK_INTERVAL), session_save_deadline: None, selection_autoscroll_deadline: None, last_render_at: None, suppressed_repeat_keys: HashSet::new(), api_rx, event_hub, last_focus, no_session, input_rx: None, last_terminal_size: terminal::size().ok(), render_notify, render_dirty, full_redraw_pending: false, overlay_panes: HashMap::new(), local_terminal_notifications: true, } } fn request_full_redraw(&mut self) { self.full_redraw_pending = true; } pub async fn run(&mut self, terminal: &mut DefaultTerminal) -> io::Result<()> { if self.input_rx.is_none() { self.input_rx = Some(crate::raw_input::spawn_input_reader()); } self.query_host_terminal_theme(); let mut needs_render = true; let mut host_mouse_capture_active = self.state.mouse_capture; while !self.state.should_quit { if self.render_dirty.load(Ordering::Acquire) { needs_render = true; } // Drain internal events first so API reads observe fresh pane state. if self.drain_internal_events() { needs_render = true; } if self.drain_api_requests() { needs_render = true; } self.sync_focus_events(); self.sync_session_save_schedule(); let now = Instant::now(); if self.handle_scheduled_tasks(now) { needs_render = true; } if self.state.request_complete_onboarding { self.state.request_complete_onboarding = false; self.open_settings_from_onboarding(); needs_render = true; } if self.state.request_new_workspace { self.state.request_new_workspace = false; self.create_workspace(); needs_render = true; } if self.state.request_new_tab { self.state.request_new_tab = false; self.create_tab(); needs_render = true; } if self.state.request_reload_config { self.state.request_reload_config = false; self.reload_config(); needs_render = true; } let now = Instant::now(); self.sync_animation_timer(now); self.sync_host_mouse_capture(&mut host_mouse_capture_active)?; if needs_render && self.can_render_now(now) { self.render_dirty.swap(false, Ordering::AcqRel); let _sync_output = SyncOutputGuard::begin()?; let kitty_graphics_enabled = self.state.kitty_graphics_enabled; if self.full_redraw_pending { if kitty_graphics_enabled { crate::kitty_graphics::clear_all_host_graphics()?; } terminal.clear()?; self.full_redraw_pending = false; } let mut cell_size = crate::kitty_graphics::HostCellSize::default(); terminal.draw(|frame| { let area = frame.area(); if kitty_graphics_enabled { cell_size = crate::kitty_graphics::HostCellSize::from_terminal(area); crate::ui::compute_view_with_cell_size(&mut self.state, area, cell_size); } else { crate::ui::compute_view(&mut self.state, area); } crate::ui::render(&self.state, frame); })?; if kitty_graphics_enabled { crate::kitty_graphics::paint_local_pane_graphics(&self.state, cell_size)?; } self.last_render_at = Some(now); needs_render = false; continue; } let next_deadline = self.next_loop_deadline(now, needs_render); let event = { let input_rx = self.input_rx.as_mut(); tokio::select! { maybe_api = self.api_rx.recv() => match maybe_api { Some(msg) => LoopEvent::Api(msg), None => LoopEvent::Timer, }, maybe_ev = self.event_rx.recv() => match maybe_ev { Some(ev) => LoopEvent::Internal(ev), None => LoopEvent::Timer, }, maybe_input = recv_raw_input_or_pending(input_rx) => match maybe_input { Some(input) => LoopEvent::RawInput(input), None => LoopEvent::InputClosed, }, _ = sleep_until_or_pending(next_deadline) => LoopEvent::Timer, _ = self.render_notify.notified() => LoopEvent::RenderRequested, } }; match event { LoopEvent::Timer => {} LoopEvent::Internal(ev) => { self.handle_internal_event(ev); needs_render = true; } LoopEvent::Api(msg) => { if self.handle_api_request_message(msg) { needs_render = true; } } LoopEvent::RawInput(input) => { if self.handle_raw_input_batch(input).await { needs_render = true; } } LoopEvent::InputClosed => { self.input_rx = None; } LoopEvent::RenderRequested => { if self.render_dirty.load(Ordering::Acquire) { needs_render = true; } } } } // Save session on exit (skip in --no-session mode) if !self.no_session { self.save_session_now(); } Ok(()) } fn sync_host_mouse_capture(&self, active: &mut bool) -> io::Result<()> { let desired = self.state.should_capture_host_mouse(); if desired == *active { return Ok(()); } if desired { execute!(io::stdout(), EnableMouseCapture)?; } else { execute!(io::stdout(), DisableMouseCapture)?; } *active = desired; Ok(()) } pub(crate) fn dismiss_release_notes(&mut self) { let preview = self .state .release_notes .as_ref() .is_some_and(|notes| notes.preview); self.state.release_notes = None; if !preview { if let Err(err) = crate::release_notes::mark_current_version_seen() { self.state.config_diagnostic = Some(format!("failed to update release notes status: {err}")); self.config_diagnostic_deadline = Some(Instant::now() + Duration::from_secs(5)); } } if self.state.product_announcement.is_some() { self.state.mode = Mode::ProductAnnouncement; } else { self.state.mode = if self.state.active.is_some() { Mode::Terminal } else { Mode::Navigate }; } } pub(crate) fn dismiss_product_announcement(&mut self) { if let Some(announcement) = self.state.product_announcement.take() { if !announcement.preview { if let Err(err) = crate::product_announcements::mark_seen(&announcement.version, &announcement.id) { self.state.config_diagnostic = Some(format!("failed to update announcement status: {err}")); self.config_diagnostic_deadline = Some(Instant::now() + Duration::from_secs(5)); } } } self.state.mode = if self.state.active.is_some() { Mode::Terminal } else { Mode::Navigate }; } pub(crate) fn scroll_release_notes(&mut self, delta: i16) { let max_scroll = self.state.release_notes_max_scroll(); if let Some(notes) = &mut self.state.release_notes { notes.scroll = if delta.is_negative() { notes.scroll.saturating_sub(delta.unsigned_abs()) } else { notes.scroll.saturating_add(delta as u16) } .min(max_scroll); } } pub(crate) fn scroll_product_announcement(&mut self, delta: i16) { let max_scroll = self.state.product_announcement_max_scroll(); if let Some(announcement) = &mut self.state.product_announcement { announcement.scroll = if delta.is_negative() { announcement.scroll.saturating_sub(delta.unsigned_abs()) } else { announcement.scroll.saturating_add(delta as u16) } .min(max_scroll); } } pub(crate) fn open_settings_from_onboarding(&mut self) { self.mark_onboarding_complete(); self.refresh_integration_recommendations(); crate::app::input::open_settings_at(&mut self.state, state::SettingsSection::Integrations); } pub(crate) fn refresh_integration_recommendations(&mut self) { self.state.integration_recommendations = crate::integration::integration_recommendations(); } pub(crate) fn install_recommended_integrations(&mut self) { let targets = self .state .integration_recommendations .iter() .filter(|recommendation| recommendation.needs_install()) .map(|recommendation| recommendation.target) .collect::>(); self.state.integration_install_messages.clear(); if targets.is_empty() { self.state .integration_install_messages .push("all detected integrations are current".to_string()); return; } for target in targets { let label = crate::integration::integration_target_label(target); match crate::integration::install_target(target) { Ok(_) => self .state .integration_install_messages .push(format!("installed {label}")), Err(err) => self .state .integration_install_messages .push(format!("{label}: {err}")), } } self.state.integration_recommendations = crate::integration::integration_recommendations(); self.state.mark_session_dirty(); } pub(crate) fn reload_config(&mut self) -> crate::config::ConfigReloadReport { self.apply_config_from_disk(true) } pub(crate) fn apply_config_from_disk( &mut self, notify_success: bool, ) -> crate::config::ConfigReloadReport { let previous_toast = self.state.toast.clone(); let report = match crate::config::load_live_config() { Ok(loaded) => self.apply_live_config( &loaded.config, &loaded.diagnostics, &loaded.invalid_sections, notify_success, ), Err(diagnostics) => { self.state.toast = None; self.state.config_diagnostic = crate::config::config_diagnostic_summary(&diagnostics); self.config_diagnostic_deadline = Some(Instant::now() + Duration::from_secs(8)); crate::config::ConfigReloadReport { status: crate::config::ConfigReloadStatus::Failed, diagnostics, } } }; self.sync_toast_deadline(previous_toast); report } fn apply_live_config( &mut self, config: &crate::config::Config, load_diagnostics: &[String], invalid_sections: &[String], notify_success: bool, ) -> crate::config::ConfigReloadReport { let mut diagnostics = load_diagnostics.to_vec(); let invalid_section = |section: &str| invalid_sections.iter().any(|invalid| invalid == section); if !invalid_section("keys") { match config.live_keybinds() { Ok(live) => { self.state.prefix_code = live.prefix.0; self.state.prefix_mods = live.prefix.1; self.state.keybinds = live.keybinds; } Err(keybind_diagnostics) => { let mut message = keybind_diagnostics.join("; "); if !message.contains("keeping current keybinds") { message.push_str("; keeping current keybinds"); } diagnostics.push(message); } } } if !invalid_section("ui") { // Validate sidebar bounds before they reach any `u16::clamp` call. // On `min > max`, treat the entire `[ui]` section as invalid: keep // the previous settings and skip the section so the re-clamp below // — and every subsequent render/drag — can never panic. if crate::config::validated_sidebar_bounds( config.ui.sidebar_min_width, config.ui.sidebar_max_width, ) .is_none() { diagnostics.push(format!( "ui.sidebar_min_width ({}) is greater than sidebar_max_width ({}); keeping previous [ui] settings", config.ui.sidebar_min_width, config.ui.sidebar_max_width, )); } else { diagnostics.extend(config.ui.sound.diagnostics()); self.state.default_sidebar_width = config.ui.sidebar_width; if self.state.sidebar_width_source == state::SidebarWidthSource::ConfigDefault { self.state.sidebar_width = config.ui.sidebar_width; } self.state.sidebar_min_width = config.ui.sidebar_min_width; self.state.sidebar_max_width = config.ui.sidebar_max_width; // Re-clamp the live width to the new bounds. No source guard — bounds // always apply, including to widths owned by Persisted or Manual. self.state.sidebar_width = self .state .sidebar_width .clamp(self.state.sidebar_min_width, self.state.sidebar_max_width); self.state.mouse_capture = config.ui.mouse_capture; self.state.confirm_close = config.ui.confirm_close; self.state.prompt_new_tab_name = config.ui.prompt_new_tab_name; self.state.show_agent_labels_on_pane_borders = config.ui.show_agent_labels_on_pane_borders; self.state.agent_panel_scope = agent_panel_scope_from_config(config.ui.agent_panel_scope); self.state.agent_panel_scroll = 0; self.state.accent = crate::config::parse_color(&config.ui.accent); if !self.state.local_sound_playback && self.state.sound != config.ui.sound { self.state.request_client_sound_config_reload = true; } self.state.sound = config.ui.sound.clone(); self.state.toast_config = config.ui.toast.clone(); } } if !invalid_section("experimental") { let was_kitty_graphics_enabled = self.state.kitty_graphics_enabled; self.state.kitty_graphics_enabled = config.experimental.kitty_graphics; crate::kitty_graphics::set_enabled(config.experimental.kitty_graphics); if was_kitty_graphics_enabled && !config.experimental.kitty_graphics { let _ = crate::kitty_graphics::clear_all_host_graphics(); } } if !invalid_section("advanced") { self.state.pane_scrollback_limit_bytes = config.advanced.scrollback_limit_bytes; } if !invalid_section("terminal") { self.state.default_shell = config.terminal.default_shell.clone(); } if !invalid_section("theme") { self.state.palette = resolve_palette_with_legacy_accent(config, !invalid_section("ui")); self.state.theme_name = config .theme .name .clone() .unwrap_or_else(|| "catppuccin".to_string()); } let status = if diagnostics.is_empty() { crate::config::ConfigReloadStatus::Applied } else { crate::config::ConfigReloadStatus::Partial }; if diagnostics.is_empty() { self.state.config_diagnostic = None; self.config_diagnostic_deadline = None; if notify_success { self.state.toast = Some(crate::app::state::ToastNotification { kind: crate::app::state::ToastKind::UpdateInstalled, title: "reloaded config".to_string(), context: "using config.toml".to_string(), target: None, }); } } else { self.state.config_diagnostic = crate::config::config_diagnostic_summary(&diagnostics); self.config_diagnostic_deadline = Some(Instant::now() + Duration::from_secs(8)); if notify_success { self.state.toast = Some(crate::app::state::ToastNotification { kind: crate::app::state::ToastKind::UpdateInstalled, title: "reloaded config".to_string(), context: "with warnings".to_string(), target: None, }); } } crate::config::ConfigReloadReport { status, diagnostics, } } } // --------------------------------------------------------------------------- // Input routing for headless server mode // --------------------------------------------------------------------------- impl App { /// Routes raw input bytes from a client through the existing input pipeline. /// /// The input bytes are parsed into `RawInputEvent`s and then processed. /// In terminal mode, keys are routed through the same semantic /// key-handling path as monolithic herdr so they are re-encoded for the /// focused pane's negotiated keyboard protocol instead of passing host /// terminal escape sequences through unchanged. #[cfg(test)] pub(crate) fn route_client_input(&mut self, data: Vec) { let events = crate::raw_input::parse_raw_input_bytes_sync(&data); self.route_client_events(events, true); } pub(crate) fn route_client_events( &mut self, events: Vec, apply_host_terminal_theme: bool, ) { for event in events { match event { crate::raw_input::RawInputEvent::Key(key) => { let key_id = repeat_key_identity(&key); match key.kind { crossterm::event::KeyEventKind::Press => { if self.state.mode == Mode::Terminal { self.suppressed_repeat_keys.remove(&key_id); self.handle_terminal_key_headless(key); } else { self.suppressed_repeat_keys.insert(key_id); self.handle_non_terminal_key(key); } } crossterm::event::KeyEventKind::Repeat => { if self.state.mode == Mode::Terminal && !self.suppressed_repeat_keys.contains(&key_id) { self.handle_terminal_key_headless(key); } // Repeats in non-terminal modes are ignored // (same as monolithic behavior). } crossterm::event::KeyEventKind::Release => { self.suppressed_repeat_keys.remove(&key_id); } } } crate::raw_input::RawInputEvent::Mouse(mouse) => { if self.state.mouse_capture { self.handle_mouse_event_headless(mouse); } else { self.state.handle_pane_mouse_only(mouse); } } crate::raw_input::RawInputEvent::Paste(text) => { if self.state.mode == Mode::Terminal { if let Some(ws_idx) = self.state.active { if let Some(ws) = self.state.workspaces.get(ws_idx) { if let Some(focused) = ws.focused_pane_id() { if let Some(runtime) = self.state.runtime_for_pane_in_workspace(ws_idx, focused) { let _ = runtime.try_send_bytes(bytes::Bytes::from( if runtime .input_state() .map(|s| s.bracketed_paste) .unwrap_or(false) { format!("\x1b[200~{text}\x1b[201~") } else { text }, )); } } } } } } crate::raw_input::RawInputEvent::OuterFocusGained | crate::raw_input::RawInputEvent::OuterFocusLost => {} crate::raw_input::RawInputEvent::HostDefaultColor { kind, color } => { if apply_host_terminal_theme { self.update_host_terminal_theme(kind, color); } } crate::raw_input::RawInputEvent::Unsupported => {} } } } /// Handles a key event in non-terminal mode for the headless server. /// /// Uses the standalone handler functions that work on `&mut AppState` /// since the server doesn't have the async context of the monolithic App. fn handle_non_terminal_key(&mut self, key: crate::input::TerminalKey) { let key_event = key.as_key_event(); match self.state.mode { Mode::Navigate => { self.handle_navigate_key(key); } Mode::RenameWorkspace | Mode::RenameTab | Mode::RenamePane => { input::handle_rename_key(&mut self.state, key_event); } Mode::Resize => { input::handle_resize_key(&mut self.state, key_event); } Mode::ConfirmClose => { input::handle_confirm_close_key(&mut self.state, key_event); } Mode::ContextMenu => { input::handle_context_menu_key(&mut self.state, key_event); } Mode::KeybindHelp => { input::handle_keybind_help_key(&mut self.state, key_event); } Mode::GlobalMenu => { input::handle_global_menu_key(&mut self.state, key_event); } Mode::Onboarding => { self.handle_onboarding_key(key_event); } Mode::ReleaseNotes => { self.handle_release_notes_key(key_event); } Mode::ProductAnnouncement => { self.handle_product_announcement_key(key_event); } Mode::Settings => { self.handle_settings_key(key_event); } Mode::Terminal => { // Should not be called in terminal mode. } } } /// Handles a mouse event for the headless server. /// /// Delegates to the same mouse handling logic used in the monolithic /// mode (hit-testing against the rendered UI), which works because /// the server's AppState maintains view geometry from virtual rendering. fn handle_mouse_event_headless(&mut self, mouse: crossterm::event::MouseEvent) { self.handle_mouse(mouse); } } #[cfg(test)] mod tests { use super::*; use crate::config::Config; use crate::detect::{Agent, AgentState}; use crate::terminal::TerminalRuntime; use crate::workspace::Workspace; use crossterm::event::{KeyCode, KeyEventKind, KeyModifiers}; use std::sync::{Mutex, OnceLock}; fn raw_key( code: KeyCode, modifiers: KeyModifiers, kind: KeyEventKind, ) -> crate::raw_input::RawInputEvent { crate::raw_input::RawInputEvent::Key( crate::input::TerminalKey::new(code, modifiers).with_kind(kind), ) } fn release_notes_state() -> state::ReleaseNotesState { state::ReleaseNotesState { version: "0.1.0".into(), body: "notes".into(), scroll: 0, preview: true, } } fn test_app() -> App { let (_api_tx, api_rx) = tokio::sync::mpsc::unbounded_channel(); App::new( &Config::default(), true, None, api_rx, crate::api::EventHub::default(), ) } fn config_env_lock() -> &'static Mutex<()> { static LOCK: OnceLock> = OnceLock::new(); LOCK.get_or_init(|| Mutex::new(())) } fn temp_config_path(name: &str) -> std::path::PathBuf { let unique = format!( "herdr-{name}-{}-{}", std::process::id(), std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_nanos() ); std::env::temp_dir().join(unique).join("config.toml") } fn restore_xdg_state_home(original: Option) { if let Some(value) = original { std::env::set_var("XDG_STATE_HOME", value); } else { std::env::remove_var("XDG_STATE_HOME"); } } #[test] fn git_refresh_deadline_is_suppressed_while_in_flight() { let mut app = test_app(); app.state.workspaces.push(Workspace::test_new("one")); app.git_refresh_in_flight = true; assert_eq!(app.git_refresh_deadline(), None); } #[test] fn git_status_event_clears_in_flight_refresh() { let mut app = test_app(); app.git_refresh_in_flight = true; let previous_refresh = Instant::now() - Duration::from_secs(10); app.last_git_remote_status_refresh = previous_refresh; app.handle_internal_event(AppEvent::GitStatusRefreshed { results: Vec::new(), }); assert!(!app.git_refresh_in_flight); assert!(app.last_git_remote_status_refresh > previous_refresh); } #[test] fn git_status_event_marks_render_dirty_when_status_changes() { let mut app = test_app(); app.state.workspaces.push(Workspace::test_new("one")); app.render_dirty.store(false, Ordering::Release); let workspace_id = app.state.workspaces[0].id.clone(); let resolved_identity_cwd = app.state.workspaces[0].resolved_identity_cwd().unwrap(); app.handle_internal_event(AppEvent::GitStatusRefreshed { results: vec![crate::workspace::WorkspaceGitStatus { workspace_id, resolved_identity_cwd, branch: Some("render-dirty-test".into()), ahead_behind: Some((1, 0)), }], }); assert!(app.render_dirty.load(Ordering::Acquire)); } #[test] fn startup_uses_configured_agent_panel_scope() { let mut config = Config::default(); config.ui.agent_panel_scope = crate::config::AgentPanelScopeConfig::Current; let (_api_tx, api_rx) = tokio::sync::mpsc::unbounded_channel(); let app = App::new(&config, true, None, api_rx, crate::api::EventHub::default()); assert_eq!( app.state.agent_panel_scope, state::AgentPanelScope::CurrentWorkspace ); } #[test] fn startup_restores_preview_update_available_from_saved_notes() { let _guard = config_env_lock().lock().unwrap(); let path = temp_config_path("startup-preview-update-available"); std::env::set_var(crate::config::CONFIG_PATH_ENV_VAR, &path); // Use a bogus far-future version so preview=true regardless of current binary version. crate::release_notes::save_pending("99.99.99", "### Changed\n- One").unwrap(); let app = test_app(); assert_eq!(app.state.update_available.as_deref(), Some("99.99.99")); assert!(app.state.latest_release_notes_available); std::env::remove_var(crate::config::CONFIG_PATH_ENV_VAR); let _ = std::fs::remove_dir_all(path.parent().unwrap()); } #[test] fn startup_does_not_restore_update_available_from_older_saved_notes() { let _guard = config_env_lock().lock().unwrap(); let path = temp_config_path("startup-stale-update-notes"); std::env::set_var(crate::config::CONFIG_PATH_ENV_VAR, &path); crate::release_notes::save_pending("0.4.9", "### Changed\n- One").unwrap(); let app = test_app(); assert_eq!(app.state.update_available, None); assert!(app.state.latest_release_notes_available); std::env::remove_var(crate::config::CONFIG_PATH_ENV_VAR); let _ = std::fs::remove_dir_all(path.parent().unwrap()); } #[test] fn startup_keeps_pending_release_notes_available_without_auto_opening() { let _guard = config_env_lock().lock().unwrap(); let path = temp_config_path("startup-pending-release-notes-no-auto-open"); std::env::set_var(crate::config::CONFIG_PATH_ENV_VAR, &path); crate::release_notes::save_pending(env!("CARGO_PKG_VERSION"), "### Changed\n- One") .unwrap(); let config = Config { onboarding: Some(false), ..Default::default() }; let (_api_tx, api_rx) = tokio::sync::mpsc::unbounded_channel(); let app = App::new(&config, true, None, api_rx, crate::api::EventHub::default()); assert_eq!(app.state.mode, Mode::Navigate); assert!(app.state.release_notes.is_none()); assert!(app.state.latest_release_notes_available); std::env::remove_var(crate::config::CONFIG_PATH_ENV_VAR); let _ = std::fs::remove_dir_all(path.parent().unwrap()); } #[test] fn startup_still_auto_opens_unseen_product_announcement() { let _guard = config_env_lock().lock().unwrap(); let path = temp_config_path("startup-product-announcement-auto-open"); let state_home = path.parent().unwrap().join("state"); let original_xdg_state_home = std::env::var_os("XDG_STATE_HOME"); std::env::set_var(crate::config::CONFIG_PATH_ENV_VAR, &path); std::env::set_var("XDG_STATE_HOME", &state_home); crate::release_notes::save_pending(env!("CARGO_PKG_VERSION"), "### Changed\n- One") .unwrap(); crate::product_announcements::save_manifest_announcement( env!("CARGO_PKG_VERSION"), Some(&crate::product_announcements::ManifestAnnouncement { id: "startup-announcement".into(), title: Some("Startup announcement".into()), body: "### Announcement\n- One".into(), }), ) .unwrap(); let config = Config { onboarding: Some(false), ..Default::default() }; let (_api_tx, api_rx) = tokio::sync::mpsc::unbounded_channel(); let app = App::new(&config, true, None, api_rx, crate::api::EventHub::default()); assert_eq!(app.state.mode, Mode::ProductAnnouncement); assert_eq!( app.state .product_announcement .as_ref() .map(|announcement| announcement.id.as_str()), Some("startup-announcement") ); assert!(app.state.release_notes.is_none()); std::env::remove_var(crate::config::CONFIG_PATH_ENV_VAR); restore_xdg_state_home(original_xdg_state_home); let _ = std::fs::remove_dir_all(path.parent().unwrap()); } #[test] fn reload_config_updates_live_state() { let _guard = config_env_lock().lock().unwrap(); let path = temp_config_path("reload-config-success"); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write( &path, "[terminal]\ndefault_shell = \"nu\"\n[keys]\nnew_workspace = \"g\"\nprefix = \"ctrl+a\"\n[ui]\nagent_panel_scope = \"current\"\n[ui.toast]\ndelivery = \"herdr\"\n", ) .unwrap(); std::env::set_var(crate::config::CONFIG_PATH_ENV_VAR, &path); let mut app = test_app(); let report = app.reload_config(); assert_eq!(report.status, crate::config::ConfigReloadStatus::Applied); assert_eq!(app.state.prefix_code, KeyCode::Char('a')); assert_eq!(app.state.prefix_mods, KeyModifiers::CONTROL); assert_eq!( app.state.keybinds.new_workspace, (KeyCode::Char('g'), KeyModifiers::empty()) ); assert_eq!( app.state.toast_config.delivery, crate::config::ToastDelivery::Herdr ); assert_eq!( app.state.agent_panel_scope, state::AgentPanelScope::CurrentWorkspace ); assert_eq!(app.state.default_shell, "nu"); assert!(app.state.config_diagnostic.is_none()); let toast = app.state.toast.as_ref().unwrap(); assert_eq!(toast.kind, crate::app::state::ToastKind::UpdateInstalled); assert_eq!(toast.title, "reloaded config"); assert_eq!(toast.context, "using config.toml"); std::env::remove_var(crate::config::CONFIG_PATH_ENV_VAR); let _ = std::fs::remove_dir_all(path.parent().unwrap()); } #[test] fn reload_config_updates_sidebar_width_only_when_config_owned() { let _guard = config_env_lock().lock().unwrap(); let path = temp_config_path("reload-config-sidebar-width"); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::env::set_var(crate::config::CONFIG_PATH_ENV_VAR, &path); let mut app = test_app(); assert_eq!( app.state.sidebar_width_source, state::SidebarWidthSource::ConfigDefault ); std::fs::write(&path, "[ui]\nsidebar_width = 34\n").unwrap(); let report = app.reload_config(); assert_eq!(report.status, crate::config::ConfigReloadStatus::Applied); assert_eq!(app.state.default_sidebar_width, 34); assert_eq!(app.state.sidebar_width, 34); app.state.sidebar_width = 31; app.state.sidebar_width_source = state::SidebarWidthSource::Manual; std::fs::write(&path, "[ui]\nsidebar_width = 35\n").unwrap(); let report = app.reload_config(); assert_eq!(report.status, crate::config::ConfigReloadStatus::Applied); assert_eq!(app.state.default_sidebar_width, 35); assert_eq!(app.state.sidebar_width, 31); std::env::remove_var(crate::config::CONFIG_PATH_ENV_VAR); let _ = std::fs::remove_dir_all(path.parent().unwrap()); } #[test] fn reload_config_updates_sidebar_bounds_and_reclamps() { let _guard = config_env_lock().lock().unwrap(); let path = temp_config_path("reload-config-sidebar-bounds"); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::env::set_var(crate::config::CONFIG_PATH_ENV_VAR, &path); let mut app = test_app(); // Default bounds. assert_eq!(app.state.sidebar_min_width, 18); assert_eq!(app.state.sidebar_max_width, 36); // Manually set a width and flip the source so the existing // sidebar_width-only-when-config-owned guard does NOT update it. app.state.sidebar_width = 30; app.state.sidebar_width_source = state::SidebarWidthSource::Manual; // Tightening max below the current width must re-clamp the live width // even when source is Manual — bounds always apply. std::fs::write(&path, "[ui]\nsidebar_max_width = 24\n").unwrap(); let report = app.reload_config(); assert_eq!(report.status, crate::config::ConfigReloadStatus::Applied); assert_eq!(app.state.sidebar_max_width, 24); assert_eq!( app.state.sidebar_width, 24, "manual width must re-clamp to new max" ); // Loosening max leaves the live width alone (it's already within bounds). app.state.sidebar_width = 24; std::fs::write(&path, "[ui]\nsidebar_max_width = 60\n").unwrap(); let report = app.reload_config(); assert_eq!(report.status, crate::config::ConfigReloadStatus::Applied); assert_eq!(app.state.sidebar_max_width, 60); assert_eq!(app.state.sidebar_width, 24); // Raising min above the current width re-clamps upward. std::fs::write(&path, "[ui]\nsidebar_min_width = 30\n").unwrap(); let report = app.reload_config(); assert_eq!(report.status, crate::config::ConfigReloadStatus::Applied); assert_eq!(app.state.sidebar_min_width, 30); assert_eq!( app.state.sidebar_width, 30, "manual width must re-clamp up to new min" ); std::env::remove_var(crate::config::CONFIG_PATH_ENV_VAR); let _ = std::fs::remove_dir_all(path.parent().unwrap()); } #[test] fn app_new_falls_back_to_default_bounds_on_inverted_config() { let mut config = Config::default(); config.ui.sidebar_min_width = 50; config.ui.sidebar_max_width = 30; let (_api_tx, api_rx) = tokio::sync::mpsc::unbounded_channel(); let app = App::new(&config, true, None, api_rx, crate::api::EventHub::default()); assert_eq!( app.state.sidebar_min_width, 18, "App::new must fall back to default min when bounds are inverted" ); assert_eq!( app.state.sidebar_max_width, 36, "App::new must fall back to default max when bounds are inverted" ); } #[test] fn reload_config_invalid_sidebar_bounds_keeps_previous_ui_and_returns_partial() { let _guard = config_env_lock().lock().unwrap(); let path = temp_config_path("reload-config-invalid-sidebar-bounds"); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::env::set_var(crate::config::CONFIG_PATH_ENV_VAR, &path); let mut app = test_app(); let original_min = app.state.sidebar_min_width; let original_max = app.state.sidebar_max_width; let original_mouse_capture = app.state.mouse_capture; // Pair the bad bounds with another `[ui]` field change to confirm the // entire section is treated as invalid (not just the bounds). let target_mouse_capture = !original_mouse_capture; std::fs::write( &path, format!( "[ui]\nsidebar_min_width = 50\nsidebar_max_width = 30\nmouse_capture = {}\n", target_mouse_capture ), ) .unwrap(); let report = app.reload_config(); assert_eq!(report.status, crate::config::ConfigReloadStatus::Partial); assert_eq!(app.state.sidebar_min_width, original_min); assert_eq!(app.state.sidebar_max_width, original_max); assert_eq!( app.state.mouse_capture, original_mouse_capture, "[ui] is treated as invalid on bad bounds; mouse_capture must not apply" ); assert!(app .state .config_diagnostic .as_deref() .is_some_and(|message| { message.contains("sidebar_min_width") && message.contains("sidebar_max_width") && message.contains("greater") })); std::env::remove_var(crate::config::CONFIG_PATH_ENV_VAR); let _ = std::fs::remove_dir_all(path.parent().unwrap()); } #[test] fn reload_config_keeps_current_keybinds_on_invalid_binding_but_applies_other_sections() { let _guard = config_env_lock().lock().unwrap(); let path = temp_config_path("reload-config-invalid-keybind"); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write( &path, "[keys]\nnew_workspace = \"wat\"\n[ui.toast]\ndelivery = \"terminal\"\n", ) .unwrap(); std::env::set_var(crate::config::CONFIG_PATH_ENV_VAR, &path); let mut app = test_app(); let original_prefix = (app.state.prefix_code, app.state.prefix_mods); let original_keybinds = app.state.keybinds.new_workspace; let report = app.reload_config(); assert_eq!(report.status, crate::config::ConfigReloadStatus::Partial); assert_eq!( (app.state.prefix_code, app.state.prefix_mods), original_prefix ); assert_eq!(app.state.keybinds.new_workspace, original_keybinds); assert_eq!( app.state.toast_config.delivery, crate::config::ToastDelivery::Terminal ); assert!(app .state .config_diagnostic .as_deref() .is_some_and(|message| { message.contains("keys.new_workspace") && message.contains("keeping current keybinds") })); std::env::remove_var(crate::config::CONFIG_PATH_ENV_VAR); let _ = std::fs::remove_dir_all(path.parent().unwrap()); } #[test] fn reload_config_preserves_invalid_ui_section_but_applies_valid_keys() { let _guard = config_env_lock().lock().unwrap(); let path = temp_config_path("reload-config-invalid-ui-section"); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write( &path, "[keys]\nnew_workspace = \"g\"\n[ui.toast]\ndelivery = \"desktop\"\n", ) .unwrap(); std::env::set_var(crate::config::CONFIG_PATH_ENV_VAR, &path); let mut app = test_app(); app.state.toast_config.delivery = crate::config::ToastDelivery::Herdr; let report = app.reload_config(); assert_eq!(report.status, crate::config::ConfigReloadStatus::Partial); assert_eq!( app.state.keybinds.new_workspace, (KeyCode::Char('g'), KeyModifiers::empty()) ); assert_eq!( app.state.toast_config.delivery, crate::config::ToastDelivery::Herdr ); assert!(app .state .config_diagnostic .as_deref() .is_some_and(|message| message.contains("invalid ui config"))); std::env::remove_var(crate::config::CONFIG_PATH_ENV_VAR); let _ = std::fs::remove_dir_all(path.parent().unwrap()); } #[test] fn settings_save_toast_delivery_persists_then_applies_live_config() { let _guard = config_env_lock().lock().unwrap(); let path = temp_config_path("settings-save-toast-delivery"); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(&path, "onboarding = false\n").unwrap(); std::env::set_var(crate::config::CONFIG_PATH_ENV_VAR, &path); let mut app = test_app(); assert_eq!( app.state.toast_config.delivery, crate::config::ToastDelivery::Off ); app.save_toast_delivery(crate::config::ToastDelivery::Terminal); assert_eq!( app.state.toast_config.delivery, crate::config::ToastDelivery::Terminal ); let content = std::fs::read_to_string(&path).unwrap(); assert!(content.contains("delivery = \"terminal\"")); assert!(app.state.config_diagnostic.is_none()); std::env::remove_var(crate::config::CONFIG_PATH_ENV_VAR); let _ = std::fs::remove_dir_all(path.parent().unwrap()); } #[test] fn save_agent_panel_scope_persists_then_applies_live_config() { let _guard = config_env_lock().lock().unwrap(); let path = temp_config_path("save-agent-panel-scope"); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(&path, "onboarding = false\n").unwrap(); std::env::set_var(crate::config::CONFIG_PATH_ENV_VAR, &path); let mut app = test_app(); assert_eq!( app.state.agent_panel_scope, state::AgentPanelScope::AllWorkspaces ); app.save_agent_panel_scope(state::AgentPanelScope::CurrentWorkspace); assert_eq!( app.state.agent_panel_scope, state::AgentPanelScope::CurrentWorkspace ); let content = std::fs::read_to_string(&path).unwrap(); assert!(content.contains("agent_panel_scope = \"current\"")); assert!(app.state.config_diagnostic.is_none()); std::env::remove_var(crate::config::CONFIG_PATH_ENV_VAR); let _ = std::fs::remove_dir_all(path.parent().unwrap()); } #[test] fn reload_config_keeps_current_state_on_invalid_toml() { let _guard = config_env_lock().lock().unwrap(); let path = temp_config_path("reload-config-invalid-toml"); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(&path, "[keys\nnew_workspace = \"g\"\n").unwrap(); std::env::set_var(crate::config::CONFIG_PATH_ENV_VAR, &path); let mut app = test_app(); let original_prefix = (app.state.prefix_code, app.state.prefix_mods); let original_keybinds = app.state.keybinds.new_workspace; let original_toast_delivery = app.state.toast_config.delivery; let report = app.reload_config(); assert_eq!(report.status, crate::config::ConfigReloadStatus::Failed); assert_eq!( (app.state.prefix_code, app.state.prefix_mods), original_prefix ); assert_eq!(app.state.keybinds.new_workspace, original_keybinds); assert_eq!(app.state.toast_config.delivery, original_toast_delivery); assert!(app .state .config_diagnostic .as_deref() .is_some_and(|message| { message.contains("config parse error") && message.contains("keeping current config") })); assert!(app.state.toast.is_none()); std::env::remove_var(crate::config::CONFIG_PATH_ENV_VAR); let _ = std::fs::remove_dir_all(path.parent().unwrap()); } #[tokio::test] async fn raw_input_waits_when_reader_is_gone() { let result = tokio::time::timeout(Duration::from_millis(20), recv_raw_input_or_pending(None)).await; assert!(result.is_err()); } #[tokio::test] async fn terminal_mode_handles_repeat_key_events() { let mut app = test_app(); app.state.workspaces = vec![Workspace::test_new("test")]; app.state.active = Some(0); app.state.selected = 0; app.state.mode = Mode::Terminal; let handled = app .handle_raw_input_event(raw_key( KeyCode::Backspace, KeyModifiers::empty(), KeyEventKind::Repeat, )) .await; assert!(handled); } #[tokio::test] async fn outer_focus_gained_marks_visible_done_panes_seen() { let mut app = test_app(); let mut workspace = Workspace::test_new("test"); let root_pane = workspace.tabs[0].root_pane; let split_pane = workspace.test_split(ratatui::layout::Direction::Horizontal); let background_tab = workspace.test_add_tab(Some("background")); let background_pane = workspace.tabs[background_tab].root_pane; app.state.workspaces = vec![workspace]; app.state.ensure_test_terminals(); let root_terminal_id = app.state.workspaces[0].tabs[0].panes[&root_pane] .attached_terminal_id .clone(); app.state .terminals .get_mut(&root_terminal_id) .unwrap() .state = AgentState::Idle; app.state.workspaces[0].tabs[0] .panes .get_mut(&root_pane) .unwrap() .seen = false; let split_terminal_id = app.state.workspaces[0].tabs[0].panes[&split_pane] .attached_terminal_id .clone(); app.state .terminals .get_mut(&split_terminal_id) .unwrap() .state = AgentState::Idle; app.state.workspaces[0].tabs[0] .panes .get_mut(&split_pane) .unwrap() .seen = false; let bg_terminal_id = app.state.workspaces[0].tabs[background_tab].panes[&background_pane] .attached_terminal_id .clone(); app.state.terminals.get_mut(&bg_terminal_id).unwrap().state = AgentState::Idle; app.state.workspaces[0].tabs[background_tab] .panes .get_mut(&background_pane) .unwrap() .seen = false; app.state.active = Some(0); app.state.selected = 0; app.state.mode = Mode::Terminal; app.state.outer_terminal_focus = Some(false); let handled = app .handle_raw_input_event(crate::raw_input::RawInputEvent::OuterFocusGained) .await; assert!(handled); assert_eq!(app.state.outer_terminal_focus, Some(true)); assert!(app.state.workspaces[0].tabs[0].panes[&root_pane].seen); assert!(app.state.workspaces[0].tabs[0].panes[&split_pane].seen); assert!(!app.state.workspaces[0].tabs[background_tab].panes[&background_pane].seen); } #[tokio::test] async fn repeat_key_events_are_ignored_outside_terminal_mode() { let mut app = test_app(); app.state.mode = Mode::ReleaseNotes; app.state.release_notes = Some(release_notes_state()); let handled = app .handle_raw_input_event(raw_key( KeyCode::Enter, KeyModifiers::empty(), KeyEventKind::Repeat, )) .await; assert!(!handled); assert_eq!(app.state.mode, Mode::ReleaseNotes); assert!(app.state.release_notes.is_some()); } #[tokio::test] async fn modal_press_does_not_leak_repeat_into_terminal_mode() { let mut app = test_app(); app.state.workspaces = vec![Workspace::test_new("test")]; app.state.active = Some(0); app.state.selected = 0; app.state.mode = Mode::ReleaseNotes; app.state.release_notes = Some(release_notes_state()); let press_handled = app .handle_raw_input_event(raw_key( KeyCode::Enter, KeyModifiers::empty(), KeyEventKind::Press, )) .await; let repeat_handled = app .handle_raw_input_event(raw_key( KeyCode::Enter, KeyModifiers::empty(), KeyEventKind::Repeat, )) .await; let release_handled = app .handle_raw_input_event(raw_key( KeyCode::Enter, KeyModifiers::empty(), KeyEventKind::Release, )) .await; let next_press_handled = app .handle_raw_input_event(raw_key( KeyCode::Enter, KeyModifiers::empty(), KeyEventKind::Press, )) .await; assert!(press_handled); assert_eq!(app.state.mode, Mode::Terminal); assert!(!repeat_handled); assert!(!release_handled); assert!(next_press_handled); } #[test] fn read_only_api_requests_do_not_force_rerender() { let read_only = crate::api::schema::Request { id: "req_1".into(), method: crate::api::schema::Method::WorkspaceList( crate::api::schema::EmptyParams::default(), ), }; let mutating = crate::api::schema::Request { id: "req_2".into(), method: crate::api::schema::Method::WorkspaceFocus( crate::api::schema::WorkspaceTarget { workspace_id: "w_1".into(), }, ), }; let pane_rename = crate::api::schema::Request { id: "req_3".into(), method: crate::api::schema::Method::PaneRename(crate::api::schema::PaneRenameParams { pane_id: "w_1-1".into(), label: Some("logs".into()), }), }; assert!(!crate::api::request_changes_ui(&read_only)); assert!(crate::api::request_changes_ui(&mutating)); assert!(crate::api::request_changes_ui(&pane_rename)); } #[test] fn workspace_create_response_includes_initial_tab_and_root_pane() { let mut app = test_app(); app.state.workspaces = vec![Workspace::test_new("api-root-pane")]; app.state.ensure_test_terminals(); app.state.active = Some(0); app.state.selected = 0; let crate::api::schema::ResponseResult::WorkspaceCreated { workspace, tab, root_pane, } = app.workspace_created_result(0).unwrap() else { panic!("expected workspace_created response"); }; assert_eq!(workspace.label, "api-root-pane"); assert_eq!(tab.workspace_id, workspace.workspace_id); assert_eq!(root_pane.workspace_id, workspace.workspace_id); assert_eq!(root_pane.tab_id, tab.tab_id); assert!(root_pane.terminal_id.starts_with("term_")); assert_ne!(root_pane.terminal_id, root_pane.pane_id); } #[test] fn tab_create_response_includes_root_pane() { let mut app = test_app(); let mut workspace = Workspace::test_new("api-tab-root-pane"); workspace.test_add_tab(None); app.state.workspaces = vec![workspace]; app.state.ensure_test_terminals(); app.state.active = Some(0); app.state.selected = 0; let crate::api::schema::ResponseResult::TabCreated { tab, root_pane } = app.tab_created_result(0, 1).unwrap() else { panic!("expected tab_created response"); }; assert_eq!(tab.workspace_id, root_pane.workspace_id); assert_eq!(root_pane.tab_id, tab.tab_id); assert_eq!(tab.pane_count, 1); } #[test] fn workspace_creation_in_navigate_mode_uses_selected_workspace_seed_cwd() { let mut app = test_app(); let mut first = Workspace::test_new("herdr"); first.identity_cwd = std::path::PathBuf::from("/tmp/herdr"); let mut second = Workspace::test_new("pion"); second.identity_cwd = std::path::PathBuf::from("/tmp/pion"); app.state.workspaces = vec![first, second]; app.state.active = Some(0); app.state.selected = 1; app.state.mode = Mode::Navigate; let ws_idx = app.workspace_creation_source().unwrap(); let seed_cwd = app.seed_cwd_from_workspace(ws_idx).unwrap(); assert_eq!(ws_idx, 1); assert_eq!(seed_cwd, std::path::PathBuf::from("/tmp/pion")); } #[test] fn server_stop_request_sets_should_quit_flag() { let mut app = test_app(); let response = app.handle_api_request(crate::api::schema::Request { id: "req_server_stop".into(), method: crate::api::schema::Method::ServerStop( crate::api::schema::EmptyParams::default(), ), }); let response: serde_json::Value = serde_json::from_str(&response).unwrap(); assert_eq!(response["result"]["type"], "ok"); assert!(app.state.should_quit); } #[test] fn pane_rename_request_sets_and_clears_manual_label() { let mut app = test_app(); let workspace = Workspace::test_new("api-pane-rename"); let pane = workspace.tabs[0].root_pane; app.state.workspaces = vec![workspace]; app.state.ensure_test_terminals(); app.state.active = Some(0); app.state.selected = 0; let pane_id = app.pane_info(0, pane).unwrap().pane_id; let response = app.handle_api_request(crate::api::schema::Request { id: "req_pane_rename".into(), method: crate::api::schema::Method::PaneRename(crate::api::schema::PaneRenameParams { pane_id: pane_id.clone(), label: Some("reviewer".into()), }), }); let response: serde_json::Value = serde_json::from_str(&response).unwrap(); assert_eq!(response["result"]["type"], "pane_info"); assert_eq!(response["result"]["pane"]["label"], "reviewer"); let terminal_id = app.state.workspaces[0] .pane_state(pane) .unwrap() .attached_terminal_id .clone(); assert_eq!( app.state .terminals .get(&terminal_id) .unwrap() .manual_label .as_deref(), Some("reviewer") ); let response = app.handle_api_request(crate::api::schema::Request { id: "req_pane_rename_clear".into(), method: crate::api::schema::Method::PaneRename(crate::api::schema::PaneRenameParams { pane_id, label: None, }), }); let response: serde_json::Value = serde_json::from_str(&response).unwrap(); assert_eq!(response["result"]["type"], "pane_info"); assert!(response["result"]["pane"].get("label").is_none()); assert!(app .state .terminals .get(&terminal_id) .unwrap() .manual_label .is_none()); } #[test] fn terminal_target_resolves_terminal_id() { let mut app = test_app(); let workspace = Workspace::test_new("terminal-target-id"); let pane = workspace.tabs[0].root_pane; let terminal_id = workspace.terminal_id(pane).unwrap().to_string(); app.state.workspaces = vec![workspace]; app.state.active = Some(0); app.state.selected = 0; let resolved = app.resolve_terminal_target(&terminal_id).unwrap(); assert_eq!(resolved.ws_idx, 0); assert_eq!(resolved.pane_id, pane); assert_eq!(resolved.terminal_id, terminal_id); } #[test] fn terminal_target_resolves_legacy_pane_id() { let mut app = test_app(); let workspace = Workspace::test_new("terminal-target-pane"); let pane = workspace.tabs[0].root_pane; let terminal_id = workspace.terminal_id(pane).unwrap().to_string(); app.state.workspaces = vec![workspace]; app.state.active = Some(0); app.state.selected = 0; let pane_id = app.public_pane_id(0, pane).unwrap(); let resolved = app.resolve_terminal_target(&pane_id).unwrap(); assert_eq!(resolved.pane_id, pane); assert_eq!(resolved.terminal_id, terminal_id); } #[test] fn terminal_target_resolves_unique_agent_name() { let mut app = test_app(); let workspace = Workspace::test_new("terminal-target-name"); let pane = workspace.tabs[0].root_pane; let terminal_id = workspace.terminal_id(pane).unwrap().to_string(); app.state.workspaces = vec![workspace]; app.state.ensure_test_terminals(); let attached_terminal_id = app.state.workspaces[0] .pane_state(pane) .unwrap() .attached_terminal_id .clone(); app.state .terminals .get_mut(&attached_terminal_id) .unwrap() .set_agent_name("reviewer".into()); app.state.active = Some(0); app.state.selected = 0; let resolved = app.resolve_terminal_target("reviewer").unwrap(); assert_eq!(resolved.pane_id, pane); assert_eq!(resolved.terminal_id, terminal_id); } #[test] fn terminal_target_reports_missing_target() { let mut app = test_app(); app.state.workspaces = vec![Workspace::test_new("terminal-target-missing")]; app.state.active = Some(0); app.state.selected = 0; let err = app.resolve_terminal_target("missing-agent").unwrap_err(); assert_eq!( err, crate::app::terminal_targets::TerminalTargetError::NotFound { target: "missing-agent".into() } ); } #[test] fn terminal_target_reports_ambiguous_duplicate_agent_name() { let mut app = test_app(); let mut workspace = Workspace::test_new("terminal-target-ambiguous"); let first = workspace.tabs[0].root_pane; let second = workspace.test_split(ratatui::layout::Direction::Horizontal); app.state.workspaces = vec![workspace]; app.state.ensure_test_terminals(); let first_terminal_id = app.state.workspaces[0] .pane_state(first) .unwrap() .attached_terminal_id .clone(); app.state .terminals .get_mut(&first_terminal_id) .unwrap() .set_agent_name("worker".into()); let second_terminal_id = app.state.workspaces[0] .pane_state(second) .unwrap() .attached_terminal_id .clone(); app.state .terminals .get_mut(&second_terminal_id) .unwrap() .set_agent_name("worker".into()); app.state.active = Some(0); app.state.selected = 0; let err = app.resolve_terminal_target("worker").unwrap_err(); let crate::app::terminal_targets::TerminalTargetError::Ambiguous { target, candidates } = err else { panic!("expected ambiguous terminal target"); }; assert_eq!(target, "worker"); assert_eq!(candidates.len(), 2); assert!(candidates.iter().all(|candidate| { candidate.terminal_id.starts_with("term_") && candidate.pane_id.starts_with(&app.state.workspaces[0].id) && candidate.workspace_id == app.state.workspaces[0].id && candidate.cwd.is_some() })); } #[tokio::test] async fn pane_split_request_targets_pane_in_background_tab() { let _guard = config_env_lock().lock().unwrap(); let original_shell = std::env::var_os("SHELL"); std::env::set_var("SHELL", "/usr/bin/true"); let mut app = test_app(); let mut workspace = Workspace::test_new("api-pane-split-background-tab"); let active_pane = workspace.tabs[0].root_pane; let background_tab = workspace.test_add_tab(Some("worker")); let target_pane = workspace.tabs[background_tab].root_pane; workspace.switch_tab(background_tab); let background_previous_focus = workspace.test_split(ratatui::layout::Direction::Horizontal); workspace.switch_tab(0); app.state.workspaces = vec![workspace]; app.state.ensure_test_terminals(); let split_cwd = std::env::temp_dir(); let target_terminal_id = app.state.workspaces[0] .pane_state(target_pane) .unwrap() .attached_terminal_id .clone(); app.state .terminals .get_mut(&target_terminal_id) .unwrap() .cwd = split_cwd.clone(); app.state.active = Some(0); app.state.selected = 0; let target_pane_id = app.pane_info(0, target_pane).unwrap().pane_id; let target_tab_id = app.public_tab_id(0, background_tab).unwrap(); let response = app.handle_api_request(crate::api::schema::Request { id: "req_pane_split_background_tab".into(), method: crate::api::schema::Method::PaneSplit(crate::api::schema::PaneSplitParams { workspace_id: None, target_pane_id, direction: crate::api::schema::SplitDirection::Right, cwd: None, focus: false, }), }); let response: serde_json::Value = serde_json::from_str(&response).unwrap(); assert_eq!(response["result"]["type"], "pane_info"); assert_eq!(response["result"]["pane"]["tab_id"], target_tab_id); assert_eq!( response["result"]["pane"]["cwd"], split_cwd.display().to_string() ); assert_eq!(response["result"]["pane"]["focused"], false); assert_eq!(app.state.active, Some(0)); assert_eq!(app.state.workspaces[0].active_tab, 0); assert_eq!( app.state.workspaces[0].tabs[0].layout.focused(), active_pane ); assert_eq!(app.state.workspaces[0].tabs[0].layout.pane_count(), 1); assert_eq!( app.state.workspaces[0].tabs[background_tab] .layout .focused(), background_previous_focus ); assert_eq!( app.state.workspaces[0].tabs[background_tab] .layout .pane_count(), 3 ); let runtimes: Vec<_> = app.state.terminal_runtimes.drain().collect(); for (_terminal_id, runtime) in runtimes { runtime.shutdown(); } match original_shell { Some(value) => std::env::set_var("SHELL", value), None => std::env::remove_var("SHELL"), } } #[tokio::test] async fn pane_split_request_focuses_new_pane_when_requested() { let _guard = config_env_lock().lock().unwrap(); let original_shell = std::env::var_os("SHELL"); std::env::set_var("SHELL", "/usr/bin/true"); let mut app = test_app(); let mut workspace = Workspace::test_new("api-pane-split-focus-background-tab"); let background_tab = workspace.test_add_tab(Some("worker")); workspace.switch_tab(0); app.state.workspaces = vec![workspace]; app.state.ensure_test_terminals(); app.state.active = Some(0); app.state.selected = 0; let target_pane = app.state.workspaces[0].tabs[background_tab].root_pane; let target_pane_id = app.pane_info(0, target_pane).unwrap().pane_id; let target_tab_id = app.public_tab_id(0, background_tab).unwrap(); let response = app.handle_api_request(crate::api::schema::Request { id: "req_pane_split_focus_background_tab".into(), method: crate::api::schema::Method::PaneSplit(crate::api::schema::PaneSplitParams { workspace_id: None, target_pane_id, direction: crate::api::schema::SplitDirection::Right, cwd: None, focus: true, }), }); let response: serde_json::Value = serde_json::from_str(&response).unwrap(); assert_eq!(response["result"]["type"], "pane_info"); assert_eq!(response["result"]["pane"]["tab_id"], target_tab_id); assert_eq!(response["result"]["pane"]["focused"], true); assert_eq!(app.state.active, Some(0)); assert_eq!(app.state.workspaces[0].active_tab, background_tab); let runtimes: Vec<_> = app.state.terminal_runtimes.drain().collect(); for (_terminal_id, runtime) in runtimes { runtime.shutdown(); } match original_shell { Some(value) => std::env::set_var("SHELL", value), None => std::env::remove_var("SHELL"), } } #[test] fn pane_close_request_closes_only_the_target_tab_when_other_tabs_exist() { let mut app = test_app(); let mut workspace = Workspace::test_new("api-pane-close"); let second_tab = workspace.test_add_tab(Some("logs")); workspace.switch_tab(second_tab); app.state.workspaces = vec![workspace]; app.state.ensure_test_terminals(); app.state.active = Some(0); app.state.selected = 0; let target_pane = app.state.workspaces[0].tabs[second_tab].root_pane; let target_pane_id = app.pane_info(0, target_pane).unwrap().pane_id; let response = app.handle_api_request(crate::api::schema::Request { id: "req_pane_close".into(), method: crate::api::schema::Method::PaneClose(crate::api::schema::PaneTarget { pane_id: target_pane_id, }), }); let response: serde_json::Value = serde_json::from_str(&response).unwrap(); assert_eq!(response["result"]["type"], "ok"); assert_eq!(app.state.workspaces.len(), 1); assert_eq!(app.state.workspaces[0].tabs.len(), 1); assert_eq!(app.state.workspaces[0].display_name(), "api-pane-close"); } #[test] fn pane_close_request_closes_workspace_when_it_removes_the_last_pane() { let mut app = test_app(); let workspace = Workspace::test_new("api-pane-close-last"); app.state.workspaces = vec![workspace]; app.state.ensure_test_terminals(); app.state.active = Some(0); app.state.selected = 0; let target_pane = app.state.workspaces[0].tabs[0].root_pane; let target_pane_id = app.pane_info(0, target_pane).unwrap().pane_id; let response = app.handle_api_request(crate::api::schema::Request { id: "req_pane_close_last".into(), method: crate::api::schema::Method::PaneClose(crate::api::schema::PaneTarget { pane_id: target_pane_id, }), }); let response: serde_json::Value = serde_json::from_str(&response).unwrap(); assert_eq!(response["result"]["type"], "ok"); assert!(app.state.workspaces.is_empty()); } #[test] fn session_dirty_flag_schedules_debounced_save() { let mut app = test_app(); app.no_session = false; app.state.session_dirty = true; app.sync_session_save_schedule(); assert!(!app.state.session_dirty); assert!(app.session_save_deadline.is_some()); } #[test] fn next_loop_deadline_includes_session_save_deadline() { let mut app = test_app(); let now = Instant::now(); app.session_save_deadline = Some(now + Duration::from_secs(2)); app.next_resize_poll = now + Duration::from_secs(5); app.next_auto_update_check = Some(now + Duration::from_secs(6)); assert_eq!( app.next_loop_deadline(now, false), app.session_save_deadline ); } #[test] fn headless_next_loop_deadline_ignores_resize_poll() { let mut app = test_app(); let now = Instant::now(); app.next_resize_poll = now + Duration::from_millis(100); app.session_save_deadline = Some(now + Duration::from_secs(2)); app.next_auto_update_check = Some(now + Duration::from_secs(6)); assert_eq!( app.next_headless_loop_deadline(now, false), app.session_save_deadline ); } #[test] fn headless_next_loop_deadline_returns_none_when_resize_poll_is_only_deadline() { let mut app = test_app(); let now = Instant::now(); app.next_resize_poll = now - Duration::from_millis(1); app.config_diagnostic_deadline = None; app.toast_deadline = None; app.next_animation_tick = None; app.next_auto_update_check = None; app.session_save_deadline = None; app.state.workspaces.clear(); assert_eq!(app.next_headless_loop_deadline(now, false), None); } #[test] fn due_session_save_deadline_is_cleared() { let mut app = test_app(); app.session_save_deadline = Some(Instant::now() - Duration::from_secs(1)); app.handle_scheduled_tasks(Instant::now()); assert!(app.session_save_deadline.is_none()); } #[test] fn next_loop_deadline_includes_selection_autoscroll_deadline() { let mut app = test_app(); let now = Instant::now(); app.selection_autoscroll_deadline = Some(now + Duration::from_millis(5)); app.next_animation_tick = Some(now + Duration::from_millis(100)); app.session_save_deadline = Some(now + Duration::from_millis(200)); assert_eq!( app.next_loop_deadline(now, false), app.selection_autoscroll_deadline ); } #[test] fn tick_selection_autoscroll_self_heals_when_state_cleared() { let mut app = test_app(); let now = Instant::now(); app.state.selection_autoscroll = None; app.selection_autoscroll_deadline = Some(now); app.tick_selection_autoscroll(now); assert!(app.selection_autoscroll_deadline.is_none()); } #[test] fn tick_selection_autoscroll_stops_on_rect_change() { let mut app = test_app(); let now = Instant::now(); let ws = Workspace::test_new("test"); let pane_id = ws.tabs[0].root_pane; app.state.workspaces.push(ws); app.state.active = Some(0); app.state.selection = Some(crate::selection::Selection::anchor(pane_id, 0, 0, None)); // Set autoscroll with a stale inner_rect that doesn't match pane_infos app.state.selection_autoscroll = Some(state::SelectionAutoscroll { direction: state::SelectionAutoscrollDirection::Down, last_mouse_screen_col: 0, last_mouse_screen_row: 999, inner_rect: ratatui::layout::Rect::new(0, 0, 1, 1), // wrong rect }); app.selection_autoscroll_deadline = Some(now); app.tick_selection_autoscroll(now); assert!(app.state.selection_autoscroll.is_none()); assert!(app.selection_autoscroll_deadline.is_none()); } #[tokio::test] async fn full_internal_event_queue_eventually_applies_working_to_idle_transition() { let mut app = test_app(); let ws = Workspace::test_new("test"); let pane_id = ws.tabs[0].root_pane; app.state.workspaces = vec![ws]; app.state.ensure_test_terminals(); app.state.active = Some(0); app.state.selected = 0; app.state.mode = Mode::Terminal; let terminal_id = app.state.workspaces[0] .pane_state(pane_id) .unwrap() .attached_terminal_id .clone(); app.handle_internal_event(AppEvent::StateChanged { pane_id, agent: Some(Agent::Pi), state: AgentState::Working, }); assert_eq!( app.state.terminals.get(&terminal_id).unwrap().state, AgentState::Working ); for i in 0..64 { app.event_tx .try_send(AppEvent::UpdateReady { version: format!("9.9.{i}"), install_command: "herdr update".into(), }) .unwrap(); } let tx = app.event_tx.clone(); let send = tx.send(AppEvent::StateChanged { pane_id, agent: Some(Agent::Pi), state: AgentState::Idle, }); tokio::pin!(send); let blocked = tokio::time::timeout(Duration::from_millis(20), async { (&mut send).await }).await; assert!( blocked.is_err(), "state change sender should wait for queue space instead of failing" ); app.drain_internal_events(); tokio::time::timeout(Duration::from_millis(50), async { (&mut send).await }) .await .expect("state change should enqueue once queue space is available") .expect("app event receiver should still be alive"); app.drain_internal_events(); assert_eq!( app.state.terminals.get(&terminal_id).unwrap().state, AgentState::Idle, "Working→Idle should still apply after temporary queue pressure" ); } #[test] fn route_client_input_dispatches_navigate_mode_keybinds() { let mut app = test_app(); app.state.workspaces = vec![Workspace::test_new("test")]; app.state.active = Some(0); app.state.selected = 0; // Start in navigate mode. app.state.mode = Mode::Navigate; // Send Ctrl+B then Esc (prefix → leave navigate mode). // Ctrl+B is 0x02 in raw terminal input. // After entering navigate mode and pressing Esc, we should leave navigate mode. let esc_bytes = vec![0x1b]; // Esc app.route_client_input(esc_bytes); // Esc in navigate mode should leave navigate mode. assert_eq!( app.state.mode, Mode::Terminal, "Esc should leave navigate mode and return to Terminal mode" ); } #[test] fn route_client_input_q_detaches_in_persistence_mode() { let mut app = test_app(); app.state.workspaces = vec![Workspace::test_new("test")]; app.state.active = Some(0); app.state.selected = 0; app.state.quit_detaches = true; // Start in navigate mode. app.state.mode = Mode::Navigate; assert!(!app.state.detach_requested); let q_bytes = b"q".to_vec(); app.route_client_input(q_bytes); assert!( app.state.detach_requested, "q should detach in persistence mode" ); assert_eq!( app.state.mode, Mode::Terminal, "q should leave navigate mode" ); } #[test] fn route_client_input_prefix_then_q_detaches_in_persistence_mode() { let mut app = test_app(); app.state.workspaces = vec![Workspace::test_new("test")]; app.state.active = Some(0); app.state.selected = 0; app.state.quit_detaches = true; // Start in terminal mode (default after workspace creation). app.state.mode = Mode::Terminal; assert!(!app.state.detach_requested); // Send Ctrl+B (prefix key, raw byte 0x02). let prefix_bytes = vec![0x02]; app.route_client_input(prefix_bytes); assert_eq!( app.state.mode, Mode::Navigate, "prefix key should enter navigate mode" ); assert!( !app.state.detach_requested, "prefix key should not set detach flag" ); let q_bytes = b"q".to_vec(); app.route_client_input(q_bytes); assert!( app.state.detach_requested, "q should detach in persistence mode" ); assert_eq!( app.state.mode, Mode::Terminal, "q should leave navigate mode" ); } #[tokio::test] async fn route_client_input_double_prefix_passes_prefix_through_to_focused_pane() { let mut app = test_app(); let mut workspace = Workspace::test_new("test"); let focused = workspace.focused_pane_id().unwrap(); let (runtime, mut rx) = TerminalRuntime::test_with_channel(80, 24); workspace.tabs[0].runtimes.insert(focused, runtime); app.state.workspaces = vec![workspace]; app.state.active = Some(0); app.state.selected = 0; app.state.mode = Mode::Terminal; app.state.prefix_code = KeyCode::Char('l'); app.state.prefix_mods = KeyModifiers::CONTROL; app.route_client_input(vec![0x0c]); assert_eq!(app.state.mode, Mode::Navigate); app.route_client_input(vec![0x0c]); assert_eq!(app.state.mode, Mode::Terminal); assert_eq!(rx.recv().await.unwrap(), bytes::Bytes::from(vec![0x0c])); } #[tokio::test] async fn route_client_input_reencodes_terminal_keys_for_focused_pane_protocol() { let mut app = test_app(); let mut workspace = Workspace::test_new("test"); let focused = workspace.focused_pane_id().unwrap(); let (runtime, mut rx) = TerminalRuntime::test_with_channel(80, 24); workspace.tabs[0].runtimes.insert(focused, runtime); app.state.workspaces = vec![workspace]; app.state.active = Some(0); app.state.selected = 0; app.state.mode = Mode::Terminal; // Ghostty/kitty-style Ctrl-C should be normalized back to the pane's // negotiated encoding instead of being forwarded verbatim. app.route_client_input(b"\x1b[99;5u".to_vec()); assert_eq!(rx.recv().await.unwrap(), bytes::Bytes::from(vec![3])); } #[tokio::test] async fn route_client_input_preserves_shift_enter_for_modify_other_keys_pane() { let mut app = test_app(); let mut workspace = Workspace::test_new("test"); let focused = workspace.focused_pane_id().unwrap(); let (runtime, mut rx) = TerminalRuntime::test_with_channel_and_scrollback_bytes(80, 24, 0, b"\x1b[>4;1m", 4); workspace.tabs[0].runtimes.insert(focused, runtime); app.state.workspaces = vec![workspace]; app.state.active = Some(0); app.state.selected = 0; app.state.mode = Mode::Terminal; app.route_client_input(b"\x1b[13;2u".to_vec()); assert_eq!( rx.recv().await.unwrap(), bytes::Bytes::from_static(b"\x1b[27;2;13~") ); } #[tokio::test] async fn route_client_input_splits_multi_event_payloads_before_forwarding() { let mut app = test_app(); let mut workspace = Workspace::test_new("test"); let focused = workspace.focused_pane_id().unwrap(); let (runtime, mut rx) = TerminalRuntime::test_with_channel(80, 24); workspace.tabs[0].runtimes.insert(focused, runtime); app.state.workspaces = vec![workspace]; app.state.active = Some(0); app.state.selected = 0; app.state.mode = Mode::Terminal; app.route_client_input(b"ab".to_vec()); assert_eq!(rx.recv().await.unwrap(), bytes::Bytes::from_static(b"a")); assert_eq!(rx.recv().await.unwrap(), bytes::Bytes::from_static(b"b")); assert!(rx.try_recv().is_err()); } #[tokio::test] async fn route_client_input_forwards_multilingual_ime_text_to_focused_pane() { let mut app = test_app(); let mut workspace = Workspace::test_new("test"); let focused = workspace.focused_pane_id().unwrap(); let text = "中日한🙂"; let (runtime, mut rx) = TerminalRuntime::test_with_channel_capacity(80, 24, text.chars().count()); workspace.tabs[0].runtimes.insert(focused, runtime); app.state.workspaces = vec![workspace]; app.state.active = Some(0); app.state.selected = 0; app.state.mode = Mode::Terminal; app.route_client_input(text.as_bytes().to_vec()); let mut forwarded = Vec::new(); for _ in text.chars() { let chunk = rx.recv().await.unwrap(); forwarded.extend_from_slice(&chunk); } assert_eq!(forwarded, text.as_bytes()); assert!(rx.try_recv().is_err()); } #[tokio::test] async fn route_client_input_forwards_long_voice_like_cjk_text_without_truncation() { let mut app = test_app(); let mut workspace = Workspace::test_new("test"); let focused = workspace.focused_pane_id().unwrap(); let text = "你好,今天我们测试一段比较长的语音输入。こんにちは。안녕하세요.🙂".repeat(64); let char_count = text.chars().count(); let (runtime, mut rx) = TerminalRuntime::test_with_channel_capacity(80, 24, char_count); workspace.tabs[0].runtimes.insert(focused, runtime); app.state.workspaces = vec![workspace]; app.state.active = Some(0); app.state.selected = 0; app.state.mode = Mode::Terminal; app.route_client_input(text.as_bytes().to_vec()); let mut forwarded = Vec::new(); for _ in 0..char_count { let chunk = rx.recv().await.unwrap(); forwarded.extend_from_slice(&chunk); } assert_eq!(forwarded, text.as_bytes()); assert!(rx.try_recv().is_err()); } #[test] fn route_client_input_handles_mouse_events() { let mut app = test_app(); app.state.workspaces = vec![Workspace::test_new("test")]; app.state.active = Some(0); app.state.selected = 0; // Send a mouse scroll-up event via SGR encoding. let mouse_bytes = b"\x1b[<64;10;5M".to_vec(); // This should not panic even though mouse handling is simplified // in headless mode. app.route_client_input(mouse_bytes); // No assertions on specific behavior — just no panic. } #[test] fn route_client_input_advances_onboarding_modal() { let mut app = test_app(); app.state.mode = Mode::Onboarding; app.route_client_input(b"\r".to_vec()); assert_eq!(app.state.mode, Mode::Settings); assert_eq!( app.state.settings.section, state::SettingsSection::Integrations ); } #[test] fn route_client_input_closes_release_notes_modal() { let mut app = test_app(); app.state.workspaces = vec![Workspace::test_new("test")]; app.state.active = Some(0); app.state.selected = 0; app.state.mode = Mode::ReleaseNotes; app.state.release_notes = Some(release_notes_state()); app.route_client_input(b"\x1b".to_vec()); assert_eq!(app.state.mode, Mode::Terminal); assert!(app.state.release_notes.is_none()); } #[test] fn route_client_input_closes_settings_modal() { let mut app = test_app(); app.state.workspaces = vec![Workspace::test_new("test")]; app.state.active = Some(0); app.state.selected = 0; app.state.mode = Mode::Settings; app.state.settings.original_theme = Some(app.state.theme_name.clone()); app.state.settings.original_palette = Some(app.state.palette.clone()); app.route_client_input(b"\x1b".to_vec()); assert_eq!(app.state.mode, Mode::Terminal); } #[test] fn route_client_input_updates_host_terminal_theme_from_osc_response() { let mut app = test_app(); app.route_client_input(b"\x1b]11;#123456\x07".to_vec()); assert_eq!( app.state.host_terminal_theme.background, Some(crate::terminal_theme::RgbColor { r: 0x12, g: 0x34, b: 0x56, }) ); } #[test] fn parse_raw_input_bytes_with_ranges_tracks_offsets() { // Verify that the range-aware parser correctly tracks byte offsets // for events within a multi-event input buffer. let input = b"\x1b[Aa".to_vec(); // Up arrow + 'a' let events = crate::raw_input::parse_raw_input_bytes_with_ranges(&input); assert_eq!(events.len(), 2, "should parse Up arrow and 'a'"); // Up arrow: \x1b[A = 3 bytes starting at offset 0 assert_eq!(events[0].start, 0); assert_eq!(events[0].len, 3); // 'a': 1 byte starting at offset 3 assert_eq!(events[1].start, 3); assert_eq!(events[1].len, 1); // Verify the raw bytes for each event are correct. assert_eq!( &input[events[0].start..events[0].start + events[0].len], b"\x1b[A" ); assert_eq!( &input[events[1].start..events[1].start + events[1].len], b"a" ); } }