node-app-build 5.23.2

Mini app developer CLI: scaffold, validate, package node-app-* Debian packages
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
//! Platform-repo mode for `node-app dev`.
//!
//! When invoked from the node monorepo (detected by the presence of
//! `infra/debian/platform-depends`), boot the platform server here AND
//! auto-resolve every node-app the platform depends on, building & staging
//! each one before the daemon starts.
//!
//! The list of platform-side app deps is parsed from
//! `infra/debian/platform-depends`: any non-blank, non-comment line beginning
//! with `node-app-` becomes an app name (prefix stripped).
//!
//! Unlike the app-developer flow, this mode does NOT sideload via IPC and
//! does NOT watch source files — the platform's own inotify watcher picks up
//! pre-staged apps on boot, and contributor edits to the platform crates are
//! handled via their own cargo workflow.

use std::path::{Path, PathBuf};
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};

use anyhow::{Context, Result};

use super::host::{self, InstanceProfile};
use super::sources_resolver;
use super::{build_and_stage, load_manifest, DevArgs, SHUTDOWN_REQUESTED};
use crate::tui::{self, BuildScope, DevSignals, LogSource, ServiceStatus};

/// Entry point for platform-repo dev mode.
///
/// Returns once Ctrl-C / TUI quit is observed and the daemon has been asked
/// to shut down.
pub fn run(platform_root: &Path, args: &DevArgs<'_>) -> Result<()> {
    // ── Parse platform-depends FIRST so the TUI can seed its sidebar ──────────
    // (TUI runs in another thread; we have to know the app list before
    // constructing AppState. Errors here print to stderr — no TUI active yet.)
    let depends_path = platform_root.join("infra/debian/platform-depends");
    let app_names = parse_platform_depends(&depends_path)
        .with_context(|| format!("parse {}", depends_path.display()))?;

    // Install the OS signal handler up front so Ctrl+C interrupts in-flight
    // dep builds even before the TUI thread is running (no-TUI mode, or
    // before pre-boot staging completes in TUI mode).
    install_signal_handler();

    // ── TUI setup (mirrors app-mode in dev::run) ──────────────────────────────
    let use_tui = !args.no_tui && !args.once && tui::is_tty();
    let (log_tx_opt, signals_opt, tui_handle) = if use_tui {
        let (tx, rx, signals) = tui::setup();
        // Mirror dev::run line 147: register the TUI's quit flag globally so
        // build polling loops (`run_in_with_sink`, `run_build_cmd`) can
        // observe `q` / Ctrl+C-as-key and kill the cargo child. Without this
        // the TUI swallows Ctrl+C in raw mode and builds run to completion.
        let _ = super::QUIT_FLAG.set(signals.quit_requested.clone());
        // Repurpose `instance_names` as the dep-app list: MonorepoHost::tail_logs
        // tags each line with `[<app>] ` and AppState::push_log routes those
        // into per-app buffers. Mouse-click on an app in the sidebar sets
        // `instance_filter` so the App pane shows just that app's logs.
        let mut app_state = tui::state::AppState::new(
            "node-platform".to_string(),
            String::new(),
            app_names.clone(),
        );
        app_state.seed_app_list(&app_names);
        // Resolve node names up-front (same logic as the profile-resolution
        // block below) so the TUI's nodes sidebar can show every instance
        // immediately, even before the daemons have booted.
        let node_names: Vec<String> = if args.instances.is_empty() {
            vec!["alice".to_string()]
        } else {
            args.instances.clone()
        };
        // Single-instance runs don't need the nodes sidebar — it's just
        // visual noise. Skip seeding so the box stays hidden in that case.
        if node_names.len() > 1 {
            app_state.seed_node_list(&node_names);
        }
        let signals_clone = signals.clone();
        let handle = std::thread::spawn(move || {
            if let Err(e) = tui::run(rx, app_state, signals_clone) {
                eprintln!("TUI error: {e}");
            }
        });
        (Some(tx), Some(signals), Some(handle))
    } else {
        (None, None, None)
    };

    // Guard to flush TUI cleanly on every exit path.
    struct TuiGuard {
        signals: Option<DevSignals>,
        handle: Option<std::thread::JoinHandle<()>>,
    }
    impl Drop for TuiGuard {
        fn drop(&mut self) {
            if let Some(sigs) = &self.signals {
                sigs.mark_shutdown_complete();
            }
            if let Some(h) = self.handle.take() {
                let _ = h.join();
            }
        }
    }
    let _tui_guard = TuiGuard {
        signals: signals_opt.clone(),
        handle: tui_handle,
    };

    tui::sys_log(
        log_tx_opt.as_ref(),
        format!(
            "→ platform mode (cwd = {})  reading infra/debian/platform-depends…",
            platform_root.display()
        ),
    );
    if app_names.is_empty() {
        tui::sys_log(
            log_tx_opt.as_ref(),
            "→ no node-app-* entries in platform-depends; will boot server with no extra apps.",
        );
    } else {
        tui::sys_log(
            log_tx_opt.as_ref(),
            format!("{} node-app dep(s) declared: {}", app_names.len(), app_names.join(", ")),
        );
    }

    // ── Resolve sources (sibling → cache → clone) ─────────────────────────────
    let resolved_paths = sources_resolver::resolve(
        platform_root,
        &app_names,
        &args.dep_paths,
        log_tx_opt.as_ref(),
    )?;

    // Merge with explicit --dep flags (user can pass extras not in
    // platform-depends, or override one of the listed apps).
    let mut all_dep_paths: Vec<PathBuf> = args.dep_paths.clone();
    all_dep_paths.extend(resolved_paths);

    // Publish each dep's resolved on-disk path to the TUI so the apps
    // sidebar can show *where* each app lives (sibling vs cache vs --dep
    // override) and the log-pane title can show the full path when an app
    // is focused. Best-effort: a dep with an unparseable manifest just
    // shows up without a path.
    for p in &all_dep_paths {
        if let Ok(m) = load_manifest(p) {
            tui::update_app_path(log_tx_opt.as_ref(), &m.name, p.clone());
        }
    }

    // ── Resolve instance profiles ─────────────────────────────────────────────
    // Platform mode now honours --instances alice,bob so contributors can
    // exercise multi-node flows (gossip, P2P, payments). The TUI's app
    // sidebar still works as a single filter axis (apps); per-node logs are
    // distinguishable via the `[<node>] ` prefix MonorepoHost::spawn_daemon
    // already injects into stdout/stderr.
    let profiles: Vec<InstanceProfile> = if args.instances.is_empty() {
        vec![InstanceProfile::alice()]
    } else {
        args.instances
            .iter()
            .map(|n| InstanceProfile::from_name(n))
            .collect::<anyhow::Result<Vec<_>>>()?
    };
    tui::sys_log(
        log_tx_opt.as_ref(),
        format!(
            "→ booting {} instance(s): {}",
            profiles.len(),
            profiles.iter().map(|p| p.name.as_str()).collect::<Vec<_>>().join(", ")
        ),
    );

    // ── Build one MonorepoHost per instance, all targeted at the platform ────
    let mode = host::Mode::Monorepo {
        path: platform_root.to_path_buf(),
    };
    let hosts: Vec<Box<dyn host::DaemonHost>> = profiles
        .iter()
        .map(|p| {
            host::for_mode(
                mode.clone(),
                p.clone(),
                // socket_override / dev_dir_override only make sense for a
                // single instance — for multi-instance let MonorepoHost
                // derive its own per-instance paths.
                if profiles.len() == 1 { args.socket_override } else { None },
                if profiles.len() == 1 { args.dev_dir_override } else { None },
                log_tx_opt.clone(),
            )
        })
        .collect();

    // ── Pre-boot dep staging ─────────────────────────────────────────────────
    // Stage into EVERY host's dev-dir so each node loads the same set of
    // dep apps on first boot. We only build each dep once and copy from the
    // canonical staging location to the other instance dev-dirs.
    if !all_dep_paths.is_empty() {
        let pre_start_dev_dirs: Vec<PathBuf> = hosts
            .iter()
            .filter_map(|h| h.pre_start_dev_dir())
            .collect();
        if !pre_start_dev_dirs.is_empty() {
            tui::sys_log(
                log_tx_opt.as_ref(),
                format!(
                    "→ staging {} dep(s) into {} instance dev-dir(s) (pre-boot)…",
                    all_dep_paths.len(),
                    pre_start_dev_dirs.len()
                ),
            );
            stage_with_status(&all_dep_paths, &pre_start_dev_dirs, log_tx_opt.as_ref())?;
        }
    }

    // ── Boot the platform daemons sequentially ───────────────────────────────
    // Sequential boot avoids cargo build-lock contention; each daemon's
    // logs are prefixed `[alice] ` / `[bob] ` so they're distinguishable.
    // (Signal handler is installed at function entry.)
    let mut handles: Vec<host::DaemonHandle> = Vec::with_capacity(hosts.len());
    for host_impl in &hosts {
        let handle = host_impl.ensure_running().context("start platform daemon")?;
        tui::sys_log(
            log_tx_opt.as_ref(),
            format!("✓ platform up — {}", handle.banner),
        );
        handles.push(handle);
    }

    // Post-boot fallback (covers any host without a pre-start dev-dir).
    if !all_dep_paths.is_empty() {
        let post_start_dirs: Vec<PathBuf> = hosts
            .iter()
            .zip(&handles)
            .filter(|(h, _)| h.pre_start_dev_dir().is_none())
            .map(|(_, handle)| handle.dev_dir.clone())
            .collect();
        if !post_start_dirs.is_empty() {
            tui::sys_log(
                log_tx_opt.as_ref(),
                format!(
                    "→ staging {} dep(s) into {} instance(s) (post-boot)…",
                    all_dep_paths.len(),
                    post_start_dirs.len()
                ),
            );
            stage_with_status(&all_dep_paths, &post_start_dirs, log_tx_opt.as_ref())?;
        }
    }

    if args.once {
        tui::sys_log(
            log_tx_opt.as_ref(),
            "✓ --once: platform booted and deps staged; shutting down.",
        );
        for h in &hosts {
            h.shutdown();
        }
        return Ok(());
    }

    // Stream per-app logs from every node. tail_logs internally prefixes
    // lines with `[<app>] ` so the existing per-app routing aggregates
    // across nodes; the original `[<node>] ` prefix on daemon stdout keeps
    // node distinction visible in the unified Daemon pane.
    for h in &hosts {
        for name in &app_names {
            h.tail_logs(name);
        }
    }

    tui::sys_log(
        log_tx_opt.as_ref(),
        "→ platform running. Edit platform code in the monorepo and rerun to pick up changes. \
         Ctrl-C to stop.",
    );

    // ── Block until shutdown is requested ────────────────────────────────────
    loop {
        if SHUTDOWN_REQUESTED.load(Ordering::SeqCst) {
            break;
        }
        if let Some(sigs) = &signals_opt {
            if sigs.should_quit() {
                break;
            }
            if sigs.take_restart() {
                let started = Instant::now();
                banner(log_tx_opt.as_ref(), "⟳ RESTART REQUESTED (r) — system daemon");
                for h in &hosts {
                    if let Err(e) = h.restart() {
                        tui::sys_log(log_tx_opt.as_ref(), format!("✗ restart failed: {:#}", e));
                    }
                }
                banner(
                    log_tx_opt.as_ref(),
                    format!("✓ RESTART COMPLETE ({:.1}s)", started.elapsed().as_secs_f32()),
                );
            }
            if let Some(scope) = sigs.take_build_scope() {
                let started = Instant::now();
                banner(
                    log_tx_opt.as_ref(),
                    format!("⟳ MANUAL REBUILD ({}) TRIGGERED", scope_label(scope)),
                );

                let do_apps = matches!(scope, BuildScope::Apps | BuildScope::All);
                let do_system = matches!(scope, BuildScope::System | BuildScope::All);
                let do_ui = matches!(scope, BuildScope::Ui | BuildScope::All);

                // 1. Apps: restage every node-app dep (build_and_stage rebuilds each).
                if do_apps {
                    if all_dep_paths.is_empty() {
                        tui::sys_log(
                            log_tx_opt.as_ref(),
                            "→ apps: no node-app deps declared; nothing to rebuild.",
                        );
                    } else {
                        let dev_dirs: Vec<PathBuf> =
                            handles.iter().map(|h| h.dev_dir.clone()).collect();
                        tui::sys_log(
                            log_tx_opt.as_ref(),
                            format!("→ rebuilding {} app dep(s)…", all_dep_paths.len()),
                        );
                        if let Err(e) =
                            stage_with_status(&all_dep_paths, &dev_dirs, log_tx_opt.as_ref())
                        {
                            tui::sys_log(
                                log_tx_opt.as_ref(),
                                format!("✗ app rebuild failed: {:#}", e),
                            );
                        }
                    }
                }

                // 2. System daemon: host.restart() runs `cargo build -p node-server`
                //    and respawns the daemon, surfacing Daemon-pane status updates.
                if do_system {
                    for h in &hosts {
                        if let Err(e) = h.restart() {
                            tui::sys_log(
                                log_tx_opt.as_ref(),
                                format!("✗ system rebuild/restart failed: {:#}", e),
                            );
                        }
                    }
                }

                // 3. UI: Vite already hot-reloads on source changes, so a
                //    forced rebuild here would just churn the browser. For now
                //    we just acknowledge the lane in the UiServer tab; if a
                //    hard restart is needed later, restart the spawned UI
                //    child via MonorepoHost. We don't expose that yet because
                //    it would tear down the user's open Vite session.
                if do_ui {
                    tui::sys_log(
                        log_tx_opt.as_ref(),
                        "→ ui: Vite HMR is active — no rebuild needed. \
                         Touch a source file to trigger a hot reload.",
                    );
                    tui::update_status(
                        log_tx_opt.as_ref(),
                        LogSource::UiServer,
                        ServiceStatus::Ready,
                        Some("HMR — no rebuild needed".into()),
                    );
                }

                banner(
                    log_tx_opt.as_ref(),
                    format!(
                        "✓ REBUILD COMPLETE ({:.1}s)",
                        started.elapsed().as_secs_f32()
                    ),
                );
            }
        }
        std::thread::sleep(Duration::from_millis(200));
    }

    tui::sys_log(log_tx_opt.as_ref(), "→ shutting down…");
    for h in &hosts {
        h.shutdown();
    }
    drop(log_tx_opt);
    Ok(())
}

/// Build & stage each dep, publishing per-app status to the TUI sidebar.
/// Building → Loaded { reloads: 1 } on success; Failed(message) on error.
///
/// `dev_dirs` is the list of all instance dev-dirs that should receive a
/// copy of the staged dep. Each dep is built ONCE (against the first dev-dir
/// via `build_and_stage`); the staged output is then mirrored byte-for-byte
/// into every subsequent dev-dir via `copy_dir_recursive`. Returns the first
/// error encountered (after marking that app failed).
fn stage_with_status(
    dep_paths: &[PathBuf],
    dev_dirs: &[PathBuf],
    log_tx: Option<&crate::tui::LogTx>,
) -> Result<()> {
    if dev_dirs.is_empty() {
        return Ok(());
    }
    for dep_path in dep_paths {
        // Best-effort read of the manifest name so per-app status events line
        // up with the sidebar entries seeded from platform-depends. If the
        // manifest is unreadable we still attempt the stage; build_and_stage
        // will surface the real error.
        let manifest = load_manifest(dep_path).ok();
        let app_name = manifest.as_ref().map(|m| m.name.clone());

        // platform-runtime deps (e.g. bun-runtime) are packaging-only targets
        // — nothing to build, stage, or mirror. Mark the sidebar entry as a
        // no-op and continue to the next dep.
        if manifest
            .as_ref()
            .map(|m| m.app_type.eq_ignore_ascii_case("platform-runtime"))
            .unwrap_or(false)
        {
            if let Some(ref n) = app_name {
                tui::update_app_status(
                    log_tx,
                    n,
                    ServiceStatus::Loaded { reloads: 0 },
                    Some("platform-runtime (not staged)".to_string()),
                );
            }
            continue;
        }

        if let Some(ref n) = app_name {
            tui::update_app_status(log_tx, n, ServiceStatus::Building, None);
        }

        // Build once + stage into the first dev-dir.
        let first_dir = &dev_dirs[0];
        if let Err(e) = build_and_stage(dep_path, first_dir, log_tx) {
            if let Some(ref n) = app_name {
                let short = e.to_string().chars().take(60).collect::<String>();
                tui::update_app_status(log_tx, n, ServiceStatus::Failed(short), None);
            }
            return Err(e);
        }

        // Mirror the staged output to every other dev-dir.
        if let Some(name) = &app_name {
            let src = first_dir.join(name);
            for dst_root in &dev_dirs[1..] {
                let dst = dst_root.join(name);
                if dst.exists() {
                    std::fs::remove_dir_all(&dst).ok();
                }
                if let Err(e) = super::copy_dir_recursive(&src, &dst) {
                    let short = e.to_string().chars().take(60).collect::<String>();
                    tui::update_app_status(log_tx, name, ServiceStatus::Failed(short), None);
                    return Err(e);
                }
            }
        }

        if let Some(ref n) = app_name {
            let detail = if dev_dirs.len() > 1 {
                format!("staged ×{}", dev_dirs.len())
            } else {
                "staged".into()
            };
            tui::update_app_status(
                log_tx,
                n,
                ServiceStatus::Loaded { reloads: 1 },
                Some(detail),
            );
        }
    }
    Ok(())
}

/// Parse `infra/debian/platform-depends`: yield each `node-app-<name>` line's
/// stripped name. Blank lines and comments (`#`) are ignored. Lines that
/// don't start with `node-app-` are skipped (they're system packages).
pub fn parse_platform_depends(path: &Path) -> Result<Vec<String>> {
    let text = std::fs::read_to_string(path)
        .with_context(|| format!("read {}", path.display()))?;
    let mut out = Vec::new();
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        // Strip dpkg version constraint trailers, e.g. "node-app-foo (>= 1.0)".
        let pkg = line
            .split_whitespace()
            .next()
            .unwrap_or("")
            .trim();
        if let Some(rest) = pkg.strip_prefix("node-app-") {
            if !rest.is_empty() {
                out.push(rest.to_string());
            }
        }
    }
    Ok(out)
}

#[cfg(unix)]
fn install_signal_handler() {
    use std::sync::atomic::AtomicBool;
    static INSTALLED: AtomicBool = AtomicBool::new(false);
    if INSTALLED.swap(true, Ordering::SeqCst) {
        return;
    }
    unsafe {
        libc::signal(
            libc::SIGINT,
            super::handle_shutdown_signal as *const () as libc::sighandler_t,
        );
        libc::signal(
            libc::SIGTERM,
            super::handle_shutdown_signal as *const () as libc::sighandler_t,
        );
    }
}

#[cfg(not(unix))]
fn install_signal_handler() {}

/// Short human label for a rebuild scope, used inside the banner line so the
/// user can tell at a glance which slice they asked for.
fn scope_label(scope: BuildScope) -> &'static str {
    match scope {
        BuildScope::All => "all",
        BuildScope::System => "system",
        BuildScope::Apps => "apps",
        BuildScope::Ui => "ui",
    }
}

/// Emit a bracketed banner via the TUI System pane so manual rebuild / restart
/// activity is impossible to miss in the log stream. Three lines (rule, label,
/// rule) keep the boundary visually distinct from regular `→` / `✓` lines.
fn banner(log_tx: Option<&crate::tui::LogTx>, label: impl Into<String>) {
    const RULE: &str =
        "════════════════════════════════════════════════════════════════════";
    tui::sys_log(log_tx, "");
    tui::sys_log(log_tx, RULE);
    tui::sys_log(log_tx, format!("  {}", label.into()));
    tui::sys_log(log_tx, RULE);
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn parse_strips_prefix_and_skips_non_app_lines() {
        let tmp = TempDir::new().unwrap();
        let p = tmp.path().join("platform-depends");
        fs::write(
            &p,
            "# header comment\n\
             jq\n\
             curl\n\
             \n\
             # Built-in node apps\n\
             node-app-esp32-bridge\n\
             node-app-discovery\n\
             # trailing comment\n",
        )
        .unwrap();

        let names = parse_platform_depends(&p).unwrap();
        assert_eq!(names, vec!["esp32-bridge", "discovery"]);
    }

    #[test]
    fn parse_handles_version_constraints() {
        let tmp = TempDir::new().unwrap();
        let p = tmp.path().join("platform-depends");
        fs::write(&p, "node-app-foo (>= 1.2.3)\n").unwrap();
        assert_eq!(parse_platform_depends(&p).unwrap(), vec!["foo"]);
    }

    #[test]
    fn parse_skips_empty_node_app_prefix() {
        let tmp = TempDir::new().unwrap();
        let p = tmp.path().join("platform-depends");
        fs::write(&p, "node-app-\nnode-app-real\n").unwrap();
        assert_eq!(parse_platform_depends(&p).unwrap(), vec!["real"]);
    }

    #[test]
    fn parse_missing_file_errors() {
        let tmp = TempDir::new().unwrap();
        let p = tmp.path().join("nope");
        assert!(parse_platform_depends(&p).is_err());
    }
}