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
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
//! Session persistence integration for the Editor
//!
//! This module provides conversion between live Editor state and serialized Session data.
//!
//! # Role in Incremental Streaming Architecture
//!
//! This module handles session save/restore for terminals.
//! See `crate::services::terminal` for the full architecture diagram.
//!
//! ## Session Save
//!
//! [`Editor::save_session`] calls [`Editor::sync_all_terminal_backing_files`] to ensure
//! all terminal backing files contain complete state (scrollback + visible screen)
//! before serializing session metadata.
//!
//! ## Session Restore
//!
//! [`Editor::restore_terminal_from_session`] loads the backing file directly as a
//! read-only buffer, skipping the expensive log replay. The user starts in scrollback
//! mode viewing the last session state. A new PTY is spawned when they re-enter
//! terminal mode.
//!
//! Performance: O(1) ≈ 10ms (lazy load) vs O(n) ≈ 1000ms (log replay)
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::time::Instant;
use crate::state::EditorState;
use crate::model::event::{BufferId, SplitDirection, SplitId};
use crate::services::terminal::TerminalId;
use crate::session::{
FileExplorerState, PersistedFileSession, SearchOptions, SerializedBookmark, SerializedCursor,
SerializedFileState, SerializedScroll, SerializedSplitDirection, SerializedSplitNode,
SerializedSplitViewState, SerializedTabRef, SerializedTerminalSession, SerializedViewMode,
Session, SessionConfigOverrides, SessionError, SessionHistories, SESSION_VERSION,
};
use crate::state::ViewMode;
use crate::view::split::{SplitNode, SplitViewState};
use super::types::Bookmark;
use super::Editor;
/// Session persistence state tracker
///
/// Tracks dirty state and handles debounced saving for crash resistance.
pub struct SessionTracker {
/// Whether session has unsaved changes
dirty: bool,
/// Last save time
last_save: Instant,
/// Minimum interval between saves (debounce)
save_interval: std::time::Duration,
/// Whether session persistence is enabled
enabled: bool,
}
impl SessionTracker {
/// Create a new session tracker
pub fn new(enabled: bool) -> Self {
Self {
dirty: false,
last_save: Instant::now(),
save_interval: std::time::Duration::from_secs(5),
enabled,
}
}
/// Check if session tracking is enabled
pub fn is_enabled(&self) -> bool {
self.enabled
}
/// Mark session as needing save
pub fn mark_dirty(&mut self) {
if self.enabled {
self.dirty = true;
}
}
/// Check if a save is needed and enough time has passed
pub fn should_save(&self) -> bool {
self.enabled && self.dirty && self.last_save.elapsed() >= self.save_interval
}
/// Record that a save was performed
pub fn record_save(&mut self) {
self.dirty = false;
self.last_save = Instant::now();
}
/// Check if there are unsaved changes (for shutdown)
pub fn is_dirty(&self) -> bool {
self.dirty
}
}
impl Editor {
/// Capture current editor state into a Session
pub fn capture_session(&self) -> Session {
tracing::debug!("Capturing session for {:?}", self.working_dir);
// Collect terminal metadata for session restore
let mut terminals = Vec::new();
let mut terminal_indices: HashMap<TerminalId, usize> = HashMap::new();
let mut seen = HashSet::new();
for terminal_id in self.terminal_buffers.values().copied() {
if seen.insert(terminal_id) {
let idx = terminals.len();
terminal_indices.insert(terminal_id, idx);
let handle = self.terminal_manager.get(terminal_id);
let (cols, rows) = handle
.map(|h| h.size())
.unwrap_or((self.terminal_width, self.terminal_height));
let cwd = handle.and_then(|h| h.cwd());
let shell = handle
.map(|h| h.shell().to_string())
.unwrap_or_else(crate::services::terminal::detect_shell);
let log_path = self
.terminal_log_files
.get(&terminal_id)
.cloned()
.unwrap_or_else(|| {
let root = self.dir_context.terminal_dir_for(&self.working_dir);
root.join(format!("fresh-terminal-{}.log", terminal_id.0))
});
let backing_path = self
.terminal_backing_files
.get(&terminal_id)
.cloned()
.unwrap_or_else(|| {
let root = self.dir_context.terminal_dir_for(&self.working_dir);
root.join(format!("fresh-terminal-{}.txt", terminal_id.0))
});
terminals.push(SerializedTerminalSession {
terminal_index: idx,
cwd,
shell,
cols,
rows,
log_path,
backing_path,
});
}
}
let split_layout = serialize_split_node(
self.split_manager.root(),
&self.buffer_metadata,
&self.working_dir,
&self.terminal_buffers,
&terminal_indices,
);
// Build a map of split_id -> active_buffer_id from the split tree
// This tells us which buffer's cursor/scroll to save for each split
let active_buffers: HashMap<SplitId, BufferId> = self
.split_manager
.root()
.get_leaves_with_rects(ratatui::layout::Rect::default())
.into_iter()
.map(|(split_id, buffer_id, _)| (split_id, buffer_id))
.collect();
let mut split_states = HashMap::new();
for (split_id, view_state) in &self.split_view_states {
let active_buffer = active_buffers.get(split_id).copied();
let serialized = serialize_split_view_state(
view_state,
&self.buffer_metadata,
&self.working_dir,
active_buffer,
&self.terminal_buffers,
&terminal_indices,
);
tracing::trace!(
"Split {:?}: {} open tabs, active_buffer={:?}",
split_id,
serialized.open_tabs.len(),
active_buffer
);
split_states.insert(split_id.0, serialized);
}
tracing::debug!(
"Captured {} split states, active_split={}",
split_states.len(),
self.split_manager.active_split().0
);
// Capture file explorer state
let file_explorer = if let Some(ref explorer) = self.file_explorer {
// Get expanded directories from the tree
let expanded_dirs = get_expanded_dirs(explorer, &self.working_dir);
FileExplorerState {
visible: self.file_explorer_visible,
width_percent: self.file_explorer_width_percent,
expanded_dirs,
scroll_offset: explorer.get_scroll_offset(),
show_hidden: explorer.ignore_patterns().show_hidden(),
show_gitignored: explorer.ignore_patterns().show_gitignored(),
}
} else {
FileExplorerState {
visible: self.file_explorer_visible,
width_percent: self.file_explorer_width_percent,
expanded_dirs: Vec::new(),
scroll_offset: 0,
show_hidden: false,
show_gitignored: false,
}
};
// Capture config overrides (only store deviations from defaults)
let config_overrides = SessionConfigOverrides {
line_numbers: Some(self.config.editor.line_numbers),
relative_line_numbers: Some(self.config.editor.relative_line_numbers),
line_wrap: Some(self.config.editor.line_wrap),
syntax_highlighting: Some(self.config.editor.syntax_highlighting),
enable_inlay_hints: Some(self.config.editor.enable_inlay_hints),
mouse_enabled: Some(self.mouse_enabled),
menu_bar_hidden: Some(!self.menu_bar_visible),
};
// Capture histories using the items() accessor from the prompt_histories HashMap
let histories = SessionHistories {
search: self
.prompt_histories
.get("search")
.map(|h| h.items().to_vec())
.unwrap_or_default(),
replace: self
.prompt_histories
.get("replace")
.map(|h| h.items().to_vec())
.unwrap_or_default(),
command_palette: Vec::new(), // Future: when command palette has history
goto_line: self
.prompt_histories
.get("goto_line")
.map(|h| h.items().to_vec())
.unwrap_or_default(),
open_file: Vec::new(), // Future: when file open prompt has history
};
tracing::trace!(
"Captured histories: {} search, {} replace",
histories.search.len(),
histories.replace.len()
);
// Capture search options
let search_options = SearchOptions {
case_sensitive: self.search_case_sensitive,
whole_word: self.search_whole_word,
use_regex: self.search_use_regex,
confirm_each: self.search_confirm_each,
};
// Capture bookmarks
let bookmarks =
serialize_bookmarks(&self.bookmarks, &self.buffer_metadata, &self.working_dir);
// Capture external files (files outside working_dir)
// These are stored as absolute paths since they can't be made relative
let external_files: Vec<PathBuf> = self
.buffer_metadata
.values()
.filter_map(|meta| meta.file_path())
.filter(|abs_path| abs_path.strip_prefix(&self.working_dir).is_err())
.cloned()
.collect();
if !external_files.is_empty() {
tracing::debug!("Captured {} external files", external_files.len());
}
Session {
version: SESSION_VERSION,
working_dir: self.working_dir.clone(),
split_layout,
active_split_id: self.split_manager.active_split().0,
split_states,
config_overrides,
file_explorer,
histories,
search_options,
bookmarks,
terminals,
external_files,
saved_at: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs(),
}
}
/// Save the current session to disk
///
/// Ensures all active terminals have their visible screen synced to
/// backing files before capturing the session.
/// Also saves global file states (scroll/cursor positions per file).
pub fn save_session(&mut self) -> Result<(), SessionError> {
// Ensure all terminal backing files have complete state before saving
self.sync_all_terminal_backing_files();
// Save global file states for all open file buffers
self.save_all_global_file_states();
let session = self.capture_session();
session.save()
}
/// Save global file states for all open file buffers
fn save_all_global_file_states(&self) {
// Collect all file states from all splits
for (split_id, view_state) in &self.split_view_states {
// Get the active buffer for this split
let active_buffer = self
.split_manager
.root()
.get_leaves_with_rects(ratatui::layout::Rect::default())
.into_iter()
.find(|(sid, _, _)| *sid == *split_id)
.map(|(_, buffer_id, _)| buffer_id);
if let Some(buffer_id) = active_buffer {
self.save_buffer_file_state(buffer_id, view_state);
}
}
}
/// Save file state for a specific buffer (used when closing files and saving session)
fn save_buffer_file_state(&self, buffer_id: BufferId, view_state: &SplitViewState) {
// Get the file path for this buffer
let abs_path = match self.buffer_metadata.get(&buffer_id) {
Some(metadata) => match metadata.file_path() {
Some(path) => path.to_path_buf(),
None => return, // Not a file buffer
},
None => return,
};
// Capture the current state
let primary_cursor = view_state.cursors.primary();
let file_state = SerializedFileState {
cursor: SerializedCursor {
position: primary_cursor.position,
anchor: primary_cursor.anchor,
sticky_column: primary_cursor.sticky_column,
},
additional_cursors: view_state
.cursors
.iter()
.skip(1)
.map(|(_, cursor)| SerializedCursor {
position: cursor.position,
anchor: cursor.anchor,
sticky_column: cursor.sticky_column,
})
.collect(),
scroll: SerializedScroll {
top_byte: view_state.viewport.top_byte,
top_view_line_offset: view_state.viewport.top_view_line_offset,
left_column: view_state.viewport.left_column,
},
};
// Save to disk immediately
PersistedFileSession::save(&abs_path, file_state);
}
/// Sync all active terminal visible screens to their backing files.
///
/// Called before session save to ensure backing files contain complete
/// terminal state (scrollback + visible screen).
fn sync_all_terminal_backing_files(&mut self) {
use std::io::BufWriter;
// Collect terminal IDs and their backing paths
let terminals_to_sync: Vec<_> = self
.terminal_buffers
.values()
.copied()
.filter_map(|terminal_id| {
self.terminal_backing_files
.get(&terminal_id)
.map(|path| (terminal_id, path.clone()))
})
.collect();
for (terminal_id, backing_path) in terminals_to_sync {
if let Some(handle) = self.terminal_manager.get(terminal_id) {
if let Ok(state) = handle.state.lock() {
// Append visible screen to backing file
if let Ok(mut file) = self.filesystem.open_file_for_append(&backing_path) {
let mut writer = BufWriter::new(&mut *file);
if let Err(e) = state.append_visible_screen(&mut writer) {
tracing::warn!(
"Failed to sync terminal {:?} to backing file: {}",
terminal_id,
e
);
}
}
}
}
}
}
/// Try to load and apply a session for the current working directory
///
/// Returns true if a session was successfully loaded and applied.
pub fn try_restore_session(&mut self) -> Result<bool, SessionError> {
tracing::debug!("Attempting to restore session for {:?}", self.working_dir);
match Session::load(&self.working_dir)? {
Some(session) => {
tracing::info!("Found session, applying...");
self.apply_session(&session)?;
Ok(true)
}
None => {
tracing::debug!("No session found for {:?}", self.working_dir);
Ok(false)
}
}
}
/// Apply a loaded session to the editor
pub fn apply_session(&mut self, session: &Session) -> Result<(), SessionError> {
tracing::debug!(
"Applying session with {} split states",
session.split_states.len()
);
// 1. Apply config overrides
if let Some(line_numbers) = session.config_overrides.line_numbers {
self.config.editor.line_numbers = line_numbers;
}
if let Some(relative_line_numbers) = session.config_overrides.relative_line_numbers {
self.config.editor.relative_line_numbers = relative_line_numbers;
}
if let Some(line_wrap) = session.config_overrides.line_wrap {
self.config.editor.line_wrap = line_wrap;
}
if let Some(syntax_highlighting) = session.config_overrides.syntax_highlighting {
self.config.editor.syntax_highlighting = syntax_highlighting;
}
if let Some(enable_inlay_hints) = session.config_overrides.enable_inlay_hints {
self.config.editor.enable_inlay_hints = enable_inlay_hints;
}
if let Some(mouse_enabled) = session.config_overrides.mouse_enabled {
self.mouse_enabled = mouse_enabled;
}
if let Some(menu_bar_hidden) = session.config_overrides.menu_bar_hidden {
self.menu_bar_visible = !menu_bar_hidden;
}
// 2. Restore search options
self.search_case_sensitive = session.search_options.case_sensitive;
self.search_whole_word = session.search_options.whole_word;
self.search_use_regex = session.search_options.use_regex;
self.search_confirm_each = session.search_options.confirm_each;
// 3. Restore histories (merge with any existing)
tracing::debug!(
"Restoring histories: {} search, {} replace, {} goto_line",
session.histories.search.len(),
session.histories.replace.len(),
session.histories.goto_line.len()
);
for item in &session.histories.search {
self.get_or_create_prompt_history("search")
.push(item.clone());
}
for item in &session.histories.replace {
self.get_or_create_prompt_history("replace")
.push(item.clone());
}
for item in &session.histories.goto_line {
self.get_or_create_prompt_history("goto_line")
.push(item.clone());
}
// 4. Restore file explorer state
self.file_explorer_visible = session.file_explorer.visible;
self.file_explorer_width_percent = session.file_explorer.width_percent;
// Store pending show_hidden and show_gitignored settings (fixes #569)
// These will be applied when the file explorer is initialized (async)
if session.file_explorer.show_hidden {
self.pending_file_explorer_show_hidden = Some(true);
}
if session.file_explorer.show_gitignored {
self.pending_file_explorer_show_gitignored = Some(true);
}
// Initialize file explorer if it was visible in the session
// Note: We keep key_context as Normal so the editor has focus, not the explorer
if self.file_explorer_visible && self.file_explorer.is_none() {
self.init_file_explorer();
}
// 5. Open files from the session and build buffer mappings
// Collect all unique file paths from split_states (which tracks all open files per split)
let file_paths = collect_file_paths_from_states(&session.split_states);
tracing::debug!(
"Session has {} files to restore: {:?}",
file_paths.len(),
file_paths
);
let mut path_to_buffer: HashMap<PathBuf, BufferId> = HashMap::new();
for rel_path in file_paths {
let abs_path = self.working_dir.join(&rel_path);
tracing::trace!(
"Checking file: {:?} (exists: {})",
abs_path,
abs_path.exists()
);
if abs_path.exists() {
// Open the file (this will reuse existing buffer if already open)
match self.open_file_internal(&abs_path) {
Ok(buffer_id) => {
tracing::debug!("Opened file {:?} as buffer {:?}", rel_path, buffer_id);
path_to_buffer.insert(rel_path, buffer_id);
}
Err(e) => {
tracing::warn!("Failed to open file {:?}: {}", abs_path, e);
}
}
} else {
tracing::debug!("Skipping non-existent file: {:?}", abs_path);
}
}
tracing::debug!("Opened {} files from session", path_to_buffer.len());
// 5b. Restore external files (files outside the working directory)
// These are stored as absolute paths
if !session.external_files.is_empty() {
tracing::debug!(
"Restoring {} external files: {:?}",
session.external_files.len(),
session.external_files
);
for abs_path in &session.external_files {
if abs_path.exists() {
match self.open_file_internal(abs_path) {
Ok(buffer_id) => {
tracing::debug!(
"Restored external file {:?} as buffer {:?}",
abs_path,
buffer_id
);
}
Err(e) => {
tracing::warn!("Failed to restore external file {:?}: {}", abs_path, e);
}
}
} else {
tracing::debug!("Skipping non-existent external file: {:?}", abs_path);
}
}
}
// Restore terminals and build index -> buffer map
let mut terminal_buffer_map: HashMap<usize, BufferId> = HashMap::new();
if !session.terminals.is_empty() {
if let Some(ref bridge) = self.async_bridge {
self.terminal_manager.set_async_bridge(bridge.clone());
}
for terminal in &session.terminals {
if let Some(buffer_id) = self.restore_terminal_from_session(terminal) {
terminal_buffer_map.insert(terminal.terminal_index, buffer_id);
}
}
}
// 6. Rebuild split layout from the saved tree
// Map old split IDs to new ones as we create splits
let mut split_id_map: HashMap<usize, SplitId> = HashMap::new();
self.restore_split_node(
&session.split_layout,
&path_to_buffer,
&terminal_buffer_map,
&session.split_states,
&mut split_id_map,
true, // is_first_leaf - the first leaf reuses the existing split
);
// Set the active split based on the saved active_split_id
// NOTE: active_buffer is now derived from split_manager, which was already
// correctly set up by restore_split_view_state() via set_split_buffer()
if let Some(&new_active_split) = split_id_map.get(&session.active_split_id) {
self.split_manager.set_active_split(new_active_split);
}
// 7. Restore bookmarks
for (key, bookmark) in &session.bookmarks {
if let Some(&buffer_id) = path_to_buffer.get(&bookmark.file_path) {
// Verify position is valid
if let Some(buffer) = self.buffers.get(&buffer_id) {
let pos = bookmark.position.min(buffer.buffer.len());
self.bookmarks.insert(
*key,
Bookmark {
buffer_id,
position: pos,
},
);
}
}
}
tracing::debug!(
"Session restore complete: {} splits, {} buffers",
self.split_view_states.len(),
self.buffers.len()
);
Ok(())
}
/// Restore a terminal from serialized session metadata.
///
/// Uses the incremental streaming architecture for fast restore:
/// 1. Load backing file directly as read-only buffer (lazy load)
/// 2. Skip log replay entirely - user sees last session state immediately
/// 3. Spawn new PTY for live terminal when user re-enters terminal mode
///
/// Performance: O(1) for restore vs O(total_history) with log replay
fn restore_terminal_from_session(
&mut self,
terminal: &SerializedTerminalSession,
) -> Option<BufferId> {
// Resolve paths (accept absolute; otherwise treat as relative to terminals dir)
let terminals_root = self.dir_context.terminal_dir_for(&self.working_dir);
let log_path = if terminal.log_path.is_absolute() {
terminal.log_path.clone()
} else {
terminals_root.join(&terminal.log_path)
};
let backing_path = if terminal.backing_path.is_absolute() {
terminal.backing_path.clone()
} else {
terminals_root.join(&terminal.backing_path)
};
let _ = self.filesystem.create_dir_all(
log_path
.parent()
.or_else(|| backing_path.parent())
.unwrap_or(&terminals_root),
);
// Record paths using the predicted ID so buffer creation can reuse them
let predicted_id = self.terminal_manager.next_terminal_id();
self.terminal_log_files
.insert(predicted_id, log_path.clone());
self.terminal_backing_files
.insert(predicted_id, backing_path.clone());
// Spawn the terminal with backing file for incremental scrollback
let terminal_id = match self.terminal_manager.spawn(
terminal.cols,
terminal.rows,
terminal.cwd.clone(),
Some(log_path.clone()),
Some(backing_path.clone()),
) {
Ok(id) => id,
Err(e) => {
tracing::warn!(
"Failed to restore terminal {}: {}",
terminal.terminal_index,
e
);
return None;
}
};
// Ensure maps keyed by actual ID
if terminal_id != predicted_id {
self.terminal_log_files
.insert(terminal_id, log_path.clone());
self.terminal_backing_files
.insert(terminal_id, backing_path.clone());
self.terminal_log_files.remove(&predicted_id);
self.terminal_backing_files.remove(&predicted_id);
}
// Create buffer for this terminal
let buffer_id = self.create_terminal_buffer_detached(terminal_id);
// Load backing file directly as read-only buffer (skip log replay)
// The backing file already contains complete terminal state from last session
self.load_terminal_backing_file_as_buffer(buffer_id, &backing_path);
Some(buffer_id)
}
/// Load a terminal backing file directly as a read-only buffer.
///
/// This is used for fast session restore - we load the pre-rendered backing
/// file instead of replaying the raw log through the VTE parser.
fn load_terminal_backing_file_as_buffer(&mut self, buffer_id: BufferId, backing_path: &Path) {
// Check if backing file exists; if not, terminal starts empty
if !backing_path.exists() {
return;
}
let large_file_threshold = self.config.editor.large_file_threshold_bytes as usize;
if let Ok(new_state) = EditorState::from_file_with_languages(
backing_path,
self.terminal_width,
self.terminal_height,
large_file_threshold,
&self.grammar_registry,
&self.config.languages,
std::sync::Arc::clone(&self.filesystem),
) {
if let Some(state) = self.buffers.get_mut(&buffer_id) {
*state = new_state;
// Move cursor to end of buffer
let total = state.buffer.total_bytes();
state.primary_cursor_mut().position = total;
// Terminal buffers should never be considered "modified"
state.buffer.set_modified(false);
// Start in scrollback mode (editing disabled)
state.editing_disabled = true;
state.margins.set_line_numbers(false);
}
}
}
/// Internal helper to open a file and return its buffer ID
fn open_file_internal(&mut self, path: &Path) -> Result<BufferId, SessionError> {
// Check if file is already open
for (buffer_id, metadata) in &self.buffer_metadata {
if let Some(file_path) = metadata.file_path() {
if file_path == path {
return Ok(*buffer_id);
}
}
}
// File not open, open it using the Editor's open_file method
self.open_file(path).map_err(SessionError::Io)
}
/// Recursively restore the split layout from a serialized tree
fn restore_split_node(
&mut self,
node: &SerializedSplitNode,
path_to_buffer: &HashMap<PathBuf, BufferId>,
terminal_buffers: &HashMap<usize, BufferId>,
split_states: &HashMap<usize, SerializedSplitViewState>,
split_id_map: &mut HashMap<usize, SplitId>,
is_first_leaf: bool,
) {
match node {
SerializedSplitNode::Leaf {
file_path,
split_id,
} => {
// Get the buffer for this file, or use the default buffer
let buffer_id = file_path
.as_ref()
.and_then(|p| path_to_buffer.get(p).copied())
.unwrap_or(self.active_buffer());
let current_split_id = if is_first_leaf {
// First leaf reuses the existing split
let split_id_val = self.split_manager.active_split();
let _ = self.split_manager.set_split_buffer(split_id_val, buffer_id);
split_id_val
} else {
// Non-first leaves use the active split (created by split_active)
self.split_manager.active_split()
};
// Map old split ID to new one
split_id_map.insert(*split_id, current_split_id);
// Restore the view state for this split
self.restore_split_view_state(
current_split_id,
*split_id,
split_states,
path_to_buffer,
terminal_buffers,
);
}
SerializedSplitNode::Terminal {
terminal_index,
split_id,
} => {
let buffer_id = terminal_buffers
.get(terminal_index)
.copied()
.unwrap_or(self.active_buffer());
let current_split_id = if is_first_leaf {
let split_id_val = self.split_manager.active_split();
let _ = self.split_manager.set_split_buffer(split_id_val, buffer_id);
split_id_val
} else {
self.split_manager.active_split()
};
split_id_map.insert(*split_id, current_split_id);
let _ = self
.split_manager
.set_split_buffer(current_split_id, buffer_id);
self.restore_split_view_state(
current_split_id,
*split_id,
split_states,
path_to_buffer,
terminal_buffers,
);
}
SerializedSplitNode::Split {
direction,
first,
second,
ratio,
split_id,
} => {
// First, restore the first child (it uses the current active split)
self.restore_split_node(
first,
path_to_buffer,
terminal_buffers,
split_states,
split_id_map,
is_first_leaf,
);
// Get the buffer for the second child's first leaf
let second_buffer_id =
get_first_leaf_buffer(second, path_to_buffer, terminal_buffers)
.unwrap_or(self.active_buffer());
// Convert direction
let split_direction = match direction {
SerializedSplitDirection::Horizontal => SplitDirection::Horizontal,
SerializedSplitDirection::Vertical => SplitDirection::Vertical,
};
// Create the split for the second child
match self
.split_manager
.split_active(split_direction, second_buffer_id, *ratio)
{
Ok(new_split_id) => {
// Create view state for the new split
let mut view_state = SplitViewState::with_buffer(
self.terminal_width,
self.terminal_height,
second_buffer_id,
);
view_state.viewport.line_wrap_enabled = self.config.editor.line_wrap;
self.split_view_states.insert(new_split_id, view_state);
// Map the container split ID (though we mainly care about leaves)
split_id_map.insert(*split_id, new_split_id);
// Recursively restore the second child (it's now in the new split)
self.restore_split_node(
second,
path_to_buffer,
terminal_buffers,
split_states,
split_id_map,
false,
);
}
Err(e) => {
tracing::error!("Failed to create split during session restore: {}", e);
}
}
}
}
}
/// Restore view state for a specific split
fn restore_split_view_state(
&mut self,
current_split_id: SplitId,
saved_split_id: usize,
split_states: &HashMap<usize, SerializedSplitViewState>,
path_to_buffer: &HashMap<PathBuf, BufferId>,
terminal_buffers: &HashMap<usize, BufferId>,
) {
// Try to find the saved state for this split
let Some(split_state) = split_states.get(&saved_split_id) else {
return;
};
let Some(view_state) = self.split_view_states.get_mut(¤t_split_id) else {
return;
};
let mut active_buffer_id: Option<BufferId> = None;
if !split_state.open_tabs.is_empty() {
for tab in &split_state.open_tabs {
match tab {
SerializedTabRef::File(rel_path) => {
if let Some(&buffer_id) = path_to_buffer.get(rel_path) {
if !view_state.open_buffers.contains(&buffer_id) {
view_state.open_buffers.push(buffer_id);
}
if terminal_buffers.values().any(|&tid| tid == buffer_id) {
view_state.viewport.line_wrap_enabled = false;
}
}
}
SerializedTabRef::Terminal(index) => {
if let Some(&buffer_id) = terminal_buffers.get(index) {
if !view_state.open_buffers.contains(&buffer_id) {
view_state.open_buffers.push(buffer_id);
}
view_state.viewport.line_wrap_enabled = false;
}
}
}
}
if let Some(active_idx) = split_state.active_tab_index {
if let Some(tab) = split_state.open_tabs.get(active_idx) {
active_buffer_id = match tab {
SerializedTabRef::File(rel) => path_to_buffer.get(rel).copied(),
SerializedTabRef::Terminal(index) => terminal_buffers.get(index).copied(),
};
}
}
} else {
// Backward compatibility path using open_files/active_file_index
for rel_path in &split_state.open_files {
if let Some(&buffer_id) = path_to_buffer.get(rel_path) {
if !view_state.open_buffers.contains(&buffer_id) {
view_state.open_buffers.push(buffer_id);
}
}
}
let active_file_path = split_state.open_files.get(split_state.active_file_index);
active_buffer_id =
active_file_path.and_then(|rel_path| path_to_buffer.get(rel_path).copied());
}
// Restore cursor and scroll for the active file
if let Some(active_id) = active_buffer_id {
// Find the file state for the active buffer
for (rel_path, file_state) in &split_state.file_states {
let buffer_for_path = path_to_buffer.get(rel_path).copied();
if buffer_for_path == Some(active_id) {
if let Some(buffer) = self.buffers.get(&active_id) {
let max_pos = buffer.buffer.len();
let cursor_pos = file_state.cursor.position.min(max_pos);
// Set cursor in SplitViewState
view_state.cursors.primary_mut().position = cursor_pos;
view_state.cursors.primary_mut().anchor =
file_state.cursor.anchor.map(|a| a.min(max_pos));
view_state.cursors.primary_mut().sticky_column =
file_state.cursor.sticky_column;
// Set scroll position
view_state.viewport.top_byte = file_state.scroll.top_byte.min(max_pos);
view_state.viewport.top_view_line_offset =
file_state.scroll.top_view_line_offset;
view_state.viewport.left_column = file_state.scroll.left_column;
// Mark viewport to skip sync on first resize after session restore
// This prevents ensure_visible from overwriting the restored scroll position
view_state.viewport.set_skip_resize_sync();
tracing::trace!(
"Restored SplitViewState for {:?}: cursor={}, top_byte={}",
rel_path,
cursor_pos,
view_state.viewport.top_byte
);
}
// Also set cursor in EditorState (authoritative for cursors)
if let Some(editor_state) = self.buffers.get_mut(&active_id) {
let max_pos = editor_state.buffer.len();
let cursor_pos = file_state.cursor.position.min(max_pos);
editor_state.cursors.primary_mut().position = cursor_pos;
editor_state.cursors.primary_mut().anchor =
file_state.cursor.anchor.map(|a| a.min(max_pos));
editor_state.cursors.primary_mut().sticky_column =
file_state.cursor.sticky_column;
// Note: viewport is now exclusively owned by SplitViewState (restored above)
}
break;
}
}
// Set this buffer as active in the split
let _ = self
.split_manager
.set_split_buffer(current_split_id, active_id);
}
// Restore view mode
view_state.view_mode = match split_state.view_mode {
SerializedViewMode::Source => ViewMode::Source,
SerializedViewMode::Compose => ViewMode::Compose,
};
view_state.compose_width = split_state.compose_width;
view_state.tab_scroll_offset = split_state.tab_scroll_offset;
}
}
/// Helper: Get the buffer ID from the first leaf node in a split tree
fn get_first_leaf_buffer(
node: &SerializedSplitNode,
path_to_buffer: &HashMap<PathBuf, BufferId>,
terminal_buffers: &HashMap<usize, BufferId>,
) -> Option<BufferId> {
match node {
SerializedSplitNode::Leaf { file_path, .. } => file_path
.as_ref()
.and_then(|p| path_to_buffer.get(p).copied()),
SerializedSplitNode::Terminal { terminal_index, .. } => {
terminal_buffers.get(terminal_index).copied()
}
SerializedSplitNode::Split { first, .. } => {
get_first_leaf_buffer(first, path_to_buffer, terminal_buffers)
}
}
}
// ============================================================================
// Serialization helpers
// ============================================================================
fn serialize_split_node(
node: &SplitNode,
buffer_metadata: &HashMap<BufferId, super::types::BufferMetadata>,
working_dir: &Path,
terminal_buffers: &HashMap<BufferId, TerminalId>,
terminal_indices: &HashMap<TerminalId, usize>,
) -> SerializedSplitNode {
match node {
SplitNode::Leaf {
buffer_id,
split_id,
} => {
if let Some(terminal_id) = terminal_buffers.get(buffer_id) {
if let Some(index) = terminal_indices.get(terminal_id) {
return SerializedSplitNode::Terminal {
terminal_index: *index,
split_id: split_id.0,
};
}
}
let file_path = buffer_metadata
.get(buffer_id)
.and_then(|meta| meta.file_path())
.and_then(|abs_path| {
abs_path
.strip_prefix(working_dir)
.ok()
.map(|p| p.to_path_buf())
});
SerializedSplitNode::Leaf {
file_path,
split_id: split_id.0,
}
}
SplitNode::Split {
direction,
first,
second,
ratio,
split_id,
} => SerializedSplitNode::Split {
direction: match direction {
SplitDirection::Horizontal => SerializedSplitDirection::Horizontal,
SplitDirection::Vertical => SerializedSplitDirection::Vertical,
},
first: Box::new(serialize_split_node(
first,
buffer_metadata,
working_dir,
terminal_buffers,
terminal_indices,
)),
second: Box::new(serialize_split_node(
second,
buffer_metadata,
working_dir,
terminal_buffers,
terminal_indices,
)),
ratio: *ratio,
split_id: split_id.0,
},
}
}
fn serialize_split_view_state(
view_state: &crate::view::split::SplitViewState,
buffer_metadata: &HashMap<BufferId, super::types::BufferMetadata>,
working_dir: &Path,
active_buffer: Option<BufferId>,
terminal_buffers: &HashMap<BufferId, TerminalId>,
terminal_indices: &HashMap<TerminalId, usize>,
) -> SerializedSplitViewState {
let mut open_tabs = Vec::new();
let mut open_files = Vec::new();
let mut active_tab_index = None;
for buffer_id in &view_state.open_buffers {
let tab_index = open_tabs.len();
if let Some(terminal_id) = terminal_buffers.get(buffer_id) {
if let Some(idx) = terminal_indices.get(terminal_id) {
open_tabs.push(SerializedTabRef::Terminal(*idx));
if Some(*buffer_id) == active_buffer {
active_tab_index = Some(tab_index);
}
continue;
}
}
if let Some(rel_path) = buffer_metadata
.get(buffer_id)
.and_then(|meta| meta.file_path())
.and_then(|abs_path| abs_path.strip_prefix(working_dir).ok())
{
open_tabs.push(SerializedTabRef::File(rel_path.to_path_buf()));
open_files.push(rel_path.to_path_buf());
if Some(*buffer_id) == active_buffer {
active_tab_index = Some(tab_index);
}
}
}
// Derive active_file_index for backward compatibility
let active_file_index = active_tab_index
.and_then(|idx| open_tabs.get(idx))
.and_then(|tab| match tab {
SerializedTabRef::File(path) => {
Some(open_files.iter().position(|p| p == path).unwrap_or(0))
}
_ => None,
})
.unwrap_or(0);
// Serialize file states - only save cursor/scroll for the ACTIVE buffer if it is a file
let mut file_states = HashMap::new();
if let Some(active_id) = active_buffer {
if let Some(meta) = buffer_metadata.get(&active_id) {
if let Some(abs_path) = meta.file_path() {
if let Ok(rel_path) = abs_path.strip_prefix(working_dir) {
let primary_cursor = view_state.cursors.primary();
file_states.insert(
rel_path.to_path_buf(),
SerializedFileState {
cursor: SerializedCursor {
position: primary_cursor.position,
anchor: primary_cursor.anchor,
sticky_column: primary_cursor.sticky_column,
},
additional_cursors: view_state
.cursors
.iter()
.skip(1) // Skip primary
.map(|(_, cursor)| SerializedCursor {
position: cursor.position,
anchor: cursor.anchor,
sticky_column: cursor.sticky_column,
})
.collect(),
scroll: SerializedScroll {
top_byte: view_state.viewport.top_byte,
top_view_line_offset: view_state.viewport.top_view_line_offset,
left_column: view_state.viewport.left_column,
},
},
);
}
}
}
}
SerializedSplitViewState {
open_tabs,
active_tab_index,
open_files,
active_file_index,
file_states,
tab_scroll_offset: view_state.tab_scroll_offset,
view_mode: match view_state.view_mode {
ViewMode::Source => SerializedViewMode::Source,
ViewMode::Compose => SerializedViewMode::Compose,
},
compose_width: view_state.compose_width,
}
}
fn serialize_bookmarks(
bookmarks: &HashMap<char, Bookmark>,
buffer_metadata: &HashMap<BufferId, super::types::BufferMetadata>,
working_dir: &Path,
) -> HashMap<char, SerializedBookmark> {
bookmarks
.iter()
.filter_map(|(key, bookmark)| {
buffer_metadata
.get(&bookmark.buffer_id)
.and_then(|meta| meta.file_path())
.and_then(|abs_path| {
abs_path.strip_prefix(working_dir).ok().map(|rel_path| {
(
*key,
SerializedBookmark {
file_path: rel_path.to_path_buf(),
position: bookmark.position,
},
)
})
})
})
.collect()
}
/// Collect all unique file paths from split_states
fn collect_file_paths_from_states(
split_states: &HashMap<usize, SerializedSplitViewState>,
) -> Vec<PathBuf> {
let mut paths = Vec::new();
for state in split_states.values() {
if !state.open_tabs.is_empty() {
for tab in &state.open_tabs {
if let SerializedTabRef::File(path) = tab {
if !paths.contains(path) {
paths.push(path.clone());
}
}
}
} else {
for path in &state.open_files {
if !paths.contains(path) {
paths.push(path.clone());
}
}
}
}
paths
}
/// Get list of expanded directories from a FileTreeView
fn get_expanded_dirs(
explorer: &crate::view::file_tree::FileTreeView,
working_dir: &Path,
) -> Vec<PathBuf> {
let mut expanded = Vec::new();
let tree = explorer.tree();
// Iterate through all nodes and collect expanded directories
for node in tree.all_nodes() {
if node.is_expanded() && node.is_dir() {
// Get the path and make it relative to working_dir
if let Ok(rel_path) = node.entry.path.strip_prefix(working_dir) {
expanded.push(rel_path.to_path_buf());
}
}
}
expanded
}