kimun-notes 0.23.2

A terminal-based notes application
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
//! `PanelOrder` — the pure focus/order/visibility state machine for the
//! editor screen's persistent **Panels**. Keyed only on `PanelKind`, so it
//! carries no vault or heavy component state and is testable in isolation.
//! `PanelSet` (below) composes it with the concrete panels.

use std::sync::Arc;

use crate::server_client::RagClient;
use ratatui::Frame;
use ratatui::crossterm::event::{MouseButton, MouseEventKind};
use ratatui::layout::{Constraint, Direction, Layout, Position, Rect};

use crate::components::Component;
use crate::components::activity_rail::{ActivityRail, RAIL_WIDTH, RailCaps};
use crate::components::ask_thread::ThreadPanel;
use crate::components::attachment_view::AttachmentView;
use crate::components::drawer::{DrawerHost, DrawerView};
use crate::components::event_state::EventState;
use crate::components::events::{AppTx, InputEvent};
use crate::components::panel::{PanelKind, panel_block};
use crate::components::query_panel::QueryPanel;
use crate::components::sidebar::SidebarComponent;
use crate::components::text_editor::TextEditorComponent;
use crate::settings::themes::Theme;

/// Default drawer width in columns. Resizable at runtime by dragging the
/// drawer↔editor divider.
const DEFAULT_DRAWER_WIDTH: u16 = 34;
/// Narrowest the drawer can be dragged.
const MIN_DRAWER_WIDTH: u16 = 20;
/// Columns that must always remain for the editor when dragging the divider.
const MIN_EDITOR_WIDTH: u16 = 20;

struct Slot {
    kind: PanelKind,
    visible: bool,
}

/// Ordered panels + which one is focused. The layout is fixed left→right:
/// rail → drawer → editor. The rail and the editor are always visible; the
/// drawer toggles. Focus tracks a panel by kind and cycles over the visible
/// panels, wrapping at both ends.
pub struct PanelOrder {
    slots: Vec<Slot>,
    focus: usize,
}

impl PanelOrder {
    /// Default layout: rail → drawer (visible) → editor (focused).
    pub fn new() -> Self {
        let slots = vec![
            Slot {
                kind: PanelKind::Rail,
                visible: true,
            },
            Slot {
                kind: PanelKind::Drawer,
                visible: true,
            },
            Slot {
                kind: PanelKind::Editor,
                visible: true,
            },
        ];
        let focus = slots
            .iter()
            .position(|s| s.kind == PanelKind::Editor)
            .expect("editor slot present");
        Self { slots, focus }
    }

    /// The currently focused panel.
    pub fn focused(&self) -> PanelKind {
        self.slots[self.focus].kind
    }

    /// The visible panel one step left of focus, wrapping at the left end.
    pub fn prev_kind(&self) -> Option<PanelKind> {
        self.step(|i, n| (i + n - 1) % n)
    }

    /// The visible panel one step right of focus, wrapping at the right end.
    pub fn next_kind(&self) -> Option<PanelKind> {
        self.step(|i, n| (i + 1) % n)
    }

    /// Step through the *visible* panels from the focused one.
    fn step(&self, advance: impl Fn(usize, usize) -> usize) -> Option<PanelKind> {
        let visible = self.visible_in_order();
        let n = visible.len();
        if n < 2 {
            return None;
        }
        let i = visible.iter().position(|&k| k == self.focused())?;
        Some(visible[advance(i, n)])
    }

    /// Move focus to `kind`. No-op if the kind is not present.
    pub fn focus(&mut self, kind: PanelKind) {
        if let Some(i) = self.slots.iter().position(|s| s.kind == kind) {
            self.focus = i;
        }
    }

    /// Whether `kind` is currently visible.
    pub fn is_visible(&self, kind: PanelKind) -> bool {
        self.slots
            .iter()
            .find(|s| s.kind == kind)
            .is_some_and(|s| s.visible)
    }

    /// Reveal `kind`.
    pub fn show(&mut self, kind: PanelKind) {
        if let Some(s) = self.slots.iter_mut().find(|s| s.kind == kind) {
            s.visible = true;
        }
    }

    /// Hide `kind`. The rail and the editor are always visible, so hiding
    /// them is a no-op.
    pub fn hide(&mut self, kind: PanelKind) {
        if kind == PanelKind::Editor || kind == PanelKind::Rail {
            return;
        }
        if let Some(s) = self.slots.iter_mut().find(|s| s.kind == kind) {
            s.visible = false;
        }
        // If focus was on the panel we just hid, move it to the nearest
        // visible panel (the editor is always visible, so a target exists).
        if !self.slots[self.focus].visible {
            self.focus = self.nearest_visible(self.focus);
        }
    }

    /// The visible panels in their current left→right order. Drives the
    /// render layout: each panel contributes one column in this sequence.
    pub fn visible_in_order(&self) -> Vec<PanelKind> {
        self.slots
            .iter()
            .filter(|s| s.visible)
            .map(|s| s.kind)
            .collect()
    }

    /// Index of the nearest visible slot, searching outward from `from`.
    /// Falls back to `from` if somehow nothing is visible (cannot happen —
    /// the editor is always visible).
    fn nearest_visible(&self, from: usize) -> usize {
        let n = self.slots.len();
        (1..n)
            .flat_map(|d| [from.checked_sub(d), Some(from + d).filter(|&i| i < n)])
            .flatten()
            .find(|&i| self.slots[i].visible)
            .unwrap_or(from)
    }
}

impl Default for PanelOrder {
    fn default() -> Self {
        Self::new()
    }
}

/// Column width a panel occupies when laid out. The rail is fixed, the
/// drawer is runtime-resizable, and the editor fills the remainder.
fn panel_column(kind: PanelKind, drawer_width: u16) -> Constraint {
    match kind {
        PanelKind::Rail => Constraint::Length(RAIL_WIDTH),
        PanelKind::Drawer => Constraint::Length(drawer_width),
        PanelKind::Editor => Constraint::Min(0),
    }
}

/// Lay `visible` out left→right as one column per panel. Shared by `render`
/// and mouse hit-testing so clicks are always tested against the same rects
/// the panels were drawn into.
fn layout_columns(visible: &[PanelKind], area: Rect, drawer_width: u16) -> Vec<(PanelKind, Rect)> {
    let constraints: Vec<Constraint> = visible
        .iter()
        .map(|k| panel_column(*k, drawer_width))
        .collect();
    let columns = Layout::default()
        .direction(Direction::Horizontal)
        .constraints(constraints)
        .split(area);
    visible
        .iter()
        .copied()
        .zip(columns.iter().copied())
        .collect()
}

/// The panel whose column contains the given screen cell, if any.
fn kind_at(columns: &[(PanelKind, Rect)], column: u16, row: u16) -> Option<PanelKind> {
    columns
        .iter()
        .find(|(_, rect)| rect.contains(Position::new(column, row)))
        .map(|(kind, _)| *kind)
}

/// Which content the editor *area* currently shows — a pure selector, not a
/// container. The heavy stateful panels are
/// permanent residents of `PanelSet`: the note editor is `PanelSet::editor`
/// and the Ask workspace's conversation thread is `PanelSet::ask`, each living
/// for the whole screen lifetime regardless of which content is selected — so
/// their state (a live nvim backend, undo history, the conversation) survives
/// switching the area away and back. Only the read-only attachment view is
/// owned by its arm here, since it carries no state worth preserving. Exactly
/// one variant is active at a time.
enum EditorAreaContent {
    Note,
    // Boxed: `AttachmentView` can hold a full text-file preview plus
    // icons/key bindings — boxing keeps the enum from ballooning to the size
    // of that arm.
    Attachment(Box<AttachmentView>),
    /// Selects the resident `PanelSet::ask` for display (unit — the thread
    /// panel itself lives on `PanelSet`, not in this variant).
    Ask,
}

/// The editor screen's persistent **Panels** — the activity rail, the single
/// drawer, and the editor — plus the `PanelOrder` that decides visibility and
/// which one is focused. Routes input and render to the focused / visible
/// panels; the host (`EditorScreen`) reaches a specific drawer view through
/// the typed accessors for view-specific calls.
pub struct PanelSet {
    order: PanelOrder,
    rail: ActivityRail,
    drawer: DrawerHost,
    /// The note editor. Retained for the whole screen lifetime — including
    /// while an attachment or the Ask workspace is shown — so its backend
    /// (e.g. a live nvim process) and undo history survive the round trip.
    editor: TextEditorComponent,
    /// The Ask workspace's conversation thread + composer. Like `editor`, a
    /// permanent resident: retained for the whole screen lifetime so the
    /// conversation survives switching the editor area to another view and
    /// back, the same way the note editor does. Owns its own `RagClient`. Shown only
    /// when `content` is `EditorAreaContent::Ask`.
    ask: ThreadPanel,
    /// Which content the editor *area* currently shows: the note editor
    /// (resident `editor`), a read-only attachment view, or the Ask workspace
    /// (resident `ask`). See `EditorAreaContent`.
    content: EditorAreaContent,
    /// Current drawer width in columns (divider-draggable).
    drawer_width: u16,
    /// Whether a divider drag is in progress.
    dragging_divider: bool,
    /// The column each visible panel was drawn into on the last render —
    /// the single source of truth for mouse hit-testing. Empty until the
    /// first render.
    column_rects: Vec<(PanelKind, Rect)>,
}

impl PanelSet {
    pub fn from_panels(
        drawer: DrawerHost,
        editor: TextEditorComponent,
        icons: crate::settings::icons::Icons,
        key_bindings: crate::keys::KeyBindings,
        rail_caps: RailCaps,
    ) -> Self {
        let mut ask = ThreadPanel::new();
        ask.set_icons(icons.clone());
        Self {
            order: PanelOrder::new(),
            rail: ActivityRail::new(key_bindings, icons, rail_caps),
            drawer,
            editor,
            ask,
            content: EditorAreaContent::Note,
            drawer_width: DEFAULT_DRAWER_WIDTH,
            dragging_divider: false,
            column_rects: Vec::new(),
        }
    }

    /// Rebuild the activity rail with fresh feature visibility — the runtime
    /// path for SEM/ASK appearing or disappearing (RAG status change). Keeps
    /// the rail cursor on the drawer's active view so navigation continues
    /// from there.
    pub fn rebuild_rail(
        &mut self,
        key_bindings: crate::keys::KeyBindings,
        icons: crate::settings::icons::Icons,
        rail_caps: RailCaps,
    ) {
        let active = self.drawer.active_view();
        self.ask.set_icons(icons.clone());
        self.rail = ActivityRail::new(key_bindings, icons, rail_caps);
        self.rail.set_cursor(active);
    }

    /// Whether the activity rail currently shows `view` (feature gate on).
    #[cfg(test)]
    pub fn rail_shows(&self, view: DrawerView) -> bool {
        self.rail.shows(view)
    }

    /// The single injection point for the live RAG client: hands it to the
    /// resident Ask panel, which derives its composer-enabled state from the
    /// client's presence (a present client enables submission,
    /// `None` disables it without evicting the thread). Because the panel is
    /// resident, one call keeps it correct whether or not Ask is on screen.
    pub fn set_ask_client(&mut self, client: Option<Arc<RagClient>>) {
        self.ask.set_client(client);
    }

    // ── Order / focus / visibility (delegate to PanelOrder) ─────────────────

    pub fn focused(&self) -> PanelKind {
        self.order.focused()
    }

    /// Status-bar label for the focused panel; the drawer resolves to its
    /// active view's label.
    pub fn focused_label(&self) -> &'static str {
        match self.order.focused() {
            PanelKind::Drawer => self.drawer.active_view().label(),
            // The editor area showing the Ask workspace reads as ASK, not
            // EDITOR — mirrors the panel frame's "Ask" title.
            PanelKind::Editor if self.is_showing_ask() => DrawerView::Ask.label(),
            kind => kind.label(),
        }
    }

    pub fn prev_kind(&self) -> Option<PanelKind> {
        self.order.prev_kind()
    }

    pub fn next_kind(&self) -> Option<PanelKind> {
        self.order.next_kind()
    }

    pub fn is_visible(&self, kind: PanelKind) -> bool {
        self.order.is_visible(kind)
    }

    pub fn show(&mut self, kind: PanelKind) {
        self.order.show(kind);
    }

    pub fn hide(&mut self, kind: PanelKind) {
        self.order.hide(kind);
    }

    /// Move focus to `kind`. Any transition away from the editor closes its
    /// autocomplete popup so it doesn't linger while another panel owns input.
    pub fn focus(&mut self, kind: PanelKind) {
        if kind != PanelKind::Editor {
            self.editor.close_autocomplete();
        }
        self.order.focus(kind);
    }

    // ── Drawer view control ─────────────────────────────────────────────────

    pub fn active_drawer_view(&self) -> DrawerView {
        self.drawer.active_view()
    }

    /// Whether the drawer's active view is a text-input context (status-bar
    /// ⌨/≣ indicator).
    pub fn drawer_is_text_input(&self) -> bool {
        self.drawer.is_text_input()
    }

    /// Grow/shrink the drawer by `delta` columns (leader window commands),
    /// clamped to the same bounds the divider drag enforces.
    pub fn adjust_drawer_width(&mut self, delta: i16) {
        // Before the first render there are no rects to clamp against —
        // skip rather than allow an unbounded grow.
        let Some(right) = self.column_rects.iter().map(|(_, r)| r.right()).max() else {
            return;
        };
        let new = self.drawer_width.saturating_add_signed(delta);
        let max_width = right.saturating_sub(RAIL_WIDTH + MIN_EDITOR_WIDTH);
        self.drawer_width = new.clamp(MIN_DRAWER_WIDTH, max_width.max(MIN_DRAWER_WIDTH));
    }

    /// Switch the drawer's active `view` and rail cursor *without* changing
    /// its visibility — for paths that must not force-reveal a drawer the user
    /// explicitly hid (e.g. leaving the Ask workspace when a note opens).
    pub fn switch_drawer_view(&mut self, view: DrawerView) {
        self.drawer.set_view(view);
        self.rail.set_cursor(view);
    }

    /// Switch the drawer to `view` and reveal it. Keeps the rail cursor in
    /// step so keyboard navigation continues from the active item.
    pub fn open_drawer_view(&mut self, view: DrawerView) {
        self.switch_drawer_view(view);
        self.order.show(PanelKind::Drawer);
    }

    // ── Typed accessors for panel-specific calls ───────────────────────────

    pub fn sidebar(&self) -> &SidebarComponent {
        self.drawer.sidebar()
    }
    pub fn sidebar_mut(&mut self) -> &mut SidebarComponent {
        self.drawer.sidebar_mut()
    }
    /// The note editor, or `None` while an attachment or the Ask workspace is
    /// shown in its place. Callers reaching for the editor cross a mode
    /// boundary and must handle that case.
    pub fn editor(&self) -> Option<&TextEditorComponent> {
        matches!(self.content, EditorAreaContent::Note).then_some(&self.editor)
    }
    pub fn editor_mut(&mut self) -> Option<&mut TextEditorComponent> {
        if !matches!(self.content, EditorAreaContent::Note) {
            return None;
        }
        Some(&mut self.editor)
    }

    /// Show `view` in the editor area, replacing any prior attachment/Ask
    /// content and hiding the note editor. Closes the editor's autocomplete
    /// so it can't linger under the attachment, and focuses the editor panel.
    pub fn show_attachment(&mut self, view: AttachmentView) {
        self.editor.close_autocomplete();
        self.content = EditorAreaContent::Attachment(Box::new(view));
        self.order.focus(PanelKind::Editor);
    }

    /// Return the editor area to the note editor, discarding any attachment.
    /// No-op when already showing the editor, and — unlike `hide_ask` — a
    /// no-op when showing the Ask workspace too: this method's contract is
    /// specifically about attachments, so it leaves Ask content alone (use
    /// `hide_ask` for that).
    pub fn clear_attachment(&mut self) {
        if matches!(self.content, EditorAreaContent::Attachment(_)) {
            self.content = EditorAreaContent::Note;
        }
    }

    /// Whether the editor area is currently showing an attachment.
    pub fn is_showing_attachment(&self) -> bool {
        matches!(self.content, EditorAreaContent::Attachment(_))
    }

    /// The vault path of the attachment on show, if any — used to open it with
    /// the OS default program.
    pub fn attachment_path(&self) -> Option<&kimun_core::nfs::VaultPath> {
        match &self.content {
            EditorAreaContent::Attachment(view) => Some(view.path()),
            _ => None,
        }
    }

    /// Select the resident Ask workspace as the editor-area content, hiding
    /// the note editor. Mirrors `show_attachment`: closes the editor's
    /// autocomplete and focuses the editor panel. The thread persists by
    /// residency — this only flips the selector.
    pub fn show_ask(&mut self) {
        self.editor.close_autocomplete();
        self.content = EditorAreaContent::Ask;
        self.order.focus(PanelKind::Editor);
    }

    /// Return the editor area to the note editor when it's showing Ask. The
    /// resident thread panel is untouched — its conversation survives. No-op
    /// for any other content (mirrors `clear_attachment`'s scoping).
    pub fn hide_ask(&mut self) {
        if matches!(self.content, EditorAreaContent::Ask) {
            self.content = EditorAreaContent::Note;
        }
    }

    /// The resident Ask panel (always present; shown only when `content` is
    /// `Ask`).
    pub fn ask(&self) -> &ThreadPanel {
        &self.ask
    }
    /// The resident Ask panel, mutably.
    pub fn ask_mut(&mut self) -> &mut ThreadPanel {
        &mut self.ask
    }

    /// Whether the editor area is currently showing the Ask workspace.
    pub fn is_showing_ask(&self) -> bool {
        matches!(self.content, EditorAreaContent::Ask)
    }

    /// The active editor-area content as a `Component` — the attachment view
    /// or Ask panel when one is shown, otherwise the note editor. Lets
    /// input/hint routing dispatch once instead of branching on
    /// `self.content` at each site. (Render stays separate: it wraps the
    /// editor in its own dirty-title block.)
    fn editor_area(&self) -> &dyn Component {
        match &self.content {
            EditorAreaContent::Attachment(view) => view.as_ref(),
            EditorAreaContent::Ask => &self.ask,
            EditorAreaContent::Note => &self.editor,
        }
    }
    pub fn query(&self) -> &QueryPanel {
        self.drawer.query()
    }
    pub fn query_mut(&mut self) -> &mut QueryPanel {
        self.drawer.query_mut()
    }
    pub fn semantic_mut(&mut self) -> &mut crate::components::semantic_search::SemanticPanel {
        self.drawer.semantic_mut()
    }
    pub fn ask_sources_mut(&mut self) -> &mut crate::components::ask_sources::SourcesPanel {
        self.drawer.ask_sources_mut()
    }
    pub fn tags_mut(&mut self) -> &mut crate::components::drawer_views::TagsPanel {
        self.drawer.tags_mut()
    }
    pub fn links_mut(&mut self) -> &mut crate::components::drawer_views::LinksPanel {
        self.drawer.links_mut()
    }
    pub fn outline_mut(&mut self) -> &mut crate::components::drawer_views::OutlinePanel {
        self.drawer.outline_mut()
    }
    pub fn drawer_set_config_info(&mut self, info: crate::components::drawer::ConfigInfo) {
        self.drawer.set_config_info(info);
    }

    // ── Routing ────────────────────────────────────────────────────────────

    /// Footer hints for the focused panel.
    pub fn focused_hints(&self) -> Vec<(String, String)> {
        match self.order.focused() {
            PanelKind::Rail => self.rail.hint_shortcuts(),
            PanelKind::Drawer => self.drawer.hint_shortcuts(),
            PanelKind::Editor => self.editor_area().hint_shortcuts(),
        }
    }

    /// Route an input event to the focused panel.
    pub fn handle_input(&mut self, event: &InputEvent, tx: &AppTx) -> EventState {
        match self.order.focused() {
            PanelKind::Rail => self.rail.handle_input(event, tx),
            PanelKind::Drawer => self.drawer.handle_input(event, tx),
            PanelKind::Editor => self.editor_area_handle_input(event, tx),
        }
    }

    /// Deliver an input event to the editor-area content. The Ask arm calls
    /// the resident panel's inherent `ThreadPanel::handle_input` (it derives
    /// submission from its own client); the others use the trait. Each arm
    /// borrows a distinct field, disjoint from `content`.
    fn editor_area_handle_input(&mut self, event: &InputEvent, tx: &AppTx) -> EventState {
        match &mut self.content {
            EditorAreaContent::Ask => self.ask.handle_input(event, tx),
            EditorAreaContent::Attachment(view) => view.handle_input(event, tx),
            EditorAreaContent::Note => self.editor.handle_input(event, tx),
        }
    }

    /// Whether a press on this cell points *at* somewhere in the note buffer.
    ///
    /// Three conditions, and only the first is about geometry:
    ///
    /// - **Inside the editor component itself.** Asked of the component, not of
    ///   [`Self::column_rects`], because the column is wider than the buffer: it
    ///   also holds the frame `render` draws around the component (and, to its
    ///   left, the divider that [`Self::handle_mouse`] claims before any panel
    ///   sees it). A press on either is out of the component's bounds, so it
    ///   returns `NotConsumed` and the cursor never moves.
    /// - **The editor area is showing the note.** It may instead hold an
    ///   attachment preview or the Ask workspace, neither of which has a cursor
    ///   or a link under the pointer — an attachment would launch an external
    ///   program and Ask would swallow the press.
    /// - **The mouse drives the cursor.** False under the **nvim** backend,
    ///   where a press never moves the cursor at all, so anything reading the
    ///   cursor afterwards reads wherever the *keyboard* left it.
    ///
    /// Every one of them is the same question asked of a different layer: did
    /// this press *place the cursor*? Anything that answers a press by reading
    /// the cursor — following a link, most obviously — has to ask all three, or
    /// it acts on a position the press never set. The column alone was the
    /// original gate, and each of the others was a defect before it was a
    /// condition. Callers that only want the column should not reuse this.
    pub fn is_note_buffer_cell(&self, column: u16, row: u16) -> bool {
        matches!(self.content, EditorAreaContent::Note)
            && self.editor.mouse_drives_cursor()
            && self.editor.covers(column, row)
    }

    /// The divider hit zone: the drawer's right border column (the cell
    /// between drawer content and editor).
    fn on_divider(&self, column: u16, row: u16) -> bool {
        self.column_rects
            .iter()
            .find(|(kind, _)| *kind == PanelKind::Drawer)
            .is_some_and(|(_, rect)| {
                rect.height > 0
                    && column == rect.right().saturating_sub(1)
                    && row >= rect.y
                    && row < rect.bottom()
            })
    }

    /// Apply a divider drag: the drawer's new width follows the cursor,
    /// clamped so both the drawer and the editor keep a usable minimum.
    fn drag_divider_to(&mut self, column: u16) {
        let Some((_, drawer_rect)) = self
            .column_rects
            .iter()
            .find(|(kind, _)| *kind == PanelKind::Drawer)
        else {
            return;
        };
        let total_right = self
            .column_rects
            .iter()
            .map(|(_, r)| r.right())
            .max()
            .unwrap_or(drawer_rect.right());
        let max_width = total_right
            .saturating_sub(drawer_rect.x)
            .saturating_sub(MIN_EDITOR_WIDTH);
        let new_width = column.saturating_sub(drawer_rect.x).saturating_add(1);
        self.drawer_width = new_width.clamp(MIN_DRAWER_WIDTH, max_width.max(MIN_DRAWER_WIDTH));
    }

    /// Route a mouse event by hit-testing the panel columns from the last
    /// render. Dragging the drawer↔editor divider resizes the drawer. A
    /// button-down click focuses the panel under the cursor — the one
    /// consistent click-to-focus rule for every panel — and the event is
    /// then forwarded to that panel for its internal behavior (cursor
    /// placement, list selection, scrolling). Events outside every column
    /// (or before the first render) are not consumed.
    pub fn handle_mouse(&mut self, event: &InputEvent, tx: &AppTx) -> EventState {
        let InputEvent::Mouse(mouse) = event else {
            return EventState::NotConsumed;
        };

        // Divider drag lifecycle.
        match mouse.kind {
            MouseEventKind::Down(MouseButton::Left) if self.on_divider(mouse.column, mouse.row) => {
                self.dragging_divider = true;
                return EventState::Consumed;
            }
            MouseEventKind::Drag(MouseButton::Left) if self.dragging_divider => {
                self.drag_divider_to(mouse.column);
                return EventState::Consumed;
            }
            MouseEventKind::Up(MouseButton::Left) if self.dragging_divider => {
                self.dragging_divider = false;
                return EventState::Consumed;
            }
            _ => {}
        }

        let Some(kind) = kind_at(&self.column_rects, mouse.column, mouse.row) else {
            return EventState::NotConsumed;
        };
        if matches!(mouse.kind, MouseEventKind::Down(_)) {
            self.focus(kind);
        }
        match kind {
            PanelKind::Rail => {
                self.rail.handle_input(event, tx);
            }
            PanelKind::Drawer => {
                self.drawer.handle_mouse(event, tx);
            }
            PanelKind::Editor => {
                self.editor_area_handle_input(event, tx);
            }
        }
        EventState::Consumed
    }

    /// Lay the visible panels out left→right and render each. `show_focus`
    /// is false while an overlay is open, so no panel draws its focused
    /// highlight under the overlay.
    pub fn render(&mut self, f: &mut Frame, area: Rect, theme: &Theme, show_focus: bool) {
        let visible = self.order.visible_in_order();
        if visible.is_empty() {
            return;
        }
        let columns = layout_columns(&visible, area, self.drawer_width);
        self.column_rects = columns.clone();

        let focused = self.order.focused();
        let drawer_view = self
            .is_visible(PanelKind::Drawer)
            .then(|| self.drawer.active_view());
        for (kind, rect) in &columns {
            let is_focused = show_focus && *kind == focused;
            let rect = *rect;
            match kind {
                PanelKind::Rail => self.rail.render(f, rect, theme, is_focused, drawer_view),
                PanelKind::Drawer => self.drawer.render(f, rect, theme, is_focused),
                PanelKind::Editor => {
                    // The editor area's frame is drawn here (not by the
                    // component) so the dirty marker and focus border live with
                    // the layout. The frame title reflects which content the
                    // area is showing — the note editor, an attachment, or Ask.
                    match &mut self.content {
                        EditorAreaContent::Attachment(view) => {
                            let block = panel_block("Attachment", theme, is_focused);
                            let inner = block.inner(rect);
                            f.render_widget(block, rect);
                            view.render(f, inner, theme, is_focused);
                        }
                        EditorAreaContent::Ask => {
                            let block = panel_block("Ask", theme, is_focused);
                            let inner = block.inner(rect);
                            f.render_widget(block, rect);
                            self.ask.render(f, inner, theme, is_focused);
                        }
                        EditorAreaContent::Note => {
                            let title = if self.editor.is_dirty() {
                                "Editor [+]"
                            } else {
                                "Editor"
                            };
                            let block = panel_block(title, theme, is_focused);
                            let inner = block.inner(rect);
                            f.render_widget(block, rect);
                            self.editor.render(f, inner, theme, is_focused);
                        }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::settings::AppSettings;
    use crate::test_support::{mouse_down_at, temp_vault};
    use ratatui::crossterm::event::{KeyModifiers, MouseEvent, MouseEventKind};
    use tokio::sync::mpsc::unbounded_channel;

    async fn make_panel_set() -> PanelSet {
        let vault = temp_vault("panelset").await;
        vault.validate_and_init().await.unwrap();
        let settings = AppSettings::default();
        let sidebar = SidebarComponent::new(
            settings.key_bindings.clone(),
            vault.clone(),
            settings.icons(),
            &settings,
        );
        let editor = TextEditorComponent::new(settings.key_bindings.clone(), &settings);
        let query = QueryPanel::new(
            vault.clone(),
            settings.key_bindings.clone(),
            settings.icons(),
        );
        let tags = crate::components::drawer_views::TagsPanel::new(
            vault.clone(),
            settings.icons(),
            settings.yank_combos(),
        );
        let links = crate::components::drawer_views::LinksPanel::new(
            vault.clone(),
            settings.icons(),
            settings.yank_combos(),
        );
        let semantic = crate::components::semantic_search::SemanticPanel::new(
            vault.clone(),
            std::sync::Arc::new(std::sync::RwLock::new(settings.clone())),
            settings.icons(),
            settings.yank_combos(),
        );
        let outline = crate::components::drawer_views::OutlinePanel::new(
            vault.clone(),
            settings.icons(),
            settings.yank_combos(),
        );
        let drawer = DrawerHost::new(
            vault,
            &settings.key_bindings,
            sidebar,
            query,
            semantic,
            tags,
            links,
            outline,
        );
        PanelSet::from_panels(
            drawer,
            editor,
            settings.icons(),
            settings.key_bindings,
            RailCaps {
                semantic: true,
                ask: true,
            },
        )
    }

    /// Lay the visible panels out over a fixed area by actually rendering them.
    ///
    /// Assigning `column_rects` directly would be shorter and wrong: the hit
    /// tests read the editor component's own rect too, and only `render`
    /// assigns that. A layout that sets one and not the other describes a frame
    /// that never existed.
    fn lay_out(panels: &mut PanelSet) {
        let area = Rect::new(0, 0, 120, 40);
        let theme = crate::settings::themes::Theme::default();
        let mut term =
            ratatui::Terminal::new(ratatui::backend::TestBackend::new(area.width, area.height))
                .unwrap();
        term.draw(|f| panels.render(f, area, &theme, true)).unwrap();
    }

    /// A cell in the middle of the editor column, as laid out.
    fn editor_cell(panels: &PanelSet) -> (u16, u16) {
        let (_, rect) = panels
            .column_rects
            .iter()
            .find(|(kind, _)| *kind == PanelKind::Editor)
            .expect("the editor is always visible");
        (rect.x + rect.width / 2, rect.y + rect.height / 2)
    }

    /// The gate is not merely geometric. It read as "the editor column" once,
    /// and a double-click in the Ask workspace was swallowed while one in an
    /// attachment preview spawned an external viewer — the same cell, three
    /// different things underneath it.
    #[tokio::test]
    async fn the_note_buffer_gate_tracks_what_the_editor_area_shows() {
        let mut panels = make_panel_set().await;
        lay_out(&mut panels);
        let (col, row) = editor_cell(&panels);
        assert!(
            panels.is_note_buffer_cell(col, row),
            "the note buffer is what the gate is for"
        );

        panels.show_ask();
        assert!(
            !panels.is_note_buffer_cell(col, row),
            "the Ask workspace has no cursor to point at"
        );

        panels.hide_ask();
        assert!(panels.is_note_buffer_cell(col, row), "and back again");
    }

    /// A divider press is claimed before any panel sees it and never changes
    /// focus, so it must not count as pointing at the buffer either.
    #[tokio::test]
    async fn the_note_buffer_gate_rejects_the_divider_and_other_columns() {
        let mut panels = make_panel_set().await;
        lay_out(&mut panels);
        let (_, drawer) = panels
            .column_rects
            .iter()
            .find(|(kind, _)| *kind == PanelKind::Drawer)
            .expect("the drawer is visible by default");
        let (divider_col, row) = (drawer.right().saturating_sub(1), drawer.y + 1);
        assert!(panels.on_divider(divider_col, row), "precondition");
        assert!(!panels.is_note_buffer_cell(divider_col, row));
        assert!(
            !panels.is_note_buffer_cell(drawer.x + 1, row),
            "and the drawer is not the editor"
        );
    }

    /// The editor *column* is not the editor *buffer*: `PanelSet::render` draws
    /// a bordered frame around the component and hands it only the interior.
    /// A press on the frame is out of the component's bounds, so it returns
    /// `NotConsumed` and the cursor never moves — counting those cells let two
    /// clicks on the `─ Editor` title bar follow whichever link the cursor was
    /// parked on, a note the user never pointed at.
    #[tokio::test]
    async fn the_note_buffer_gate_rejects_the_editor_frame() {
        let mut panels = make_panel_set().await;
        lay_out(&mut panels);
        let (_, rect) = panels
            .column_rects
            .iter()
            .find(|(kind, _)| *kind == PanelKind::Editor)
            .expect("the editor is always visible");
        let rect = *rect;
        let (mid_col, mid_row) = (rect.x + rect.width / 2, rect.y + rect.height / 2);
        assert!(
            panels.is_note_buffer_cell(mid_col, mid_row),
            "precondition: the interior still counts"
        );
        assert!(
            !panels.is_note_buffer_cell(mid_col, rect.y),
            "the title row is frame"
        );
        assert!(
            !panels.is_note_buffer_cell(mid_col, rect.bottom() - 1),
            "so is the bottom border"
        );
        assert!(
            !panels.is_note_buffer_cell(rect.x, mid_row),
            "so is the left border"
        );
        assert!(
            !panels.is_note_buffer_cell(rect.right() - 1, mid_row),
            "so is the right border"
        );
    }

    fn scroll_at(col: u16, row: u16) -> InputEvent {
        InputEvent::Mouse(MouseEvent {
            kind: MouseEventKind::ScrollDown,
            column: col,
            row,
            modifiers: KeyModifiers::NONE,
        })
    }

    fn drag_at(col: u16, row: u16) -> InputEvent {
        InputEvent::Mouse(MouseEvent {
            kind: MouseEventKind::Drag(MouseButton::Left),
            column: col,
            row,
            modifiers: KeyModifiers::NONE,
        })
    }

    fn up_at(col: u16, row: u16) -> InputEvent {
        InputEvent::Mouse(MouseEvent {
            kind: MouseEventKind::Up(MouseButton::Left),
            column: col,
            row,
            modifiers: KeyModifiers::NONE,
        })
    }

    /// A button-down click focuses the panel whose column it lands in — for
    /// every panel, in any prior focus state.
    #[tokio::test]
    async fn click_focuses_panel_under_cursor() {
        let mut panels = make_panel_set().await;
        lay_out(&mut panels);
        let (tx, _rx) = unbounded_channel();

        assert_eq!(panels.focused(), PanelKind::Editor);
        // Rail (0..7) | Drawer (7..41) | Editor (41..120).
        assert_eq!(
            panels.handle_mouse(&mouse_down_at(3, 5), &tx),
            EventState::Consumed
        );
        assert_eq!(panels.focused(), PanelKind::Rail);
        assert_eq!(
            panels.handle_mouse(&mouse_down_at(20, 5), &tx),
            EventState::Consumed
        );
        assert_eq!(panels.focused(), PanelKind::Drawer);
        // Regression: a click on the editor must focus it even while another
        // panel is focused.
        assert_eq!(
            panels.handle_mouse(&mouse_down_at(60, 5), &tx),
            EventState::Consumed
        );
        assert_eq!(panels.focused(), PanelKind::Editor);
    }

    /// Before the first render no rects exist, and clicks outside every
    /// column must not move focus.
    #[tokio::test]
    async fn click_outside_panels_changes_nothing() {
        let mut panels = make_panel_set().await;
        let (tx, _rx) = unbounded_channel();

        // No render yet → no rects → nothing to hit.
        assert_eq!(
            panels.handle_mouse(&mouse_down_at(10, 10), &tx),
            EventState::NotConsumed
        );
        assert_eq!(panels.focused(), PanelKind::Editor);

        lay_out(&mut panels);
        // Cells outside the laid-out area miss.
        assert_eq!(
            panels.handle_mouse(&mouse_down_at(10, 50), &tx),
            EventState::NotConsumed
        );
        assert_eq!(panels.focused(), PanelKind::Editor);
    }

    /// Scrolling routes to the panel under the cursor without stealing focus.
    #[tokio::test]
    async fn scroll_does_not_change_focus() {
        let mut panels = make_panel_set().await;
        lay_out(&mut panels);
        let (tx, _rx) = unbounded_channel();

        assert_eq!(
            panels.handle_mouse(&scroll_at(20, 5), &tx),
            EventState::Consumed
        );
        assert_eq!(panels.focused(), PanelKind::Editor);
    }

    /// Dragging the drawer↔editor divider resizes the drawer, clamped to the
    /// minimum widths on both sides.
    #[tokio::test]
    async fn divider_drag_resizes_drawer() {
        let mut panels = make_panel_set().await;
        lay_out(&mut panels);
        let (tx, _rx) = unbounded_channel();

        // Drawer occupies 7..41; the divider is its right border column (40).
        assert_eq!(
            panels.handle_mouse(&mouse_down_at(40, 5), &tx),
            EventState::Consumed
        );
        assert_eq!(
            panels.handle_mouse(&drag_at(60, 5), &tx),
            EventState::Consumed
        );
        assert_eq!(panels.drawer_width, 54); // 60 - 7 + 1
        // Dragging far left clamps to the minimum drawer width.
        assert_eq!(
            panels.handle_mouse(&drag_at(0, 5), &tx),
            EventState::Consumed
        );
        assert_eq!(panels.drawer_width, MIN_DRAWER_WIDTH);
        // Dragging far right clamps so the editor keeps its minimum.
        assert_eq!(
            panels.handle_mouse(&drag_at(200, 5), &tx),
            EventState::Consumed
        );
        assert_eq!(panels.drawer_width, 120 - 7 - MIN_EDITOR_WIDTH);
        // Release ends the drag: further drags are plain panel events.
        assert_eq!(
            panels.handle_mouse(&up_at(80, 5), &tx),
            EventState::Consumed
        );
        let width_before = panels.drawer_width;
        panels.handle_mouse(&drag_at(50, 5), &tx);
        assert_eq!(panels.drawer_width, width_before);
    }

    #[test]
    fn default_focus_is_editor() {
        let order = PanelOrder::new();
        assert_eq!(order.focused(), PanelKind::Editor);
    }

    #[test]
    fn focus_cycle_wraps_over_visible_panels() {
        let mut order = PanelOrder::new();
        // Focus = editor (right end); next wraps to the rail.
        assert_eq!(order.next_kind(), Some(PanelKind::Rail));
        assert_eq!(order.prev_kind(), Some(PanelKind::Drawer));

        order.focus(PanelKind::Rail);
        assert_eq!(order.prev_kind(), Some(PanelKind::Editor)); // wrap left
        assert_eq!(order.next_kind(), Some(PanelKind::Drawer));
    }

    #[test]
    fn focus_cycle_skips_hidden_drawer() {
        let mut order = PanelOrder::new();
        order.hide(PanelKind::Drawer);
        assert_eq!(order.next_kind(), Some(PanelKind::Rail));
        order.focus(PanelKind::Rail);
        assert_eq!(order.next_kind(), Some(PanelKind::Editor));
    }

    #[test]
    fn show_hide_toggles_visibility_except_rail_and_editor() {
        let mut order = PanelOrder::new();
        assert!(order.is_visible(PanelKind::Drawer));

        order.hide(PanelKind::Drawer);
        assert!(!order.is_visible(PanelKind::Drawer));
        order.show(PanelKind::Drawer);
        assert!(order.is_visible(PanelKind::Drawer));

        // The rail and the editor cannot be hidden.
        order.hide(PanelKind::Editor);
        assert!(order.is_visible(PanelKind::Editor));
        order.hide(PanelKind::Rail);
        assert!(order.is_visible(PanelKind::Rail));
    }

    #[test]
    fn hiding_focused_panel_moves_focus_to_visible() {
        let mut order = PanelOrder::new();
        order.focus(PanelKind::Drawer);
        order.hide(PanelKind::Drawer);
        // Focus cannot stay on a hidden panel.
        assert!(order.is_visible(order.focused()));
    }

    #[test]
    fn layout_columns_splits_area_in_panel_order() {
        let area = Rect::new(0, 0, 120, 40);
        let visible = [PanelKind::Rail, PanelKind::Drawer, PanelKind::Editor];
        let columns = layout_columns(&visible, area, DEFAULT_DRAWER_WIDTH);

        assert_eq!(columns.len(), 3);
        // Rail fixed, drawer at its width, editor takes the rest.
        assert_eq!(columns[0].0, PanelKind::Rail);
        assert_eq!(columns[0].1.width, RAIL_WIDTH);
        assert_eq!(columns[1].0, PanelKind::Drawer);
        assert_eq!(columns[1].1.width, DEFAULT_DRAWER_WIDTH);
        assert_eq!(columns[2].0, PanelKind::Editor);
        assert_eq!(columns[2].1.width, 120 - RAIL_WIDTH - DEFAULT_DRAWER_WIDTH);
        // Columns tile the area left→right.
        assert_eq!(columns[0].1.x, 0);
        assert_eq!(columns[1].1.x, RAIL_WIDTH);
        assert_eq!(columns[2].1.x, RAIL_WIDTH + DEFAULT_DRAWER_WIDTH);
    }

    #[test]
    fn hidden_drawer_gives_width_to_editor() {
        let area = Rect::new(0, 0, 120, 40);
        let visible = [PanelKind::Rail, PanelKind::Editor];
        let columns = layout_columns(&visible, area, DEFAULT_DRAWER_WIDTH);

        assert_eq!(columns.len(), 2);
        assert_eq!(columns[1].0, PanelKind::Editor);
        assert_eq!(columns[1].1.width, 120 - RAIL_WIDTH);
    }

    #[test]
    fn kind_at_hit_tests_panel_columns() {
        let area = Rect::new(0, 0, 120, 40);
        let visible = [PanelKind::Rail, PanelKind::Drawer, PanelKind::Editor];
        let columns = layout_columns(&visible, area, DEFAULT_DRAWER_WIDTH);

        assert_eq!(kind_at(&columns, 0, 0), Some(PanelKind::Rail));
        assert_eq!(kind_at(&columns, 6, 10), Some(PanelKind::Rail));
        assert_eq!(kind_at(&columns, 7, 10), Some(PanelKind::Drawer));
        assert_eq!(kind_at(&columns, 40, 39), Some(PanelKind::Drawer));
        assert_eq!(kind_at(&columns, 41, 0), Some(PanelKind::Editor));
        assert_eq!(kind_at(&columns, 119, 39), Some(PanelKind::Editor));
        // Outside the laid-out area.
        assert_eq!(kind_at(&columns, 120, 10), None);
        assert_eq!(kind_at(&columns, 10, 40), None);
        // No columns yet (before the first render).
        assert_eq!(kind_at(&[], 10, 10), None);
    }

    #[test]
    fn open_drawer_view_reveals_and_switches() {
        let mut order = PanelOrder::new();
        order.hide(PanelKind::Drawer);
        assert!(!order.is_visible(PanelKind::Drawer));
        order.show(PanelKind::Drawer);
        assert!(order.is_visible(PanelKind::Drawer));
    }

    fn test_attachment_view() -> AttachmentView {
        let details = kimun_core::AttachmentDetails {
            path: kimun_core::nfs::VaultPath::new("a.png"),
            size: 0,
            modified_secs: 0,
            extension: Some("png".to_string()),
            content: kimun_core::AttachmentContent::Binary,
        };
        AttachmentView::new(
            details,
            crate::settings::icons::Icons::new(false),
            crate::keys::KeyBindings::empty(),
        )
    }

    #[tokio::test]
    async fn ask_content_hides_the_editor_and_leaving_restores_it() {
        let mut ps = make_panel_set().await;
        assert!(ps.editor().is_some());
        ps.show_ask();
        assert!(ps.editor().is_none());
        assert!(ps.is_showing_ask());
        // Leaving Ask returns the note editor; the resident thread survives.
        ps.hide_ask();
        assert!(!ps.is_showing_ask());
        assert!(ps.editor().is_some());
    }

    /// `set_ask_client` is the single injection point: it drives the resident
    /// Ask panel's client, which is its composer-enabled signal. No client ⇒
    /// disabled (never a forever-`Thinking` turn); a present client ⇒ enabled.
    #[tokio::test]
    async fn set_ask_client_drives_the_resident_panels_client() {
        let mut ps = make_panel_set().await;
        ps.set_ask_client(None);
        assert!(!ps.ask().has_client());
        // Handing a client back enables it. (A bare client over a throwaway
        // vault id is fine — it's never called here.)
        let client = std::sync::Arc::new(crate::server_client::RagClient::new(
            "http://localhost:0".to_string(),
            None,
            "vault".to_string(),
        ));
        ps.set_ask_client(Some(client));
        assert!(ps.ask().has_client());
    }

    #[tokio::test]
    async fn showing_an_attachment_replaces_ask() {
        let mut ps = make_panel_set().await;
        ps.show_ask();
        ps.show_attachment(test_attachment_view());
        assert!(!ps.is_showing_ask());
        assert!(ps.is_showing_attachment());
    }

    #[test]
    fn visible_in_order_skips_hidden() {
        let mut order = PanelOrder::new();
        assert_eq!(
            order.visible_in_order(),
            vec![PanelKind::Rail, PanelKind::Drawer, PanelKind::Editor]
        );
        order.hide(PanelKind::Drawer);
        assert_eq!(
            order.visible_in_order(),
            vec![PanelKind::Rail, PanelKind::Editor]
        );
    }
}