waterui-cli 0.1.4

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

use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::time::{Duration, Instant, UNIX_EPOCH};

use cargo_toml::Manifest as CargoManifest;
use color_eyre::eyre::{Context, Result, bail};
use futures::{FutureExt as _, pin_mut, select};
use notify::{RecursiveMode, Watcher as _};
use sha2::Digest as _;
use smol::stream::StreamExt;
use tracing::{error, info};

use super::app_client::PreviewAppClient;
use super::inputs::{ProjectInputsFingerprint, project_inputs_fingerprint};
use super::protocol::DylibId;
use super::protocol::PreviewPlatform;
use super::protocol::PreviewRuntimePlatform;
use super::protocol::PreviewTcpConfig;

use crate::apple::dynamic_runtime;
use crate::build::{RustBuild, RustLinkage};
use crate::device::{Device, DeviceEvent, Local, LogLevel, RunOptions, Running};
use crate::platform::TargetPlatform;
use crate::project::Project;
use crate::runtime_compat::{PREVIEW_RUNTIME_ENV_VARS, runtime_profile_tag};
use crate::runtime_fingerprint::{compute_runtime_fingerprint, runtime_package_identity};
use crate::support_app;
use waterui_preview_protocol::registry::preview_instance_registry_dir;

const PREVIEW_TEMPLATE_COMMIT: &str = env!("WATERUI_CLI_COMMIT");
const PREVIEW_METADATA_FILE: &str = ".waterui-preview-signature";
const PREVIEW_DYLIB_METADATA_SUFFIX: &str = ".waterui-preview-dylib-signature";

#[derive(Debug, Clone)]
struct PreviewRequirements {
    waterui_path: Option<PathBuf>,
    runtime_fingerprint: String,
    runtime_features: Vec<String>,
    app_crate_name: crate::project_types::CrateName,
    app_path: PathBuf,
}

#[derive(Debug)]
struct ResolvedPreviewMetadata {
    metadata: cargo_metadata::Metadata,
    app_crate_name: crate::project_types::CrateName,
    app_path: PathBuf,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct PreviewLinkMode {
    crate_type_override: Option<&'static str>,
    prefer_dynamic: bool,
    abi_feature: &'static str,
}

impl PreviewLinkMode {
    const MACOS_DYNAMIC: Self = Self {
        crate_type_override: None,
        prefer_dynamic: true,
        abi_feature: crate::templates::preview_ffi::APPLE_ABI_FEATURE,
    };
    const PORTABLE_DYNAMIC: Self = Self {
        crate_type_override: Some("cdylib"),
        prefer_dynamic: true,
        abi_feature: crate::templates::preview_ffi::APPLE_ABI_FEATURE,
    };
    const ANDROID_DYNAMIC: Self = Self {
        crate_type_override: Some("cdylib"),
        prefer_dynamic: true,
        abi_feature: crate::templates::preview_ffi::ANDROID_ABI_FEATURE,
    };

    const fn for_platform(platform: PreviewPlatform) -> Self {
        match platform {
            PreviewPlatform::Macos => Self::MACOS_DYNAMIC,
            PreviewPlatform::Ios | PreviewPlatform::IosSimulator => Self::PORTABLE_DYNAMIC,
            PreviewPlatform::Android => Self::ANDROID_DYNAMIC,
        }
    }

    const fn signature_tag(self) -> &'static str {
        if self.crate_type_override.is_some() {
            "preview-cdylib+shared-waterui-dylib+prefer-dynamic"
        } else {
            "preview-dylib+shared-waterui-dylib+prefer-dynamic"
        }
    }

    fn configure_build(self, build: RustBuild) -> RustBuild {
        let build = match self.crate_type_override {
            Some(crate_type) => build.with_crate_type_override(crate_type),
            None => build,
        };
        build.with_feature(self.abi_feature)
    }
}

/// A preview session that manages the preview app and TCP connection.
#[derive(Debug)]
pub struct PreviewSession {
    /// TCP client to the preview app.
    pub client: PreviewAppClient,
    /// Current platform.
    pub platform: PreviewPlatform,
    /// Path to the built dylib (if any).
    dylib_path: Option<PathBuf>,
    /// Running instance for apps launched by this session.
    running: Option<Pin<Box<Running>>>,
    /// Whether this session owns the app lifecycle.
    owns_app: bool,
    /// Optional path to sccache for compilation caching.
    sccache_path: Option<PathBuf>,
    /// Runtime fingerprint used for ABI-safe dylib invalidation.
    runtime_fingerprint: String,
}

#[derive(Debug, Clone)]
/// A built dylib payload (stable id + on-disk path).
pub struct BuiltDylib {
    /// Stable preview cache id for the dylib payload.
    pub id: DylibId,
    /// Path to dylib on disk.
    pub path: PathBuf,
}

impl PreviewSession {
    /// Build the user's project as a dylib.
    ///
    /// # Errors
    /// Returns an error if the project cannot be opened, rebuilt, or fingerprinted.
    pub async fn build_dylib(&mut self, project_path: &std::path::Path) -> Result<BuiltDylib> {
        build_preview_dylib(
            project_path,
            self.platform,
            self.sccache_path.as_ref(),
            &self.runtime_fingerprint,
            &mut self.dylib_path,
        )
        .await
    }

    /// Render a preview and return PNG bytes.
    ///
    /// # Errors
    /// Returns an error if the preview app rejects the render or the transport fails.
    pub async fn render(
        &mut self,
        dylib: &BuiltDylib,
        symbol: &str,
        width: f32,
        height: f32,
    ) -> Result<Vec<u8>> {
        let prefer_local_path = self.platform == PreviewPlatform::Macos;
        self.client
            .render_with_dylib_file(
                dylib.id,
                &dylib.path,
                symbol,
                width,
                height,
                prefer_local_path,
            )
            .await
            .map_err(|e| color_eyre::eyre::eyre!("Preview app error: {e}"))
    }

    /// Shutdown the preview app if this session launched it.
    ///
    /// # Errors
    /// Returns an error if the support app does not acknowledge the shutdown request.
    pub async fn shutdown(&mut self) -> Result<()> {
        if self.owns_app {
            let result = self.client.shutdown().await;
            // Dropping `running` will terminate the app if still alive.
            self.running.take();
            self.owns_app = false;
            result?;
        }
        Ok(())
    }

    /// Detach the preview app so it keeps running after this session is dropped.
    ///
    /// The app continues running and can be reused by future preview sessions.
    pub fn detach(&mut self) {
        if let Some(mut running) = self.running.take() {
            running.as_mut().detach();
            self.owns_app = false;
        }
    }
}

/// Configures the module build to compile exactly as the runtime it will be
/// loaded into was compiled.
///
/// The preview wrapper crate lives in the managed build cache, whose generated
/// sources are regenerated whenever the CLI's scaffold templates move, so its
/// dependency graph must not be compiled into that regenerated tree.
///
/// It goes into the *support app's* shared target directory rather than the
/// previewed project's. A preview module is loaded into the support app and
/// resolves its framework symbols against the runtime that app already has open,
/// so the two have to be the same build of that runtime — not merely the same
/// source at the same version. Two target directories mean two independent
/// compilations, each with its own `-C metadata` and therefore its own hash in
/// every mangled symbol; the module then fails to `dlopen` against a runtime
/// whose symbols no longer match, even though every input to both builds was
/// identical.
///
/// Cargo folds both the deployment target and the unified feature set into that
/// same `-C metadata` hash, so a module that disagrees with its host on either
/// one links against symbols the host does not have.
async fn configure_preview_module_build(
    preview_crate_path: &Path,
    platform: PreviewPlatform,
    target: TargetPlatform,
    link_mode: PreviewLinkMode,
) -> Result<RustBuild> {
    let support_target_dir = Project::open(&preview_support_path()?)
        .await
        .wrap_err("Failed to open preview support project for its target directory")?
        .water_target_dir(RustLinkage::SharedRuntime)
        .await?;
    let rust_build = link_mode
        .configure_build(RustBuild::new(preview_crate_path, target.triple()))
        .with_target_dir(support_target_dir);

    let support_project = Project::open(&preview_support_path()?)
        .await
        .wrap_err("Failed to open the preview support project")?;
    if matches!(platform, PreviewPlatform::Android) {
        Ok(rust_build.with_features(
            crate::android::platform::android_ffi_dependency_features(&support_project).await?,
        ))
    } else {
        let browser_runtime = support_project
            .browser_runtime_plan(target, crate::platform::TargetBackend::Apple)
            .await?;
        let (key, value) =
            crate::apple::platform::apple_deployment_target(&support_project, target)
                .await
                .wrap_err("Failed to resolve the preview support deployment target")?;
        Ok(rust_build.with_env(key, value).with_features(
            crate::apple::platform::apple_ffi_dependency_features(
                &support_project,
                browser_runtime,
            )
            .await?,
        ))
    }
}

async fn build_preview_dylib(
    project_path: &Path,
    platform: PreviewPlatform,
    sccache_path: Option<&PathBuf>,
    runtime_fingerprint: &str,
    dylib_path: &mut Option<PathBuf>,
) -> Result<BuiltDylib> {
    let total_start = Instant::now();
    let fingerprint_start = Instant::now();
    let project_inputs = project_inputs_fingerprint(project_path).await?;
    info!(
        project_path = %project_path.display(),
        fingerprint = %project_inputs,
        elapsed_ms = fingerprint_start.elapsed().as_millis(),
        "Preview fingerprinted project inputs"
    );

    let project_open_start = Instant::now();
    let project = Project::open_for_preview_build(project_path).await?;
    info!(
        project_path = %project_path.display(),
        elapsed_ms = project_open_start.elapsed().as_millis(),
        "Preview opened project"
    );
    // Scaffold rather than assume: this build used to derive the module's path
    // and trust that some earlier flow had written it, which held only while a
    // previous preview's module survived in the build cache. The support-app
    // discard that runs when the runtime checkout changes deletes that cache,
    // and the next dylib build then spawned cargo in a directory that did not
    // exist — the "Failed to execute cargo build: No such file or directory"
    // that hit every first preview after switching workspaces.
    let scaffold_start = Instant::now();
    let preview_crate_path = scaffold_preview_module(&project).await?;
    info!(
        path = %preview_crate_path.display(),
        elapsed_ms = scaffold_start.elapsed().as_millis(),
        "Preview module scaffold is up to date"
    );
    let preview_crate_name = project.preview_dylib_crate_name();
    let target = match platform {
        PreviewPlatform::Macos => TargetPlatform::MacOS,
        PreviewPlatform::IosSimulator => TargetPlatform::IOSSimulator,
        PreviewPlatform::Ios => TargetPlatform::IOS,
        PreviewPlatform::Android => TargetPlatform::Android,
    };
    let target_triple = target.triple().to_string();
    let link_mode = PreviewLinkMode::for_platform(platform);

    ensure_project_dev_feature_for_preview(&project).await?;

    let mut rust_build =
        configure_preview_module_build(&preview_crate_path, platform, target, link_mode).await?;
    let dylib_path_start = Instant::now();
    let expected_path = rust_build
        .dylib_path(preview_crate_name.as_str(), false)
        .await?;
    info!(
        build_crate_path = %preview_crate_path.display(),
        build_crate_name = %preview_crate_name,
        path = %expected_path.display(),
        elapsed_ms = dylib_path_start.elapsed().as_millis(),
        "Preview resolved dylib path"
    );
    let candidate_path = dylib_path.clone().unwrap_or_else(|| expected_path.clone());

    let dylib_signature = dylib_build_signature(
        project_inputs,
        runtime_fingerprint,
        &target_triple,
        preview_crate_name.as_str(),
        link_mode,
    );
    let built_path = if dylib_is_up_to_date(&candidate_path, &dylib_signature).await? {
        candidate_path
    } else {
        info!("Building dylib...");
        if let Some(sccache) = sccache_path {
            rust_build = rust_build.with_sccache(sccache.clone());
        }
        if link_mode.prefer_dynamic {
            rust_build = rust_build.with_preferred_dynamic_linking();
        }
        let build_start = Instant::now();
        let built_path = rust_build
            .build_dylib(preview_crate_name.as_str(), false)
            .await
            .wrap_err("Failed to build dylib")?;
        prepare_preview_module_linkage(&built_path, link_mode, platform).await?;
        write_dylib_signature(&built_path, &dylib_signature).await?;
        info!(
            build_crate_path = %preview_crate_path.display(),
            build_crate_name = %preview_crate_name,
            path = %built_path.display(),
            elapsed_ms = build_start.elapsed().as_millis(),
            "Preview built dylib"
        );
        built_path
    };

    *dylib_path = Some(built_path.clone());

    let dylib_id_start = Instant::now();
    let id = compute_dylib_id(&built_path, &dylib_signature).await?;
    info!(
        path = %built_path.display(),
        elapsed_ms = dylib_id_start.elapsed().as_millis(),
        total_elapsed_ms = total_start.elapsed().as_millis(),
        "Preview prepared dylib payload"
    );
    Ok(BuiltDylib {
        id,
        path: built_path,
    })
}

async fn prepare_preview_module_linkage(
    built_path: &Path,
    link_mode: PreviewLinkMode,
    platform: PreviewPlatform,
) -> Result<()> {
    if !link_mode.prefer_dynamic {
        return Ok(());
    }
    if platform == PreviewPlatform::Android {
        return Ok(());
    }
    let build_lib_dir = built_path.parent().ok_or_else(|| {
        color_eyre::eyre::eyre!(
            "Preview dylib path has no output directory: {}",
            built_path.display()
        )
    })?;
    dynamic_runtime::retarget_module(built_path, build_lib_dir).await
}

async fn ensure_project_dev_feature_for_preview(project: &Project) -> Result<()> {
    let manifest_path = project.root().join("Cargo.toml");
    let manifest = smol::unblock(move || CargoManifest::from_path(&manifest_path)).await?;
    let Some(dev_features) = manifest.features.get("dev") else {
        bail!(
            "Preview requires `{}/dev` feature. Add `[features] dev = [\"waterui/dynamic_linking\"]` to {}",
            project.crate_name().as_str(),
            project.root().join("Cargo.toml").display()
        );
    };
    if !dev_features
        .iter()
        .any(|feature| feature == "waterui/dynamic_linking")
    {
        bail!(
            "Preview requires `{}/dev` to include `waterui/dynamic_linking`. Update {}",
            project.crate_name().as_str(),
            project.root().join("Cargo.toml").display()
        );
    }
    Ok(())
}

fn dylib_signature_path(path: &Path) -> PathBuf {
    let mut raw = path.as_os_str().to_os_string();
    raw.push(PREVIEW_DYLIB_METADATA_SUFFIX);
    PathBuf::from(raw)
}

fn dylib_build_signature(
    project_inputs: ProjectInputsFingerprint,
    runtime_fingerprint: &str,
    target_triple: &str,
    crate_name: &str,
    link_mode: PreviewLinkMode,
) -> String {
    let link_mode = link_mode.signature_tag();
    format!(
        "inputs={project_inputs}\nruntime={runtime_fingerprint}\ntarget={target_triple}\ncrate={crate_name}\nlink_mode={link_mode}"
    )
}

fn preview_run_options() -> RunOptions {
    let mut run_options = RunOptions::new();
    run_options.set_replace_existing_macos_app_instances(false);
    run_options.set_log_level(LogLevel::Info);
    let preview_cache_root = waterui_preview_protocol::registry::preview_cache_root_dir();
    let water_cache_dir = preview_cache_root.parent().unwrap_or_else(|| {
        panic!(
            "preview cache root must have a parent directory: {}",
            preview_cache_root.display()
        )
    });
    run_options.insert_env_var(
        "WATER_CACHE_DIR".to_string(),
        water_cache_dir.display().to_string(),
    );
    for (key, value) in PREVIEW_RUNTIME_ENV_VARS {
        run_options.insert_env_var(key.to_string(), value.to_string());
    }
    if let Some(rust_log) = std::env::var_os("RUST_LOG") {
        run_options.insert_env_var(
            "RUST_LOG".to_string(),
            rust_log.to_string_lossy().into_owned(),
        );
    }
    run_options
}

async fn write_dylib_signature(path: &Path, signature: &str) -> Result<()> {
    let signature_path = dylib_signature_path(path);
    smol::fs::write(signature_path, signature.as_bytes()).await?;
    Ok(())
}

async fn dylib_is_up_to_date(path: &std::path::Path, expected_signature: &str) -> Result<bool> {
    match smol::fs::metadata(path).await {
        Ok(_) => {}
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
        Err(e) => return Err(e.into()),
    }

    let signature_path = dylib_signature_path(path);
    let stored_signature = match smol::fs::read_to_string(&signature_path).await {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
        Err(e) => return Err(e.into()),
    };

    Ok(stored_signature.trim() == expected_signature)
}

async fn compute_dylib_id(path: &Path, build_signature: &str) -> Result<DylibId> {
    let path = path.to_path_buf();
    let build_signature = build_signature.to_string();
    smol::unblock(move || {
        let metadata = std::fs::metadata(&path)?;
        let modified = metadata.modified()?;
        let mut hasher = sha2::Sha256::new();
        hasher.update(build_signature.as_bytes());
        hasher.update([0]);
        hasher.update(path.to_string_lossy().as_bytes());
        hasher.update([0]);
        hasher.update(metadata.len().to_le_bytes());

        match modified.duration_since(UNIX_EPOCH) {
            Ok(duration) => {
                hasher.update([0]);
                hasher.update(duration.as_secs().to_le_bytes());
                hasher.update(duration.subsec_nanos().to_le_bytes());
            }
            Err(err) => {
                hasher.update([1]);
                hasher.update(err.duration().as_secs().to_le_bytes());
                hasher.update(err.duration().subsec_nanos().to_le_bytes());
            }
        }

        let hash: [u8; 32] = hasher.finalize().into();
        Ok(DylibId::from_bytes(hash))
    })
    .await
}

/// Launch a preview session for the given platform.
///
/// This will:
/// 1. Try to connect to an existing preview app via TCP
/// 2. If not found, scaffold and launch the preview app
/// 3. Wait for TCP connection
///
/// # Arguments
/// * `platform` - Target platform for preview
/// * `sccache_path` - Optional path to sccache for compilation caching
///
/// # Errors
/// Returns an error if the preview app cannot be launched or connected.
pub async fn launch_preview_session(
    project_path: &Path,
    platform: PreviewPlatform,
    sccache_path: Option<PathBuf>,
) -> Result<PreviewSession> {
    let requirements_start = Instant::now();
    let requirements = resolve_preview_requirements(project_path, platform).await?;
    info!(
        project_path = %project_path.display(),
        elapsed_ms = requirements_start.elapsed().as_millis(),
        "Preview resolved runtime requirements"
    );
    let expected_fingerprint = requirements.runtime_fingerprint.clone();
    let tcp_config = PreviewTcpConfig::from_env()
        .map_err(|e| color_eyre::eyre::eyre!(e))
        .wrap_err("Invalid preview TCP config")?;

    let connect_start = Instant::now();
    if let Some(session) = try_connect_existing_preview_app(
        tcp_config,
        &expected_fingerprint,
        platform,
        sccache_path.clone(),
    )
    .await?
    {
        info!(
            elapsed_ms = connect_start.elapsed().as_millis(),
            "Preview reused existing support app"
        );
        return Ok(session);
    }

    let project = open_preview_support_project(&requirements).await?;
    let running = launch_preview_app_for_platform(&project, platform).await?;
    build_preview_session_from_launch(
        running,
        platform,
        tcp_config,
        expected_fingerprint,
        sccache_path,
    )
    .await
}

async fn try_connect_existing_preview_app(
    tcp_config: PreviewTcpConfig,
    expected_fingerprint: &str,
    platform: PreviewPlatform,
    sccache_path: Option<PathBuf>,
) -> Result<Option<PreviewSession>> {
    let client = match platform {
        PreviewPlatform::Macos => connect_existing_macos_preview_app(expected_fingerprint).await?,
        PreviewPlatform::IosSimulator | PreviewPlatform::Ios | PreviewPlatform::Android => {
            PreviewAppClient::connect(
                tcp_config,
                expected_fingerprint,
                preview_runtime_platform(platform),
            )
            .await
            .ok()
        }
    };
    let Some(client) = client else {
        return Ok(None);
    };

    info!("Connected to existing preview app");
    Ok(Some(PreviewSession {
        client,
        platform,
        dylib_path: None,
        running: None,
        owns_app: false,
        sccache_path,
        runtime_fingerprint: expected_fingerprint.to_string(),
    }))
}

async fn connect_existing_macos_preview_app(
    expected_fingerprint: &str,
) -> Result<Option<PreviewAppClient>> {
    Ok(
        PreviewAppClient::connect_registered(expected_fingerprint, PreviewRuntimePlatform::Macos)
            .await
            .ok(),
    )
}

const fn preview_runtime_platform(platform: PreviewPlatform) -> PreviewRuntimePlatform {
    match platform {
        PreviewPlatform::Macos => PreviewRuntimePlatform::Macos,
        PreviewPlatform::IosSimulator => PreviewRuntimePlatform::IosSimulator,
        PreviewPlatform::Ios => PreviewRuntimePlatform::Ios,
        PreviewPlatform::Android => PreviewRuntimePlatform::Android,
    }
}

async fn open_preview_support_project(requirements: &PreviewRequirements) -> Result<Project> {
    info!("No preview app running, launching...");
    let preview_app_path = preview_support_path()?;
    let ensure_start = Instant::now();
    ensure_preview_support_app(&preview_app_path, requirements).await?;
    info!(
        path = %preview_app_path.display(),
        elapsed_ms = ensure_start.elapsed().as_millis(),
        "Preview support app scaffold is up to date"
    );
    let open_start = Instant::now();
    let project = Project::open(&preview_app_path)
        .await
        .wrap_err("Failed to open preview app project")?;
    info!(
        path = %preview_app_path.display(),
        elapsed_ms = open_start.elapsed().as_millis(),
        "Preview support project opened"
    );
    Ok(project)
}

async fn launch_preview_app_for_platform(
    project: &Project,
    platform: PreviewPlatform,
) -> Result<Running> {
    match platform {
        PreviewPlatform::Macos => launch_preview_on_macos(project).await,
        PreviewPlatform::IosSimulator => launch_preview_on_ios_simulator(project).await,
        PreviewPlatform::Ios => {
            bail!("Physical iOS devices are not yet supported for preview");
        }
        PreviewPlatform::Android => launch_preview_on_android(project).await,
    }
}

async fn launch_preview_on_macos(project: &Project) -> Result<Running> {
    let backend = project
        .apple_backend()
        .ok_or_else(|| color_eyre::eyre::eyre!("Apple backend not configured"))?;
    let device = Local;
    device.launch().await?;
    info!("Building and running preview app on macOS...");
    project
        .run_with_options(
            backend,
            TargetPlatform::MacOS,
            device,
            preview_run_options(),
        )
        .await
        .map_err(|e| color_eyre::eyre::eyre!("Failed to run preview app: {e}"))
}

async fn launch_preview_on_ios_simulator(project: &Project) -> Result<Running> {
    let backend = project
        .apple_backend()
        .ok_or_else(|| color_eyre::eyre::eyre!("Apple backend not configured"))?;
    let simulator = select_preview_ios_simulator().await?;
    simulator.launch().await?;
    info!("Building and running preview app on iOS Simulator...");
    project
        .run_with_options(
            backend,
            TargetPlatform::IOSSimulator,
            simulator,
            preview_run_options(),
        )
        .await
        .map_err(|e| color_eyre::eyre::eyre!("Failed to run preview app: {e}"))
}

async fn select_preview_ios_simulator() -> Result<crate::apple::device::AppleSimulator> {
    let simulators = crate::apple::device::AppleSimulator::scan_ios().await?;
    simulators
        .iter()
        .find(|simulator| simulator.state == "Booted")
        .cloned()
        .or_else(|| simulators.into_iter().next())
        .ok_or_else(|| {
            color_eyre::eyre::eyre!("No iOS simulator available. Please create one in Xcode.")
        })
}

async fn launch_preview_on_android(project: &Project) -> Result<Running> {
    let backend = project
        .android_backend()
        .ok_or_else(|| color_eyre::eyre::eyre!("Android backend not configured"))?;

    if let Some(device) = crate::android::device::AndroidDevice::scan()
        .await?
        .into_iter()
        .next()
    {
        device.launch().await?;
        info!("Building and running preview app on Android device...");
        return project
            .run_android_with_options(backend, device, preview_run_options())
            .await
            .map_err(|e| color_eyre::eyre::eyre!("Failed to run preview app: {e}"));
    }

    let avd_name = crate::android::platform::AndroidPlatform::list_avds()
        .await?
        .into_iter()
        .next()
        .ok_or_else(|| color_eyre::eyre::eyre!("No Android devices or emulators available."))?;
    let emulator = crate::android::device::AndroidEmulator::open(avd_name).await?;
    emulator.launch().await?;
    info!("Building and running preview app on Android emulator...");
    project
        .run_android_with_options(backend, emulator, preview_run_options())
        .await
        .map_err(|e| color_eyre::eyre::eyre!("Failed to run preview app: {e}"))
}

async fn build_preview_session_from_launch(
    running: Running,
    platform: PreviewPlatform,
    tcp_config: PreviewTcpConfig,
    expected_fingerprint: String,
    sccache_path: Option<PathBuf>,
) -> Result<PreviewSession> {
    info!("Preview app launched, waiting for TCP connection...");
    let mut running = Box::pin(running);
    match wait_for_connection_or_crash(&mut running, platform, tcp_config, &expected_fingerprint)
        .await
    {
        ConnectionWaitResult::Ready(client) => Ok(PreviewSession {
            client,
            platform,
            dylib_path: None,
            running: Some(running),
            owns_app: true,
            sccache_path,
            runtime_fingerprint: expected_fingerprint,
        }),
        ConnectionWaitResult::Crashed(message) => {
            bail!(
                "Preview app crashed:
{message}"
            );
        }
        ConnectionWaitResult::Exited => {
            bail!(
                "Preview app exited unexpectedly.
Check the app logs for more information."
            );
        }
        ConnectionWaitResult::Timeout => {
            bail!(
                "Preview app is still running after {} seconds but never accepted a connection.
Possible causes:
- The TCP server failed to start
- Port range {}..={} may be blocked
- The app is stuck during initialization

Try running with WATERUI_CRASH_DEBUG=1 for more details.",
                STARTUP_DEADLINE.as_secs(),
                tcp_config.port_start,
                tcp_config.ports().end()
            );
        }
    }
}

/// Result of waiting for preview-app readiness.
enum ConnectionWaitResult {
    /// Preview app accepted a connection and completed the protocol handshake.
    Ready(PreviewAppClient),
    /// App crashed with error message.
    Crashed(String),
    /// App exited without crash.
    Exited,
    /// The app stayed alive but never became reachable before the hang backstop.
    Timeout,
}

/// How long a launched preview app may stay alive without ever becoming reachable.
///
/// This is a backstop against a wedged process, not a judgement about how fast a
/// preview app "should" start. Readiness is decided by real signals — the registry
/// entry the app publishes, its listening-address log line, and its crash/exit
/// events — so a slow but healthy launch is waited out rather than failed. An
/// earlier 10s budget sat right on top of the ~10.2s cold start of a debug support
/// app and lost the race by milliseconds, killing an app that was about to work.
const STARTUP_DEADLINE: Duration = Duration::from_mins(3);

/// Wait for TCP connection while monitoring for app crashes.
///
/// macOS support apps publish a registry entry once the TCP server is ready, so wait on that
/// concrete readiness signal instead of sleeping between blind connection retries.
async fn wait_for_connection_or_crash(
    running: &mut Pin<Box<Running>>,
    platform: PreviewPlatform,
    tcp_config: PreviewTcpConfig,
    expected_fingerprint: &str,
) -> ConnectionWaitResult {
    const NON_MACOS_POLL_INTERVAL: Duration = Duration::from_millis(100);

    let start = Instant::now();

    let ready = match platform {
        PreviewPlatform::Macos => {
            wait_for_registered_preview_ready(
                running,
                expected_fingerprint,
                start,
                STARTUP_DEADLINE,
            )
            .await
        }
        PreviewPlatform::IosSimulator | PreviewPlatform::Ios | PreviewPlatform::Android => {
            wait_for_polled_preview_ready(
                running,
                tcp_config,
                expected_fingerprint,
                preview_runtime_platform(platform),
                start,
                STARTUP_DEADLINE,
                NON_MACOS_POLL_INTERVAL,
            )
            .await
        }
    };

    match ready {
        ConnectionWaitResult::Timeout => drain_terminal_preview_event(running).await,
        other => other,
    }
}

async fn wait_for_registered_preview_ready(
    running: &mut Pin<Box<Running>>,
    expected_fingerprint: &str,
    start: Instant,
    timeout: Duration,
) -> ConnectionWaitResult {
    const POLL_INTERVAL: Duration = Duration::from_millis(100);

    if let Some(client) =
        try_connect_registered_preview(expected_fingerprint, PreviewRuntimePlatform::Macos, start)
            .await
    {
        return ConnectionWaitResult::Ready(client);
    }

    let registry_dir = preview_instance_registry_dir();
    if let Err(error) = smol::fs::create_dir_all(&registry_dir).await {
        error!(path = %registry_dir.display(), "Failed to create preview registry dir: {error}");
        return ConnectionWaitResult::Timeout;
    }

    let (event_tx, event_rx) = async_channel::unbounded();
    let callback_tx = event_tx.clone();
    let mut watcher = match notify::recommended_watcher(move |result| {
        let _ = callback_tx.try_send(result);
    }) {
        Ok(watcher) => watcher,
        Err(error) => {
            error!(path = %registry_dir.display(), "Failed to create preview registry watcher: {error}");
            return ConnectionWaitResult::Timeout;
        }
    };
    if let Err(error) = watcher.watch(&registry_dir, RecursiveMode::NonRecursive) {
        error!(path = %registry_dir.display(), "Failed to watch preview registry dir: {error}");
        return ConnectionWaitResult::Timeout;
    }

    loop {
        if let Some(client) = try_connect_registered_preview(
            expected_fingerprint,
            PreviewRuntimePlatform::Macos,
            start,
        )
        .await
        {
            return ConnectionWaitResult::Ready(client);
        }

        let remaining = timeout.saturating_sub(start.elapsed());
        if remaining.is_zero() {
            return ConnectionWaitResult::Timeout;
        }

        let sleep = futures::FutureExt::fuse(smol::Timer::after(POLL_INTERVAL.min(remaining)));
        let running_event = running.next().fuse();
        let registry_event = futures::FutureExt::fuse(event_rx.recv());
        pin_mut!(sleep);
        pin_mut!(running_event);
        pin_mut!(registry_event);

        select! {
            event = running_event => {
                if let Some(result) = preview_connection_result_from_device_event(
                    event,
                    expected_fingerprint,
                    PreviewRuntimePlatform::Macos,
                    start,
                )
                .await
                {
                    return result;
                }
            },
            event = registry_event => {
                match event {
                    Ok(Ok(_notification)) => {}
                    Ok(Err(error)) => {
                        error!(path = %registry_dir.display(), "Preview registry watcher error: {error}");
                    }
                    Err(_) => return ConnectionWaitResult::Timeout,
                }
            },
            _ = sleep => {}
        }
    }
}

async fn wait_for_polled_preview_ready(
    running: &mut Pin<Box<Running>>,
    tcp_config: PreviewTcpConfig,
    expected_fingerprint: &str,
    expected_platform: PreviewRuntimePlatform,
    start: Instant,
    timeout: Duration,
    poll_interval: Duration,
) -> ConnectionWaitResult {
    loop {
        if let Some(client) =
            try_connect_polled_preview(tcp_config, expected_fingerprint, expected_platform, start)
                .await
        {
            return ConnectionWaitResult::Ready(client);
        }

        let remaining = timeout.saturating_sub(start.elapsed());
        if remaining.is_zero() {
            return ConnectionWaitResult::Timeout;
        }

        let sleep = futures::FutureExt::fuse(smol::Timer::after(poll_interval.min(remaining)));
        let running_event = running.next().fuse();
        pin_mut!(sleep);
        pin_mut!(running_event);

        select! {
            event = running_event => {
                if let Some(result) = preview_connection_result_from_device_event(
                    event,
                    expected_fingerprint,
                    expected_platform,
                    start,
                )
                .await
                {
                    return result;
                }
            },
            _ = sleep => {}
        }
    }
}

/// Probe the registry for a ready preview app, keeping the connection it establishes.
///
/// The probe completes a full protocol handshake, so discarding the client and
/// reconnecting afterwards would pay for that handshake twice and reopen the window
/// for the app to go away in between.
async fn try_connect_registered_preview(
    expected_fingerprint: &str,
    expected_platform: PreviewRuntimePlatform,
    start: Instant,
) -> Option<PreviewAppClient> {
    let client = PreviewAppClient::connect_registered(expected_fingerprint, expected_platform)
        .await
        .ok()?;
    info!(
        "Connected to preview app after {}ms",
        start.elapsed().as_millis()
    );
    Some(client)
}

/// Probe the configured port range for a ready preview app, keeping the connection.
async fn try_connect_polled_preview(
    tcp_config: PreviewTcpConfig,
    expected_fingerprint: &str,
    expected_platform: PreviewRuntimePlatform,
    start: Instant,
) -> Option<PreviewAppClient> {
    let client = PreviewAppClient::connect(tcp_config, expected_fingerprint, expected_platform)
        .await
        .ok()?;
    info!(
        "Connected to preview app after {}ms",
        start.elapsed().as_millis()
    );
    Some(client)
}

async fn preview_connection_result_from_device_event(
    event: Option<DeviceEvent>,
    expected_fingerprint: &str,
    expected_platform: PreviewRuntimePlatform,
    start: Instant,
) -> Option<ConnectionWaitResult> {
    match event? {
        DeviceEvent::Crashed(message) => {
            info!("App crashed after {}ms", start.elapsed().as_millis());
            Some(ConnectionWaitResult::Crashed(message))
        }
        DeviceEvent::Exited(_) => {
            info!("App exited after {}ms", start.elapsed().as_millis());
            Some(ConnectionWaitResult::Exited)
        }
        DeviceEvent::Log { level, message } => {
            info!("Preview app log event: {message}");
            if level == tracing::Level::ERROR {
                error!("{message}");
            }
            if let Some(addr) = parse_preview_listening_addr(&message)
                && let Ok(client) =
                    PreviewAppClient::connect_addr(addr, expected_fingerprint, expected_platform)
                        .await
            {
                info!(
                    "Connected to preview app after {}ms",
                    start.elapsed().as_millis()
                );
                return Some(ConnectionWaitResult::Ready(client));
            }
            None
        }
        _ => None,
    }
}

fn parse_preview_listening_addr(message: &str) -> Option<SocketAddr> {
    const PREFIX: &str = "Preview support app listening on ";
    let suffix = message.split(PREFIX).nth(1)?;
    let port = suffix.rsplit(':').next()?.trim().parse::<u16>().ok()?;
    Some(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port))
}

async fn drain_terminal_preview_event(running: &mut Pin<Box<Running>>) -> ConnectionWaitResult {
    while let Some(event) = futures_lite::future::poll_once(running.as_mut().next())
        .await
        .flatten()
    {
        match event {
            DeviceEvent::Crashed(message) => return ConnectionWaitResult::Crashed(message),
            DeviceEvent::Exited(_) => return ConnectionWaitResult::Exited,
            _ => {}
        }
    }

    ConnectionWaitResult::Timeout
}

/// Get the path to the preview support app.
fn preview_support_path() -> Result<PathBuf> {
    support_app::support_app_path("preview_support")
}

/// Root of the workspace a preview module joins.
///
/// This is the support runtime's generated FFI crate. The path is derived rather
/// than read from an opened [`Project`] because the module has to exist before the
/// support application is scaffolded: resolving the runtime's requirements reads
/// the module's own Cargo metadata.
async fn preview_support_ffi_crate_path() -> Result<PathBuf> {
    // The support application's root has to exist before its build-cache path can
    // be derived, because deriving it canonicalizes the root. On the very first
    // preview nothing has scaffolded it yet, and an empty directory is exactly
    // what the scaffolder expects to find.
    let support_path = preview_support_path()?;
    smol::fs::create_dir_all(&support_path)
        .await
        .wrap_err("Failed to create the preview support application directory")?;
    Ok(crate::water_dir::project_build_cache_dir(&support_path)
        .await?
        .join("ffi"))
}

/// Write the project's preview module into the support runtime's workspace.
///
/// Only one module lives there at a time. A module left behind by a previously
/// previewed project would still be a workspace member, and Cargo resolves every
/// member of a workspace, so a stale one whose project has since moved or been
/// deleted breaks the build of an unrelated preview.
async fn scaffold_preview_module(project: &Project) -> Result<PathBuf> {
    let support_path = preview_support_path()?;
    // Before anything reads the support runtime's workspace: one left over from
    // a different `WaterUI` checkout points its manifests at a path that may no
    // longer exist, and reading it fails before the scaffolder gets a chance to
    // notice and rebuild.
    // The project's recorded runtime path is written relative to the project,
    // so it is resolved against the project rather than against wherever the
    // CLI happens to have been invoked from.
    let runtime_path = project
        .manifest()
        .waterui_path
        .as_deref()
        .map(|path| project.root().join(path));
    support_app::discard_support_app_for_other_runtime(&support_path, runtime_path.as_deref())
        .await?;
    let workspace_root = preview_support_ffi_crate_path().await?;
    let modules_root = workspace_root.join(crate::templates::PREVIEW_MODULES_DIR);
    let crate_path = project.preview_dylib_crate_path(&workspace_root);
    if let Ok(mut entries) = smol::fs::read_dir(&modules_root).await {
        use smol::stream::StreamExt as _;
        while let Some(entry) = entries.next().await {
            let entry = entry.wrap_err("Failed to read preview modules directory")?;
            if entry.path() != crate_path {
                smol::fs::remove_dir_all(entry.path())
                    .await
                    .wrap_err("Failed to remove a stale preview module")?;
            }
        }
    }
    let crate_path = project
        .scaffold_preview_ffi_companion(&workspace_root)
        .await
        .wrap_err("Failed to scaffold the preview module")?;

    // Then refresh the support runtime, so the manifest that roots this workspace
    // is rewritten with the module now on disk. A module under a root that does
    // not declare it is rejected outright by Cargo, and the root lists whichever
    // modules it finds — so it has to be written after, never before.
    if support_path.join("Water.toml").is_file() {
        Project::open(&support_path)
            .await
            .wrap_err("Failed to open the preview support project")?;
    }
    Ok(crate_path)
}

/// Ensure the preview support app exists and matches the current project requirements.
async fn ensure_preview_support_app(path: &Path, requirements: &PreviewRequirements) -> Result<()> {
    let desired_signature = preview_signature(requirements);
    let scaffold_path = path.to_path_buf();
    let scaffold_requirements = requirements.clone();
    support_app::ensure_support_app(
        path,
        PREVIEW_METADATA_FILE,
        &desired_signature,
        "preview support",
        move || async move { scaffold_preview_app(&scaffold_path, &scaffold_requirements).await },
    )
    .await
}

/// Scaffold the preview support app as a normal playground project.
async fn scaffold_preview_app(path: &Path, requirements: &PreviewRequirements) -> Result<()> {
    use crate::project::{CreateOptions, Manifest as WaterManifest, PackageType};
    use crate::templates::TemplateContext;

    let waterui_path = requirements.waterui_path.clone();

    let options = CreateOptions {
        name: "WaterUI Preview".to_string(),
        bundle_identifier: crate::project_types::BundleIdentifier::try_from("dev.waterui.preview")
            .expect("preview support bundle identifier must be valid"),
        package_type: PackageType::Playground,
        waterui_path: waterui_path.clone(),
        author: String::new(),
    };

    // Create as normal playground project
    let project = Project::create(path, options)
        .await
        .map_err(|e| color_eyre::eyre::eyre!("Failed to create preview app: {e}"))?;

    // Mark the preview app as accessory/headless.
    let mut manifest = WaterManifest::open(project.root().join("Water.toml")).await?;
    manifest.package.accessory = true;
    manifest.save(project.root()).await?;

    let ctx = TemplateContext::for_support_playground(
        "WaterUI Preview",
        "WaterUIPreview",
        project.crate_name().clone(),
        crate::project_types::BundleIdentifier::try_from("dev.waterui.preview")
            .expect("preview support bundle identifier must be valid"),
        waterui_path,
        true,
        Some(requirements.runtime_fingerprint.clone()),
    )
    .with_preview_runtime_features(requirements.runtime_features.clone())
    .with_preview_app_dependency(
        requirements.app_crate_name.clone(),
        requirements.app_path.clone(),
    );

    crate::templates::preview::scaffold(project.root(), &ctx)
        .await
        .wrap_err("Failed to scaffold embedded preview app template")?;

    info!("Preview app scaffolded at {}", path.display());
    Ok(())
}

fn preview_signature(requirements: &PreviewRequirements) -> String {
    format!(
        "template_commit={PREVIEW_TEMPLATE_COMMIT}\nwaterui_dependency={}\nruntime_fingerprint={}\ntemplate_fingerprint={}",
        requirements.waterui_path.as_ref().map_or_else(
            || String::from("registry"),
            |path| path.display().to_string()
        ),
        requirements.runtime_fingerprint,
        crate::templates::preview::template_fingerprint(),
    )
}

async fn resolve_preview_requirements(
    project_path: &Path,
    platform: PreviewPlatform,
) -> Result<PreviewRequirements> {
    let resolved = resolve_preview_metadata(project_path, platform).await?;
    let metadata = &resolved.metadata;
    let waterui = select_unique_package(metadata, "waterui")?;
    let runtime_features = resolved_package_features(metadata, waterui)?;
    let graph_fingerprint = resolved_graph_fingerprint(metadata)?;

    if let Some(requirements) = resolve_preview_requirements_from_manifest(
        project_path,
        &runtime_features,
        &graph_fingerprint,
        &resolved.app_crate_name,
        &resolved.app_path,
    )
    .await?
    {
        return Ok(requirements);
    }
    let waterui_core = select_unique_package(metadata, "waterui-core")?;
    let runtime_identity = runtime_package_identity(waterui_core);

    let runtime_fingerprint_start = Instant::now();
    let runtime_fingerprint_base = if waterui.source.is_none() {
        let waterui_root = waterui
            .manifest_path
            .as_std_path()
            .parent()
            .map(Path::to_path_buf)
            .ok_or_else(|| color_eyre::eyre::eyre!("Failed to derive waterui package root path"))?;
        let fingerprint = compute_runtime_fingerprint(&waterui_root, &runtime_identity).await?;
        info!(
            waterui_root = %waterui_root.display(),
            elapsed_ms = runtime_fingerprint_start.elapsed().as_millis(),
            "Preview computed dev-mode runtime fingerprint"
        );
        return Ok(PreviewRequirements {
            waterui_path: Some(waterui_root),
            runtime_fingerprint: runtime_fingerprint(
                &fingerprint,
                &runtime_features,
                &graph_fingerprint,
            ),
            runtime_features,
            app_crate_name: resolved.app_crate_name,
            app_path: resolved.app_path,
        });
    } else {
        let source = waterui
            .source
            .as_ref()
            .map(ToString::to_string)
            .expect("registry dependency must have a source");
        info!(
            package = %runtime_identity,
            source = %source,
            elapsed_ms = runtime_fingerprint_start.elapsed().as_millis(),
            "Preview resolved release-mode runtime fingerprint"
        );
        format!("{runtime_identity}:source:{source}")
    };

    Ok(PreviewRequirements {
        waterui_path: None,
        runtime_fingerprint: runtime_fingerprint(
            &runtime_fingerprint_base,
            &runtime_features,
            &graph_fingerprint,
        ),
        runtime_features,
        app_crate_name: resolved.app_crate_name,
        app_path: resolved.app_path,
    })
}

async fn resolve_preview_requirements_from_manifest(
    project_path: &Path,
    runtime_features: &[String],
    graph_fingerprint: &str,
    app_crate_name: &crate::project_types::CrateName,
    app_path: &Path,
) -> Result<Option<PreviewRequirements>> {
    let manifest_open_start = Instant::now();
    let manifest = crate::project::Manifest::open(project_path.join("Water.toml"))
        .await
        .map_err(|error| {
            color_eyre::eyre::eyre!(
                "Failed to read Water.toml for preview requirements at {}: {error}",
                project_path.display()
            )
        })?;
    info!(
        project_path = %project_path.display(),
        elapsed_ms = manifest_open_start.elapsed().as_millis(),
        "Preview opened Water.toml for runtime requirements"
    );
    let Some(waterui_path) = manifest.waterui_path else {
        return Ok(None);
    };

    let resolve_root_start = Instant::now();
    let waterui_root = resolve_waterui_root_from_manifest(project_path, &waterui_path).await?;
    info!(
        project_path = %project_path.display(),
        waterui_root = %waterui_root.display(),
        elapsed_ms = resolve_root_start.elapsed().as_millis(),
        "Preview resolved waterui root from manifest"
    );

    let runtime_identity_start = Instant::now();
    let runtime_identity = runtime_identity_from_waterui_root(&waterui_root).await?;
    info!(
        waterui_root = %waterui_root.display(),
        elapsed_ms = runtime_identity_start.elapsed().as_millis(),
        "Preview resolved runtime identity"
    );

    let runtime_fingerprint_start = Instant::now();
    let runtime_fingerprint = runtime_fingerprint(
        &compute_runtime_fingerprint(&waterui_root, &runtime_identity).await?,
        runtime_features,
        graph_fingerprint,
    );
    info!(
        project_path = %project_path.display(),
        waterui_root = %waterui_root.display(),
        elapsed_ms = runtime_fingerprint_start.elapsed().as_millis(),
        "Preview resolved runtime requirements from Water.toml"
    );

    Ok(Some(PreviewRequirements {
        waterui_path: Some(waterui_root),
        runtime_fingerprint,
        runtime_features: runtime_features.to_vec(),
        app_crate_name: app_crate_name.clone(),
        app_path: app_path.to_path_buf(),
    }))
}

async fn resolve_preview_metadata(
    project_path: &Path,
    platform: PreviewPlatform,
) -> Result<ResolvedPreviewMetadata> {
    let project = Project::open_for_preview_build(project_path).await?;
    ensure_project_dev_feature_for_preview(&project).await?;
    let manifest_path = scaffold_preview_module(&project).await?.join("Cargo.toml");
    let app_crate_name = project.crate_name().clone();
    let app_path = project.root().to_path_buf();
    let metadata_start = Instant::now();
    let metadata_manifest_path = manifest_path.clone();
    let abi_feature = PreviewLinkMode::for_platform(platform)
        .abi_feature
        .to_string();
    let metadata = smol::unblock(move || {
        let mut command = cargo_metadata::MetadataCommand::new();
        command
            .manifest_path(metadata_manifest_path)
            .features(cargo_metadata::CargoOpt::SomeFeatures(vec![abi_feature]));
        command.exec()
    })
    .await
    .wrap_err("Failed to resolve user project Cargo metadata with its dev feature")?;
    info!(
        project_path = %project_path.display(),
        elapsed_ms = metadata_start.elapsed().as_millis(),
        "Preview resolved user project cargo metadata"
    );
    Ok(ResolvedPreviewMetadata {
        metadata,
        app_crate_name,
        app_path,
    })
}

fn resolved_package_features(
    metadata: &cargo_metadata::Metadata,
    package: &cargo_metadata::Package,
) -> Result<Vec<String>> {
    let resolve = metadata.resolve.as_ref().ok_or_else(|| {
        color_eyre::eyre::eyre!("Cargo metadata omitted its dependency resolution graph")
    })?;
    let node = resolve
        .nodes
        .iter()
        .find(|node| node.id == package.id)
        .ok_or_else(|| {
            color_eyre::eyre::eyre!(
                "Cargo metadata omitted the resolution node for package `{}`",
                package.name
            )
        })?;
    let mut features = node
        .features
        .iter()
        .map(ToString::to_string)
        .collect::<Vec<_>>();
    features.sort_unstable();
    features.dedup();
    if !features.iter().any(|feature| feature == "dynamic_linking") {
        bail!("Preview requires the project dev feature to enable waterui/dynamic_linking");
    }
    Ok(features)
}

fn resolved_graph_fingerprint(metadata: &cargo_metadata::Metadata) -> Result<String> {
    let resolve = metadata.resolve.as_ref().ok_or_else(|| {
        color_eyre::eyre::eyre!("Cargo metadata omitted its dependency resolution graph")
    })?;
    let mut units = resolve
        .nodes
        .iter()
        .map(|node| {
            let mut features = node
                .features
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>();
            features.sort_unstable();
            format!("{}|{}", node.id, features.join(","))
        })
        .collect::<Vec<_>>();
    units.sort_unstable();
    let mut hasher = sha2::Sha256::new();
    for unit in units {
        hasher.update(unit.as_bytes());
        hasher.update(b"\n");
    }
    Ok(hex::encode(hasher.finalize()))
}

fn runtime_fingerprint(base: &str, features: &[String], graph_fingerprint: &str) -> String {
    format!(
        "{base}|features={}|graph={}|profile={}",
        features.join(","),
        graph_fingerprint,
        runtime_profile_tag()
    )
}

async fn resolve_waterui_root_from_manifest(
    project_path: &Path,
    waterui_path: &str,
) -> Result<PathBuf> {
    let candidate = PathBuf::from(waterui_path);
    let resolved = if candidate.is_absolute() {
        candidate
    } else {
        project_path.join(candidate)
    };
    smol::fs::canonicalize(&resolved).await.wrap_err_with(|| {
        format!(
            "Failed to resolve `waterui_path = {waterui_path}` from {}",
            project_path.display()
        )
    })
}

async fn runtime_identity_from_waterui_root(waterui_root: &Path) -> Result<String> {
    let core_manifest_path = waterui_root.join("core").join("Cargo.toml");
    let manifest_text = smol::fs::read_to_string(&core_manifest_path)
        .await
        .wrap_err("Failed to read waterui-core Cargo.toml for preview requirements")?;
    let manifest: toml::Table = manifest_text
        .parse()
        .wrap_err("Failed to parse waterui-core Cargo.toml for preview requirements")?;
    let package = manifest
        .get("package")
        .and_then(toml::Value::as_table)
        .ok_or_else(|| {
            color_eyre::eyre::eyre!(
                "Invalid waterui-core manifest at {}: missing package section",
                core_manifest_path.display()
            )
        })?;
    let package_name = package
        .get("name")
        .and_then(toml::Value::as_str)
        .ok_or_else(|| {
            color_eyre::eyre::eyre!(
                "Invalid waterui-core manifest at {}: missing package.name",
                core_manifest_path.display()
            )
        })?;
    if package_name != "waterui-core" {
        bail!(
            "Invalid preview runtime root {}: expected core/Cargo.toml package `waterui-core`, found `{}`",
            waterui_root.display(),
            package_name
        );
    }
    let package_version = package
        .get("version")
        .and_then(toml::Value::as_str)
        .ok_or_else(|| {
            color_eyre::eyre::eyre!(
                "Invalid waterui-core manifest at {}: missing package.version",
                core_manifest_path.display()
            )
        })?;

    Ok(format!("{package_name}@{package_version}"))
}

fn select_unique_package<'a>(
    metadata: &'a cargo_metadata::Metadata,
    name: &str,
) -> Result<&'a cargo_metadata::Package> {
    let mut matches = metadata.packages.iter().filter(|p| p.name == name);
    let first = matches.next().ok_or_else(|| {
        color_eyre::eyre::eyre!("Could not resolve package `{name}` from metadata")
    })?;
    if matches.next().is_some() {
        bail!(
            "Multiple `{name}` packages were resolved. Preview requires a single resolved `{name}` package to guarantee compatibility."
        );
    }
    Ok(first)
}

#[cfg(test)]
mod tests {
    use super::{PreviewLinkMode, PreviewPlatform};

    #[test]
    fn macos_preview_uses_shared_waterui_runtime() {
        let link_mode = PreviewLinkMode::for_platform(PreviewPlatform::Macos);

        assert_eq!(link_mode, PreviewLinkMode::MACOS_DYNAMIC);
        assert_eq!(link_mode.crate_type_override, None);
        assert!(link_mode.prefer_dynamic);
        assert_eq!(
            link_mode.abi_feature,
            crate::templates::preview_ffi::APPLE_ABI_FEATURE
        );
        assert_eq!(
            link_mode.signature_tag(),
            "preview-dylib+shared-waterui-dylib+prefer-dynamic"
        );
    }

    #[test]
    fn remote_preview_platforms_use_shared_runtime_cdylibs() {
        for platform in [PreviewPlatform::Ios, PreviewPlatform::IosSimulator] {
            let link_mode = PreviewLinkMode::for_platform(platform);

            assert_eq!(link_mode, PreviewLinkMode::PORTABLE_DYNAMIC);
            assert_eq!(link_mode.crate_type_override, Some("cdylib"));
            assert!(link_mode.prefer_dynamic);
            assert_eq!(
                link_mode.abi_feature,
                crate::templates::preview_ffi::APPLE_ABI_FEATURE
            );
            assert_eq!(
                link_mode.signature_tag(),
                "preview-cdylib+shared-waterui-dylib+prefer-dynamic"
            );
        }
    }

    #[test]
    fn android_preview_uses_the_jni_shared_runtime_abi() {
        let link_mode = PreviewLinkMode::for_platform(PreviewPlatform::Android);
        assert_eq!(link_mode, PreviewLinkMode::ANDROID_DYNAMIC);
        assert_eq!(link_mode.crate_type_override, Some("cdylib"));
        assert!(link_mode.prefer_dynamic);
        assert_eq!(
            link_mode.abi_feature,
            crate::templates::preview_ffi::ANDROID_ABI_FEATURE
        );
    }
}