Mountain/Binary/Main/AppLifecycle.rs
1//! # AppLifecycle (Binary/Main)
2//!
3//! ## RESPONSIBILITIES
4//!
5//! Application lifecycle management for the Tauri application setup and
6//! initialization. This module handles the complete setup process during the
7//! Tauri setup hook, including tray initialization, command registration, IPC
8//! server setup, window creation, environment configuration, and async service
9//! initialization.
10//!
11//! ## ARCHITECTURAL ROLE
12//!
13//! The AppLifecycle module is the **initialization layer** in Mountain's
14//! architecture:
15//!
16//! ```text
17//! Tauri Builder Setup ──► AppLifecycle::AppLifecycleSetup()
18//! │
19//! ├─► Tray Initialization
20//! ├─► Command Registration
21//! ├─► IPC Server Setup
22//! ├─► Window Building
23//! ├─► Environment Setup
24//! ├─► Runtime Setup
25//! └─► Async Service Initialization
26//! ```
27//!
28//! ## KEY COMPONENTS
29//!
30//! - **AppLifecycleSetup()**: Main setup function orchestrating all
31//! initialization
32//! - **Tray Initialization**: System tray icon with Dark/Light mode support
33//! - **Command Registration**: Native command registration with application
34//! state
35//! - **IPC Server**: Mountain IPC server for frontend-backend communication
36//! - **Window Building**: Main application window configuration
37//! - **MountainEnvironment**: Environment context for application services
38//! - **ApplicationRunTime**: Runtime context with scheduler and environment
39//! - **Status Reporter**: IPC status reporting initialization
40//! - **Advanced Features**: Advanced IPC features initialization
41//! - **Wind Sync**: Wind advanced sync initialization
42//! - **Async Initialization**: Post-setup async service initialization
43//!
44//! ## ERROR HANDLING
45//!
46//! Returns `Result<(), Box<dyn std::error::Error>>` for setup errors.
47//! Non-critical failures are logged but don't prevent application startup.
48//! Critical failures are propagated to prevent incomplete startup.
49//!
50//! ## LOGGING
51//!
52//! Comprehensive logging at INFO level for major setup steps,
53//! DEBUG level for detailed processing, and ERROR for failures.
54//! All logs are prefixed with `[Lifecycle] [ComponentName]`.
55//!
56//! ## PERFORMANCE CONSIDERATIONS
57//!
58//! - Async initialization spawned after main setup to avoid blocking
59//! - Services initialized only when needed
60//! - Clone operations minimized for Arc-wrapped shared state
61//!
62//! ## TODO
63//! - [ ] Add setup progress tracking
64//! - [ ] Implement setup timeout handling
65//! - [ ] Add setup rollback mechanism on failure
66
67use std::sync::Arc;
68
69use tauri::Manager;
70use Echo::Scheduler::Scheduler::Scheduler;
71
72use crate::dev_log;
73#[cfg(debug_assertions)]
74use crate::Binary::Debug::WebkitServer;
75
76/// Master "disable Land customisations" gate. Returns `true` when the
77/// `Disable=true` env var is set (PascalCase, single-word, matching
78/// the rest of Land's env surface in `.env.Land.Diagnostics`). When
79/// enabled, Mountain skips:
80/// - `WindowEvent::CloseRequested` intercept (Cmd+W routes natively)
81/// - Cocoon + Air sidecar spawn
82/// - The Wind / SkyBridge advanced-features registration
83/// - The smoke-test gating that would otherwise activate via Sky
84///
85/// Code paths are NOT removed - just skipped at runtime so a clean
86/// `Disable=` env var (or `Disable=false`) restores stock behaviour.
87fn IsLandDisabled() -> bool {
88 std::env::var("Disable")
89 .map(|Value| Value.eq_ignore_ascii_case("true"))
90 .unwrap_or(false)
91}
92
93use crate::{
94 // Crate root imports
95 ApplicationState::State::ApplicationState::ApplicationState,
96 // Binary submodule imports
97 Binary::Build::WindowBuild::WindowBuild as WindowBuildFn,
98 Binary::Extension::ExtensionPopulate::ExtensionPopulate as ExtensionPopulateFn,
99 Binary::Extension::ScanPathConfigure::ScanPathConfigure as ScanPathConfigureFn,
100 Binary::Register::AdvancedFeaturesRegister::AdvancedFeaturesRegister as AdvancedFeaturesRegisterFn,
101 Binary::Register::CommandRegister::CommandRegister as CommandRegisterFn,
102 Binary::Register::IPCServerRegister::IPCServerRegister as IPCServerRegisterFn,
103 Binary::Register::StatusReporterRegister::StatusReporterRegister as StatusReporterRegisterFn,
104 Binary::Register::WindSyncRegister::WindSyncRegister as WindSyncRegisterFn,
105 Binary::Service::AirStart::AirStart as AirStartFn,
106 Binary::Service::CocoonStart::CocoonStart as CocoonStartFn,
107 Binary::Service::ConfigurationInitialize::ConfigurationInitialize as ConfigurationInitializeFn,
108 Binary::Service::VineStart::VineStart as VineStartFn,
109 Binary::Tray::EnableTray as EnableTrayFn,
110 Environment::MountainEnvironment::MountainEnvironment,
111 RunTime::ApplicationRunTime::ApplicationRunTime,
112};
113
114/// Logs a checkpoint message at TRACE level.
115macro_rules! TraceStep {
116
117 ($($arg:tt)*) => {{
118
119 dev_log!("lifecycle", $($arg)*);
120 }};
121}
122
123/// Sets up the application lifecycle during Tauri initialization.
124///
125/// This function coordinates all setup operations:
126/// 1. System tray initialization
127/// 2. Native command registration
128/// 3. IPC server initialization
129/// 4. Main window creation
130/// 5. Mountain environment setup
131/// 6. Application runtime setup
132/// 7. Status reporter initialization
133/// 8. Advanced features initialization
134/// 9. Wind advanced sync initialization
135/// 10. Async post-setup initialization
136///
137/// # Parameters
138///
139/// * `app` - Mutable reference to Tauri App instance
140/// * `app_handle` - Cloned Tauri AppHandle for async operations
141/// * `localhost_url` - URL for the development server
142/// * `scheduler` - Arc-wrapped Echo Scheduler
143/// * `app_state` - Application state clone
144///
145/// # Returns
146///
147/// `Result<(), Box<dyn std::error::Error>>` - Ok on success, Err on critical
148/// failure
149pub fn AppLifecycleSetup(
150 app:&mut tauri::App,
151
152 app_handle:tauri::AppHandle,
153
154 localhost_url:String,
155
156 scheduler:Arc<Scheduler>,
157
158 app_state:Arc<ApplicationState>,
159) -> Result<(), Box<dyn std::error::Error>> {
160 dev_log!("lifecycle", "[Lifecycle] [Setup] Setup hook started.");
161
162 dev_log!("lifecycle", "[Lifecycle] [Setup] LocalhostUrl={}", localhost_url);
163
164 let app_handle_for_setup = app_handle.clone();
165
166 TraceStep!("[Lifecycle] [Setup] AppHandle acquired.");
167
168 // -------------------------------------------------------------------------
169 // [UI] [Tray] Initialize System Tray
170 // -------------------------------------------------------------------------
171 dev_log!("lifecycle", "[UI] [Tray] Initializing system tray...");
172
173 if let Err(Error) = EnableTrayFn::enable_tray(app) {
174 dev_log!("lifecycle", "error: [UI] [Tray] Failed to enable tray: {}", Error);
175 }
176
177 // -------------------------------------------------------------------------
178 // [Lifecycle] [Commands] Register native commands
179 // -------------------------------------------------------------------------
180 dev_log!("lifecycle", "[Lifecycle] [Commands] Registering native commands...");
181
182 if let Err(e) = CommandRegisterFn(&app_handle_for_setup, &app_state) {
183 dev_log!("lifecycle", "error: [Lifecycle] [Commands] Failed to register commands: {}", e);
184 }
185
186 dev_log!("lifecycle", "[Lifecycle] [Commands] Native commands registered.");
187
188 // -------------------------------------------------------------------------
189 // [Lifecycle] [IPC] Initialize IPC Server
190 // -------------------------------------------------------------------------
191 dev_log!("lifecycle", "[Lifecycle] [IPC] Initializing Mountain IPC Server...");
192
193 if let Err(e) = IPCServerRegisterFn(&app_handle_for_setup) {
194 dev_log!("lifecycle", "error: [Lifecycle] [IPC] Failed to register IPC server: {}", e);
195 }
196
197 // -------------------------------------------------------------------------
198 // [UI] [Window] Build main window
199 // -------------------------------------------------------------------------
200 dev_log!("lifecycle", "[UI] [Window] Building main window...");
201
202 let MainWindow = WindowBuildFn(app, localhost_url.clone());
203
204 dev_log!("lifecycle", "[UI] [Window] Main window ready.");
205
206 // DevTools auto-open is opt-in via the PascalCase env var
207 // `Inspect=1` (or any non-empty value other than `0`). Naming
208 // follows Land's single-word PascalCase verb convention -
209 // see `.env.Land.Diagnostics` for the documented set.
210 //
211 // Auto-opening DevTools on every debug launch was the direct
212 // cause of "I can't type or fire keybindings": the DevTools
213 // window steals macOS keyboard focus the moment it appears, so
214 // the main webview never becomes first responder and every
215 // keystroke goes to DevTools (or the system menu) instead of
216 // the workbench. The keybinding shortcut `Cmd+Alt+I` (Tauri's
217 // default) and the right-click "Inspect" entry both still
218 // work when needed.
219 #[cfg(debug_assertions)]
220 {
221 let WantDevTools = std::env::var("Inspect")
222 .map(|Value| !Value.is_empty() && Value != "0")
223 .unwrap_or(false);
224
225 if WantDevTools {
226 dev_log!("lifecycle", "[UI] [Window] Inspect=1 set: opening DevTools.");
227
228 MainWindow.open_devtools();
229 } else {
230 dev_log!(
231 "lifecycle",
232 "[UI] [Window] Debug build: DevTools auto-open suppressed (export Inspect=1 to override)."
233 );
234 }
235 }
236
237 #[cfg(debug_assertions)]
238 {
239 let enable_debug_server = std::env::var("DebugServer").map(|v| v != "0" && !v.is_empty()).unwrap_or(false);
240 if enable_debug_server {
241 dev_log!(
242 "lifecycle",
243 "[Debug] [Webkit] Debug server starting on port {}...",
244 std::env::var("DebugServerPort")
245 .ok()
246 .and_then(|p| p.parse().ok())
247 .unwrap_or(9933)
248 );
249 WebkitServer::install(&MainWindow);
250 }
251 }
252
253 // -------------------------------------------------------------------------
254 // [UI] [Window] Intercept CloseRequested so Cmd+W (and the macOS app
255 // menu's Window > Close item) routes through the workbench instead of
256 // killing the whole window.
257 //
258 // On macOS, Tauri 2.x installs a default app menu that maps Cmd+W to
259 // NSWindow's `performClose:`. The webview's keydown handler never gets
260 // the event because the menu wins the responder chain. The result the
261 // user sees: hitting Cmd+W to close a tab nukes the entire editor.
262 //
263 // The fix is the standard Electron-style handshake:
264 // 1. Mountain prevents the close.
265 // 2. Mountain emits `sky://window/close-requested` to the webview.
266 // 3. Sky listens, asks the workbench to close the active editor; if there is
267 // no active editor (or the workbench refuses), Sky calls
268 // `nativeHost:closeWindow`, which uses `WebviewWindow::destroy()` to tear
269 // the window down without re-firing CloseRequested.
270 if IsLandDisabled() {
271 dev_log!(
272 "window",
273 "[UI] [Window] Disable=true: CloseRequested intercept SKIPPED (Cmd+W will close window natively)"
274 );
275 } else {
276 use tauri::Emitter;
277
278 let CloseEmitter = MainWindow.clone();
279
280 MainWindow.on_window_event(move |Event| {
281 if let tauri::WindowEvent::CloseRequested { api, .. } = Event {
282 api.prevent_close();
283 let _ = CloseEmitter.emit("sky://window/close-requested", ());
284 dev_log!("window", "[UI] [Window] CloseRequested intercepted; forwarded to webview");
285 }
286 });
287 }
288
289 // -------------------------------------------------------------------------
290 // [Backend] [Dirs] Ensure userdata directories exist
291 // -------------------------------------------------------------------------
292 {
293 let PathResolver = app.path();
294
295 let AppDataDir = PathResolver.app_data_dir().unwrap_or_default();
296
297 let LogDir = PathResolver.app_log_dir().unwrap_or_default();
298
299 let HomeDir = PathResolver.home_dir().unwrap_or_default();
300
301 // Set the canonical userdata base so WindServiceHandlers resolves
302 // /User/... paths to the real Tauri app_data_dir (not hardcoded "Land").
303 crate::IPC::WindServiceHandlers::Utilities::UserdataDir::set_userdata_base_dir(
304 AppDataDir.to_string_lossy().to_string(),
305 );
306
307 // Set the real filesystem root for /Static/Application/ path mapping.
308 // In dev mode, Tauri serves from ../Sky/Target relative to Mountain.
309 // Tauri's resource_dir gives us the frontendDist path.
310 // Resolve Sky/Target via Tauri first; fall back to executable-
311 // relative bundle and monorepo layouts so raw-binary launches
312 // (e.g. running `Target/release/<bin>` directly from a terminal)
313 // still resolve `STATIC_APPLICATION_ROOT` correctly. Without this
314 // fallback, release binaries launched outside `.app` had an
315 // empty static root, causing extension-contributed icons served
316 // via `vscode-file://` to 404 (GitLens / Roo / Claude side bar
317 // icons missing).
318 let SkyTargetDir = PathResolver
319 .resource_dir()
320 .ok()
321 .filter(|P| !P.as_os_str().is_empty() && P.exists())
322 .unwrap_or_else(|| {
323 let ExeParent = std::env::current_exe()
324 .ok()
325 .and_then(|Exe| Exe.parent().map(|P| P.to_path_buf()))
326 .unwrap_or_default();
327
328 // `.app/Contents/MacOS/<bin>` → `Contents/Resources/`
329 let BundleResources = ExeParent.join("../Resources");
330 if BundleResources.exists() {
331 return BundleResources;
332 }
333
334 // Monorepo layout: `Element/Mountain/Target/<profile>/<bin>` →
335 // `Element/Sky/Target/`. Used by both debug runs and raw-
336 // release launches from inside the repo.
337 let RepoSky = ExeParent.join("../../../Sky/Target");
338 if RepoSky.exists() {
339 return RepoSky;
340 }
341
342 // Last resort: alongside the binary. A broken bundle layout
343 // then surfaces as visible "asset not found" 404s instead of
344 // silent empty-string joins.
345 ExeParent
346 });
347
348 crate::IPC::WindServiceHandlers::Utilities::ApplicationRoot::set_static_application_root(
349 SkyTargetDir.to_string_lossy().to_string(),
350 );
351
352 dev_log!(
353 "lifecycle",
354 "[Lifecycle] [Dirs] Static application root: {}",
355 SkyTargetDir.display()
356 );
357
358 // Every directory VS Code may stat or readdir during startup
359 let Dirs = [
360 // User profile directories
361 AppDataDir.join("User"),
362 AppDataDir.join("User/globalStorage"),
363 AppDataDir.join("User/workspaceStorage"),
364 AppDataDir.join("User/workspaceStorage/vscode-chat-images"),
365 AppDataDir.join("User/extensions"),
366 AppDataDir.join("User/profiles/__default__profile__"),
367 AppDataDir.join("User/snippets"),
368 AppDataDir.join("User/prompts"),
369 AppDataDir.join("User/caches"),
370 // Configuration cache
371 AppDataDir.join("CachedConfigurations/defaults/__default__profile__-configurationDefaultsOverrides"),
372 // Log directories - VS Code stats {logsPath}/window1/output_{timestamp}
373 LogDir.join("window1"),
374 // System extensions directory - VS Code scans appRoot/../extensions
375 // which resolves to /Static/Application/extensions (mapped to Sky Target).
376 SkyTargetDir.join("Static/Application/extensions"),
377 // Agent directories VS Code probes for (create to avoid stat errors)
378 HomeDir.join(".claude/agents"),
379 HomeDir.join(".copilot/agents"),
380 ];
381
382 for Dir in &Dirs {
383 if let Err(Error) = std::fs::create_dir_all(Dir) {
384 dev_log!(
385 "lifecycle",
386 "warn: [Lifecycle] [Dirs] Failed to create {}: {}",
387 Dir.display(),
388 Error
389 );
390 }
391 }
392
393 // Default empty files VS Code reads on startup
394 let DefaultFiles:&[(&std::path::Path, &str)] = &[
395 (&AppDataDir.join("User/settings.json"), "{}"),
396 (&AppDataDir.join("User/keybindings.json"), "[]"),
397 (&AppDataDir.join("User/tasks.json"), "{}"),
398 (&AppDataDir.join("User/extensions.json"), "[]"),
399 (&AppDataDir.join("User/mcp.json"), "{}"),
400 ];
401
402 for (FilePath, DefaultContent) in DefaultFiles {
403 if !FilePath.exists() {
404 let _ = std::fs::write(FilePath, DefaultContent);
405 }
406 }
407
408 // Atom I7: ensure `security.workspace.trust.enabled: false` lives
409 // in User/settings.json. Without it, opening the Land repo as a
410 // workspace triggers VS Code's workspace-trust gate: built-in
411 // extensions whose `location` is inside the picked folder are
412 // marked `DisabledByTrustRequirement` (see
413 // `extensionEnablementService.ts:549`). Since our built-ins ship
414 // under `Element/Sky/Target/Static/Application/extensions/` -
415 // which IS inside the repo - any user picking the repo as a
416 // workspace hits this filter for every extension. Disabling the
417 // trust system wholesale is the correct Land-level policy; we're
418 // a personal editor, not a multi-user sandbox. Users can opt
419 // back in by flipping this key in their User/settings.json.
420 {
421 let SettingsPath = AppDataDir.join("User/settings.json");
422
423 let Current = std::fs::read_to_string(&SettingsPath).unwrap_or_else(|_| "{}".to_string());
424
425 if !Current.contains("\"security.workspace.trust.enabled\"") {
426 if let Ok(mut Parsed) = serde_json::from_str::<serde_json::Value>(&Current) {
427 if !Parsed.is_object() {
428 Parsed = serde_json::json!({});
429 }
430
431 if let Some(Obj) = Parsed.as_object_mut() {
432 Obj.insert("security.workspace.trust.enabled".to_string(), serde_json::Value::Bool(false));
433 }
434
435 if let Ok(Serialized) = serde_json::to_string_pretty(&Parsed) {
436 let _ = std::fs::write(&SettingsPath, Serialized);
437
438 dev_log!(
439 "lifecycle",
440 "[Lifecycle] [Dirs] Injected default 'security.workspace.trust.enabled=false' into {}",
441 SettingsPath.display()
442 );
443 }
444 }
445 }
446 }
447
448 // Set GlobalMementoPath now that we know the real Tauri app data dir
449 if let Ok(mut Path) = app_state.GlobalMementoPath.lock() {
450 *Path = AppDataDir.join("User/globalStorage/global.json");
451 dev_log!("lifecycle", "[Lifecycle] [Dirs] GlobalMementoPath: {}", Path.display());
452 }
453
454 dev_log!(
455 "lifecycle",
456 "[Lifecycle] [Dirs] Userdata directories ensured at {}",
457 AppDataDir.display()
458 );
459 }
460
461 // -------------------------------------------------------------------------
462 // [Backend] [Env] Mountain environment
463 // -------------------------------------------------------------------------
464 dev_log!("lifecycle", "[Backend] [Env] Creating MountainEnvironment...");
465
466 let Environment = Arc::new(MountainEnvironment::Create(app_handle_for_setup.clone(), app_state.clone()));
467
468 dev_log!("lifecycle", "[Backend] [Env] MountainEnvironment ready.");
469
470 // -------------------------------------------------------------------------
471 // [Backend] [Runtime] ApplicationRunTime
472 // -------------------------------------------------------------------------
473 dev_log!("lifecycle", "[Backend] [Runtime] Creating ApplicationRunTime...");
474
475 let Runtime = Arc::new(ApplicationRunTime::Create(scheduler.clone(), Environment.clone()));
476
477 app_handle_for_setup.manage(Runtime.clone());
478
479 dev_log!("lifecycle", "[Backend] [Runtime] ApplicationRunTime managed.");
480
481 // -------------------------------------------------------------------------
482 // [Lifecycle] [IPC] Initialize Status Reporter
483 // -------------------------------------------------------------------------
484 if let Err(e) = StatusReporterRegisterFn(&app_handle_for_setup, Runtime.clone()) {
485 dev_log!(
486 "lifecycle",
487 "error: [Lifecycle] [IPC] Failed to initialize status reporter: {}",
488 e
489 );
490 }
491
492 // -------------------------------------------------------------------------
493 // [Lifecycle] [IPC] Initialize Advanced Features
494 // -------------------------------------------------------------------------
495 if let Err(e) = AdvancedFeaturesRegisterFn(&app_handle_for_setup, Runtime.clone()) {
496 dev_log!(
497 "lifecycle",
498 "error: [Lifecycle] [IPC] Failed to initialize advanced features: {}",
499 e
500 );
501 }
502
503 // -------------------------------------------------------------------------
504 // [Lifecycle] [IPC] Initialize Wind Advanced Sync
505 // -------------------------------------------------------------------------
506 if let Err(e) = WindSyncRegisterFn(&app_handle_for_setup, Runtime.clone()) {
507 dev_log!(
508 "lifecycle",
509 "error: [Lifecycle] [IPC] Failed to initialize wind advanced sync: {}",
510 e
511 );
512 }
513
514 // -------------------------------------------------------------------------
515 // [Lifecycle] [PostSetup] Async initialization work
516 // -------------------------------------------------------------------------
517 let PostSetupAppHandle = app_handle_for_setup.clone();
518
519 let PostSetupEnvironment = Environment.clone();
520
521 tauri::async_runtime::spawn(async move {
522 dev_log!("lifecycle", "[Lifecycle] [PostSetup] Starting...");
523 let PostSetupStart = crate::IPC::DevLog::NowNano::Fn();
524 let AppStateForSetup = PostSetupEnvironment.ApplicationState.clone();
525 TraceStep!("[Lifecycle] [PostSetup] AppState cloned.");
526
527 // [Config]
528 // First-pass merge runs against the empty `ScannedExtensions`
529 // map (the scan happens later in this lifecycle). User /
530 // workspace `settings.json` overrides land here, but extension
531 // `contributes.configuration.properties[*].default` keys cannot
532 // be collected yet. Without a second pass after the scan,
533 // `getConfiguration('git').get('enabled')` returns undefined,
534 // vscode.git's `_activate` takes the `if (!enabled) return;`
535 // short-circuit, and the SCM viewlet stays empty even though
536 // Cocoon successfully activated the extension. The second pass
537 // below repairs this without disturbing the existing initial
538 // merge that the rest of bootstrap depends on.
539 let ConfigStart = crate::IPC::DevLog::NowNano::Fn();
540 let _ = ConfigurationInitializeFn(&PostSetupEnvironment).await;
541 crate::otel_span!("lifecycle:config:initialize", ConfigStart);
542
543 // [Workspace] [Trust] Desktop app - trust local workspace by default
544 AppStateForSetup.Workspace.SetTrustStatus(true);
545
546 // [Extensions] [ScanPaths]
547 let ExtScanStart = crate::IPC::DevLog::NowNano::Fn();
548 let _ = ScanPathConfigureFn(&AppStateForSetup);
549
550 // [Extensions] [Scan]
551 let _ = ExtensionPopulateFn(PostSetupAppHandle.clone(), &AppStateForSetup).await;
552 crate::otel_span!("lifecycle:extensions:scan", ExtScanStart);
553
554 // [Config] [Re-merge] - now that ScannedExtensions is populated,
555 // run the merge a second time so `collect_default_configurations`
556 // can walk extension manifests and seed `git.enabled = true`,
557 // `git.path = null`, `git.autoRepositoryDetection = true`, plus
558 // every other `contributes.configuration.properties[*].default`
559 // the 113 scanned extensions declare. The first-pass merge logged
560 // "0 top-level keys"; this pass should log a much larger count.
561 // User / workspace overrides applied during the first pass are
562 // preserved because the merge order is Default → User → Workspace
563 // and the cached User/Workspace JSON files are re-read each call.
564 let ConfigRemergeStart = crate::IPC::DevLog::NowNano::Fn();
565 let _ = ConfigurationInitializeFn(&PostSetupEnvironment).await;
566 crate::otel_span!("lifecycle:config:remerge-after-extension-scan", ConfigRemergeStart);
567
568 // [Vine] [gRPC]
569 let VineStart = crate::IPC::DevLog::NowNano::Fn();
570 let _ = VineStartFn(
571 PostSetupAppHandle.clone(),
572 "127.0.0.1:50051".to_string(),
573 "127.0.0.1:50052".to_string(),
574 )
575 .await;
576 crate::otel_span!("lifecycle:vine:start", VineStart);
577
578 // [Cocoon] [Sidecar] - skipped when Disable=true so the
579 // workbench loads without an extension host. Useful for
580 // bisecting whether typing-input regressions originate in
581 // Cocoon's gRPC handlers or upstream / Tauri / WKWebView.
582 if IsLandDisabled() {
583 dev_log!(
584 "cocoon",
585 "[Cocoon] [Start] Disable=true: Cocoon spawn SKIPPED (workbench will run without extensions)"
586 );
587 } else {
588 let CocoonStart = crate::IPC::DevLog::NowNano::Fn();
589 let _ = CocoonStartFn(&PostSetupAppHandle, &PostSetupEnvironment).await;
590 crate::otel_span!("lifecycle:cocoon:start", CocoonStart);
591 }
592
593 // [Air] [Sidecar] - daemon for updates / downloads / signing /
594 // indexing / system monitoring. Spawn parallel to Cocoon; both
595 // are sidecars in the Vine pool. AirStart returns Ok(()) even
596 // on spawn failure (graceful degradation - workbench works
597 // without Air, just without those background capabilities).
598 // Skipped under `Disable=true` for parity with Cocoon.
599 if IsLandDisabled() {
600 dev_log!("grpc", "[Air] [Start] Disable=true: Air spawn SKIPPED");
601 } else {
602 let AirStartT0 = crate::IPC::DevLog::NowNano::Fn();
603 let _ = AirStartFn(&PostSetupAppHandle, &PostSetupEnvironment).await;
604 crate::otel_span!("lifecycle:air:start", AirStartT0);
605 }
606
607 // [Lifecycle] [Phase] Advance Starting → Ready now that the gRPC
608 // server + Cocoon sidecar + extension scan have all finished. Wind's
609 // `TauriChannel("lifecycle").listen("onDidChangePhase")` subscribers
610 // fire so long-running services can start pulling.
611 AppStateForSetup.Feature.Lifecycle.AdvanceAndBroadcast(2, &PostSetupAppHandle);
612
613 // Schedule a background transition to Restored (3), then Eventually
614 // (4). Sky/Wind are the authoritative signal - they call
615 // `lifecycle:advancePhase` over Tauri IPC when the workbench is
616 // truly interactive (`Restored`) and when late-binding extensions
617 // should stop blocking (`Eventually`). `AdvanceAndBroadcast`
618 // rejects backwards/same-phase advances (LifecyclePhaseState.rs:53),
619 // so the timers below are pure fallbacks: if Sky has already driven
620 // the phase, these become no-ops and log nothing visible.
621 //
622 // The windows are deliberately generous - a debug-electron cold
623 // boot with 98 extensions has been observed to finish its
624 // `$activateByEvent("*")` burst at ~3.5 s on an M4 mini and
625 // noticeably later on older hardware. The previous 2 s / 5 s
626 // timings ran the risk of flipping Restored while the burst was
627 // still in flight, which prematurely unblocked services gated on
628 // "the editor is interactive". 8 s / 15 s keeps a safety margin
629 // without visibly delaying late-binding extensions that legitimately
630 // need Eventually to fire.
631 let LifecycleStateClone = AppStateForSetup.Feature.Lifecycle.clone();
632 let AppHandleForPhase = PostSetupAppHandle.clone();
633 tauri::async_runtime::spawn(async move {
634 tokio::time::sleep(tokio::time::Duration::from_millis(8_000)).await;
635 if LifecycleStateClone.GetPhase() < 3 {
636 dev_log!(
637 "lifecycle",
638 "[Lifecycle] [Fallback] Sky did not advance to Restored within 8s; Mountain auto-advancing \
639 (current phase={})",
640 LifecycleStateClone.GetPhase()
641 );
642 LifecycleStateClone.AdvanceAndBroadcast(3, &AppHandleForPhase);
643 }
644 tokio::time::sleep(tokio::time::Duration::from_millis(15_000)).await;
645 if LifecycleStateClone.GetPhase() < 4 {
646 dev_log!(
647 "lifecycle",
648 "[Lifecycle] [Fallback] Sky did not advance to Eventually within 23s total; Mountain \
649 auto-advancing (current phase={})",
650 LifecycleStateClone.GetPhase()
651 );
652 LifecycleStateClone.AdvanceAndBroadcast(4, &AppHandleForPhase);
653 }
654 });
655
656 // Hidden-until-ready safety timer: `WindowBuild.rs` creates the main
657 // window with `.visible(false)` and the `lifecycle:advancePhase(3)`
658 // handler reveals it once Sky reports the workbench DOM is attached.
659 // If Sky crashes before phase 3 reaches Mountain, the window would
660 // stay invisible forever. Force-reveal after 3 s so the user always
661 // sees SOMETHING even on a completely broken Sky. 3 s matches the
662 // observed p95 of `[Lifecycle] [Phase] Advance Ready` on a cold
663 // M-series boot, so the timer rarely fires on a healthy path.
664 let AppHandleForEmergencyShow = PostSetupAppHandle.clone();
665 tauri::async_runtime::spawn(async move {
666 tokio::time::sleep(tokio::time::Duration::from_millis(3_000)).await;
667 if let Some(MainWindow) = AppHandleForEmergencyShow.get_webview_window("main") {
668 if let Ok(false) = MainWindow.is_visible() {
669 dev_log!(
670 "lifecycle",
671 "warn: [Lifecycle] [Fallback] main window hidden at +3s; force-revealing to avoid an \
672 invisible-window lockup (Sky never reached phase 3)"
673 );
674 let _ = MainWindow.show();
675 let _ = MainWindow.set_focus();
676 }
677 }
678 });
679
680 crate::otel_span!("lifecycle:postsetup:complete", PostSetupStart);
681 dev_log!("lifecycle", "[Lifecycle] [PostSetup] Complete. System ready.");
682 });
683
684 Ok(())
685}