sk-app 0.3.0

The Skathi host: windows, the event loop, the JS bindings and the embedding API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
//! Skathi host shell: JavaScript (JSC via redjs) inside a gpui window.
//!
//! [`dev`] (reads `packages/cli/dist`, polls `changes.json` for HMR) or [`prod`]
//! (`--features prod`, runs the SKPK [`payload`] stamped into the exe) is aliased as [`boot_mode`];
//! both expose `boot(&JsRuntime)` and `poll_frame(frame_no: u32)`.
//!
//! Run through [`run_app`]: [`run_exe`] (the process is the app) or [`embed`] (another program
//! runs the engine on its own thread).

use std::cell::RefCell;

use gpui::{
    div, prelude::*, px, rgba, size, App, Bounds, Context, TitlebarOptions, WeakEntity, Window,
    WindowBounds, WindowControlArea, WindowOptions,
};
use gpui_platform::application;
use sk_runtime::runtime::{PUMP_MICROTASKS, PUMP_RAF, PUMP_TIMERS};
use sk_runtime::{host_fn, with_published, with_published_app, JsRuntime, Phase};

mod background;
#[cfg(feature = "prod")]
mod bytecode;
#[cfg(not(feature = "prod"))]
mod dev;
mod idle;
// `sk_devtools` is emitted by build.rs: every dev build, plus a release that asked for devtools.
#[cfg(sk_devtools)]
mod devtools;
// `pub` for the exe's `#[global_allocator]` and for embedders, which declare the allocator themselves.
#[cfg(sk_devtools)]
pub mod heapcount;
/// Allocator an embedder can install to enable native allocation recording.
#[cfg(sk_devtools)]
pub use heapcount::Counting as HostAllocator;
#[cfg(not(sk_devtools))]
pub use std::alloc::System as HostAllocator;
mod http_client;
// The unit tests are the library's own binary, and some read the counts.
#[cfg(all(sk_devtools, test))]
#[global_allocator]
static GLOBAL: heapcount::Counting = heapcount::Counting;
#[cfg(not(target_os = "windows"))]
mod chrome_posix;
#[cfg(target_os = "windows")]
#[doc(hidden)]
pub mod consent_window;
#[cfg(target_os = "windows")]
mod content_dialog;
#[doc(hidden)]
pub mod crash_window;
mod dialogs;
pub mod embed;
pub mod hotkeys;
#[cfg(sk_devtools)]
mod inspector;
pub mod js;
mod json;
mod mapped_file;
#[cfg(feature = "audio")]
mod microphone;
#[cfg(feature = "native-aot")]
mod native_aot;
mod occlusion;
mod owner;
mod payload;
mod perf;
mod popout;
mod popout_win;
#[cfg(feature = "prod")]
mod prod;
mod quiet;
mod reclaim;
mod reload;
#[cfg(all(feature = "webgpu", target_os = "windows"))]
mod shared_gpu;
mod shutdown;
mod slot;
pub mod tray;
mod window;

#[cfg(not(feature = "prod"))]
use dev as boot_mode;
#[cfg(feature = "prod")]
use prod as boot_mode;

/// Vue's esm-bundler build reads three flags off globalThis (bun refuses to inline them); must run
/// BEFORE the app bundle, since ESM import hoisting would put the bundle's Vue code first.
/// Generated by `bun run preludes` and checked in, so `cargo build` needs no JS toolchain.
const PRELUDE_JS: &str = include_str!("prelude.js");

/// The windowing surface's JS half, evaluated after [`PRELUDE_JS`] and before the app bundle.
const WINDOW_PRELUDE_JS: &str = include_str!("window.prelude.js");

thread_local! {
    static FRAME_NO: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
    static FIRST_WAVE_RELEASED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// The first JS wave waits one frame for the first draw, so rAF and `onMounted` timers measure a
/// laid-out tree instead of reading 0. Later waves are never delayed by this.
fn first_wave_waits(window: &mut Window) -> bool {
    if FIRST_WAVE_RELEASED.with(|c| c.get()) {
        return false;
    }
    FIRST_WAVE_RELEASED.with(|c| c.set(true));
    window.refresh();
    true
}

// `SK_LOG` turns on gpui's own log records: a bare level or `RUST_LOG`-style per-target directives
// (`SK_LOG=off,gpui=debug`). Records are teed into `sk_tree::log`'s thread-local ring: hence
// [`OFF_THREAD`] and [`drain_log_tee`].
struct StderrLogger {
    /// Longest prefix first, so `gpui::window` beats `gpui`.
    directives: Vec<(String, log::LevelFilter)>,
    default: log::LevelFilter,
}

/// `::`-boundary-aware prefix match: `gpui_windows` must not match a `gpui` directive.
fn target_matches(target: &str, prefix: &str) -> bool {
    target.len() >= prefix.len()
        && target.starts_with(prefix)
        && (target.len() == prefix.len() || target[prefix.len()..].starts_with("::"))
}

impl StderrLogger {
    fn level_for(&self, target: &str) -> log::LevelFilter {
        for (prefix, l) in &self.directives {
            if target_matches(target, prefix) {
                return *l;
            }
        }
        self.default
    }
}

impl log::Log for StderrLogger {
    fn enabled(&self, metadata: &log::Metadata) -> bool {
        metadata.level() <= self.level_for(metadata.target())
    }
    fn log(&self, record: &log::Record) {
        if !self.enabled(record.metadata()) {
            return;
        }
        let line = format!("[{} {}] {}", record.level(), record.target(), record.args());
        // stderr first: unbuffered, so a message logged on the way to `abort()` still gets out.
        eprintln!("{line}");
        tee(record.level(), line);
    }
    fn flush(&self) {}
}

static MAIN_THREAD: std::sync::OnceLock<std::thread::ThreadId> = std::sync::OnceLock::new();
static OFF_THREAD: std::sync::Mutex<Vec<(&'static str, String)>> =
    std::sync::Mutex::new(Vec::new());
/// Bounds a wedged subsystem logging in a loop.
const OFF_THREAD_CAP: usize = 512;

fn kind_of(level: log::Level) -> &'static str {
    match level {
        log::Level::Error => "error",
        log::Level::Warn => "warn",
        _ => "log",
    }
}

fn tee(level: log::Level, line: String) {
    if !sk_tree::log::is_enabled() {
        return;
    }
    let kind = kind_of(level);
    if MAIN_THREAD.get() == Some(&std::thread::current().id()) {
        sk_tree::log::record(kind, line);
        return;
    }
    if let Ok(mut queue) = OFF_THREAD.lock() {
        if queue.len() >= OFF_THREAD_CAP {
            queue.remove(0); // drop the OLDEST: a fatal is always the newest
        }
        queue.push((kind, line));
    }
}

/// `try_lock`: a frame never blocks on a logging thread.
fn drain_log_tee() {
    if !sk_tree::log::is_enabled() {
        return;
    }
    let Ok(mut queue) = OFF_THREAD.try_lock() else {
        return;
    };
    for (kind, line) in queue.drain(..) {
        sk_tree::log::record(kind, line);
    }
}

fn parse_level(word: &str) -> Option<log::LevelFilter> {
    match word.trim().to_ascii_lowercase().as_str() {
        "" | "info" | "1" | "true" => Some(log::LevelFilter::Info),
        "off" | "0" | "false" => Some(log::LevelFilter::Off),
        "error" => Some(log::LevelFilter::Error),
        "warn" => Some(log::LevelFilter::Warn),
        "debug" => Some(log::LevelFilter::Debug),
        "trace" => Some(log::LevelFilter::Trace),
        _ => None,
    }
}

fn install_logger() {
    let _ = MAIN_THREAD.set(std::thread::current().id());
    let spec = std::env::var("SK_LOG").unwrap_or_default();
    let mut default = log::LevelFilter::Off;
    let mut directives: Vec<(String, log::LevelFilter)> = Vec::new();
    let mut saw_bare = false;
    for part in spec.split(',') {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }
        match part.split_once('=') {
            Some((target, level)) => match parse_level(level) {
                Some(l) => directives.push((target.trim().to_string(), l)),
                None => eprintln!("[sk] SK_LOG: {level:?} is not a level — ignoring {part:?}"),
            },
            None => match parse_level(part) {
                Some(l) => {
                    default = l;
                    saw_bare = true;
                }
                None => eprintln!("[sk] SK_LOG={part:?} is not a level — using info"),
            },
        }
    }
    // `SK_LOG=gpui=debug` alone means that target only; an unset `SK_LOG` must stay Off.
    if !saw_bare && directives.is_empty() && !spec.is_empty() {
        default = log::LevelFilter::Info;
    }
    directives.sort_by(|a, b| b.0.len().cmp(&a.0.len()));
    let max = directives
        .iter()
        .map(|(_, l)| *l)
        .chain([default])
        .max()
        .unwrap_or(default);
    let logger: &'static StderrLogger = Box::leak(Box::new(StderrLogger {
        directives,
        default,
    }));
    if log::set_logger(logger).is_ok() {
        // Must be the loosest directive, or records are dropped before `enabled` sees their target.
        log::set_max_level(max);
    }
}

#[cfg(test)]
#[test]
fn devtools_are_in_every_build_that_did_not_opt_out() {
    assert_eq!(cfg!(sk_devtools), !cfg!(feature = "no-devtools"));
}

#[cfg(test)]
mod logger_tests {
    use super::*;
    use log::LevelFilter as L;

    fn logger(spec: &[(&str, L)], default: L) -> StderrLogger {
        let mut directives: Vec<(String, L)> =
            spec.iter().map(|(t, l)| ((*t).to_string(), *l)).collect();
        directives.sort_by(|a, b| b.0.len().cmp(&a.0.len()));
        StderrLogger {
            directives,
            default,
        }
    }

    #[test]
    fn the_longest_matching_directive_wins() {
        let l = logger(&[("gpui", L::Warn), ("gpui::window", L::Debug)], L::Off);
        assert_eq!(l.level_for("gpui::window"), L::Debug);
        assert_eq!(l.level_for("gpui::platform"), L::Warn);
        assert_eq!(l.level_for("sk_tree"), L::Off);
    }

    #[test]
    fn target_boundaries_are_module_separators() {
        assert!(target_matches("gpui::window", "gpui"));
        assert!(target_matches("gpui", "gpui"));
        assert!(!target_matches("gpui_windows::events", "gpui"));
    }
}

struct Shell;

thread_local! {
    static SHELL: RefCell<Option<WeakEntity<Shell>>> = const { RefCell::new(None) };
    /// The primary window itself, not its root view: the multi-window repaint fan-out runs inside
    /// input listeners, where the root view may already be borrowed.
    static MAIN_WINDOW: std::cell::Cell<Option<gpui::AnyWindowHandle>> =
        const { std::cell::Cell::new(None) };
}

/// The forced synchronous layout a DOM measurement asks for (`sk_tree::set_sync_layout`): draws the
/// primary window once. `with_app` is `None` inside a real frame, so this never runs inside a draw.
///
/// Unleased window (boot, first mount): through its handle. Later waves run leased, where
/// `handle.update` fails, so the draw goes through the window that wave published.
///
/// Never inside a gpui input listener: gpui has the frame's listeners taken out, and a draw would
/// swap the frame under them. The read stays stale there.
fn sync_layout() {
    let Some(handle) = MAIN_WINDOW.with(|w| w.get()) else {
        return;
    };
    let draw = |window: &mut gpui::Window, cx: &mut gpui::App| {
        sk_runtime::bridge::with_draw(|| window.draw(cx).clear(cx))
    };
    let drew = sk_runtime::bridge::with_app(|cx| {
        handle.update(cx, |_, window, cx| draw(window, cx)).is_ok()
    });
    if drew != Some(false) || sk_tree::in_input_dispatch() {
        return;
    }
    sk_runtime::with_commit(|window, cx| {
        if window.window_handle() == handle {
            draw(window, cx);
        }
    });
}

fn commit_boot_tree(runtime: &JsRuntime) {
    // Vue's mount/load handlers may queue their last DOM writes in a microtask.
    runtime.ctx().drain_microtasks();
    sk_tree::flush_changes();
}

#[cfg(test)]
mod startup_tests {
    #[test]
    fn boot_microtask_styles_are_computed_before_any_frame_pump() {
        sk_runtime::testing::on_js_thread(|| {
            sk_runtime::JsRuntime::with(|runtime| {
                sk_tree::install(runtime);
                runtime.eval(
                "globalThis.__startupRoot = __sk_create_root(); \
                 globalThis.__startupNode = __sk_create_element(__sk_intern('button')); \
                 __sk_insert(__startupNode, __startupRoot, 0); \
                 __sk_set_style(__startupNode, __sk_intern('opacity'), '0.25'); \
                 queueMicrotask(() => __sk_set_style(__startupNode, __sk_intern('opacity'), '0.75'));",
                "sk://startup-regression.js",
            ).expect("queue the mount/load microtask through the native DOM bridge");
                super::commit_boot_tree(runtime);
                let node = runtime
                    .ctx()
                    .global_get("__startupNode")
                    .unwrap()
                    .as_number()
                    .unwrap() as u32;
                // Reads existing computed state without forcing the cascade (getComputedStyle would flush it).
                let styles = sk_tree::devtools::computed_styles(node)
                    .expect("boot writes must already be cascaded");
                let base = &styles.iter().find(|(name, _)| *name == "base").unwrap().1;
                assert!(
                    base.contains("0.75"),
                    "the first draw must not await pump_frame to cascade boot opacity: {base}"
                );
            })
        });
    }
}

const HIDDEN_START_GRACE: std::time::Duration = std::time::Duration::from_secs(10);

/// A hidden start with no tray icon and no shown window after [`HIDDEN_START_GRACE`] shows the
/// window, so a failed tray cannot strand the app.
fn reveal_if_unreachable(cx: &mut App) {
    cx.spawn(async move |cx| {
        cx.background_executor().timer(HIDDEN_START_GRACE).await;
        let _ = cx.update(|_| {
            if shutdown::is_closing() || window::revealed() || sk_desktop::tray::Tray::app_shown() {
                return;
            }
            let line = format!(
                "[sk] started hidden, and no tray icon is up after {} s: showing the window so the app can be reached",
                HIDDEN_START_GRACE.as_secs()
            );
            eprintln!("{line}");
            sk_tree::log::record("warn", line);
            window::request_activate();
        });
    })
    .detach();
}

#[cfg(target_os = "windows")]
fn reveal_startup_window(cx: &mut App, activate: bool) {
    let Some(handle) = MAIN_WINDOW.with(|window| window.get()) else {
        window::cancel_startup_reveal();
        return;
    };
    cx.spawn(async move |cx| {
        if shutdown::is_closing() || sk_runtime::bridge::poisoned() {
            window::cancel_startup_reveal();
            return;
        }
        let hwnd = cx.update(|cx| handle.update(cx, |_, window, _| window::capture_hwnd(window)));
        let Ok(Some(hwnd)) = hwnd else {
            window::cancel_startup_reveal();
            return;
        };
        // WM_PAINT takes the App itself, so it must run outside any update.
        popout_win::paint_now(hwnd);
        if shutdown::is_closing() || sk_runtime::bridge::poisoned() {
            window::cancel_startup_reveal();
            return;
        }
        let shown = cx.update(|cx| {
            handle.update(cx, |_, window, _| {
                window.show_window(
                    activate,
                    || !shutdown::is_closing() && !sk_runtime::bridge::poisoned(),
                    move |shown| {
                        window::cancel_startup_reveal();
                        if shown {
                            quiet::send_hwnd_to_back(hwnd);
                        }
                        if !shown && !shutdown::is_closing() {
                            eprintln!("[window] the prepared startup window could not be shown");
                        }
                    },
                )
            })
        });
        if !matches!(shown, Ok(true)) {
            window::cancel_startup_reveal();
            eprintln!("[window] failed to reveal the prepared startup window");
        }
    })
    .detach();
}

/// The display the primary window is on. Outside any update of the primary window.
pub(crate) fn main_window_display(cx: &mut App) -> Option<gpui::DisplayId> {
    let handle = MAIN_WINDOW.with(|w| w.get())?;
    handle
        .update(cx, |_, window, cx| window.display(cx).map(|d| d.id()))
        .ok()
        .flatten()
}

/// The primary window's gpui id (devtools `windows` calls it `main`).
#[cfg(sk_devtools)]
pub(crate) fn main_window_id() -> Option<u64> {
    MAIN_WINDOW
        .with(|w| w.get())
        .map(|h| h.window_id().as_u64())
}

/// Not `Window::refresh`: that raises gpui's `refreshing` flag, which makes the frame ignore every
/// `Entity::cached` recording and defeats the retained-render cache.
pub(crate) fn refresh_main(cx: &mut App) {
    notify_shell(cx);
}

pub(crate) fn notify_shell(cx: &mut App) {
    SHELL.with(|s| {
        if let Some(shell) = s.borrow().as_ref().and_then(|w| w.upgrade()) {
            shell.update(cx, |_, cx| cx.notify());
        }
    });
}

host_fn!(fn sk_set_status(g, args) {
    let text = unsafe { sk_runtime::redjs::webapi::util::read_string(g, args.arg(0).0) }
        .unwrap_or_default();
    // The CURRENT value, not a stream: a 2 Hz status ticker must not evict the log ring.
    sk_tree::log::set_status(text);
    sk_runtime::redjs::api::Value::undefined().0
});

host_fn!(fn sk_perf_mark(g, args) {
    let text = unsafe { sk_runtime::redjs::webapi::util::read_string(g, args.arg(0).0) }
        .unwrap_or_default();
    perf::mark(&text);
    sk_runtime::redjs::api::Value::undefined().0
});

host_fn!(fn sk_log(g, args) {
    let text = unsafe { sk_runtime::redjs::webapi::util::read_string(g, args.arg(0).0) }
        .unwrap_or_default();
    sk_tree::log::record("log", text);
    sk_runtime::redjs::api::Value::undefined().0
});

/// The per-frame JS pump: runs before the frame's draw, so `cx.notify()` from a host fn lands in the same frame.
fn pump_frame(window: &mut Window, cx: &mut App) {
    #[cfg(sk_devtools)]
    let _allocation_scope = crate::heapcount::recording::scope("runtime", "frame/pump");
    // A cloaked or occluded window is a hidden page: decline the pump and, by not stamping the
    // frame clock, hand the window to the background tick. Not before the first frame (boot wave).
    if background::pumped_once() && (window::cloaked() || window::occluded()) {
        idle::rearm_paced(window, pump_frame, idle::CLOAKED_INTERVAL);
        return;
    }
    perf::frame();
    background::note_frame();
    // Before the poison gate: a worker's log is what an agent wants once JS has given up.
    drain_log_tee();
    if sk_runtime::bridge::poisoned() {
        // No JS after a caught native panic: show the fatal dialog once, do not re-arm.
        crash_window::on_poisoned(cx);
        return;
    }
    if first_wave_waits(window) {
        idle::rearm_unpaced(window, pump_frame);
        return;
    }
    // Before the pump, so what the mousemove handler schedules drains this frame.
    sk_tree::flush_pending_mouse_move(window, cx);
    #[cfg(sk_devtools)]
    inspector::poll_frame(cx);
    js_wave(window, cx, Wave::Frame);
    window::note_painted_frame();
    after_wave(window, cx);
    #[cfg(sk_devtools)]
    if devtools::busy() {
        idle::note_moved();
    }
    idle::rearm(
        window,
        pump_frame,
        window::app_focused(cx) || quiet::never_focus(),
    );
    perf::pump_done();
    // Observers run after layout and before paint, so this draws ahead of gpui's draw. After
    // `pump_done` so that draw stays in gpui's bucket of the frame trace.
    sk_tree::update_layout_observers(window, cx);
    // The background tick measures the stall from here, so a slow frame is not mistaken for a parked one.
    background::note_frame();
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Wave {
    Frame,
    /// The window draws no frames: no `requestAnimationFrame`, as in a hidden page.
    Background,
}

/// One JS wave inside one `Phase::Commit` publication.
pub(crate) fn js_wave(window: &mut Window, cx: &mut App, wave: Wave) {
    let focused = window::app_focused(cx) || quiet::never_focus();
    with_published(window, cx, Phase::Commit, || {
        // HMR before the pump, so what Vue schedules while patching drains this frame.
        if wave == Wave::Frame {
            let n = FRAME_NO.with(|f| {
                let n = f.get().wrapping_add(1);
                f.set(n);
                n
            });
            boot_mode::poll_frame(n);
        }
        reload::pump();
        // Before `rt.pump` so `resize` handlers' DOM mutations drain this frame.
        sk_runtime::with_commit(|window, cx| window::pump(window, cx));
        sk_runtime::runtime::set_frame_budget_ms(window::frame_budget_ms());
        let flags = match wave {
            Wave::Frame => PUMP_TIMERS | PUMP_RAF | PUMP_MICROTASKS,
            Wave::Background => PUMP_TIMERS | PUMP_MICROTASKS,
        };
        JsRuntime::with(|rt| {
            let pumped = std::time::Instant::now();
            let stats = rt.pump(flags);
            let elapsed = pumped.elapsed();
            if wave == Wave::Frame {
                #[cfg_attr(not(feature = "audio"), allow(unused_mut))]
                let mut report = idle::Wave::from_stats(&stats, elapsed);
                #[cfg(feature = "audio")]
                {
                    report.audio = sk_runtime::redjs::webapi::audio::busy(rt.raw());
                }
                idle::note_wave(report);
            }
            #[cfg(sk_devtools)]
            devtools::trace::note_js(elapsed.as_secs_f32() * 1000.0);
            for err in rt.drain_errors() {
                eprintln!("[js uncaught] {}\n{}", err.header, err.stack);
                sk_tree::log::record(
                    "error",
                    format!("[js uncaught] {}\n{}", err.header, err.stack),
                );
            }
            reclaim::after_wave(
                rt,
                focused,
                wave == Wave::Background || window::page_hidden(),
            );
        });
        // One devtools command per frame, in this publication, so it never sees a half-applied patch.
        #[cfg(sk_devtools)]
        {
            devtools::pump();
        }
        js::frame();
        sk_permissions::pump();
        sk_desktop::pump();
        embed::pump();
        // At most one localStorage file write per frame.
        #[cfg(feature = "storages")]
        sk_storage::pump();
    });
}

/// What follows a JS wave on both clocks. On the background tick the repaint only marks the window dirty.
pub(crate) fn after_wave(window: &mut Window, cx: &mut App) {
    // Media ticks run before the draw so a media element paints this tick's picture. The device
    // check comes first: after a renderer device loss every `<video>` must rebuild before it ticks.
    publish_video_device();
    let media_moved = sk_tree::frame_tick(window, cx);
    let flush = sk_tree::flush_changes_kind();
    let tree_moved = flush != sk_tree::Flush::Unchanged;
    #[cfg(sk_devtools)]
    if tree_moved {
        devtools::ws::note_tree_changed();
    }
    // A hidden page paints no animation. Playing media asks for a draw only via `media_moved`.
    let animating = sk_tree::animating() && !window::page_hidden();
    let moving = animating || media_moved;
    if flush == sk_tree::Flush::DrawnBySync {
        // A forced layout already drew this tree; with no newer work the notify below is skipped.
        sk_tree::perf::note_sync_tail(!moving);
    }
    if flush == sk_tree::Flush::Changed || moving {
        notify_shell(cx);
    }
    if tree_moved || moving {
        // CSS animations alone are not work: an unfocused window paces them.
        if tree_moved || media_moved {
            idle::note_moved();
        } else {
            idle::note_animating();
        }
        // The synchronous layout draws only the primary window.
        popout::notify_all(cx);
    }
    // After the flush, so a socket is never told about a revision the tree has not reached.
    #[cfg(sk_devtools)]
    devtools::ws::broadcast_frame();
}

impl Render for Shell {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        #[cfg(sk_devtools)]
        let _allocation_scope = crate::heapcount::recording::scope("render", "frame/build");
        perf::render_begin();
        let el = self.render_body(window, cx);
        perf::render_done();
        el
    }
}

impl Shell {
    fn render_body(&mut self, window: &mut Window, cx: &mut Context<Self>) -> gpui::Div {
        let shell = div()
            .relative()
            .flex()
            .flex_col()
            .size_full()
            .text_color(gpui::white())
            .font_family(".SystemUIFont");
        #[cfg(not(target_os = "windows"))]
        let shell = chrome_posix::wrap(shell, window, true);
        let shell = match window::opaque_fill(window::backdrop(), window::effective_dark(window)) {
            Some(fill) => shell.bg(fill),
            None => shell,
        };
        if !window::fallback_titlebar() {
            return shell
                .child(sk_tree::build_root(window, cx))
                .children(sk_tree::build_view_transition())
                .children(window_controls_overlay(window))
                .children(inspector_overlay());
        }
        shell
            .child(
                div()
                    .id("titlebar")
                    .window_control_area(WindowControlArea::Drag)
                    .h(px(window::title_bar_height()))
                    .overflow_hidden()
                    .px(px(14.))
                    .flex()
                    .items_center()
                    .text_size(px(13.))
                    .child(window::title()),
            )
            // `flex_1().min_h(0)` gives the app root a definite box; an auto-height slot would break
            // `h-full`, `overflow: auto` and `position: fixed` inside the app.
            .child(
                div()
                    .flex_1()
                    .min_h(px(0.))
                    .child(sk_tree::build_root(window, cx)),
            )
            .children(sk_tree::build_view_transition())
            .children(window_controls_overlay(window))
            .children(inspector_overlay())
    }
}

/// Lives in the shell, not the app's tree, so the inspector never appears in the tree it inspects.
fn inspector_overlay() -> Option<gpui::Div> {
    #[cfg(sk_devtools)]
    {
        devtools::highlight_overlay()
    }
    #[cfg(not(sk_devtools))]
    {
        None
    }
}

/// The host-drawn caption-button cluster (`titleBarOverlay`), top-right.
///
/// `window_control_area` makes `WM_NCHITTEST` answer HTMINBUTTON/HTMAXBUTTON/HTCLOSE, so the OS
/// performs the action and HTMAXBUTTON arms the Windows 11 snap-layouts flyout.
fn window_controls_overlay(window: &Window) -> Option<gpui::Div> {
    let (height, overlay) = window::overlay()?;
    let dark = window::effective_dark(window);
    // Win10 has these code points in Segoe MDL2 Assets; `fallbacks` is DirectWrite's per-code-point chain.
    const MIN: &str = "\u{e921}";
    const MAX: &str = "\u{e922}";
    const CLOSE: &str = "\u{e8bb}";
    let glyph_font = gpui::Font {
        family: "Segoe Fluent Icons".into(),
        fallbacks: Some(gpui::FontFallbacks::from_fonts(vec![
            "Segoe MDL2 Assets".to_string(),
            "Segoe UI Symbol".to_string(),
        ])),
        features: Default::default(),
        weight: Default::default(),
        style: Default::default(),
    };
    let symbol = overlay
        .symbol_color
        .map(rgba)
        .unwrap_or_else(|| rgba(if dark { 0xffffffe0 } else { 0x000000e0 }));
    let hover = if dark { 0xffffff1a } else { 0x0000000f };
    let button = |id: &'static str, glyph: &'static str, area: WindowControlArea, hover: u32| {
        div()
            .id(id)
            .w(px(window::OVERLAY_BUTTON_WIDTH))
            .h(px(height))
            .flex()
            .items_center()
            .justify_center()
            .text_size(px(10.))
            .text_color(symbol)
            .font(glyph_font.clone())
            .window_control_area(area)
            .hover(|s| s.bg(rgba(hover)))
            .child(glyph)
    };
    let mut strip = div()
        .absolute()
        .top_0()
        .right_0()
        .h(px(height))
        .flex()
        .flex_row();
    if let Some(bg) = overlay.color {
        strip = strip.bg(rgba(bg));
    }
    Some(
        strip
            .child(button("wco-min", MIN, WindowControlArea::Min, hover))
            .child(button("wco-max", MAX, WindowControlArea::Max, hover))
            .child(button(
                "wco-close",
                CLOSE,
                WindowControlArea::Close,
                0xc42b1cff,
            )),
    )
}

/// The directory a relative `<img src>` resolves against: `SK_APP_ROOT`, else [`dev::boot`] reads
/// it from the dev build's manifest. Prod leaves it unset (working directory, with an advisory).
fn publish_app_root() {
    #[cfg(feature = "prod")]
    if prod::publish_asset_store() {
        return;
    }
    if let Some(dir) = std::env::var_os("SK_APP_ROOT") {
        if !dir.is_empty() {
            sk_tree::set_asset_base(std::path::PathBuf::from(dir));
        }
    }
}

fn install_iframe_backend() {
    #[cfg(feature = "storages")]
    let data = embed::data_dir()
        .map(std::path::Path::to_path_buf)
        .or_else(|| {
            sk_storage::default_folder(boot_mode::app_name().as_deref())
                .parent()
                .map(std::path::Path::to_path_buf)
        });
    #[cfg(not(feature = "storages"))]
    let data: Option<std::path::PathBuf> = None;
    let user_data = data
        .unwrap_or_else(|| std::env::temp_dir().join("skathi"))
        .join("webview");
    let config = sk_webview::Config {
        assets: std::rc::Rc::new(|path| sk_tree::read_app_asset(path)),
        user_data,
        page_origin: "app://redjs".into(),
        devtools: !cfg!(feature = "prod"),
    };
    if let Some(backend) = sk_webview::backend(config) {
        sk_tree::iframe::set_backend(backend, std::rc::Rc::new(sk_runtime::frames::wake));
    }
}

/// Closes every `<iframe>` document on quit, so no browser process outlives the app.
fn close_iframes_on_quit(cx: &mut App) {
    std::mem::forget(cx.on_app_quit(|_| {
        sk_tree::iframe::shutdown();
        std::future::ready(())
    }));
}

/// Hands `<video>` the renderer's D3D11 device, again after a device loss (each `<video>` rebuilds,
/// keeping position and transport state). Runs every frame. The pointer is BORROWED from
/// `DirectXDevices`; `sk_video` clones the COM interface if it keeps it.
#[cfg(target_os = "windows")]
fn publish_video_device() {
    use std::cell::Cell;
    #[cfg(feature = "native-dx12")]
    {
        static INSTALL: std::sync::Once = std::sync::Once::new();
        INSTALL.call_once(|| {
            fn provide() -> Result<Option<sk_tree::SharedVideoDevice>, String> {
                gpui_windows::ensure_renderer_d3d11_device()
                    .map(|lease| {
                        lease.map(|lease| sk_tree::SharedVideoDevice {
                            device: lease.device,
                            generation: lease.generation,
                            keep_alive: lease.keep_alive,
                        })
                    })
                    .map_err(|error| {
                        format!("Could not initialize renderer video bridge: {error:#}")
                    })
            }
            // The renderer's owned lease keeps the raw COM pointer valid.
            if let Err(error) = unsafe { sk_tree::install_video_device_provider(provide) } {
                log::error!("Could not install lazy video device provider: {error}");
            }
        });
    }
    thread_local! {
        /// 0 is never a live generation.
        static PUBLISHED: Cell<u64> = const { Cell::new(0) };
    }
    let (ptr, generation) = gpui_windows::renderer_d3d11_device();
    let previous = PUBLISHED.with(Cell::get);
    if generation == 0 || previous == generation || (ptr.is_null() && previous == 0) {
        return;
    }
    // A new native12 generation has no D3D11 bridge yet: old decoders still rebuild; the next load asks the lazy provider.
    let first = previous == 0;
    PUBLISHED.with(|p| p.set(generation));
    // SAFETY: the pointer comes straight from the live `DirectXDevices`.
    unsafe { sk_tree::set_video_device(ptr, generation) };
    if first {
        return;
    }
    let rebuilt = sk_tree::video_device_changed();
    let msg = format!(
        "[video] the renderer recreated its D3D11 device (generation {generation}) — rebuilt \
         {rebuilt} <video> element(s) on it, resuming where they were"
    );
    eprintln!("{msg}");
    sk_tree::log::record("window", msg);
}

#[cfg(not(target_os = "windows"))]
fn publish_video_device() {}

/// gpui's `Resource::Uri` client is redjs's network stack ([`http_client`]); without one gpui's
/// `NullHttpClient` fails every request.
fn install_http_client(app: gpui::Application) -> gpui::Application {
    app.with_http_client(std::sync::Arc::new(http_client::RedjsHttpClient::new()))
}

/// The host exe's `main`: this process IS the app.
pub fn run_exe() {
    // First, so a host whose runner is already gone never opens a window.
    owner::watch();
    // The one parse of the command line; consumers never read `std::env::args()`.
    let args = sk_desktop::args::process();
    // `sk build`'s host check: a bare host prints one JSON line and exits. A packaged exe's argv belongs to its app.
    if args.host.host_info && !payload::embedded_present() {
        println!("{}", payload::host_info_json());
        return;
    }
    // `--sk-dist` is `SK_DIST` for a process started for a protocol link (no inherited environment).
    if let Some(dist) = args.host.sk_dist.as_deref().filter(|d| !d.is_empty()) {
        std::env::set_var("SK_DIST", dist);
    }
    // Single instance, before the inspector, logger and gpui: a second launch forwards its
    // argv/url/cwd and exits without a window. The inspector (`--devtools`) is never an instance.
    {
        let launch_cfg = if args.host.devtools {
            None
        } else {
            boot_mode::launch_config()
        };
        // The instance key is the app's id and storage folder, not the slot.
        #[cfg(not(feature = "prod"))]
        let dev_slot = Some(slot::dir());
        #[cfg(feature = "prod")]
        let dev_slot = None;
        let build_name = if args.host.devtools {
            None
        } else {
            boot_mode::app_name()
        };
        if let sk_desktop::launch::Outcome::Exit(code) =
            sk_desktop::launch::start(args, launch_cfg.as_deref(), build_name, dev_slot)
        {
            std::process::exit(code);
        }
        if !args.host.devtools {
            sk_desktop::launch::register_declared();
        }
    }
    // `--devtools` rewrites the dist slot and instance env vars: before anything reads them.
    #[cfg(sk_devtools)]
    inspector::init();
    #[cfg(feature = "prod")]
    {
        #[cfg(sk_devtools)]
        let inspecting = inspector::is_devtools_host();
        #[cfg(not(sk_devtools))]
        let inspecting = false;
        if !inspecting {
            prod::require_payload();
        }
    }
    run_app();
    // Ends the process without the C runtime's exit path.
    shutdown::finish();
}

/// The exe's boot without the process-owned parts: the embedder owns the command line and is the
/// instance; the end is reported rather than taken.
pub(crate) fn run_embedded() {
    let args = sk_desktop::args::process();
    if !embed::desktop_launch_prepared() {
        let _ = sk_desktop::launch::start(args, None, boot_mode::app_name(), None);
    }
    run_app();
    shutdown::finish();
}

fn run_app() {
    // Before anything gpui does, so the renderer's boot messages are visible.
    install_logger();
    #[cfg(all(feature = "webgpu", target_os = "windows"))]
    shared_gpu::install().expect("installing shared graphics device provider");
    perf::boot();
    #[cfg(sk_devtools)]
    if heapcount::on() {
        sk_tree::perf::set_live_bytes_probe(|| heapcount::snapshot().map(|s| s.0));
        sk_tree::devtools::set_image_tracking(true);
    }
    // The primary window owns the JS pump; closing it ends the host on every OS (AppKit otherwise keeps a windowless app running).
    let app = install_http_client(application()).with_quit_mode(gpui::QuitMode::LastWindowClosed);
    // The show is queued, never applied inside AppKit's callback.
    #[cfg(target_os = "macos")]
    app.on_reopen(|_| embed::reopen());
    #[cfg(feature = "prod")]
    let app = if payload::get().is_some() {
        payload::install_effects();
        app.with_assets(payload::GpuiAssets)
    } else {
        app
    };
    app.run(|cx: &mut App| {
        // `--devtools`: the app is the inspector, from this executable.
        #[cfg(sk_devtools)]
        let devtools_mode = inspector::is_devtools_host();
        #[cfg(not(sk_devtools))]
        let devtools_mode = false;
        sk_elements::init(cx);
        publish_app_root();
        // First quit hook (they run in order): a quit no accepted close announced, such as the
        // session ending, hides the windows and arms the deadline; `pagehide` runs before storage flushes.
        std::mem::forget(cx.on_app_quit(|_| {
            window::cancel_startup_reveal();
            shutdown::begin("quit");
            window::page_hide();
            std::future::ready(())
        }));
        std::mem::forget(cx.on_app_quit(|_| {
            JsRuntime::try_with(|runtime| js::shutdown(runtime.ctx()));
            std::future::ready(())
        }));
        close_iframes_on_quit(cx);
        // Before any text field's interceptor, so Escape leaves a pointer lock ahead of them all.
        std::mem::forget(cx.intercept_keystrokes(sk_tree::pointer_lock_intercept_escape));
        #[cfg(sk_devtools)]
        {
            inspector::install_hotkey(cx);
            // A debugger must not outlive its subject (the child also watches us, for a crash).
            std::mem::forget(cx.on_app_quit(|_| {
                shutdown::step("inspector", inspector::close_children);
                std::future::ready(())
            }));
        }
        // So a final-frame `Set-Cookie` or `pagehide` `setItem` reaches disk.
        #[cfg(feature = "storages")]
        std::mem::forget(cx.on_app_quit(|_| {
            shutdown::step("storage", || {
                if let Err(e) = sk_storage::flush() {
                    eprintln!("[storage] localStorage: the last change was not written: {e}");
                }
                if let Err(e) = sk_storage::cookies::flush() {
                    eprintln!("[storage] cookies: the last change was not written: {e}");
                }
            });
            shutdown::step("http-cache", sk_runtime::redjs::webapi::http::cache::uninstall);
            std::future::ready(())
        }));
        // Synchronous: gpui gives quit futures only 200 ms.
        #[cfg(feature = "indexeddb")]
        std::mem::forget(cx.on_app_quit(|_| {
            let t = std::time::Instant::now();
            let done = shutdown::step("indexeddb", || sk_runtime::redjs::ffi::redjs_idb_shutdown(2_000));
            if done == 0 {
                eprintln!(
                    "[sk] IndexedDB did not finish closing within {} ms; the next start recovers from its WAL",
                    t.elapsed().as_millis()
                );
            }
            std::future::ready(())
        }));
        shutdown::install_test_delay(cx);
        // Before the runtime exists so the log ring records the first advisory.
        #[cfg(sk_devtools)]
        devtools::arm();

        // The window config is read before `open_window` (creation-time-only options need it to
        // avoid a flash) and before the JS runtime (`"devtools": false` must be answered before a port is bound).
        #[cfg(sk_devtools)]
        let window_json =
            if devtools_mode { inspector::window_config() } else { boot_mode::window_config() };
        #[cfg(not(sk_devtools))]
        let window_json = boot_mode::window_config();
        // The HTTP cache cap rides in the same block; read before it is consumed.
        #[cfg(feature = "storages")]
        let http_cache_mb = http_client::cache_mb(window_json.as_deref());
        let cfg = window::load_config(window_json);

        // Before `JsRuntime::init` so the bundle's first line sees the settled state.
        #[cfg(sk_devtools)]
        devtools::boot(window::devtools_config_enabled());

        // Seeded before `JsRuntime::init` so the first `navigator.onLine` read queues no event.
        sk_desktop::network::install();

        #[cfg(all(sk_devtools, not(feature = "native-aot")))]
        if let Some(summary) = devtools_mode.then(|| inspector::engine_without_native(
            std::env::var_os("SK_DEVTOOLS_ENGINE").as_deref(),
            std::env::var_os("SK_DEVTOOLS_NATIVE_IMAGE").is_some(),
        ).err()).flatten() {
            eprintln!("[native-aot] {summary}");
            embed::finished(false, summary);
            cx.quit();
            return;
        }
        #[cfg(feature = "native-aot")]
        if let Err(error) = native_aot::prepare(devtools_mode) {
            let summary = if devtools_mode {
                format!("native inspector preparation failed: {error}")
            } else {
                format!(
                    "this app's native image cannot run on this host ({error}). \
                     Rebuild the app with `sk build --aot` from the sk that matches this host."
                )
            };
            eprintln!("[native-aot] {summary}");
            let embedded =
                payload::get().is_some_and(|l| matches!(l.source, payload::Source::Embedder(_)));
            if !devtools_mode && !embedded {
                payload::message_box(&summary);
                std::process::exit(3);
            }
            embed::finished(false, summary);
            cx.quit();
            return;
        }
        JsRuntime::init();
        #[cfg(target_os = "windows")]
        consent_window::install(cx);
        let setup_result = JsRuntime::with(|rt| -> Result<(), String> {
            rt.register("__sk_set_status", 1, sk_set_status as *const _);
            rt.register("__sk_log", 1, sk_log as *const _);
            rt.register("__sk_perf_mark", 1, sk_perf_mark as *const _);
            reload::install(rt);
            sk_tree::install(rt);
            window::install(rt);
            popout::install(rt);
            #[cfg(feature = "audio")]
            microphone::install();
            // gpui's clipboard, the one native <input> uses, so there is one owner of `OpenClipboard`.
            #[cfg(feature = "clipboard")]
            sk_clipboard::install();
            sk_permissions::install(rt);
            sk_locale::install(rt);
            // Without a backend every `<iframe src>` answers `error`.
            if !devtools_mode {
                install_iframe_backend();
            }
            sk_desktop::set_log_sink(|kind, text| sk_tree::log::record(kind, text));
            sk_desktop::install(rt);
            // A file dialog is owned by the window published for the call that asked.
            sk_desktop::dialog::set_owner_resolver(dialogs::owner);
            sk_permissions::set_asker(dialogs::ask_permission);
            sk_permissions::set_app_name(&cfg.title);
            crash_window::set_app_name(&cfg.title);
            // Before any app code: the area loads lazily, so a late install would hand the app an empty `localStorage`.
            #[cfg(feature = "storages")]
            if !devtools_mode {
                let encrypted = embed::storage_encrypted();
                if embed::data_dir().is_some() || encrypted.is_some() {
                    let directory = embed::data_dir().map(std::path::Path::to_path_buf)
                        .unwrap_or_else(|| sk_storage::default_folder(boot_mode::app_name().as_deref()));
                    sk_storage::set_storage_folder(&directory, encrypted)?;
                    if encrypted == Some(true) {
                        sk_storage::encrypt_local_storage_at(&directory)?;
                    }
                }
            }
            #[cfg(feature = "storages")]
            sk_storage::install(
                rt,
                if devtools_mode { Some("sk-devtools".to_string()) } else { boot_mode::app_name() },
            );
            // After `install` (which names the app), before any JS; sealed when storage is.
            #[cfg(feature = "storages")]
            if !devtools_mode {
                if let Some(directory) = embed::data_dir() {
                    sk_storage::http_cache::install_at(http_cache_mb, directory.join("cache").join("http"));
                } else {
                    sk_storage::http_cache::install(http_cache_mb);
                }
            }
            // Without storage the answers last for the run.
            #[cfg(feature = "storages")]
            sk_permissions::set_decisions_file(sk_storage::cookies::folder().map(|f| f.join("permissions.json")));
            // Embedding plugins initialize against the installed storage and cookie jar.
            if !devtools_mode {
                tray::install(rt)?;
                hotkeys::install(rt)?;
                embed::setup(rt)?;
            }
            #[cfg(sk_devtools)]
            devtools::install(rt);
            embed::install(rt);
            unsafe { sk_runtime::standins::install_missing(rt.raw()) };
            Ok(())
        });
        if let Err(error) = setup_result {
            let summary = format!("host setup failed: {error}");
            eprintln!("[embed] {summary}");
            embed::finished(false, summary);
            cx.quit();
            return;
        }

        let bounds = Bounds::centered(None, size(px(cfg.width), px(cfg.height)), cx);
        let startup_visible = embed::visible();
        let startup_focus = !devtools_mode && !quiet::never_focus() && embed::activates();
        let defer_reveal = cfg!(target_os = "windows") && startup_visible;
        if defer_reveal {
            window::begin_startup_reveal();
        }
        cx.open_window(
            WindowOptions {
                window_bounds: Some(WindowBounds::Windowed(bounds)),
                window_background: cfg.backdrop.to_gpui(),
                titlebar: Some(TitlebarOptions {
                    title: Some(cfg.title.clone().into()),
                    // The chrome-mode switch (`!hide_title_bar` adds `WS_CAPTION`): creation-time only.
                    appears_transparent: cfg.title_bar_style == window::TitleBarStyle::Hidden,
                    traffic_light_position: window::traffic_light_position(
                        cfg.title_bar_style == window::TitleBarStyle::Hidden,
                        cfg.title_bar_height,
                    ),
                    ..Default::default()
                }),
                is_resizable: cfg.resizable,
                is_minimizable: cfg.minimizable,
                // macOS: the app's `window-drag` regions move the window, not AppKit's title-bar band.
                app_owns_titlebar_drag: cfg.title_bar_style == window::TitleBarStyle::Hidden,
                window_min_size: match (cfg.min_width, cfg.min_height) {
                    (None, None) => None,
                    (w, h) => Some(size(px(w.unwrap_or(0.0)), px(h.unwrap_or(0.0)))),
                },
                // The armed pump must not opt the window into the 33 ms unfocused throttle (JS timers would coarsen).
                inactive_frame_interval: None,
                // Maps to `SW_SHOWNOACTIVATE`: F12 shows the inspector without taking the caret from the app.
                show: startup_visible && !defer_reveal,
                focus: startup_focus,
                #[cfg(target_os = "linux")]
                window_decorations: Some(gpui::WindowDecorations::Client),
                #[cfg(target_os = "linux")]
                app_id: embed::desktop_id().or_else(|| sk_desktop::launch::identity().map(|i| i.id.clone())),
                ..Default::default()
            },
            |window, cx| {
                if std::env::var_os("SK_RETAINED_LAYOUT").as_deref() != Some(std::ffi::OsStr::new("0")) {
                    window.vn_enable_retained_layout();
                }
                // Before the first frame is presented, so a test host is never seen in front.
                quiet::send_to_back(window);
                publish_video_device();
                let shell = cx.new(|_| Shell);
                SHELL.with(|s| *s.borrow_mut() = Some(shell.downgrade()));
                window::init(&cfg, window, cx);
                // The pipe thread raises it directly: the foreground grant is short-lived.
                if let Some(hwnd) = window::capture_hwnd(window) {
                    sk_desktop::launch::set_window(hwnd);
                }
                // `close-requested` and `beforeunload`: a synchronous boolean.
                window.on_window_should_close(cx, |window, cx| {
                    let closing = window::should_close();
                    if closing {
                        window::cancel_startup_reveal();
                        shutdown::begin("a close request (WM_CLOSE)");
                    }
                    // A pop-out left open would be a live window with no JS clock.
                    if closing && popout::count() > 0 {
                        sk_tree::log::record(
                            "window",
                            format!(
                                "[window] the primary window is closing — taking {} pop-out(s) \
                                 with it",
                                popout::count()
                            ),
                        );
                        popout::close_all(cx);
                    }
                    // A file dialog owned by this window outlives a close request by its own 100 ms timer.
                    closing && dialogs::may_close_now(window.window_handle(), cx)
                });
                window.on_next_frame(pump_frame);
                shell
            },
        )
        .map(|handle| MAIN_WINDOW.with(|w| w.set(Some(handle.into()))))
        .unwrap();
        background::start(cx);
        #[cfg(target_os = "windows")]
        sk_runtime::frames::set_waker(gpui_windows::wake_frames);

        // Before any JS: the bundle's `onMounted` needs layout reads.
        sk_tree::set_sync_layout(sync_layout);
        let text_system = cx.text_system().clone();
        sk_css::set_font_source(move || text_system.all_font_names());
        let metric_system = cx.text_system().clone();
        let metric_text = RefCell::new((0usize, gpui::WindowTextSystem::new(metric_system.clone())));
        sk_css::set_font_metric_source(move |font, size| {
            let mut cache = metric_text.borrow_mut();
            let (queries, text) = &mut *cache;
            // This metric-only window is not frame-pumped: bound its line cache.
            if *queries >= 128 {
                *text = gpui::WindowTextSystem::new(metric_system.clone());
                *queries = 0;
            }
            *queries += 1;
            let run = gpui::TextRun { len: 1, font: font.clone(), color: gpui::black(), ..Default::default() };
            let lines = text.shape_text("0".into(), gpui::px(size), &[run], None, None).ok()?;
            let line = lines.first()?;
            let font_id = line.runs().first()?.font_id;
            Some(sk_css::FontRelativeMetrics {
                zero_advance: f32::from(line.size(gpui::px(size)).width),
                x_height: f32::from(text.x_height(font_id, gpui::px(size))),
            })
        });

        // Host fns called at top level land in Phase::App.
        #[cfg(sk_devtools)]
        let mut startup_error: Option<String> = None;
        with_published_app(cx, || {
            JsRuntime::with(|rt| {
                if let Err(e) = perf::boot_eval("preludes", || rt.eval(PRELUDE_JS, "sk://prelude.js")) {
                    eprintln!("[js boot] {}\n{}", e.header, e.stack);
                    #[cfg(all(sk_devtools, feature = "native-aot"))]
                    if devtools_mode && sk_runtime::redjs::aot::is_active() {
                        startup_error = Some(format!("native inspector prelude failed: {}", e.header));
                        return;
                    }
                }
                if let Err(e) = perf::boot_eval("preludes", || rt.eval(WINDOW_PRELUDE_JS, "sk://window.js")) {
                    eprintln!("[js boot] {}\n{}", e.header, e.stack);
                    #[cfg(all(sk_devtools, feature = "native-aot"))]
                    if devtools_mode && sk_runtime::redjs::aot::is_active() {
                        startup_error = Some(format!("native inspector prelude failed: {}", e.header));
                        return;
                    }
                }
                // `SK_SCENARIO` pins a harness app to one screen; sanitised, published as a global.
                let scenario = std::env::var("SK_SCENARIO").unwrap_or_default();
                if !scenario.is_empty() {
                    let safe: String = scenario
                        .chars()
                        .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
                        .collect();
                    let js = format!("globalThis.__SK_SCENARIO__ = \"{safe}\";");
                    if let Err(e) = rt.eval(&js, "sk://scenario.js") {
                        eprintln!("[js boot] {}\n{}", e.header, e.stack);
                    }
                }
                #[cfg(sk_devtools)]
                if devtools_mode {
                    if let Err(error) = inspector::boot(rt) {
                        startup_error = Some(error);
                        return;
                    }
                } else {
                    boot_mode::boot(rt);
                }
                #[cfg(not(sk_devtools))]
                boot_mode::boot(rt);
                window::content_loaded();
                commit_boot_tree(rt);
            });
        });
        #[cfg(sk_devtools)]
        if let Some(error) = startup_error {
            let summary = format!("inspector startup failed: {error}");
            eprintln!("[native-aot] {summary}");
            embed::finished(false, summary);
            window::cancel_startup_reveal();
            cx.quit();
            return;
        }
        refresh_main(cx);
        #[cfg(target_os = "windows")]
        if defer_reveal {
            reveal_startup_window(cx, startup_focus);
        }
        // A hidden window has no frame callback to own the boot wave: start its background clock.
        if !embed::visible() {
            background::note_frame();
            reveal_if_unreachable(cx);
        }
        if !devtools_mode && !quiet::never_focus() && embed::activates() {
            cx.activate(true);
        }
        #[cfg(sk_devtools)]
        if devtools_mode {
            inspector::watch_parent();
        }
    });
}