fresh-editor 0.3.0

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
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
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
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
//! File operations for the Editor.
//!
//! This module contains file I/O and watching operations:
//! - Saving buffers
//! - Reverting to saved version
//! - Auto-revert and file change polling
//! - LSP file notifications (open, change)
//! - File modification time tracking
//! - Save conflict detection

use crate::model::buffer::SudoSaveRequired;
use crate::model::filesystem::FileSystem;
use crate::view::file_tree::FileTreeView;
use crate::view::prompt::PromptType;
use std::path::{Path, PathBuf};

use lsp_types::TextDocumentContentChangeEvent;
use rust_i18n::t;

use crate::model::event::{BufferId, EventLog};
use crate::services::lsp::manager::LspSpawnResult;
use crate::state::EditorState;

use super::{BufferMetadata, Editor};

impl Editor {
    /// Save the active buffer
    pub fn save(&mut self) -> anyhow::Result<()> {
        // Fail fast if remote connection is down
        if !self.authority.filesystem.is_remote_connected() {
            anyhow::bail!(
                "Cannot save: remote connection lost ({})",
                self.authority
                    .filesystem
                    .remote_connection_info()
                    .unwrap_or("unknown host")
            );
        }

        let path = self
            .active_state()
            .buffer
            .file_path()
            .map(|p| p.to_path_buf());

        match self.active_state_mut().buffer.save() {
            Ok(()) => self.finalize_save(path),
            Err(e) => {
                if let Some(sudo_info) = e.downcast_ref::<SudoSaveRequired>() {
                    let info = sudo_info.clone();
                    self.start_prompt(
                        t!("prompt.sudo_save_confirm").to_string(),
                        PromptType::ConfirmSudoSave { info },
                    );
                    Ok(())
                } else if let Some(path) = path {
                    // Check if failure is due to non-existent parent directory
                    let is_not_found = e
                        .downcast_ref::<std::io::Error>()
                        .is_some_and(|io_err| io_err.kind() == std::io::ErrorKind::NotFound);
                    if is_not_found {
                        if let Some(parent) = path.parent() {
                            if !self.authority.filesystem.exists(parent) {
                                let dir_name = parent
                                    .strip_prefix(&self.working_dir)
                                    .unwrap_or(parent)
                                    .display()
                                    .to_string();
                                self.start_prompt(
                                    t!("buffer.create_directory_confirm", name = &dir_name)
                                        .to_string(),
                                    PromptType::ConfirmCreateDirectory { path },
                                );
                                return Ok(());
                            }
                        }
                    }
                    Err(e)
                } else {
                    Err(e)
                }
            }
        }
    }

    /// Internal helper to finalize save state (mark as saved, notify LSP, etc.)
    pub(crate) fn finalize_save(&mut self, path: Option<PathBuf>) -> anyhow::Result<()> {
        let buffer_id = self.active_buffer();
        self.finalize_save_buffer(buffer_id, path, false)
    }

    /// Internal helper to finalize save state for a specific buffer
    pub(crate) fn finalize_save_buffer(
        &mut self,
        buffer_id: BufferId,
        path: Option<PathBuf>,
        silent: bool,
    ) -> anyhow::Result<()> {
        // Auto-detect language if it's currently "text" and we have a path
        if let Some(ref p) = path {
            if let Some(state) = self.buffers.get_mut(&buffer_id) {
                if state.language == "text" {
                    let first_line = state.buffer.first_line_lossy();
                    let detected =
                        crate::primitives::detected_language::DetectedLanguage::from_path(
                            p,
                            first_line.as_deref(),
                            &self.grammar_registry,
                            &self.config.languages,
                        );
                    state.apply_language(detected);
                }
            }
        }

        if !silent {
            self.status_message = Some(t!("status.file_saved").to_string());
        }

        // Mark the event log position as saved (for undo modified tracking)
        if let Some(event_log) = self.event_logs.get_mut(&buffer_id) {
            event_log.mark_saved();
        }

        // Update file modification time after save
        if let Some(ref p) = path {
            if let Ok(metadata) = self.authority.filesystem.metadata(p) {
                if let Some(mtime) = metadata.modified {
                    self.file_mod_times.insert(p.clone(), mtime);
                }
            }
        }

        // Reload .gitignore in the file explorer when the user saves one.
        // Otherwise the tree keeps filtering by the old rules until restart.
        if let Some(ref p) = path {
            if p.file_name().and_then(|n| n.to_str()) == Some(".gitignore") {
                if let Some(parent) = p.parent() {
                    let parent = parent.to_path_buf();
                    let fs = self.authority.filesystem.clone();
                    if let Some(explorer) = self.file_explorer.as_mut() {
                        load_gitignore_via_fs(fs.as_ref(), explorer, &parent);
                    }
                }
            }
        }

        // Notify LSP of save
        self.notify_lsp_save_buffer(buffer_id);

        // Delete recovery file (buffer is now saved)
        if let Err(e) = self.delete_buffer_recovery(buffer_id) {
            tracing::warn!("Failed to delete recovery file: {}", e);
        }

        // Emit control event
        if let Some(ref p) = path {
            self.emit_event(
                crate::model::control_event::events::FILE_SAVED.name,
                serde_json::json!({
                    "path": p.display().to_string()
                }),
            );
        }

        // Fire AfterFileSave hook for plugins
        if let Some(ref p) = path {
            self.plugin_manager.run_hook(
                "after_file_save",
                crate::services::plugins::hooks::HookArgs::AfterFileSave {
                    buffer_id,
                    path: p.clone(),
                },
            );
        }

        // Run on-save actions (formatters, linters, etc.)
        // Note: run_on_save_actions also assumes active_buffer internally.
        // We might need to refactor it too if we want auto-save to trigger formatters.
        // For now, let's just do it for active buffer or skip for silent auto-saves.

        if !silent {
            match self.run_on_save_actions() {
                Ok(true) => {
                    // Actions ran successfully - if status_message was set by run_on_save_actions
                    // (e.g., for missing optional formatters), keep it. Otherwise update status.
                    if self.status_message.as_deref() == Some(&t!("status.file_saved")) {
                        self.status_message =
                            Some(t!("status.file_saved_with_actions").to_string());
                    }
                    // else: keep the message set by run_on_save_actions (e.g., missing formatter)
                }
                Ok(false) => {
                    // No actions configured, keep original status
                }
                Err(e) => {
                    // Action failed, show error but don't fail the save
                    self.status_message = Some(e);
                }
            }
        }

        Ok(())
    }

    /// Auto-save all modified buffers to their original files on disk
    /// Returns the number of buffers saved
    pub fn auto_save_persistent_buffers(&mut self) -> anyhow::Result<usize> {
        if !self.config.editor.auto_save_enabled {
            return Ok(0);
        }

        // Check if enough time has passed since last auto-save
        let interval =
            std::time::Duration::from_secs(self.config.editor.auto_save_interval_secs as u64);
        if self
            .time_source
            .elapsed_since(self.last_persistent_auto_save)
            < interval
        {
            return Ok(0);
        }

        self.last_persistent_auto_save = self.time_source.now();

        // Collect info for modified buffers that have a file path
        let mut to_save = Vec::new();
        for (id, state) in &self.buffers {
            if state.buffer.is_modified() {
                if let Some(path) = state.buffer.file_path() {
                    to_save.push((*id, path.to_path_buf()));
                }
            }
        }

        let mut count = 0;
        for (id, path) in to_save {
            if let Some(state) = self.buffers.get_mut(&id) {
                match state.buffer.save() {
                    Ok(()) => {
                        self.finalize_save_buffer(id, Some(path), true)?;
                        count += 1;
                    }
                    Err(e) => {
                        // Skip if sudo is required (auto-save can't handle prompts)
                        if e.downcast_ref::<SudoSaveRequired>().is_some() {
                            tracing::debug!(
                                "Auto-save skipped for {:?} (sudo required)",
                                path.display()
                            );
                        } else {
                            tracing::warn!("Auto-save failed for {:?}: {}", path.display(), e);
                        }
                    }
                }
            }
        }

        Ok(count)
    }

    /// Save all modified file-backed buffers to disk (called on exit when auto_save is enabled).
    /// Unlike `auto_save_persistent_buffers`, this skips the interval check and only saves
    /// named file-backed buffers (not unnamed buffers).
    pub fn save_all_on_exit(&mut self) -> anyhow::Result<usize> {
        let mut to_save = Vec::new();
        for (id, state) in &self.buffers {
            if state.buffer.is_modified() {
                if let Some(path) = state.buffer.file_path() {
                    if !path.as_os_str().is_empty() {
                        to_save.push((*id, path.to_path_buf()));
                    }
                }
            }
        }

        let mut count = 0;
        for (id, path) in to_save {
            if let Some(state) = self.buffers.get_mut(&id) {
                match state.buffer.save() {
                    Ok(()) => {
                        self.finalize_save_buffer(id, Some(path), true)?;
                        count += 1;
                    }
                    Err(e) => {
                        if e.downcast_ref::<SudoSaveRequired>().is_some() {
                            tracing::debug!(
                                "Auto-save on exit skipped for {} (sudo required)",
                                path.display()
                            );
                        } else {
                            tracing::warn!(
                                "Auto-save on exit failed for {}: {}",
                                path.display(),
                                e
                            );
                        }
                    }
                }
            }
        }

        Ok(count)
    }

    /// Revert the active buffer to the last saved version on disk
    /// Returns Ok(true) if reverted, Ok(false) if no file path, Err on failure
    pub fn revert_file(&mut self) -> anyhow::Result<bool> {
        let path = match self.active_state().buffer.file_path() {
            Some(p) => p.to_path_buf(),
            None => {
                self.status_message = Some(t!("status.no_file_to_revert").to_string());
                return Ok(false);
            }
        };

        if !path.exists() {
            self.status_message =
                Some(t!("status.file_not_exists", path = path.display().to_string()).to_string());
            return Ok(false);
        }

        // Save scroll position (from SplitViewState) and cursor positions before reloading
        let active_split = self.split_manager.active_split();
        let (old_top_byte, old_left_column) = self
            .split_view_states
            .get(&active_split)
            .map(|vs| (vs.viewport.top_byte, vs.viewport.left_column))
            .unwrap_or((0, 0));
        let old_cursors = self.active_cursors().clone();

        // Preserve user settings before reloading
        let old_buffer_settings = self.active_state().buffer_settings.clone();
        let old_editing_disabled = self.active_state().editing_disabled;

        // Load the file content fresh from disk
        let mut new_state = EditorState::from_file_with_languages(
            &path,
            self.terminal_width,
            self.terminal_height,
            self.config.editor.large_file_threshold_bytes as usize,
            &self.grammar_registry,
            &self.config.languages,
            std::sync::Arc::clone(&self.authority.filesystem),
        )?;

        // Restore cursor positions (clamped to valid range for new file size)
        let new_file_size = new_state.buffer.len();
        let mut restored_cursors = old_cursors;
        restored_cursors.map(|cursor| {
            cursor.position = cursor.position.min(new_file_size);
            // Clear selection since the content may have changed
            cursor.clear_selection();
        });
        // Restore user settings (tab size, indentation, etc.)
        new_state.buffer_settings = old_buffer_settings;
        new_state.editing_disabled = old_editing_disabled;
        // Line number visibility is in per-split BufferViewState (survives buffer replacement)

        // Replace the current buffer with the new state
        let buffer_id = self.active_buffer();
        if let Some(state) = self.buffers.get_mut(&buffer_id) {
            *state = new_state;
            // Note: line_wrap_enabled is now in SplitViewState.viewport
        }

        // Restore cursor positions in SplitViewState (clamped to valid range for new file size)
        let active_split = self.split_manager.active_split();
        if let Some(view_state) = self.split_view_states.get_mut(&active_split) {
            view_state.cursors = restored_cursors;
        }

        // Restore scroll position in SplitViewState (clamped to valid range for new file size)
        if let Some(view_state) = self.split_view_states.get_mut(&active_split) {
            view_state.viewport.top_byte = old_top_byte.min(new_file_size);
            view_state.viewport.left_column = old_left_column;
        }

        // Clear the undo/redo history for this buffer
        if let Some(event_log) = self.event_logs.get_mut(&buffer_id) {
            *event_log = EventLog::new();
        }

        // Clear seen_byte_ranges so plugins get notified of all visible lines
        self.seen_byte_ranges.remove(&buffer_id);

        // Update the file modification time
        if let Ok(metadata) = self.authority.filesystem.metadata(&path) {
            if let Some(mtime) = metadata.modified {
                self.file_mod_times.insert(path.clone(), mtime);
            }
        }

        // Notify LSP that the file was changed
        self.notify_lsp_file_changed(&path);

        self.status_message = Some(t!("status.reverted").to_string());
        Ok(true)
    }

    /// Toggle auto-revert mode
    pub fn toggle_auto_revert(&mut self) {
        self.auto_revert_enabled = !self.auto_revert_enabled;

        if self.auto_revert_enabled {
            self.status_message = Some(t!("status.auto_revert_enabled").to_string());
        } else {
            self.status_message = Some(t!("status.auto_revert_disabled").to_string());
        }
    }

    /// Poll for file changes (called from main loop)
    ///
    /// Checks modification times of open files to detect external changes.
    /// Returns true if any file was changed (requires re-render).
    ///
    /// To avoid blocking the event loop, metadata checks run on a background
    /// thread. This method launches a poll if the interval has elapsed and no
    /// poll is already in flight, then checks for results from a prior poll.
    pub fn poll_file_changes(&mut self) -> bool {
        // Skip if auto-revert is disabled
        if !self.auto_revert_enabled {
            return false;
        }

        // Check for results from a previous background poll
        let mut any_changed = false;
        if let Some(ref rx) = self.pending_file_poll_rx {
            match rx.try_recv() {
                Ok(results) => {
                    self.pending_file_poll_rx = None;
                    any_changed = self.process_file_poll_results(results);
                }
                Err(std::sync::mpsc::TryRecvError::Empty) => {
                    // Still in progress — don't block, don't start another
                    return false;
                }
                Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                    // Background task panicked or was dropped
                    self.pending_file_poll_rx = None;
                }
            }
        }

        // Check poll interval
        let poll_interval =
            std::time::Duration::from_millis(self.config.editor.auto_revert_poll_interval_ms);
        let elapsed = self.time_source.elapsed_since(self.last_auto_revert_poll);
        tracing::trace!(
            "poll_file_changes: elapsed={:?}, poll_interval={:?}",
            elapsed,
            poll_interval
        );
        if elapsed < poll_interval {
            return any_changed;
        }
        self.last_auto_revert_poll = self.time_source.now();

        // Collect paths of open files that need checking
        let files_to_check: Vec<PathBuf> = self
            .buffers
            .values()
            .filter_map(|state| state.buffer.file_path().map(PathBuf::from))
            .collect();

        if files_to_check.is_empty() {
            return any_changed;
        }

        // Spawn background metadata checks
        let (tx, rx) = std::sync::mpsc::channel();
        let fs = self.authority.filesystem.clone();
        std::thread::Builder::new()
            .name("poll-file-changes".to_string())
            .spawn(move || {
                let results: Vec<(PathBuf, Option<std::time::SystemTime>)> = files_to_check
                    .into_iter()
                    .map(|path| {
                        let mtime = fs.metadata(&path).ok().and_then(|m| m.modified);
                        (path, mtime)
                    })
                    .collect();
                // Receiver may have been dropped if auto-revert was disabled
                // or the editor is shutting down — that's fine.
                if tx.send(results).is_err() {}
            })
            .ok();
        self.pending_file_poll_rx = Some(rx);

        any_changed
    }

    /// Process results from a background file poll
    fn process_file_poll_results(
        &mut self,
        results: Vec<(PathBuf, Option<std::time::SystemTime>)>,
    ) -> bool {
        let mut any_changed = false;
        for (path, mtime_opt) in results {
            let Some(current_mtime) = mtime_opt else {
                continue;
            };

            if let Some(&stored_mtime) = self.file_mod_times.get(&path) {
                if current_mtime != stored_mtime {
                    let path_str = path.display().to_string();
                    if self.handle_async_file_changed(path_str) {
                        any_changed = true;
                    }
                }
            } else {
                // First time seeing this file, record its mtime
                self.file_mod_times.insert(path, current_mtime);
            }
        }
        any_changed
    }

    /// Poll for file tree changes (called from main loop)
    ///
    /// Checks modification times of expanded directories to detect new/deleted files.
    /// Returns true if any directory was refreshed (requires re-render).
    ///
    /// Like poll_file_changes, metadata checks run on a background thread to
    /// avoid blocking the event loop.
    pub fn poll_file_tree_changes(&mut self) -> bool {
        use crate::view::file_tree::NodeId;

        // Check for results from a previous background poll
        let mut any_refreshed = false;
        let mut dir_poll_pending = false;
        if let Some(ref rx) = self.pending_dir_poll_rx {
            match rx.try_recv() {
                Ok((dir_results, git_index_mtime)) => {
                    self.pending_dir_poll_rx = None;
                    any_refreshed = self.process_dir_poll_results(dir_results, git_index_mtime);
                }
                Err(std::sync::mpsc::TryRecvError::Empty) => {
                    dir_poll_pending = true;
                }
                Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                    self.pending_dir_poll_rx = None;
                }
            }
        }

        // Check poll interval
        let poll_interval =
            std::time::Duration::from_millis(self.config.editor.file_tree_poll_interval_ms);
        if self.time_source.elapsed_since(self.last_file_tree_poll) < poll_interval {
            return any_refreshed;
        }
        self.last_file_tree_poll = self.time_source.now();

        // Re-stat every loaded .gitignore and reload/drop as needed, so
        // external edits (git pull, sed, another editor) and deletions take
        // effect without a restart. In-editor saves already reload eagerly
        // via finalize_save_buffer. Sync I/O here — a handful of small files
        // and all access goes through the filesystem authority.
        if self.sync_gitignores_from_disk() {
            any_refreshed = true;
        }

        // If a previous dir-poll is still in flight, don't stack another.
        if dir_poll_pending {
            return any_refreshed;
        }

        // Resolve the git index path once (first poll only). This uses the
        // ProcessSpawner which may block briefly on the first call, but only
        // happens once per session.
        if !self.git_index_resolved {
            self.git_index_resolved = true;
            if let Some(path) = self.resolve_git_index() {
                if let Ok(meta) = self.authority.filesystem.metadata(&path) {
                    if let Some(mtime) = meta.modified {
                        self.dir_mod_times.insert(path, mtime);
                    }
                }
            }
        }

        // Get file explorer reference
        let Some(explorer) = &self.file_explorer else {
            return any_refreshed;
        };

        // Collect expanded directories (node_id, path)
        let expanded_dirs: Vec<(NodeId, PathBuf)> = explorer
            .tree()
            .all_nodes()
            .filter(|node| node.is_dir() && node.is_expanded())
            .map(|node| (node.id, node.entry.path.clone()))
            .collect();

        // Find the git index path to include in the background metadata check
        let git_index_path: Option<PathBuf> = self
            .dir_mod_times
            .keys()
            .find(|p| p.ends_with(".git/index") || p.ends_with(".git\\index"))
            .cloned();

        if expanded_dirs.is_empty() && git_index_path.is_none() {
            return any_refreshed;
        }

        // Spawn background metadata checks (directories + git index)
        let (tx, rx) = std::sync::mpsc::channel();
        let fs = self.authority.filesystem.clone();
        std::thread::Builder::new()
            .name("poll-dir-changes".to_string())
            .spawn(move || {
                let results: Vec<(NodeId, PathBuf, Option<std::time::SystemTime>)> = expanded_dirs
                    .into_iter()
                    .map(|(node_id, path)| {
                        let mtime = fs.metadata(&path).ok().and_then(|m| m.modified);
                        (node_id, path, mtime)
                    })
                    .collect();

                // Also check git index mtime in the same background thread
                let git_index_mtime = git_index_path.and_then(|path| {
                    let mtime = fs.metadata(&path).ok().and_then(|m| m.modified);
                    Some((path, mtime?))
                });

                // Receiver may have been dropped during shutdown — that's fine.
                if tx.send((results, git_index_mtime)).is_err() {}
            })
            .ok();
        self.pending_dir_poll_rx = Some(rx);

        any_refreshed
    }

    /// Process results from a background directory poll
    fn process_dir_poll_results(
        &mut self,
        results: Vec<(
            crate::view::file_tree::NodeId,
            PathBuf,
            Option<std::time::SystemTime>,
        )>,
        git_index_mtime: Option<(PathBuf, std::time::SystemTime)>,
    ) -> bool {
        let mut dirs_to_refresh: Vec<(crate::view::file_tree::NodeId, PathBuf)> = Vec::new();

        for (node_id, path, mtime_opt) in results {
            let Some(current_mtime) = mtime_opt else {
                continue;
            };

            if let Some(&stored_mtime) = self.dir_mod_times.get(&path) {
                if current_mtime != stored_mtime {
                    self.dir_mod_times.insert(path.clone(), current_mtime);
                    dirs_to_refresh.push((node_id, path.clone()));
                    tracing::debug!("Directory changed: {:?}", path);
                }
            } else {
                self.dir_mod_times.insert(path, current_mtime);
            }
        }

        // Check if .git/index mtime changed (detected in background thread)
        let git_index_changed = if let Some((path, current_mtime)) = git_index_mtime {
            if let Some(&stored_mtime) = self.dir_mod_times.get(&path) {
                if current_mtime != stored_mtime {
                    self.dir_mod_times.insert(path, current_mtime);
                    self.plugin_manager.run_hook(
                        "focus_gained",
                        crate::services::plugins::hooks::HookArgs::FocusGained,
                    );
                    true
                } else {
                    false
                }
            } else {
                false
            }
        } else {
            false
        };

        if dirs_to_refresh.is_empty() && !git_index_changed {
            return false;
        }

        // Refresh each changed directory and (re)load its .gitignore. A new
        // .gitignore file inside an expanded dir bumps the dir's mtime so we
        // land here; reload_expanded_node re-lists entries but doesn't parse
        // rules — load_gitignore_via_fs handles the rules side.
        let refreshed_dirs: Vec<PathBuf> = dirs_to_refresh.iter().map(|(_, p)| p.clone()).collect();
        self.refresh_file_tree_dirs(&refreshed_dirs);
        let fs = self.authority.filesystem.clone();
        if let Some(explorer) = self.file_explorer.as_mut() {
            for dir in refreshed_dirs {
                load_gitignore_via_fs(fs.as_ref(), explorer, &dir);
            }
        }

        true
    }

    /// Re-read the given directories in the file explorer, preserving
    /// descendant expansion state and the cursor's path.
    ///
    /// Why reload_expanded_node and not refresh_node: refresh_node
    /// collapses the directory and re-expands it, which recycles every
    /// descendant NodeId and drops their expansion state. That's fatal
    /// for this code path, which runs unprompted from a background timer:
    /// after a cut+paste into the workspace root, the source parent's
    /// mtime changes, we land here seconds later, and refresh_node would
    /// collapse a user-expanded subtree and invalidate the cursor
    /// NodeId (after which Up/Down become no-ops because
    /// select_next/select_prev can't find the current id in the visible
    /// list).
    ///
    /// We also snapshot the cursor path before the reload and
    /// re-resolve it afterwards. reload_expanded_node still recycles
    /// ids under the refreshed root, so the old id is gone; the path
    /// survives unless the underlying file was deleted, in which case
    /// we fall back to the root so the cursor stays live and visible
    /// (a stale id is effectively no cursor at all).
    ///
    /// Exposed as `pub` so tests can drive the refresh path directly
    /// without relying on filesystem mtime detection, which is too
    /// environment-sensitive (especially across CI filesystems).
    pub fn refresh_file_tree_dirs(&mut self, paths: &[PathBuf]) {
        let (Some(runtime), Some(explorer)) = (&self.tokio_runtime, &mut self.file_explorer) else {
            return;
        };
        let cursor_path: Option<PathBuf> = explorer.get_selected_entry().map(|e| e.path.clone());
        // Re-resolve node ids by path at each step: an earlier
        // reload_expanded_node in this loop may have recycled ids under
        // its subtree, so any ids captured before this call can be
        // stale.
        for path in paths {
            let Some(id_now) = explorer.tree().get_node_by_path(path).map(|n| n.id) else {
                continue;
            };
            let tree = explorer.tree_mut();
            if let Err(e) = runtime.block_on(tree.reload_expanded_node(id_now)) {
                tracing::warn!("Failed to refresh directory {:?}: {}", path, e);
            }
        }
        if let Some(path) = cursor_path {
            if explorer.tree().get_node_by_path(&path).is_some() {
                explorer.navigate_to_path(&path);
            } else {
                let root_id = explorer.tree().root_id();
                explorer.set_selected(Some(root_id));
            }
        }
    }

    /// Re-stat every loaded .gitignore via the filesystem authority and
    /// reload or drop as needed. Returns true if anything changed.
    fn sync_gitignores_from_disk(&mut self) -> bool {
        let fs = self.authority.filesystem.clone();
        let Some(explorer) = self.file_explorer.as_mut() else {
            return false;
        };
        let dirs = explorer.ignore_patterns().loaded_gitignore_dirs();
        let mut changed = false;
        for dir in dirs {
            let gitignore_path = dir.join(".gitignore");
            match fs.metadata(&gitignore_path) {
                Err(_) => {
                    explorer.ignore_patterns_mut().remove_gitignore(&dir);
                    changed = true;
                }
                Ok(meta) => {
                    let stored = explorer.ignore_patterns().stored_gitignore_mtime(&dir);
                    if stored != meta.modified {
                        load_gitignore_via_fs(fs.as_ref(), explorer, &dir);
                        changed = true;
                    }
                }
            }
        }
        changed
    }

    /// Resolve the path to `.git/index` via `git rev-parse --git-dir`.
    /// Uses the `ProcessSpawner` so it works transparently on both local
    /// and remote (SSH) filesystems.
    fn resolve_git_index(&self) -> Option<PathBuf> {
        let spawner = &self.authority.process_spawner;
        let cwd = self.working_dir.to_string_lossy().to_string();

        // ProcessSpawner is async — run it on the tokio runtime if available,
        // otherwise fall back to blocking (should only happen in tests without
        // a runtime).
        let result = if let Some(ref rt) = self.tokio_runtime {
            rt.block_on(spawner.spawn(
                "git".to_string(),
                vec!["rev-parse".to_string(), "--git-dir".to_string()],
                Some(cwd),
            ))
        } else {
            // No runtime — can't run async spawner. This shouldn't happen
            // in production but can in minimal test setups.
            return None;
        };

        let output = result.ok()?;
        if output.exit_code != 0 {
            return None;
        }
        let git_dir = output.stdout.trim();
        let git_dir_path = if std::path::Path::new(git_dir).is_absolute() {
            PathBuf::from(git_dir)
        } else {
            self.working_dir.join(git_dir)
        };
        Some(git_dir_path.join("index"))
    }

    /// Notify LSP server about a newly opened file
    /// Handles language detection, spawning LSP clients, and sending didOpen notifications
    pub(crate) fn notify_lsp_file_opened(
        &mut self,
        path: &Path,
        buffer_id: BufferId,
        metadata: &mut BufferMetadata,
    ) {
        // Get language from buffer state
        let Some(language) = self.buffers.get(&buffer_id).map(|s| s.language.clone()) else {
            tracing::debug!("No buffer state for file: {}", path.display());
            return;
        };

        let Some(uri) = metadata.file_uri().cloned() else {
            tracing::warn!(
                "No URI in metadata for file: {} (failed to compute absolute path)",
                path.display()
            );
            return;
        };

        // Check file size
        let file_size = self
            .authority
            .filesystem
            .metadata(path)
            .ok()
            .map(|m| m.size)
            .unwrap_or(0);
        if file_size > self.config.editor.large_file_threshold_bytes {
            let reason = format!("File too large ({} bytes)", file_size);
            tracing::debug!(
                "Skipping LSP for large file: {} ({})",
                path.display(),
                reason
            );
            metadata.disable_lsp(reason);
            return;
        }

        // Get text before borrowing lsp
        let text = match self
            .buffers
            .get(&buffer_id)
            .and_then(|state| state.buffer.to_string())
        {
            Some(t) => t,
            None => {
                tracing::debug!("Buffer not fully loaded for LSP notification");
                return;
            }
        };

        let enable_inlay_hints = self.config.editor.enable_inlay_hints;
        let previous_result_id = self.diagnostic_result_ids.get(uri.as_str()).cloned();

        // Get buffer line count and version for inlay hints
        let (last_line, last_char, buffer_version) = self
            .buffers
            .get(&buffer_id)
            .map(|state| {
                let line_count = state.buffer.line_count().unwrap_or(1000);
                (
                    line_count.saturating_sub(1) as u32,
                    10000u32,
                    state.buffer.version(),
                )
            })
            .unwrap_or((999, 10000, 0));

        // Now borrow lsp and do all LSP operations
        let Some(lsp) = &mut self.lsp else {
            tracing::debug!("No LSP manager available");
            return;
        };

        tracing::debug!("LSP manager available for file: {}", path.display());
        tracing::debug!(
            "Detected language: {} for file: {}",
            language,
            path.display()
        );
        tracing::debug!("Using URI from metadata: {}", uri.as_str());
        tracing::debug!("Attempting to spawn LSP client for language: {}", language);

        match lsp.try_spawn(&language, Some(path)) {
            LspSpawnResult::Spawned => {
                // Send didOpen to ALL server handles for this language,
                // not just the first one.  With multiple servers configured
                // (e.g. error-server + warning-server) each needs to know
                // about the open document.
                for sh in lsp.get_handles_mut(&language) {
                    tracing::info!("Sending didOpen to LSP '{}' for: {}", sh.name, uri.as_str());
                    if let Err(e) = sh
                        .handle
                        .did_open(uri.clone(), text.clone(), language.clone())
                    {
                        tracing::warn!("Failed to send didOpen to LSP '{}': {}", sh.name, e);
                    } else {
                        metadata.lsp_opened_with.insert(sh.handle.id());
                    }
                }

                // Route each follow-up request through capability-aware
                // routing so we never send an optional method to a server
                // that didn't advertise it. On a cold spawn the capability
                // check returns `None` (capabilities aren't known until the
                // `initialize` response arrives); the `LspInitialized`
                // handler replays these requests once capabilities land.
                if let Some(sh) =
                    lsp.handle_for_feature_mut(&language, crate::types::LspFeature::Diagnostics)
                {
                    let request_id = self.next_lsp_request_id;
                    self.next_lsp_request_id += 1;
                    if let Err(e) =
                        sh.handle
                            .document_diagnostic(request_id, uri.clone(), previous_result_id)
                    {
                        tracing::debug!("Failed to request pull diagnostics: {}", e);
                    } else {
                        tracing::info!(
                            "Requested pull diagnostics for {} (request_id={})",
                            uri.as_str(),
                            request_id
                        );
                    }
                }

                if enable_inlay_hints {
                    if let Some(sh) =
                        lsp.handle_for_feature_mut(&language, crate::types::LspFeature::InlayHints)
                    {
                        let request_id = self.next_lsp_request_id;
                        self.next_lsp_request_id += 1;

                        if let Err(e) = sh.handle.inlay_hints(
                            request_id,
                            uri.clone(),
                            0,
                            0,
                            last_line,
                            last_char,
                        ) {
                            tracing::debug!("Failed to request inlay hints: {}", e);
                        } else {
                            self.pending_inlay_hints_requests.insert(
                                request_id,
                                super::InlayHintsRequest {
                                    buffer_id,
                                    version: buffer_version,
                                },
                            );
                            tracing::info!(
                                "Requested inlay hints for {} (request_id={})",
                                uri.as_str(),
                                request_id
                            );
                        }
                    }
                }

                // Schedule folding range refresh
                self.schedule_folding_ranges_refresh(buffer_id);
            }
            LspSpawnResult::NotAutoStart => {
                tracing::debug!(
                    "LSP for {} not auto-starting (auto_start=false). Use command palette to start manually.",
                    language
                );
                // Queue an auto-prompt for this language so the user
                // can discover the dormant server (otherwise the only
                // visible signal is a muted `LSP (off)` pill, which is
                // easy to miss). We intentionally don't show the popup
                // inline here — session restore typically opens many
                // files of the same language back-to-back, and the
                // buffer active at *this* instant isn't necessarily
                // the one the user lands on. Draining happens on
                // render, which guarantees the popup attaches to
                // whichever buffer the user is actually looking at.
                //
                // Skip queueing entirely when the user already got
                // the prompt this session or dismissed the pill —
                // both mean "please don't re-pop this."  The
                // persisted `auto_start = true` flag is what
                // silences the prompt across sessions. Also skip
                // when the process-wide toggle is off — e2e tests
                // set this via `set_lsp_auto_prompt_enabled(false)`
                // in their ctor so the popup doesn't steal
                // keystrokes from unrelated scenarios.
                if self.lsp_auto_prompt_enabled
                    && !self.auto_start_prompted_languages.contains(&language)
                    && !self.is_lsp_language_user_dismissed(&language)
                {
                    self.pending_auto_start_prompts.insert(language);
                }
            }
            LspSpawnResult::NotConfigured => {
                tracing::debug!("No LSP server configured for language: {}", language);
            }
            LspSpawnResult::Disabled => {
                tracing::debug!("LSP disabled in config for language: {}", language);
            }
            LspSpawnResult::Failed => {
                tracing::warn!("Failed to spawn LSP client for language: {}", language);
            }
        }
    }

    /// Record a file's modification time (called when opening files)
    /// This is used by the polling-based auto-revert to detect external changes
    pub(crate) fn watch_file(&mut self, path: &Path) {
        // Record current modification time for polling
        if let Ok(metadata) = self.authority.filesystem.metadata(path) {
            if let Some(mtime) = metadata.modified {
                self.file_mod_times.insert(path.to_path_buf(), mtime);
            }
        }
    }

    /// Notify LSP that a file's contents changed (e.g., after revert)
    pub(crate) fn notify_lsp_file_changed(&mut self, path: &Path) {
        use crate::services::lsp::manager::LspSpawnResult;

        let Some(lsp_uri) = super::types::file_path_to_lsp_uri(path) else {
            return;
        };

        // Find the buffer ID, content, and language for this path
        let Some((buffer_id, content, language)) = self
            .buffers
            .iter()
            .find(|(_, s)| s.buffer.file_path() == Some(path))
            .and_then(|(id, state)| {
                state
                    .buffer
                    .to_string()
                    .map(|t| (*id, t, state.language.clone()))
            })
        else {
            return;
        };

        // Check if we can spawn LSP (respects auto_start setting)
        let spawn_result = {
            let Some(lsp) = self.lsp.as_mut() else {
                return;
            };
            lsp.try_spawn(&language, Some(path))
        };

        // Only proceed if spawned successfully (or already running)
        if spawn_result != LspSpawnResult::Spawned {
            return;
        }

        // Send didOpen to any handles that haven't received it yet
        {
            let opened_with = self
                .buffer_metadata
                .get(&buffer_id)
                .map(|m| m.lsp_opened_with.clone())
                .unwrap_or_default();

            if let Some(lsp) = self.lsp.as_mut() {
                for sh in lsp.get_handles_mut(&language) {
                    if opened_with.contains(&sh.handle.id()) {
                        continue;
                    }
                    if let Err(e) =
                        sh.handle
                            .did_open(lsp_uri.clone(), content.clone(), language.clone())
                    {
                        tracing::warn!(
                            "Failed to send didOpen to LSP '{}' before didChange: {}",
                            sh.name,
                            e
                        );
                    } else {
                        tracing::debug!(
                            "Sent didOpen for {} to LSP '{}' before file change notification",
                            lsp_uri.as_str(),
                            sh.name
                        );
                    }
                }
            }

            // Mark all handles as opened
            if let Some(lsp) = self.lsp.as_ref() {
                if let Some(metadata) = self.buffer_metadata.get_mut(&buffer_id) {
                    for sh in lsp.get_handles(&language) {
                        metadata.lsp_opened_with.insert(sh.handle.id());
                    }
                }
            }
        }

        // Use full document sync - broadcast to all handles
        if let Some(lsp) = &mut self.lsp {
            let content_change = TextDocumentContentChangeEvent {
                range: None, // None means full document replacement
                range_length: None,
                text: content,
            };
            for sh in lsp.get_handles_mut(&language) {
                if let Err(e) = sh
                    .handle
                    .did_change(lsp_uri.clone(), vec![content_change.clone()])
                {
                    tracing::warn!("Failed to notify LSP '{}' of file change: {}", sh.name, e);
                }
            }
        }
    }

    /// Revert a specific buffer by ID without affecting the active viewport.
    ///
    /// This is used for auto-reverting background buffers that aren't currently
    /// visible in the active split. It reloads the buffer content and updates
    /// cursors (clamped to valid positions), but does NOT touch any viewport state.
    pub(crate) fn revert_buffer_by_id(
        &mut self,
        buffer_id: BufferId,
        path: &Path,
    ) -> anyhow::Result<()> {
        // Preserve user settings before reloading
        // TODO: Consider moving line numbers to SplitViewState (per-view setting)
        // Get cursors from split view states for this buffer (find any split showing it)
        let old_cursors = self
            .split_view_states
            .values()
            .find_map(|vs| {
                if vs.keyed_states.contains_key(&buffer_id) {
                    vs.keyed_states.get(&buffer_id).map(|bs| bs.cursors.clone())
                } else {
                    None
                }
            })
            .unwrap_or_default();
        let (old_buffer_settings, old_editing_disabled) = self
            .buffers
            .get(&buffer_id)
            .map(|s| (s.buffer_settings.clone(), s.editing_disabled))
            .unwrap_or_default();

        // Load the file content fresh from disk
        let mut new_state = EditorState::from_file_with_languages(
            path,
            self.terminal_width,
            self.terminal_height,
            self.config.editor.large_file_threshold_bytes as usize,
            &self.grammar_registry,
            &self.config.languages,
            std::sync::Arc::clone(&self.authority.filesystem),
        )?;

        // Get the new file size for clamping
        let new_file_size = new_state.buffer.len();

        // Restore cursor positions (clamped to valid range for new file size)
        let mut restored_cursors = old_cursors;
        restored_cursors.map(|cursor| {
            cursor.position = cursor.position.min(new_file_size);
            cursor.clear_selection();
        });
        // Restore user settings (tab size, indentation, etc.)
        new_state.buffer_settings = old_buffer_settings;
        new_state.editing_disabled = old_editing_disabled;
        // Line number visibility is in per-split BufferViewState (survives buffer replacement)

        // Replace the buffer content
        if let Some(state) = self.buffers.get_mut(&buffer_id) {
            *state = new_state;
        }

        // Restore cursors in any split view states that have this buffer
        for vs in self.split_view_states.values_mut() {
            if let Some(buf_state) = vs.keyed_states.get_mut(&buffer_id) {
                buf_state.cursors = restored_cursors.clone();
            }
        }

        // Clear the undo/redo history for this buffer
        if let Some(event_log) = self.event_logs.get_mut(&buffer_id) {
            *event_log = EventLog::new();
        }

        // Clear seen_byte_ranges so plugins get notified of all visible lines
        self.seen_byte_ranges.remove(&buffer_id);

        // Update the file modification time
        if let Ok(metadata) = self.authority.filesystem.metadata(path) {
            if let Some(mtime) = metadata.modified {
                self.file_mod_times.insert(path.to_path_buf(), mtime);
            }
        }

        // Notify LSP that the file was changed
        self.notify_lsp_file_changed(path);

        Ok(())
    }

    /// Handle a file change notification (from file watcher)
    pub fn handle_file_changed(&mut self, changed_path: &str) {
        let path = PathBuf::from(changed_path);

        // Find buffers that have this file open
        let buffer_ids: Vec<BufferId> = self
            .buffers
            .iter()
            .filter(|(_, state)| state.buffer.file_path() == Some(&path))
            .map(|(id, _)| *id)
            .collect();

        if buffer_ids.is_empty() {
            return;
        }

        for buffer_id in buffer_ids {
            // Skip terminal buffers - they manage their own content via PTY streaming
            // and should not be auto-reverted (which would reset editing_disabled and line_numbers)
            if self.terminal_buffers.contains_key(&buffer_id) {
                continue;
            }

            let state = match self.buffers.get(&buffer_id) {
                Some(s) => s,
                None => continue,
            };

            // Check if the file actually changed (compare mod times)
            // We use optimistic concurrency: check mtime, and if we decide to revert,
            // re-check to handle the race where a save completed between our checks.
            let current_mtime = match self
                .authority
                .filesystem
                .metadata(&path)
                .ok()
                .and_then(|m| m.modified)
            {
                Some(mtime) => mtime,
                None => continue, // Can't read file, skip
            };

            let dominated_by_stored = self
                .file_mod_times
                .get(&path)
                .map(|stored| current_mtime <= *stored)
                .unwrap_or(false);

            if dominated_by_stored {
                continue;
            }

            // If buffer has local modifications, show a warning (don't auto-revert)
            if state.buffer.is_modified() {
                self.status_message = Some(format!(
                    "File {} changed on disk (buffer has unsaved changes)",
                    path.display()
                ));
                continue;
            }

            // Auto-revert if enabled and buffer is not modified
            if self.auto_revert_enabled {
                // Optimistic concurrency: re-check mtime before reverting.
                // A save may have completed between our first check and now,
                // updating file_mod_times. If so, skip the revert.
                let still_needs_revert = self
                    .file_mod_times
                    .get(&path)
                    .map(|stored| current_mtime > *stored)
                    .unwrap_or(true);

                if !still_needs_revert {
                    continue;
                }

                // Check if this buffer is currently displayed in the active split
                let is_active_buffer = buffer_id == self.active_buffer();

                if is_active_buffer {
                    // Use revert_file() which preserves viewport for active buffer
                    if let Err(e) = self.revert_file() {
                        tracing::error!("Failed to auto-revert file {:?}: {}", path, e);
                    } else {
                        tracing::info!("Auto-reverted file: {:?}", path);
                    }
                } else {
                    // Use revert_buffer_by_id() which doesn't touch any viewport
                    // This prevents corrupting the active split's viewport state
                    if let Err(e) = self.revert_buffer_by_id(buffer_id, &path) {
                        tracing::error!("Failed to auto-revert background file {:?}: {}", path, e);
                    } else {
                        tracing::info!("Auto-reverted file: {:?}", path);
                    }
                }

                // Update the modification time tracking for this file
                self.watch_file(&path);
            }
        }
    }

    /// Check if saving would overwrite changes made by another process
    /// Returns Some(current_mtime) if there's a conflict, None otherwise
    pub fn check_save_conflict(&self) -> Option<std::time::SystemTime> {
        let path = self.active_state().buffer.file_path()?;

        // Get current file modification time
        let current_mtime = self
            .authority
            .filesystem
            .metadata(path)
            .ok()
            .and_then(|m| m.modified)?;

        // Compare with our recorded modification time
        match self.file_mod_times.get(path) {
            Some(recorded_mtime) if current_mtime > *recorded_mtime => {
                // File was modified externally since we last loaded/saved it
                Some(current_mtime)
            }
            _ => None,
        }
    }
}

/// Stat and read `dir/.gitignore` via the filesystem authority and install
/// the result on `explorer`. No-op (with a warn-level log on unexpected
/// errors) when the file doesn't exist. Shared by the init, expand, save,
/// and poll paths so everything routes through the same authority.
pub(crate) fn load_gitignore_via_fs(fs: &dyn FileSystem, explorer: &mut FileTreeView, dir: &Path) {
    let gitignore_path = dir.join(".gitignore");
    let meta = match fs.metadata(&gitignore_path) {
        Ok(m) => m,
        Err(_) => return,
    };
    let bytes = match fs.read_file(&gitignore_path) {
        Ok(b) => b,
        Err(e) => {
            tracing::warn!("Failed to read {:?}: {}", gitignore_path, e);
            return;
        }
    };
    explorer.load_gitignore_from_bytes(dir, &bytes, meta.modified);
}