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
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
//! Editor construction and initialization.
//!
//! `Editor::new` and friends — the entry points that take a configuration,
//! terminal dimensions, color capability, and filesystem implementation
//! and return a ready-to-use Editor with every field initialized.
//!
//! Also includes `start_background_grammar_build`, which kicks off the
//! initial grammar registry build asynchronously so startup doesn't block.
// Re-use everything mod.rs imports — the constructors touch every field
// on Editor and most of the types in the module.
use super::*;
/// Phase-timing helper used when `FRESH_TEST_TIMING=1` is set so test
/// authors can see where `Editor::with_options` spends its wall clock.
/// No-op when the env var is unset; printed to stderr otherwise.
struct InitTimer {
label: &'static str,
start: std::time::Instant,
last: std::time::Instant,
enabled: bool,
}
impl InitTimer {
fn start(label: &'static str) -> Self {
let enabled = std::env::var("FRESH_TEST_TIMING").is_ok_and(|v| !v.is_empty() && v != "0");
let now = std::time::Instant::now();
if enabled {
eprintln!("[timing] {label} start");
}
Self {
label,
start: now,
last: now,
enabled,
}
}
fn phase(&mut self, name: &str) {
if !self.enabled {
return;
}
let now = std::time::Instant::now();
let delta = now.duration_since(self.last);
let cumul = now.duration_since(self.start);
eprintln!(
"[timing] {name:<30} +{delta:>8.1}ms (cumul {cumul:.1}ms)",
name = name,
delta = delta.as_secs_f64() * 1000.0,
cumul = cumul.as_secs_f64() * 1000.0,
);
self.last = now;
}
fn finish(self) {
if !self.enabled {
return;
}
eprintln!(
"[timing] {label} total {total:.1}ms",
label = self.label,
total = self.start.elapsed().as_secs_f64() * 1000.0,
);
}
}
/// Set a value at a dot-separated path inside a JSON object, creating
/// intermediate maps as needed.
fn set_dot_path(root: &mut serde_json::Value, path: &str, value: serde_json::Value) {
let segments: Vec<&str> = path.split('.').filter(|s| !s.is_empty()).collect();
if segments.is_empty() {
return;
}
let mut cur = root;
for seg in &segments[..segments.len() - 1] {
if !cur.is_object() {
*cur = serde_json::Value::Object(serde_json::Map::new());
}
cur = cur
.as_object_mut()
.unwrap()
.entry((*seg).to_string())
.or_insert(serde_json::Value::Null);
}
let last = segments[segments.len() - 1];
if !cur.is_object() {
*cur = serde_json::Value::Object(serde_json::Map::new());
}
cur.as_object_mut().unwrap().insert(last.to_string(), value);
}
impl Editor {
/// Create a new editor with the given configuration and terminal dimensions
/// Uses system directories for state (recovery, sessions, etc.)
pub fn new(
config: Config,
width: u16,
height: u16,
dir_context: DirectoryContext,
color_capability: crate::view::color_support::ColorCapability,
filesystem: Arc<dyn FileSystem + Send + Sync>,
) -> AnyhowResult<Self> {
Self::with_working_dir(
config,
width,
height,
None,
dir_context,
true,
color_capability,
filesystem,
)
}
/// Create a new editor with an explicit working directory
/// This is useful for testing with isolated temporary directories
#[allow(clippy::too_many_arguments)]
pub fn with_working_dir(
config: Config,
width: u16,
height: u16,
working_dir: Option<PathBuf>,
dir_context: DirectoryContext,
plugins_enabled: bool,
color_capability: crate::view::color_support::ColorCapability,
filesystem: Arc<dyn FileSystem + Send + Sync>,
) -> AnyhowResult<Self> {
Self::with_working_dir_opts(
config,
width,
height,
working_dir,
dir_context,
plugins_enabled,
color_capability,
filesystem,
false,
)
}
/// Like [`Self::with_working_dir`] but with `defer_plugin_load`
/// exposed. When `true`, plugin loading is dispatched to the plugin
/// thread and the constructor returns immediately; results arrive
/// later via `AsyncMessage::PluginsDirLoaded` /
/// `PluginDeclarationsReady` and are applied in `process_async_messages`.
/// Used by the TUI startup path so the first frame draws without
/// waiting on TS parse/transpile/register.
#[allow(clippy::too_many_arguments)]
pub fn with_working_dir_opts(
config: Config,
width: u16,
height: u16,
working_dir: Option<PathBuf>,
dir_context: DirectoryContext,
plugins_enabled: bool,
color_capability: crate::view::color_support::ColorCapability,
filesystem: Arc<dyn FileSystem + Send + Sync>,
defer_plugin_load: bool,
) -> AnyhowResult<Self> {
tracing::info!("Building default grammar registry...");
let start = std::time::Instant::now();
let mut grammar_registry = crate::primitives::grammar::GrammarRegistry::defaults_only();
// Merge user config so find_by_path respects user globs/filenames
// from the very first lookup. `defaults_only` just built the Arc, so
// we're the sole owner; get_mut is guaranteed to succeed. Assert
// rather than silently drop config — a failure here would leave the
// user wondering why their `*.conf → bash` rule doesn't highlight.
std::sync::Arc::get_mut(&mut grammar_registry)
.expect("defaults_only returned a shared Arc")
.apply_language_config(&config.languages);
tracing::info!("Default grammar registry built in {:?}", start.elapsed());
// Don't start background grammar build here — it's deferred to the
// first flush_pending_grammars() call so that plugin-registered grammars
// from the first event-loop tick are included in a single build.
Self::with_options(
config,
width,
height,
working_dir,
filesystem,
plugins_enabled,
true, // enable_embedded_plugins (production: always allow embedded fallback)
dir_context,
None,
color_capability,
grammar_registry,
defer_plugin_load,
)
}
/// Create a new editor for testing with custom backends
///
/// By default uses empty grammar registry for fast initialization.
/// Pass `Some(registry)` for tests that need syntax highlighting or shebang detection.
///
/// `enable_plugins` controls whether the plugin runtime is active at all.
/// `enable_embedded_plugins` separately gates the cargo-binstall embedded
/// plugins fallback — tests that pre-populate `<config_dir>/plugins/` and
/// want exact control over which plugins load can pass `false` here while
/// keeping `enable_plugins = true`.
#[allow(clippy::too_many_arguments)]
pub fn for_test(
config: Config,
width: u16,
height: u16,
working_dir: Option<PathBuf>,
dir_context: DirectoryContext,
color_capability: crate::view::color_support::ColorCapability,
filesystem: Arc<dyn FileSystem + Send + Sync>,
time_source: Option<SharedTimeSource>,
grammar_registry: Option<Arc<crate::primitives::grammar::GrammarRegistry>>,
enable_plugins: bool,
enable_embedded_plugins: bool,
) -> AnyhowResult<Self> {
let mut grammar_registry =
grammar_registry.unwrap_or_else(crate::primitives::grammar::GrammarRegistry::empty);
// Merge user `[languages]` config into the catalog — production code
// does this at startup and again after the background grammar build,
// tests need the same so config-declared grammars/extensions resolve
// through `find_by_path`. Both call sites that feed into `for_test`
// (`HarnessOptions::with_full_grammar_registry` and the default
// `GrammarRegistry::empty()`) hand us the sole Arc owner.
std::sync::Arc::get_mut(&mut grammar_registry)
.expect("grammar registry Arc must be uniquely owned at for_test entry")
.apply_language_config(&config.languages);
let mut editor = Self::with_options(
config,
width,
height,
working_dir,
filesystem,
enable_plugins,
enable_embedded_plugins,
dir_context,
time_source,
color_capability,
grammar_registry,
false,
)?;
// Tests typically have no async_bridge, so the deferred grammar build
// would just drain pending_grammars and early-return. Skip it entirely.
editor.needs_full_grammar_build = false;
Ok(editor)
}
/// Create a new editor with custom options
/// This is primarily used for testing with slow or mock backends
/// to verify editor behavior under various I/O conditions
#[allow(clippy::too_many_arguments)]
fn with_options(
mut config: Config,
width: u16,
height: u16,
working_dir: Option<PathBuf>,
filesystem: Arc<dyn FileSystem + Send + Sync>,
enable_plugins: bool,
#[cfg_attr(not(feature = "embed-plugins"), allow(unused_variables))]
enable_embedded_plugins: bool,
dir_context: DirectoryContext,
time_source: Option<SharedTimeSource>,
color_capability: crate::view::color_support::ColorCapability,
grammar_registry: Arc<crate::primitives::grammar::GrammarRegistry>,
defer_plugin_load: bool,
) -> AnyhowResult<Self> {
let mut t = InitTimer::start("Editor::with_options");
// Use provided time_source or default to RealTimeSource
let time_source = time_source.unwrap_or_else(RealTimeSource::shared);
tracing::info!("Editor::new called with width={}, height={}", width, height);
// Use provided working_dir or capture from environment
let working_dir = working_dir
.unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
// Canonicalize working_dir to resolve symlinks and normalize path components
// This ensures consistent path comparisons throughout the editor
let working_dir = working_dir.canonicalize().unwrap_or(working_dir);
t.phase("preamble");
// Load all themes into registry
tracing::info!("Loading themes...");
let theme_loader = crate::view::theme::ThemeLoader::new(dir_context.themes_dir());
t.phase("ThemeLoader::new");
// Scan installed packages (language packs + bundles) before plugin loading.
// This replaces the JS loadInstalledPackages() — configs, grammars, plugin dirs,
// and theme dirs are all collected here and applied synchronously.
let scan_result =
crate::services::packages::scan_installed_packages(&dir_context.config_dir);
t.phase("scan_installed_packages");
// Apply package language configs (user config takes priority via or_insert)
for (lang_id, lang_config) in &scan_result.language_configs {
config
.languages
.entry(lang_id.clone())
.or_insert_with(|| lang_config.clone());
}
// Apply package LSP configs (user config takes priority via or_insert)
for (lang_id, lsp_config) in &scan_result.lsp_configs {
config
.lsp
.entry(lang_id.clone())
.or_insert_with(|| LspLanguageConfig::Multi(vec![lsp_config.clone()]));
}
let theme_registry = Arc::new(theme_loader.load_all(&scan_result.bundle_theme_dirs));
t.phase("theme_loader.load_all");
tracing::info!("Themes loaded");
// Get active theme from registry, falling back to default if not found
let theme = theme_registry.get_cloned(&config.theme).unwrap_or_else(|| {
tracing::warn!(
"Theme '{}' not found, falling back to default theme",
config.theme.0
);
theme_registry
.get_cloned(&crate::config::ThemeName(
crate::view::theme::THEME_HIGH_CONTRAST.to_string(),
))
.expect("Default theme must exist")
});
// Set terminal cursor color to match theme
theme.set_terminal_cursor_color();
t.phase("theme_setup");
let keybindings = Arc::new(RwLock::new(KeybindingResolver::new(&config)));
t.phase("keybindings");
// Create an empty initial buffer
let mut buffers = HashMap::new();
let mut event_logs = HashMap::new();
// Buffer IDs start at 1 (not 0) because the plugin API returns 0 to
// mean "no active buffer" from getActiveBufferId(). JavaScript treats
// 0 as falsy (`if (!bufferId)` would wrongly reject buffer 0), so
// using 1-based IDs avoids this entire class of bugs in plugins.
let buffer_id = BufferId(1);
let mut state = EditorState::new(
width,
height,
config.editor.large_file_threshold_bytes as usize,
Arc::clone(&filesystem),
);
// Configure initial buffer settings from config
state
.margins
.configure_for_line_numbers(config.editor.line_numbers);
state.buffer_settings.tab_size = config.editor.tab_size;
state.buffer_settings.auto_close = config.editor.auto_close;
// Note: line_wrap_enabled is now stored in SplitViewState.viewport
tracing::info!("EditorState created for buffer {:?}", buffer_id);
buffers.insert(buffer_id, state);
event_logs.insert(buffer_id, EventLog::new());
// Create metadata for the initial empty buffer
let mut buffer_metadata = HashMap::new();
buffer_metadata.insert(buffer_id, BufferMetadata::new());
// Initialize LSP manager with current working directory as root
let root_uri = types::file_path_to_lsp_uri(&working_dir);
t.phase("buffer_state");
// Create Tokio runtime for async I/O (LSP, file watching, git, etc.)
let tokio_runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2) // Small pool for I/O tasks
.thread_name("editor-async")
.enable_all()
.build()
.ok();
t.phase("tokio_runtime");
// Create async bridge for communication
let async_bridge = AsyncBridge::new();
if tokio_runtime.is_none() {
tracing::warn!("Failed to create Tokio runtime - async features disabled");
}
// Create LSP manager with async support
let mut lsp = LspManager::new(root_uri);
// Configure runtime and bridge if available
if let Some(ref runtime) = tokio_runtime {
lsp.set_runtime(runtime.handle().clone(), async_bridge.clone());
}
// Configure LSP servers from config
for (language, lsp_configs) in &config.lsp {
lsp.set_language_configs(language.clone(), lsp_configs.as_slice().to_vec());
}
// Configure universal (global) LSP servers — spawned once, shared across languages
let universal_servers: Vec<LspServerConfig> = config
.universal_lsp
.values()
.flat_map(|lc| lc.as_slice().to_vec())
.filter(|c| c.enabled)
.collect();
lsp.set_universal_configs(universal_servers);
// Auto-detect Deno projects: if deno.json or deno.jsonc exists in the
// workspace root, override JS/TS LSP to use `deno lsp` (#1191)
if working_dir.join("deno.json").exists() || working_dir.join("deno.jsonc").exists() {
tracing::info!("Detected Deno project (deno.json found), using deno lsp for JS/TS");
let deno_config = LspServerConfig {
command: "deno".to_string(),
args: vec!["lsp".to_string()],
enabled: true,
auto_start: false,
process_limits: ProcessLimits::default(),
initialization_options: Some(serde_json::json!({"enable": true})),
..Default::default()
};
lsp.set_language_config("javascript".to_string(), deno_config.clone());
lsp.set_language_config("typescript".to_string(), deno_config);
}
t.phase("lsp_setup");
// Initialize split manager with the initial buffer
let split_manager = SplitManager::new(buffer_id);
// Initialize per-split view state for the initial split
let mut split_view_states = HashMap::new();
let initial_split_id = split_manager.active_split();
let mut initial_view_state = SplitViewState::with_buffer(width, height, buffer_id);
initial_view_state.apply_config_defaults(
config.editor.line_numbers,
config.editor.highlight_current_line,
config.editor.line_wrap,
config.editor.wrap_indent,
config.editor.wrap_column,
config.editor.rulers.clone(),
);
split_view_states.insert(initial_split_id, initial_view_state);
// Initialize filesystem manager for file explorer
let fs_manager = Arc::new(FsManager::new(Arc::clone(&filesystem)));
// Initialize command registry (always available, used by both plugins and core)
let command_registry = Arc::new(RwLock::new(CommandRegistry::new()));
// Construct the boot-time authority. Per principle 6, the editor
// always boots with a local authority and renders immediately;
// SSH startup and plugins replace it via `install_authority`
// after their async work is done. The supplied `filesystem`
// overrides the local default to support tests that mock IO.
let authority = crate::services::authority::Authority {
filesystem: Arc::clone(&filesystem),
..crate::services::authority::Authority::local()
};
let process_spawner = Arc::clone(&authority.process_spawner);
// Initialize Quick Open registry with all providers
let mut quick_open_registry = QuickOpenRegistry::new();
quick_open_registry.register(Box::new(FileProvider::new(
Arc::clone(&filesystem),
Arc::clone(&process_spawner),
tokio_runtime.as_ref().map(|rt| rt.handle().clone()),
Some(async_bridge.sender()),
)));
quick_open_registry.register(Box::new(CommandProvider::new(
Arc::clone(&command_registry),
Arc::clone(&keybindings),
)));
quick_open_registry.register(Box::new(BufferProvider::new()));
quick_open_registry.register(Box::new(GotoLineProvider::new()));
// Build shared theme cache for plugin access
let theme_cache = Arc::new(RwLock::new(theme_registry.to_json_map()));
t.phase("split_quickopen_authority");
// Initialize plugin manager (handles both enabled and disabled cases internally)
let plugin_manager = PluginManager::new(
enable_plugins,
Arc::clone(&command_registry),
dir_context.clone(),
Arc::clone(&theme_cache),
);
t.phase("PluginManager::new");
// Update the plugin state snapshot with working_dir BEFORE loading plugins
// This ensures plugins can call getCwd() correctly during initialization
#[cfg(feature = "plugins")]
if let Some(snapshot_handle) = plugin_manager.state_snapshot_handle() {
let mut snapshot = snapshot_handle.write().unwrap();
snapshot.working_dir = working_dir.clone();
// Pre-populate keybinding labels for the static built-in
// keymap so `editor.getKeybindingLabel(action, context)`
// works for actions that aren't behind a plugin-defined
// buffer mode. Without this, a plugin asking
// `getKeybindingLabel("cycle_live_grep_provider",
// "prompt")` gets null even though Alt+P is bound, and
// ends up hardcoding the key in its UI.
populate_builtin_keybinding_labels(&mut snapshot, &keybindings);
}
// Load TypeScript plugins from multiple directories:
// 1. Next to the executable (for cargo-dist installations)
// 2. From embedded plugins (for cargo-binstall and `cargo run`,
// when embed-plugins feature is enabled)
// 3. User plugins directory (~/.config/fresh/plugins)
// 4. Package manager installed plugins (~/.config/fresh/plugins/packages/*)
if plugin_manager.is_active() {
let mut plugin_dirs: Vec<std::path::PathBuf> = vec![];
// Check next to executable first (for cargo-dist installations)
if let Ok(exe_path) = std::env::current_exe() {
if let Some(exe_dir) = exe_path.parent() {
let exe_plugin_dir = exe_dir.join("plugins");
if exe_plugin_dir.exists() {
plugin_dirs.push(exe_plugin_dir);
}
}
}
// No working-directory `plugins/` check: a user project with a
// folder named `plugins/` (e.g. a Vite/Rollup project, a Hugo
// site) is not a Fresh plugin source. Bundled plugins for the
// dev workflow come in via the embedded fallback below; user
// plugins live under `<config_dir>/plugins/`. See issue #1722.
// If no disk plugins found, try embedded plugins (cargo-binstall builds).
// `enable_embedded_plugins` lets tests opt out so they get exactly
// the plugin set they pre-populated under `<config_dir>/plugins/`,
// without the bundled set leaking in.
#[cfg(feature = "embed-plugins")]
if enable_embedded_plugins && plugin_dirs.is_empty() {
if let Some(embedded_dir) =
crate::services::plugins::embedded::get_embedded_plugins_dir()
{
tracing::info!("Using embedded plugins from: {:?}", embedded_dir);
plugin_dirs.push(embedded_dir.clone());
}
}
// Always check user config plugins directory (~/.config/fresh/plugins)
let user_plugins_dir = dir_context.config_dir.join("plugins");
if user_plugins_dir.exists() && !plugin_dirs.contains(&user_plugins_dir) {
tracing::info!("Found user plugins directory: {:?}", user_plugins_dir);
plugin_dirs.push(user_plugins_dir.clone());
}
// Check for package manager installed plugins (~/.config/fresh/plugins/packages/*)
let packages_dir = dir_context.config_dir.join("plugins").join("packages");
if packages_dir.exists() {
if let Ok(entries) = std::fs::read_dir(&packages_dir) {
for entry in entries.flatten() {
let path = entry.path();
// Skip hidden directories (like .index for registry cache)
if path.is_dir() {
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if !name.starts_with('.') {
tracing::info!("Found package manager plugin: {:?}", path);
plugin_dirs.push(path);
}
}
}
}
}
}
// Add bundle plugin directories from package scan
for dir in &scan_result.bundle_plugin_dirs {
tracing::info!("Found bundle plugin directory: {:?}", dir);
plugin_dirs.push(dir.clone());
}
if plugin_dirs.is_empty() {
tracing::debug!(
"No plugins directory found next to executable or in working dir: {:?}",
working_dir
);
}
if defer_plugin_load {
// Async startup path: hand each dir + a trailing
// ListPlugins request to the plugin thread now, return
// before they finish, and let a forwarder thread
// translate the responses into AsyncMessages that the
// main loop applies via `process_async_messages`. The
// plugin thread is FIFO, so submitting in this exact
// order guarantees declarations cover only the startup
// batch — init.ts and lifecycle hooks queue *after*
// ListPlugins from main.rs after construction returns,
// matching the original blocking behaviour.
#[cfg(feature = "plugins")]
{
let bridge = &async_bridge;
let mut dir_receivers: Vec<(
std::path::PathBuf,
fresh_plugin_runtime::thread::oneshot::Receiver<
fresh_plugin_runtime::thread::PluginsDirLoadResult,
>,
)> = Vec::with_capacity(plugin_dirs.len());
for plugin_dir in &plugin_dirs {
tracing::info!(
"Submitting async TypeScript plugin load for: {:?}",
plugin_dir
);
if let Some(rx) = plugin_manager
.load_plugins_from_dir_with_config_request(plugin_dir, &config.plugins)
{
dir_receivers.push((plugin_dir.clone(), rx));
}
}
let declarations_rx = if !dir_receivers.is_empty() {
plugin_manager.list_plugins_request()
} else {
None
};
if !dir_receivers.is_empty() {
let sender = bridge.sender();
std::thread::Builder::new()
.name("plugin-load-forwarder".to_string())
.spawn(move || {
for (dir, rx) in dir_receivers {
let load_start = std::time::Instant::now();
match rx.recv() {
Ok((errors, discovered_plugins)) => {
tracing::info!(
"Loaded TypeScript plugins from {:?} in {:?}",
dir,
load_start.elapsed()
);
drop(sender.send(
crate::services::async_bridge::AsyncMessage::PluginsDirLoaded {
dir,
errors,
discovered_plugins,
},
));
}
Err(e) => {
tracing::warn!(
"plugin-load-forwarder: dir {:?} recv failed: {}",
dir,
e
);
}
}
}
if let Some(rx) = declarations_rx {
match rx.recv() {
Ok(plugin_infos) => {
let declarations: Vec<(String, String)> = plugin_infos
.into_iter()
.filter_map(|info| {
info.declarations.map(|d| (info.name, d))
})
.collect();
drop(sender.send(
crate::services::async_bridge::AsyncMessage::PluginDeclarationsReady {
declarations,
},
));
}
Err(e) => {
tracing::warn!(
"plugin-load-forwarder: list_plugins recv failed: {}",
e
);
}
}
}
})
.ok();
}
}
} else {
// Synchronous (legacy / test) path. Used by `for_test`,
// server, GUI: every other code path that wants the
// editor fully constructed before the constructor
// returns.
for plugin_dir in plugin_dirs {
tracing::info!("Loading TypeScript plugins from: {:?}", plugin_dir);
let load_start = std::time::Instant::now();
let (errors, discovered_plugins) = plugin_manager
.load_plugins_from_dir_with_config(&plugin_dir, &config.plugins);
tracing::info!(
"Loaded TypeScript plugins from {:?} in {:?}",
plugin_dir,
load_start.elapsed()
);
// Merge discovered plugins into config
// discovered_plugins already contains the merged config (saved enabled state + discovered path)
for (name, plugin_config) in discovered_plugins {
config.plugins.insert(name, plugin_config);
}
if !errors.is_empty() {
for err in &errors {
tracing::error!("TypeScript plugin load error: {}", err);
}
// In debug/test builds, panic to surface plugin loading errors
#[cfg(debug_assertions)]
panic!(
"TypeScript plugin loading failed with {} error(s): {}",
errors.len(),
errors.join("; ")
);
}
}
// Collect `.d.ts` emits from every loaded plugin into a
// single aggregate under `<config_dir>/types/plugins.d.ts`.
// This is what makes `getPluginApi("foo")` typed in the
// user's init.ts without a hand-written cast — each plugin
// that uses `declare global { interface FreshPluginRegistry }`
// contributes its augmentation, and init.ts's tsconfig
// picks the aggregate up via `files`.
let declarations = plugin_manager.plugin_declarations();
crate::init_script::write_plugin_declarations(
&dir_context.config_dir,
&declarations,
);
}
}
t.phase("plugin_loading");
// Extract config values before moving config into the struct
let file_explorer_width = config.file_explorer.width;
let file_explorer_side = config.file_explorer.side;
let recovery_enabled = config.editor.recovery_enabled;
let check_for_updates = config.check_for_updates;
let show_menu_bar = config.editor.show_menu_bar;
let show_tab_bar = config.editor.show_tab_bar;
let show_status_bar = config.editor.show_status_bar;
let show_prompt_line = config.editor.show_prompt_line;
// Start periodic update checker if enabled (also sends daily telemetry)
let update_checker = if check_for_updates {
tracing::debug!("Update checking enabled, starting periodic checker");
Some(
crate::services::release_checker::start_periodic_update_check(
crate::services::release_checker::DEFAULT_RELEASES_URL,
time_source.clone(),
dir_context.data_dir.clone(),
),
)
} else {
tracing::debug!("Update checking disabled by config");
None
};
// Cache raw user config at startup (to avoid re-reading file every frame)
let user_config_raw = Config::read_user_config_raw(&working_dir);
// Wrap config in Arc and pre-seed the snapshot mirror + JSON cache.
// Doing this at construction means the strong count of the live
// `config` Arc starts at 2 and stays there: every `Arc::make_mut`
// call on `config` is forced to CoW, so no mutation path (direct or
// via `config_mut()`) can leave `config_cached_json` referring to
// stale memory.
let config_arc = Arc::new(config);
let config_cached_json =
Arc::new(serde_json::to_value(&*config_arc).unwrap_or(serde_json::Value::Null));
let config_snapshot_anchor = Arc::clone(&config_arc);
let mut editor = Editor {
buffers,
event_logs,
next_buffer_id: 2,
config: config_arc,
config_snapshot_anchor,
config_cached_json,
user_config_raw: Arc::new(user_config_raw),
dir_context: dir_context.clone(),
grammar_registry,
pending_grammars: scan_result
.additional_grammars
.iter()
.map(|g| PendingGrammar {
language: g.language.clone(),
grammar_path: g.path.to_string_lossy().to_string(),
extensions: g.extensions.clone(),
})
.collect(),
grammar_reload_pending: false,
grammar_build_in_progress: false,
needs_full_grammar_build: true,
streaming_grep_cancellation: None,
pending_grammar_callbacks: Vec::new(),
theme,
theme_registry,
expanded_menus_cache: crate::view::ui::ExpandedMenusCache::default(),
theme_cache,
ansi_background: None,
ansi_background_path: None,
background_fade: crate::primitives::ansi_background::DEFAULT_BACKGROUND_FADE,
keybindings,
clipboard: crate::services::clipboard::Clipboard::new(),
should_quit: false,
should_detach: false,
session_mode: false,
software_cursor_only: false,
session_name: None,
pending_escape_sequences: Vec::new(),
restart_with_dir: None,
status_message: None,
plugin_status_message: None,
last_window_title: None,
plugin_errors: Vec::new(),
prompt: None,
terminal_width: width,
terminal_height: height,
lsp: Some(lsp),
buffer_metadata,
mode_registry: ModeRegistry::new(),
tokio_runtime,
async_bridge: Some(async_bridge),
split_manager,
split_view_states,
previous_viewports: HashMap::new(),
scroll_sync_manager: ScrollSyncManager::new(),
file_explorer: None,
preview: None,
suppress_position_history_once: false,
fs_manager,
authority,
pending_authority: None,
remote_indicator_override: None,
local_filesystem: Arc::new(crate::model::filesystem::StdFileSystem),
file_explorer_visible: false,
file_explorer_sync_in_progress: false,
file_explorer_width,
file_explorer_side,
pending_file_explorer_show_hidden: None,
pending_file_explorer_show_gitignored: None,
menu_bar_visible: show_menu_bar,
file_explorer_decorations: HashMap::new(),
file_explorer_decoration_cache:
crate::view::file_tree::FileExplorerDecorationCache::default(),
file_explorer_clipboard: None,
menu_bar_auto_shown: false,
tab_bar_visible: show_tab_bar,
status_bar_visible: show_status_bar,
prompt_line_visible: show_prompt_line,
mouse_enabled: true,
same_buffer_scroll_sync: false,
mouse_cursor_position: None,
gpm_active: false,
key_context: KeyContext::Normal,
menu_state: crate::view::ui::MenuState::new(dir_context.themes_dir()),
menus: crate::config::MenuConfig::translated(),
working_dir: working_dir.clone(),
position_history: PositionHistory::new(),
in_navigation: false,
next_lsp_request_id: 0,
pending_completion_requests: HashSet::new(),
completion_items: None,
scheduled_completion_trigger: None,
completion_service: crate::services::completion::CompletionService::new(),
dabbrev_state: None,
pending_goto_definition_request: None,
hover: hover::HoverState::default(),
pending_references_request: None,
pending_references_symbol: String::new(),
pending_signature_help_request: None,
pending_code_actions_requests: HashSet::new(),
pending_code_actions_server_names: HashMap::new(),
pending_code_actions: None,
pending_inlay_hints_requests: HashMap::new(),
pending_folding_range_requests: HashMap::new(),
folding_ranges_in_flight: HashMap::new(),
folding_ranges_debounce: HashMap::new(),
pending_semantic_token_requests: HashMap::new(),
semantic_tokens_in_flight: HashMap::new(),
pending_semantic_token_range_requests: HashMap::new(),
semantic_tokens_range_in_flight: HashMap::new(),
semantic_tokens_range_last_request: HashMap::new(),
semantic_tokens_range_applied: HashMap::new(),
semantic_tokens_full_debounce: HashMap::new(),
search_state: None,
search_namespace: crate::view::overlay::OverlayNamespace::from_string(
"search".to_string(),
),
lsp_diagnostic_namespace: crate::view::overlay::OverlayNamespace::from_string(
"lsp-diagnostic".to_string(),
),
pending_search_range: None,
interactive_replace_state: None,
mouse_state: MouseState::default(),
tab_context_menu: None,
file_explorer_context_menu: None,
theme_info_popup: None,
cached_layout: CachedLayout::default(),
command_registry,
quick_open_registry,
plugin_manager,
plugin_dev_workspaces: HashMap::new(),
seen_byte_ranges: HashMap::new(),
panel_ids: HashMap::new(),
live_grep_last_state: None,
overlay_preview_state: None,
buffer_groups: HashMap::new(),
buffer_to_group: HashMap::new(),
next_buffer_group_id: 0,
grouped_subtrees: HashMap::new(),
background_process_handles: HashMap::new(),
host_process_handles: HashMap::new(),
prompt_histories: {
// Load prompt histories from disk if available
let mut histories = HashMap::new();
for history_name in ["search", "replace", "goto_line"] {
let path = dir_context.prompt_history_path(history_name);
let history = crate::input::input_history::InputHistory::load_from_file(&path)
.unwrap_or_else(|e| {
tracing::warn!("Failed to load {} history: {}", history_name, e);
crate::input::input_history::InputHistory::new()
});
histories.insert(history_name.to_string(), history);
}
histories
},
pending_async_prompt_callback: None,
pending_next_key_callbacks: std::collections::VecDeque::new(),
key_capture_active: false,
pending_key_capture_buffer: std::collections::VecDeque::new(),
goto_line_preview: None,
lsp_progress: std::collections::HashMap::new(),
lsp_server_statuses: std::collections::HashMap::new(),
lsp_window_messages: Vec::new(),
lsp_log_messages: Vec::new(),
diagnostic_result_ids: HashMap::new(),
scheduled_diagnostic_pull: None,
scheduled_inlay_hints_request: None,
stored_push_diagnostics: HashMap::new(),
stored_pull_diagnostics: HashMap::new(),
stored_diagnostics: Arc::new(HashMap::new()),
stored_folding_ranges: Arc::new(HashMap::new()),
event_broadcaster: crate::model::control_event::EventBroadcaster::default(),
bookmarks: bookmarks::BookmarkState::default(),
search_case_sensitive: true,
search_whole_word: false,
search_use_regex: false,
search_confirm_each: false,
macros: macros::MacroState::default(),
#[cfg(feature = "plugins")]
pending_plugin_actions: Vec::new(),
#[cfg(feature = "plugins")]
plugin_render_requested: false,
chord_state: Vec::new(),
user_dismissed_lsp_languages: std::collections::HashSet::new(),
pending_close_buffer: None,
pending_quit_unnamed_save: Vec::new(),
auto_revert_enabled: true,
last_auto_revert_poll: time_source.now(),
last_file_tree_poll: time_source.now(),
git_index_resolved: false,
file_mod_times: HashMap::new(),
dir_mod_times: HashMap::new(),
pending_file_poll_rx: None,
pending_dir_poll_rx: None,
file_rapid_change_counts: HashMap::new(),
file_open_state: None,
file_browser_layout: None,
recovery_service: {
let recovery_config = RecoveryConfig {
enabled: recovery_enabled,
..RecoveryConfig::default()
};
// Default to a CWD-scoped recovery directory so each working
// directory keeps its own hot-exit recovery files. If this
// editor is later promoted to session mode, `set_session_name`
// re-creates the service with `RecoveryScope::Session`.
// Issue #1550: without per-CWD scoping, opening Fresh in a
// second folder would clobber the first folder's unsaved
// unnamed buffers on shutdown.
let scope = crate::services::recovery::RecoveryScope::Standalone {
working_dir: working_dir.clone(),
};
RecoveryService::with_scope(recovery_config, &dir_context.recovery_dir(), &scope)
},
full_redraw_requested: false,
suspend_requested: false,
time_source: time_source.clone(),
last_auto_recovery_save: time_source.now(),
last_persistent_auto_save: time_source.now(),
active_custom_contexts: HashSet::new(),
plugin_global_state: HashMap::new(),
editor_mode: None,
warning_log: None,
status_log_path: None,
warning_domains: WarningDomainRegistry::new(),
update_checker,
terminal_manager: crate::services::terminal::TerminalManager::new(),
terminal_buffers: HashMap::new(),
terminal_backing_files: HashMap::new(),
terminal_log_files: HashMap::new(),
ephemeral_terminals: std::collections::HashSet::new(),
terminal_mode: false,
keyboard_capture: false,
terminal_mode_resume: std::collections::HashSet::new(),
previous_click_time: None,
previous_click_position: None,
click_count: 0,
settings_state: None,
calibration_wizard: None,
event_debug: None,
keybinding_editor: None,
key_translator: crate::input::key_translator::KeyTranslator::load_from_config_dir(
&dir_context.config_dir,
)
.unwrap_or_default(),
color_capability,
pending_file_opens: Vec::new(),
pending_hot_exit_recovery: false,
wait_tracking: HashMap::new(),
completed_waits: Vec::new(),
stdin_stream: stdin_stream::StdinStream::default(),
line_scan: line_scan::LineScan::default(),
search_scan: search_scan::SearchScan::default(),
search_overlay_top_byte: None,
review_hunks: Vec::new(),
global_popups: crate::view::popup::PopupManager::new(),
composite_buffers: HashMap::new(),
composite_view_states: HashMap::new(),
animations: crate::view::animation::AnimationRunner::new(),
previous_cursor_screen_pos: None,
cursor_jump_animation: None,
pending_vb_animations: Vec::new(),
};
t.phase("editor_struct_assembly");
// Apply clipboard configuration
editor.clipboard.apply_config(&editor.config.clipboard);
#[cfg(feature = "plugins")]
{
editor.update_plugin_state_snapshot();
if editor.plugin_manager.is_active() {
editor.plugin_manager.run_hook(
"editor_initialized",
crate::services::plugins::hooks::HookArgs::EditorInitialized {},
);
}
}
t.phase("post_struct_hooks");
t.finish();
Ok(editor)
}
/// Get a reference to the event broadcaster
pub fn event_broadcaster(&self) -> &crate::model::control_event::EventBroadcaster {
&self.event_broadcaster
}
/// Spawn a background thread to build the full grammar registry
/// (embedded grammars, user grammars, language packs, and any plugin-registered grammars).
/// Called on the first event-loop tick (via `flush_pending_grammars`) so that
/// plugin grammars registered during init are included in a single build.
pub(super) fn start_background_grammar_build(
&mut self,
additional: Vec<crate::primitives::grammar::GrammarSpec>,
callback_ids: Vec<fresh_core::api::JsCallbackId>,
) {
let Some(bridge) = &self.async_bridge else {
return;
};
self.grammar_build_in_progress = true;
let sender = bridge.sender();
let config_dir = self.dir_context.config_dir.clone();
tracing::info!(
"Spawning background grammar build thread ({} plugin grammars)...",
additional.len()
);
std::thread::Builder::new()
.name("grammar-build".to_string())
.spawn(move || {
tracing::info!("[grammar-build] Thread started");
let start = std::time::Instant::now();
let registry = if additional.is_empty() {
crate::primitives::grammar::GrammarRegistry::for_editor(config_dir)
} else {
crate::primitives::grammar::GrammarRegistry::for_editor_with_additional(
config_dir,
&additional,
)
};
tracing::info!("[grammar-build] Complete in {:?}", start.elapsed());
drop(sender.send(
crate::services::async_bridge::AsyncMessage::GrammarRegistryBuilt {
registry,
callback_ids,
},
));
})
.ok();
}
// =========================================================================
// init.ts / runtime-overlay surface (design docs §3–§6)
// =========================================================================
/// Auto-load `~/.config/fresh/init.ts` if present, through the existing
/// plugin pipeline under the stable name `crate::init_script::INIT_PLUGIN_NAME`.
pub fn load_init_script(&mut self, enabled: bool) {
use crate::init_script::{
check, decide_load, describe, record_success, refresh_types_scaffolding, CheckSeverity,
InitOutcome, LoadDecision,
};
let config_dir = self.dir_context.config_dir.clone();
if enabled {
// Refresh the types mirror from the embedded copy before anything
// reads init.ts. Guarantees the declarations the user sees match
// the running build — stale types would hide API drift.
refresh_types_scaffolding(&config_dir);
// Re-check init.ts right after the refresh so drift between the
// user's script and the current API surface (at least syntax-level
// fallout like unterminated blocks from a botched rename) shows up
// in the log immediately rather than only at eval time.
let report = check(&config_dir);
if !report.ok {
for d in &report.diagnostics {
let level = match d.severity {
CheckSeverity::Error => "error",
CheckSeverity::Warning => "warning",
};
tracing::warn!(
"init.ts pre-load {level} at {}:{}: {}",
d.line,
d.column,
d.message
);
}
}
}
let outcome = match decide_load(&config_dir, enabled) {
LoadDecision::Skip(outcome) => outcome,
LoadDecision::Load { source } => {
if !self.plugin_manager.is_active() {
InitOutcome::Failed {
message: "plugin runtime inactive (--no-plugins); init.ts cannot run"
.into(),
}
} else {
match self.plugin_manager.load_plugin_from_source(
&source,
crate::init_script::INIT_PLUGIN_NAME,
true,
) {
Ok(()) => {
record_success(&config_dir);
InitOutcome::Loaded
}
Err(e) => InitOutcome::Failed {
message: format!("{e}"),
},
}
}
}
};
let summary = describe(&outcome);
match outcome {
InitOutcome::NotFound | InitOutcome::Disabled => tracing::debug!("{}", summary),
InitOutcome::Loaded => tracing::info!("{}", summary),
InitOutcome::CrashFused { .. } | InitOutcome::Failed { .. } => {
tracing::warn!("{}", summary);
self.set_status_message(summary);
}
}
}
/// Non-blocking variant of [`Self::load_init_script`] for the TUI
/// startup path. Does the synchronous pre-work (types scaffolding
/// refresh, syntax check, fuse check), then either submits the
/// `LoadPluginFromSource` request to the plugin thread and spawns a
/// forwarder that translates the result into
/// `AsyncMessage::PluginInitScriptLoaded`, or — for the `Skip(...)`
/// outcomes — emits the message directly so the same async-dispatch
/// handler logs and applies status. The request goes through the
/// same FIFO channel as the startup plugin loads, so by the time the
/// plugin thread evaluates init.ts every batch plugin has already
/// finished — preserving the original load ordering.
pub fn load_init_script_async(&mut self, enabled: bool) {
use crate::init_script::{
check, decide_load, refresh_types_scaffolding, CheckSeverity, InitOutcome, LoadDecision,
};
use crate::services::async_bridge::PluginInitScriptOutcome;
let config_dir = self.dir_context.config_dir.clone();
if enabled {
refresh_types_scaffolding(&config_dir);
let report = check(&config_dir);
if !report.ok {
for d in &report.diagnostics {
let level = match d.severity {
CheckSeverity::Error => "error",
CheckSeverity::Warning => "warning",
};
tracing::warn!(
"init.ts pre-load {level} at {}:{}: {}",
d.line,
d.column,
d.message
);
}
}
}
let outcome_now: Option<PluginInitScriptOutcome> = match decide_load(&config_dir, enabled) {
LoadDecision::Skip(outcome) => Some(match outcome {
InitOutcome::NotFound => PluginInitScriptOutcome::NotFound,
InitOutcome::Disabled => PluginInitScriptOutcome::Disabled,
InitOutcome::CrashFused { failures } => {
PluginInitScriptOutcome::CrashFused { failures }
}
// decide_load only returns these via Load; keep total to
// satisfy the matcher.
InitOutcome::Loaded => PluginInitScriptOutcome::Loaded,
InitOutcome::Failed { message } => PluginInitScriptOutcome::Failed { message },
}),
LoadDecision::Load { source } => {
if !self.plugin_manager.is_active() {
Some(PluginInitScriptOutcome::Failed {
message: "plugin runtime inactive (--no-plugins); init.ts cannot run"
.into(),
})
} else {
self.spawn_init_script_forwarder(source);
None
}
}
};
if let Some(outcome) = outcome_now {
// Skip / fused / inactive paths: emit through the bridge so
// the same handler runs them as the success path. Falls back
// to direct application if the bridge is missing (test).
if let Some(bridge) = &self.async_bridge {
drop(bridge.sender().send(
crate::services::async_bridge::AsyncMessage::PluginInitScriptLoaded(outcome),
));
} else {
self.handle_plugin_init_script_loaded(outcome);
}
}
}
#[cfg(feature = "plugins")]
fn spawn_init_script_forwarder(&self, source: String) {
let Some(bridge) = &self.async_bridge else {
return;
};
let Some(rx) = self.plugin_manager.load_plugin_from_source_request(
&source,
crate::init_script::INIT_PLUGIN_NAME,
true,
) else {
return;
};
let sender = bridge.sender();
std::thread::Builder::new()
.name("plugin-init-forwarder".to_string())
.spawn(move || {
let outcome = match rx.recv() {
Ok(Ok(())) => crate::services::async_bridge::PluginInitScriptOutcome::Loaded,
Ok(Err(e)) => crate::services::async_bridge::PluginInitScriptOutcome::Failed {
message: format!("{e}"),
},
Err(e) => crate::services::async_bridge::PluginInitScriptOutcome::Failed {
message: format!("plugin thread closed: {e}"),
},
};
drop(sender.send(
crate::services::async_bridge::AsyncMessage::PluginInitScriptLoaded(outcome),
));
})
.ok();
}
#[cfg(not(feature = "plugins"))]
fn spawn_init_script_forwarder(&self, _source: String) {}
/// Handle `setSetting(path, value)`. Fire-and-forget: patches Config
/// directly via JSON round-trip. No overlay, no per-plugin tracking,
/// no revert on unload — same model as Neovim/VS Code/Emacs/Sublime.
pub fn handle_set_setting(&mut self, path: String, value: serde_json::Value) {
let mut json = serde_json::to_value(&*self.config).unwrap_or_default();
set_dot_path(&mut json, &path, value);
match serde_json::from_value::<crate::config::Config>(json) {
Ok(new_config) => {
let old_theme = self.config.theme.clone();
self.config = Arc::new(new_config);
if old_theme != self.config.theme {
if let Some(theme) = self.theme_registry.get_cloned(&self.config.theme) {
self.theme = theme;
}
}
*self.keybindings.write().unwrap() =
crate::input::keybindings::KeybindingResolver::new(&self.config);
self.clipboard.apply_config(&self.config.clipboard);
self.menu_bar_visible = self.config.editor.show_menu_bar;
self.tab_bar_visible = self.config.editor.show_tab_bar;
self.status_bar_visible = self.config.editor.show_status_bar;
self.prompt_line_visible = self.config.editor.show_prompt_line;
#[cfg(feature = "plugins")]
self.update_plugin_state_snapshot();
}
Err(e) => {
self.set_status_message(format!("setSetting({path}): {e}"));
}
}
}
/// Apply the result of one async startup-batch directory load.
/// Mirrors the per-iteration body of the legacy synchronous loop in
/// `with_options`: merge discovered plugins into config, log errors,
/// and panic in debug builds (the legacy behaviour).
pub(crate) fn handle_plugins_dir_loaded(
&mut self,
dir: std::path::PathBuf,
errors: Vec<String>,
discovered_plugins: std::collections::HashMap<String, fresh_core::config::PluginConfig>,
) {
if !discovered_plugins.is_empty() {
let cfg = std::sync::Arc::make_mut(&mut self.config);
for (name, plugin_config) in discovered_plugins {
cfg.plugins.insert(name, plugin_config);
}
}
if !errors.is_empty() {
for err in &errors {
tracing::error!("TypeScript plugin load error: {}", err);
}
#[cfg(debug_assertions)]
panic!(
"TypeScript plugin loading failed for {:?} with {} error(s): {}",
dir,
errors.len(),
errors.join("; ")
);
#[cfg(not(debug_assertions))]
{
let _ = dir;
}
}
}
/// Apply the declarations harvested at the end of the async startup
/// batch. Mirrors the synchronous `plugin_declarations` +
/// `write_plugin_declarations` pair in `with_options`.
pub(crate) fn handle_plugin_declarations_ready(&self, declarations: Vec<(String, String)>) {
crate::init_script::write_plugin_declarations(&self.dir_context.config_dir, &declarations);
}
/// Apply the result of the async `init.ts` load. Mirrors the trailing
/// `match outcome { ... }` block of the legacy synchronous
/// `load_init_script`.
pub(crate) fn handle_plugin_init_script_loaded(
&mut self,
outcome: crate::services::async_bridge::PluginInitScriptOutcome,
) {
use crate::init_script::{describe, record_success, InitOutcome};
use crate::services::async_bridge::PluginInitScriptOutcome as O;
let outcome = match outcome {
O::NotFound => InitOutcome::NotFound,
O::Disabled => InitOutcome::Disabled,
O::CrashFused { failures } => InitOutcome::CrashFused { failures },
O::Loaded => {
record_success(&self.dir_context.config_dir);
InitOutcome::Loaded
}
O::Failed { message } => InitOutcome::Failed { message },
};
let summary = describe(&outcome);
match outcome {
InitOutcome::NotFound | InitOutcome::Disabled => tracing::debug!("{}", summary),
InitOutcome::Loaded => tracing::info!("{}", summary),
InitOutcome::CrashFused { .. } | InitOutcome::Failed { .. } => {
tracing::warn!("{}", summary);
self.set_status_message(summary);
}
}
}
/// Fire the `plugins_loaded` hook (design M2, §3.3 phase 2).
pub fn fire_plugins_loaded_hook(&self) {
#[cfg(feature = "plugins")]
if self.plugin_manager.is_active() {
self.plugin_manager.run_hook(
"plugins_loaded",
crate::services::plugins::hooks::HookArgs::PluginsLoaded {},
);
}
}
/// Fire the `ready` hook (design M2, §3.3 phase 3).
pub fn fire_ready_hook(&self) {
#[cfg(feature = "plugins")]
if self.plugin_manager.is_active() {
self.plugin_manager
.run_hook("ready", crate::services::plugins::hooks::HookArgs::Ready {});
}
}
/// Test-only accessor for the current effective config.
#[doc(hidden)]
pub fn config_for_tests(&self) -> &crate::config::Config {
&self.config
}
/// Test-only shim that dispatches an action through the normal path.
#[doc(hidden)]
pub fn dispatch_action_for_tests(&mut self, action: crate::input::keybindings::Action) {
if let Err(e) = self.handle_action(action) {
tracing::warn!("dispatch_action_for_tests: {e}");
}
}
/// Test-only accessor for the Live Grep Resume cache (issue #1796).
#[doc(hidden)]
pub fn live_grep_last_state_for_tests(
&self,
) -> Option<&crate::services::live_grep_state::LiveGrepLastState> {
self.live_grep_last_state.as_ref()
}
/// Test-only setter for the Live Grep Resume cache.
#[doc(hidden)]
pub fn set_live_grep_last_state_for_tests(
&mut self,
state: Option<crate::services::live_grep_state::LiveGrepLastState>,
) {
self.live_grep_last_state = state;
}
/// Test-only accessor for the split tree, so layout-shape
/// regression tests can assert on the structure directly.
#[doc(hidden)]
pub fn split_manager_for_tests(&self) -> &crate::view::split::SplitManager {
&self.split_manager
}
/// Test-only accessor for a leaf's `SplitViewState`, so tab-list
/// regression tests can verify which buffers are open in a given
/// pane (the dock should only contain the buffer the user
/// actually asked for, not phantom placeholders).
#[doc(hidden)]
pub fn split_view_state_for_tests(
&self,
leaf: crate::model::event::LeafId,
) -> Option<&crate::view::split::SplitViewState> {
self.split_view_states.get(&leaf)
}
/// Refresh the plugin-readable keybinding-label snapshot from
/// the current keymap. Call this whenever a plugin is about to
/// surface key hints in its UI (overlay headers, tooltips,
/// menus) so the user's most-recent rebinds are reflected.
///
/// Cheap — walks every typed `Action` × ~9 contexts; runs in
/// well under a millisecond on this hardware. Cheaper than
/// adding refresh hooks to every keymap-mutation site.
#[cfg(feature = "plugins")]
pub(crate) fn refresh_keybinding_labels_snapshot(&self) {
if let Some(snapshot_handle) = self.plugin_manager.state_snapshot_handle() {
if let Ok(mut snapshot) = snapshot_handle.write() {
populate_builtin_keybinding_labels(&mut snapshot, &self.keybindings);
}
}
}
}
/// Walk every typed `Action` and the contexts most relevant to UI
/// labels (`Normal`, `Prompt`, `Popup`, `FileExplorer`,
/// `CompositeBuffer`, `Settings`, `Terminal`), and populate the
/// snapshot's `keybinding_labels` map with `<action>\0<context>` →
/// formatted label (e.g. `"cycle_live_grep_provider\0prompt"` →
/// `"Alt+P"`). The plugin-side `editor.getKeybindingLabel(action,
/// mode)` API reads from this map, so plugins displaying hints in
/// their UIs (overlay headers, status messages) can look up the
/// user's *actual* binding rather than hardcoding a key string.
///
/// This runs once at startup. If the user later edits their keymap
/// without restarting fresh, the labels go stale. That's acceptable
/// for v1 — keymap edits today already require a restart for full
/// effect; a subsequent commit can wire snapshot refresh into the
/// keymap-reload path.
#[cfg(feature = "plugins")]
fn populate_builtin_keybinding_labels(
snapshot: &mut crate::services::plugins::api::EditorStateSnapshot,
keybindings: &std::sync::Arc<std::sync::RwLock<crate::input::keybindings::KeybindingResolver>>,
) {
use crate::input::keybindings::{Action, KeyContext};
let Ok(resolver) = keybindings.read() else {
return;
};
let contexts = [
KeyContext::Normal,
KeyContext::Prompt,
KeyContext::Popup,
KeyContext::Completion,
KeyContext::FileExplorer,
KeyContext::Menu,
KeyContext::Terminal,
KeyContext::Settings,
KeyContext::CompositeBuffer,
];
// Clear stale built-in entries first so a re-populate after
// the user un-binds an action drops the label rather than
// leaving the old key visible. Entries whose `\0<context>`
// suffix isn't in our list are left alone — those belong to
// plugin-defined buffer modes and have their own
// re-population path in `handle_register_mode`.
let known_suffixes: Vec<String> = contexts
.iter()
.map(|c| format!("\0{}", c.to_when_clause()))
.collect();
snapshot
.keybinding_labels
.retain(|k, _| !known_suffixes.iter().any(|s| k.ends_with(s)));
for action_name in Action::all_action_names() {
for ctx in &contexts {
if let Some(label) = resolver.find_keybinding_for_action(&action_name, ctx.clone()) {
let key = format!("{}\0{}", action_name, ctx.to_when_clause());
snapshot.keybinding_labels.insert(key, label);
}
}
}
}