Skip to main content

kimun_notes/app_screen/
editor.rs

1use std::sync::Arc;
2use std::time::Duration;
3
4use async_trait::async_trait;
5use kimun_core::NoteVault;
6use kimun_core::error::{FSError, VaultError};
7use kimun_core::nfs::VaultPath;
8use ratatui::layout::{Constraint, Direction, Layout};
9use ratatui::style::Style;
10use ratatui::widgets::Paragraph;
11
12use crate::app_screen::ask::AskCoordinator;
13use crate::app_screen::editor_input::{
14    Classification, CycleDir, EditorIntent, EditorOp, InputCtx, OverlayOpen, PanelFallback,
15    classify,
16};
17use crate::app_screen::overlay_host::OverlayHost;
18use crate::app_screen::panel_set::PanelSet;
19use crate::app_screen::{AppScreen, ScreenKind};
20use crate::components::ask_thread::ThreadPanel;
21use crate::components::attachment_view::AttachmentView;
22use crate::components::autosave_timer::AutosaveTimer;
23use crate::components::dialogs::ActiveDialog;
24use crate::components::drawer::{DrawerHost, DrawerView};
25use crate::components::drawer_views::{LinksPanel, OutlinePanel, TagsPanel};
26use crate::components::event_state::EventState;
27use crate::components::events::{
28    AppEvent, AppTx, FileOp, InputEvent, OverlayData, SaveSource, SavedSearchFlow, ScreenEvent,
29    SortTarget, UpdateFlow,
30};
31use crate::components::file_list::FileListEntry;
32use crate::components::footer_bar::FooterBar;
33use crate::components::note_browser::file_finder_provider::FileFinderProvider;
34use crate::components::note_browser::search_provider::resolving_search_source;
35use crate::components::note_browser::{BrowserScope, NoteBrowserModal};
36use crate::components::overlay::{Overlay, OverlayKind};
37use crate::components::panel::PanelKind;
38use crate::components::query_panel::QueryPanel;
39use crate::components::saved_searches_modal::SavedSearchesModal;
40use crate::components::sidebar::SidebarComponent;
41use crate::components::text_editor::TextEditorComponent;
42use crate::keys::KeyBindings;
43use crate::keys::action_shortcuts::ActionShortcuts;
44use crate::keys::leader::{LeaderAction, LeaderEngine, LeaderOutcome};
45use crate::settings::SharedSettings;
46use crate::settings::icons::Icons;
47use crate::settings::themes::Theme;
48use crate::util::single_slot_task::SingleSlotTask;
49
50/// Hard cap on every blocking save path so a stuck disk (NFS hang,
51/// fsync stall) cannot freeze quit, navigation, or the next autosave
52/// tick. The same value is used both to wait for an in-flight
53/// background autosave and to bound our own synchronous save call —
54/// the worst-case quit time is therefore one cap plus the
55/// observability of `abort()` on a syscall in progress.
56const SAVE_TIMEOUT: Duration = Duration::from_secs(5);
57
58pub struct EditorScreen {
59    vault: Arc<NoteVault>,
60    settings: SharedSettings,
61    icons: Icons,
62    theme: Theme,
63    /// The persistent panels (sidebar, editor, Query panel) plus their order,
64    /// visibility, and focus. The host reaches a specific panel through the
65    /// typed accessors (`panels.editor_mut()`, …) for panel-specific calls.
66    panels: PanelSet,
67    path: VaultPath,
68    footer: FooterBar,
69    /// Async document/status state: backlink count, git summary, link
70    /// affordance cache, pending emphasis needles (see `doc_meta.rs`).
71    doc_meta: crate::app_screen::doc_meta::DocMeta,
72    /// App-global update notice, seeded by `AppEvent::Update(UpdateFlow::Available)`. Drives
73    /// the footer indicator; `None` when up to date or the check found nothing.
74    update: Option<crate::update::UpdateStatus>,
75    /// Latest RAG connection/sync status from the background sync task, shown in
76    /// the footer. `Disabled` (no server) renders nothing.
77    rag_status: crate::rag::RagStatus,
78    /// The Ask workspace's coordination layer: Thread↔Sources sync, capability
79    /// refresh, AskData routing, and show/stash transitions (see `ask.rs`).
80    ask: AskCoordinator,
81    /// The leader-key sequence state machine (Ctrl-G gateway, spec §8a).
82    leader: LeaderEngine,
83    /// The mouse presses currently forming one gesture, so a double-click in
84    /// the editor can follow a link (see `click_run`). Fed before each
85    /// classification; its answer reaches the classifier as `InputCtx`.
86    clicks: crate::app_screen::click_run::ClickRun,
87    /// App event sender, captured on enter — render-side async kicks (the
88    /// link-affordance backlink fetch) need it where no `tx` is threaded.
89    app_tx: Option<AppTx>,
90    autosave: AutosaveTimer,
91    /// The active overlay, if any. An open overlay intercepts input ahead of
92    /// the panels; closing it restores focus to the panel that opened it.
93    overlays: OverlayHost<PanelKind>,
94    /// Handle to the most recently spawned background autosave task.
95    /// `is_in_flight()` is the source of truth for "is a save still in
96    /// flight"; both successful completion AND panic flip it to false
97    /// so the next periodic tick can spawn fresh. The synchronous save
98    /// paths (`open_path` / `on_entry_op` / `on_exit`) await this slot
99    /// before issuing their own `vault.save_note`, so two concurrent
100    /// writes for the same path can never collide. Drop aborts the
101    /// in-flight task so the spawned future cannot outlive the screen.
102    autosave_task: SingleSlotTask<()>,
103}
104
105impl EditorScreen {
106    pub fn new(vault: Arc<NoteVault>, path: VaultPath, settings: SharedSettings) -> Self {
107        let s = settings.read().unwrap();
108        let kb = s.key_bindings.clone();
109        let theme = s.get_theme();
110        let footer = FooterBar::new();
111        let icons = s.icons();
112        let sidebar = SidebarComponent::from_settings(vault.clone(), &s);
113        let query_panel = QueryPanel::new(vault.clone(), kb.clone(), icons.clone());
114        let semantic = crate::components::semantic_search::SemanticPanel::new(
115            vault.clone(),
116            settings.clone(),
117            s.icons(),
118            s.yank_combos(),
119        );
120        let tags = TagsPanel::new(vault.clone(), s.icons(), s.yank_combos());
121        let links = LinksPanel::new(vault.clone(), s.icons(), s.yank_combos());
122        let outline = OutlinePanel::new(vault.clone(), s.icons(), s.yank_combos());
123        let drawer = DrawerHost::new(
124            vault.clone(),
125            &kb,
126            sidebar,
127            query_panel,
128            semantic,
129            tags,
130            links,
131            outline,
132        );
133        let rail_kb = kb.clone();
134        let mut editor = TextEditorComponent::new(kb, &s);
135        editor.set_vault(vault.clone());
136        let leader_engine = LeaderEngine::with_tree(s.leader_tree());
137        drop(s);
138        let rail_icons = icons.clone();
139        let ask = AskCoordinator::new(settings.clone(), vault.clone());
140        Self {
141            settings,
142            icons,
143            theme,
144            // SEM and ASK both start hidden: no RAG status has arrived yet, so
145            // the server's search/LLM capability is unknown. The rail rebuilds
146            // when the first health probe lands (both are status-driven).
147            panels: PanelSet::from_panels(
148                drawer,
149                editor,
150                rail_icons,
151                rail_kb,
152                crate::components::activity_rail::RailCaps {
153                    semantic: false,
154                    ask: false,
155                },
156            ),
157            doc_meta: crate::app_screen::doc_meta::DocMeta::new(vault.clone()),
158            update: None,
159            rag_status: crate::rag::RagStatus::Disabled,
160            ask,
161            vault,
162            path,
163            footer,
164            leader: leader_engine,
165            clicks: Default::default(),
166            app_tx: None,
167            autosave: AutosaveTimer::new(),
168            overlays: OverlayHost::new(),
169            autosave_task: SingleSlotTask::empty(),
170        }
171    }
172}
173
174/// Encodes raw RGBA pixels as a PNG byte stream.
175fn encode_rgba_to_png(width: u32, height: u32, rgba: &[u8]) -> std::io::Result<Vec<u8>> {
176    let mut buf = Vec::new();
177    {
178        let mut encoder = png::Encoder::new(&mut buf, width, height);
179        encoder.set_color(png::ColorType::Rgba);
180        encoder.set_depth(png::BitDepth::Eight);
181        let mut writer = encoder
182            .write_header()
183            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
184        writer
185            .write_image_data(rgba)
186            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
187    }
188    Ok(buf)
189}
190
191impl EditorScreen {
192    /// Pulls an image off the system clipboard, encodes it to PNG, saves it as
193    /// an attachment under the vault's `/assets` directory, and inserts a
194    /// markdown image link (relative to the current note) at the cursor.
195    ///
196    /// Returns `true` if a clipboard image was found and the paste was
197    /// dispatched — even if the encode/save is still in flight. Returns
198    /// `false` if the clipboard contained no image, so the caller can fall
199    /// through to a regular text paste.
200    fn try_paste_image(&mut self, tx: &AppTx) -> bool {
201        let Some(editor) = self.panels.editor_mut() else {
202            return false;
203        };
204        let img = match editor.take_clipboard_image() {
205            Some(i) if !i.rgba.is_empty() && i.width > 0 && i.height > 0 => i,
206            _ => return false,
207        };
208        // arboard contract: rgba length == width * height * 4. A mismatch means
209        // a misbehaving clipboard provider — refuse rather than encode garbage.
210        let expected = img
211            .width
212            .checked_mul(img.height)
213            .and_then(|n| n.checked_mul(4));
214        if expected != Some(img.rgba.len()) {
215            self.footer
216                .flash("Clipboard image size mismatch".to_string(), tx);
217            return true;
218        }
219        // The selection is NOT dropped here. Both steps below can fail — the
220        // PNG encode and the attachment save — and a cut done now would destroy
221        // the user's text with nothing to replace it. `insert_at_cursor`, which
222        // runs only on success, does the replacement and reconciles the vim
223        // engine out of Visual in the same breath.
224        let asset_path = self.vault.generate_attachment_path("image", "png");
225        let link_path = asset_path.relative_link_from_note(&self.path);
226        let markdown = format!("![]({link_path})");
227        let vault = self.vault.clone();
228        let tx2 = tx.clone();
229        let width = img.width as u32;
230        let height = img.height as u32;
231        let rgba = img.rgba;
232        tokio::spawn(async move {
233            // PNG encoding is CPU-bound — keep it off the runtime worker threads.
234            let png_bytes =
235                match tokio::task::spawn_blocking(move || encode_rgba_to_png(width, height, &rgba))
236                    .await
237                {
238                    Ok(Ok(b)) => b,
239                    Ok(Err(e)) => {
240                        tx2.send(AppEvent::OverlayData(OverlayData::Error(format!(
241                            "Image encode failed: {e}"
242                        ))))
243                        .ok();
244                        return;
245                    }
246                    Err(e) => {
247                        tx2.send(AppEvent::OverlayData(OverlayData::Error(format!(
248                            "Image encode task failed: {e}"
249                        ))))
250                        .ok();
251                        return;
252                    }
253                };
254            match vault.save_attachment(&asset_path, &png_bytes).await {
255                Ok(()) => {
256                    tx2.send(AppEvent::InsertAtCursor(markdown)).ok();
257                    // Only on success — the failure branches below already
258                    // report, and this path is async, so the chord echo would
259                    // otherwise be the last thing the user saw.
260                    tx2.send(AppEvent::FlashMessage("image pasted".into())).ok();
261                }
262                Err(e) => {
263                    tx2.send(AppEvent::OverlayData(OverlayData::Error(format!(
264                        "Image save failed: {e}"
265                    ))))
266                    .ok();
267                }
268            }
269        });
270        true
271    }
272
273    /// Persist a saved search via core. Used by the SaveSearchConfirmed handler
274    /// and unit tests.
275    #[cfg(test)]
276    async fn persist_saved_search(&self, name: &str, query: &str) -> Result<(), VaultError> {
277        self.vault.save_search(name, query).await
278    }
279
280    async fn follow_link(&mut self, target: String, tx: &AppTx) {
281        // External URL — hand off to the OS browser/handler.
282        if kimun_core::note::scan::is_remote_url(&target) {
283            match open::that_detached(&target) {
284                Ok(()) => self.footer.flash(format!("Opening {target}"), tx),
285                Err(e) => self.footer.flash(format!("Cannot open URL: {e}"), tx),
286            }
287            return;
288        }
289
290        // Image attachment — resolve the (potentially relative) path against
291        // the current note's directory, convert to an OS path, hand off to the
292        // OS default handler. Images are not notes, so skip the note lookup.
293        if kimun_core::note::scan::target_looks_like_image(&target) {
294            let parent = self.path.get_parent_path().0;
295            let resolved = parent.append(&VaultPath::new(target.trim()));
296            let os_path = self.vault.path_to_pathbuf(&resolved);
297            match open::that_detached(&os_path) {
298                Ok(()) => self.footer.flash(format!("Opening {target}"), tx),
299                Err(e) => self.footer.flash(format!("Cannot open image: {e}"), tx),
300            }
301            return;
302        }
303
304        // Note reference — look it up in the vault.
305        // Strip any `#fragment` suffix before resolving (e.g. `notes/design.md#goals`
306        // should resolve to `notes/design.md`, not `notes/design.md#goals.md`).
307        let target_clean = target.split('#').next().unwrap_or(&target).trim_end();
308        // Resolve the (possibly relative, e.g. `../work/anton.md`) target
309        // against this note's directory so the existence lookup uses the same
310        // absolute path the note is stored under. Bare names stay name-lookups.
311        let path = kimun_core::nfs::VaultPath::note_path_from(target_clean)
312            .resolve_link_in_note(&self.path);
313        match self.vault.open_or_search(&path).await {
314            Ok(results) if results.is_empty() => {
315                self.present_overlay(Box::new(ActiveDialog::create_note(
316                    path,
317                    self.vault.clone(),
318                    None,
319                )));
320            }
321            Ok(mut results) if results.len() == 1 => {
322                let (entry, _) = results.remove(0);
323                self.open_path(entry.path, None, tx).await;
324            }
325            Ok(results) => {
326                use crate::components::note_browser::link_results_provider::LinkResultsProvider;
327                let provider = LinkResultsProvider::from_results(results);
328                let s = self.settings.read().unwrap();
329                let modal = NoteBrowserModal::new(
330                    format!("Follow: {target}"),
331                    BrowserScope::Files,
332                    provider,
333                    self.vault.clone(),
334                    s.key_bindings.clone(),
335                    s.icons(),
336                    tx.clone(),
337                );
338                drop(s);
339                self.present_overlay(Box::new(modal));
340            }
341            Err(e) => {
342                self.footer.flash(format!("Link error: {e}"), tx);
343            }
344        }
345    }
346
347    pub async fn open_path(&mut self, path: VaultPath, emphasis: Option<Vec<String>>, tx: &AppTx) {
348        if !path.is_note() {
349            // A non-note path is either an attachment (show it in place of the
350            // editor) or a directory (browse it). Classify so a stray
351            // attachment open here still lands in the attachment view rather
352            // than the directory browser.
353            if let Ok(kimun_core::EntryKind::Attachment) = self.vault.entry_kind(&path).await {
354                self.open_attachment(path, tx).await;
355                return;
356            }
357            tx.send(AppEvent::OpenScreen(ScreenEvent::OpenBrowse(
358                self.vault.clone(),
359                path,
360            )))
361            .ok();
362            return;
363        }
364
365        // Save current note before switching
366        self.try_save().await;
367
368        {
369            let mut s = self.settings.write().unwrap();
370            s.add_path_history(&path);
371        }
372        let settings_snapshot = self.settings.read().unwrap().clone();
373        tokio::spawn(async move {
374            settings_snapshot.save_to_disk().ok();
375        });
376
377        self.path = path.clone();
378        // Returning to a note swaps the editor area back from any attachment or
379        // the Ask workspace. `clear_attachment` and `hide_ask_if_shown` each
380        // only touch their own content, so both are needed to guarantee the
381        // note editor is what shows (carry-forward: open note over Ask/attach).
382        self.hide_ask_if_shown();
383        self.panels.clear_attachment();
384        // Mark this note's row in the sidebar (clears the previous one).
385        self.panels
386            .sidebar_mut()
387            .set_open_note(Some(self.path.clone()));
388        match self.vault.get_note_text(&self.path).await {
389            Ok(content) => {
390                self.doc_meta.note_opened(&self.path, tx);
391                if let Some(ed) = self.panels.editor_mut() {
392                    ed.set_text(content);
393                    // Arrive-from-query emphasis: apply after the load so the
394                    // buffer's new revision owns the needles.
395                    if let Some(needles) = emphasis {
396                        ed.set_search_needles(needles);
397                    }
398                    ed.set_redraw_tx(tx);
399                }
400                tx.send(AppEvent::Redraw).ok();
401                // FIND / LINKS / OUTLINE reflect the open note; keep them in
402                // step. Shared with `on_note_renamed` via the helper.
403                self.reflect_open_note_in_drawers(tx);
404            }
405            Err(e) => {
406                if matches!(e, VaultError::FSError(FSError::VaultPathNotFound { .. })) {
407                    self.present_overlay(Box::new(ActiveDialog::create_note(
408                        self.path.clone(),
409                        self.vault.clone(),
410                        None,
411                    )));
412                } else {
413                    tracing::error!("Failed to read note {}: {e}", self.path);
414                    let parent = self.path.get_parent_path().0;
415                    tx.send(AppEvent::OpenScreen(ScreenEvent::OpenBrowse(
416                        self.vault.clone(),
417                        parent,
418                    )))
419                    .ok();
420                }
421                return;
422            }
423        }
424
425        // Load the sidebar on first open only; refreshes happen via explicit
426        // create/rename/delete/move events, not on every note open.
427        let note_parent = path.get_parent_path().0;
428        if self.panels.sidebar().is_empty() {
429            self.navigate_sidebar(note_parent, tx);
430        }
431
432        // Abort any existing timer and spawn a fresh one for the new note.
433        let interval = self.settings.read().unwrap().autosave_interval_secs;
434        self.autosave.restart(interval, tx.clone());
435    }
436
437    /// Take the editor area off the Ask workspace before it's swapped to
438    /// another view (a note or an attachment). `clear_attachment` and
439    /// `show_attachment` both leave Ask content alone, so this is what
440    /// guarantees the new view actually shows (see
441    /// `AskCoordinator::hide_if_shown` for the drawer-view rules).
442    fn hide_ask_if_shown(&mut self) {
443        self.ask.hide_if_shown(&mut self.panels);
444    }
445
446    /// Show the attachment at `path` in the editor area's read-only attachment
447    /// view. Saves and unmounts the open note first; while an
448    /// attachment is shown there is no open note, so the autosave task is
449    /// aborted and the sidebar's open-note marker cleared. The next periodic
450    /// autosave tick no-ops because the note editor is absent.
451    async fn open_attachment(&mut self, path: VaultPath, tx: &AppTx) {
452        // Persist the current note before swapping the editor area away from it.
453        self.try_save().await;
454        self.autosave_task.abort();
455
456        match self.vault.get_attachment_details(&path).await {
457            Ok(details) => {
458                let (icons, kb) = {
459                    let s = self.settings.read().unwrap();
460                    (s.icons(), s.key_bindings.clone())
461                };
462                let view = AttachmentView::new(details, icons, kb);
463                self.path = path;
464                // Take the area off Ask so the attachment actually replaces it
465                // (show_attachment leaves Ask content alone).
466                self.hide_ask_if_shown();
467                self.panels.show_attachment(view);
468                self.panels.sidebar_mut().set_open_note(None);
469                tx.send(AppEvent::Redraw).ok();
470            }
471            Err(e) => {
472                self.footer
473                    .flash(format!("Cannot open attachment: {e}"), tx);
474            }
475        }
476    }
477
478    fn navigate_sidebar(&mut self, dir: VaultPath, tx: &AppTx) {
479        // The sidebar hosts a streamed `SearchList`; (re)building its engine for
480        // `dir` runs `browse_vault_stream` inside the source and emits rows as they
481        // arrive (with a redraw on each).
482        self.panels.sidebar_mut().navigate(dir, tx);
483    }
484
485    /// Rebuild the sidebar listing only when it is currently showing `dir` —
486    /// used after entry create/rename/move ops so the change appears without
487    /// yanking the user away from an unrelated directory they browsed to.
488    /// Deliberately the inverse of `reveal_note_dir_in_sidebar`, which
489    /// navigates when the sidebar is NOT on the target dir.
490    fn refresh_sidebar_if_showing(&mut self, dir: &VaultPath, tx: &AppTx) {
491        self.panels.sidebar_mut().refresh_if_showing(dir, tx);
492    }
493
494    /// A note at `path` was just saved with raw title `raw_title`; update its
495    /// sidebar row in place. Keyed by the saved path, not the open note, so a
496    /// just-saved-then-deselected note's row updates too.
497    fn note_saved(&mut self, path: &VaultPath, raw_title: String) {
498        let title = FileListEntry::display_title(raw_title);
499        self.panels.sidebar_mut().update_note_row(path, &title);
500    }
501
502    async fn try_save(&mut self) {
503        // Wait out any background autosave so two concurrent `vault.save_note`
504        // calls cannot race on the same path. Capped at 5s so a wedged
505        // filesystem (NFS hang, fsync stall, SQLite lock contention) does
506        // not freeze app-quit indefinitely.
507        //
508        // If the timeout fires we MUST abort the prior task and bail
509        // without issuing our own save: dropping a JoinHandle detaches
510        // the tokio task rather than cancelling it, so the spawned
511        // vault.save_note keeps running. Calling our own vault.save_note
512        // on the same path on top of that is the exact two-writer race
513        // the in-flight serialisation is meant to prevent. abort() is
514        // best-effort (will not unwind an in-progress syscall) but it
515        // stops any further await points in the spawned task. The editor
516        // stays dirty so the next session retries; the spawned task
517        // either finishes against the disk on its own or is killed when
518        // the process exits.
519        if self.autosave_task.is_in_flight() {
520            match self.autosave_task.await_with_timeout(SAVE_TIMEOUT).await {
521                Some(_) => {} // completed (success or panic) — slot already cleared
522                None => {
523                    // Timeout: abort the spawned task and bail.
524                    self.autosave_task.abort();
525                    return;
526                }
527            }
528        }
529        // No note editor mounted (an attachment is shown) → nothing to save.
530        let Some(text) = self
531            .panels
532            .editor()
533            .filter(|e| e.is_dirty())
534            .map(|e| e.get_text())
535        else {
536            return;
537        };
538        // Same cap on our own save so quit cannot hang on a stuck
539        // disk. A timeout returns Err(_); we skip mark_saved so the
540        // editor stays dirty for any subsequent retry.
541        let save = self.vault.save_note(&self.path, &text);
542        if let Ok(Ok((_, content))) = tokio::time::timeout(SAVE_TIMEOUT, save).await {
543            if let Some(ed) = self.panels.editor_mut() {
544                ed.mark_saved(text);
545            }
546            let path = self.path.clone();
547            self.note_saved(&path, content.title);
548        }
549    }
550
551    /// Fire-and-forget autosave used by the periodic timer. The save runs in
552    /// a spawned tokio task so the main event loop is never blocked by the
553    /// filesystem + SQLite write. Completion is reported back as
554    /// `AppEvent::AutosaveCompleted`, which marks the editor clean iff the
555    /// editor is still at the revision that was written. `is_in_flight()`
556    /// on the `SingleSlotTask` slot is the "is a save in flight" signal;
557    /// it flips to false on both successful completion AND panic, so a
558    /// single panicked task can never permanently disable autosave.
559    fn spawn_autosave(&mut self, tx: &AppTx) {
560        // A previous task that hasn't reported completion yet still holds the
561        // lock on the file system + SQLite path; let it finish first.
562        if self.autosave_task.is_in_flight() {
563            return;
564        }
565        let Some(ed) = self.panels.editor() else {
566            return;
567        };
568        if !ed.is_dirty() {
569            return;
570        }
571        let text = ed.get_text();
572        let revision = ed.content_revision();
573        let vault = self.vault.clone();
574        let path = self.path.clone();
575        let tx = tx.clone();
576        self.autosave_task.spawn(async move {
577            let (saved_revision, title) = match vault.save_note(&path, &text).await {
578                Ok((_, content)) => (Some(revision), Some(content.title)),
579                Err(_) => (None, None),
580            };
581            let _ = tx.send(AppEvent::AutosaveCompleted {
582                path,
583                saved_revision,
584                title,
585            });
586        });
587    }
588
589    /// The panel to restore focus to when the active overlay closes — the
590    /// panel that was focused when the overlay opened.
591    fn opener_focus(&self) -> PanelKind {
592        self.panels.focused()
593    }
594
595    /// Present `overlay`, recording the currently focused panel as its opener so
596    /// `dismiss_overlay` can return there on close. The single way the editor
597    /// opens an overlay — the focus contract lives here, not at each call site.
598    fn present_overlay(&mut self, overlay: Box<dyn Overlay>) {
599        // An overlay taking input must never leave a leader sequence armed —
600        // its keys would be eaten by the leader intercept.
601        self.leader.cancel();
602        let opener = self.opener_focus();
603        self.overlays.open(overlay, opener);
604    }
605
606    /// Close the active overlay and restore focus to the panel that opened it.
607    /// The close-side mirror of `present_overlay`. `OverlayHost::close` returns
608    /// `None` when nothing is open, so this is a no-op then — which is also why
609    /// a selection that closed the overlay itself (and chose its own focus) is
610    /// not re-restored by a trailing `CloseOverlay`.
611    fn dismiss_overlay(&mut self) {
612        if let Some(opener) = self.overlays.close() {
613            self.panels.focus(opener);
614        }
615    }
616
617    async fn on_entry_op(&mut self, from: VaultPath, tx: &AppTx) {
618        self.dismiss_overlay();
619        // `is_like` ignores the vault-relative/absolute distinction: `from` (from
620        // a sidebar/query row) is index-absolute while `self.path` may be relative.
621        // A plain `==` would miss, leaving the stale autosave to
622        // recreate a deleted/moved note.
623        if from.is_like(&self.path) {
624            self.autosave.stop();
625            self.try_save().await;
626            let parent = self.path.get_parent_path().0;
627            tx.send(AppEvent::OpenScreen(ScreenEvent::OpenBrowse(
628                self.vault.clone(),
629                parent,
630            )))
631            .ok();
632        } else {
633            self.refresh_sidebar_if_showing(&from.get_parent_path().0, tx);
634        }
635    }
636
637    /// A note was renamed. Update its sidebar row in place; if it is the note
638    /// currently open, retarget the editor to the new path and reload the body
639    /// from disk so any self-link rewrites from the rename land in the buffer
640    /// (the in-memory text still holds the pre-rename self-links). We
641    /// deliberately do NOT `try_save` — the old path no longer exists on disk.
642    async fn on_note_renamed(&mut self, from: VaultPath, to: VaultPath, tx: &AppTx) {
643        self.dismiss_overlay();
644        self.panels.sidebar_mut().rename_note_row(&from, &to);
645        // `is_like` so an absolute `from` (index row) matches a possibly-relative
646        // `self.path` — otherwise the retarget + autosave-abort below
647        // are skipped and the stale save resurrects the old path.
648        if from.is_like(&self.path) {
649            // The open note was renamed. Kill any in-flight autosave still
650            // targeting the OLD path before retargeting (spawn_autosave bakes
651            // the path in; vault.save_note writes unconditionally, so a stale
652            // save would recreate the renamed-away file). abort() is
653            // best-effort (can't unwind a syscall already in progress).
654            self.autosave_task.abort();
655            match self.vault.get_note_text(&to).await {
656                Ok(text) => {
657                    self.path = to.clone();
658                    if let Some(ed) = self.panels.editor_mut() {
659                        ed.set_text(text.clone());
660                        ed.mark_saved(text);
661                    }
662                    self.panels
663                        .sidebar_mut()
664                        .set_open_note(Some(self.path.clone()));
665                    self.doc_meta.note_opened(&self.path, tx);
666                    self.reflect_open_note_in_drawers(tx);
667                    // Fresh autosave timer for the new path (mirrors open_path).
668                    let interval = self.settings.read().unwrap().autosave_interval_secs;
669                    self.autosave.restart(interval, tx.clone());
670                }
671                Err(_) => {
672                    // Couldn't load the renamed note — do NOT keep a dirty
673                    // buffer pointed at it (autosave would clobber the
674                    // on-disk rewrite). Fall back to Browse on the new
675                    // parent dir.
676                    self.autosave.stop();
677                    let parent = to.get_parent_path().0;
678                    tx.send(AppEvent::OpenScreen(ScreenEvent::OpenBrowse(
679                        self.vault.clone(),
680                        parent,
681                    )))
682                    .ok();
683                }
684            }
685        }
686    }
687}
688
689impl EditorScreen {
690    /// Snapshot of the screen state the input classifier reads. Built per
691    /// classification — cheap field reads only.
692    ///
693    /// `double_click` comes from [`Self::track_click`] rather than a field read
694    /// because feeding the click run mutates it; a snapshot is taken from
695    /// `&self` and cannot.
696    fn input_ctx(&self, double_click: bool) -> InputCtx {
697        InputCtx {
698            overlay: self.overlays.active_kind(),
699            leader_pending: self.leader.is_pending(),
700            focused: self.panels.focused(),
701            drawer_view: self.panels.active_drawer_view(),
702            space_leads: self.panels.editor().is_some_and(|e| e.space_leads()),
703            claim: self.panels.editor().map(|e| e.claim()).unwrap_or_default(),
704            double_click,
705        }
706    }
707
708    /// Feed an event to the click run and report whether it completes a
709    /// double-click on the note buffer.
710    ///
711    /// The screen answers only what a `ClickRun` cannot answer for itself:
712    /// whether the event is a mouse event at all, whether an overlay is in the
713    /// way, and whether the press landed on the note buffer. Which *mouse*
714    /// events end a run is `ClickRun`'s policy and lives there, where it can be
715    /// tested against a real event sequence.
716    ///
717    /// An open overlay ends the run rather than merely failing to extend it.
718    /// The classifier already gives an overlay precedence, so no follow can
719    /// fire *while* one is open — but a modal is drawn over the editor column,
720    /// and a `SearchList` activates a row on a click-click of its own. Without
721    /// ending it here, those presses stay in the run and pair with the first
722    /// press that lands after the overlay closes.
723    ///
724    /// `now` is passed in for the same reason [`ClickRun`] takes it rather than
725    /// reading a clock: a test describes a gap instead of sleeping through one.
726    /// The seam matters more here than there — this half of the rule is the part
727    /// that hit-tests, and the frame around the editor was counted as buffer
728    /// until it could be asserted against.
729    ///
730    /// [`ClickRun`]: crate::app_screen::click_run::ClickRun
731    fn track_click(&mut self, event: &InputEvent, now: std::time::Instant) -> bool {
732        let InputEvent::Mouse(mouse) = event else {
733            self.clicks.end();
734            return false;
735        };
736        if self.overlays.is_open() {
737            self.clicks.end();
738            return false;
739        }
740        // Only a press consults the hit-test; `observe` discards the flag for
741        // every other kind. Motion is the reason to care — any-event tracking
742        // delivers one per cell of travel, and this would otherwise scan the
743        // column rects twice for each.
744        let on_buffer = matches!(
745            mouse.kind,
746            ratatui::crossterm::event::MouseEventKind::Down(_)
747        ) && self.panels.is_note_buffer_cell(mouse.column, mouse.row);
748        self.clicks.observe(mouse, on_buffer, now)
749    }
750
751    /// Apply a classification: pre-effects first (footer chord flash, leader
752    /// cancel), then the intent. The classifier decides *what* an event
753    /// means; everything that mutates happens here.
754    fn apply_classification(
755        &mut self,
756        classification: Classification,
757        event: &InputEvent,
758        tx: &AppTx,
759    ) -> EventState {
760        if let Some(chord) = classification.flash {
761            self.footer.flash(chord, tx);
762        }
763        if classification.cancel_leader {
764            self.leader.cancel();
765        }
766        self.execute_intent(classification.intent, event, tx)
767    }
768
769    fn execute_intent(
770        &mut self,
771        intent: EditorIntent,
772        event: &InputEvent,
773        tx: &AppTx,
774    ) -> EventState {
775        match intent {
776            EditorIntent::Consume => EventState::Consumed,
777            EditorIntent::EditorPaste => {
778                if !self.try_paste_image(tx)
779                    && let InputEvent::Paste(text) = event
780                    && !text.is_empty()
781                    && let Some(ed) = self.panels.editor_mut()
782                {
783                    ed.paste_text(text, tx);
784                }
785                EventState::Consumed
786            }
787            EditorIntent::ImageProbe => {
788                if self.try_paste_image(tx) {
789                    EventState::Consumed
790                } else {
791                    // No image: the rest of the ladder decides. Reclassify
792                    // the tail against fresh state — any leader cancel was
793                    // already applied by the probe classification, so the
794                    // tail must not re-cancel (`cancel_leader = false`).
795                    // A key path (Ctrl+V): no press to pair, so no double.
796                    let ctx = self.input_ctx(false);
797                    let classification = {
798                        let s = self.settings.read().unwrap();
799                        crate::app_screen::editor_input::classify_tail(
800                            event,
801                            &s.key_bindings,
802                            &ctx,
803                            false,
804                        )
805                    };
806                    self.apply_classification(classification, event, tx)
807                }
808            }
809            EditorIntent::FollowLink => {
810                if self.follow_link_at_cursor(tx) {
811                    EventState::Consumed
812                } else if matches!(event, InputEvent::Mouse(_)) {
813                    // Nothing under the cursor to follow, and this arrived as a
814                    // press. Swallowing it would make the second click of a
815                    // double a silent no-op anywhere but on a link, and would
816                    // claim the gesture buffer-wide for a follow that did not
817                    // happen. Hand it back to the panels as the press it is —
818                    // the same fallback-on-runtime-outcome shape `ImageProbe`
819                    // uses when the clipboard turns out to hold no image.
820                    self.execute_intent(EditorIntent::Mouse, event, tx)
821                } else {
822                    EventState::Consumed
823                }
824            }
825            EditorIntent::LeaderKey(key) => self.handle_leader_key(&key, tx),
826            EditorIntent::LeaderStart => {
827                self.leader.start();
828                self.schedule_whichkey_reveal(tx);
829                EventState::Consumed
830            }
831            EditorIntent::Op(op) => {
832                self.run_op(op, tx);
833                EventState::Consumed
834            }
835            EditorIntent::ToggleOverlay { kind, open } => {
836                if self.overlays.active_kind() == Some(kind) {
837                    self.dismiss_overlay();
838                } else {
839                    self.open_overlay(open, tx);
840                }
841                EventState::Consumed
842            }
843            EditorIntent::OpenOverlay(open) => {
844                self.open_overlay(open, tx);
845                EventState::Consumed
846            }
847            EditorIntent::Overlay => self.overlays.handle_input(event, tx),
848            EditorIntent::Mouse => {
849                // `PanelSet` hit-tests the panel columns: a click focuses the
850                // panel under the cursor (one rule for every panel) and the
851                // event is forwarded to that panel for its internal behavior.
852                let state = self.panels.handle_mouse(event, tx);
853                // Ask clicks (turn select, citation) move the drawer's Sources.
854                self.ask.sync_sources(&mut self.panels, tx);
855                // A selectionless right-click in the editor asks for the
856                // note's context menu — the screen owns the path, so it
857                // opens it here.
858                if self.panels.editor().is_some_and(|e| e.wants_context_menu) {
859                    if let Some(ed) = self.panels.editor_mut() {
860                        ed.wants_context_menu = false;
861                    }
862                    tx.send(AppEvent::FileOp(FileOp::ShowMenu(self.path.clone())))
863                        .ok();
864                }
865                state
866            }
867            EditorIntent::Panel { fallback } => {
868                let state = self.panels.handle_input(event, tx);
869                // Ask keys (j/k select, i/composer, submit) move the drawer's
870                // Sources in step with the thread's selected turn.
871                self.ask.sync_sources(&mut self.panels, tx);
872                if state == EventState::NotConsumed {
873                    match fallback {
874                        PanelFallback::None => state,
875                        PanelFallback::FocusCycle(CycleDir::Right) => {
876                            self.focus_right(tx);
877                            EventState::Consumed
878                        }
879                        PanelFallback::FocusCycle(CycleDir::Left) => {
880                            self.focus_left(tx);
881                            EventState::Consumed
882                        }
883                        PanelFallback::FocusEditor => {
884                            self.focus_editor();
885                            EventState::Consumed
886                        }
887                    }
888                } else {
889                    state
890                }
891            }
892        }
893    }
894
895    fn run_op(&mut self, op: EditorOp, tx: &AppTx) {
896        match op {
897            EditorOp::ToggleDrawer => self.toggle_drawer(tx),
898            EditorOp::FocusLeft => self.focus_left(tx),
899            EditorOp::FocusRight => self.focus_right(tx),
900            EditorOp::OpenJournal => {
901                tx.send(AppEvent::OpenJournal).ok();
902            }
903            EditorOp::ShowFileOps => {
904                tx.send(AppEvent::FileOp(FileOp::ShowMenu(self.path.clone())))
905                    .ok();
906            }
907            EditorOp::ToggleQueryPanel => self.toggle_backlinks(tx),
908            EditorOp::OpenFileBrowserReveal => {
909                self.open_drawer_view(DrawerView::Files, tx);
910                self.reveal_note_dir_in_sidebar(tx);
911            }
912            EditorOp::SaveCurrentQuery => {
913                if let Some((query, provenance, source)) = self.save_query_source() {
914                    // Opening the save dialog replaces the note browser (if
915                    // any); the chained-open guard preserves the original
916                    // opener focus.
917                    self.present_overlay(Box::new(ActiveDialog::save_search(
918                        query,
919                        provenance,
920                        source,
921                        self.vault.clone(),
922                        tx,
923                    )));
924                }
925            }
926            EditorOp::FindInBuffer => {
927                if let Some(ed) = self.panels.editor_mut() {
928                    ed.open_or_advance_search();
929                }
930            }
931            EditorOp::ReplaceInBuffer => {
932                if let Some(ed) = self.panels.editor_mut() {
933                    ed.open_replace();
934                }
935            }
936            EditorOp::ApplyText(text_action) => {
937                if let Some(ed) = self.panels.editor_mut() {
938                    ed.apply_text_action(text_action);
939                }
940            }
941            EditorOp::OpenAsk => self.open_ask_workspace(tx),
942        }
943    }
944
945    /// The one door for every overlay the screen can open: guard (no overlay
946    /// over an open overlay), build the recipe, present it. Opens that need
947    /// more than construction (the Ask workspace's capability gate, drawer
948    /// views) are not overlays and keep their own methods.
949    fn open_overlay(&mut self, open: OverlayOpen, tx: &AppTx) {
950        if self.overlays.is_open() {
951            return;
952        }
953        let overlay = self.build_overlay(open, tx);
954        self.present_overlay(overlay);
955    }
956
957    /// The note the editor area is showing, if any — what every "+this
958    /// note" leader action (`m r`/`m m`/`m d`/`m c`/`m y`/`m i`) acts on.
959    /// `None` on the vault root, in the attachment view (`self.path` is
960    /// then the attachment's path, never a note) and while the Ask
961    /// workspace is up (`self.path` still names the note it replaced, but
962    /// the user is not looking at it). The one definition of "this note",
963    /// so the m-group cannot disagree about it.
964    fn open_note(&self) -> Option<&VaultPath> {
965        if self.panels.is_showing_ask() || !self.path.is_note() {
966            None
967        } else {
968            Some(&self.path)
969        }
970    }
971
972    /// [`Self::open_note`], flashing "no note open" when there is none.
973    fn open_note_or_flash(&self, tx: &AppTx) -> Option<VaultPath> {
974        let note = self.open_note().cloned();
975        if note.is_none() {
976            tx.send(AppEvent::FlashMessage("no note open".into())).ok();
977        }
978        note
979    }
980
981    /// Leader `m i`: pin the open note, or unpin it if pinned. Refused with
982    /// a flash when nothing is open (see [`Self::open_note`]), when the
983    /// open note is no longer on disk, or when the vault already holds the
984    /// cap.
985    fn toggle_pin_open_note(&self, tx: &AppTx) {
986        let Some(path) = self.open_note_or_flash(tx) else {
987            return;
988        };
989        let vault = self.vault.clone();
990        let tx = tx.clone();
991        tokio::spawn(async move {
992            let msg = match vault.toggle_pinned_note(&path).await {
993                Ok(kimun_core::PinToggle::Pinned { position }) => format!(
994                    "pinned as {} of {}",
995                    position + 1,
996                    kimun_core::PINNED_NOTES_CAP
997                ),
998                Ok(kimun_core::PinToggle::Unpinned) => "unpinned".to_string(),
999                Ok(kimun_core::PinToggle::Full) => format!(
1000                    "already {} pinned — unpin one first",
1001                    kimun_core::PINNED_NOTES_CAP
1002                ),
1003                Err(VaultError::FSError(FSError::VaultPathNotFound { .. })) => {
1004                    format!("note not found: {path}")
1005                }
1006                Err(e) => {
1007                    tracing::warn!("failed to toggle pin on {path}: {e}");
1008                    format!("could not update pinned notes: {e}")
1009                }
1010            };
1011            tx.send(AppEvent::FlashMessage(msg)).ok();
1012        });
1013    }
1014
1015    /// Leader digit `n`: open pinned note `n` (1-based). A slot with no pin,
1016    /// or a pin whose note is missing on disk, flashes instead.
1017    fn jump_to_pinned(&self, n: u8, tx: &AppTx) {
1018        let vault = self.vault.clone();
1019        let tx = tx.clone();
1020        tokio::spawn(async move {
1021            let pins = match vault.list_pinned_notes().await {
1022                Ok(pins) => pins,
1023                Err(e) => {
1024                    tx.send(AppEvent::FlashMessage(format!(
1025                        "could not read pinned notes: {e}"
1026                    )))
1027                    .ok();
1028                    return;
1029                }
1030            };
1031            let Some(path) = pins.get(usize::from(n).saturating_sub(1)).cloned() else {
1032                tx.send(AppEvent::FlashMessage(format!("no pinned note {n}")))
1033                    .ok();
1034                return;
1035            };
1036            if !vault.exists(&path).await {
1037                tx.send(AppEvent::FlashMessage(format!(
1038                    "pinned note not found: {path}"
1039                )))
1040                .ok();
1041                return;
1042            }
1043            tx.send(AppEvent::OpenPath {
1044                path,
1045                emphasis: None,
1046            })
1047            .ok();
1048        });
1049    }
1050
1051    /// Construction recipes for [`OverlayOpen`] — the single site answering
1052    /// "what overlays exist and how is each built". Reads screen state (vault,
1053    /// settings, open note, panel sort/order seeds) but never mutates it;
1054    /// presentation and the open-guard live in [`Self::open_overlay`].
1055    fn build_overlay(&self, open: OverlayOpen, tx: &AppTx) -> Box<dyn Overlay> {
1056        let s = self.settings.read().unwrap();
1057        match open {
1058            // The note-browser modal over the full-text search provider
1059            // (Ctrl-K and the leader's find paths).
1060            OverlayOpen::SearchBrowser => {
1061                let provider = resolving_search_source(
1062                    self.vault.clone(),
1063                    s.current_last_paths(),
1064                    Some(self.path.clone()),
1065                );
1066                Box::new(NoteBrowserModal::new(
1067                    "Note Browser",
1068                    BrowserScope::Query,
1069                    provider,
1070                    self.vault.clone(),
1071                    s.key_bindings.clone(),
1072                    s.icons(),
1073                    tx.clone(),
1074                ))
1075            }
1076            // The note-browser modal over the fuzzy file finder (Ctrl-O and
1077            // the leader's `f f`).
1078            OverlayOpen::FileFinder => {
1079                let current_dir = self.path.get_parent_path().0;
1080                let provider = FileFinderProvider::new(self.vault.clone(), current_dir);
1081                Box::new(NoteBrowserModal::new(
1082                    "Find Note",
1083                    BrowserScope::Files,
1084                    provider,
1085                    self.vault.clone(),
1086                    s.key_bindings.clone(),
1087                    s.icons(),
1088                    tx.clone(),
1089                ))
1090            }
1091            // F3 and leader `f s`.
1092            OverlayOpen::SavedSearches => Box::new(SavedSearchesModal::new(
1093                self.vault.clone(),
1094                s.key_bindings.clone(),
1095                s.icons(),
1096                tx.clone(),
1097            )),
1098            // Ctrl+Shift+P and leader `p`.
1099            OverlayOpen::CommandPalette => {
1100                let gateway = s
1101                    .key_bindings
1102                    .first_combo_for(&ActionShortcuts::Leader)
1103                    .unwrap_or_else(|| "leader".to_string());
1104                Box::new(
1105                    crate::components::command_palette::CommandPaletteModal::new(
1106                        &s.leader_tree(),
1107                        &gateway,
1108                        s.icons(),
1109                        tx.clone(),
1110                    ),
1111                )
1112            }
1113            // SwitchWorkspace action and leader `v s`.
1114            OverlayOpen::WorkspaceSwitcher => Box::new(ActiveDialog::workspace_switcher(&s)),
1115            // Leader `v t` and inside CFG via `t`; the full settings screen
1116            // stays on the OpenSettings binding.
1117            OverlayOpen::ThemePicker => Box::new(ActiveDialog::theme_picker(&s)),
1118            OverlayOpen::Help => Box::new(ActiveDialog::help(&s.key_bindings)),
1119            OverlayOpen::QueryHelp => Box::new(ActiveDialog::query_syntax()),
1120            OverlayOpen::Cheatsheet => Box::new(ActiveDialog::cheatsheet(&s)),
1121            OverlayOpen::SortQuery => {
1122                let (field, order) = self.panels.query().current_order();
1123                Box::new(ActiveDialog::sort(SortTarget::Query, field, order, false))
1124            }
1125            OverlayOpen::SortSidebar => {
1126                let (field, order) = self.panels.sidebar().current_sort();
1127                Box::new(ActiveDialog::sort(
1128                    SortTarget::Sidebar,
1129                    field,
1130                    order,
1131                    self.panels.sidebar().group_dirs(),
1132                ))
1133            }
1134            OverlayOpen::QuickNote => Box::new(ActiveDialog::quick_note(self.vault.clone())),
1135            // Leader `f p`.
1136            OverlayOpen::PinnedNotes => {
1137                Box::new(ActiveDialog::pinned_notes(self.vault.clone(), tx))
1138            }
1139        }
1140    }
1141
1142    /// One owner for the self-update lifecycle's display half; the
1143    /// app-global half (persisting dismissals, seeding later screens) lives
1144    /// in the App loop (`app::handle_app_message`).
1145    fn handle_update(&mut self, flow: UpdateFlow, tx: &AppTx) {
1146        match flow {
1147            UpdateFlow::Available(status) => {
1148                self.update = Some(status);
1149            }
1150            UpdateFlow::ShowDialog => {
1151                if let Some(status) = self.update.clone() {
1152                    self.present_overlay(Box::new(ActiveDialog::update(&status)));
1153                }
1154            }
1155            UpdateFlow::Dismiss(_) => {
1156                // Persistence happens in main; here we just drop the indicator.
1157                self.update = None;
1158            }
1159            UpdateFlow::Applied => {
1160                // Installed — drop the notice so the footer/dialog stop offering
1161                // the version we just wrote (restart still required to run it).
1162                self.update = None;
1163            }
1164            UpdateFlow::Apply => {
1165                let tx2 = tx.clone();
1166                tx.send(AppEvent::FlashMessage("Downloading update…".into()))
1167                    .ok();
1168                tokio::spawn(async move {
1169                    let result = async {
1170                        let latest = crate::update::latest_release().await?;
1171                        crate::update::install(latest).await
1172                    }
1173                    .await;
1174                    let msg = match result {
1175                        Ok(()) => {
1176                            tx2.send(AppEvent::Update(UpdateFlow::Applied)).ok();
1177                            "Update installed — restart kimün to apply".to_string()
1178                        }
1179                        Err(e) => format!("Update failed: {e}"),
1180                    };
1181                    tx2.send(AppEvent::FlashMessage(msg)).ok();
1182                });
1183            }
1184        }
1185    }
1186
1187    /// One owner for file operations: requests present the matching dialog,
1188    /// confirmations keep the sidebar and the open note in step.
1189    async fn handle_file_op(&mut self, op: FileOp, tx: &AppTx) {
1190        match op {
1191            FileOp::ShowMenu(path) => {
1192                self.present_overlay(Box::new(ActiveDialog::file_ops_menu(path)));
1193            }
1194            FileOp::ShowDelete(path) => {
1195                self.present_overlay(Box::new(ActiveDialog::delete(path, self.vault.clone())));
1196            }
1197            FileOp::ShowRename(path) => {
1198                self.present_overlay(Box::new(ActiveDialog::rename(path, self.vault.clone())));
1199            }
1200            FileOp::ShowMove(path) => {
1201                self.present_overlay(Box::new(ActiveDialog::move_to(
1202                    path,
1203                    self.vault.clone(),
1204                    tx,
1205                )));
1206            }
1207            FileOp::ShowCreateWithContent { path, content } => {
1208                // The suggested path is derived from a title (an Ask question),
1209                // so unlike the other create-note entry points it is not known
1210                // to be free — and the create behind this dialog avoids
1211                // conflicts by incrementing the name. Resolve that name here so
1212                // the dialog shows the note the user is actually confirming,
1213                // instead of promising `ask/foo.md` and quietly writing
1214                // `ask/foo_0.md`.
1215                let path = self.vault.free_note_path(&path).await;
1216                self.present_overlay(Box::new(ActiveDialog::create_note(
1217                    path,
1218                    self.vault.clone(),
1219                    Some(content),
1220                )));
1221            }
1222            FileOp::Created(path) => {
1223                // Pure notification: a note now exists at `path`. Opening is the
1224                // creator's job (via OpenPath); here we only keep the sidebar in
1225                // step when it is browsing the new note's directory.
1226                self.refresh_sidebar_if_showing(&path.get_parent_path().0, tx);
1227            }
1228            FileOp::Deleted(path) => {
1229                self.on_entry_op(path, tx).await;
1230            }
1231            FileOp::Renamed { from, to } => {
1232                // Note rename → targeted row update (and retarget the editor if
1233                // it is the open note). Directory rename keeps the full reload.
1234                if from.is_note() {
1235                    self.on_note_renamed(from, to, tx).await;
1236                } else {
1237                    self.on_entry_op(from, tx).await;
1238                }
1239            }
1240            FileOp::Moved { from, .. } => {
1241                self.on_entry_op(from, tx).await;
1242            }
1243        }
1244    }
1245
1246    /// One owner for the saved-search save/select flow.
1247    fn handle_saved_search(&mut self, flow: SavedSearchFlow, tx: &AppTx) {
1248        match flow {
1249            SavedSearchFlow::Selected { query, name } => {
1250                // Deliberate non-restoring close: the selection lands in the
1251                // Query panel (set by apply_saved_search), not back on the
1252                // overlay's opener — so close the overlay without dismiss_overlay.
1253                self.overlays.close();
1254                self.apply_saved_search(query, name, tx);
1255            }
1256            SavedSearchFlow::Confirmed {
1257                name,
1258                query,
1259                source,
1260            } => {
1261                // Write in the background; the breadcrumb re-pin waits for
1262                // the success event so the UI never claims an unpersisted
1263                // save (see `Persisted` below).
1264                let vault = self.vault.clone();
1265                let tx = tx.clone();
1266                tokio::spawn(async move {
1267                    match vault.save_search(&name, &query).await {
1268                        Ok(()) => {
1269                            tx.send(AppEvent::SavedSearch(SavedSearchFlow::Persisted {
1270                                name,
1271                                query,
1272                                source,
1273                            }))
1274                            .ok();
1275                        }
1276                        Err(e) => {
1277                            tracing::warn!("failed to save search '{}': {}", name, e);
1278                            tx.send(AppEvent::SavedSearch(SavedSearchFlow::SaveFailed { name }))
1279                                .ok();
1280                        }
1281                    }
1282                });
1283            }
1284            // Re-pin the panel breadcrumb to the saved identity: the edited
1285            // marker drops on an update, the name switches on a save-as-new.
1286            // Only for panel-sourced saves (a note-browser save must not
1287            // steal the panel's provenance, even when the query text
1288            // coincides), and not for the query-as-name fallback (a
1289            // breadcrumb that echoes the query is noise).
1290            SavedSearchFlow::Persisted {
1291                name,
1292                query,
1293                source: SaveSource::QueryPanel,
1294            } if name.trim() != query.trim() => {
1295                self.panels.query_mut().repin_saved_search(name, &query);
1296            }
1297            SavedSearchFlow::Persisted { .. } => {}
1298            SavedSearchFlow::SaveFailed { name } => {
1299                self.footer
1300                    .flash(format!("Failed to save search '{name}'"), tx);
1301            }
1302        }
1303    }
1304
1305    /// The editor-owned singles: everything with exactly one arm and no
1306    /// family. Family events never reach this match.
1307    async fn handle_owned_message(&mut self, msg: AppEvent, tx: &AppTx) {
1308        match msg {
1309            AppEvent::RagStatus(status) => {
1310                let ask_was = self.rag_status.llm_available();
1311                let sem_was = self.rag_status.search_available();
1312                self.rag_status = status;
1313                // Both rail entries are live-status-driven: ASK on whether the
1314                // server can answer questions, SEM on whether it can search.
1315                // Rebuild the rail when either flips (an active view
1316                // stays put when its capability drops — only the rail entry
1317                // goes). The Ask client only needs refreshing on the ASK flip.
1318                let ask_now = status.llm_available();
1319                let sem_now = status.search_available();
1320                if ask_was != ask_now || sem_was != sem_now {
1321                    let (kb, icons) = {
1322                        let s = self.settings.read().unwrap();
1323                        (s.key_bindings.clone(), s.icons())
1324                    };
1325                    self.panels.rebuild_rail(
1326                        kb,
1327                        icons,
1328                        crate::components::activity_rail::RailCaps {
1329                            semantic: sem_now,
1330                            ask: ask_now,
1331                        },
1332                    );
1333                }
1334                if ask_was != ask_now {
1335                    self.ask
1336                        .refresh_capability(&mut self.panels, self.rag_status)
1337                        .await;
1338                }
1339            }
1340            AppEvent::Ask(data) => self.ask.handle_data(&mut self.panels, data, tx),
1341            // Stale completions (for notes we've navigated away from) fall
1342            // through to the catch-all and are dropped.
1343            AppEvent::FlashMessage(msg) => {
1344                self.footer.flash(msg, tx);
1345            }
1346            AppEvent::ExecuteLeaderAction(action) => {
1347                if self.overlays.is_open() {
1348                    // The palette closes itself before sending, so this is
1349                    // unreachable from it — but never drop an action silently.
1350                    tracing::warn!("ExecuteLeaderAction({action:?}) dropped: overlay open");
1351                } else {
1352                    self.execute_leader_action(action, tx);
1353                }
1354            }
1355            AppEvent::ApplyTheme { theme, persist } => {
1356                // The picker resolved the theme already — no disk re-read,
1357                // just adapt to the terminal and swap.
1358                {
1359                    let mut s = self.settings.write().unwrap();
1360                    s.set_theme(theme.name.clone());
1361                }
1362                self.theme = (*theme).adapt_to_terminal();
1363                if persist {
1364                    let snapshot = self.settings.read().unwrap().clone();
1365                    tokio::spawn(async move {
1366                        snapshot.save_to_disk().ok();
1367                    });
1368                }
1369                tx.send(AppEvent::Redraw).ok();
1370            }
1371            // Drawer panels can't emit these under an overlay, but guard
1372            // anyway: never mutate panels while an overlay owns input.
1373            AppEvent::RunTagQuery(label) if !self.overlays.is_open() => {
1374                self.open_find_with_query(format!("#{label}"), None, tx);
1375            }
1376            AppEvent::JumpToHeading(heading) if !self.overlays.is_open() => {
1377                if let Some(ed) = self.panels.editor_mut() {
1378                    ed.jump_to_heading(&heading);
1379                }
1380                self.focus_editor();
1381            }
1382            AppEvent::OpenDrawerView(view) => {
1383                // The rail hides SEM unless the server is reachable for search,
1384                // but the leader path (`drawer.semantic`) can still request it —
1385                // gate here so every route gets the same answer.
1386                if view == DrawerView::Semantic && !self.rag_status.search_available() {
1387                    let msg = if crate::rag::rag_configured(&self.settings) {
1388                        "Semantic search needs a reachable server with an embedder"
1389                    } else {
1390                        "Set kimun_server_url in config to use semantic search"
1391                    };
1392                    tx.send(AppEvent::FlashMessage(msg.into())).ok();
1393                }
1394                // ASK needs an LLM-configured server (the rail hides its entry
1395                // otherwise); gate every route the same way.
1396                else if view == DrawerView::Ask && !self.rag_status.llm_available() {
1397                    tx.send(AppEvent::FlashMessage(
1398                        "Ask needs an LLM-configured server; this one is semantic-search only"
1399                            .into(),
1400                    ))
1401                    .ok();
1402                }
1403                // Selecting the already-active view toggles the drawer closed
1404                // (spec §3: clicking the active rail item toggles).
1405                else if self.panels.is_visible(PanelKind::Drawer)
1406                    && self.panels.active_drawer_view() == view
1407                {
1408                    self.panels.hide(PanelKind::Drawer);
1409                } else {
1410                    self.open_drawer_view(view, tx);
1411                }
1412            }
1413            AppEvent::CloseOverlay => {
1414                // Dismiss-to-opener. Guarded by is_open() on purpose: a
1415                // selection that wants a specific post-close focus
1416                // (OpenPath -> editor, SavedSearchSelected -> Query panel)
1417                // closes the overlay itself first, so a later/!dialog
1418                // CloseOverlay must not re-restore and clobber that focus.
1419                self.dismiss_overlay();
1420            }
1421            AppEvent::SortChanged {
1422                target,
1423                field,
1424                order,
1425                group_directories,
1426                persist,
1427            } => {
1428                match target {
1429                    SortTarget::Sidebar if persist => {
1430                        // Update the sidebar's in-session per-context default AND
1431                        // apply live. `is_current_journal()` is the single source
1432                        // of truth for which context this save targets — reused
1433                        // for the on-disk settings write below.
1434                        let is_journal = self.panels.sidebar().is_current_journal();
1435                        self.panels
1436                            .sidebar_mut()
1437                            .save_default(field, order, group_directories);
1438                        {
1439                            let mut s = self.settings.write().unwrap();
1440                            if is_journal {
1441                                s.journal_sort_field =
1442                                    crate::settings::SortFieldSetting::from(field);
1443                                s.journal_sort_order =
1444                                    crate::settings::SortOrderSetting::from(order);
1445                            } else {
1446                                s.default_sort_field =
1447                                    crate::settings::SortFieldSetting::from(field);
1448                                s.default_sort_order =
1449                                    crate::settings::SortOrderSetting::from(order);
1450                            }
1451                            s.group_directories = group_directories;
1452                        }
1453                        let snapshot = self.settings.read().unwrap().clone();
1454                        tokio::spawn(async move {
1455                            snapshot.save_to_disk().ok();
1456                        });
1457                    }
1458                    SortTarget::Sidebar => {
1459                        self.panels
1460                            .sidebar_mut()
1461                            .apply_sort(field, order, group_directories)
1462                    }
1463                    // The query panel has no persisted default (the order lives
1464                    // in the query string); `persist` is always false here.
1465                    SortTarget::Query => self.panels.query_mut().apply_sort(field, order, tx),
1466                }
1467            }
1468            AppEvent::Autosave => {
1469                self.spawn_autosave(tx);
1470            }
1471            AppEvent::AutosaveCompleted {
1472                path,
1473                saved_revision,
1474                title,
1475            } => {
1476                if path == self.path
1477                    && let Some(rev) = saved_revision
1478                    && let Some(ed) = self.panels.editor_mut()
1479                {
1480                    ed.mark_saved_at_revision(rev);
1481                }
1482                if let Some(raw_title) = title {
1483                    self.note_saved(&path, raw_title);
1484                }
1485                // The write changed the working tree — refresh the git
1486                // segment (throttled).
1487                self.doc_meta.refresh_git(tx);
1488                // `SingleSlotTask::is_in_flight()` flips to false the
1489                // moment the spawned future returns (success or panic),
1490                // so we don't have to clear the slot manually here —
1491                // the next `spawn_autosave` tick will overwrite it.
1492                // Skip explicit cleanup; was previously racy because a
1493                // stale completion arriving after `try_save` had
1494                // already cleared and respawned could wipe the fresh
1495                // handle.
1496            }
1497            AppEvent::FocusSidebar => {
1498                self.focus_sidebar(tx);
1499            }
1500            AppEvent::FollowLink(target) => {
1501                self.follow_link(target, tx).await;
1502            }
1503            AppEvent::FollowLabel(name) => {
1504                let initial = format!("#{name}");
1505                let s = self.settings.read().unwrap();
1506                let provider = resolving_search_source(
1507                    self.vault.clone(),
1508                    s.current_last_paths(),
1509                    Some(self.path.clone()),
1510                );
1511                let modal = NoteBrowserModal::with_initial_query(
1512                    "Note Browser",
1513                    BrowserScope::Query,
1514                    provider,
1515                    self.vault.clone(),
1516                    s.key_bindings.clone(),
1517                    s.icons(),
1518                    tx.clone(),
1519                    initial,
1520                );
1521                drop(s);
1522                self.present_overlay(Box::new(modal));
1523            }
1524            AppEvent::InsertAtCursor(text) if self.panels.focused() == PanelKind::Editor => {
1525                if let Some(ed) = self.panels.editor_mut() {
1526                    ed.insert_at_cursor(&text, tx);
1527                }
1528            }
1529            _ => {}
1530        }
1531    }
1532
1533    pub fn focus_editor(&mut self) {
1534        self.panels.focus(PanelKind::Editor);
1535    }
1536
1537    /// Whether the drawer is open showing `view`.
1538    fn drawer_open_on(&self, view: DrawerView) -> bool {
1539        self.panels.is_visible(PanelKind::Drawer) && self.panels.active_drawer_view() == view
1540    }
1541
1542    /// Reflect the currently-open note (`self.path`) into whichever drawer view
1543    /// is visible (FIND/LINKS/OUTLINE). Shared by `open_path` and
1544    /// `on_note_renamed` so a rename keeps the drawers in step, not just a
1545    /// fresh open.
1546    fn reflect_open_note_in_drawers(&mut self, tx: &AppTx) {
1547        let path = self.path.clone();
1548        if self.drawer_open_on(DrawerView::Find) {
1549            self.panels.query_mut().set_note(path.clone(), tx.clone());
1550        }
1551        if self.panels.is_visible(PanelKind::Drawer) {
1552            match self.panels.active_drawer_view() {
1553                DrawerView::Links => self.panels.links_mut().set_note(path.clone(), tx),
1554                DrawerView::Outline => self.panels.outline_mut().set_note(path, tx),
1555                _ => {}
1556            }
1557        }
1558    }
1559
1560    /// Point the sidebar at the current note's directory. Skips the engine
1561    /// rebuild when the sidebar is already there so an in-progress filter
1562    /// and selection survive a re-open.
1563    fn reveal_note_dir_in_sidebar(&mut self, tx: &AppTx) {
1564        let note_parent = self.path.get_parent_path().0;
1565        if self.panels.sidebar().is_empty()
1566            || !note_parent.is_like(self.panels.sidebar().current_dir())
1567        {
1568            self.navigate_sidebar(note_parent, tx);
1569        }
1570    }
1571
1572    /// Focus the drawer, revealing it on FILES if hidden — but never clobber
1573    /// the view the user already has open (e.g. a FIND query in progress).
1574    /// Sent by the nvim backend's leave-editor motions.
1575    pub fn focus_sidebar(&mut self, tx: &AppTx) {
1576        if !self.panels.is_visible(PanelKind::Drawer) {
1577            // Routed through the host opener so the FILES view reveals the
1578            // current note's directory like any other drawer open (it also
1579            // focuses the drawer).
1580            self.open_drawer_view(DrawerView::Files, tx);
1581        } else {
1582            self.panels.focus(PanelKind::Drawer);
1583        }
1584    }
1585
1586    /// Switch the drawer to `view`, reveal it, and focus it. The per-view
1587    /// reveal side effects live in `drawer_view_revealed` (the heavy work
1588    /// that keeps the reveal in the host rather than in `PanelSet`).
1589    fn open_drawer_view(&mut self, view: DrawerView, tx: &AppTx) {
1590        // Keep the editor-area Ask content in lockstep with the drawer view:
1591        // entering ASK restores the stashed thread; leaving it stashes the
1592        // live one (rules 1 & 2 — thread survives every view switch).
1593        self.ask.transition(&mut self.panels, view, tx);
1594        let newly_shown = !self.drawer_open_on(view);
1595        self.panels.open_drawer_view(view);
1596        self.drawer_view_revealed(view, newly_shown, tx);
1597        // The ASK workspace lives in the editor area; drop the user on the
1598        // composer rather than the Sources drawer. Every other view focuses
1599        // the drawer as before.
1600        if view == DrawerView::Ask {
1601            self.panels.focus(PanelKind::Editor);
1602        } else {
1603            self.panels.focus(PanelKind::Drawer);
1604        }
1605    }
1606
1607    /// Ensure the Ask workspace is the editor-area content, for the leader
1608    /// `a` conversation actions. Ungated: managing an existing thread works
1609    /// even when the server can't answer (the composer stays disabled).
1610    fn ensure_ask_workspace(&mut self, tx: &AppTx) {
1611        if !self.panels.is_showing_ask() {
1612            self.open_drawer_view(DrawerView::Ask, tx);
1613        }
1614    }
1615
1616    /// Ensure the Ask workspace is showing, then run `f` against its live
1617    /// panel — the shared shape behind the leader `a n`/`a y`/`a e`/`a r`
1618    /// conversation actions.
1619    fn with_ask_panel(&mut self, tx: &AppTx, f: impl FnOnce(&mut ThreadPanel, &AppTx)) {
1620        self.ensure_ask_workspace(tx);
1621        f(self.panels.ask_mut(), tx);
1622    }
1623
1624    /// Per-view side effects to run when `view` becomes visible in the
1625    /// drawer — the single table shared by every reveal path (rail/leader
1626    /// opens, the Ctrl-T toggle restore) so a view cannot go stale on one
1627    /// path and refresh on another. `newly_shown` gates the effects that
1628    /// must not clobber state the user already has on screen (an
1629    /// in-progress FIND query, a browsed sidebar directory); the rest
1630    /// refresh unconditionally. Never touches focus — callers decide that.
1631    fn drawer_view_revealed(&mut self, view: DrawerView, newly_shown: bool, tx: &AppTx) {
1632        match view {
1633            DrawerView::Find if newly_shown => {
1634                self.panels
1635                    .query_mut()
1636                    .set_note(self.path.clone(), tx.clone());
1637            }
1638            DrawerView::Files if newly_shown => {
1639                self.reveal_note_dir_in_sidebar(tx);
1640            }
1641            DrawerView::Config => {
1642                let info = {
1643                    let s = self.settings.read().unwrap();
1644                    let key_of = |a: &ActionShortcuts| {
1645                        s.key_bindings
1646                            .first_combo_for(a)
1647                            .unwrap_or_else(|| "unbound".to_string())
1648                    };
1649                    crate::components::drawer::ConfigInfo {
1650                        theme_name: s.get_theme().name,
1651                        leader_key: key_of(&ActionShortcuts::Leader),
1652                        preferences_key: key_of(&ActionShortcuts::OpenPreferences),
1653                        leader_timeout_ms: s.leader_timeout_ms,
1654                        config_path: s
1655                            .config_file
1656                            .as_ref()
1657                            .map(|p| p.display().to_string())
1658                            .unwrap_or_else(|| "default location".to_string()),
1659                    }
1660                };
1661                self.panels.drawer_set_config_info(info);
1662            }
1663            DrawerView::Semantic => self.panels.semantic_mut().ensure_source(tx),
1664            DrawerView::Tags => self.panels.tags_mut().refresh(tx),
1665            DrawerView::Links => self.panels.links_mut().set_note(self.path.clone(), tx),
1666            DrawerView::Outline => self.panels.outline_mut().set_note(self.path.clone(), tx),
1667            _ => {}
1668        }
1669    }
1670
1671    /// Move focus one visible panel left, wrapping at the end.
1672    fn focus_left(&mut self, _tx: &AppTx) {
1673        if let Some(kind) = self.panels.prev_kind() {
1674            self.panels.focus(kind);
1675        }
1676    }
1677
1678    /// Move focus one visible panel right, wrapping at the end.
1679    fn focus_right(&mut self, _tx: &AppTx) {
1680        if let Some(kind) = self.panels.next_kind() {
1681            self.panels.focus(kind);
1682        }
1683    }
1684
1685    /// Toggle the drawer (Ctrl-T): hiding it gives the full remaining width
1686    /// to the editor; showing it restores the last view. Restoring is a
1687    /// fresh reveal: the restored view re-targets/refreshes via the shared
1688    /// `drawer_view_revealed` table — the note (or its data) may have
1689    /// changed while hidden. Unlike an explicit open, toggling never moves
1690    /// focus into the drawer.
1691    fn toggle_drawer(&mut self, tx: &AppTx) {
1692        if self.panels.is_visible(PanelKind::Drawer) {
1693            self.panels.hide(PanelKind::Drawer);
1694        } else {
1695            self.panels.show(PanelKind::Drawer);
1696            self.drawer_view_revealed(self.panels.active_drawer_view(), true, tx);
1697        }
1698    }
1699
1700    /// The query the save-current-query action would save, with its
1701    /// saved-search provenance (breadcrumb name) for the dialog's name
1702    /// pre-fill. Sourced from the active note browser if one is open (Ctrl+K
1703    /// modal), otherwise from the Query panel. `None` when there is nothing
1704    /// to save: a blank query, or another overlay is open.
1705    fn save_query_source(&self) -> Option<(String, Option<String>, SaveSource)> {
1706        let (query, provenance, source) = match self.overlays.active_kind() {
1707            Some(OverlayKind::NoteBrowser) => (
1708                self.overlays.active_query().unwrap_or_default().to_string(),
1709                self.overlays
1710                    .active_saved_search_provenance()
1711                    .map(str::to_string),
1712                SaveSource::NoteBrowser,
1713            ),
1714            None => (
1715                self.panels.query().active_query().to_string(),
1716                self.panels.query().saved_search_name().map(str::to_string),
1717                SaveSource::QueryPanel,
1718            ),
1719            Some(_) => return None,
1720        };
1721        if query.trim().is_empty() {
1722            None
1723        } else {
1724            Some((query, provenance, source))
1725        }
1726    }
1727
1728    /// Schedule a redraw for when the which-key overlay should reveal: the
1729    /// hesitation timeout after the sequence (re)advanced. Fluent typing
1730    /// never sees the overlay; the timer redraw simply finds the sequence
1731    /// already gone.
1732    fn schedule_whichkey_reveal(&self, tx: &AppTx) {
1733        let timeout = {
1734            let s = self.settings.read().unwrap();
1735            std::time::Duration::from_millis(s.leader_timeout_ms)
1736        };
1737        let tx2 = tx.clone();
1738        tokio::spawn(async move {
1739            tokio::time::sleep(timeout + std::time::Duration::from_millis(10)).await;
1740            let _ = tx2.send(AppEvent::Redraw);
1741        });
1742    }
1743
1744    /// Switch to the Ask workspace and drop the cursor on the composer (the
1745    /// Ask shortcut / leader `a a`). The rail hides the ASK entry when the
1746    /// server can't answer questions, so this shortcut is the only remaining
1747    /// way in — hence the `llm_available` gate. The gate only
1748    /// applies to that enter-from-outside path: when Ask is already showing,
1749    /// focusing the composer is ungated, matching the sibling `a n`/`a
1750    /// y`/`a e`/`a r` actions, which work fine on a degraded (capability-off)
1751    /// thread.
1752    fn open_ask_workspace(&mut self, tx: &AppTx) {
1753        if self.overlays.is_open() {
1754            return;
1755        }
1756        if !self.panels.is_showing_ask() {
1757            if !self.rag_status.llm_available() {
1758                tx.send(AppEvent::FlashMessage(
1759                    "Ask needs an LLM-configured server; this one is semantic-search only".into(),
1760                ))
1761                .ok();
1762                return;
1763            }
1764            self.open_drawer_view(DrawerView::Ask, tx);
1765        }
1766        self.panels.ask_mut().focus_composer();
1767        self.panels.focus(PanelKind::Editor);
1768    }
1769
1770    /// Follow the **follow target** under the editor cursor (FollowLink action,
1771    /// Ctrl+Enter on kitty-protocol terminals).
1772    ///
1773    /// Returns whether anything was actually followed, so a caller that only
1774    /// *guessed* there was something there can fall back. A double-click is
1775    /// exactly that guess: the classifier cannot hit-test the buffer, so it
1776    /// asks and lets the answer decide.
1777    fn follow_link_at_cursor(&mut self, tx: &AppTx) -> bool {
1778        use crate::components::text_editor::FollowTarget;
1779        // In the attachment view, FollowLink (Ctrl+N) opens the attachment with
1780        // the OS default program rather than following a link (there is none).
1781        if self.panels.is_showing_attachment() {
1782            self.open_attachment_externally(tx);
1783            return true;
1784        }
1785        let Some(editor) = self.panels.editor_mut() else {
1786            return false;
1787        };
1788        match editor.follow_target_at_cursor() {
1789            Some(FollowTarget::Link(target)) => {
1790                tx.send(AppEvent::FollowLink(target)).ok();
1791                true
1792            }
1793            Some(FollowTarget::Label(name)) => {
1794                tx.send(AppEvent::FollowLabel(name)).ok();
1795                true
1796            }
1797            None => false,
1798        }
1799    }
1800
1801    /// Opens the attachment currently shown in the editor area with the OS
1802    /// default program (the same handoff `follow_link` uses for image links).
1803    fn open_attachment_externally(&mut self, tx: &AppTx) {
1804        let Some(path) = self.panels.attachment_path() else {
1805            return;
1806        };
1807        let os_path = self.vault.path_to_pathbuf(path);
1808        match open::that_detached(&os_path) {
1809            Ok(()) => self
1810                .footer
1811                .flash(format!("Opening {}", os_path.display()), tx),
1812            Err(e) => self.footer.flash(format!("Cannot open: {e}"), tx),
1813        }
1814    }
1815
1816    /// One key of a pending leader sequence. Esc cancels (focus returns to
1817    /// the editor), Backspace steps up, chars walk the tree, a fired leaf
1818    /// executes. Everything is consumed — a pending sequence owns the
1819    /// keyboard.
1820    fn handle_leader_key(
1821        &mut self,
1822        key: &ratatui::crossterm::event::KeyEvent,
1823        tx: &AppTx,
1824    ) -> EventState {
1825        use ratatui::crossterm::event::{KeyCode, KeyModifiers};
1826        match key.code {
1827            KeyCode::Esc => {
1828                self.leader.cancel();
1829                self.focus_editor();
1830            }
1831            KeyCode::Backspace => {
1832                let outcome = self.leader.step_up();
1833                // Stepping past the root cancels — no reveal to re-arm then.
1834                if outcome == LeaderOutcome::SteppedUp {
1835                    self.schedule_whichkey_reveal(tx);
1836                }
1837            }
1838            KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
1839                match self.leader.feed(c) {
1840                    LeaderOutcome::Fired(action) => self.execute_leader_action(action, tx),
1841                    LeaderOutcome::Invalid => {
1842                        // Gentle feedback; the sequence stays pending.
1843                        self.footer.flash(format!("leader: no entry for '{c}'"), tx);
1844                        self.schedule_whichkey_reveal(tx);
1845                    }
1846                    LeaderOutcome::Descended => self.schedule_whichkey_reveal(tx),
1847                    _ => {}
1848                }
1849            }
1850            // Other keys (arrows, function keys, …) are swallowed; the
1851            // sequence stays pending. Ctrl-chords never reach here — the
1852            // intercept in handle_input cancels and re-dispatches them.
1853            _ => {}
1854        }
1855        tx.send(AppEvent::Redraw).ok();
1856        EventState::Consumed
1857    }
1858
1859    /// Execute a fired leader leaf. Stubs for surfaces that land in later
1860    /// phases flash a "coming soon" notice instead of silently doing nothing.
1861    fn execute_leader_action(&mut self, action: LeaderAction, tx: &AppTx) {
1862        match action {
1863            LeaderAction::OpenDrawer(view) => self.open_drawer_view(view, tx),
1864
1865            LeaderAction::AppCheckUpdates => {
1866                if let Some(status) = self.update.clone() {
1867                    self.present_overlay(Box::new(ActiveDialog::update(&status)));
1868                } else {
1869                    // No cached notice — run a forced check and report the result.
1870                    let tx2 = tx.clone();
1871                    tx.send(AppEvent::FlashMessage("Checking for updates…".into()))
1872                        .ok();
1873                    tokio::spawn(async move {
1874                        let Ok(config_dir) = crate::settings::config_dir() else {
1875                            return;
1876                        };
1877                        match crate::update::check_now(config_dir, true).await {
1878                            Ok(Some(status)) if status.update_available => {
1879                                // Manual check: surface the notice AND open the
1880                                // dialog the user explicitly asked for (shown even
1881                                // if previously skipped — they asked).
1882                                tx2.send(AppEvent::Update(UpdateFlow::Available(status)))
1883                                    .ok();
1884                                tx2.send(AppEvent::Update(UpdateFlow::ShowDialog)).ok();
1885                            }
1886                            Ok(_) => {
1887                                tx2.send(AppEvent::FlashMessage("kimün is up to date".into()))
1888                                    .ok();
1889                            }
1890                            Err(e) => {
1891                                tx2.send(AppEvent::FlashMessage(format!(
1892                                    "Update check failed: {e}"
1893                                )))
1894                                .ok();
1895                            }
1896                        }
1897                    });
1898                }
1899            }
1900
1901            // +find — list-style leaves route to today's pickers; the
1902            // telescope modal takes them over in phase 08.
1903            LeaderAction::FindFiles => self.open_overlay(OverlayOpen::FileFinder, tx),
1904            LeaderAction::FindGrep => self.open_overlay(OverlayOpen::SearchBrowser, tx),
1905            LeaderAction::FindTags => self.open_drawer_view(DrawerView::Tags, tx),
1906            LeaderAction::FindBacklinks => {
1907                self.open_find_with_query("<{note}".to_string(), None, tx)
1908            }
1909            LeaderAction::FindSaved => self.open_overlay(OverlayOpen::SavedSearches, tx),
1910            LeaderAction::FindRecent => self.open_overlay(OverlayOpen::SearchBrowser, tx),
1911            LeaderAction::FindHeadings => self.open_drawer_view(DrawerView::Outline, tx),
1912
1913            // +note
1914            LeaderAction::NoteNew => {
1915                // The FILES filter doubles as the create field (typing a new
1916                // name offers "Create: …"); the telescope picker (08) gives
1917                // this a dedicated door.
1918                self.open_drawer_view(DrawerView::Files, tx);
1919                self.footer
1920                    .flash("type a name — Enter creates".to_string(), tx);
1921            }
1922            LeaderAction::NoteDaily => {
1923                tx.send(AppEvent::OpenJournal).ok();
1924            }
1925            LeaderAction::NoteFromTemplate => {
1926                self.footer.flash("templates — coming soon".to_string(), tx);
1927            }
1928            LeaderAction::NoteRename => {
1929                if let Some(path) = self.open_note_or_flash(tx) {
1930                    tx.send(AppEvent::FileOp(FileOp::ShowRename(path))).ok();
1931                }
1932            }
1933            LeaderAction::NoteMove => {
1934                if let Some(path) = self.open_note_or_flash(tx) {
1935                    tx.send(AppEvent::FileOp(FileOp::ShowMove(path))).ok();
1936                }
1937            }
1938            LeaderAction::NoteDelete => {
1939                if let Some(path) = self.open_note_or_flash(tx) {
1940                    tx.send(AppEvent::FileOp(FileOp::ShowDelete(path))).ok();
1941                }
1942            }
1943
1944            // +links
1945            LeaderAction::LinksTab(tab) => {
1946                self.open_drawer_view(DrawerView::Links, tx);
1947                self.panels.links_mut().show_tab(tab, tx);
1948            }
1949            LeaderAction::LinksGraph => {
1950                self.footer
1951                    .flash("local graph — coming soon".to_string(), tx);
1952            }
1953
1954            // +git/sync — status is live; the rest are display-only stubs
1955            // (spec §12 keeps git interactions out of scope).
1956            LeaderAction::GitStatus => {
1957                self.doc_meta.refresh_git(tx);
1958                let msg = self
1959                    .doc_meta
1960                    .git()
1961                    .cloned()
1962                    .unwrap_or_else(|| "not a git repository".to_string());
1963                self.footer.flash(msg, tx);
1964            }
1965            LeaderAction::GitSync | LeaderAction::GitLog | LeaderAction::GitDiff => {
1966                self.footer
1967                    .flash("git is display-only for now".to_string(), tx);
1968            }
1969
1970            // +vault
1971            LeaderAction::VaultSwitch => self.open_overlay(OverlayOpen::WorkspaceSwitcher, tx),
1972            LeaderAction::VaultReindex => {
1973                // Fast reindex right here — the same pipeline the Settings
1974                // screen runs, result surfaced as a footer flash.
1975                let vault = self.vault.clone();
1976                let tx2 = tx.clone();
1977                self.footer.flash("reindexing…".to_string(), tx);
1978                tokio::spawn(async move {
1979                    let started = std::time::Instant::now();
1980                    let result = vault.index_notes(kimun_core::NotesValidation::Fast).await;
1981                    let msg = match result {
1982                        Ok(_) => format!("reindexed in {:.1?}", started.elapsed()),
1983                        Err(e) => format!("reindex failed: {e}"),
1984                    };
1985                    tx2.send(AppEvent::FlashMessage(msg)).ok();
1986                });
1987            }
1988            // `v c` opens the config panel (the CFG drawer); `v t` opens the
1989            // theme picker directly (also reachable inside CFG via `t`).
1990            LeaderAction::VaultConfig => self.open_drawer_view(DrawerView::Config, tx),
1991            LeaderAction::VaultTheme => self.open_overlay(OverlayOpen::ThemePicker, tx),
1992            LeaderAction::VaultPreferences => {
1993                tx.send(AppEvent::OpenScreen(ScreenEvent::OpenPreferences))
1994                    .ok();
1995            }
1996            LeaderAction::AppOnboarding => {
1997                tx.send(AppEvent::OpenScreen(ScreenEvent::OpenOnboarding))
1998                    .ok();
1999            }
2000
2001            // +window
2002            LeaderAction::WindowZen => {
2003                self.panels.hide(PanelKind::Drawer);
2004                self.focus_editor();
2005            }
2006            LeaderAction::WindowSplit => {
2007                self.footer
2008                    .flash("editor splits — coming soon".to_string(), tx);
2009            }
2010            LeaderAction::WindowGrowDrawer => self.panels.adjust_drawer_width(4),
2011            LeaderAction::WindowShrinkDrawer => self.panels.adjust_drawer_width(-4),
2012
2013            // +this note
2014            LeaderAction::NoteToggleTodo => {
2015                self.footer
2016                    .flash("toggle todo — coming soon".to_string(), tx);
2017            }
2018            LeaderAction::NotePreview => {
2019                self.footer
2020                    .flash("preview — lands with phase 09".to_string(), tx);
2021            }
2022            LeaderAction::NoteCopyWikilink => {
2023                if let Some(path) = self.open_note_or_flash(tx) {
2024                    let link = format!("[[{}]]", path.get_clean_name());
2025                    crate::components::yank(link, "wikilink copied", tx);
2026                }
2027            }
2028            LeaderAction::NoteExport => {
2029                self.footer.flash("export — coming soon".to_string(), tx);
2030            }
2031            LeaderAction::NoteYankPath => {
2032                if let Some(path) = self.open_note_or_flash(tx) {
2033                    crate::components::yank(path.to_string(), "note path copied", tx);
2034                }
2035            }
2036
2037            // +ask — the Ask workspace's conversation actions.
2038            LeaderAction::AskFocus => self.open_ask_workspace(tx),
2039            LeaderAction::AskNew => {
2040                self.with_ask_panel(tx, |panel, _tx| {
2041                    panel.thread_mut().clear();
2042                    panel.focus_composer();
2043                });
2044                self.panels.ask_sources_mut().reset(tx);
2045            }
2046            LeaderAction::AskCopy => {
2047                self.with_ask_panel(tx, |panel, tx| panel.copy_selected(tx));
2048            }
2049            LeaderAction::AskSave => {
2050                self.with_ask_panel(tx, |panel, tx| panel.save_selected(tx));
2051            }
2052            LeaderAction::AskRegenerate => {
2053                self.with_ask_panel(tx, |panel, tx| panel.regenerate_selected(tx));
2054                self.ask.sync_sources(&mut self.panels, tx);
2055            }
2056            LeaderAction::AskSource => {
2057                self.ensure_ask_workspace(tx);
2058                // The top source of the selected turn — sync the drawer to the
2059                // current turn first, then open its first source in the reader.
2060                self.ask.sync_sources_from_selected(&mut self.panels, tx);
2061                self.panels.ask_sources_mut().open_reader(0, tx);
2062                self.panels.focus(PanelKind::Drawer);
2063            }
2064
2065            LeaderAction::Palette => self.open_overlay(OverlayOpen::CommandPalette, tx),
2066            LeaderAction::Help => self.open_overlay(OverlayOpen::Cheatsheet, tx),
2067
2068            LeaderAction::NoteSave => {
2069                // Flush the periodic autosave immediately (no manual-save
2070                // concept; this force-persists the current buffer if dirty).
2071                self.spawn_autosave(tx);
2072            }
2073            LeaderAction::AppQuit => {
2074                tx.send(AppEvent::Quit).ok();
2075            }
2076
2077            // +pinned
2078            LeaderAction::FindPinned => self.open_overlay(OverlayOpen::PinnedNotes, tx),
2079            LeaderAction::NoteTogglePin => self.toggle_pin_open_note(tx),
2080            LeaderAction::PinnedJump(n) => self.jump_to_pinned(n, tx),
2081        }
2082    }
2083
2084    /// Kick off the async loads behind status line 2: the open note's
2085    /// backlink count and the workspace git summary. Results return as
2086    /// `BacklinkCountLoaded` / `GitStatusLoaded`; stale backlink completions
2087    /// are dropped by path. Contract: this runs when a note is *opened* (and
2088    /// the git half on autosave) — counts can go stale while a note stays
2089    /// open and another note adds a link to it; accepted for now.
2090    /// The one path that reveals FIND with a concrete query: used by saved
2091    /// searches and tag queries so they cannot drift on what "open FIND"
2092    /// means.
2093    fn open_find_with_query(&mut self, query: String, name: Option<String>, tx: &AppTx) {
2094        self.panels.open_drawer_view(DrawerView::Find);
2095        self.panels.query_mut().apply_query(query, name, tx.clone());
2096        self.panels.focus(PanelKind::Drawer);
2097    }
2098
2099    fn apply_saved_search(&mut self, query: String, name: String, tx: &AppTx) {
2100        // The virtual backlinks entry's name should not override the
2101        // default "Backlinks" title — but the panel's title logic already
2102        // shows "Backlinks" whenever the active query is `<{note}`, so it's
2103        // safe to always pass the name through.
2104        self.open_find_with_query(query, Some(name), tx);
2105    }
2106
2107    fn toggle_backlinks(&mut self, tx: &AppTx) {
2108        if self.drawer_open_on(DrawerView::Find) {
2109            self.panels.hide(PanelKind::Drawer);
2110        } else {
2111            self.open_drawer_view(DrawerView::Find, tx);
2112        }
2113    }
2114}
2115
2116#[async_trait]
2117impl AppScreen for EditorScreen {
2118    fn get_kind(&self) -> ScreenKind {
2119        ScreenKind::Editor
2120    }
2121
2122    async fn on_enter(&mut self, tx: &AppTx) {
2123        self.app_tx = Some(tx.clone());
2124        self.open_path(self.path.clone(), None, tx).await;
2125    }
2126
2127    fn handle_input(&mut self, event: &InputEvent, tx: &AppTx) -> EventState {
2128        // Classify first, mutate after: the pure classifier resolves the
2129        // event against the input precedence (see `editor_input`), and the
2130        // executor methods below apply the resulting intent.
2131        //
2132        // The click run is fed ahead of the snapshot — it is the one piece of
2133        // input-relevant state the event itself advances, and the classifier
2134        // cannot advance it and stay pure. Nothing user-visible moves here.
2135        let double_click = self.track_click(event, std::time::Instant::now());
2136        let ctx = self.input_ctx(double_click);
2137        // The settings lock guards the key bindings, which only the
2138        // shortcut tier reads — never lock for mouse/paste traffic (mouse
2139        // motion is high-frequency).
2140        let classification = if matches!(event, InputEvent::Key(_)) {
2141            let s = self.settings.read().unwrap();
2142            classify(event, &s.key_bindings, &ctx)
2143        } else {
2144            classify(event, &KeyBindings::empty(), &ctx)
2145        };
2146        self.apply_classification(classification, event, tx)
2147    }
2148
2149    fn render(&mut self, f: &mut ratatui::Frame) {
2150        let theme = &self.theme;
2151        f.render_widget(
2152            ratatui::widgets::Block::default().style(theme.base_style()),
2153            f.area(),
2154        );
2155
2156        let rows = Layout::default()
2157            .direction(Direction::Vertical)
2158            .constraints([
2159                Constraint::Length(1),
2160                Constraint::Min(0),
2161                Constraint::Length(crate::components::footer_bar::STATUS_BAR_HEIGHT),
2162            ])
2163            .split(f.area());
2164
2165        // ── Title bar (1 line): Kimün · note breadcrumb · workspace badge ──
2166        // Build the badge line once; its column width comes from the same
2167        // value that gets rendered, so glyph/separator tweaks can't drift.
2168        let workspace_badge = {
2169            let s = self.settings.read().unwrap();
2170            s.workspace_config.as_ref().map(|wc| {
2171                ratatui::text::Line::from(vec![
2172                    ratatui::text::Span::styled(
2173                        self.icons.workspace,
2174                        Style::default().fg(theme.accent.to_ratatui()),
2175                    ),
2176                    ratatui::text::Span::styled(
2177                        format!("  {}", wc.global.current_workspace),
2178                        Style::default().fg(theme.gray.to_ratatui()),
2179                    ),
2180                ])
2181            })
2182        };
2183        let workspace_label_width = workspace_badge
2184            .as_ref()
2185            .map(ratatui::text::Line::width)
2186            .unwrap_or_default();
2187        let breadcrumb = self
2188            .path
2189            .to_string()
2190            .trim_start_matches('/')
2191            .replace('/', " / ");
2192        let title_cols = Layout::default()
2193            .direction(Direction::Horizontal)
2194            .constraints([
2195                Constraint::Min(0),
2196                Constraint::Length(workspace_label_width as u16 + 2),
2197            ])
2198            .split(rows[0]);
2199        f.render_widget(
2200            Paragraph::new(ratatui::text::Line::from(vec![
2201                ratatui::text::Span::styled(
2202                    " Kimün ",
2203                    Style::default()
2204                        .fg(theme.accent.to_ratatui())
2205                        .add_modifier(ratatui::style::Modifier::BOLD),
2206                ),
2207                ratatui::text::Span::styled(
2208                    format!("─  {breadcrumb}"),
2209                    Style::default().fg(theme.fg_secondary.to_ratatui()),
2210                ),
2211            ])),
2212            title_cols[0],
2213        );
2214        if let Some(badge) = workspace_badge {
2215            f.render_widget(
2216                Paragraph::new(badge).alignment(ratatui::layout::Alignment::Right),
2217                title_cols[1],
2218            );
2219        }
2220
2221        // The panels lay themselves out and render. No panel shows its
2222        // focused highlight while an overlay sits over them.
2223        self.panels
2224            .render(f, rows[1], theme, !self.overlays.is_open());
2225
2226        // Status bar reflects the overlay if one is open, otherwise the
2227        // focused panel. `editing` drives the ⌨/≣ focus-context indicator —
2228        // true when a text field holds the cursor.
2229        let (focus_label, hints) = if let Some(kind) = self.overlays.active_kind() {
2230            (kind.label(), self.overlays.hint_shortcuts())
2231        } else {
2232            (self.panels.focused_label(), self.panels.focused_hints())
2233        };
2234        let editing = if let Some(kind) = self.overlays.active_kind() {
2235            // Browsers and the saved-searches modal host a query input;
2236            // dialogs are button/list selections.
2237            !matches!(kind, OverlayKind::Dialog)
2238        } else {
2239            match self.panels.focused() {
2240                PanelKind::Editor => true,
2241                PanelKind::Drawer => self.panels.drawer_is_text_input(),
2242                PanelKind::Rail => false,
2243            }
2244        };
2245        let path_str = self.path.to_string();
2246        // Link-under-cursor affordance (spec §5.2): `→ target · N backlinks`.
2247        // The backlink count loads async, cached per target.
2248        let link_segment = if self.panels.focused() == PanelKind::Editor && !self.overlays.is_open()
2249        {
2250            let link = self
2251                .panels
2252                .editor()
2253                .and_then(|e| e.follow_target_at_cursor());
2254            self.doc_meta
2255                .link_segment(link.as_ref(), &self.path, self.app_tx.as_ref())
2256        } else {
2257            None
2258        };
2259        // ln/col only when the editor buffer holds the cursor (not the
2260        // attachment view, which has none).
2261        let ln_col = (self.panels.focused() == PanelKind::Editor && !self.overlays.is_open())
2262            .then(|| {
2263                self.panels.editor().map(|e| {
2264                    let (row, col) = e.cursor_pos();
2265                    (row + 1, col + 1)
2266                })
2267            })
2268            .flatten();
2269        // Match count when the FIND drawer is the focused query context.
2270        let matches = (self.panels.focused() == PanelKind::Drawer
2271            && self.panels.active_drawer_view() == DrawerView::Find)
2272            .then(|| self.panels.query().result_count());
2273        let (global_hints, leader_timeout, gateway_label) = {
2274            let s = self.settings.read().unwrap();
2275            (
2276                crate::components::hints::global_hints(&s.key_bindings),
2277                std::time::Duration::from_millis(s.leader_timeout_ms),
2278                s.key_bindings
2279                    .first_combo_for(&ActionShortcuts::Leader)
2280                    .unwrap_or_else(|| "leader".to_string()),
2281            )
2282        };
2283        let ctx = crate::components::footer_bar::StatusContext {
2284            focus_label,
2285            editing,
2286            hints: &hints,
2287            global_hints: &global_hints,
2288            doc: crate::components::footer_bar::DocState {
2289                path: &path_str,
2290                dirty: self.panels.editor().is_some_and(|e| e.is_dirty()),
2291                ln_col,
2292                backlinks: self.doc_meta.backlinks(),
2293                git: self.doc_meta.git().cloned(),
2294                matches,
2295                link: link_segment,
2296                update: self
2297                    .update
2298                    .as_ref()
2299                    .map(|u| format!("⬆ {} available", u.latest)),
2300                rag: self.rag_status.label().map(|s| s.to_string()),
2301            },
2302        };
2303        self.footer.render(f, rows[2], theme, &ctx);
2304
2305        // which-key overlay — docked above the status bar once the user
2306        // hesitates mid-sequence (spec §8b).
2307        let whichkey_visible = self
2308            .leader
2309            .pending_since()
2310            .is_some_and(|since| since.elapsed() >= leader_timeout);
2311        if whichkey_visible {
2312            let gateway = gateway_label;
2313            let area = f.area();
2314            let h = crate::components::which_key::desired_height(&self.leader, area.width)
2315                .min(rows[1].height);
2316            let rect =
2317                ratatui::layout::Rect::new(area.x, rows[2].y.saturating_sub(h), area.width, h);
2318            crate::components::which_key::render(f, rect, theme, &self.leader, &gateway);
2319        }
2320
2321        // Overlay — rendered last so it appears on top of everything.
2322        self.overlays.render(f, f.area(), &self.theme);
2323    }
2324
2325    async fn handle_app_message(&mut self, msg: AppEvent, tx: &AppTx) {
2326        match msg {
2327            // Overlay data belongs to the open overlay alone (see CONTEXT.md):
2328            // route it there and stop. `NotConsumed` — no overlay open, or not
2329            // the kind the data was addressed to — means the result is stale;
2330            // it is dropped here and nothing else ever sees it.
2331            AppEvent::OverlayData(data) => {
2332                self.overlays.handle_data(&data, &self.vault, tx);
2333            }
2334            AppEvent::Update(flow) => self.handle_update(flow, tx),
2335            AppEvent::FileOp(op) => self.handle_file_op(op, tx).await,
2336            AppEvent::SavedSearch(flow) => self.handle_saved_search(flow, tx),
2337            msg => {
2338                // Async status results (backlink count, git, link meta) are
2339                // DocMeta's; everything else reaches the owned match.
2340                let Some(msg) = self.doc_meta.handle(msg, &self.path) else {
2341                    return;
2342                };
2343                self.handle_owned_message(msg, tx).await;
2344            }
2345        }
2346    }
2347
2348    /// The editor handles every path itself: notes open in the buffer,
2349    /// directories navigate the sidebar. Always consumes.
2350    async fn try_open_path(
2351        &mut self,
2352        path: VaultPath,
2353        emphasis: Option<Vec<String>>,
2354        tx: &AppTx,
2355    ) -> Option<VaultPath> {
2356        self.dismiss_overlay();
2357        if path.is_note() {
2358            self.open_path(path, emphasis, tx).await;
2359            self.focus_editor();
2360        } else {
2361            self.navigate_sidebar(path, tx);
2362        }
2363        None
2364    }
2365
2366    async fn try_open_attachment(&mut self, path: VaultPath, tx: &AppTx) -> Option<VaultPath> {
2367        self.dismiss_overlay();
2368        self.open_attachment(path, tx).await;
2369        None
2370    }
2371
2372    async fn on_exit(&mut self, _tx: &AppTx) {
2373        self.try_save().await;
2374    }
2375}
2376
2377#[cfg(test)]
2378mod tests {
2379    use super::*;
2380    use crate::keys::key_event_to_combo;
2381
2382    /// Compile-time test: `PanelKind` and `OverlayKind` are usable here.
2383    #[test]
2384    fn panel_kind_labels_and_overlay_kind_compile() {
2385        assert_eq!(PanelKind::Editor.label(), "EDITOR");
2386        assert_eq!(PanelKind::Rail.label(), "RAIL");
2387        assert_eq!(DrawerView::Files.label(), "FILES");
2388        assert_eq!(DrawerView::Find.label(), "FIND");
2389        let _kind = OverlayKind::Dialog;
2390    }
2391
2392    /// One screen over a fresh temp vault. Returns the `TempDir` so the vault
2393    /// directory outlives the test body.
2394    async fn test_screen() -> (
2395        EditorScreen,
2396        Arc<NoteVault>,
2397        SharedSettings,
2398        tempfile::TempDir,
2399    ) {
2400        use crate::settings::AppSettings;
2401        use kimun_core::VaultConfig;
2402        use std::sync::RwLock;
2403
2404        let dir = tempfile::TempDir::new().unwrap();
2405        let vault = Arc::new(
2406            NoteVault::new(VaultConfig::new(crate::test_support::sys(dir.path())))
2407                .await
2408                .unwrap(),
2409        );
2410        let settings: SharedSettings = Arc::new(RwLock::new(AppSettings::default()));
2411        let screen = EditorScreen::new(vault.clone(), VaultPath::root(), settings.clone());
2412        (screen, vault, settings, dir)
2413    }
2414
2415    fn key_event(code: ratatui::crossterm::event::KeyCode) -> InputEvent {
2416        use ratatui::crossterm::event::{KeyEvent, KeyModifiers};
2417        InputEvent::Key(KeyEvent::new(code, KeyModifiers::NONE))
2418    }
2419
2420    fn ctrl_key(c: char) -> InputEvent {
2421        use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
2422        InputEvent::Key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL))
2423    }
2424
2425    fn chr(c: char) -> InputEvent {
2426        key_event(ratatui::crossterm::event::KeyCode::Char(c))
2427    }
2428
2429    /// Ctrl-G (leader) then `o` `f` opens the FILES drawer — the full
2430    /// sequence fires with no menu drawn and no timeout wait.
2431    #[tokio::test]
2432    async fn leader_sequence_opens_drawer_view() {
2433        let (mut screen, _, _, _dir) = test_screen().await;
2434        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
2435
2436        // Start from a non-Files view so the switch is observable.
2437        screen.panels.open_drawer_view(DrawerView::Tags);
2438
2439        screen.handle_input(&ctrl_key('g'), &tx);
2440        assert!(screen.leader.is_pending());
2441        screen.handle_input(&chr('o'), &tx);
2442        screen.handle_input(&chr('f'), &tx);
2443
2444        assert!(!screen.leader.is_pending());
2445        assert_eq!(screen.panels.active_drawer_view(), DrawerView::Files);
2446        assert_eq!(screen.panels.focused(), PanelKind::Drawer);
2447    }
2448
2449    /// Opening the FILES drawer points the sidebar at the current note's
2450    /// directory, not the stale dir it was last left on.
2451    #[tokio::test]
2452    async fn opening_files_drawer_reveals_current_note_dir() {
2453        let (mut screen, _, _, _dir) = test_screen().await;
2454        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
2455
2456        screen.path = VaultPath::new("projects").append(&VaultPath::note_path_from("plan"));
2457        // Sidebar left on an unrelated directory, drawer hidden.
2458        screen
2459            .panels
2460            .sidebar_mut()
2461            .navigate(VaultPath::new("other"), &tx);
2462        screen.panels.hide(PanelKind::Drawer);
2463
2464        screen.open_drawer_view(DrawerView::Files, &tx);
2465
2466        assert!(
2467            screen
2468                .panels
2469                .sidebar()
2470                .current_dir()
2471                .is_like(&VaultPath::new("projects"))
2472        );
2473    }
2474
2475    /// With FILES already open but browsed elsewhere, the open-file-browser
2476    /// shortcut is the "where is my note" gesture: it re-reveals the current
2477    /// note's directory.
2478    #[tokio::test]
2479    async fn file_browser_shortcut_rereveals_note_dir_when_already_open() {
2480        let (mut screen, _, _, _dir) = test_screen().await;
2481        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
2482
2483        screen.path = VaultPath::new("projects").append(&VaultPath::note_path_from("plan"));
2484        screen.open_drawer_view(DrawerView::Files, &tx);
2485        // User browses away while FILES stays open.
2486        screen
2487            .panels
2488            .sidebar_mut()
2489            .navigate(VaultPath::new("other"), &tx);
2490
2491        screen.handle_input(&ctrl_key('e'), &tx);
2492
2493        assert!(
2494            screen
2495                .panels
2496                .sidebar()
2497                .current_dir()
2498                .is_like(&VaultPath::new("projects"))
2499        );
2500    }
2501
2502    /// The gateway works mid-typing: with the editor focused, Ctrl-G arms
2503    /// the sequence and the next chars are consumed, not inserted.
2504    #[tokio::test]
2505    async fn leader_consumes_keys_while_editor_focused() {
2506        let (mut screen, _, _, _dir) = test_screen().await;
2507        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
2508
2509        screen.panels.editor_mut().unwrap().set_text(String::new());
2510        assert_eq!(screen.panels.focused(), PanelKind::Editor);
2511
2512        screen.handle_input(&ctrl_key('g'), &tx);
2513        assert!(screen.leader.is_pending());
2514        // 'w' is a group key; it must not land in the buffer.
2515        screen.handle_input(&chr('w'), &tx);
2516        screen.handle_input(&chr('z'), &tx); // zen: hides the drawer
2517        assert_eq!(screen.panels.editor().unwrap().get_text(), "");
2518        assert!(!screen.panels.is_visible(PanelKind::Drawer));
2519    }
2520
2521    /// Esc cancels a pending sequence and returns focus to the editor.
2522    #[tokio::test]
2523    async fn leader_esc_cancels_and_focuses_editor() {
2524        let (mut screen, _, _, _dir) = test_screen().await;
2525        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
2526
2527        screen.panels.focus(PanelKind::Rail);
2528        screen.handle_input(&ctrl_key('g'), &tx);
2529        screen.handle_input(&chr('f'), &tx);
2530        screen.handle_input(&key_event(ratatui::crossterm::event::KeyCode::Esc), &tx);
2531
2532        assert!(!screen.leader.is_pending());
2533        assert_eq!(screen.panels.focused(), PanelKind::Editor);
2534    }
2535
2536    /// Drain `rx` until an event matching `pred` arrives, or time out.
2537    async fn wait_for(
2538        rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
2539        pred: impl Fn(&AppEvent) -> bool,
2540    ) -> AppEvent {
2541        tokio::time::timeout(std::time::Duration::from_secs(2), async {
2542            loop {
2543                let e = rx.recv().await.expect("channel open");
2544                if pred(&e) {
2545                    break e;
2546                }
2547            }
2548        })
2549        .await
2550        .expect("expected event")
2551    }
2552
2553    /// Leader `f p` opens the pinned-notes dialog (a plain overlay open, same
2554    /// door as every other leader-triggered dialog).
2555    #[tokio::test(flavor = "multi_thread")]
2556    async fn leader_f_p_opens_the_pinned_notes_dialog() {
2557        let (mut screen, _, _, _dir) = test_screen().await;
2558        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
2559        screen.handle_input(&ctrl_key('g'), &tx);
2560        screen.handle_input(&chr('f'), &tx);
2561        screen.handle_input(&chr('p'), &tx);
2562        assert!(screen.overlays.is_open());
2563        assert_eq!(
2564            screen.overlays.active_kind(),
2565            Some(crate::components::overlay::OverlayKind::Dialog)
2566        );
2567    }
2568
2569    /// Leader `m i` pins the open note, flashing its 1-based position, then
2570    /// unpins it on the second press.
2571    #[tokio::test(flavor = "multi_thread")]
2572    async fn leader_m_i_toggles_the_pin_and_flashes() {
2573        let (mut screen, vault, _, _dir) = test_screen().await;
2574        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2575        let note = VaultPath::new("plan.md");
2576        vault.create_note(&note, "hi").await.unwrap();
2577        screen.path = note.clone();
2578
2579        screen.handle_input(&ctrl_key('g'), &tx);
2580        screen.handle_input(&chr('m'), &tx);
2581        screen.handle_input(&chr('i'), &tx);
2582        let e = wait_for(&mut rx, |e| matches!(e, AppEvent::FlashMessage(_))).await;
2583        assert!(
2584            matches!(&e, AppEvent::FlashMessage(m) if m == "pinned as 1 of 9"),
2585            "{e:?}"
2586        );
2587        // list_pinned_notes returns canonical, vault-absolute paths.
2588        assert_eq!(
2589            vault.list_pinned_notes().await.unwrap(),
2590            vec![VaultPath::new("/plan.md")]
2591        );
2592
2593        screen.handle_input(&ctrl_key('g'), &tx);
2594        screen.handle_input(&chr('m'), &tx);
2595        screen.handle_input(&chr('i'), &tx);
2596        let e = wait_for(&mut rx, |e| matches!(e, AppEvent::FlashMessage(_))).await;
2597        assert!(
2598            matches!(&e, AppEvent::FlashMessage(m) if m == "unpinned"),
2599            "{e:?}"
2600        );
2601        assert!(vault.list_pinned_notes().await.unwrap().is_empty());
2602    }
2603
2604    /// A tenth pin is refused with a message telling the user what to do —
2605    /// the cap is what guarantees every pinned note keeps a digit shortcut.
2606    #[tokio::test(flavor = "multi_thread")]
2607    async fn leader_m_i_refuses_a_tenth_pin() {
2608        let (mut screen, vault, _, _dir) = test_screen().await;
2609        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2610        for i in 0..kimun_core::PINNED_NOTES_CAP {
2611            let n = VaultPath::new(format!("n{i}.md"));
2612            vault.create_note(&n, "hi").await.unwrap();
2613            vault.toggle_pinned_note(&n).await.unwrap();
2614        }
2615        let extra = VaultPath::new("extra.md");
2616        vault.create_note(&extra, "hi").await.unwrap();
2617        screen.path = extra;
2618        screen.handle_input(&ctrl_key('g'), &tx);
2619        screen.handle_input(&chr('m'), &tx);
2620        screen.handle_input(&chr('i'), &tx);
2621        let e = wait_for(&mut rx, |e| matches!(e, AppEvent::FlashMessage(_))).await;
2622        assert!(
2623            matches!(&e, AppEvent::FlashMessage(m) if m == "already 9 pinned — unpin one first"),
2624            "{e:?}"
2625        );
2626    }
2627
2628    /// The open path can name a note that is no longer on disk — removed
2629    /// in another terminal, or a create dialog dismissed with the path left
2630    /// set. Pinning it would only store a pin born "missing", so it flashes.
2631    #[tokio::test(flavor = "multi_thread")]
2632    async fn leader_m_i_on_a_missing_note_flashes() {
2633        let (mut screen, vault, _, _dir) = test_screen().await;
2634        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2635        screen.path = VaultPath::new("gone.md");
2636        screen.handle_input(&ctrl_key('g'), &tx);
2637        screen.handle_input(&chr('m'), &tx);
2638        screen.handle_input(&chr('i'), &tx);
2639        let e = wait_for(&mut rx, |e| matches!(e, AppEvent::FlashMessage(_))).await;
2640        assert!(
2641            matches!(&e, AppEvent::FlashMessage(m) if m == "note not found: gone.md"),
2642            "{e:?}"
2643        );
2644        assert!(vault.list_pinned_notes().await.unwrap().is_empty());
2645    }
2646
2647    /// Every "+this note" action shares one definition of "this note": with
2648    /// the Ask workspace up, `m c` refuses exactly as `m i` does, instead of
2649    /// copying a wikilink to the note the user is no longer looking at.
2650    #[tokio::test(flavor = "multi_thread")]
2651    async fn leader_m_c_with_ask_shown_flashes_like_m_i() {
2652        let (mut screen, vault, _, _dir) = test_screen().await;
2653        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2654        let note = VaultPath::new("plan.md");
2655        vault.create_note(&note, "hi").await.unwrap();
2656        screen.path = note;
2657        screen.open_drawer_view(DrawerView::Ask, &tx);
2658
2659        screen.handle_input(&ctrl_key('g'), &tx);
2660        screen.handle_input(&chr('m'), &tx);
2661        screen.handle_input(&chr('c'), &tx);
2662        let e = wait_for(&mut rx, |e| matches!(e, AppEvent::FlashMessage(_))).await;
2663        assert!(
2664            matches!(&e, AppEvent::FlashMessage(m) if m == "no note open"),
2665            "{e:?}"
2666        );
2667    }
2668
2669    /// Toggling with no note open (the screen starts on the vault root, which
2670    /// is not a note) flashes rather than doing nothing.
2671    #[tokio::test(flavor = "multi_thread")]
2672    async fn leader_m_i_with_no_note_open_flashes() {
2673        let (mut screen, _, _, _dir) = test_screen().await;
2674        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2675        // test_screen opens on VaultPath::root(), which is not a note.
2676        screen.handle_input(&ctrl_key('g'), &tx);
2677        screen.handle_input(&chr('m'), &tx);
2678        screen.handle_input(&chr('i'), &tx);
2679        let e = wait_for(&mut rx, |e| matches!(e, AppEvent::FlashMessage(_))).await;
2680        assert!(
2681            matches!(&e, AppEvent::FlashMessage(m) if m == "no note open"),
2682            "{e:?}"
2683        );
2684    }
2685
2686    /// The attachment view counts as "no note open" even though `self.path`
2687    /// is set (to the attachment's path, itself never a note).
2688    #[tokio::test(flavor = "multi_thread")]
2689    async fn leader_m_i_with_attachment_shown_flashes() {
2690        let (mut screen, vault, _, _dir) = test_screen().await;
2691        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2692        vault
2693            .save_attachment(&VaultPath::new("assets/diagram.png"), &[1, 2, 3])
2694            .await
2695            .unwrap();
2696        screen
2697            .try_open_attachment(VaultPath::new("assets/diagram.png"), &tx)
2698            .await;
2699        assert!(screen.panels.is_showing_attachment());
2700
2701        screen.handle_input(&ctrl_key('g'), &tx);
2702        screen.handle_input(&chr('m'), &tx);
2703        screen.handle_input(&chr('i'), &tx);
2704        let e = wait_for(&mut rx, |e| matches!(e, AppEvent::FlashMessage(_))).await;
2705        assert!(
2706            matches!(&e, AppEvent::FlashMessage(m) if m == "no note open"),
2707            "{e:?}"
2708        );
2709    }
2710
2711    /// The Ask workspace counts as "no note open" even though `self.path`
2712    /// still names the note that was open before switching to Ask — the
2713    /// editor area is not showing it.
2714    #[tokio::test(flavor = "multi_thread")]
2715    async fn leader_m_i_with_ask_shown_flashes() {
2716        let (mut screen, vault, _, _dir) = test_screen().await;
2717        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2718        let note = VaultPath::new("plan.md");
2719        vault.create_note(&note, "hi").await.unwrap();
2720        screen.path = note;
2721        screen.open_drawer_view(DrawerView::Ask, &tx);
2722        assert!(screen.panels.is_showing_ask());
2723
2724        screen.handle_input(&ctrl_key('g'), &tx);
2725        screen.handle_input(&chr('m'), &tx);
2726        screen.handle_input(&chr('i'), &tx);
2727        let e = wait_for(&mut rx, |e| matches!(e, AppEvent::FlashMessage(_))).await;
2728        assert!(
2729            matches!(&e, AppEvent::FlashMessage(m) if m == "no note open"),
2730            "{e:?}"
2731        );
2732    }
2733
2734    /// Leader digit `2` opens the second pinned note (1-based).
2735    #[tokio::test(flavor = "multi_thread")]
2736    async fn leader_digit_opens_the_nth_pinned_note() {
2737        let (mut screen, vault, _, _dir) = test_screen().await;
2738        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2739        let a = VaultPath::new("a.md");
2740        let b = VaultPath::new("b.md");
2741        vault.create_note(&a, "a").await.unwrap();
2742        vault.create_note(&b, "b").await.unwrap();
2743        vault.toggle_pinned_note(&a).await.unwrap();
2744        vault.toggle_pinned_note(&b).await.unwrap();
2745
2746        screen.handle_input(&ctrl_key('g'), &tx);
2747        screen.handle_input(&chr('2'), &tx);
2748        let e = wait_for(&mut rx, |e| matches!(e, AppEvent::OpenPath { .. })).await;
2749        // list_pinned_notes returns the canonical, vault-absolute form
2750        // (`/b.md`); is_like compares components only.
2751        assert!(
2752            matches!(&e, AppEvent::OpenPath { path, .. } if path.is_like(&b)),
2753            "{e:?}"
2754        );
2755    }
2756
2757    /// A digit with no pin in that slot flashes instead of failing silently.
2758    #[tokio::test(flavor = "multi_thread")]
2759    async fn leader_digit_with_no_such_pin_flashes() {
2760        let (mut screen, _, _, _dir) = test_screen().await;
2761        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2762        screen.handle_input(&ctrl_key('g'), &tx);
2763        screen.handle_input(&chr('4'), &tx);
2764        let e = wait_for(&mut rx, |e| matches!(e, AppEvent::FlashMessage(_))).await;
2765        assert!(
2766            matches!(&e, AppEvent::FlashMessage(m) if m == "no pinned note 4"),
2767            "{e:?}"
2768        );
2769    }
2770
2771    /// A pin whose note has vanished from disk flashes — and is kept, never
2772    /// pruned, since only an explicit unpin removes it.
2773    #[tokio::test(flavor = "multi_thread")]
2774    async fn leader_digit_to_a_missing_pin_flashes() {
2775        let (mut screen, vault, _, dir) = test_screen().await;
2776        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2777        let gone = VaultPath::new("gone.md");
2778        vault.create_note(&gone, "hi").await.unwrap();
2779        vault.toggle_pinned_note(&gone).await.unwrap();
2780        // Vanishes outside kimün after being pinned.
2781        std::fs::remove_file(dir.path().join("gone.md")).unwrap();
2782        screen.handle_input(&ctrl_key('g'), &tx);
2783        screen.handle_input(&chr('1'), &tx);
2784        let e = wait_for(&mut rx, |e| matches!(e, AppEvent::FlashMessage(_))).await;
2785        // The flashed path is the canonical form list_pinned_notes returned.
2786        assert!(
2787            matches!(&e, AppEvent::FlashMessage(m) if m == "pinned note not found: /gone.md"),
2788            "{e:?}"
2789        );
2790    }
2791
2792    /// Bare Space never leads — the leader is only the configured gateway.
2793    /// Space types a space in the editor and never arms the sequence, whatever
2794    /// panel is focused (rail, a list drawer, or a text-input drawer).
2795    #[tokio::test]
2796    async fn space_never_leads() {
2797        let (mut screen, _, _, _dir) = test_screen().await;
2798        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
2799
2800        // Editor focused: Space must insert a space.
2801        screen.panels.editor_mut().unwrap().set_text(String::new());
2802        screen.handle_input(&chr(' '), &tx);
2803        assert!(!screen.leader.is_pending());
2804        assert_eq!(screen.panels.editor().unwrap().get_text(), " ");
2805
2806        // Rail focused: Space must NOT lead.
2807        screen.panels.focus(PanelKind::Rail);
2808        screen.handle_input(&chr(' '), &tx);
2809        assert!(!screen.leader.is_pending());
2810
2811        // FIND drawer (a text input): Space must NOT lead.
2812        screen.panels.open_drawer_view(DrawerView::Find);
2813        screen.panels.focus(PanelKind::Drawer);
2814        screen.handle_input(&chr(' '), &tx);
2815        assert!(!screen.leader.is_pending());
2816    }
2817
2818    #[tokio::test]
2819    async fn persist_saved_search_writes_via_core() {
2820        let (screen, _, _, _dir) = test_screen().await;
2821
2822        screen.persist_saved_search("t", "#todo").await.unwrap();
2823
2824        let all = screen.vault.list_saved_searches().await.unwrap();
2825        assert!(all.iter().any(|s| s.name == "t" && s.query == "#todo"));
2826    }
2827
2828    #[tokio::test]
2829    async fn applying_saved_search_sets_panel_query_and_focuses_it() {
2830        let (mut screen, _, _, _dir) = test_screen().await;
2831
2832        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
2833        screen.apply_saved_search(
2834            "<{note}".to_string(),
2835            "Backlinks (current note)".to_string(),
2836            &tx,
2837        );
2838        assert!(screen.panels.is_visible(PanelKind::Drawer));
2839        assert_eq!(screen.panels.active_drawer_view(), DrawerView::Find);
2840        assert_eq!(screen.panels.query().active_query(), "<{note}");
2841        assert_eq!(screen.panels.focused(), PanelKind::Drawer);
2842    }
2843
2844    #[tokio::test]
2845    async fn saved_search_persisted_repins_panel_breadcrumb() {
2846        let (mut screen, _, _, _dir) = test_screen().await;
2847
2848        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
2849        screen.apply_saved_search("#todo".to_string(), "todo".to_string(), &tx);
2850        screen
2851            .panels
2852            .query_mut()
2853            .set_active_query("#todo and #urgent".to_string());
2854
2855        screen
2856            .handle_app_message(
2857                AppEvent::SavedSearch(SavedSearchFlow::Persisted {
2858                    name: "urgent-todos".to_string(),
2859                    query: "#todo and #urgent".to_string(),
2860                    source: SaveSource::QueryPanel,
2861                }),
2862                &tx,
2863            )
2864            .await;
2865
2866        assert_eq!(
2867            screen.panels.query().saved_search_breadcrumb().as_deref(),
2868            Some("urgent-todos"),
2869            "a persisted panel-sourced save re-pins the breadcrumb"
2870        );
2871    }
2872
2873    #[tokio::test]
2874    async fn persisted_note_browser_save_does_not_repin_even_on_equal_query() {
2875        let (mut screen, _, _, _dir) = test_screen().await;
2876
2877        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
2878        screen.apply_saved_search("#todo".to_string(), "todo".to_string(), &tx);
2879
2880        // A note-browser-sourced save whose query text happens to equal the
2881        // panel's live query: source identity, not text equality, decides.
2882        screen
2883            .handle_app_message(
2884                AppEvent::SavedSearch(SavedSearchFlow::Persisted {
2885                    name: "inbox".to_string(),
2886                    query: "#todo".to_string(),
2887                    source: SaveSource::NoteBrowser,
2888                }),
2889                &tx,
2890            )
2891            .await;
2892
2893        assert_eq!(
2894            screen.panels.query().saved_search_breadcrumb().as_deref(),
2895            Some("todo"),
2896            "a note-browser save must not steal the panel's provenance"
2897        );
2898    }
2899
2900    #[tokio::test]
2901    async fn persisted_query_as_name_save_skips_repin() {
2902        let (mut screen, _, _, _dir) = test_screen().await;
2903
2904        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
2905        screen.apply_saved_search("#todo".to_string(), "todo".to_string(), &tx);
2906
2907        // The empty-name fallback saved the query under its own text. Pinning
2908        // that as the breadcrumb name would just echo the query (CONTEXT.md:
2909        // the breadcrumb is a distinct provenance tag, not the query).
2910        screen
2911            .handle_app_message(
2912                AppEvent::SavedSearch(SavedSearchFlow::Persisted {
2913                    name: "#todo".to_string(),
2914                    query: "#todo".to_string(),
2915                    source: SaveSource::QueryPanel,
2916                }),
2917                &tx,
2918            )
2919            .await;
2920
2921        assert_eq!(
2922            screen.panels.query().saved_search_breadcrumb().as_deref(),
2923            Some("todo"),
2924            "a query-as-name save leaves the breadcrumb alone"
2925        );
2926    }
2927
2928    #[tokio::test]
2929    async fn save_search_confirmed_persists_then_emits_persisted() {
2930        let (mut screen, vault, _, _dir) = test_screen().await;
2931
2932        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2933        screen
2934            .handle_app_message(
2935                AppEvent::SavedSearch(SavedSearchFlow::Confirmed {
2936                    name: "mine".to_string(),
2937                    query: "#todo".to_string(),
2938                    source: SaveSource::QueryPanel,
2939                }),
2940                &tx,
2941            )
2942            .await;
2943
2944        // The write runs in a spawned task; Persisted arrives only on success.
2945        let event = tokio::time::timeout(std::time::Duration::from_secs(5), async {
2946            loop {
2947                match rx.recv().await {
2948                    Some(e @ AppEvent::SavedSearch(SavedSearchFlow::Persisted { .. })) => break e,
2949                    Some(_) => continue,
2950                    None => panic!("channel closed before SavedSearchPersisted"),
2951                }
2952            }
2953        })
2954        .await
2955        .expect("SavedSearchPersisted within timeout");
2956
2957        let AppEvent::SavedSearch(SavedSearchFlow::Persisted {
2958            name,
2959            query,
2960            source,
2961        }) = event
2962        else {
2963            unreachable!()
2964        };
2965        assert_eq!((name.as_str(), query.as_str()), ("mine", "#todo"));
2966        assert_eq!(source, SaveSource::QueryPanel);
2967        let all = vault.list_saved_searches().await.unwrap();
2968        assert!(all.iter().any(|s| s.name == "mine" && s.query == "#todo"));
2969    }
2970
2971    #[tokio::test]
2972    async fn save_query_source_carries_panel_provenance() {
2973        let (mut screen, _, _, _dir) = test_screen().await;
2974
2975        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
2976        screen.apply_saved_search("#todo".to_string(), "todo".to_string(), &tx);
2977
2978        assert_eq!(
2979            screen.save_query_source(),
2980            Some((
2981                "#todo".to_string(),
2982                Some("todo".to_string()),
2983                SaveSource::QueryPanel
2984            )),
2985            "the save dialog opens pre-filled with the breadcrumb provenance"
2986        );
2987    }
2988
2989    // The try_save timeout-abort regression tests (commits 55eb49ed +
2990    // 5e28b796) previously lived here against `await_or_abort`. The
2991    // logic now lives in `SingleSlotTask::await_with_timeout` and is
2992    // covered by `single_slot_task_timeout_returns_none_keeps_handle`
2993    // in `crate::util::single_slot_task`.
2994
2995    #[tokio::test]
2996    async fn saved_search_selected_then_close_overlay_keeps_backlinks_focus() {
2997        use crate::settings::AppSettings;
2998        use kimun_core::VaultConfig;
2999        use std::sync::RwLock;
3000
3001        let dir = tempfile::TempDir::new().unwrap();
3002        let vault = Arc::new(
3003            NoteVault::new(VaultConfig::new(crate::test_support::sys(dir.path())))
3004                .await
3005                .unwrap(),
3006        );
3007        let settings: SharedSettings = Arc::new(RwLock::new(AppSettings::default()));
3008        let mut screen = EditorScreen::new(vault, VaultPath::root(), settings);
3009
3010        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3011        // Replay the exact sequence the saved-searches modal emits on select.
3012        screen
3013            .handle_app_message(
3014                AppEvent::SavedSearch(SavedSearchFlow::Selected {
3015                    query: "<{note}".to_string(),
3016                    name: "Backlinks (current note)".to_string(),
3017                }),
3018                &tx,
3019            )
3020            .await;
3021        screen.handle_app_message(AppEvent::CloseOverlay, &tx).await;
3022
3023        assert!(
3024            screen.panels.focused() == PanelKind::Drawer
3025                && screen.panels.active_drawer_view() == DrawerView::Find,
3026            "focus should remain on the FIND drawer after select + close"
3027        );
3028        assert!(!screen.overlays.is_open(), "overlay should be closed");
3029    }
3030
3031    /// Capture-all guard: while an overlay is open, an opener action
3032    /// (QuickNote) must NOT replace it. Drives a real QuickNote keypress
3033    /// through `handle_input` so the guard in the action arm is exercised
3034    /// end-to-end.
3035    #[tokio::test]
3036    async fn opener_action_does_not_replace_open_overlay() {
3037        use crate::settings::AppSettings;
3038        use kimun_core::VaultConfig;
3039        use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
3040        use std::sync::RwLock;
3041
3042        let dir = tempfile::TempDir::new().unwrap();
3043        let vault = Arc::new(
3044            NoteVault::new(VaultConfig::new(crate::test_support::sys(dir.path())))
3045                .await
3046                .unwrap(),
3047        );
3048        let settings: SharedSettings = Arc::new(RwLock::new(AppSettings::default()));
3049        let mut screen = EditorScreen::new(vault.clone(), VaultPath::root(), settings.clone());
3050
3051        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3052
3053        // Force a SavedSearches overlay open and focus it, as if the user had
3054        // opened it via its action.
3055        {
3056            let s = settings.read().unwrap();
3057            let modal = SavedSearchesModal::new(
3058                vault.clone(),
3059                s.key_bindings.clone(),
3060                s.icons(),
3061                tx.clone(),
3062            );
3063            drop(s);
3064            screen.overlays.open(Box::new(modal), screen.opener_focus());
3065        }
3066        assert_eq!(
3067            screen.overlays.active_kind(),
3068            Some(OverlayKind::SavedSearches),
3069            "precondition: SavedSearches overlay is active"
3070        );
3071
3072        // The QuickNote action key (Ctrl+W by default). Assert the binding
3073        // resolves to QuickNote so this test fails loudly if the default
3074        // rebinds, rather than silently exercising the wrong path.
3075        let quick_note_event = KeyEvent::new(KeyCode::Char('w'), KeyModifiers::CONTROL);
3076        {
3077            let s = settings.read().unwrap();
3078            let combo = key_event_to_combo(&quick_note_event).expect("Ctrl+W maps to a combo");
3079            assert_eq!(
3080                s.key_bindings.get_action(&combo),
3081                Some(ActionShortcuts::QuickNote),
3082                "test assumes Ctrl+W is bound to QuickNote"
3083            );
3084        }
3085
3086        screen.handle_input(&InputEvent::Key(quick_note_event), &tx);
3087
3088        // The guard must have suppressed the open: the SavedSearches overlay
3089        // is still active, NOT replaced by the QuickNote dialog.
3090        assert_eq!(
3091            screen.overlays.active_kind(),
3092            Some(OverlayKind::SavedSearches),
3093            "open overlay must not be replaced by a QuickNote opener action"
3094        );
3095    }
3096
3097    /// Focus actions are inert while an overlay owns input: pressing
3098    /// FocusEditor (Ctrl+L) with a dialog open must not reveal or move the
3099    /// panels underneath, so closing the dialog leaves the layout unchanged.
3100    #[tokio::test]
3101    async fn focus_action_is_noop_while_overlay_open() {
3102        use crate::settings::AppSettings;
3103        use kimun_core::VaultConfig;
3104        use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
3105        use std::sync::RwLock;
3106
3107        let dir = tempfile::TempDir::new().unwrap();
3108        let vault = Arc::new(
3109            NoteVault::new(VaultConfig::new(crate::test_support::sys(dir.path())))
3110                .await
3111                .unwrap(),
3112        );
3113        let settings: SharedSettings = Arc::new(RwLock::new(AppSettings::default()));
3114        let mut screen = EditorScreen::new(vault.clone(), VaultPath::root(), settings.clone());
3115
3116        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3117
3118        // Open a SavedSearches overlay (Query panel starts hidden).
3119        {
3120            let s = settings.read().unwrap();
3121            let modal = SavedSearchesModal::new(
3122                vault.clone(),
3123                s.key_bindings.clone(),
3124                s.icons(),
3125                tx.clone(),
3126            );
3127            drop(s);
3128            screen.overlays.open(Box::new(modal), screen.opener_focus());
3129        }
3130        assert_ne!(screen.panels.active_drawer_view(), DrawerView::Find);
3131        let focused_before = screen.panels.focused();
3132
3133        // Ctrl+L (FocusEditor / focus right) must be consumed but do nothing.
3134        let focus_right = KeyEvent::new(KeyCode::Char('l'), KeyModifiers::CONTROL);
3135        {
3136            let s = settings.read().unwrap();
3137            let combo = key_event_to_combo(&focus_right).expect("Ctrl+L maps to a combo");
3138            assert_eq!(
3139                s.key_bindings.get_action(&combo),
3140                Some(ActionShortcuts::FocusEditor),
3141                "test assumes Ctrl+L is bound to FocusEditor"
3142            );
3143        }
3144        screen.handle_input(&InputEvent::Key(focus_right), &tx);
3145
3146        assert_eq!(
3147            screen.panels.focused(),
3148            focused_before,
3149            "focus action must not move focus while an overlay is open"
3150        );
3151        assert_ne!(
3152            screen.panels.active_drawer_view(),
3153            DrawerView::Find,
3154            "focus action must not switch the drawer view while an overlay is open"
3155        );
3156        assert_eq!(
3157            screen.overlays.active_kind(),
3158            Some(OverlayKind::SavedSearches),
3159            "overlay stays active"
3160        );
3161    }
3162
3163    /// Opening the journal while an overlay is up dismisses the overlay, so the
3164    /// journal note isn't loaded behind it. OpenJournal is now resolved at the
3165    /// app level into an OpenPath, which lands here in `try_open_path` — that's
3166    /// the door that must dismiss the overlay.
3167    #[tokio::test(flavor = "multi_thread")]
3168    async fn open_journal_dismisses_open_overlay() {
3169        let vault = crate::test_support::temp_vault("editor-journal").await;
3170        vault.validate_and_init().await.unwrap();
3171        let settings = std::sync::Arc::new(std::sync::RwLock::new(
3172            crate::settings::AppSettings::default(),
3173        ));
3174        let mut screen = EditorScreen::new(vault.clone(), VaultPath::root(), settings.clone());
3175        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3176
3177        {
3178            let s = settings.read().unwrap();
3179            let modal = SavedSearchesModal::new(
3180                vault.clone(),
3181                s.key_bindings.clone(),
3182                s.icons(),
3183                tx.clone(),
3184            );
3185            drop(s);
3186            screen.present_overlay(Box::new(modal));
3187        }
3188        assert!(screen.overlays.is_open(), "precondition: overlay open");
3189
3190        let (details, _, _) = vault.journal_entry().await.unwrap();
3191        screen.try_open_path(details.path, None, &tx).await;
3192
3193        assert!(
3194            !screen.overlays.is_open(),
3195            "opening the journal must dismiss the overlay before loading the note"
3196        );
3197    }
3198
3199    /// Opening an attachment swaps the editor area to the read-only attachment
3200    /// view: the note editor accessor reports absent, and FollowLink in that
3201    /// state opens externally rather than touching the (absent) editor.
3202    #[tokio::test(flavor = "multi_thread")]
3203    async fn opening_attachment_shows_attachment_view() {
3204        let vault = crate::test_support::temp_vault("editor-attachment").await;
3205        vault.validate_and_init().await.unwrap();
3206        vault
3207            .save_attachment(&VaultPath::new("assets/diagram.png"), &[1, 2, 3])
3208            .await
3209            .unwrap();
3210        let settings = std::sync::Arc::new(std::sync::RwLock::new(
3211            crate::settings::AppSettings::default(),
3212        ));
3213        let mut screen = EditorScreen::new(vault.clone(), VaultPath::root(), settings);
3214        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3215
3216        // Precondition: a note editor is mounted.
3217        assert!(screen.panels.editor().is_some());
3218
3219        screen
3220            .try_open_attachment(VaultPath::new("assets/diagram.png"), &tx)
3221            .await;
3222
3223        assert!(
3224            screen.panels.is_showing_attachment(),
3225            "the editor area shows the attachment view"
3226        );
3227        assert!(
3228            screen.panels.editor().is_none(),
3229            "no note editor is mounted while an attachment is shown"
3230        );
3231        assert_eq!(
3232            screen.panels.attachment_path(),
3233            Some(&VaultPath::new("assets/diagram.png"))
3234        );
3235
3236        // Returning to a note swaps the editor area back.
3237        vault
3238            .create_note(&VaultPath::new("note.md"), "hi")
3239            .await
3240            .unwrap();
3241        screen.open_path(VaultPath::new("note.md"), None, &tx).await;
3242        assert!(!screen.panels.is_showing_attachment());
3243        assert!(screen.panels.editor().is_some());
3244    }
3245
3246    #[tokio::test]
3247    async fn save_query_from_note_browser_opens_save_dialog() {
3248        use crate::settings::AppSettings;
3249        use kimun_core::VaultConfig;
3250        use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
3251        use std::sync::RwLock;
3252
3253        let dir = tempfile::TempDir::new().unwrap();
3254        let vault = Arc::new(
3255            NoteVault::new(VaultConfig::new(crate::test_support::sys(dir.path())))
3256                .await
3257                .unwrap(),
3258        );
3259        let settings: SharedSettings = Arc::new(RwLock::new(AppSettings::default()));
3260        let mut screen = EditorScreen::new(vault.clone(), VaultPath::root(), settings.clone());
3261
3262        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3263
3264        // Open a note browser carrying a query, as if the user typed "#todo".
3265        {
3266            let s = settings.read().unwrap();
3267            let provider = resolving_search_source(vault.clone(), s.current_last_paths(), None);
3268            let modal = NoteBrowserModal::with_initial_query(
3269                "Note Browser",
3270                BrowserScope::Query,
3271                provider,
3272                vault.clone(),
3273                s.key_bindings.clone(),
3274                s.icons(),
3275                tx.clone(),
3276                "#todo",
3277            );
3278            drop(s);
3279            screen.overlays.open(Box::new(modal), screen.opener_focus());
3280        }
3281        assert_eq!(
3282            screen.overlays.active_kind(),
3283            Some(OverlayKind::NoteBrowser),
3284            "precondition: note browser is active with a query"
3285        );
3286        assert_eq!(screen.overlays.active_query(), Some("#todo"));
3287
3288        // Ctrl+D (SaveCurrentQuery) while the note browser is active should
3289        // replace it with the save-search dialog, sourcing the browser's query.
3290        let save_event = KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL);
3291        {
3292            let s = settings.read().unwrap();
3293            let combo = key_event_to_combo(&save_event).expect("Ctrl+D maps to a combo");
3294            assert_eq!(
3295                s.key_bindings.get_action(&combo),
3296                Some(ActionShortcuts::SaveCurrentQuery),
3297                "test assumes Ctrl+D is bound to SaveCurrentQuery"
3298            );
3299        }
3300
3301        screen.handle_input(&InputEvent::Key(save_event), &tx);
3302
3303        assert_eq!(
3304            screen.overlays.active_kind(),
3305            Some(OverlayKind::Dialog),
3306            "saving from the note browser opens the save-search dialog"
3307        );
3308    }
3309
3310    /// Renaming the open note keeps it open under the new path (retarget in
3311    /// place) instead of navigating away, and reloads the buffer clean.
3312    #[tokio::test(flavor = "multi_thread")]
3313    async fn renaming_open_note_retargets_in_place() {
3314        let vault = crate::test_support::temp_vault("editor-rename").await;
3315        vault.validate_and_init().await.unwrap();
3316        let from = VaultPath::note_path_from("old");
3317        vault.create_note(&from, "# Old\n\nbody").await.unwrap();
3318        let settings = std::sync::Arc::new(std::sync::RwLock::new(
3319            crate::settings::AppSettings::default(),
3320        ));
3321        let mut screen = EditorScreen::new(vault.clone(), from.clone(), settings);
3322        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3323        screen.on_enter(&tx).await;
3324
3325        let to = VaultPath::note_path_from("new");
3326        vault.rename_note(&from, &to).await.unwrap();
3327        screen
3328            .handle_app_message(
3329                AppEvent::FileOp(FileOp::Renamed {
3330                    from: from.clone(),
3331                    to: to.clone(),
3332                }),
3333                &tx,
3334            )
3335            .await;
3336
3337        assert_eq!(screen.path, to, "editor retargets to the new path");
3338        assert!(
3339            !screen.panels.editor().unwrap().is_dirty(),
3340            "reloaded buffer is clean (won't clobber the renamed file)"
3341        );
3342    }
3343
3344    /// Opening a note marks its sidebar row; saving it (AutosaveCompleted with a
3345    /// new title) updates that row's title in place.
3346    #[tokio::test(flavor = "multi_thread")]
3347    async fn open_then_save_marks_and_retitles_sidebar_row() {
3348        let vault = crate::test_support::temp_vault("editor-marksave").await;
3349        vault.validate_and_init().await.unwrap();
3350        vault
3351            .create_note(&VaultPath::note_path_from("alpha"), "# Alpha\n\nbody")
3352            .await
3353            .unwrap();
3354        let settings = std::sync::Arc::new(std::sync::RwLock::new(
3355            crate::settings::AppSettings::default(),
3356        ));
3357        let path = VaultPath::note_path_from("alpha");
3358        let mut screen = EditorScreen::new(vault.clone(), path.clone(), settings);
3359        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3360        screen.on_enter(&tx).await;
3361        for _ in 0..50 {
3362            screen.panels.sidebar_mut().poll_for_test();
3363            if !screen.panels.sidebar().is_loading_for_test() {
3364                break;
3365            }
3366            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
3367        }
3368
3369        assert!(
3370            screen
3371                .panels
3372                .sidebar()
3373                .note_row_is_open_for_test("alpha.md"),
3374            "the open note's row is marked"
3375        );
3376
3377        screen
3378            .handle_app_message(
3379                AppEvent::AutosaveCompleted {
3380                    path: path.clone(),
3381                    saved_revision: None,
3382                    title: Some("New First Line".to_string()),
3383                },
3384                &tx,
3385            )
3386            .await;
3387
3388        assert_eq!(
3389            screen.panels.sidebar().note_row_title_for_test("alpha.md"),
3390            Some("New First Line".to_string()),
3391            "the saved note's row title updated in place"
3392        );
3393    }
3394
3395    /// Switching the drawer view Ask → Files → Ask preserves the conversation:
3396    /// the resident thread panel is never dropped, so its turns are intact on
3397    /// the way back in (rules 1 & 2, CONTEXT.md: Thread lifetime).
3398    #[tokio::test]
3399    async fn ask_drawer_switch_preserves_thread() {
3400        let (mut screen, _, _, _dir) = test_screen().await;
3401        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3402
3403        // Enter the Ask workspace and seed a couple of turns.
3404        screen.open_drawer_view(DrawerView::Ask, &tx);
3405        assert!(screen.panels.is_showing_ask());
3406        {
3407            let panel = screen.panels.ask_mut();
3408            panel.thread_mut().ask("first?".into());
3409            panel.thread_mut().ask("second?".into());
3410        }
3411        assert_eq!(screen.panels.ask().thread().turns().len(), 2);
3412
3413        // Switch away: the editor area leaves Ask, but the resident thread
3414        // panel keeps the conversation.
3415        screen.open_drawer_view(DrawerView::Files, &tx);
3416        assert!(!screen.panels.is_showing_ask());
3417        assert_eq!(screen.panels.ask().thread().turns().len(), 2);
3418
3419        // Switch back: the same conversation is on screen.
3420        screen.open_drawer_view(DrawerView::Ask, &tx);
3421        assert!(screen.panels.is_showing_ask());
3422        assert_eq!(
3423            screen.panels.ask().thread().turns().len(),
3424            2,
3425            "the conversation survives the round trip"
3426        );
3427    }
3428
3429    /// An `AskData::AnswerReady` delivered through the screen's real message
3430    /// pump (`handle_app_message`, the same entry point the app loop uses —
3431    /// not the coordinator's `handle_data` called directly) must still land on
3432    /// the thread: it should route through `handle_owned_message`'s
3433    /// `AppEvent::Ask(data)` arm to `AskCoordinator::handle_data` end to end.
3434    #[tokio::test]
3435    async fn ask_answer_ready_reaches_the_thread_via_the_owned_message_path() {
3436        let (mut screen, _, _, _dir) = test_screen().await;
3437        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3438
3439        screen.open_drawer_view(DrawerView::Ask, &tx);
3440        let id = screen.panels.ask_mut().thread_mut().ask("q?".into());
3441
3442        screen
3443            .handle_app_message(
3444                AppEvent::Ask(crate::components::events::AskData::AnswerReady {
3445                    turn_id: id,
3446                    result: Ok(("the answer".into(), vec![])),
3447                }),
3448                &tx,
3449            )
3450            .await;
3451
3452        let panel = screen.panels.ask_mut();
3453        let turn = panel.thread().selected().expect("a turn is selected");
3454        assert!(matches!(turn.status, crate::ask::TurnStatus::Done));
3455        assert_eq!(turn.answer, "the answer");
3456    }
3457
3458    /// Opening a note from the browser while the Ask workspace is shown must
3459    /// swap the editor area to the note (carry-forward: `open_path` calls
3460    /// `clear_attachment`, which no-ops on Ask, so the stash is the only thing
3461    /// that gets the note on screen) — and the thread survives to be re-shown.
3462    #[tokio::test]
3463    async fn opening_a_note_over_ask_shows_the_note_and_keeps_the_thread() {
3464        let vault = crate::test_support::temp_vault("editor-ask-open").await;
3465        vault.validate_and_init().await.unwrap();
3466        vault
3467            .create_note(&VaultPath::note_path_from("alpha"), "# Alpha\n\nbody")
3468            .await
3469            .unwrap();
3470        let settings = std::sync::Arc::new(std::sync::RwLock::new(
3471            crate::settings::AppSettings::default(),
3472        ));
3473        let mut screen = EditorScreen::new(vault, VaultPath::root(), settings);
3474        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3475
3476        screen.open_drawer_view(DrawerView::Ask, &tx);
3477        screen
3478            .panels
3479            .ask_mut()
3480            .thread_mut()
3481            .ask("a question?".into());
3482        assert!(screen.panels.is_showing_ask());
3483
3484        // Open a note: the editor area must show it, not the thread.
3485        screen
3486            .open_path(VaultPath::note_path_from("alpha"), None, &tx)
3487            .await;
3488        assert!(!screen.panels.is_showing_ask(), "the note replaced Ask");
3489        assert!(screen.panels.editor().is_some(), "the note editor is shown");
3490        assert_eq!(
3491            screen.panels.active_drawer_view(),
3492            DrawerView::Files,
3493            "the Sources drawer must not linger on a hidden conversation"
3494        );
3495
3496        // Re-enter Ask: the resident conversation comes back intact.
3497        screen.open_drawer_view(DrawerView::Ask, &tx);
3498        assert_eq!(
3499            screen.panels.ask().thread().turns().len(),
3500            1,
3501            "the thread survived opening the note"
3502        );
3503    }
3504
3505    /// Opening a note while Ask is shown but the drawer was explicitly hidden
3506    /// must switch the drawer's view to FILES *without* re-revealing it — the
3507    /// view switch preserves visibility (fold-in #4). Before the fix the
3508    /// FILES switch went through `open_drawer_view`, which force-showed a
3509    /// drawer the user had hidden.
3510    #[tokio::test]
3511    async fn opening_a_note_over_ask_with_hidden_drawer_keeps_it_hidden() {
3512        let vault = crate::test_support::temp_vault("editor-ask-hidden-drawer").await;
3513        vault.validate_and_init().await.unwrap();
3514        vault
3515            .create_note(&VaultPath::note_path_from("alpha"), "# Alpha\n\nbody")
3516            .await
3517            .unwrap();
3518        let settings = std::sync::Arc::new(std::sync::RwLock::new(
3519            crate::settings::AppSettings::default(),
3520        ));
3521        let mut screen = EditorScreen::new(vault, VaultPath::root(), settings);
3522        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3523
3524        // Enter Ask, then hide the drawer while the workspace stays on screen.
3525        screen.open_drawer_view(DrawerView::Ask, &tx);
3526        screen.panels.hide(PanelKind::Drawer);
3527        assert!(!screen.panels.is_visible(PanelKind::Drawer));
3528        assert!(screen.panels.is_showing_ask());
3529
3530        // Open a note: Ask leaves the editor area and the drawer view switches
3531        // to FILES, but the drawer must stay hidden.
3532        screen
3533            .open_path(VaultPath::note_path_from("alpha"), None, &tx)
3534            .await;
3535        assert!(!screen.panels.is_showing_ask(), "the note replaced Ask");
3536        assert!(
3537            !screen.panels.is_visible(PanelKind::Drawer),
3538            "a hidden drawer must not be force-revealed"
3539        );
3540        assert_eq!(
3541            screen.panels.active_drawer_view(),
3542            DrawerView::Files,
3543            "the view switched off Ask to FILES"
3544        );
3545    }
3546
3547    /// Regression for the rail-click toggle bug: before the fix, opening a
3548    /// note over Ask left the drawer's active view stuck on `Ask` (only the
3549    /// editor-area content moved), so the next `OpenDrawerView(Ask)` — what a
3550    /// rail click sends — read as "already showing, toggle it closed"
3551    /// instead of "reopen it", requiring a second click. Drives the real
3552    /// `AppEvent::OpenDrawerView` path (not the direct `open_drawer_view`
3553    /// helper) so this test actually exercises that toggle branch.
3554    #[tokio::test]
3555    async fn rail_click_reenters_ask_in_one_click_after_a_note_stashed_it() {
3556        let vault = crate::test_support::temp_vault("editor-ask-rail-reentry").await;
3557        vault.validate_and_init().await.unwrap();
3558        vault
3559            .create_note(&VaultPath::note_path_from("alpha"), "# Alpha\n\nbody")
3560            .await
3561            .unwrap();
3562        let settings = std::sync::Arc::new(std::sync::RwLock::new(
3563            crate::settings::AppSettings::default(),
3564        ));
3565        let mut screen = EditorScreen::new(vault, VaultPath::root(), settings);
3566        screen.rag_status = crate::rag::RagStatus::Online {
3567            llm_available: true,
3568        };
3569        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3570
3571        screen
3572            .handle_app_message(AppEvent::OpenDrawerView(DrawerView::Ask), &tx)
3573            .await;
3574        assert!(screen.panels.is_showing_ask());
3575        screen
3576            .panels
3577            .ask_mut()
3578            .thread_mut()
3579            .ask("a question?".into());
3580
3581        screen
3582            .open_path(VaultPath::note_path_from("alpha"), None, &tx)
3583            .await;
3584        assert!(!screen.panels.is_showing_ask());
3585
3586        // One click — one `OpenDrawerView(Ask)` — must land back on Ask.
3587        screen
3588            .handle_app_message(AppEvent::OpenDrawerView(DrawerView::Ask), &tx)
3589            .await;
3590        assert!(
3591            screen.panels.is_showing_ask(),
3592            "a single reopen must not read as a toggle-off"
3593        );
3594        assert_eq!(
3595            screen.panels.ask().thread().turns().len(),
3596            1,
3597            "the thread survived the round trip"
3598        );
3599    }
3600
3601    /// Opening an attachment while the Ask workspace is shown must swap the
3602    /// editor area to the attachment view (`show_attachment` leaves Ask content
3603    /// alone, so the stash is the only thing that gets it off screen) — and the
3604    /// thread survives to be re-shown. Mirrors the open-note-over-Ask case for
3605    /// the attachment entry point.
3606    #[tokio::test]
3607    async fn opening_an_attachment_over_ask_shows_it_and_keeps_the_thread() {
3608        let vault = crate::test_support::temp_vault("editor-ask-open-att").await;
3609        vault.validate_and_init().await.unwrap();
3610        let att_path = VaultPath::new("pic.png");
3611        vault
3612            .save_attachment(&att_path, b"\x89PNG\r\n\x1a\n")
3613            .await
3614            .unwrap();
3615        let settings = std::sync::Arc::new(std::sync::RwLock::new(
3616            crate::settings::AppSettings::default(),
3617        ));
3618        let mut screen = EditorScreen::new(vault, VaultPath::root(), settings);
3619        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3620
3621        screen.open_drawer_view(DrawerView::Ask, &tx);
3622        screen
3623            .panels
3624            .ask_mut()
3625            .thread_mut()
3626            .ask("a question?".into());
3627        assert!(screen.panels.is_showing_ask());
3628
3629        // Open an attachment: the editor area must show it, not the thread.
3630        screen.open_attachment(att_path, &tx).await;
3631        assert!(
3632            !screen.panels.is_showing_ask(),
3633            "the attachment replaced Ask"
3634        );
3635
3636        // Re-enter Ask: the stashed conversation comes back intact.
3637        screen.open_drawer_view(DrawerView::Ask, &tx);
3638        assert_eq!(
3639            screen.panels.ask().thread().turns().len(),
3640            1,
3641            "the thread survived opening the attachment"
3642        );
3643    }
3644
3645    /// Client presence at the screen seam: with no LLM-capable server there is
3646    /// no client, so the resident Ask panel's composer is disabled (never a
3647    /// forever-`Thinking` turn; carry-forward #2).
3648    #[tokio::test]
3649    async fn refresh_ask_capability_disables_without_a_client() {
3650        let (mut screen, _, _, _dir) = test_screen().await;
3651
3652        // rag_status is Disabled here → no client → composer disabled.
3653        screen
3654            .ask
3655            .refresh_capability(&mut screen.panels, screen.rag_status)
3656            .await;
3657        assert!(
3658            !screen.panels.ask().has_client(),
3659            "the resident Ask panel loses its client without an LLM server"
3660        );
3661    }
3662
3663    /// An answer that lands while the user is browsing FILES (Ask not shown) is
3664    /// delivered to the resident thread, not dropped (rule 3).
3665    #[tokio::test]
3666    async fn answer_lands_on_the_thread_while_browsing_files() {
3667        let (mut screen, _, _, _dir) = test_screen().await;
3668        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3669
3670        screen.open_drawer_view(DrawerView::Ask, &tx);
3671        let turn_id = screen.panels.ask_mut().thread_mut().ask("q?".into());
3672        // Leave Ask: the in-flight turn stays on the resident panel.
3673        screen.open_drawer_view(DrawerView::Files, &tx);
3674        assert!(!screen.panels.is_showing_ask());
3675
3676        screen.ask.handle_data(
3677            &mut screen.panels,
3678            crate::components::events::AskData::AnswerReady {
3679                turn_id,
3680                result: Ok(("the answer".into(), vec![])),
3681            },
3682            &tx,
3683        );
3684
3685        let thread = screen.panels.ask().thread();
3686        let turn = thread.turns().iter().find(|t| t.id == turn_id).unwrap();
3687        assert!(
3688            matches!(turn.status, crate::ask::TurnStatus::Done),
3689            "the answer completed the turn"
3690        );
3691    }
3692
3693    /// SEM's rail entry is live-status-driven, exactly like ASK: hidden until a
3694    /// health probe reports the server reachable for search, shown for a
3695    /// semantic-only server (search works, ASK stays hidden), and hidden again
3696    /// when the server drops offline.
3697    #[tokio::test]
3698    async fn sem_rail_entry_tracks_search_availability() {
3699        let (mut screen, _, _, _dir) = test_screen().await;
3700        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3701
3702        // Startup: no status yet → SEM (and ASK) hidden.
3703        assert!(!screen.panels.rail_shows(DrawerView::Semantic));
3704        assert!(!screen.panels.rail_shows(DrawerView::Ask));
3705
3706        // Semantic-only server comes online: SEM appears, ASK stays hidden.
3707        screen
3708            .handle_owned_message(
3709                AppEvent::RagStatus(crate::rag::RagStatus::Online {
3710                    llm_available: false,
3711                }),
3712                &tx,
3713            )
3714            .await;
3715        assert!(screen.panels.rail_shows(DrawerView::Semantic));
3716        assert!(!screen.panels.rail_shows(DrawerView::Ask));
3717
3718        // Server drops offline: SEM disappears too (not driven by config).
3719        screen
3720            .handle_owned_message(AppEvent::RagStatus(crate::rag::RagStatus::Offline), &tx)
3721            .await;
3722        assert!(!screen.panels.rail_shows(DrawerView::Semantic));
3723
3724        // LLM-capable server: both SEM and ASK appear.
3725        screen
3726            .handle_owned_message(
3727                AppEvent::RagStatus(crate::rag::RagStatus::Online {
3728                    llm_available: true,
3729                }),
3730                &tx,
3731            )
3732            .await;
3733        assert!(screen.panels.rail_shows(DrawerView::Semantic));
3734        assert!(screen.panels.rail_shows(DrawerView::Ask));
3735    }
3736
3737    /// Leader `a a` (`open_ask_workspace`) gates on `llm_available` only for
3738    /// the enter-from-outside path. Once Ask is already showing, the
3739    /// sibling `a n`/`a y`/`a e`/`a r` actions all work on a degraded
3740    /// (capability-off) thread, so re-focusing the composer must be
3741    /// consistent with them rather than flashing the gate message again.
3742    #[tokio::test]
3743    async fn ask_focus_skips_the_llm_gate_when_already_showing_ask() {
3744        let (mut screen, _, _, _dir) = test_screen().await;
3745        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
3746
3747        screen.rag_status = crate::rag::RagStatus::Online {
3748            llm_available: true,
3749        };
3750        screen.open_ask_workspace(&tx);
3751        assert!(screen.panels.is_showing_ask());
3752
3753        // Capability drops mid-conversation: the thread stays on screen with
3754        // the composer merely disabled, never evicted.
3755        screen.rag_status = crate::rag::RagStatus::Offline;
3756
3757        screen.open_ask_workspace(&tx);
3758        assert!(screen.panels.is_showing_ask(), "still showing Ask");
3759        assert_eq!(screen.panels.focused(), PanelKind::Editor);
3760        assert!(
3761            rx.try_recv().is_err(),
3762            "no gate flash while Ask is already showing"
3763        );
3764    }
3765
3766    // ── Following a link with the mouse: the screen's half of the rule ──────
3767    //
3768    // `ClickRun` owns which *mouse* events are one gesture and is tested
3769    // against a real event sequence there. What `track_click` owns is
3770    // everything the run cannot answer for itself — is this a mouse event, is
3771    // an overlay in the way, did the press land on the note buffer — and that
3772    // last one is a hit-test, which is where the frame-counted-as-buffer defect
3773    // lived.
3774
3775    /// Lay the screen out by rendering it, so the hit-test reads the rects a
3776    /// real frame produced rather than defaults.
3777    fn lay_out(screen: &mut EditorScreen) {
3778        let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 40)).unwrap();
3779        term.draw(|f| screen.render(f)).unwrap();
3780    }
3781
3782    /// The buffer's top-left cell, found by asking the screen's own gate — so
3783    /// the coordinates cannot drift from the layout the way a literal would.
3784    fn buffer_origin(screen: &EditorScreen) -> (u16, u16) {
3785        (0..40u16)
3786            .flat_map(|row| (0..120u16).map(move |col| (col, row)))
3787            .find(|(col, row)| screen.panels.is_note_buffer_cell(*col, *row))
3788            .expect("a laid-out screen always shows the note buffer")
3789    }
3790
3791    /// A cell on the frame `PanelSet::render` draws around the editor: the
3792    /// corner one row above and one column left of the buffer's first cell.
3793    ///
3794    /// The assert is the point, not a formality. Deriving the probe from
3795    /// [`buffer_origin`] means the gate picks where the test looks, so a gate
3796    /// that answered "the editor column" would slide this probe out of the
3797    /// column with it and every frame assertion below would hold vacuously.
3798    /// Focus is the independent witness: `PanelSet::handle_mouse` focuses the
3799    /// panel whose *column* contains the press, and it is the column, not the
3800    /// buffer, that this cell has to be inside for the tests to mean anything.
3801    fn frame_corner(screen: &mut EditorScreen, tx: &AppTx) -> (u16, u16) {
3802        let (col, row) = buffer_origin(screen);
3803        let corner = (col - 1, row - 1);
3804        screen.panels.focus(PanelKind::Drawer);
3805        screen.handle_input(&press_at(corner.0, corner.1), tx);
3806        assert_eq!(
3807            screen.panels.focused(),
3808            PanelKind::Editor,
3809            "precondition: the frame is inside the editor column"
3810        );
3811        // That probe was a real press. Drop it so the run starts clean.
3812        screen.clicks.end();
3813        corner
3814    }
3815
3816    fn press_at(col: u16, row: u16) -> InputEvent {
3817        use ratatui::crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
3818        InputEvent::Mouse(MouseEvent {
3819            kind: MouseEventKind::Down(MouseButton::Left),
3820            column: col,
3821            row,
3822            modifiers: KeyModifiers::NONE,
3823        })
3824    }
3825
3826    fn moved_at(col: u16, row: u16) -> InputEvent {
3827        use ratatui::crossterm::event::{KeyModifiers, MouseEvent, MouseEventKind};
3828        InputEvent::Mouse(MouseEvent {
3829            kind: MouseEventKind::Moved,
3830            column: col,
3831            row,
3832            modifiers: KeyModifiers::NONE,
3833        })
3834    }
3835
3836    /// A fixed origin, so the tests describe gaps rather than wall-clock time.
3837    fn at(millis: u64) -> std::time::Instant {
3838        static ORIGIN: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
3839        *ORIGIN.get_or_init(std::time::Instant::now) + std::time::Duration::from_millis(millis)
3840    }
3841
3842    #[tokio::test]
3843    async fn two_presses_on_the_buffer_are_a_double_click() {
3844        let (mut screen, _, _, _dir) = test_screen().await;
3845        lay_out(&mut screen);
3846        let (col, row) = buffer_origin(&screen);
3847
3848        assert!(!screen.track_click(&press_at(col, row), at(0)));
3849        assert!(screen.track_click(&press_at(col, row), at(120)));
3850    }
3851
3852    /// The gate is not the editor *column*: `PanelSet::render` frames the
3853    /// component, and a press on that frame never reaches the component's
3854    /// `handle_mouse`, so the cursor stays where it was. Counting those cells
3855    /// let two clicks on the `─ Editor` title bar follow whichever link the
3856    /// cursor was parked on — a note the user never pointed at.
3857    #[tokio::test]
3858    async fn a_press_on_the_editor_frame_is_never_half_of_a_double() {
3859        let (mut screen, _, _, _dir) = test_screen().await;
3860        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3861        lay_out(&mut screen);
3862        let (col, row) = frame_corner(&mut screen, &tx);
3863
3864        assert!(!screen.track_click(&press_at(col, row), at(0)));
3865        assert!(
3866            !screen.track_click(&press_at(col, row), at(120)),
3867            "two clicks on the frame are not a follow"
3868        );
3869    }
3870
3871    /// A frame press does not merely fail to pair — it ends the run, so it
3872    /// cannot sit unnoticed between two buffer presses and let them pair
3873    /// across it.
3874    #[tokio::test]
3875    async fn a_frame_press_separates_two_buffer_presses() {
3876        let (mut screen, _, _, _dir) = test_screen().await;
3877        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3878        lay_out(&mut screen);
3879        let (frame_col, frame_row) = frame_corner(&mut screen, &tx);
3880        let (col, row) = buffer_origin(&screen);
3881
3882        screen.track_click(&press_at(col, row), at(0));
3883        screen.track_click(&press_at(frame_col, frame_row), at(40));
3884        assert!(!screen.track_click(&press_at(col, row), at(80)));
3885    }
3886
3887    /// Only a press consults the hit-test. Any-event tracking delivers a
3888    /// `Moved` per cell of travel, including over the frame, and the pointer
3889    /// crossing the border mid-gesture is not the user doing anything.
3890    #[tokio::test]
3891    async fn motion_over_the_frame_does_not_break_a_double() {
3892        let (mut screen, _, _, _dir) = test_screen().await;
3893        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
3894        lay_out(&mut screen);
3895        let (frame_col, frame_row) = frame_corner(&mut screen, &tx);
3896        let (col, row) = buffer_origin(&screen);
3897
3898        screen.track_click(&press_at(col, row), at(0));
3899        assert!(!screen.track_click(&moved_at(frame_col, frame_row), at(40)));
3900        assert!(screen.track_click(&press_at(col, row), at(120)));
3901    }
3902
3903    #[tokio::test]
3904    async fn a_key_between_presses_ends_the_click_run() {
3905        let (mut screen, _, _, _dir) = test_screen().await;
3906        lay_out(&mut screen);
3907        let (col, row) = buffer_origin(&screen);
3908
3909        screen.track_click(&press_at(col, row), at(0));
3910        assert!(!screen.track_click(&chr('x'), at(40)));
3911        assert!(!screen.track_click(&press_at(col, row), at(80)));
3912    }
3913
3914    /// An overlay ends the run rather than merely failing to extend it. A modal
3915    /// is drawn over the editor column and a `SearchList` activates a row on a
3916    /// click-click of its own; without ending it, those presses stay in the run
3917    /// and pair with the first one that lands after the overlay closes.
3918    #[tokio::test]
3919    async fn an_overlay_ends_the_click_run() {
3920        let (mut screen, _, _, _dir) = test_screen().await;
3921        lay_out(&mut screen);
3922        let (col, row) = buffer_origin(&screen);
3923        let vault = screen.vault.clone();
3924
3925        screen.track_click(&press_at(col, row), at(0));
3926        screen.present_overlay(Box::new(ActiveDialog::create_note(
3927            VaultPath::note_path_from("x"),
3928            vault,
3929            None,
3930        )));
3931        assert!(
3932            !screen.track_click(&press_at(col, row), at(40)),
3933            "a press under an overlay is the overlay's"
3934        );
3935        screen.dismiss_overlay();
3936        assert!(
3937            !screen.track_click(&press_at(col, row), at(80)),
3938            "and neither press survives to pair with the next one"
3939        );
3940    }
3941
3942    /// End to end: the second press of a pair over a wikilink emits the same
3943    /// `FollowLink` the bound shortcut does. The first press is what placed the
3944    /// cursor the second one asks about, which is why one path serves both.
3945    #[tokio::test]
3946    async fn a_double_click_on_a_wikilink_follows_it() {
3947        let (mut screen, _, _, _dir) = test_screen().await;
3948        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
3949        screen
3950            .panels
3951            .editor_mut()
3952            .unwrap()
3953            .set_text("[[target note]]".to_string());
3954        lay_out(&mut screen);
3955        // Mid-link, so the exact gutter width the editor renders cannot move
3956        // the press off the span.
3957        let (col, row) = buffer_origin(&screen);
3958        let (col, row) = (col + 6, row);
3959
3960        screen.handle_input(&press_at(col, row), &tx);
3961        screen.handle_input(&press_at(col, row), &tx);
3962
3963        let followed = std::iter::from_fn(|| rx.try_recv().ok())
3964            .find_map(|ev| match ev {
3965                AppEvent::FollowLink(target) => Some(target),
3966                _ => None,
3967            })
3968            .expect("the double-click emitted no FollowLink");
3969        assert_eq!(followed, "target note");
3970    }
3971
3972    /// The first press only places the cursor. Following on a single click is
3973    /// the behaviour this replaced: a stray click while reading would navigate.
3974    #[tokio::test]
3975    async fn a_single_press_on_a_wikilink_only_places_the_cursor() {
3976        let (mut screen, _, _, _dir) = test_screen().await;
3977        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
3978        screen
3979            .panels
3980            .editor_mut()
3981            .unwrap()
3982            .set_text("[[target note]]".to_string());
3983        lay_out(&mut screen);
3984        let (col, row) = buffer_origin(&screen);
3985
3986        screen.handle_input(&press_at(col + 6, row), &tx);
3987
3988        assert!(
3989            !std::iter::from_fn(|| rx.try_recv().ok())
3990                .any(|ev| matches!(ev, AppEvent::FollowLink(_))),
3991            "one click is a cursor placement, not a navigation"
3992        );
3993        assert!(
3994            screen
3995                .panels
3996                .editor()
3997                .unwrap()
3998                .follow_target_at_cursor()
3999                .is_some(),
4000            "but it did land on the link, so the next press has something to follow"
4001        );
4002    }
4003}
4004
4005#[cfg(test)]
4006mod sort_routing_tests {
4007    use super::*;
4008    use crate::app_screen::AppScreen;
4009    use crate::components::events::SortTarget;
4010    use crate::components::file_list::{SortField, SortOrder};
4011
4012    async fn make_editor() -> (
4013        EditorScreen,
4014        AppTx,
4015        tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
4016    ) {
4017        let vault = crate::test_support::temp_vault("editor-sort").await;
4018        vault.validate_and_init().await.unwrap();
4019        let settings = std::sync::Arc::new(std::sync::RwLock::new(
4020            crate::settings::AppSettings::default(),
4021        ));
4022        let screen = EditorScreen::new(vault, VaultPath::root(), settings);
4023        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
4024        (screen, tx, rx)
4025    }
4026
4027    #[tokio::test(flavor = "multi_thread")]
4028    async fn sort_save_default_persists_to_settings() {
4029        let (mut screen, tx, _rx) = make_editor().await;
4030        screen
4031            .handle_app_message(
4032                AppEvent::SortChanged {
4033                    target: SortTarget::Sidebar,
4034                    field: SortField::Title,
4035                    order: SortOrder::Descending,
4036                    group_directories: true,
4037                    persist: true,
4038                },
4039                &tx,
4040            )
4041            .await;
4042        let s = screen.settings.read().unwrap();
4043        assert_eq!(
4044            s.default_sort_field,
4045            crate::settings::SortFieldSetting::Title
4046        );
4047        assert_eq!(
4048            s.default_sort_order,
4049            crate::settings::SortOrderSetting::Descending
4050        );
4051        assert!(s.group_directories);
4052    }
4053
4054    #[tokio::test(flavor = "multi_thread")]
4055    async fn sort_save_default_journal_dir_writes_journal_settings() {
4056        let (mut screen, tx, _rx) = make_editor().await;
4057        // Point the sidebar at the journal directory (current_dir set synchronously).
4058        let journal = screen.vault.journal_path().clone();
4059        screen.panels.sidebar_mut().navigate(journal, &tx);
4060
4061        screen
4062            .handle_app_message(
4063                AppEvent::SortChanged {
4064                    target: SortTarget::Sidebar,
4065                    field: SortField::Title,
4066                    order: SortOrder::Ascending,
4067                    group_directories: false,
4068                    persist: true,
4069                },
4070                &tx,
4071            )
4072            .await;
4073
4074        let s = screen.settings.read().unwrap();
4075        assert_eq!(
4076            s.journal_sort_field,
4077            crate::settings::SortFieldSetting::Title
4078        );
4079        assert_eq!(
4080            s.journal_sort_order,
4081            crate::settings::SortOrderSetting::Ascending
4082        );
4083        // Default (non-journal) settings must be untouched from their defaults.
4084        assert_eq!(
4085            s.default_sort_field,
4086            crate::settings::SortFieldSetting::Name
4087        );
4088    }
4089
4090    /// A non-persisting SortChanged (a plain dialog toggle) applies live but
4091    /// must NOT write settings.
4092    #[tokio::test(flavor = "multi_thread")]
4093    async fn sort_changed_without_persist_leaves_settings() {
4094        let (mut screen, tx, _rx) = make_editor().await;
4095        screen
4096            .handle_app_message(
4097                AppEvent::SortChanged {
4098                    target: SortTarget::Sidebar,
4099                    field: SortField::Title,
4100                    order: SortOrder::Descending,
4101                    group_directories: true,
4102                    persist: false,
4103                },
4104                &tx,
4105            )
4106            .await;
4107        let s = screen.settings.read().unwrap();
4108        assert_eq!(
4109            s.default_sort_field,
4110            crate::settings::SortFieldSetting::Name
4111        );
4112        assert_eq!(
4113            s.default_sort_order,
4114            crate::settings::SortOrderSetting::Ascending
4115        );
4116        assert!(!s.group_directories);
4117    }
4118}