mnml-rs 0.2.13

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
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
//! Session save / restore — `<workspace>/.mnml/session.json`.
//!
//! `save_session_on_quit` writes open editor buffers + cursors + the
//! per-tab split tree + UI state; `try_restore_session` reads it back
//! on launch and re-opens the buffers + rebuilds the layout.
//!
//! Extracted from `app/mod.rs` (file-split follow-up). Pure
//! non-destructive move; no API change.

use super::*;

impl App {
    /// `[session] restore = true` ⇒ on quit, write the open editor buffers +
    /// their cursors to `<workspace>/.mnml/session.json` so the next launch can
    /// re-open them. Best-effort (errors are swallowed). No-op when restore is
    /// off, or when nothing is open.
    pub fn save_session_on_quit(&self) {
        if !self.config.session.restore {
            return;
        }
        // Save editor buffers in tab order, with PaneId → saved-index lookup
        // for the layout pass. Also fold the currently-open buffers' cursors
        // into `file_cursors` so per-file restore covers them even if the user
        // closes them after relaunch.
        let mut open: Vec<SavedBuffer> = Vec::new();
        let mut pane_to_idx: Vec<Option<usize>> = vec![None; self.panes.len()];
        let mut active: Option<usize> = None;
        let mut merged_cursors = self.file_cursors.clone();
        for (i, p) in self.panes.iter().enumerate() {
            if let Pane::Editor(b) = p
                && let Some(path) = &b.path
            {
                pane_to_idx[i] = Some(open.len());
                if self.active == Some(i) {
                    active = Some(open.len());
                }
                open.push(SavedBuffer {
                    path: path.to_string_lossy().into_owned(),
                    cursor_byte: b.editor.cursor(),
                    scroll: b.scroll,
                    breakpoints: b.breakpoints.clone(),
                    breakpoint_conditions: b.breakpoint_conditions.clone(),
                    breakpoint_hit_conditions: b.breakpoint_hit_conditions.clone(),
                    is_pinned: b.is_pinned,
                });
                merged_cursors.insert(path.clone(), (b.editor.cursor(), b.scroll));
            }
        }
        // Try to mirror the split tree. If any leaf isn't an editor we can save
        // (e.g. a transient pty / diff / browser pane), drop layout — the buffer
        // list alone is enough for the most common case.
        //
        // Multi-tab persistence: write one SavedLayout per tab page in
        // `layouts`, plus `active_layout` so restore lands on the right
        // tab. Keep `layout` (single-tab field) populated with the
        // active tab's layout so older mnml binaries reading this
        // session.json still get a sensible single-tab restore.
        let layouts: Vec<Option<SavedLayout>> = self
            .layouts
            .iter()
            .map(|l| saved_layout_from(l, &pane_to_idx))
            .collect();
        let layout = layouts.get(self.active_layout).cloned().unwrap_or(None);
        let saved = SavedSession {
            workspace: self.workspace.to_string_lossy().into_owned(),
            open,
            active,
            layout,
            layouts: Some(layouts),
            active_layout: Some(self.active_layout),
            tree_visible: Some(self.tree_visible),
            tree_root_expanded: Some(self.tree_root_expanded),
            tree_width: Some(self.tree_width),
            right_panel_visible: Some(self.right_panel_visible),
            right_panel_width: Some(self.right_panel_width),
            // 2026-06-28: persist hosted tabs by KIND so a restart
            // restores the right-panel state. AI is skipped — its
            // live state isn't worth chasing across restarts.
            right_panel_tabs: Some(
                self.right_panel_panes
                    .iter()
                    .filter_map(|pid| match self.panes.get(*pid) {
                        Some(Pane::Outline(_)) => Some("outline".to_string()),
                        Some(Pane::Diagnostics(_)) => Some("diagnostics".to_string()),
                        // code-reviewer W-1 2026-06-28: Tests + Grep
                        // are NOT serialised. Restoring them would
                        // mean either an idle placeholder (confusing)
                        // or auto-re-running on every startup
                        // (intrusive). User re-fires explicitly. AI
                        // already skipped (live state + auth). Was
                        // previously saved-but-dropped — bad UX.
                        _ => None,
                    })
                    .collect(),
            ),
            right_panel_active_idx: if self.right_panel_panes.is_empty() {
                None
            } else {
                Some(self.right_panel_active_idx)
            },
            git_section_expanded: Some(self.git_section_expanded),
            integration_section_expanded: Some(self.integration_section_expanded),
            git_branches_expanded: Some(self.git_branches_expanded),
            last_grep_query: if self.last_grep_query.is_empty() {
                None
            } else {
                Some(self.last_grep_query.clone())
            },
            tree_expanded_dirs: Some(
                self.tree
                    .expanded_dirs()
                    .into_iter()
                    .map(|p| p.to_string_lossy().into_owned())
                    .collect(),
            ),
            tree_show_hidden: Some(self.tree.show_hidden),
            // #1101 (2026-08-20) — new session-restore surfaces.
            // ActivitySection variants with a payload (LauncherIcon,
            // Mount) reference an index into a per-launch config
            // vector that can shift between runs; only unit variants
            // round-trip cleanly. Payload variants fall through to
            // the default (Explorer) on next start — safer than
            // restoring a stale index.
            active_section: match self.active_section {
                ActivitySection::LauncherIcon(_) | ActivitySection::Mount(_) => None,
                other => Some(format!("{other:?}").to_ascii_lowercase()),
            },
            fullscreen_mode: Some(self.fullscreen_mode).filter(|v| *v),
            bottom_panel_visible: Some(self.bottom_panel_visible).filter(|v| *v),
            bottom_panel_height: self
                .bottom_panel_visible
                .then_some(self.bottom_panel_height),
            bottom_panel_active_idx: (self.bottom_panel_visible
                && self.bottom_panel_active_idx > 0)
                .then_some(self.bottom_panel_active_idx),
            recent_commands: {
                let cap: Vec<String> = self.recent_commands.iter().take(50).cloned().collect();
                if cap.is_empty() { None } else { Some(cap) }
            },
            // #1112 (2026-08-20) — search-section persistence.
            search_case_sensitive: Some(self.search_case_sensitive).filter(|v| *v),
            search_whole_word: Some(self.search_whole_word).filter(|v| *v),
            search_regex: Some(self.search_regex).filter(|v| *v),
            search_history: {
                let cap: Vec<String> = self.search_history.iter().take(20).cloned().collect();
                if cap.is_empty() { None } else { Some(cap) }
            },
            extra_workspaces: self
                .extra_workspaces
                .iter()
                .map(|w| SavedExtraWorkspace {
                    name: w.name.clone(),
                    expanded: w.expanded,
                    expanded_dirs: w
                        .tree
                        .expanded_dirs()
                        .into_iter()
                        .map(|p| p.to_string_lossy().into_owned())
                        .collect(),
                    show_hidden: Some(w.tree.show_hidden),
                })
                .collect(),
            recent_files: self
                .recent_files
                .iter()
                .map(|p| p.to_string_lossy().into_owned())
                .collect(),
            browser_url_history: self.browser_url_history.clone(),
            last_browser_device: self.last_browser_device,
            theme: Some(crate::ui::theme::cur().name.to_string()),
            wrap: Some(self.config.ui.wrap),
            clock_show_utc: Some(self.clock_show_utc),
            claude_agents_age_filter: Some(match self.claude_agents_last_age_filter {
                crate::claude_agents::AgeFilter::Today => "today".to_string(),
                crate::claude_agents::AgeFilter::Week => "week".to_string(),
                crate::claude_agents::AgeFilter::Month => "month".to_string(),
                crate::claude_agents::AgeFilter::All => "all".to_string(),
            }),
            http_panel_collections_collapsed: {
                let coll_root = self.workspace.join(".mnml").join("collections");
                self.http_panel_collections_collapsed_dirs
                    .iter()
                    .filter_map(|p| p.strip_prefix(&coll_root).ok())
                    .map(|rel| rel.to_string_lossy().into_owned())
                    .collect()
            },
            dock_widgets: self.dock_widgets.clone(),
            dock_widget_next_id: if self.dock_widget_next_id > 0 {
                Some(self.dock_widget_next_id)
            } else {
                None
            },
            pty_session_names: {
                // Walk pty panes — record (session_id, display_name)
                // for any renamed Claude session so a later resume can
                // re-apply the name. Carry forward prior-launch entries
                // too (a Claude session not open this run still keeps
                // its saved name).
                let mut m = self.saved_pty_session_names.clone();
                for p in &self.panes {
                    if let Pane::Pty(s) = p
                        && let (Some(sid), Some(name)) = (&s.profile.session_id, &s.display_name)
                    {
                        m.insert(sid.clone(), name.clone());
                    }
                }
                m.into_iter().collect()
            },
            macros: self
                .macro_buffer
                .iter()
                .filter(|(_, keys)| !keys.is_empty())
                .map(|(reg, keys)| SavedMacro {
                    register: *reg,
                    keys: keys
                        .iter()
                        .map(|k| crate::input::keymap::Chord::of(k).to_spec())
                        .collect(),
                })
                .collect(),
            file_cursors: merged_cursors
                .iter()
                .map(|(p, &(c, s))| SavedFileCursor {
                    path: p.to_string_lossy().into_owned(),
                    cursor_byte: c,
                    scroll: s,
                })
                .collect(),
            global_marks: self
                .global_marks
                .iter()
                .map(|(&letter, (path, row, col))| SavedGlobalMark {
                    letter,
                    path: path.to_string_lossy().into_owned(),
                    row: *row,
                    col: *col,
                })
                .collect(),
            folds: {
                // Live panes take precedence — a currently-open buffer's
                // in-memory folds are fresher than whatever was last
                // captured on close in `file_folds`. Everything else in
                // `file_folds` (folds of buffers already closed this
                // session, or hydrated from a previous session) fills in.
                let mut merged: std::collections::HashMap<PathBuf, Vec<(usize, usize)>> =
                    self.file_folds.clone();
                for p in &self.panes {
                    if let Pane::Editor(b) = p
                        && let Some(path) = &b.path
                    {
                        if b.folds.is_empty() {
                            merged.remove(path);
                        } else {
                            merged.insert(
                                path.clone(),
                                b.folds.iter().map(|(&s, &e)| (s, e)).collect(),
                            );
                        }
                    }
                }
                merged
                    .into_iter()
                    .map(|(path, folds)| SavedFolds {
                        path: path.to_string_lossy().into_owned(),
                        folds,
                    })
                    .collect()
            },
            nav_back: self
                .nav_back
                .iter()
                .map(|np| SavedNavPoint {
                    path: np.path.to_string_lossy().into_owned(),
                    row: np.row,
                    col: np.col,
                })
                .collect(),
            nav_forward: self
                .nav_forward
                .iter()
                .map(|np| SavedNavPoint {
                    path: np.path.to_string_lossy().into_owned(),
                    row: np.row,
                    col: np.col,
                })
                .collect(),
            edit_history: self
                .panes
                .iter()
                .filter_map(|p| match p {
                    Pane::Editor(b) if !b.edit_history.is_empty() => {
                        b.path.as_ref().map(|path| SavedEditHistory {
                            path: path.to_string_lossy().into_owned(),
                            entries: b.edit_history.clone(),
                        })
                    }
                    _ => None,
                })
                .collect(),
            find_history: self.find_history.clone(),
            closed_buffers: self
                .closed_buffers
                .iter()
                .map(|(p, row, col)| SavedNavPoint {
                    path: p.to_string_lossy().into_owned(),
                    row: *row,
                    col: *col,
                })
                .collect(),
            ex_history: self.ex_history.clone(),
            dap_watches: self.dap_watches.clone(),
            harpoon: if self.harpoon.iter().all(|s| s.is_none()) {
                Vec::new()
            } else {
                self.harpoon
                    .iter()
                    .map(|s| s.as_ref().map(|p| p.to_string_lossy().into_owned()))
                    .collect()
            },
            git_graph_detail_col: self.git_graph_detail_col_override,
            diff_view_mode: if self.diff_view_mode_pref == crate::pane::DiffViewMode::Inline {
                None
            } else {
                Some(self.diff_view_mode_pref)
            },
            diff_wrap: self.diff_wrap_pref,
            ai_tokens_in: self.ai_tokens_in,
            ai_tokens_out: self.ai_tokens_out,
            suggest_shown: self.suggest_shown,
            suggest_accepted: self.suggest_accepted,
        };
        let Ok(text) = serde_json::to_string_pretty(&saved) else {
            return;
        };
        let dir = self.workspace.join(".mnml");
        let _ = std::fs::create_dir_all(&dir);
        let _ = std::fs::write(dir.join("session.json"), text);
    }

    /// Read `.mnml/session.json` and re-open the buffers in it (if the saved
    /// workspace matches). Called once from `main.rs` after `App::new` when
    /// `[session] restore = true`. Missing / mismatched / corrupt file ⇒ no-op.
    pub fn try_restore_session(&mut self) {
        if !self.config.session.restore {
            return;
        }
        let path = self.workspace.join(".mnml").join("session.json");
        let Ok(text) = std::fs::read_to_string(&path) else {
            return;
        };
        let Ok(saved) = serde_json::from_str::<SavedSession>(&text) else {
            return;
        };
        if saved.workspace != self.workspace.to_string_lossy() {
            return;
        }
        // saved-index → restored PaneId (None if the file was missing on disk).
        let mut idx_to_pane: Vec<Option<PaneId>> = vec![None; saved.open.len()];
        let mut active_pane: Option<PaneId> = None;
        for (i, b) in saved.open.iter().enumerate() {
            let p = std::path::Path::new(&b.path);
            if !p.exists() {
                continue;
            }
            self.open_path(p);
            if let Some(pid) = self.active {
                idx_to_pane[i] = Some(pid);
                if saved.active == Some(i) {
                    active_pane = Some(pid);
                }
                if let Some(Pane::Editor(buf)) = self.panes.get_mut(pid) {
                    // Restored buffers are not preview — otherwise the
                    // next open_path() in this loop would replace this
                    // one (preview-replacement) and we'd lose every
                    // buffer but the last. Pinned state is restored
                    // from the saved session (2026-06-21).
                    buf.is_preview = false;
                    buf.is_pinned = b.is_pinned;
                    let (row, col) = byte_to_row_col(buf.editor.text(), b.cursor_byte);
                    buf.editor.place_cursor(row, col);
                    buf.scroll = b.scroll;
                    // Restore DAP breakpoints (drop any past the file's
                    // current end — file may have shrunk while mnml was
                    // closed).
                    let last_line = buf.editor.line_count().saturating_sub(1) as u32;
                    buf.breakpoints = b
                        .breakpoints
                        .iter()
                        .filter(|&&l| l <= last_line)
                        .copied()
                        .collect();
                    // Restore conditional-breakpoint conditions, but
                    // only for lines that survived the breakpoints
                    // filter above — orphaned conditions (e.g. line was
                    // never a breakpoint, or got trimmed for shrinkage)
                    // would never be applied.
                    let live: std::collections::HashSet<u32> =
                        buf.breakpoints.iter().copied().collect();
                    buf.breakpoint_conditions = b
                        .breakpoint_conditions
                        .iter()
                        .filter(|(l, _)| live.contains(l))
                        .map(|(l, c)| (*l, c.clone()))
                        .collect();
                    buf.breakpoint_hit_conditions = b
                        .breakpoint_hit_conditions
                        .iter()
                        .filter(|(l, _)| live.contains(l))
                        .map(|(l, c)| (*l, c.clone()))
                        .collect();
                }
            }
        }
        // Multi-tab layouts: prefer the new `layouts` Vec when
        // present. Each tab restores independently; tabs whose
        // SavedLayout can't be remapped (a leaf pointed at a buffer
        // that no longer exists) fall back to Layout::Empty.
        if let Some(saved_layouts) = saved.layouts.as_ref()
            && !saved_layouts.is_empty()
        {
            let mut restored_layouts: Vec<Layout> = Vec::with_capacity(saved_layouts.len());
            let mut restored_actives: Vec<Option<PaneId>> = Vec::with_capacity(saved_layouts.len());
            for slot in saved_layouts {
                let lay = slot
                    .as_ref()
                    .and_then(|sl| layout_from_saved(sl, &idx_to_pane))
                    .unwrap_or(Layout::Empty);
                let first = lay.first_leaf();
                restored_layouts.push(lay);
                restored_actives.push(first);
            }
            self.layouts = restored_layouts;
            self.tab_actives = restored_actives;
            self.active_layout = saved.active_layout.unwrap_or(0).min(self.layouts.len() - 1);
            // Sync top-level active with the restored layout's first leaf.
            self.active = self.tab_actives[self.active_layout];
        } else if let Some(sl) = saved.layout.as_ref()
            && let Some(restored) = layout_from_saved(sl, &idx_to_pane)
        {
            // Legacy single-tab session.json — load it as the only tab.
            *self.layout_mut() = restored;
        }
        // qa-5th 2026-06-29 SEV-2 — session restore desync. If
        // saved.open is non-empty but layout is null (e.g. user
        // closed all panes via Ctrl+W then quit, leaving buffers
        // in the open[] list with no leaf to host them), every
        // buffer comes back as a pane but the bufferline strip
        // doesn't show them. Synthesize a LeafTabs containing
        // every editor pane so they're reachable via tab click.
        if matches!(self.layout(), Layout::Empty) && !self.panes.is_empty() {
            let editor_pids: Vec<PaneId> = self
                .panes
                .iter()
                .enumerate()
                .filter_map(|(i, p)| matches!(p, crate::pane::Pane::Editor(_)).then_some(i))
                .collect();
            if !editor_pids.is_empty() {
                let active = self.active.unwrap_or(editor_pids[0]);
                let active = if editor_pids.contains(&active) {
                    active
                } else {
                    editor_pids[0]
                };
                *self.layout_mut() = Layout::leaf_with_tabs(active, editor_pids);
                self.active = Some(active);
            }
        }
        // Restore the file-tree visibility flag too (`None` ⇒ leave the
        // launch-time default alone — an older session.json without the field).
        if let Some(v) = saved.tree_visible {
            self.tree_visible = v;
        }
        if let Some(v) = saved.tree_root_expanded {
            self.tree_root_expanded = v;
        }
        if let Some(v) = saved.right_panel_visible {
            self.right_panel_visible = v;
        }
        if let Some(v) = saved.right_panel_width {
            self.right_panel_width = v.clamp(8, 200);
        }
        // 2026-06-28 — re-host the right-panel tabs (Outline /
        // Diagnostics) from the saved kind list. Only fires when
        // the panel is visible; AI tabs were skipped on save.
        if self.right_panel_visible
            && let Some(kinds) = saved.right_panel_tabs
        {
            for kind in &kinds {
                match kind.as_str() {
                    "outline" => self.open_outline_pane(),
                    "diagnostics" => self.open_diagnostics_pane(),
                    _ => {}
                }
            }
            if let Some(idx) = saved.right_panel_active_idx
                && idx < self.right_panel_panes.len()
            {
                self.right_panel_active_idx = idx;
            }
        }
        if let Some(v) = saved.tree_width {
            self.tree_width = v.clamp(8, 200);
        }
        if let Some(v) = saved.integration_section_expanded {
            self.integration_section_expanded = v;
        }
        if let Some(v) = saved.git_branches_expanded {
            self.git_branches_expanded = v;
        }
        if let Some(v) = saved.last_grep_query {
            self.last_grep_query = v;
        }
        if let Some(v) = saved.git_section_expanded {
            self.git_section_expanded = v;
        }
        if let Some(dirs) = saved.tree_expanded_dirs {
            self.tree
                .set_expanded_dirs(dirs.into_iter().map(PathBuf::from));
        }
        if let Some(v) = saved.tree_show_hidden
            && self.tree.show_hidden != v
        {
            self.tree.show_hidden = v;
            self.tree.refresh();
        }
        // #1101 (2026-08-20) — restore active activity-bar section,
        // fullscreen, bottom panel, palette recents. Unknown /
        // renamed sections silently fall back to Explorer.
        if let Some(name) = saved.active_section.as_deref() {
            let s = match name {
                "explorer" => Some(ActivitySection::Explorer),
                "search" => Some(ActivitySection::Search),
                "git" => Some(ActivitySection::Git),
                "debug" => Some(ActivitySection::Debug),
                "integrations" => Some(ActivitySection::Integrations),
                "sessions" => Some(ActivitySection::Sessions),
                "agents" => Some(ActivitySection::Agents),
                "cloudagents" => Some(ActivitySection::CloudAgents),
                "http" => Some(ActivitySection::Http),
                "notes" => Some(ActivitySection::Notes),
                "todos" => Some(ActivitySection::Todos),
                "findings" => Some(ActivitySection::Findings),
                _ => None,
            };
            if let Some(sec) = s {
                self.active_section = sec;
            }
        }
        if saved.fullscreen_mode.unwrap_or(false) {
            self.fullscreen_mode = true;
        }
        if saved.bottom_panel_visible.unwrap_or(false) {
            self.bottom_panel_visible = true;
            if let Some(h) = saved.bottom_panel_height {
                self.bottom_panel_height = h.clamp(3, 60);
            }
            if let Some(idx) = saved.bottom_panel_active_idx {
                self.bottom_panel_active_idx = idx;
            }
        }
        if let Some(cmds) = saved.recent_commands {
            self.recent_commands = cmds;
        }
        // #1112 (2026-08-20) — restore search-section flags + history.
        if saved.search_case_sensitive.unwrap_or(false) {
            self.search_case_sensitive = true;
        }
        if saved.search_whole_word.unwrap_or(false) {
            self.search_whole_word = true;
        }
        if saved.search_regex.unwrap_or(false) {
            self.search_regex = true;
        }
        if let Some(hist) = saved.search_history {
            self.search_history = hist;
        }
        // Restore extra-workspace state (matched by name — renames lose
        // their previous state silently).
        for s in saved.extra_workspaces {
            if let Some(w) = self.extra_workspaces.iter_mut().find(|w| w.name == s.name) {
                w.expanded = s.expanded;
                if let Some(v) = s.show_hidden
                    && w.tree.show_hidden != v
                {
                    w.tree.show_hidden = v;
                    w.tree.refresh();
                }
                w.tree
                    .set_expanded_dirs(s.expanded_dirs.into_iter().map(PathBuf::from));
            }
        }
        if !saved.recent_files.is_empty() {
            // Honor the saved order (most-recent first), capping at the runtime
            // limit (which may have shrunk between versions).
            self.recent_files = saved
                .recent_files
                .into_iter()
                .map(PathBuf::from)
                .take(RECENT_FILES_MAX)
                .collect();
        }
        if !saved.browser_url_history.is_empty() {
            self.browser_url_history = saved
                .browser_url_history
                .into_iter()
                .take(BROWSER_URL_HISTORY_MAX)
                .collect();
        }
        if let Some(name) = saved.theme.as_deref() {
            // Best-effort — unknown theme names (e.g. someone deleted a theme
            // file) just leave the launch-default in place. Silent so the
            // restore doesn't toast on every cold start.
            let _ = self.set_theme_silent(name);
        }
        if let Some(w) = saved.wrap {
            self.config.ui.wrap = w;
        }
        if let Some(v) = saved.clock_show_utc {
            self.clock_show_utc = v;
        }
        if let Some(s) = saved.claude_agents_age_filter.as_deref() {
            self.claude_agents_last_age_filter = match s {
                "today" => crate::claude_agents::AgeFilter::Today,
                "week" => crate::claude_agents::AgeFilter::Week,
                "month" => crate::claude_agents::AgeFilter::Month,
                "all" => crate::claude_agents::AgeFilter::All,
                _ => crate::claude_agents::AgeFilter::default(),
            };
        }
        // #22 v3 — restore collapsed COLLECTIONS dirs (relative
        // paths resolved against the current workspace's
        // `.mnml/collections/`).
        if !saved.http_panel_collections_collapsed.is_empty() {
            let coll_root = self.workspace.join(".mnml").join("collections");
            self.http_panel_collections_collapsed_dirs = saved
                .http_panel_collections_collapsed
                .iter()
                .map(|rel| coll_root.join(rel))
                .collect();
        }
        self.saved_pty_session_names = saved.pty_session_names.into_iter().collect();
        // Restore the dock widgets verbatim — they own their
        // positions, sizes, and content. `next_id` is restored
        // so future widgets keep monotonically increasing ids
        // (no collisions with restored ones).
        self.dock_widgets = saved.dock_widgets;
        if let Some(next) = saved.dock_widget_next_id {
            self.dock_widget_next_id = next;
        } else if !self.dock_widgets.is_empty() {
            // Old session.json before we tracked next_id — derive
            // from max(id) + 1 so we don't reuse an id.
            self.dock_widget_next_id =
                self.dock_widgets.iter().map(|w| w.id).max().unwrap_or(0) + 1;
        }
        // Drop indices that no longer point into the (potentially
        // shorter) preset table — older sessions could have saved an
        // out-of-range value after a code change.
        if let Some(idx) = saved.last_browser_device
            && idx < crate::browser_pane::DEVICE_PRESETS.len()
        {
            self.last_browser_device = Some(idx);
        }
        for m in saved.macros {
            let keys: Vec<_> = m
                .keys
                .iter()
                .filter_map(|spec| crate::input::keymap::parse_key_spec(spec))
                .collect();
            if !keys.is_empty() {
                self.macro_buffer.insert(m.register, keys);
            }
        }
        for fc in saved.file_cursors {
            self.file_cursors
                .insert(PathBuf::from(fc.path), (fc.cursor_byte, fc.scroll));
        }
        for gm in saved.global_marks {
            // Uppercase letters only — guard against malformed session files.
            if gm.letter.is_ascii_uppercase() {
                self.global_marks
                    .insert(gm.letter, (PathBuf::from(gm.path), gm.row, gm.col));
            }
        }
        // Restore folds onto any buffer whose path matches a saved entry,
        // AND hydrate `file_folds` so files opened later this session
        // (that were closed at save time) get their folds back too.
        // Out-of-range pairs (start >= line_count, or end < start) get
        // dropped silently — likely stale because the file was edited
        // externally.
        for sf in saved.folds {
            let target = PathBuf::from(&sf.path);
            self.file_folds.insert(target.clone(), sf.folds.clone());
            for p in self.panes.iter_mut() {
                if let Pane::Editor(b) = p
                    && b.path.as_deref() == Some(target.as_path())
                {
                    let line_count = b.editor.line_count();
                    for (start, end) in &sf.folds {
                        if *end >= *start && *start < line_count && *end < line_count {
                            b.folds.insert(*start, *end);
                        }
                    }
                    break;
                }
            }
        }
        // Nav stacks — `Alt+Left` / `Alt+Right` history. Trust the saved
        // entries' (row, col) blindly; if a file was deleted or edited
        // externally, the jump just lands at a clamped position. Capped at
        // the runtime maximum.
        self.nav_back = saved
            .nav_back
            .into_iter()
            .map(|np| NavPoint {
                path: PathBuf::from(np.path),
                row: np.row,
                col: np.col,
            })
            .collect();
        self.nav_forward = saved
            .nav_forward
            .into_iter()
            .map(|np| NavPoint {
                path: PathBuf::from(np.path),
                row: np.row,
                col: np.col,
            })
            .collect();
        if self.nav_back.len() > NAV_STACK_MAX {
            let drop_n = self.nav_back.len() - NAV_STACK_MAX;
            self.nav_back.drain(..drop_n);
        }
        if self.nav_forward.len() > NAV_STACK_MAX {
            let drop_n = self.nav_forward.len() - NAV_STACK_MAX;
            self.nav_forward.drain(..drop_n);
        }
        // Find query history — restore the most recent N (oldest first).
        if !saved.find_history.is_empty() {
            let take_from = saved.find_history.len().saturating_sub(FIND_HISTORY_MAX);
            self.find_history = saved.find_history.into_iter().skip(take_from).collect();
            self.find_history_cursor = self.find_history.len();
        }
        // Closed-buffer stack — restore the most recent N (oldest first).
        if !saved.closed_buffers.is_empty() {
            let take_from = saved
                .closed_buffers
                .len()
                .saturating_sub(CLOSED_BUFFERS_MAX);
            self.closed_buffers = saved
                .closed_buffers
                .into_iter()
                .skip(take_from)
                .map(|np| (PathBuf::from(np.path), np.row, np.col))
                .collect();
        }
        // Ex command history — restore the most recent 100. Push into
        // every open editor's input handler too so vim's cmdline Up/Down
        // can walk it immediately.
        if !saved.ex_history.is_empty() {
            let take_from = saved.ex_history.len().saturating_sub(100);
            self.ex_history = saved.ex_history.into_iter().skip(take_from).collect();
            for p in self.panes.iter_mut() {
                if let Pane::Editor(b) = p {
                    b.input.set_ex_history(self.ex_history.clone());
                }
            }
        }
        // DAP watch expressions — restore the list (cached results
        // re-eval on the next stop and aren't persisted).
        if !saved.dap_watches.is_empty() {
            self.dap_watches = saved.dap_watches;
        }
        // SCM/CI pane view-mode + collapse state.
        // (GH / GL / AZ view-mode + collapsed state all moved to
        // mnml-forge-* integrations in 2026-06.)
        // Harpoon slots — restore up to 9 (silently drop any extras a
        // hand-edited session.json might carry).
        for (i, slot) in saved.harpoon.into_iter().take(9).enumerate() {
            self.harpoon[i] = slot.map(PathBuf::from);
        }
        // GitGraph detail-divider drag override.
        self.git_graph_detail_col_override = saved.git_graph_detail_col;
        // Remembered diff view-mode + wrap toggle.
        if let Some(m) = saved.diff_view_mode {
            self.diff_view_mode_pref = m;
        }
        self.diff_wrap_pref = saved.diff_wrap;
        // AI token tally + suggestion accept tally — restored so the
        // cost / accept-rate readouts are lifetime, not per-launch.
        self.ai_tokens_in = saved.ai_tokens_in;
        self.ai_tokens_out = saved.ai_tokens_out;
        self.suggest_shown = saved.suggest_shown;
        self.suggest_accepted = saved.suggest_accepted;
        // Per-file change list — restore for any buffer we just re-opened.
        // Cursor sits past the newest entry so the first `g;` lands on the
        // most recent edit (vim convention).
        for seh in saved.edit_history {
            let target = PathBuf::from(&seh.path);
            for p in self.panes.iter_mut() {
                if let Pane::Editor(b) = p
                    && b.path.as_deref() == Some(target.as_path())
                {
                    let line_count = b.editor.line_count();
                    let entries: Vec<(usize, usize)> = seh
                        .entries
                        .into_iter()
                        .filter(|(r, _)| *r < line_count)
                        .collect();
                    let cap = entries.len();
                    b.edit_history = entries;
                    b.edit_history_cursor = cap;
                    break;
                }
            }
        }
        let fallback = idx_to_pane.iter().rev().flatten().next().copied();
        if let Some(p) = active_pane.or(fallback) {
            self.reveal_pane(p);
        }
    }
}

#[cfg(test)]
mod session_tests {
    use super::*;
    use std::fs;

    fn app_with_files() -> (tempfile::TempDir, App) {
        let d = tempfile::tempdir().unwrap();
        fs::write(d.path().join("a.txt"), "alpha").unwrap();
        fs::write(d.path().join("b.txt"), "beta").unwrap();
        // vim input_style — these session-round-trip tests exercise
        // pane management orthogonal to the standard-mode preview-tab
        // UX. Force vim mode so `open_path` always pins.
        let mut cfg = Config::default();
        cfg.editor.input_style = "vim".to_string();
        let app = App::new(d.path().to_path_buf(), cfg).unwrap();
        (d, app)
    }

    #[test]
    fn session_round_trips_open_buffers_and_active() {
        let (d, mut app) = app_with_files();
        app.open_path(&d.path().join("a.txt"));
        app.open_path(&d.path().join("b.txt"));
        // Move b.txt's cursor onto "beta"'s `t` (byte 2).
        if let Some(Pane::Editor(b)) = app.panes.get_mut(1) {
            b.editor.place_cursor(0, 2);
            b.scroll = 0;
        }
        app.save_session_on_quit();
        assert!(d.path().join(".mnml/session.json").exists());
        // A fresh App on the same workspace + try_restore re-opens both.
        let mut app2 = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        assert!(app2.panes.is_empty());
        app2.try_restore_session();
        assert_eq!(app2.panes.len(), 2);
        // The previously-active (b.txt = index 1) should be focused.
        assert_eq!(app2.active, Some(1));
        // Cursor on b.txt was at (0, 2).
        if let Some(Pane::Editor(b)) = app2.panes.get(1) {
            assert_eq!(b.editor.row_col(), (0, 2));
        } else {
            panic!("expected an editor at index 1");
        }
    }

    #[test]
    fn session_round_trips_multi_tab_layouts() {
        // Two tab pages, each with a different active file. Save +
        // restore should re-open the buffers AND land on the same tab
        // with the same active layout.
        let (d, mut app) = app_with_files();
        let a_path = d.path().join("a.txt").canonicalize().unwrap();
        let b_path = d.path().join("b.txt").canonicalize().unwrap();
        // Tab 1: a.txt
        app.open_path(&a_path);
        // Tab 2: b.txt
        app.tab_new(None);
        app.open_path(&b_path);
        assert_eq!(app.layouts.len(), 2);
        assert_eq!(app.active_layout, 1);
        app.save_session_on_quit();

        let mut app2 = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        app2.try_restore_session();
        assert_eq!(
            app2.layouts.len(),
            2,
            "should restore both tabs, got {}",
            app2.layouts.len()
        );
        assert_eq!(app2.active_layout, 1);
        // Both files should be open as panes.
        let _a = app2
            .panes
            .iter()
            .position(|p| matches!(p, Pane::Editor(b) if b.is_at(&a_path)))
            .expect("a.txt should be re-opened");
        let _b = app2
            .panes
            .iter()
            .position(|p| matches!(p, Pane::Editor(b) if b.is_at(&b_path)))
            .expect("b.txt should be re-opened");
    }

    #[test]
    fn session_skips_save_when_restore_off() {
        let d = tempfile::tempdir().unwrap();
        fs::write(d.path().join("a.txt"), "alpha").unwrap();
        let mut cfg = Config::default();
        cfg.session.restore = false;
        let mut app = App::new(d.path().to_path_buf(), cfg).unwrap();
        app.open_path(&d.path().join("a.txt"));
        app.save_session_on_quit();
        assert!(!d.path().join(".mnml/session.json").exists());
    }

    #[test]
    fn session_round_trips_tree_state() {
        let d = tempfile::tempdir().unwrap();
        // Need a sub-directory so the tree has something to expand/collapse.
        fs::create_dir(d.path().join("sub")).unwrap();
        fs::write(d.path().join("sub").join("c.txt"), "c").unwrap();
        fs::write(d.path().join("a.txt"), "a").unwrap();
        let mut app = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        // Default after `Tree::open`: depth-0 dirs are expanded. Collapse `sub`.
        let sub = app.workspace.join("sub");
        let mut dirs: Vec<PathBuf> = app
            .tree
            .expanded_dirs()
            .into_iter()
            .filter(|p| p != &sub)
            .collect();
        dirs.sort();
        let collapsed_snapshot = dirs.clone();
        app.tree.set_expanded_dirs(dirs);
        // Also flip the section header (independent state) so we exercise both.
        app.tree_root_expanded = false;
        app.save_session_on_quit();

        let mut app2 = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        // Pre-restore, the default expansion is whatever Tree::open chose.
        // After restore, it should match what we saved.
        app2.try_restore_session();
        let mut got = app2.tree.expanded_dirs();
        got.sort();
        assert_eq!(got, collapsed_snapshot);
        assert!(!app2.tree_root_expanded);
    }
}