fresh/app/editor_init.rs
1//! Editor construction and initialization.
2//!
3//! `Editor::new` and friends — the entry points that take a configuration,
4//! terminal dimensions, color capability, and filesystem implementation
5//! and return a ready-to-use Editor with every field initialized.
6//!
7//! Also includes `start_background_grammar_build`, which kicks off the
8//! initial grammar registry build asynchronously so startup doesn't block.
9
10// Re-use everything mod.rs imports — the constructors touch every field
11// on Editor and most of the types in the module.
12use super::*;
13
14/// Phase-timing helper used when `FRESH_TEST_TIMING=1` is set so test
15/// authors can see where `Editor::with_options` spends its wall clock.
16/// No-op when the env var is unset; printed to stderr otherwise.
17struct InitTimer {
18 label: &'static str,
19 start: std::time::Instant,
20 last: std::time::Instant,
21 enabled: bool,
22}
23
24impl InitTimer {
25 fn start(label: &'static str) -> Self {
26 let enabled = std::env::var("FRESH_TEST_TIMING").is_ok_and(|v| !v.is_empty() && v != "0");
27 let now = std::time::Instant::now();
28 if enabled {
29 eprintln!("[timing] {label} start");
30 }
31 Self {
32 label,
33 start: now,
34 last: now,
35 enabled,
36 }
37 }
38 fn phase(&mut self, name: &str) {
39 if !self.enabled {
40 return;
41 }
42 let now = std::time::Instant::now();
43 let delta = now.duration_since(self.last);
44 let cumul = now.duration_since(self.start);
45 eprintln!(
46 "[timing] {name:<30} +{delta:>8.1}ms (cumul {cumul:.1}ms)",
47 name = name,
48 delta = delta.as_secs_f64() * 1000.0,
49 cumul = cumul.as_secs_f64() * 1000.0,
50 );
51 self.last = now;
52 }
53 fn finish(self) {
54 if !self.enabled {
55 return;
56 }
57 eprintln!(
58 "[timing] {label} total {total:.1}ms",
59 label = self.label,
60 total = self.start.elapsed().as_secs_f64() * 1000.0,
61 );
62 }
63}
64
65/// Set a value at a dot-separated path inside a JSON object, creating
66/// intermediate maps as needed.
67fn set_dot_path(root: &mut serde_json::Value, path: &str, value: serde_json::Value) {
68 let segments: Vec<&str> = path.split('.').filter(|s| !s.is_empty()).collect();
69 if segments.is_empty() {
70 return;
71 }
72 let mut cur = root;
73 for seg in &segments[..segments.len() - 1] {
74 if !cur.is_object() {
75 *cur = serde_json::Value::Object(serde_json::Map::new());
76 }
77 cur = cur
78 .as_object_mut()
79 .unwrap()
80 .entry((*seg).to_string())
81 .or_insert(serde_json::Value::Null);
82 }
83 let last = segments[segments.len() - 1];
84 if !cur.is_object() {
85 *cur = serde_json::Value::Object(serde_json::Map::new());
86 }
87 cur.as_object_mut().unwrap().insert(last.to_string(), value);
88}
89
90/// Pre-built non-trivial inputs handed to [`Editor::from_parts`].
91///
92/// Everything in here either depends on external resources (filesystem,
93/// config, plugins, themes, terminal dimensions, …) or is one of the
94/// few editor-global fields a caller wants to control directly — most
95/// notably the initial set of `windows`. Trivial fields (counters at
96/// zero, empty collections, `None` options, registries built from
97/// scratch with no dependencies) are filled in by the constructor.
98///
99/// The factory methods (`Editor::new`, `Editor::with_working_dir`,
100/// `Editor::with_working_dir_opts`, `Editor::for_test`,
101/// `Editor::with_options`) build a value of this type and pass it to
102/// `Editor::from_parts`. No production code constructs `Editor`
103/// without going through `from_parts`, so adding a field here forces
104/// every factory to provide it.
105pub(super) struct EditorParts {
106 // Config / paths
107 pub(super) config: Arc<Config>,
108 pub(super) config_snapshot_anchor: Arc<Config>,
109 pub(super) config_cached_json: Arc<serde_json::Value>,
110 pub(super) user_config_raw: Arc<serde_json::Value>,
111 pub(super) dir_context: DirectoryContext,
112
113 // Themes
114 pub(super) theme: Arc<RwLock<crate::view::theme::Theme>>,
115 pub(super) theme_registry: Arc<crate::view::theme::ThemeRegistry>,
116 pub(super) theme_cache: Arc<RwLock<HashMap<String, serde_json::Value>>>,
117
118 // Grammar
119 pub(super) grammar_registry: Arc<crate::primitives::grammar::GrammarRegistry>,
120 pub(super) pending_grammars: Vec<PendingGrammar>,
121 pub(super) needs_full_grammar_build: bool,
122
123 // Keybindings + buffer-id allocation
124 pub(super) keybindings: Arc<RwLock<KeybindingResolver>>,
125 pub(super) buffer_id_alloc: crate::app::window_resources::BufferIdAllocator,
126 pub(super) next_buffer_id: usize,
127
128 // Terminal
129 pub(super) terminal_width: u16,
130 pub(super) terminal_height: u16,
131 pub(super) color_capability: crate::view::color_support::ColorCapability,
132
133 // Async / IO
134 pub(super) tokio_runtime: Option<Arc<tokio::runtime::Runtime>>,
135 pub(super) async_bridge: AsyncBridge,
136 pub(super) authority: crate::services::authority::Authority,
137 pub(super) local_filesystem: Arc<dyn FileSystem + Send + Sync>,
138
139 // Chrome flags resolved from config
140
141 // Windows — the whole point of the split: the factory builds these
142 // (from disk persistence or a single seed window), the constructor
143 // just installs them.
144 pub(super) windows: HashMap<fresh_core::WindowId, crate::app::window::Window>,
145 pub(super) active_window: fresh_core::WindowId,
146 pub(super) next_window_id: u64,
147
148 // Registries / managers
149 pub(super) command_registry: Arc<RwLock<CommandRegistry>>,
150 pub(super) quick_open_registry: QuickOpenRegistry,
151 pub(super) plugin_manager: Arc<RwLock<PluginManager>>,
152 pub(super) recovery_service: Arc<std::sync::Mutex<RecoveryService>>,
153 pub(super) key_translator: crate::input::key_translator::KeyTranslator,
154 pub(super) update_checker: Option<crate::services::release_checker::PeriodicUpdateChecker>,
155
156 // Time
157 pub(super) time_source: SharedTimeSource,
158
159 // Persisted plugin global state (one map per plugin). Pulled from
160 // `<data_dir>/orchestrator/state/<plugin>.json` by the
161 // factory so plugins reading `getGlobalState(...)` on first tick
162 // see the previous run's values without a separate
163 // post-construction load step.
164 pub(super) plugin_global_state: HashMap<String, HashMap<String, serde_json::Value>>,
165
166 /// Per-plugin config schemas discovered from `<plugin>.schema.json` sidecars.
167 pub(super) plugin_schemas: HashMap<String, serde_json::Value>,
168
169 /// Editor-wide event broadcaster, shared with every WindowResources.
170 pub(super) event_broadcaster: crate::model::control_event::EventBroadcaster,
171}
172
173impl Editor {
174 /// Lightweight constructor. Takes the non-trivial editor-global
175 /// resources via [`EditorParts`] and fills in every other field
176 /// with its empty/default value. No I/O, no plugin loading, no
177 /// disk reads happen here — that's all the factory's job
178 /// ([`Editor::with_options`] and friends), so this method can
179 /// also serve as a building block for narrowly-scoped tests that
180 /// want to assemble an `Editor` from hand-built parts.
181 ///
182 /// Fields that need a `time_source` for their initial value
183 /// (auto-revert timestamps, etc.) read it out of `parts` rather
184 /// than capturing a new clock — so two editors built from the
185 /// same parts agree on "now".
186 pub(super) fn from_parts(parts: EditorParts) -> Self {
187 Editor {
188 // From parts (non-trivial):
189 next_buffer_id: parts.next_buffer_id,
190 buffer_id_alloc: parts.buffer_id_alloc,
191 config: parts.config,
192 config_snapshot_anchor: parts.config_snapshot_anchor,
193 config_cached_json: parts.config_cached_json,
194 user_config_raw: parts.user_config_raw,
195 dir_context: parts.dir_context.clone(),
196 grammar_registry: parts.grammar_registry,
197 pending_grammars: parts.pending_grammars,
198 needs_full_grammar_build: parts.needs_full_grammar_build,
199 theme: parts.theme,
200 theme_registry: parts.theme_registry,
201 theme_cache: parts.theme_cache,
202 keybindings: parts.keybindings,
203 terminal_width: parts.terminal_width,
204 terminal_height: parts.terminal_height,
205 last_layout_signature: None,
206 tokio_runtime: parts.tokio_runtime,
207 async_bridge: Some(parts.async_bridge),
208 paste_pending: std::collections::HashMap::new(),
209 paste_slow_path_just_armed: false,
210 paste_render_suppress_until: None,
211 authority: parts.authority,
212 local_filesystem: parts.local_filesystem,
213 menu_state: crate::view::ui::MenuState::new(parts.dir_context.themes_dir()),
214 windows: parts.windows,
215 session_keepalives: HashMap::new(),
216 remote_attach_inflight: std::collections::HashSet::new(),
217 remote_attach_cancelled: std::collections::HashSet::new(),
218 remote_attach_cancels: std::collections::HashMap::new(),
219 active_window: parts.active_window,
220 next_window_id: parts.next_window_id,
221 command_registry: parts.command_registry,
222 quick_open_registry: parts.quick_open_registry,
223 plugin_manager: parts.plugin_manager,
224 recovery_service: parts.recovery_service,
225 time_source: parts.time_source,
226 color_capability: parts.color_capability,
227 update_checker: parts.update_checker,
228 key_translator: parts.key_translator,
229
230 // Trivial defaults (no external dependencies):
231 materialize_pending: std::collections::HashSet::new(),
232 grammar_reload_pending: false,
233 grammar_build_in_progress: false,
234 pending_grammar_callbacks: Vec::new(),
235 expanded_menus_cache: crate::view::ui::ExpandedMenusCache::default(),
236 ansi_background: None,
237 ansi_background_path: None,
238 background_fade: crate::primitives::ansi_background::DEFAULT_BACKGROUND_FADE,
239 clipboard: crate::services::clipboard::Clipboard::new(),
240 should_quit: false,
241 workspace_trust_prompt_cancellable: false,
242 workspace_trust_markers: Vec::new(),
243 workspace_trust_scroll: 0,
244 should_detach: false,
245 session_mode: false,
246 software_cursor_only: false,
247 session_name: None,
248 pending_escape_sequences: Vec::new(),
249 restart_with_dir: None,
250 last_window_title: None,
251 mode_registry: ModeRegistry::new(),
252 pending_authority: None,
253 pending_keepalive: None,
254 remote_indicator_override: None,
255 menus: crate::config::MenuConfig::translated(),
256 background_process_handles: HashMap::new(),
257 host_process_handles: HashMap::new(),
258 status_bar_token_registry: Mutex::new(HashMap::new()),
259 plugin_schemas: std::sync::Arc::new(std::sync::RwLock::new(parts.plugin_schemas)),
260 event_broadcaster: parts.event_broadcaster,
261 #[cfg(feature = "plugins")]
262 pending_plugin_actions: Vec::new(),
263 #[cfg(feature = "plugins")]
264 plugin_render_requested: false,
265 full_redraw_requested: false,
266 suspend_requested: false,
267 plugin_global_state: parts.plugin_global_state,
268 warning_log: None,
269 status_log_path: None,
270 #[cfg(feature = "plugins")]
271 file_watcher_manager: crate::services::file_watcher::FileWatcherManager::new(),
272 last_path_change_for_test: None,
273 last_watch_response_for_test: None,
274 preview_window_id: None,
275 settings_state: None,
276 calibration_wizard: None,
277 // event_debug moved to Window
278 keybinding_editor: None,
279 stdin_stream: stdin_stream::StdinStream::default(),
280 global_popups: crate::view::popup::PopupManager::new(),
281 previous_cursor_screen_pos: None,
282 cursor_jump_animation: None,
283 pending_vb_animations: Vec::new(),
284 widget_registry: crate::widgets::WidgetRegistry::new(),
285 floating_widget_panel: None,
286 dock: None,
287 dock_width: None,
288 dock_resizing: false,
289 }
290 }
291
292 /// Create a new editor with the given configuration and terminal dimensions
293 /// Uses system directories for state (recovery, sessions, etc.)
294 pub fn new(
295 config: Config,
296 width: u16,
297 height: u16,
298 dir_context: DirectoryContext,
299 color_capability: crate::view::color_support::ColorCapability,
300 filesystem: Arc<dyn FileSystem + Send + Sync>,
301 ) -> AnyhowResult<Self> {
302 Self::with_working_dir(
303 config,
304 width,
305 height,
306 None,
307 dir_context,
308 true,
309 color_capability,
310 filesystem,
311 )
312 }
313
314 /// Create a new editor with an explicit working directory
315 /// This is useful for testing with isolated temporary directories
316 #[allow(clippy::too_many_arguments)]
317 pub fn with_working_dir(
318 config: Config,
319 width: u16,
320 height: u16,
321 working_dir: Option<PathBuf>,
322 dir_context: DirectoryContext,
323 plugins_enabled: bool,
324 color_capability: crate::view::color_support::ColorCapability,
325 filesystem: Arc<dyn FileSystem + Send + Sync>,
326 ) -> AnyhowResult<Self> {
327 // Convenience constructor (tests, and any caller that only has a
328 // filesystem to inject): the editor's real authority *is* a local one
329 // backed by that filesystem. Build it here so the editor is still
330 // constructed with the authority it runs under — production callers
331 // that own a non-local authority pass it straight to
332 // `with_working_dir_opts` instead.
333 let authority = Self::local_authority_with_filesystem(filesystem);
334 Self::with_working_dir_opts(
335 config,
336 width,
337 height,
338 working_dir,
339 dir_context,
340 plugins_enabled,
341 color_capability,
342 authority,
343 false,
344 )
345 }
346
347 /// Like [`Self::with_working_dir`] but with `defer_plugin_load`
348 /// exposed. When `true`, plugin loading is dispatched to the plugin
349 /// thread and the constructor returns immediately; results arrive
350 /// later via `AsyncMessage::PluginsDirLoaded` /
351 /// `PluginDeclarationsReady` and are applied in `process_async_messages`.
352 /// Used by the TUI startup path so the first frame draws without
353 /// waiting on TS parse/transpile/register.
354 #[allow(clippy::too_many_arguments)]
355 pub fn with_working_dir_opts(
356 config: Config,
357 width: u16,
358 height: u16,
359 working_dir: Option<PathBuf>,
360 dir_context: DirectoryContext,
361 plugins_enabled: bool,
362 color_capability: crate::view::color_support::ColorCapability,
363 authority: crate::services::authority::Authority,
364 defer_plugin_load: bool,
365 ) -> AnyhowResult<Self> {
366 tracing::info!("Building default grammar registry...");
367 let start = std::time::Instant::now();
368 let mut grammar_registry = crate::primitives::grammar::GrammarRegistry::defaults_only();
369 // Merge user config so find_by_path respects user globs/filenames
370 // from the very first lookup. `defaults_only` just built the Arc, so
371 // we're the sole owner; get_mut is guaranteed to succeed. Assert
372 // rather than silently drop config — a failure here would leave the
373 // user wondering why their `*.conf → bash` rule doesn't highlight.
374 std::sync::Arc::get_mut(&mut grammar_registry)
375 .expect("defaults_only returned a shared Arc")
376 .apply_language_config(&config.languages);
377 tracing::info!("Default grammar registry built in {:?}", start.elapsed());
378 // Don't start background grammar build here — it's deferred to the
379 // first flush_pending_grammars() call so that plugin-registered grammars
380 // from the first event-loop tick are included in a single build.
381 Self::with_options(
382 config,
383 width,
384 height,
385 working_dir,
386 authority,
387 plugins_enabled,
388 true, // enable_embedded_plugins (production: always allow embedded fallback)
389 dir_context,
390 None,
391 color_capability,
392 grammar_registry,
393 defer_plugin_load,
394 )
395 }
396
397 /// Create a new editor for testing with custom backends
398 ///
399 /// By default uses empty grammar registry for fast initialization.
400 /// Pass `Some(registry)` for tests that need syntax highlighting or shebang detection.
401 ///
402 /// `enable_plugins` controls whether the plugin runtime is active at all.
403 /// `enable_embedded_plugins` separately gates the cargo-binstall embedded
404 /// plugins fallback — tests that pre-populate `<config_dir>/plugins/` and
405 /// want exact control over which plugins load can pass `false` here while
406 /// keeping `enable_plugins = true`.
407 #[allow(clippy::too_many_arguments)]
408 pub fn for_test(
409 config: Config,
410 width: u16,
411 height: u16,
412 working_dir: Option<PathBuf>,
413 dir_context: DirectoryContext,
414 color_capability: crate::view::color_support::ColorCapability,
415 filesystem: Arc<dyn FileSystem + Send + Sync>,
416 time_source: Option<SharedTimeSource>,
417 grammar_registry: Option<Arc<crate::primitives::grammar::GrammarRegistry>>,
418 enable_plugins: bool,
419 enable_embedded_plugins: bool,
420 ) -> AnyhowResult<Self> {
421 let mut grammar_registry =
422 grammar_registry.unwrap_or_else(crate::primitives::grammar::GrammarRegistry::empty);
423 // Merge user `[languages]` config into the catalog — production code
424 // does this at startup and again after the background grammar build,
425 // tests need the same so config-declared grammars/extensions resolve
426 // through `find_by_path`. Both call sites that feed into `for_test`
427 // (`HarnessOptions::with_full_grammar_registry` and the default
428 // `GrammarRegistry::empty()`) hand us the sole Arc owner.
429 std::sync::Arc::get_mut(&mut grammar_registry)
430 .expect("grammar registry Arc must be uniquely owned at for_test entry")
431 .apply_language_config(&config.languages);
432 let authority = Self::local_authority_with_filesystem(filesystem);
433 let mut editor = Self::with_options(
434 config,
435 width,
436 height,
437 working_dir,
438 authority,
439 enable_plugins,
440 enable_embedded_plugins,
441 dir_context,
442 time_source,
443 color_capability,
444 grammar_registry,
445 false,
446 )?;
447 // Tests typically have no async_bridge, so the deferred grammar build
448 // would just drain pending_grammars and early-return. Skip it entirely.
449 editor.needs_full_grammar_build = false;
450 Ok(editor)
451 }
452
453 /// Build a local authority whose filesystem is the supplied one.
454 ///
455 /// The bridge for callers that only have a `FileSystem` to inject (the
456 /// `new` / `with_working_dir` / `for_test` convenience constructors): a
457 /// local-backed authority *is* the real authority such an editor runs
458 /// under, so this is construction with the true authority, not a
459 /// placeholder destined to be replaced. Carries a permissive trust and an
460 /// inactive env provider — the defaults `Authority::local` uses for the
461 /// host backend.
462 fn local_authority_with_filesystem(
463 filesystem: Arc<dyn FileSystem + Send + Sync>,
464 ) -> crate::services::authority::Authority {
465 crate::services::authority::Authority {
466 filesystem,
467 ..crate::services::authority::Authority::local(
468 Arc::new(crate::services::workspace_trust::WorkspaceTrust::permissive()),
469 Arc::new(crate::services::env_provider::EnvProvider::inactive()),
470 )
471 }
472 }
473
474 /// Create a new editor with custom options
475 /// This is primarily used for testing with slow or mock backends
476 /// to verify editor behavior under various I/O conditions
477 #[allow(clippy::too_many_arguments)]
478 fn with_options(
479 mut config: Config,
480 width: u16,
481 height: u16,
482 working_dir: Option<PathBuf>,
483 authority: crate::services::authority::Authority,
484 enable_plugins: bool,
485 #[cfg_attr(not(feature = "embed-plugins"), allow(unused_variables))]
486 enable_embedded_plugins: bool,
487 dir_context: DirectoryContext,
488 time_source: Option<SharedTimeSource>,
489 color_capability: crate::view::color_support::ColorCapability,
490 grammar_registry: Arc<crate::primitives::grammar::GrammarRegistry>,
491 defer_plugin_load: bool,
492 ) -> AnyhowResult<Self> {
493 let mut t = InitTimer::start("Editor::with_options");
494 // The editor is constructed with the *real* authority it will run
495 // under — never a local placeholder that gets replaced later (that
496 // left a window where, e.g., quick-open's `git ls-files` ran through
497 // the local spawner while the filesystem was already remote). The
498 // filesystem is derived from it; the spawner/long-running/terminal
499 // ride along on `self.authority`.
500 let filesystem = std::sync::Arc::clone(&authority.filesystem);
501 // Use provided time_source or default to RealTimeSource
502 let time_source = time_source.unwrap_or_else(RealTimeSource::shared);
503 tracing::info!("Editor::new called with width={}, height={}", width, height);
504
505 // Use provided working_dir or capture from environment
506 let working_dir = working_dir
507 .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
508
509 // Canonicalize working_dir to resolve symlinks and normalize path components
510 // This ensures consistent path comparisons throughout the editor
511 let working_dir = working_dir.canonicalize().unwrap_or(working_dir);
512
513 t.phase("preamble");
514 // Load all themes into registry
515 tracing::info!("Loading themes...");
516 let theme_loader = crate::view::theme::ThemeLoader::new(dir_context.themes_dir());
517 t.phase("ThemeLoader::new");
518 // Scan installed packages (language packs + bundles) before plugin loading.
519 // This replaces the JS loadInstalledPackages() — configs, grammars, plugin dirs,
520 // and theme dirs are all collected here and applied synchronously.
521 let scan_result =
522 crate::services::packages::scan_installed_packages(&dir_context.config_dir);
523 t.phase("scan_installed_packages");
524
525 // Apply package language configs (user config takes priority via or_insert)
526 for (lang_id, lang_config) in &scan_result.language_configs {
527 config
528 .languages
529 .entry(lang_id.clone())
530 .or_insert_with(|| lang_config.clone());
531 }
532
533 // Apply package LSP configs (user config takes priority via or_insert)
534 for (lang_id, lsp_config) in &scan_result.lsp_configs {
535 config
536 .lsp
537 .entry(lang_id.clone())
538 .or_insert_with(|| LspLanguageConfig::Multi(vec![lsp_config.clone()]));
539 }
540
541 let theme_registry = Arc::new(theme_loader.load_all(&scan_result.bundle_theme_dirs));
542 t.phase("theme_loader.load_all");
543 tracing::info!("Themes loaded");
544
545 // Get active theme from registry, falling back to default if not found
546 let theme_inner = theme_registry.get_cloned(&config.theme).unwrap_or_else(|| {
547 tracing::warn!(
548 "Theme '{}' not found, falling back to default theme",
549 config.theme.0
550 );
551 theme_registry
552 .get_cloned(&crate::config::ThemeName(
553 crate::view::theme::THEME_HIGH_CONTRAST.to_string(),
554 ))
555 .expect("Default theme must exist")
556 });
557
558 // Set terminal cursor color to match theme
559 theme_inner.set_terminal_cursor_color();
560 let theme = Arc::new(RwLock::new(theme_inner));
561
562 t.phase("theme_setup");
563 let keybindings = Arc::new(RwLock::new(KeybindingResolver::new(&config)));
564 t.phase("keybindings");
565
566 // Create an empty initial buffer
567 let mut buffers = crate::app::window::WindowBuffers::new();
568 let mut event_logs = HashMap::new();
569
570 // Buffer IDs start at 1 (not 0) because the plugin API returns 0 to
571 // mean "no active buffer" from getActiveBufferId(). JavaScript treats
572 // 0 as falsy (`if (!bufferId)` would wrongly reject buffer 0), so
573 // using 1-based IDs avoids this entire class of bugs in plugins.
574 let buffer_id = BufferId(1);
575 let mut state = EditorState::new(
576 width,
577 height,
578 config.editor.large_file_threshold_bytes as usize,
579 Arc::clone(&filesystem),
580 );
581 // Configure initial buffer settings from config
582 state
583 .margins
584 .configure_for_line_numbers(config.editor.line_numbers);
585 state.buffer_settings.tab_size = config.editor.tab_size;
586 state.buffer_settings.auto_close = config.editor.auto_close;
587 // Note: line_wrap_enabled is now stored in SplitViewState.viewport
588 tracing::info!("EditorState created for buffer {:?}", buffer_id);
589 buffers.insert(buffer_id, state);
590 event_logs.insert(buffer_id, EventLog::new());
591
592 // Create metadata for the initial empty buffer. After Step 0l
593 // this lives on the base `Window`; we accumulate it locally and
594 // hand it off when the window is constructed below.
595 let mut buffer_metadata: HashMap<BufferId, BufferMetadata> = HashMap::new();
596 buffer_metadata.insert(buffer_id, BufferMetadata::new());
597
598 // Read orchestrator persistence (`windows.json` and
599 // `state/*.json` under `<data_dir>/orchestrator/`)
600 // before the LSP and base-window construction below.
601 // Pulling persistence in here lets the factory build the
602 // right windows up front: previously this ran from
603 // `main.rs` after construction, so the freshly built
604 // single-base window had to be torn down and replaced with
605 // an inert shell — leaving the active window with
606 // `splits = None` until something re-seeded it. Now the
607 // factory picks the persisted active id/root, attaches the
608 // seed buffer + LSP to it directly, and the constructor
609 // sees a well-formed windows map.
610 let persisted_env = crate::app::orchestrator_persistence::read_persisted_windows_env(
611 filesystem.as_ref(),
612 &dir_context.data_dir,
613 &working_dir,
614 );
615 let plugin_global_state = crate::app::orchestrator_persistence::read_persisted_plugin_state(
616 filesystem.as_ref(),
617 &dir_context.data_dir,
618 &working_dir,
619 );
620
621 // Reopen the session the user last used *in this project*, if
622 // any — never a session from another project. Cross-project
623 // restore is what dragged yesterday's directories/files into a
624 // different project's window; `pick_active_window_for_cwd` only
625 // ever returns a window rooted at `working_dir`, so launching
626 // elsewhere can't pull this project's sessions in (and vice
627 // versa). When the cwd has no sessions, fall back to a clean
628 // base window (id 1) at the launch cwd. This also keeps the LSP
629 // / Open-Terminal default pointed at the launch cwd (issue
630 // #2026).
631 let picked_active = crate::app::orchestrator_persistence::pick_active_window_for_cwd(
632 persisted_env.as_ref(),
633 &working_dir,
634 );
635 let (active_window_id, _active_window_root) = picked_active
636 .map(|w| (fresh_core::WindowId(w.id), w.root.clone()))
637 .unwrap_or((fresh_core::WindowId(1), working_dir.clone()));
638
639 t.phase("buffer_state");
640 // Create Tokio runtime for async I/O (LSP, file watching, git, etc.)
641 let tokio_runtime = tokio::runtime::Builder::new_multi_thread()
642 .worker_threads(2) // Small pool for I/O tasks
643 .thread_name("editor-async")
644 .enable_all()
645 .build()
646 .ok()
647 .map(Arc::new);
648 t.phase("tokio_runtime");
649
650 // Create editor-global async bridge for editor-scoped async
651 // sources (plugin runtime callbacks, file-open dialog, etc.).
652 // Per-window subsystems (LSP, terminal output, file-explorer
653 // async expansion) flow through their owning window's
654 // bridge instead — see `Window.bridge`.
655 let async_bridge = AsyncBridge::new();
656 let event_broadcaster = crate::model::control_event::EventBroadcaster::default();
657
658 if tokio_runtime.is_none() {
659 tracing::warn!("Failed to create Tokio runtime - async features disabled");
660 }
661
662 // The base window's LSP manager is built by `Window::new`
663 // (rooted at the window's root, wired to its own bridge), just
664 // like every other window — there is no special boot-time LSP
665 // construction here anymore. See `build_window_lsp`.
666
667 t.phase("lsp_setup");
668 // Initialize split manager with the initial buffer
669 let split_manager = SplitManager::new(buffer_id);
670
671 // Initialize per-split view state for the initial split
672 let mut split_view_states = HashMap::new();
673 let initial_split_id = split_manager.active_split();
674 let mut initial_view_state = SplitViewState::with_buffer(width, height, buffer_id);
675 initial_view_state.apply_config_defaults(
676 config.editor.line_numbers,
677 config.editor.highlight_current_line,
678 config.editor.line_wrap,
679 config.editor.wrap_indent,
680 config.editor.wrap_column,
681 config.editor.rulers.clone(),
682 config.editor.scroll_offset,
683 );
684 split_view_states.insert(initial_split_id, initial_view_state);
685
686 // Initialize filesystem manager for file explorer
687 let fs_manager = Arc::new(FsManager::new(Arc::clone(&filesystem)));
688
689 // Initialize command registry (always available, used by both plugins and core)
690 let command_registry = Arc::new(RwLock::new(CommandRegistry::new()));
691
692 // The authority is the *real* one this editor runs under, handed in
693 // by the caller — not a local placeholder swapped out later. Every
694 // backend-derived seam below (quick-open's file provider, the LSP
695 // spawner, each window's `resources.authority`) is wired from it at
696 // construction, so there is no window in which, e.g., quick-open's
697 // `git ls-files` runs through a local spawner while the filesystem is
698 // already remote. Runtime authority transitions still go through the
699 // destructive `install_authority` restart (principle 7), which
700 // rebuilds the editor with the next authority via this same path.
701 let process_spawner = Arc::clone(&authority.process_spawner);
702
703 // Initialize Quick Open registry with all providers
704 let mut quick_open_registry = QuickOpenRegistry::new();
705 quick_open_registry.register(Box::new(FileProvider::new(
706 Arc::clone(&filesystem),
707 Arc::clone(&process_spawner),
708 tokio_runtime.as_ref().map(|rt| rt.handle().clone()),
709 Some(async_bridge.sender()),
710 )));
711 quick_open_registry.register(Box::new(CommandProvider::new(
712 Arc::clone(&command_registry),
713 Arc::clone(&keybindings),
714 )));
715 quick_open_registry.register(Box::new(BufferProvider::new()));
716 quick_open_registry.register(Box::new(GotoLineProvider::new()));
717
718 // Build shared theme cache for plugin access
719 let theme_cache = Arc::new(RwLock::new(theme_registry.to_json_map()));
720
721 t.phase("split_quickopen_authority");
722 // Initialize plugin manager (handles both enabled and disabled cases internally)
723 let plugin_manager = Arc::new(RwLock::new(PluginManager::new(
724 enable_plugins,
725 Arc::clone(&command_registry),
726 dir_context.clone(),
727 Arc::clone(&theme_cache),
728 )));
729 t.phase("PluginManager::new");
730
731 // Update the plugin state snapshot with working_dir BEFORE loading plugins
732 // This ensures plugins can call getCwd() correctly during initialization
733 #[cfg(feature = "plugins")]
734 if let Some(snapshot_handle) = plugin_manager.read().unwrap().state_snapshot_handle() {
735 let mut snapshot = snapshot_handle.write().unwrap();
736 snapshot.working_dir = working_dir.clone();
737 // Pre-populate keybinding labels for the static built-in
738 // keymap so `editor.getKeybindingLabel(action, context)`
739 // works for actions that aren't behind a plugin-defined
740 // buffer mode. Without this, a plugin asking
741 // `getKeybindingLabel("cycle_live_grep_provider",
742 // "prompt")` gets null even though Alt+P is bound, and
743 // ends up hardcoding the key in its UI.
744 populate_builtin_keybinding_labels(&mut snapshot, &keybindings);
745 // Seed the snapshot's `config` view with the resolved
746 // initial config so plugins reading
747 // `editor.getPluginConfig()` (and the lower-level
748 // `defineConfigX` snapshot-lookups) see user-set values
749 // on their very first call. Without this seed the
750 // synchronous test path runs plugin scripts BEFORE the
751 // first `update_plugin_state_snapshot` tick, so a
752 // preset `plugins.<name>.settings.<field>` is invisible
753 // to the plugin until much later — defeating any
754 // "react to user config at startup" pattern (e.g.
755 // vi_mode's `autoStart`).
756 if let Ok(json) = serde_json::to_value(&config) {
757 snapshot.config = std::sync::Arc::new(json);
758 }
759 }
760
761 // Load TypeScript plugins from multiple directories:
762 // 1. Next to the executable (for cargo-dist installations)
763 // 1. Embedded plugins (compiled into the binary via the
764 // embed-plugins feature, default on for every shipped build).
765 // 2. User plugins directory (~/.config/fresh/plugins).
766 // 3. Package manager installed plugins (~/.config/fresh/plugins/packages/*).
767 // No working-directory or exe-dir lookup: a user project with a folder
768 // named `plugins/` (a Vite/Rollup project, a Hugo site) is not a Fresh
769 // plugin source, and packagers no longer ship plugins/ alongside the
770 // binary now that the bundled set is fully embedded.
771 // Plugin schemas populated lazily by plugins calling
772 // `editor.definePluginConfig(...)` at load time. See
773 // `handle_register_plugin_config_schema`.
774 let plugin_schemas: HashMap<String, serde_json::Value> = HashMap::new();
775 if plugin_manager.read().unwrap().is_active() {
776 let mut plugin_dirs: Vec<std::path::PathBuf> = vec![];
777
778 // Embedded plugins. `enable_embedded_plugins` lets tests opt out so
779 // they get exactly the plugin set they pre-populated under
780 // `<config_dir>/plugins/`, without the bundled set leaking in.
781 #[cfg(feature = "embed-plugins")]
782 if enable_embedded_plugins && plugin_dirs.is_empty() {
783 if let Some(embedded_dir) =
784 crate::services::plugins::embedded::get_embedded_plugins_dir()
785 {
786 tracing::info!("Using embedded plugins from: {:?}", embedded_dir);
787 plugin_dirs.push(embedded_dir.clone());
788 }
789 }
790
791 // Always check user config plugins directory (~/.config/fresh/plugins)
792 let user_plugins_dir = dir_context.config_dir.join("plugins");
793 if user_plugins_dir.exists() && !plugin_dirs.contains(&user_plugins_dir) {
794 tracing::info!("Found user plugins directory: {:?}", user_plugins_dir);
795 plugin_dirs.push(user_plugins_dir.clone());
796 }
797
798 // Check for package manager installed plugins (~/.config/fresh/plugins/packages/*)
799 let packages_dir = dir_context.config_dir.join("plugins").join("packages");
800 if packages_dir.exists() {
801 if let Ok(entries) = std::fs::read_dir(&packages_dir) {
802 for entry in entries.flatten() {
803 let path = entry.path();
804 // Skip hidden directories (like .index for registry cache)
805 if path.is_dir() {
806 if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
807 if !name.starts_with('.') {
808 tracing::info!("Found package manager plugin: {:?}", path);
809 plugin_dirs.push(path);
810 }
811 }
812 }
813 }
814 }
815 }
816
817 // Add bundle plugin directories from package scan
818 for dir in &scan_result.bundle_plugin_dirs {
819 tracing::info!("Found bundle plugin directory: {:?}", dir);
820 plugin_dirs.push(dir.clone());
821 }
822
823 if plugin_dirs.is_empty() {
824 tracing::debug!(
825 "No plugins directory found next to executable or in working dir: {:?}",
826 working_dir
827 );
828 }
829
830 if defer_plugin_load {
831 // Async startup path: hand each dir + a trailing
832 // ListPlugins request to the plugin thread now, return
833 // before they finish, and let a forwarder thread
834 // translate the responses into AsyncMessages that the
835 // main loop applies via `process_async_messages`. The
836 // plugin thread is FIFO, so submitting in this exact
837 // order guarantees declarations cover only the startup
838 // batch — init.ts and lifecycle hooks queue *after*
839 // ListPlugins from main.rs after construction returns,
840 // matching the original blocking behaviour.
841 #[cfg(feature = "plugins")]
842 {
843 let bridge = &async_bridge;
844 let mut dir_receivers: Vec<(
845 std::path::PathBuf,
846 fresh_plugin_runtime::thread::oneshot::Receiver<
847 fresh_plugin_runtime::thread::PluginsDirLoadResult,
848 >,
849 )> = Vec::with_capacity(plugin_dirs.len());
850 for plugin_dir in &plugin_dirs {
851 tracing::info!(
852 "Submitting async TypeScript plugin load for: {:?}",
853 plugin_dir
854 );
855 if let Some(rx) = plugin_manager
856 .read()
857 .unwrap()
858 .load_plugins_from_dir_with_config_request(plugin_dir, &config.plugins)
859 {
860 dir_receivers.push((plugin_dir.clone(), rx));
861 }
862 }
863 let declarations_rx = if !dir_receivers.is_empty() {
864 plugin_manager.read().unwrap().list_plugins_request()
865 } else {
866 None
867 };
868 if !dir_receivers.is_empty() {
869 let sender = bridge.sender();
870 std::thread::Builder::new()
871 .name("plugin-load-forwarder".to_string())
872 .spawn(move || {
873 for (dir, rx) in dir_receivers {
874 let load_start = std::time::Instant::now();
875 match rx.recv() {
876 Ok((errors, discovered_plugins)) => {
877 tracing::info!(
878 "Loaded TypeScript plugins from {:?} in {:?}",
879 dir,
880 load_start.elapsed()
881 );
882 drop(sender.send(
883 crate::services::async_bridge::AsyncMessage::PluginsDirLoaded {
884 dir,
885 errors,
886 discovered_plugins,
887 },
888 ));
889 }
890 Err(e) => {
891 tracing::warn!(
892 "plugin-load-forwarder: dir {:?} recv failed: {}",
893 dir,
894 e
895 );
896 }
897 }
898 }
899 if let Some(rx) = declarations_rx {
900 match rx.recv() {
901 Ok(plugin_infos) => {
902 let declarations: Vec<(String, String)> = plugin_infos
903 .into_iter()
904 .filter_map(|info| {
905 info.declarations.map(|d| (info.name, d))
906 })
907 .collect();
908 drop(sender.send(
909 crate::services::async_bridge::AsyncMessage::PluginDeclarationsReady {
910 declarations,
911 },
912 ));
913 }
914 Err(e) => {
915 tracing::warn!(
916 "plugin-load-forwarder: list_plugins recv failed: {}",
917 e
918 );
919 }
920 }
921 }
922 })
923 .ok();
924 }
925 }
926 } else {
927 // Synchronous (legacy / test) path. Used by `for_test`,
928 // server, GUI: every other code path that wants the
929 // editor fully constructed before the constructor
930 // returns.
931 for plugin_dir in plugin_dirs {
932 tracing::info!("Loading TypeScript plugins from: {:?}", plugin_dir);
933 let load_start = std::time::Instant::now();
934 let (errors, discovered_plugins) = plugin_manager
935 .read()
936 .unwrap()
937 .load_plugins_from_dir_with_config(&plugin_dir, &config.plugins);
938 tracing::info!(
939 "Loaded TypeScript plugins from {:?} in {:?}",
940 plugin_dir,
941 load_start.elapsed()
942 );
943
944 // Merge discovered plugins into config
945 // discovered_plugins already contains the merged config (saved enabled state + discovered path)
946 for (name, plugin_config) in discovered_plugins {
947 config.plugins.insert(name, plugin_config);
948 }
949
950 if !errors.is_empty() {
951 for err in &errors {
952 tracing::error!("TypeScript plugin load error: {}", err);
953 }
954 // In debug/test builds, panic to surface plugin loading errors
955 #[cfg(debug_assertions)]
956 panic!(
957 "TypeScript plugin loading failed with {} error(s): {}",
958 errors.len(),
959 errors.join("; ")
960 );
961 }
962 }
963
964 // Collect `.d.ts` emits from every loaded plugin into a
965 // single aggregate under `<config_dir>/types/plugins.d.ts`.
966 // This is what makes `getPluginApi("foo")` typed in the
967 // user's init.ts without a hand-written cast — each plugin
968 // that uses `declare global { interface FreshPluginRegistry }`
969 // contributes its augmentation, and init.ts's tsconfig
970 // picks the aggregate up via `files`.
971 let declarations = plugin_manager.read().unwrap().plugin_declarations();
972 crate::init_script::write_plugin_declarations(
973 &dir_context.config_dir,
974 &declarations,
975 );
976 }
977 }
978
979 t.phase("plugin_loading");
980 // Extract config values before moving config into the struct
981 let recovery_enabled = config.editor.recovery_enabled;
982 let check_for_updates = config.check_for_updates;
983
984 // Start periodic update checker if enabled (also sends daily telemetry)
985 let update_checker = if check_for_updates {
986 tracing::debug!("Update checking enabled, starting periodic checker");
987 Some(
988 crate::services::release_checker::start_periodic_update_check(
989 crate::services::release_checker::DEFAULT_RELEASES_URL,
990 time_source.clone(),
991 dir_context.data_dir.clone(),
992 ),
993 )
994 } else {
995 tracing::debug!("Update checking disabled by config");
996 None
997 };
998
999 // Cache raw user config at startup (to avoid re-reading file every frame)
1000 let user_config_raw = Config::read_user_config_raw(&working_dir);
1001
1002 // Wrap config in Arc and pre-seed the snapshot mirror + JSON cache.
1003 // Doing this at construction means the strong count of the live
1004 // `config` Arc starts at 2 and stays there: every `Arc::make_mut`
1005 // call on `config` is forced to CoW, so no mutation path (direct or
1006 // via `config_mut()`) can leave `config_cached_json` referring to
1007 // stale memory.
1008 let config_arc = Arc::new(config);
1009 let config_cached_json =
1010 Arc::new(serde_json::to_value(&*config_arc).unwrap_or(serde_json::Value::Null));
1011 let config_snapshot_anchor = Arc::clone(&config_arc);
1012
1013 // The buffer-id allocator starts at the same value as
1014 // `next_buffer_id`. Both are kept in sync by every allocation
1015 // path (`Editor::alloc_buffer_id` advances both); the allocator
1016 // is what gets cloned into every `Window` so handlers on
1017 // `impl Window` can mint ids without an `Editor` reference.
1018 let buffer_id_alloc = crate::app::window_resources::BufferIdAllocator::new(2);
1019
1020 // The local-host filesystem handle. Hoisted here (rather than
1021 // constructed inline in the `Editor` literal below) so the
1022 // base window's `WindowResources` and the editor share the same
1023 // `Arc` from the start.
1024 let local_filesystem: Arc<dyn crate::model::filesystem::FileSystem + Send + Sync> =
1025 Arc::new(crate::model::filesystem::StdFileSystem);
1026
1027 // Hot-exit recovery service, shared (Arc<Mutex>) into every
1028 // `Window` via `WindowResources` so per-window restore/auto-save
1029 // can reach it without an active-window flip.
1030 let recovery_service = {
1031 let recovery_config = RecoveryConfig {
1032 enabled: recovery_enabled,
1033 ..RecoveryConfig::default()
1034 };
1035 // Default to a CWD-scoped recovery directory so each working
1036 // directory keeps its own hot-exit recovery files. If this
1037 // editor is later promoted to session mode, `set_session_name`
1038 // re-creates the service with `RecoveryScope::Session`.
1039 // Issue #1550: without per-CWD scoping, opening Fresh in a
1040 // second folder would clobber the first folder's unsaved
1041 // unnamed buffers on shutdown.
1042 let scope = crate::services::recovery::RecoveryScope::Standalone {
1043 working_dir: working_dir.clone(),
1044 };
1045 std::sync::Arc::new(std::sync::Mutex::new(RecoveryService::with_scope(
1046 recovery_config,
1047 &dir_context.recovery_dir(),
1048 &scope,
1049 )))
1050 };
1051
1052 // Build the resource bundle every `Window` gets a clone of. The
1053 // base window receives one clone here; subsequent windows
1054 // (created via `Editor::create_window_at` or first-dive seeding
1055 // in `set_active_window`) reach back to `Editor::window_resources()`
1056 // for an equivalent bundle.
1057 let base_resources = crate::app::window_resources::WindowResources {
1058 config: Arc::clone(&config_arc),
1059 grammar_registry: Arc::clone(&grammar_registry),
1060 theme_registry: Arc::clone(&theme_registry),
1061 theme_cache: Arc::clone(&theme_cache),
1062 keybindings: Arc::clone(&keybindings),
1063 command_registry: Arc::clone(&command_registry),
1064 fs_manager: Arc::clone(&fs_manager),
1065 local_filesystem: Arc::clone(&local_filesystem),
1066 buffer_id_alloc: buffer_id_alloc.clone(),
1067 authority: authority.clone(),
1068 time_source: Arc::clone(&time_source),
1069 dir_context: dir_context.clone(),
1070 tokio_runtime: tokio_runtime.clone(),
1071 async_bridge: Some(async_bridge.clone()),
1072 plugin_manager: Arc::clone(&plugin_manager),
1073 theme: Arc::clone(&theme),
1074 event_broadcaster: event_broadcaster.clone(),
1075 recovery_service: Arc::clone(&recovery_service),
1076 };
1077
1078 // Build the active window — the one that holds the seed
1079 // buffer, the SplitManager, the LSP, and the
1080 // already-configured per-window bridge. Its label / root /
1081 // plugin state come from the persisted session we chose to
1082 // reopen (the last-used one for this cwd). When there was none
1083 // we boot a clean base: empty label, cwd root, no inherited
1084 // state. We deliberately key off the *picked* window, not a
1085 // lookup by `active_window_id` — a clean base reuses id 1, and
1086 // a stale persisted id-1 window (a different project's old
1087 // base) must not lend its label/root/state to it.
1088 let (active_label, active_root, active_plugin_state) = picked_active
1089 .map(|w| (w.label.clone(), w.root.clone(), w.plugin_state.clone()))
1090 .unwrap_or_else(|| (String::new(), working_dir.clone(), HashMap::new()));
1091
1092 let mut active_win = crate::app::window::Window::new(
1093 active_window_id,
1094 active_label,
1095 active_root,
1096 base_resources,
1097 );
1098 // Seed the window's terminal dimensions from the editor's
1099 // initial size — `Window::new` defaults to 80x24, which is
1100 // wrong for any harness that constructs the editor at a
1101 // different size (issue surfaces in
1102 // test_hidden_terminal_resyncs_pty_size_when_revealed).
1103 active_win.terminal_width = width;
1104 active_win.terminal_height = height;
1105 // Install the initial split layout. The LSP manager and per-
1106 // window bridge were already built by `Window::new` (rooted at
1107 // this window's root, wired together), so there's nothing to
1108 // hand off here — every window owns its manager by construction.
1109 active_win.buffers = buffers;
1110 active_win
1111 .buffers
1112 .set_splits((split_manager, split_view_states));
1113 active_win.buffer_metadata = buffer_metadata;
1114 active_win.event_logs = event_logs;
1115 active_win.plugin_state = active_plugin_state;
1116 // Load prompt histories from disk for the active window.
1117 // Each window has its own prompt-history rings.
1118 for history_name in ["search", "replace", "goto_line"] {
1119 let path = dir_context.prompt_history_path(history_name);
1120 let history = crate::input::input_history::InputHistory::load_from_file(&path)
1121 .unwrap_or_else(|e| {
1122 tracing::warn!("Failed to load {} history: {}", history_name, e);
1123 crate::input::input_history::InputHistory::new()
1124 });
1125 active_win
1126 .prompt_histories
1127 .insert(history_name.to_string(), history);
1128 }
1129
1130 // Build the inert shells for every other persisted window.
1131 // Their `splits` stays `None`; first dive into them re-warms
1132 // exactly like a freshly created window.
1133 let mut windows = HashMap::new();
1134 if let Some(ref env) = persisted_env {
1135 // The active window came from a real pick when `picked_active`
1136 // is `Some` — its persisted entry must NOT also become a shell.
1137 // When the pick found nothing we synthesized a clean base at
1138 // `WindowId(1)` (the base is always id 1); a global
1139 // `windows.json` may already hold a *different* project's id-1
1140 // base, which would collide. Re-id that collider onto a fresh
1141 // id so it survives as an inactive shell instead of being
1142 // shadowed/dropped (issue #2056 cross-project case).
1143 let active_came_from_pick = picked_active.is_some();
1144 let active_root_key =
1145 crate::app::orchestrator_persistence::canonical_key(&active_win.root);
1146 let mut next_fresh_id = env
1147 .next_id
1148 .max(env.windows.iter().map(|w| w.id).max().unwrap_or(0) + 1)
1149 .max(active_window_id.0 + 1);
1150 for ps in &env.windows {
1151 if active_came_from_pick && ps.id == active_window_id.0 {
1152 continue;
1153 }
1154 // One session per directory: never seed a shell that
1155 // resolves to the active window's own directory (the
1156 // clean-base case where the cwd has a stale persisted
1157 // window the pick didn't claim).
1158 if crate::app::orchestrator_persistence::canonical_key(&ps.root) == active_root_key
1159 {
1160 continue;
1161 }
1162 let id = if ps.id == active_window_id.0 {
1163 let fresh = fresh_core::WindowId(next_fresh_id);
1164 next_fresh_id += 1;
1165 fresh
1166 } else {
1167 fresh_core::WindowId(ps.id)
1168 };
1169 let resources = crate::app::window_resources::WindowResources {
1170 config: Arc::clone(&config_arc),
1171 grammar_registry: Arc::clone(&grammar_registry),
1172 theme_registry: Arc::clone(&theme_registry),
1173 theme_cache: Arc::clone(&theme_cache),
1174 keybindings: Arc::clone(&keybindings),
1175 command_registry: Arc::clone(&command_registry),
1176 fs_manager: Arc::clone(&fs_manager),
1177 local_filesystem: Arc::clone(&local_filesystem),
1178 buffer_id_alloc: buffer_id_alloc.clone(),
1179 authority: authority.clone(),
1180 time_source: Arc::clone(&time_source),
1181 dir_context: dir_context.clone(),
1182 tokio_runtime: tokio_runtime.clone(),
1183 async_bridge: Some(async_bridge.clone()),
1184 plugin_manager: Arc::clone(&plugin_manager),
1185 theme: Arc::clone(&theme),
1186 event_broadcaster: event_broadcaster.clone(),
1187 recovery_service: Arc::clone(&recovery_service),
1188 };
1189 let mut shell = crate::app::window::Window::new(
1190 id,
1191 ps.label.clone(),
1192 ps.root.clone(),
1193 resources,
1194 );
1195 shell.terminal_width = width;
1196 shell.terminal_height = height;
1197 shell.plugin_state = ps.plugin_state.clone();
1198 windows.insert(id, shell);
1199 }
1200 }
1201 windows.insert(active_window_id, active_win);
1202
1203 // Allocate next window ids past every persisted entry and
1204 // past our active id, so `createWindow` after restart never
1205 // collides with an id the user might still see in plugin
1206 // state. Falls back to 2 (the post-base-window default)
1207 // when there's no persistence.
1208 let max_existing = windows.keys().map(|k| k.0).max().unwrap_or(0);
1209 let next_window_id = persisted_env
1210 .as_ref()
1211 .map(|env| env.next_id.max(max_existing + 1))
1212 .unwrap_or(2);
1213
1214 let key_translator = crate::input::key_translator::KeyTranslator::load_from_config_dir(
1215 &dir_context.config_dir,
1216 )
1217 .unwrap_or_default();
1218
1219 let pending_grammars = scan_result
1220 .additional_grammars
1221 .iter()
1222 .map(|g| PendingGrammar {
1223 language: g.language.clone(),
1224 grammar_path: g.path.to_string_lossy().to_string(),
1225 extensions: g.extensions.clone(),
1226 })
1227 .collect();
1228
1229 let parts = EditorParts {
1230 config: config_arc,
1231 config_snapshot_anchor,
1232 config_cached_json,
1233 user_config_raw: Arc::new(user_config_raw),
1234 dir_context: dir_context.clone(),
1235 theme,
1236 theme_registry,
1237 theme_cache,
1238 grammar_registry,
1239 pending_grammars,
1240 needs_full_grammar_build: true,
1241 keybindings,
1242 buffer_id_alloc: buffer_id_alloc.clone(),
1243 next_buffer_id: 2,
1244 terminal_width: width,
1245 terminal_height: height,
1246 color_capability,
1247 tokio_runtime,
1248 async_bridge,
1249 authority,
1250 local_filesystem: Arc::clone(&local_filesystem),
1251 windows,
1252 active_window: active_window_id,
1253 next_window_id,
1254 command_registry,
1255 quick_open_registry,
1256 plugin_manager,
1257 recovery_service,
1258 key_translator,
1259 update_checker,
1260 time_source: time_source.clone(),
1261 plugin_global_state,
1262 plugin_schemas,
1263 event_broadcaster: event_broadcaster.clone(),
1264 };
1265
1266 let mut editor = Editor::from_parts(parts);
1267
1268 t.phase("editor_struct_assembly");
1269 // Apply clipboard configuration
1270 editor.clipboard.apply_config(&editor.config.clipboard);
1271
1272 // Seed splits/buffers for every persisted inactive window so they
1273 // render in preview surfaces (Orchestrator's WindowEmbed) before the
1274 // user first dives in. Without this, restored windows have
1275 // `splits == None` and paint blank in the preview pane. We also
1276 // catch the (rarer) inverse where splits is set but the buffer
1277 // map is empty — that combo is what hit the historic
1278 // "active buffer must be present" panic in render.
1279 let needs_seed: Vec<fresh_core::WindowId> = editor
1280 .windows
1281 .iter()
1282 .filter(|(_, s)| s.buffers.splits().is_none() || s.buffers.len() == 0)
1283 .map(|(id, _)| *id)
1284 .collect();
1285 for id in needs_seed {
1286 if let Some((buf, state, metadata, event_log, mgr, vs)) =
1287 editor.build_fresh_layout_if_needed(id)
1288 {
1289 if let Some(s) = editor.windows.get_mut(&id) {
1290 s.buffers.set_splits((mgr, vs));
1291 s.buffers.insert(buf, state);
1292 s.buffer_metadata.insert(buf, metadata);
1293 s.event_logs.insert(buf, event_log);
1294 }
1295 }
1296 }
1297
1298 // Lazy materialization: every non-active window keeps only its
1299 // empty seed layout for now and is restored from disk on first
1300 // dive/preview (see `materialize_window`). Only the foreground
1301 // (CLI-dir) window is restored eagerly, by the caller's
1302 // `try_restore_workspace`.
1303 editor.materialize_pending = editor
1304 .windows
1305 .keys()
1306 .copied()
1307 .filter(|id| *id != editor.active_window)
1308 .collect();
1309
1310 #[cfg(feature = "plugins")]
1311 {
1312 editor.update_plugin_state_snapshot();
1313 if editor.plugin_manager.read().unwrap().is_active() {
1314 editor.plugin_manager.read().unwrap().run_hook(
1315 "editor_initialized",
1316 crate::services::plugins::hooks::HookArgs::EditorInitialized {},
1317 );
1318 }
1319 }
1320 t.phase("post_struct_hooks");
1321 t.finish();
1322 Ok(editor)
1323 }
1324
1325 /// Get a reference to the event broadcaster
1326 pub fn event_broadcaster(&self) -> &crate::model::control_event::EventBroadcaster {
1327 &self.event_broadcaster
1328 }
1329
1330 /// Spawn a background thread to build the full grammar registry
1331 /// (embedded grammars, user grammars, language packs, and any plugin-registered grammars).
1332 /// Called on the first event-loop tick (via `flush_pending_grammars`) so that
1333 /// plugin grammars registered during init are included in a single build.
1334 pub(super) fn start_background_grammar_build(
1335 &mut self,
1336 additional: Vec<crate::primitives::grammar::GrammarSpec>,
1337 callback_ids: Vec<fresh_core::api::JsCallbackId>,
1338 ) {
1339 let Some(bridge) = &self.async_bridge else {
1340 return;
1341 };
1342 self.grammar_build_in_progress = true;
1343 let sender = bridge.sender();
1344 let config_dir = self.dir_context.config_dir.clone();
1345 tracing::info!(
1346 "Spawning background grammar build thread ({} plugin grammars)...",
1347 additional.len()
1348 );
1349 std::thread::Builder::new()
1350 .name("grammar-build".to_string())
1351 .spawn(move || {
1352 tracing::info!("[grammar-build] Thread started");
1353 let start = std::time::Instant::now();
1354 let registry = if additional.is_empty() {
1355 crate::primitives::grammar::GrammarRegistry::for_editor(config_dir)
1356 } else {
1357 crate::primitives::grammar::GrammarRegistry::for_editor_with_additional(
1358 config_dir,
1359 &additional,
1360 )
1361 };
1362 tracing::info!("[grammar-build] Complete in {:?}", start.elapsed());
1363 drop(sender.send(
1364 crate::services::async_bridge::AsyncMessage::GrammarRegistryBuilt {
1365 registry,
1366 callback_ids,
1367 },
1368 ));
1369 })
1370 .ok();
1371 }
1372
1373 // =========================================================================
1374 // init.ts / runtime-overlay surface (design docs §3–§6)
1375 // =========================================================================
1376
1377 /// Auto-load `~/.config/fresh/init.ts` if present, through the existing
1378 /// plugin pipeline under the stable name `crate::init_script::INIT_PLUGIN_NAME`.
1379 pub fn load_init_script(&mut self, enabled: bool) {
1380 use crate::init_script::{
1381 check, decide_load, describe, record_success, refresh_types_scaffolding, CheckSeverity,
1382 InitOutcome, LoadDecision,
1383 };
1384
1385 let config_dir = self.dir_context.config_dir.clone();
1386
1387 if enabled {
1388 // Refresh the types mirror from the embedded copy before anything
1389 // reads init.ts. Guarantees the declarations the user sees match
1390 // the running build — stale types would hide API drift.
1391 refresh_types_scaffolding(&config_dir);
1392
1393 // Re-check init.ts right after the refresh so drift between the
1394 // user's script and the current API surface (at least syntax-level
1395 // fallout like unterminated blocks from a botched rename) shows up
1396 // in the log immediately rather than only at eval time.
1397 let report = check(&config_dir);
1398 if !report.ok {
1399 for d in &report.diagnostics {
1400 let level = match d.severity {
1401 CheckSeverity::Error => "error",
1402 CheckSeverity::Warning => "warning",
1403 };
1404 tracing::warn!(
1405 "init.ts pre-load {level} at {}:{}: {}",
1406 d.line,
1407 d.column,
1408 d.message
1409 );
1410 }
1411 }
1412 }
1413
1414 let outcome = match decide_load(&config_dir, enabled) {
1415 LoadDecision::Skip(outcome) => outcome,
1416 LoadDecision::Load { source } => {
1417 if !self.plugin_manager.read().unwrap().is_active() {
1418 InitOutcome::Failed {
1419 message: "plugin runtime inactive (--no-plugins); init.ts cannot run"
1420 .into(),
1421 }
1422 } else {
1423 match self.plugin_manager.read().unwrap().load_plugin_from_source(
1424 &source,
1425 crate::init_script::INIT_PLUGIN_NAME,
1426 true,
1427 ) {
1428 Ok(()) => {
1429 record_success(&config_dir);
1430 InitOutcome::Loaded
1431 }
1432 Err(e) => InitOutcome::Failed {
1433 message: format!("{e}"),
1434 },
1435 }
1436 }
1437 }
1438 };
1439
1440 let summary = describe(&outcome);
1441 match outcome {
1442 InitOutcome::NotFound | InitOutcome::Disabled => tracing::debug!("{}", summary),
1443 InitOutcome::Loaded => tracing::info!("{}", summary),
1444 InitOutcome::CrashFused { .. } | InitOutcome::Failed { .. } => {
1445 tracing::warn!("{}", summary);
1446 self.set_status_message(summary);
1447 }
1448 }
1449 }
1450
1451 /// Non-blocking variant of [`Self::load_init_script`] for the TUI
1452 /// startup path. Does the synchronous pre-work (types scaffolding
1453 /// refresh, syntax check, fuse check), then either submits the
1454 /// `LoadPluginFromSource` request to the plugin thread and spawns a
1455 /// forwarder that translates the result into
1456 /// `AsyncMessage::PluginInitScriptLoaded`, or — for the `Skip(...)`
1457 /// outcomes — emits the message directly so the same async-dispatch
1458 /// handler logs and applies status. The request goes through the
1459 /// same FIFO channel as the startup plugin loads, so by the time the
1460 /// plugin thread evaluates init.ts every batch plugin has already
1461 /// finished — preserving the original load ordering.
1462 pub fn load_init_script_async(&mut self, enabled: bool) {
1463 use crate::init_script::{
1464 check, decide_load, refresh_types_scaffolding, CheckSeverity, InitOutcome, LoadDecision,
1465 };
1466 use crate::services::async_bridge::PluginInitScriptOutcome;
1467
1468 let config_dir = self.dir_context.config_dir.clone();
1469
1470 if enabled {
1471 refresh_types_scaffolding(&config_dir);
1472 let report = check(&config_dir);
1473 if !report.ok {
1474 for d in &report.diagnostics {
1475 let level = match d.severity {
1476 CheckSeverity::Error => "error",
1477 CheckSeverity::Warning => "warning",
1478 };
1479 tracing::warn!(
1480 "init.ts pre-load {level} at {}:{}: {}",
1481 d.line,
1482 d.column,
1483 d.message
1484 );
1485 }
1486 }
1487 }
1488
1489 let outcome_now: Option<PluginInitScriptOutcome> = match decide_load(&config_dir, enabled) {
1490 LoadDecision::Skip(outcome) => Some(match outcome {
1491 InitOutcome::NotFound => PluginInitScriptOutcome::NotFound,
1492 InitOutcome::Disabled => PluginInitScriptOutcome::Disabled,
1493 InitOutcome::CrashFused { failures } => {
1494 PluginInitScriptOutcome::CrashFused { failures }
1495 }
1496 // decide_load only returns these via Load; keep total to
1497 // satisfy the matcher.
1498 InitOutcome::Loaded => PluginInitScriptOutcome::Loaded,
1499 InitOutcome::Failed { message } => PluginInitScriptOutcome::Failed { message },
1500 }),
1501 LoadDecision::Load { source } => {
1502 if !self.plugin_manager.read().unwrap().is_active() {
1503 Some(PluginInitScriptOutcome::Failed {
1504 message: "plugin runtime inactive (--no-plugins); init.ts cannot run"
1505 .into(),
1506 })
1507 } else {
1508 self.spawn_init_script_forwarder(source);
1509 None
1510 }
1511 }
1512 };
1513
1514 if let Some(outcome) = outcome_now {
1515 // Skip / fused / inactive paths: emit through the bridge so
1516 // the same handler runs them as the success path. Falls back
1517 // to direct application if the bridge is missing (test).
1518 if let Some(bridge) = &self.async_bridge {
1519 drop(bridge.sender().send(
1520 crate::services::async_bridge::AsyncMessage::PluginInitScriptLoaded(outcome),
1521 ));
1522 } else {
1523 self.handle_plugin_init_script_loaded(outcome);
1524 }
1525 }
1526 }
1527
1528 #[cfg(feature = "plugins")]
1529 fn spawn_init_script_forwarder(&self, source: String) {
1530 let Some(bridge) = &self.async_bridge else {
1531 return;
1532 };
1533 let Some(rx) = self
1534 .plugin_manager
1535 .read()
1536 .unwrap()
1537 .load_plugin_from_source_request(&source, crate::init_script::INIT_PLUGIN_NAME, true)
1538 else {
1539 return;
1540 };
1541 let sender = bridge.sender();
1542 std::thread::Builder::new()
1543 .name("plugin-init-forwarder".to_string())
1544 .spawn(move || {
1545 let outcome = match rx.recv() {
1546 Ok(Ok(())) => crate::services::async_bridge::PluginInitScriptOutcome::Loaded,
1547 Ok(Err(e)) => crate::services::async_bridge::PluginInitScriptOutcome::Failed {
1548 message: format!("{e}"),
1549 },
1550 Err(e) => crate::services::async_bridge::PluginInitScriptOutcome::Failed {
1551 message: format!("plugin thread closed: {e}"),
1552 },
1553 };
1554 drop(sender.send(
1555 crate::services::async_bridge::AsyncMessage::PluginInitScriptLoaded(outcome),
1556 ));
1557 })
1558 .ok();
1559 }
1560
1561 #[cfg(not(feature = "plugins"))]
1562 fn spawn_init_script_forwarder(&self, _source: String) {}
1563
1564 /// Handle `setSetting(path, value)`. Fire-and-forget: patches Config
1565 /// directly via JSON round-trip. No overlay, no per-plugin tracking,
1566 /// no revert on unload — same model as Neovim/VS Code/Emacs/Sublime.
1567 pub fn handle_set_setting(&mut self, path: String, value: serde_json::Value) {
1568 let mut json = serde_json::to_value(&*self.config).unwrap_or_default();
1569 set_dot_path(&mut json, &path, value);
1570 match serde_json::from_value::<crate::config::Config>(json) {
1571 Ok(new_config) => {
1572 let old_theme = self.config.theme.clone();
1573 self.config = Arc::new(new_config);
1574 if old_theme != self.config.theme {
1575 if let Some(theme) = self.theme_registry.get_cloned(&self.config.theme) {
1576 *self.theme.write().unwrap() = theme;
1577 }
1578 }
1579 *self.keybindings.write().unwrap() =
1580 crate::input::keybindings::KeybindingResolver::new(&self.config);
1581 self.clipboard.apply_config(&self.config.clipboard);
1582 {
1583 let cfg = self.config.editor.clone();
1584 let win = self.active_window_mut();
1585 win.menu_bar_visible = cfg.show_menu_bar;
1586 win.tab_bar_visible = cfg.show_tab_bar;
1587 win.status_bar_visible = cfg.show_status_bar;
1588 win.prompt_line_visible = cfg.show_prompt_line;
1589 }
1590 #[cfg(feature = "plugins")]
1591 self.update_plugin_state_snapshot();
1592 }
1593 Err(e) => {
1594 self.set_status_message(format!("setSetting({path}): {e}"));
1595 }
1596 }
1597 }
1598
1599 /// Append a single config field to a plugin's accumulated schema and
1600 /// pre-populate its default value. Each `defineConfigX(...)` call
1601 /// from the plugin's TS code fires one of these.
1602 ///
1603 /// On first call for a plugin we synthesise a fresh
1604 /// `{"type": "object", "properties": {}}` schema and grow it as more
1605 /// fields arrive. Re-registering the same `field_name` overwrites
1606 /// the previous definition (which is what we want on plugin
1607 /// reload — plugins re-run their `defineConfigX` calls).
1608 pub fn handle_add_plugin_config_field(
1609 &mut self,
1610 plugin_name: String,
1611 field_name: String,
1612 field_schema: serde_json::Value,
1613 ) {
1614 tracing::trace!(
1615 "Registering plugin config field: {}.{}",
1616 plugin_name,
1617 field_name
1618 );
1619 // Merge the new field into the existing accumulated schema (or a
1620 // fresh one) and run the same strict validation as a bulk-register.
1621 let updated_schema = {
1622 let schemas = self.plugin_schemas.read().ok();
1623 let existing = schemas.as_ref().and_then(|m| m.get(&plugin_name)).cloned();
1624 let mut schema = existing.unwrap_or_else(|| {
1625 serde_json::json!({
1626 "type": "object",
1627 "properties": {},
1628 })
1629 });
1630 if let Some(props) = schema
1631 .as_object_mut()
1632 .and_then(|o| o.get_mut("properties"))
1633 .and_then(|p| p.as_object_mut())
1634 {
1635 props.insert(field_name.clone(), field_schema.clone());
1636 }
1637 schema
1638 };
1639
1640 if let Err(msg) = crate::plugin_schemas::validate_plugin_schema(&updated_schema) {
1641 // Field passed JS-side validation but somehow broke the full
1642 // schema — log and skip so we don't poison the registry.
1643 self.set_status_message(format!(
1644 "defineConfig({}.{}): {}",
1645 plugin_name, field_name, msg
1646 ));
1647 return;
1648 }
1649
1650 // Pre-populate the default for THIS field only.
1651 if let Some(default) = field_schema.get("default").cloned() {
1652 let cfg = std::sync::Arc::make_mut(&mut self.config);
1653 let entry = cfg.plugins.entry(plugin_name.clone()).or_default();
1654 let settings_obj = match &mut entry.settings {
1655 serde_json::Value::Object(_) => &mut entry.settings,
1656 slot => {
1657 *slot = serde_json::Value::Object(Default::default());
1658 slot
1659 }
1660 };
1661 if let serde_json::Value::Object(map) = settings_obj {
1662 map.entry(field_name.clone()).or_insert(default);
1663 }
1664 }
1665
1666 if let Ok(mut schemas) = self.plugin_schemas.write() {
1667 schemas.insert(plugin_name, updated_schema);
1668 }
1669
1670 #[cfg(feature = "plugins")]
1671 self.update_plugin_state_snapshot();
1672 }
1673
1674 /// Apply the result of one async startup-batch directory load.
1675 /// Mirrors the per-iteration body of the legacy synchronous loop in
1676 /// `with_options`: merge discovered plugins into config, log errors,
1677 /// and panic in debug builds (the legacy behaviour).
1678 pub(crate) fn handle_plugins_dir_loaded(
1679 &mut self,
1680 dir: std::path::PathBuf,
1681 errors: Vec<String>,
1682 discovered_plugins: std::collections::HashMap<String, fresh_core::config::PluginConfig>,
1683 ) {
1684 if !discovered_plugins.is_empty() {
1685 let cfg = std::sync::Arc::make_mut(&mut self.config);
1686 for (name, plugin_config) in discovered_plugins {
1687 cfg.plugins.insert(name, plugin_config);
1688 }
1689 }
1690 if !errors.is_empty() {
1691 for err in &errors {
1692 tracing::error!("TypeScript plugin load error: {}", err);
1693 }
1694 #[cfg(debug_assertions)]
1695 panic!(
1696 "TypeScript plugin loading failed for {:?} with {} error(s): {}",
1697 dir,
1698 errors.len(),
1699 errors.join("; ")
1700 );
1701 #[cfg(not(debug_assertions))]
1702 {
1703 let _ = dir;
1704 }
1705 }
1706 }
1707
1708 /// Apply the declarations harvested at the end of the async startup
1709 /// batch. Mirrors the synchronous `plugin_declarations` +
1710 /// `write_plugin_declarations` pair in `with_options`.
1711 pub(crate) fn handle_plugin_declarations_ready(&self, declarations: Vec<(String, String)>) {
1712 crate::init_script::write_plugin_declarations(&self.dir_context.config_dir, &declarations);
1713 }
1714
1715 /// Apply the result of the async `init.ts` load. Mirrors the trailing
1716 /// `match outcome { ... }` block of the legacy synchronous
1717 /// `load_init_script`.
1718 pub(crate) fn handle_plugin_init_script_loaded(
1719 &mut self,
1720 outcome: crate::services::async_bridge::PluginInitScriptOutcome,
1721 ) {
1722 use crate::init_script::{describe, record_success, InitOutcome};
1723 use crate::services::async_bridge::PluginInitScriptOutcome as O;
1724 let outcome = match outcome {
1725 O::NotFound => InitOutcome::NotFound,
1726 O::Disabled => InitOutcome::Disabled,
1727 O::CrashFused { failures } => InitOutcome::CrashFused { failures },
1728 O::Loaded => {
1729 record_success(&self.dir_context.config_dir);
1730 InitOutcome::Loaded
1731 }
1732 O::Failed { message } => InitOutcome::Failed { message },
1733 };
1734 let summary = describe(&outcome);
1735 match outcome {
1736 InitOutcome::NotFound | InitOutcome::Disabled => tracing::debug!("{}", summary),
1737 InitOutcome::Loaded => tracing::info!("{}", summary),
1738 InitOutcome::CrashFused { .. } | InitOutcome::Failed { .. } => {
1739 tracing::warn!("{}", summary);
1740 self.set_status_message(summary);
1741 }
1742 }
1743 }
1744
1745 /// Fire the `plugins_loaded` hook (design M2, §3.3 phase 2).
1746 pub fn fire_plugins_loaded_hook(&self) {
1747 #[cfg(feature = "plugins")]
1748 if self.plugin_manager.read().unwrap().is_active() {
1749 self.plugin_manager.read().unwrap().run_hook(
1750 "plugins_loaded",
1751 crate::services::plugins::hooks::HookArgs::PluginsLoaded {},
1752 );
1753 }
1754 }
1755
1756 /// Fire the `ready` hook (design M2, §3.3 phase 3).
1757 pub fn fire_ready_hook(&self) {
1758 #[cfg(feature = "plugins")]
1759 if self.plugin_manager.read().unwrap().is_active() {
1760 self.plugin_manager
1761 .read()
1762 .unwrap()
1763 .run_hook("ready", crate::services::plugins::hooks::HookArgs::Ready {});
1764 }
1765 }
1766
1767 /// Test-only accessor for the current effective config.
1768 #[doc(hidden)]
1769 pub fn config_for_tests(&self) -> &crate::config::Config {
1770 &self.config
1771 }
1772
1773 /// Test-only shim that dispatches an action through the normal path.
1774 #[doc(hidden)]
1775 pub fn dispatch_action_for_tests(&mut self, action: crate::input::keybindings::Action) {
1776 if let Err(e) = self.handle_action(action) {
1777 tracing::warn!("dispatch_action_for_tests: {e}");
1778 }
1779 }
1780
1781 /// Test-only accessor for the Live Grep Resume cache (issue #1796).
1782 #[doc(hidden)]
1783 pub fn live_grep_last_state_for_tests(
1784 &self,
1785 ) -> Option<&crate::services::live_grep_state::LiveGrepLastState> {
1786 self.active_window().live_grep_last_state.as_ref()
1787 }
1788
1789 /// Test-only setter for the Live Grep Resume cache.
1790 #[doc(hidden)]
1791 pub fn set_live_grep_last_state_for_tests(
1792 &mut self,
1793 state: Option<crate::services::live_grep_state::LiveGrepLastState>,
1794 ) {
1795 self.active_window_mut().live_grep_last_state = state;
1796 }
1797
1798 /// Test-only accessor for the split tree, so layout-shape
1799 /// regression tests can assert on the structure directly.
1800 #[doc(hidden)]
1801 pub fn split_manager_for_tests(&self) -> &crate::view::split::SplitManager {
1802 self.windows
1803 .get(&self.active_window)
1804 .and_then(|w| w.buffers.splits())
1805 .map(|(mgr, _)| mgr)
1806 .expect("active window must have a populated split layout")
1807 }
1808
1809 /// Test-only accessor for a leaf's `SplitViewState`, so tab-list
1810 /// regression tests can verify which buffers are open in a given
1811 /// pane (the dock should only contain the buffer the user
1812 /// actually asked for, not phantom placeholders).
1813 #[doc(hidden)]
1814 pub fn split_view_state_for_tests(
1815 &self,
1816 leaf: crate::model::event::LeafId,
1817 ) -> Option<&crate::view::split::SplitViewState> {
1818 self.windows
1819 .get(&self.active_window)
1820 .and_then(|w| w.buffers.splits())
1821 .map(|(_, vs)| vs)
1822 .expect("active window must have a populated split layout")
1823 .get(&leaf)
1824 }
1825
1826 /// Refresh the plugin-readable keybinding-label snapshot from
1827 /// the current keymap. Call this whenever a plugin is about to
1828 /// surface key hints in its UI (overlay headers, tooltips,
1829 /// menus) so the user's most-recent rebinds are reflected.
1830 ///
1831 /// Cheap — walks every typed `Action` × ~9 contexts; runs in
1832 /// well under a millisecond on this hardware. Cheaper than
1833 /// adding refresh hooks to every keymap-mutation site.
1834 #[cfg(feature = "plugins")]
1835 pub(crate) fn refresh_keybinding_labels_snapshot(&self) {
1836 if let Some(snapshot_handle) = self.plugin_manager.read().unwrap().state_snapshot_handle() {
1837 if let Ok(mut snapshot) = snapshot_handle.write() {
1838 populate_builtin_keybinding_labels(&mut snapshot, &self.keybindings);
1839 }
1840 }
1841 }
1842}
1843
1844/// Walk every typed `Action` and the contexts most relevant to UI
1845/// labels (`Normal`, `Prompt`, `Popup`, `FileExplorer`,
1846/// `CompositeBuffer`, `Settings`, `Terminal`), and populate the
1847/// snapshot's `keybinding_labels` map with `<action>\0<context>` →
1848/// formatted label (e.g. `"cycle_live_grep_provider\0prompt"` →
1849/// `"Alt+P"`). The plugin-side `editor.getKeybindingLabel(action,
1850/// mode)` API reads from this map, so plugins displaying hints in
1851/// their UIs (overlay headers, status messages) can look up the
1852/// user's *actual* binding rather than hardcoding a key string.
1853///
1854/// This runs once at startup. If the user later edits their keymap
1855/// without restarting fresh, the labels go stale. That's acceptable
1856/// for v1 — keymap edits today already require a restart for full
1857/// effect; a subsequent commit can wire snapshot refresh into the
1858/// keymap-reload path.
1859#[cfg(feature = "plugins")]
1860fn populate_builtin_keybinding_labels(
1861 snapshot: &mut crate::services::plugins::api::EditorStateSnapshot,
1862 keybindings: &std::sync::Arc<std::sync::RwLock<crate::input::keybindings::KeybindingResolver>>,
1863) {
1864 use crate::input::keybindings::{Action, KeyContext};
1865 let Ok(resolver) = keybindings.read() else {
1866 return;
1867 };
1868 let contexts = [
1869 KeyContext::Normal,
1870 KeyContext::Prompt,
1871 KeyContext::Popup,
1872 KeyContext::Completion,
1873 KeyContext::FileExplorer,
1874 KeyContext::Menu,
1875 KeyContext::Terminal,
1876 KeyContext::Settings,
1877 KeyContext::CompositeBuffer,
1878 ];
1879 // Clear stale built-in entries first so a re-populate after
1880 // the user un-binds an action drops the label rather than
1881 // leaving the old key visible. Entries whose `\0<context>`
1882 // suffix isn't in our list are left alone — those belong to
1883 // plugin-defined buffer modes and have their own
1884 // re-population path in `handle_register_mode`.
1885 let known_suffixes: Vec<String> = contexts
1886 .iter()
1887 .map(|c| format!("\0{}", c.to_when_clause()))
1888 .collect();
1889 snapshot
1890 .keybinding_labels
1891 .retain(|k, _| !known_suffixes.iter().any(|s| k.ends_with(s)));
1892 // Built-in actions plus any plugin actions that are actually bound
1893 // (e.g. the Universal Search scope toggles `live_grep_toggle_*`), so
1894 // `getKeybindingLabel` can resolve a plugin control's accelerator.
1895 let plugin_action_names = resolver.bound_plugin_action_names();
1896 let action_names = Action::all_action_names()
1897 .into_iter()
1898 .chain(plugin_action_names);
1899 for action_name in action_names {
1900 for ctx in &contexts {
1901 if let Some(label) = resolver.find_keybinding_for_action(&action_name, ctx.clone()) {
1902 let key = format!("{}\0{}", action_name, ctx.to_when_clause());
1903 snapshot.keybinding_labels.insert(key, label);
1904 }
1905 }
1906 }
1907}