Skip to main content

fresh/app/
editor_accessors.rs

1//! Plain accessor methods on `Editor`.
2//!
3//! Configuration getters, key-translator/time-source/event-broadcaster
4//! handles, LSP / completion / update query helpers, mode registry
5//! access, status/warning log setup, and the per-frame timer-check
6//! methods (mouse hover / semantic highlight / diagnostic pull /
7//! completion trigger).
8//!
9//! These are mostly small `&self` queries that read a single field;
10//! grouping them together keeps mod.rs focused on the central
11//! orchestration.
12
13use super::*;
14
15impl Editor {
16    /// Get a reference to the async bridge (if available)
17    pub fn async_bridge(&self) -> Option<&AsyncBridge> {
18        self.async_bridge.as_ref()
19    }
20
21    /// Get a reference to the config
22    pub fn config(&self) -> &Config {
23        &self.config
24    }
25
26    /// Get a mutable reference to the config.
27    ///
28    /// Routes through `Arc::make_mut`: if the plugin state snapshot (or any
29    /// other reader) still holds an `Arc` to the current value, this
30    /// CoW-clones so existing readers observe a stable value and the next
31    /// snapshot refresh sees a new pointer. `Arc<T>` has no `DerefMut`, so
32    /// the only way to mutate through `self.config` is via this accessor —
33    /// there is no code path that can silently leave a reader with stale
34    /// data.
35    ///
36    /// Window-side reads (`Window::config()`) read a *separate* Arc clone
37    /// stashed in `WindowResources`. Mutations through `config_mut`
38    /// therefore leave window clones stale until [`Editor::sync_windows_config`]
39    /// runs. Callers that mutate a config field which Window code reads
40    /// (e.g. `editor.line_wrap`, `editor.enable_inlay_hints`,
41    /// `languages`, etc.) must call `sync_windows_config()` afterwards.
42    /// `set_config` does this automatically.
43    pub fn config_mut(&mut self) -> &mut Config {
44        Arc::make_mut(&mut self.config)
45    }
46
47    /// Replace the config wholesale. Used by the "reload config" path and
48    /// by tests that want to swap in a freshly-parsed file. Constructs a
49    /// fresh `Arc`, so any snapshot that still holds the old value sees
50    /// the pointer move and will reserialize on the next refresh.
51    ///
52    /// Also propagates the new `Arc` to every window's
53    /// `resources.config`, so window-scoped reads see the swap.
54    pub fn set_config(&mut self, new_config: Config) {
55        self.config = Arc::new(new_config);
56        self.sync_windows_config();
57    }
58
59    /// Propagate `self.config` to every window's `resources.config` so
60    /// window-side reads (`Window::config()`) see the latest value.
61    /// `Arc::clone` is cheap, so this is a constant-time fanout per
62    /// window. Called from `set_config` and at the end of any
63    /// `config_mut()`-driven mutation that affects window-read fields.
64    pub(crate) fn sync_windows_config(&mut self) {
65        let cfg = self.config.clone();
66        for w in self.windows.values_mut() {
67            w.resources.config = cfg.clone();
68        }
69    }
70
71    /// Replace the cached raw user config. Like `set_config`, constructs
72    /// a fresh `Arc` so the plugin snapshot notices the change.
73    pub(crate) fn set_user_config_raw(&mut self, value: serde_json::Value) {
74        self.user_config_raw = Arc::new(value);
75    }
76
77    /// Mutable access to the active window's merged diagnostics map.
78    /// Routes through `Arc::make_mut`, which CoW-clones while the
79    /// plugin snapshot still holds the old map — readers never
80    /// observe an in-place mutation.
81    pub(crate) fn stored_diagnostics_mut(
82        &mut self,
83    ) -> &mut HashMap<String, Vec<lsp_types::Diagnostic>> {
84        Arc::make_mut(&mut self.active_window_mut().stored_diagnostics)
85    }
86
87    /// Mutable access to the active window's folding-ranges map.
88    /// Same `Arc::make_mut` CoW pattern as `stored_diagnostics_mut`.
89    pub(crate) fn stored_folding_ranges_mut(
90        &mut self,
91    ) -> &mut HashMap<String, Vec<lsp_types::FoldingRange>> {
92        Arc::make_mut(&mut self.active_window_mut().stored_folding_ranges)
93    }
94
95    /// Get a reference to the key translator (for input calibration)
96    pub fn key_translator(&self) -> &crate::input::key_translator::KeyTranslator {
97        &self.key_translator
98    }
99
100    /// Get a reference to the time source
101    pub fn time_source(&self) -> &SharedTimeSource {
102        &self.time_source
103    }
104
105    /// Emit a control event
106    pub fn emit_event(&self, name: impl Into<String>, data: serde_json::Value) {
107        self.event_broadcaster.emit_named(name, data);
108    }
109
110    /// Send a response to a plugin for an async operation
111    pub(super) fn send_plugin_response(&self, response: fresh_core::api::PluginResponse) {
112        self.plugin_manager
113            .read()
114            .unwrap()
115            .deliver_response(response);
116    }
117
118    // `take_pending_semantic_token_request` and
119    // `take_pending_semantic_token_range_request` live on `impl Window`
120    // — call them via `self.active_window_mut()`.
121
122    /// Get all keybindings as (key, action) pairs
123    pub fn get_all_keybindings(&self) -> Vec<(String, String)> {
124        self.keybindings.read().unwrap().get_all_bindings()
125    }
126
127    /// Get the formatted keybinding for a specific action (for display in messages)
128    /// Returns None if no keybinding is found for the action
129    pub fn get_keybinding_for_action(&self, action_name: &str) -> Option<String> {
130        self.keybindings
131            .read()
132            .unwrap()
133            .find_keybinding_for_action(action_name, self.active_window().key_context.clone())
134    }
135
136    /// Raw-event counterpart: return the `(KeyCode, KeyModifiers)` currently
137    /// bound to `action` in `context`. Intended for callers that need to
138    /// simulate the user pressing the bound key (e2e tests, some hotkey-
139    /// chaining code) without hardcoding a default that a user's rebind
140    /// would invalidate.
141    pub fn keybinding_event_for_action(
142        &self,
143        action: &crate::input::keybindings::Action,
144        context: crate::input::keybindings::KeyContext,
145    ) -> Option<(crossterm::event::KeyCode, crossterm::event::KeyModifiers)> {
146        self.keybindings
147            .read()
148            .unwrap()
149            .get_keybinding_event_for_action(action, context)
150    }
151
152    /// Get mutable access to the mode registry
153    pub fn mode_registry_mut(&mut self) -> &mut ModeRegistry {
154        &mut self.mode_registry
155    }
156
157    /// Get immutable access to the mode registry
158    pub fn mode_registry(&self) -> &ModeRegistry {
159        &self.mode_registry
160    }
161
162    /// Get the currently active buffer ID.
163    ///
164    /// This is derived from the split manager (single source of truth).
165    /// The editor always has at least one buffer, so this never fails.
166    ///
167    /// When the active split has a buffer-group tab as its active target
168    /// (i.e., `active_group_tab.is_some()`), this returns the buffer of the
169    /// currently-focused inner panel — so that input routing, command palette
170    /// context, buffer mode, and other "what is the user looking at" queries
171    /// resolve to the panel the user is actually interacting with rather than
172    /// the split's background leaf buffer.
173    ///
174    /// The override only takes effect if the inner panel's buffer is still
175    /// live in `self.buffers`; otherwise it falls back to the main split's
176    /// leaf buffer so callers never see a stale/freed buffer id.
177    #[inline]
178    pub fn active_buffer(&self) -> BufferId {
179        let (_, buf) = self.effective_active_pair();
180        buf
181    }
182
183    /// The split id whose `SplitViewState` owns the currently-focused
184    /// cursors/viewport/buffer state. For a regular split this is just
185    /// `split_manager.active_split()`. For a split that has a group tab
186    /// active, this returns the focused inner panel's leaf id (which
187    /// lives in `split_view_states` even though it's not in the main
188    /// split tree).
189    #[inline]
190    pub fn effective_active_split(&self) -> crate::model::event::LeafId {
191        let (split, _) = self.effective_active_pair();
192        split
193    }
194
195    /// Resolve the effective (split, buffer) pair for the currently-focused
196    /// target. This is the single source of truth — both `active_buffer` and
197    /// `effective_active_split` derive from it so they can never disagree.
198    ///
199    /// Returned invariant: `split_view_states[split]` exists, its
200    /// `active_buffer` equals the returned buffer id, `self.buffers`
201    /// contains the returned buffer id, and `split.keyed_states` contains
202    /// an entry for the returned buffer id. Consequently the mutation path
203    /// in `apply_event_to_active_buffer` (which indexes into
204    /// `keyed_states[buffer]`) is always well-defined for the returned pair.
205    ///
206    /// If a buffer-group panel is focused but any of the invariants above
207    /// is not satisfied for the inner leaf (for example because the panel
208    /// buffer was freed without clearing `focused_group_leaf`), the helper
209    /// falls back to the outer split's own leaf. The fallback is also
210    /// validated before being returned.
211    #[inline]
212    fn effective_active_pair(&self) -> (crate::model::event::LeafId, BufferId) {
213        self.active_window().effective_active_pair()
214    }
215
216    /// Get the mode name for the active buffer.
217    ///
218    /// Resolution order:
219    ///   1. The buffer's own virtual-buffer mode, if it has one.
220    ///   2. The mode declared by the buffer-group containing this
221    ///      buffer (e.g. a `git-log` group's keybindings apply to its
222    ///      panels regardless of whether each panel is a virtual
223    ///      buffer or a file-backed one — `openFileStreaming` produces
224    ///      the latter for streaming detail panels).
225    pub fn active_buffer_mode(&self) -> Option<&str> {
226        let buffer_id = self.active_buffer();
227        let win = self.active_window();
228        if let Some(mode) = win
229            .buffer_metadata
230            .get(&buffer_id)
231            .and_then(|meta| meta.virtual_mode())
232        {
233            return Some(mode);
234        }
235        let group_id = win.buffer_to_group.get(&buffer_id).copied()?;
236        win.buffer_groups.get(&group_id).map(|g| g.mode.as_str())
237    }
238
239    /// Check if the active buffer is read-only
240    pub fn is_active_buffer_read_only(&self) -> bool {
241        if let Some(metadata) = self
242            .active_window()
243            .buffer_metadata
244            .get(&self.active_buffer())
245        {
246            if metadata.read_only {
247                return true;
248            }
249            // Also check if the mode is read-only
250            if let Some(mode_name) = metadata.virtual_mode() {
251                return self.mode_registry.is_read_only(mode_name);
252            }
253        }
254        false
255    }
256
257    // `mark_buffer_read_only` lives on `impl Window` — call it via
258    // `self.active_window_mut().mark_buffer_read_only(buffer_id, ro)`.
259
260    /// Get the effective mode for the active buffer.
261    ///
262    /// Buffer-local mode (virtual buffers) takes precedence over the global
263    /// editor mode, so that e.g. a search-replace panel isn't hijacked by
264    /// a markdown-source or vi-mode global mode.
265    pub fn effective_mode(&self) -> Option<&str> {
266        // When a floating widget panel is mounted, its plugin-defined
267        // mode (`editor.setEditorMode(...)`) takes precedence over the
268        // underlying buffer's virtual mode. Without this, opening the
269        // Orchestrator picker from a python3 terminal session would
270        // resolve mode-keybindings against `"terminal"` instead of
271        // `"orchestrator-open"`, so picker-specific shortcuts like
272        // `Alt+N` never reached their handlers.
273        if self.floating_widget_panel.is_some() {
274            if let Some(mode) = self.active_window().editor_mode.as_deref() {
275                return Some(mode);
276            }
277        }
278        self.active_buffer_mode()
279            .or(self.active_window().editor_mode.as_deref())
280    }
281
282    // `has_active_lsp_progress`, `get_lsp_progress`, and
283    // `is_lsp_server_ready` live on `impl Window` — call them via
284    // `self.active_window().has_active_lsp_progress()` etc.
285
286    /// Read-only view of the editor-wide popup stack.
287    ///
288    /// `global_popups` itself is `pub(crate)` so its internals stay
289    /// private to the app module; tests need to inspect its depth /
290    /// contents to verify "no two popups stacked across the buffer-
291    /// local and global stacks" invariants (e.g. issue 1 of the LSP
292    /// indicator-click bugs), so we expose an immutable accessor here.
293    pub fn global_popups(&self) -> &crate::view::popup::PopupManager {
294        &self.global_popups
295    }
296
297    /// The earliest wall-clock deadline at which the main event loop
298    /// needs to wake up and re-render, *purely because of internal
299    /// time-driven UI elements* (animations, the LSP status-bar
300    /// spinner). Returns `None` when no time-driven UI is in flight —
301    /// the loop can sleep until the next user / async event without
302    /// missing a frame.
303    ///
304    /// The `Some` case includes the LSP-progress spinner: its glyph
305    /// is computed from `SystemTime::now() / 100ms`, so the loop has
306    /// to wake at ~100ms cadence to actually advance it. Without
307    /// this signal, the indicator would only tick when an unrelated
308    /// event caused a frame, and the user would see a "frozen"
309    /// spinner whenever the server stopped emitting `$/progress`
310    /// (e.g. died externally — see #1941 issue 3).
311    pub fn next_periodic_redraw_deadline(&self) -> Option<std::time::Instant> {
312        let lsp_progress_deadline = if self.active_window().has_active_lsp_progress() {
313            // 100ms matches the spinner-glyph period in
314            // `lsp_status::compose_lsp_status`.
315            Some(std::time::Instant::now() + std::time::Duration::from_millis(100))
316        } else {
317            None
318        };
319        let anim_deadline = self.active_window().animations.next_deadline();
320        // Paste-pending deadline: the editor tick falls back to the
321        // internal clipboard if the async arboard read doesn't return
322        // by this point. Including it here makes the main loop wake
323        // exactly when the timeout needs to fire, so a hung clipboard
324        // owner can't block the UI past `PASTE_ASYNC_DEADLINE`.
325        let paste_deadline = self.next_paste_deadline();
326        // Note: the terminal-title poll deadline is intentionally NOT folded
327        // in here. This deadline path caps the loop's wait to one frame
328        // (~16ms) for smooth animation, which would turn the ~1s title poll
329        // into a 60Hz busy loop. The loop's existing 50ms idle poll is fine
330        // granularity to notice `terminal_titles_need_poll` going true.
331        [lsp_progress_deadline, anim_deadline, paste_deadline]
332            .into_iter()
333            .flatten()
334            .min()
335    }
336
337    /// Earliest time a terminal tab needs its foreground-process title
338    /// re-polled, across all windows. `None` when no window has an
339    /// auto-named (non-explicit) terminal. Drives the event loop's periodic
340    /// wakeups so a tab reflects a command that starts or exits while the
341    /// UI is otherwise idle (the render that follows runs
342    /// `Window::sync_terminal_titles`).
343    pub fn terminal_title_poll_deadline(&self) -> Option<std::time::Instant> {
344        if !self.config.editor.terminal_auto_title {
345            return None;
346        }
347        let mut earliest: Option<std::time::Instant> = None;
348        for window in self.windows.values() {
349            let has_auto = window
350                .terminal_buffers
351                .keys()
352                .any(|b| !window.terminal_explicit_titles.contains(b));
353            if !has_auto {
354                continue;
355            }
356            let deadline = match window.terminal_fg_poll_at {
357                Some(last) => last + crate::app::terminal::FG_POLL_INTERVAL,
358                None => std::time::Instant::now(),
359            };
360            earliest = Some(earliest.map_or(deadline, |e| e.min(deadline)));
361        }
362        earliest
363    }
364
365    /// Whether a terminal tab is due for a foreground-process title poll
366    /// (its deadline has passed). The event loop ORs this into its
367    /// `needs_render` decision so the periodic wakeup actually paints a
368    /// frame, matching how animations and the LSP spinner are handled.
369    pub fn terminal_titles_need_poll(&self) -> bool {
370        self.terminal_title_poll_deadline()
371            .is_some_and(|d| d <= std::time::Instant::now())
372    }
373
374    /// Get stored LSP diagnostics (for testing and external access)
375    /// Returns a reference to the diagnostics map keyed by file URI
376    pub fn get_stored_diagnostics(&self) -> &HashMap<String, Vec<lsp_types::Diagnostic>> {
377        &self.active_window().stored_diagnostics
378    }
379
380    /// Check if an update is available
381    pub fn is_update_available(&self) -> bool {
382        self.update_checker
383            .as_ref()
384            .map(|c| c.is_update_available())
385            .unwrap_or(false)
386    }
387
388    /// Get the latest version string if an update is available
389    pub fn latest_version(&self) -> Option<&str> {
390        self.update_checker
391            .as_ref()
392            .and_then(|c| c.latest_version())
393    }
394
395    /// Get the cached release check result (for shutdown notification)
396    pub fn get_update_result(
397        &self,
398    ) -> Option<&crate::services::release_checker::ReleaseCheckResult> {
399        self.update_checker
400            .as_ref()
401            .and_then(|c| c.get_cached_result())
402    }
403
404    /// Set a custom update checker (for testing)
405    ///
406    /// This allows injecting a custom PeriodicUpdateChecker that points to a mock server,
407    /// enabling E2E tests for the update notification UI.
408    #[doc(hidden)]
409    pub fn set_update_checker(
410        &mut self,
411        checker: crate::services::release_checker::PeriodicUpdateChecker,
412    ) {
413        self.update_checker = Some(checker);
414    }
415
416    /// Configure LSP server for a specific language
417    pub fn set_lsp_config(&mut self, language: String, config: Vec<LspServerConfig>) {
418        let __active_id = self.active_window;
419        if let Some(lsp) = self.windows.get_mut(&__active_id).map(|w| &mut w.lsp) {
420            lsp.set_language_configs(language, config);
421        }
422    }
423
424    // `running_lsp_servers`, `pending_completion_requests_count`,
425    // `completion_items_count`, `initialized_lsp_server_count`, and
426    // `shutdown_lsp_server` live on `impl Window` — call them via
427    // `self.active_window()` / `self.active_window_mut()`.
428
429    /// Set up warning log monitoring
430    ///
431    /// When warnings/errors are logged, they will be written to the specified path
432    /// and the editor will be notified via the receiver.
433    pub fn set_warning_log(&mut self, receiver: std::sync::mpsc::Receiver<()>, path: PathBuf) {
434        self.warning_log = Some((receiver, path));
435    }
436
437    /// Take the warning-log receiver+path out of this editor.
438    ///
439    /// The receiver is single-consumer and lives for the process's
440    /// lifetime; on a destructive editor restart (e.g. authority swap)
441    /// `main.rs` lifts it from the old editor and re-installs it on the
442    /// new one so warnings keep flowing post-restart instead of vanishing
443    /// with the dropped editor.
444    pub fn take_warning_log(&mut self) -> Option<(std::sync::mpsc::Receiver<()>, PathBuf)> {
445        self.warning_log.take()
446    }
447
448    /// Set the status message log path
449    pub fn set_status_log_path(&mut self, path: PathBuf) {
450        self.status_log_path = Some(path);
451    }
452
453    /// Queue a new authority and restart the editor.
454    ///
455    /// Per the design decision in `docs/internal/AUTHORITY_DESIGN.md`,
456    /// authority transitions piggy-back on the existing
457    /// `change_working_dir` restart path. The caller never sees an
458    /// editor that is half-transitioned: the current `Editor` is
459    /// dropped, `main.rs` rebuilds a fresh one with the queued
460    /// authority, and session restore reopens buffers against the new
461    /// backend. This is slower than an in-place pointer swap but is
462    /// far more robust — every cached `Arc<dyn FileSystem>`, LSP
463    /// handle, terminal PTY, plugin state, and in-flight task is
464    /// dropped cleanly by the existing restart machinery.
465    pub fn install_authority(&mut self, authority: crate::services::authority::Authority) {
466        self.pending_authority = Some(authority);
467        // Re-open the same working directory; `main.rs` picks up the
468        // pending authority from the old editor just before dropping it.
469        self.request_restart(self.working_dir().to_path_buf());
470    }
471
472    /// Install a new authority that owns a live connection, parking its
473    /// keepalive bundle so the connection survives the restart.
474    ///
475    /// Remote-agent backends (SSH-style, K8s) hold carrier processes,
476    /// reconnect/heartbeat tasks, and a Tokio handle that must outlive
477    /// the `Editor` rebuild — exactly the role of the daemon's
478    /// `session_keepalive` slot. The restart loop pairs
479    /// `take_pending_authority` with `take_pending_keepalive` and moves
480    /// the bundle into the process-/server-level keepalive, dropping the
481    /// previous one (tearing down the prior connection). Opaque
482    /// `Box<dyn Any + Send>` so core/main need not name the backend.
483    pub fn install_authority_with_keepalive(
484        &mut self,
485        authority: crate::services::authority::Authority,
486        keepalive: Box<dyn std::any::Any + Send>,
487        working_dir: std::path::PathBuf,
488    ) {
489        // Unlike `install_authority` (which re-opens the *current* working
490        // dir), a remote-agent attach must re-root the editor at the pod-side
491        // workspace — otherwise the explorer, quick-open, and open-file all
492        // operate on the local host path, which doesn't exist in the pod.
493        self.pending_keepalive = Some(keepalive);
494        self.pending_authority = Some(authority);
495        self.request_restart(working_dir);
496    }
497
498    /// Restore the default local authority. Same destructive-restart
499    /// semantics as `install_authority` — the caller never observes a
500    /// half-transitioned editor.
501    pub fn clear_authority(&mut self) {
502        // Reuse the editor's live trust handle so the restored local authority
503        // is gated by the same workspace-trust state.
504        let trust = std::sync::Arc::clone(&self.authority.workspace_trust);
505        let env = std::sync::Arc::clone(&self.authority.env_provider);
506        self.install_authority(crate::services::authority::Authority::local(trust, env));
507    }
508
509    /// Take the queued authority (if any). Called by `main.rs` on
510    /// restart to move the queued authority into the fresh editor.
511    pub fn take_pending_authority(&mut self) -> Option<crate::services::authority::Authority> {
512        self.pending_authority.take()
513    }
514
515    /// Take the keepalive bundle queued alongside a pending authority by
516    /// [`Self::install_authority_with_keepalive`]. Called by the restart
517    /// loop right beside `take_pending_authority` so the new connection's
518    /// carrier/tasks are parked before the old `Editor` is dropped.
519    pub fn take_pending_keepalive(&mut self) -> Option<Box<dyn std::any::Any + Send>> {
520        self.pending_keepalive.take()
521    }
522
523    /// Directly replace the active authority without triggering a
524    /// restart. Intended for the post-construction wiring in `main.rs`
525    /// only, where the editor is still being set up and there is no
526    /// user-visible state to preserve. Do not call this from the event
527    /// loop — use `install_authority` for that.
528    ///
529    /// Also refreshes the plugin state snapshot so hooks that fire after
530    /// this call (notably `plugins_loaded`, fired by `main.rs` right
531    /// after `set_boot_authority`) see the real `authority_label` instead
532    /// of the empty string the temporary `Authority::local()` carried
533    /// during construction.
534    pub fn set_boot_authority(&mut self, authority: crate::services::authority::Authority) {
535        self.authority = authority;
536        // Propagate the new authority to every window's resources so
537        // window-side filesystem/path-translation reads (`Window::authority()`)
538        // see the swap. `Authority` carries internal `Arc`s, so this just
539        // clones cheap handles.
540        let auth = self.authority.clone();
541        for w in self.windows.values_mut() {
542            w.resources.authority = auth.clone();
543        }
544        // Propagate the authority's long-running spawner into the LSP
545        // manager so `force_spawn` can route server processes through
546        // the right backend. The editor rebuilds on every authority
547        // transition (AUTHORITY_DESIGN.md principle 7), so this is the
548        // single wiring point — no need for a hot-swap API. Path
549        // translation rides along for the same reason — LSP URIs need
550        // to be host↔container-translated under the new authority.
551        let __active_id = self.active_window;
552        if let Some(lsp) = self.windows.get_mut(&__active_id).map(|w| &mut w.lsp) {
553            lsp.set_long_running_spawner(self.authority.long_running_spawner.clone());
554            lsp.set_path_translation(self.authority.path_translation.clone());
555            lsp.set_workspace_trust(self.authority.workspace_trust.clone());
556        }
557        // Re-point quick-open's file provider at the new backend. The provider
558        // captured the *previous* authority's filesystem + spawner; without
559        // this, quick-open's `git ls-files` keeps listing the old backend's
560        // files after an in-place authority swap (see
561        // `QuickOpenRegistry::set_file_backends`).
562        self.quick_open_registry.set_file_backends(
563            self.authority.filesystem.clone(),
564            self.authority.process_spawner.clone(),
565        );
566        #[cfg(feature = "plugins")]
567        {
568            self.update_plugin_state_snapshot();
569            // Notify plugins so they can re-register state-gated
570            // commands (e.g. devcontainer `Attach` only when not
571            // attached). Production transitions also trigger a full
572            // editor restart that re-runs plugin init, but firing
573            // here keeps in-process transitions and the test harness
574            // (which simulates the restart inline) consistent.
575            let label = self.authority.display_label.clone();
576            self.plugin_manager.read().unwrap().run_hook(
577                "authority_changed",
578                crate::services::plugins::hooks::HookArgs::AuthorityChanged { label },
579            );
580        }
581    }
582
583    /// The active window's id. The active session under the (in-progress)
584    /// per-session model; today pinned to the single window.
585    pub fn active_window_id(&self) -> fresh_core::WindowId {
586        self.active_window
587    }
588
589    /// Swap a *single* session's (window's) authority without a restart —
590    /// the per-session counterpart to [`Self::set_boot_authority`], which
591    /// fans one authority across every window at boot.
592    ///
593    /// Updates that window's `resources.authority` and re-points its LSP
594    /// backend (long-running spawner, path translation, trust); when the
595    /// window is the active one, mirrors into the editor-wide `authority`
596    /// cache the rest of the editor reads and fires the `authority_changed`
597    /// hook. This is the activation primitive a per-session attach (the
598    /// planned `attachRemoteAgent` op, and the Orchestrator session-swap)
599    /// builds on, and the seam that lets distinct windows hold distinct
600    /// authorities concurrently (`AUTHORITY_DESIGN.md` §"Evolution:
601    /// per-session authority").
602    ///
603    /// Caveat — why production attach still goes through the destructive
604    /// `install_authority` restart: like `set_boot_authority`, this does
605    /// not invalidate per-buffer captured filesystem handles or terminals
606    /// opened under the previous authority. Hot-swapping those safely is
607    /// the remaining per-window cache-invalidation work gated on the live
608    /// multi-session migration; until it lands, this method is the
609    /// infrastructure seam, exercised by tests and the activation path,
610    /// not yet the user-facing attach.
611    pub fn set_session_authority(
612        &mut self,
613        window_id: fresh_core::WindowId,
614        authority: crate::services::authority::Authority,
615    ) {
616        let is_active = self.active_window == window_id;
617        if let Some(w) = self.windows.get_mut(&window_id) {
618            w.resources.authority = authority.clone();
619            // Each window owns its `LspManager` by construction (no longer an
620            // `Option`); re-point its backend handles, matching the active-
621            // window re-pointing `set_boot_authority` does for every window.
622            let lsp = &mut w.lsp;
623            lsp.set_long_running_spawner(authority.long_running_spawner.clone());
624            lsp.set_path_translation(authority.path_translation.clone());
625            lsp.set_workspace_trust(authority.workspace_trust.clone());
626        }
627        if is_active {
628            self.authority = authority;
629            // Re-point quick-open's file provider at the now-active backend
630            // (see `set_boot_authority` — same stale-capture fix).
631            self.quick_open_registry.set_file_backends(
632                self.authority.filesystem.clone(),
633                self.authority.process_spawner.clone(),
634            );
635            #[cfg(feature = "plugins")]
636            {
637                self.update_plugin_state_snapshot();
638                let label = self.authority.display_label.clone();
639                self.plugin_manager.read().unwrap().run_hook(
640                    "authority_changed",
641                    crate::services::plugins::hooks::HookArgs::AuthorityChanged { label },
642                );
643            }
644        }
645    }
646
647    /// Adopt the now-active window's authority into the editor-wide caches,
648    /// called by [`Self::set_active_window`] right after the active pointer
649    /// moves. The per-window `resources.authority` is already correct (each
650    /// window owns its own, re-pointed at creation / on
651    /// `set_session_authority`); this propagates it to the single editor-wide
652    /// `self.authority` the rest of the editor reads, and re-points quick-open
653    /// at the new backend's filesystem/spawner.
654    ///
655    /// `previous_label` is the active backend's label *before* the switch:
656    /// when it is unchanged (the overwhelmingly common local→local case, and
657    /// any switch between same-backend windows) we skip the
658    /// `authority_changed` hook + snapshot churn so window switching stays
659    /// cheap and the status bar doesn't flicker.
660    pub(crate) fn adopt_active_window_authority(&mut self, previous_label: &str) {
661        let new_authority = self.active_window().authority().clone();
662        let label_changed = new_authority.display_label != previous_label;
663        self.authority = new_authority;
664        // Re-point quick-open's file provider at the now-active backend (the
665        // same stale-capture fix `set_boot_authority` / `set_session_authority`
666        // apply). Cheap `Arc` clones, so it's fine to do on every switch.
667        self.quick_open_registry.set_file_backends(
668            self.authority.filesystem.clone(),
669            self.authority.process_spawner.clone(),
670        );
671        if label_changed {
672            #[cfg(feature = "plugins")]
673            {
674                self.update_plugin_state_snapshot();
675                let label = self.authority.display_label.clone();
676                self.plugin_manager.read().unwrap().run_hook(
677                    "authority_changed",
678                    crate::services::plugins::hooks::HookArgs::AuthorityChanged { label },
679                );
680            }
681        }
682    }
683
684    /// Read-only access to the active authority.
685    pub fn authority(&self) -> &crate::services::authority::Authority {
686        &self.authority
687    }
688
689    /// The editor's current working directory — the active window's
690    /// project root. Derived, not stored: there is no separate
691    /// `working_dir` field that could drift out of sync with the active
692    /// window (issue #2056). Individual buffers may live elsewhere.
693    pub fn working_dir(&self) -> &std::path::Path {
694        &self.active_window().root
695    }
696
697    /// The currently active `Session`. Always `WindowId(1)` until
698    /// the multi-session migration step lands; until then this is
699    /// effectively a typed wrapper around `working_dir`. New code
700    /// should prefer this accessor so the eventual migration is a
701    /// no-op for the call site.
702    ///
703    /// Panics if the active session id is not present in the
704    /// `sessions` map. That invariant is upheld by the constructor
705    /// and `setActiveWindow` (when added) — if the panic ever fires
706    /// it indicates a bug in session lifecycle code.
707    pub fn active_window(&self) -> &crate::app::window::Window {
708        self.windows
709            .get(&self.active_window)
710            .expect("active_window id must be a member of sessions")
711    }
712
713    /// The active session's id.
714    pub fn active_session_id(&self) -> fresh_core::WindowId {
715        self.active_window
716    }
717
718    /// True iff the editor-global dock is open AND currently holds
719    /// keyboard focus. Test helpers use this to wait for `Toggle Dock`'s
720    /// async focus-grab to settle before dispatching subsequent keys;
721    /// without that readiness check, keys can race into the editor
722    /// during the gap and the test silently waits for a dock response
723    /// that never comes.
724    pub fn is_dock_focused(&self) -> bool {
725        self.dock.as_ref().is_some_and(|d| d.focused)
726    }
727
728    /// Allocate the next globally-unique `BufferId`. Use this in
729    /// `impl Editor` handler bodies that mint new buffer ids. Handlers
730    /// that have already moved to `impl Window` use
731    /// `Window::alloc_buffer_id` (which delegates to the same
732    /// `Arc<BufferIdAllocator>` shared via `WindowResources`).
733    ///
734    /// Keeps `next_buffer_id` in sync with the allocator's high-water
735    /// mark so workspace snapshots that read the `next_buffer_id`
736    /// counter directly continue to see a correct value. The
737    /// allocator's atomic is the source of truth; this counter mirrors
738    /// it for serialization compatibility.
739    pub(crate) fn alloc_buffer_id(&mut self) -> fresh_core::BufferId {
740        let id = self.buffer_id_alloc.next();
741        // Bump the legacy counter past the freshly-issued id so
742        // workspace serialization snapshots see a value at least one
743        // greater than every issued id.
744        if id.0 + 1 > self.next_buffer_id {
745            self.next_buffer_id = id.0 + 1;
746        }
747        id
748    }
749
750    /// Number of sessions currently in the editor. Always 1 until
751    /// the multi-session step lands.
752    pub fn session_count(&self) -> usize {
753        self.windows.len()
754    }
755
756    /// Look up a session by id. Returns `None` if `id` is not in
757    /// the sessions map. Useful for tests; production code that
758    /// needs the active session should use `active_window()`.
759    pub fn session(&self, id: fresh_core::WindowId) -> Option<&crate::app::window::Window> {
760        self.windows.get(&id)
761    }
762
763    /// Active session's utility-dock panel-id → buffer-id map.
764    /// Used by tests to assert that the active window's dock
765    /// occupancy is what was set on it. (Pre-0b this asserted
766    /// "warm-swap restored the stash"; post-0b every window owns
767    /// its own dock, so the assertion is just "this window's
768    /// `panel_ids` map matches expectations.")
769    #[doc(hidden)]
770    pub fn panel_ids_for_test(&self) -> &std::collections::HashMap<String, fresh_core::BufferId> {
771        self.panel_ids()
772    }
773
774    /// Inject a panel_ids entry. Used by tests to populate the
775    /// active session's dock occupancy without going through the
776    /// async plugin command path.
777    #[doc(hidden)]
778    pub fn insert_panel_id_for_test(&mut self, key: String, buffer_id: fresh_core::BufferId) {
779        self.panel_ids_mut().insert(key, buffer_id);
780    }
781
782    /// True iff the active session has an LSP manager attached. Every
783    /// window now owns one by construction (`Window::new`), so this is
784    /// always true; the helper is retained as a regression guard so a
785    /// future change that reintroduces a manager-less window state is
786    /// caught by the orchestrator-window tests.
787    #[doc(hidden)]
788    pub fn has_lsp_for_test(&self) -> bool {
789        self.lsp().is_some()
790    }
791
792    /// Most-recent `path_changed` event the editor received.
793    /// Test-only — used by `watch_path` e2e tests to assert
794    /// kernel events surfaced to the editor.
795    #[doc(hidden)]
796    pub fn last_path_change_for_test(&self) -> Option<&(u64, std::path::PathBuf, &'static str)> {
797        self.last_path_change_for_test.as_ref()
798    }
799
800    /// Most-recent `WatchPathRegistered` plugin response, paired
801    /// with its request_id. Test-only.
802    #[doc(hidden)]
803    pub fn last_watch_response_for_test(&self) -> Option<&(u64, Result<u64, String>)> {
804        self.last_watch_response_for_test.as_ref()
805    }
806
807    /// Inject an mtime entry into the active session's mod-time
808    /// cache. Used by tests to populate `Window.file_mod_times`
809    /// without going through real file I/O. (Pre-0b this was
810    /// reaching the warm-swap stash; post-0b it's a direct
811    /// insert into the active window's cache.)
812    #[doc(hidden)]
813    pub fn insert_mtime_for_test(&mut self, path: std::path::PathBuf, t: std::time::SystemTime) {
814        self.file_mod_times_mut().insert(path, t);
815    }
816
817    /// Whether the active session's mtime cache contains `path`.
818    #[doc(hidden)]
819    pub fn has_mtime_for_test(&self, path: &std::path::Path) -> bool {
820        self.file_mod_times().contains_key(path)
821    }
822
823    /// Mutable access to the active session. Used by lifecycle code
824    /// that re-targets per-session state (renaming, etc.). Same
825    /// panic invariant as `active_window()`.
826    pub fn active_window_mut(&mut self) -> &mut crate::app::window::Window {
827        let id = self.active_window;
828        self.windows
829            .get_mut(&id)
830            .expect("active_window id must be a member of sessions")
831    }
832
833    /// Borrow one of the two coexisting widget-panel slots (centered
834    /// modal vs. left dock). See `PanelSlot`.
835    pub(crate) fn panel(
836        &self,
837        slot: crate::app::PanelSlot,
838    ) -> Option<&crate::app::FloatingWidgetState> {
839        match slot {
840            crate::app::PanelSlot::Floating => self.floating_widget_panel.as_ref(),
841            crate::app::PanelSlot::Dock => self.dock.as_ref(),
842        }
843    }
844
845    /// Mutable handle to one of the two widget-panel slots.
846    pub(crate) fn panel_mut(
847        &mut self,
848        slot: crate::app::PanelSlot,
849    ) -> Option<&mut crate::app::FloatingWidgetState> {
850        match slot {
851            crate::app::PanelSlot::Floating => self.floating_widget_panel.as_mut(),
852            crate::app::PanelSlot::Dock => self.dock.as_mut(),
853        }
854    }
855
856    /// Mutable handle to the slot *option* itself (for take/assign).
857    pub(crate) fn panel_opt_mut(
858        &mut self,
859        slot: crate::app::PanelSlot,
860    ) -> &mut Option<crate::app::FloatingWidgetState> {
861        match slot {
862            crate::app::PanelSlot::Floating => &mut self.floating_widget_panel,
863            crate::app::PanelSlot::Dock => &mut self.dock,
864        }
865    }
866
867    /// Which slot currently holds the panel with this id, if any.
868    #[cfg(feature = "plugins")]
869    pub(crate) fn slot_of_panel(&self, panel_id: u64) -> Option<crate::app::PanelSlot> {
870        if self
871            .floating_widget_panel
872            .as_ref()
873            .is_some_and(|f| f.panel_id == panel_id)
874        {
875            Some(crate::app::PanelSlot::Floating)
876        } else if self.dock.as_ref().is_some_and(|f| f.panel_id == panel_id) {
877            Some(crate::app::PanelSlot::Dock)
878        } else {
879            None
880        }
881    }
882
883    /// Map a panel sentinel buffer-id back to its slot.
884    pub(crate) fn slot_for_panel_buffer(buffer_id: BufferId) -> Option<crate::app::PanelSlot> {
885        if buffer_id == crate::app::FLOATING_PANEL_BUFFER_ID {
886            Some(crate::app::PanelSlot::Floating)
887        } else if buffer_id == crate::app::DOCK_PANEL_BUFFER_ID {
888            Some(crate::app::PanelSlot::Dock)
889        } else {
890            None
891        }
892    }
893
894    /// The active window's layout-cache (split-leaf rects, tab rects,
895    /// file-explorer rect, view-line mappings). Mouse hit-testing and
896    /// visual-line motion read from here.
897    pub(crate) fn active_layout(&self) -> &crate::app::types::WindowLayoutCache {
898        &self.active_window().layout_cache
899    }
900
901    /// Mutable handle to the active window's layout cache. Renderer
902    /// writes split / tab / file-explorer hit-test rects here at the
903    /// end of each frame.
904    pub(crate) fn active_layout_mut(&mut self) -> &mut crate::app::types::WindowLayoutCache {
905        &mut self.active_window_mut().layout_cache
906    }
907
908    /// The active window's editor-chrome layout cache (status bar,
909    /// menu, popups, prompt overlay, full-frame cell-theme map).
910    /// Mouse hit-testing reads from here.
911    pub(crate) fn active_chrome(&self) -> &crate::app::types::ChromeLayout {
912        &self.active_window().chrome_layout
913    }
914
915    /// Mutable handle to the active window's chrome-layout cache.
916    /// Renderer writes status-bar / menu / popup / prompt-overlay
917    /// hit-test rects here at the end of each frame.
918    pub(crate) fn active_chrome_mut(&mut self) -> &mut crate::app::types::ChromeLayout {
919        &mut self.active_window_mut().chrome_layout
920    }
921
922    /// Active window's utility-dock panel-id → buffer-id map.
923    /// Each window owns its own dock; switching windows shows a
924    /// different (possibly empty) dock.
925    pub(crate) fn panel_ids(&self) -> &std::collections::HashMap<String, BufferId> {
926        &self.active_window().panel_ids
927    }
928
929    /// Mutable handle to the active window's panel-id map.
930    pub(crate) fn panel_ids_mut(&mut self) -> &mut std::collections::HashMap<String, BufferId> {
931        &mut self.active_window_mut().panel_ids
932    }
933
934    /// Active window's open-file mtime cache. Auto-revert only
935    /// fires for files in the active window — dormant windows
936    /// keep their mtime snapshot until the next dive.
937    pub(crate) fn file_mod_times(
938        &self,
939    ) -> &std::collections::HashMap<std::path::PathBuf, std::time::SystemTime> {
940        &self.active_window().file_mod_times
941    }
942
943    /// Mutable handle to the active window's mtime cache.
944    pub(crate) fn file_mod_times_mut(
945        &mut self,
946    ) -> &mut std::collections::HashMap<std::path::PathBuf, std::time::SystemTime> {
947        &mut self.active_window_mut().file_mod_times
948    }
949
950    /// Active window's file-explorer view (`None` if it's never been
951    /// opened in this window). Each window has its own tree;
952    /// switching windows shows that window's view (or none).
953    pub fn file_explorer(&self) -> Option<&FileTreeView> {
954        self.active_window().file_explorer.as_ref()
955    }
956
957    /// Mutable handle to the active window's file-explorer view.
958    /// Holds `&mut self` for the call's lifetime — for sites that
959    /// also need to read other Editor fields, use direct
960    /// `self.windows.get_mut(&self.active_window).and_then(|w| w.file_explorer.as_mut())`
961    /// instead so the borrow on `self.windows` stays disjoint.
962    pub fn file_explorer_mut(&mut self) -> Option<&mut FileTreeView> {
963        self.active_window_mut().file_explorer.as_mut()
964    }
965
966    /// Active window's buffer storage. Each window owns its
967    /// `EditorState` map outright; closing the window drops them.
968    /// Cross-window iteration goes through `self.windows.values()`
969    /// directly.
970    pub(crate) fn buffers(&self) -> &crate::app::window::WindowBuffers {
971        &self.active_window().buffers
972    }
973
974    /// Mutable handle to the active window's buffer storage.
975    /// Holds `&mut self` for the call's lifetime — at sites that
976    /// need a concurrent mutable borrow on another Window field
977    /// (`splits`, `event_logs`, etc.) take a single
978    /// `let window = self.windows.get_mut(&self.active_window).unwrap()`
979    /// and split-access the disjoint sub-fields directly.
980    pub(crate) fn buffers_mut(&mut self) -> &mut crate::app::window::WindowBuffers {
981        &mut self.active_window_mut().buffers
982    }
983
984    /// Active window's LSP manager. Each window owns one rooted at its
985    /// project root (built in `Window::new`), so this is always
986    /// present; the `Option` is retained for call-site ergonomics and
987    /// because the active-window lookup is itself fallible in spirit.
988    pub(crate) fn lsp(&self) -> Option<&crate::services::lsp::manager::LspManager> {
989        Some(&self.active_window().lsp)
990    }
991
992    /// Mutable handle to the active window's LSP manager. Same
993    /// borrow caveat as `file_explorer_mut()`: at sites that also
994    /// need to read other Editor fields, prefer direct
995    /// `self.windows.get_mut(&self.active_window).map(|w| &mut w.lsp)`.
996    pub(crate) fn lsp_mut(&mut self) -> Option<&mut crate::services::lsp::manager::LspManager> {
997        Some(&mut self.active_window_mut().lsp)
998    }
999
1000    /// Active window's split tree. Panics if the window has no
1001    /// layout yet — the invariant is "the active window always has
1002    /// `splits` populated", upheld by `set_active_window` (which
1003    /// seeds the layout on first dive) and by editor init (which
1004    /// hands the initial layout to the base window).
1005    pub(crate) fn split_manager(&self) -> &crate::view::split::SplitManager {
1006        &self
1007            .active_window()
1008            .buffers
1009            .splits()
1010            .expect("active window must have a populated split layout")
1011            .0
1012    }
1013
1014    /// Mutable handle to the active window's split tree.
1015    pub(crate) fn split_manager_mut(&mut self) -> &mut crate::view::split::SplitManager {
1016        &mut self
1017            .active_window_mut()
1018            .buffers
1019            .splits_mut()
1020            .expect("active window must have a populated split layout")
1021            .0
1022    }
1023
1024    /// Active window's per-leaf view state map.
1025    #[cfg(test)]
1026    pub(crate) fn split_view_states(
1027        &self,
1028    ) -> &std::collections::HashMap<crate::model::event::LeafId, crate::view::split::SplitViewState>
1029    {
1030        &self
1031            .active_window()
1032            .buffers
1033            .splits()
1034            .expect("active window must have a populated split layout")
1035            .1
1036    }
1037
1038    /// Mutable handle to the active window's per-leaf view state map.
1039    pub(crate) fn split_view_states_mut(
1040        &mut self,
1041    ) -> &mut std::collections::HashMap<
1042        crate::model::event::LeafId,
1043        crate::view::split::SplitViewState,
1044    > {
1045        &mut self
1046            .active_window_mut()
1047            .buffers
1048            .splits_mut()
1049            .expect("active window must have a populated split layout")
1050            .1
1051    }
1052
1053    /// Return buffer ids whose on-disk path sits at or under `root`.
1054    /// Used by file-explorer operations that need to react when a file
1055    /// or directory on disk goes away or moves.
1056    pub fn buffer_ids_under_path(&self, root: &std::path::Path) -> Vec<BufferId> {
1057        self.windows
1058            .get(&self.active_window)
1059            .map(|w| &w.buffers)
1060            .expect("active window present")
1061            .iter()
1062            .filter_map(|(id, state)| {
1063                let p = state.buffer.file_path()?;
1064                if p == root || p.starts_with(root) {
1065                    Some(*id)
1066                } else {
1067                    None
1068                }
1069            })
1070            .collect()
1071    }
1072
1073    /// Get remote connection info if editing remote files
1074    ///
1075    /// Returns `Some("user@host")` for remote editing, `None` for local.
1076    pub fn remote_connection_info(&self) -> Option<&str> {
1077        self.authority.filesystem.remote_connection_info()
1078    }
1079
1080    /// Get connection string for display in status bar and file explorer.
1081    ///
1082    /// Per principle 9, identity lives in the authority. The label set
1083    /// by whoever constructed the authority wins; if it is empty (the
1084    /// SSH constructor leaves it that way) we fall back to the
1085    /// filesystem's `remote_connection_info()`, which knows how to
1086    /// annotate disconnected SSH sessions.
1087    pub fn connection_display_string(&self) -> Option<String> {
1088        if !self.authority.display_label.is_empty() {
1089            return Some(self.authority.display_label.clone());
1090        }
1091        self.remote_connection_info().map(|conn| {
1092            if self.authority.filesystem.is_remote_connected() {
1093                conn.to_string()
1094            } else {
1095                format!("{} (Disconnected)", conn)
1096            }
1097        })
1098    }
1099
1100    /// Get the status log path
1101    pub fn get_status_log_path(&self) -> Option<&PathBuf> {
1102        self.status_log_path.as_ref()
1103    }
1104
1105    /// Open the status log file (user clicked on status message)
1106    pub fn open_status_log(&mut self) {
1107        if let Some(path) = self.status_log_path.clone() {
1108            // Use open_local_file since log files are always local
1109            match self.active_window_mut().open_local_file(&path) {
1110                Ok(buffer_id) => {
1111                    self.active_window_mut()
1112                        .mark_buffer_read_only(buffer_id, true);
1113                }
1114                Err(e) => {
1115                    tracing::error!("Failed to open status log: {}", e);
1116                }
1117            }
1118        } else {
1119            self.set_status_message("Status log not available".to_string());
1120        }
1121    }
1122
1123    /// Check for and handle any new warnings in the warning log
1124    ///
1125    /// Updates the general warning domain for the status bar.
1126    /// Returns true if new warnings were found.
1127    pub fn check_warning_log(&mut self) -> bool {
1128        let path = match &self.warning_log {
1129            Some((receiver, path)) => {
1130                let mut new_warning_count = 0usize;
1131                while receiver.try_recv().is_ok() {
1132                    new_warning_count += 1;
1133                }
1134                if new_warning_count == 0 {
1135                    return false;
1136                }
1137                (path.clone(), new_warning_count)
1138            }
1139            None => return false,
1140        };
1141        let (path, new_warning_count) = path;
1142        self.active_window_mut()
1143            .warning_domains
1144            .general
1145            .add_warnings(new_warning_count);
1146        self.active_window_mut()
1147            .warning_domains
1148            .general
1149            .set_log_path(path);
1150
1151        true
1152    }
1153
1154    /// Get the warning domain registry
1155    // Warning-domain accessors live on `impl Window`:
1156    //  - `clear_warnings` — call as `self.active_window_mut().clear_warnings()`.
1157    //  - Read access via `active_window().warning_domains` directly
1158    //    (and its `.general` / `.lsp` sub-registries).
1159    // `has_lsp_error`, `get_effective_warning_level`,
1160    // `get_general_warning_level`, `get_general_warning_count`,
1161    // `get_warning_domains`, `get_warning_log_path`,
1162    // `clear_warning_indicator` were thin getters with no remaining
1163    // callers and have been removed.
1164
1165    /// Open the warning log file (user-initiated action). Stays on
1166    /// `impl Editor` because it calls editor-orchestration helpers
1167    /// (`open_local_file`, `mark_buffer_read_only`).
1168    pub fn open_warning_log(&mut self) {
1169        if let Some(path) = self
1170            .active_window_mut()
1171            .warning_domains
1172            .general
1173            .log_path
1174            .clone()
1175        {
1176            // Use open_local_file since log files are always local
1177            match self.active_window_mut().open_local_file(&path) {
1178                Ok(buffer_id) => {
1179                    self.active_window_mut()
1180                        .mark_buffer_read_only(buffer_id, true);
1181                }
1182                Err(e) => {
1183                    tracing::error!("Failed to open warning log: {}", e);
1184                }
1185            }
1186        }
1187    }
1188
1189    // `update_lsp_warning_domain` lives on `impl Window` — call it via
1190    // `self.active_window_mut().update_lsp_warning_domain()`.
1191
1192    /// Check if mouse hover timer has expired and trigger LSP hover request
1193    ///
1194    /// This implements debounced hover - we wait for the configured delay before
1195    /// sending the request to avoid spamming the LSP server on every mouse move.
1196    /// Returns true if a hover request was triggered.
1197    /// True when the LSP status popup (the one opened by clicking the "LSP"
1198    /// indicator in the status bar) is the top popup.
1199    ///
1200    /// Hover popups share the active state's popup stack with it, but the LSP
1201    /// status popup is non-transient, so the hover dismiss-transients pass
1202    /// leaves it in place and a hover would stack on top of it. Callers use
1203    /// this to suppress hover while it is open.
1204    pub(crate) fn is_lsp_status_popup_open(&self) -> bool {
1205        self.active_state()
1206            .popups
1207            .top()
1208            .is_some_and(|p| matches!(p.resolver, crate::view::popup::PopupResolver::LspStatus))
1209    }
1210
1211    pub fn check_mouse_hover_timer(&mut self) -> bool {
1212        // Check if mouse hover is enabled
1213        if !self.config.editor.mouse_hover_enabled {
1214            return false;
1215        }
1216
1217        // Suppress hover while the LSP status popup is open so the hover card
1218        // doesn't stack on top of it.
1219        if self.is_lsp_status_popup_open() {
1220            return false;
1221        }
1222
1223        let hover_delay = std::time::Duration::from_millis(self.config.editor.mouse_hover_delay_ms);
1224
1225        // Get hover state without borrowing self
1226        let hover_info = match self.active_window_mut().mouse_state.lsp_hover_state {
1227            Some((byte_pos, start_time, screen_x, screen_y)) => {
1228                if self.active_window_mut().mouse_state.lsp_hover_request_sent {
1229                    return false; // Already sent request for this position
1230                }
1231                if start_time.elapsed() < hover_delay {
1232                    return false; // Timer hasn't expired yet
1233                }
1234                Some((byte_pos, screen_x, screen_y))
1235            }
1236            None => return false,
1237        };
1238
1239        let Some((byte_pos, screen_x, screen_y)) = hover_info else {
1240            return false;
1241        };
1242
1243        // Store mouse position for popup positioning
1244        self.active_window_mut()
1245            .hover
1246            .set_screen_position((screen_x, screen_y));
1247
1248        // Request hover at the byte position — only mark as sent if dispatched
1249        match self.request_hover_at_position(byte_pos) {
1250            Ok(true) => {
1251                self.active_window_mut().mouse_state.lsp_hover_request_sent = true;
1252                true
1253            }
1254            Ok(false) => false, // no server ready, timer will retry
1255            Err(e) => {
1256                tracing::debug!("Failed to request hover: {}", e);
1257                false
1258            }
1259        }
1260    }
1261
1262    // `check_semantic_highlight_timer` lives on `impl Window` — call it
1263    // via `self.active_window().check_semantic_highlight_timer()`.
1264
1265    // `check_diagnostic_pull_timer` lives on `impl Window` — call it via
1266    // `self.active_window_mut().check_diagnostic_pull_timer()`. Pulls
1267    // run against the active window's LSP manager and its per-window
1268    // `scheduled_diagnostic_pull` debounce slot.
1269
1270    /// Check if completion trigger timer has expired and trigger completion if so
1271    ///
1272    /// This implements debounced completion - we wait for quick_suggestions_delay_ms
1273    /// before sending the completion request to avoid spamming the LSP server.
1274    /// Returns true if a completion request was triggered.
1275    pub fn check_completion_trigger_timer(&mut self) -> bool {
1276        // Check if we have a scheduled completion trigger
1277        let Some(trigger_time) = self.active_window_mut().scheduled_completion_trigger else {
1278            return false;
1279        };
1280
1281        // Check if the timer has expired
1282        if Instant::now() < trigger_time {
1283            return false;
1284        }
1285
1286        // Clear the scheduled trigger
1287        self.active_window_mut().scheduled_completion_trigger = None;
1288
1289        // Don't trigger if a popup is already visible
1290        if self.active_state().popups.is_visible() {
1291            return false;
1292        }
1293
1294        // Trigger the completion request
1295        self.request_completion();
1296
1297        true
1298    }
1299}