zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
//! `zc agent install | uninstall | status` (spec §6.1).

use crate::agent::client::AgentClient;
use crate::agent::config::AgentConfig;
use crate::agent::launchd::Launchctl;
use std::path::Path;
use std::time::{Duration, Instant};

/// The `Mesh` row of `zc agent status` (mesh-routes §5), or `None` for an
/// agent from before the mesh route was reported, which sends no `mesh`.
pub fn mesh_line(m: &serde_json::Value) -> Option<String> {
    let address = m["address"].as_str().unwrap_or("?");
    let reach = if m["reachable"] == true {
        "reachable"
    } else {
        "not reachable"
    };
    Some(match m["route"].as_str()? {
        "host" => format!(
            "host VPN {} ({address}) · {reach}",
            m["interface"].as_str().unwrap_or("?")
        ),
        "proxy" => format!(
            "via the {} container ({address}) · {reach}",
            m["interface"].as_str().unwrap_or("zakuro-wg")
        ),
        _ => "not connected — run zc connect".to_string(),
    })
}

pub fn format_status(s: &serde_json::Value) -> String {
    let m = &s["this_mac"];
    let mut out = format!(
        "  This Mac   {} · broker {} · workers {}/{} running ({} busy)\n",
        if m["sharing"] == true {
            "sharing"
        } else {
            "paused"
        },
        m["broker"].as_str().unwrap_or("?"),
        m["workers"]["running"],
        m["workers"]["desired"],
        m["workers"]["busy"],
    );
    if let Some(line) = mesh_line(&s["mesh"]) {
        out += &format!("  Mesh       {line}\n");
    }
    let price = &s["prices"]["this_mac"];
    if let Some(p) = price["effective_per_hour"].as_f64() {
        out += &format!(
            "  Price      {p} cr/h ({})\n",
            price["state"].as_str().unwrap_or("?")
        );
    }
    if s["account"].is_object() {
        out += &format!(
            "  Account    {} · ¥{}\n",
            s["account"]["username"].as_str().unwrap_or("?"),
            s["account"]["balance"]
        );
    }
    if s["earnings"].is_object() {
        out += &format!(
            "  Earnings   {} today · {} last 7 days\n",
            s["earnings"]["today"], s["earnings"]["last_7d"]
        );
    }
    // Only once the hub has answered: `devices` is null until then, and
    // "Devices 0/0 online" would read as "you have no devices".
    if s["devices"].is_array() {
        out += &format!(
            "  Devices    {}/{} online\n",
            s["devices_online"], s["devices_total"]
        );
    }
    for p in s["problems"].as_array().into_iter().flatten() {
        let hint = p["hint"]
            .as_str()
            .map(|h| format!(" — {h}"))
            .unwrap_or_default();
        out += &format!("  ! {}{hint}\n", p["message"].as_str().unwrap_or(""));
        if let Some(d) = p["detail"].as_str().and_then(failure_line) {
            out += &format!("    {d}\n");
        }
    }
    out
}

/// Case-insensitive markers of a line that explains why something died,
/// rather than merely something it warned about along the way.
const FAILURE_MARKERS: &[&str] = &[
    "error",
    "exception",
    "traceback",
    "panic",
    "fatal",
    "refus",
    "fail",
    "critical",
];

/// The line of a problem's `detail` that explains the failure, marked `…`
/// when there was more: `worker_crashloop` carries a 20-line log tail, and
/// the status screen is not the place for it. `None` for a detail that is
/// only whitespace.
///
/// The tail's first line is whatever the process happened to warn about
/// first -- often a library `DeprecationWarning` -- which is rarely why it
/// died. The last line that looks like an error is a far better default, so
/// that is preferred; only when nothing in the tail looks like an error do
/// we fall back to its first line (#269).
fn failure_line(detail: &str) -> Option<String> {
    let lines: Vec<&str> = detail
        .trim()
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .collect();
    let (&first, rest) = lines.split_first()?;
    let chosen = lines
        .iter()
        .rev()
        .find(|l| {
            let lower = l.to_lowercase();
            FAILURE_MARKERS.iter().any(|m| lower.contains(m))
        })
        .copied()
        .unwrap_or(first);
    Some(match rest.is_empty() {
        true => chosen.to_string(),
        false => format!("{chosen}…"),
    })
}

pub fn status(json: bool) -> i32 {
    let Some(dir) = crate::credentials::dir().map(|d| d.join("agent")) else {
        eprintln!("zc agent: no HOME or ZAKURO_HOME");
        return 1;
    };
    let summary = AgentClient::from_dir(&dir)
        .ok_or_else(|| "no ~/.zakuro/agent/agent.json".to_string())
        .and_then(|c| c.summary(Duration::from_secs(2)));
    match summary {
        Ok(s) if json => {
            println!("{}", serde_json::to_string_pretty(&s).unwrap_or_default());
            0
        }
        Ok(s) => {
            print!("{}", format_status(&s));
            0
        }
        Err(e) => {
            eprintln!("zc agent is not reachable: {e}");
            1
        }
    }
}

/// The install logic, minus anything macOS-specific: `install_and_wait`,
/// then a one-line report. Platform-neutral so it runs and is tested on
/// every OS; only the no-arg `install()` below is macOS-gated.
pub fn install_with(
    launchctl: Launchctl,
    domain: &str,
    exe: &Path,
    home: &Path,
    env: &[(&str, String)],
    cfg: &AgentConfig,
) -> i32 {
    match install_and_wait(launchctl, domain, exe, home, env, cfg) {
        Ok(port) => {
            println!(
                "✓ zc agent is running on 127.0.0.1:{port} (launchd {})",
                crate::agent::launchd::LABEL
            );
            0
        }
        Err(e) => {
            eprintln!("{e}");
            1
        }
    }
}

/// Write the plist via `crate::agent::launchd::install`, then wait up to 5 s
/// for the agent to answer. The port returned is read back from `agent.json`
/// once the agent answers on it: the port the agent launchd started really
/// bound, whatever the installing shell's config asked for.
pub fn install_and_wait(
    launchctl: Launchctl,
    domain: &str,
    exe: &Path,
    home: &Path,
    env: &[(&str, String)],
    cfg: &AgentConfig,
) -> Result<u16, String> {
    crate::agent::launchd::install(launchctl, domain, exe, home, env, &cfg.dir, cfg.port)
        .map_err(|e| format!("zc agent install: {e}"))?;
    wait_for_agent(&cfg.dir, Duration::from_secs(5)).ok_or_else(|| {
        format!(
            "zc agent was installed but did not answer within 5 s; see {}",
            cfg.dir.join(crate::agent::files::LOG_FILE).display()
        )
    })
}

/// Poll the agent that `agent.json` in `dir` names until it answers, and
/// return the port it answered on.
pub fn wait_for_agent(dir: &Path, timeout: Duration) -> Option<u16> {
    let deadline = Instant::now() + timeout;
    while Instant::now() < deadline {
        if let Some(c) = AgentClient::from_dir(dir) {
            if c.summary(Duration::from_secs(1)).is_ok() {
                return Some(c.port());
            }
        }
        std::thread::sleep(Duration::from_millis(250));
    }
    None
}

#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
pub fn install() -> i32 {
    eprintln!("zc agent install is not supported on this platform yet");
    2
}

/// Linux: a systemd user unit (`agent::systemd`), then wait for the agent
/// like the macOS path does.
#[cfg(target_os = "linux")]
pub fn install() -> i32 {
    use crate::agent::systemd;
    let cfg = match AgentConfig::from_env() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("zc agent install: {e}");
            return 1;
        }
    };
    let home = std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default());
    let exe = match std::env::current_exe() {
        Ok(p) => p,
        Err(e) => {
            eprintln!("zc agent install: {e}");
            return 1;
        }
    };
    let unit = systemd::unit_path(&home, std::env::var("XDG_CONFIG_HOME").ok().as_deref());
    let env = crate::agent::launchd::carried_env(|k| std::env::var(k).ok());
    if let Err(e) = systemd::install(
        &systemd::run_systemctl,
        &unit,
        &exe,
        &home,
        &env,
        &cfg.dir,
        cfg.port,
    ) {
        eprintln!("zc agent install: {e}");
        return 1;
    }
    let Some(port) = wait_for_agent(&cfg.dir, Duration::from_secs(10)) else {
        eprintln!(
            "zc agent was installed but did not answer within 10 s; see {} and `journalctl --user -u {}`",
            cfg.dir.join(crate::agent::files::LOG_FILE).display(),
            systemd::UNIT
        );
        return 1;
    };
    println!(
        "✓ zc agent is running on 127.0.0.1:{port} (systemd --user {})",
        systemd::UNIT
    );
    let user = std::env::var("USER").unwrap_or_default();
    if !systemd::lingering(&user, Path::new("/var/lib/systemd/linger")) {
        println!(
            "  note: it stops when your last session ends. To keep it running after logout:\n        loginctl enable-linger {}",
            if user.is_empty() { "$USER" } else { &user }
        );
    }
    0
}

/// Windows: a per-user Task Scheduler task (`agent::schtasks`), then wait for
/// the agent like the other platforms do.
#[cfg(windows)]
pub fn install() -> i32 {
    use crate::agent::schtasks;
    let cfg = match AgentConfig::from_env() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("zc agent install: {e}");
            return 1;
        }
    };
    let exe = match std::env::current_exe() {
        Ok(p) => p,
        Err(e) => {
            eprintln!("zc agent install: {e}");
            return 1;
        }
    };
    let lookup = |k: &str| std::env::var(k).ok();
    let Some(user) = schtasks::current_user(lookup) else {
        eprintln!("zc agent install: %USERNAME% is not set");
        return 1;
    };
    let env = crate::agent::launchd::carried_env(lookup);
    if let Err(e) = schtasks::install(
        &schtasks::run_schtasks,
        &schtasks::conhost_path(lookup),
        &exe,
        &user,
        &env,
        &cfg.dir,
        cfg.port,
    ) {
        eprintln!("zc agent install: {e}");
        return 1;
    }
    let Some(port) = wait_for_agent(&cfg.dir, Duration::from_secs(10)) else {
        eprintln!(
            "zc agent was installed but did not answer within 10 s; see {} and Task Scheduler ({})",
            cfg.dir.join(crate::agent::files::LOG_FILE).display(),
            schtasks::TASK
        );
        return 1;
    };
    println!(
        "✓ zc agent is running on 127.0.0.1:{port} (Task Scheduler {})",
        schtasks::TASK
    );
    0
}

#[cfg(target_os = "macos")]
pub fn install() -> i32 {
    let cfg = match AgentConfig::from_env() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("zc agent install: {e}");
            return 1;
        }
    };
    let home = std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default());
    let exe = match std::env::current_exe() {
        Ok(p) => p,
        Err(e) => {
            eprintln!("zc agent install: {e}");
            return 1;
        }
    };
    let env = crate::agent::launchd::carried_env(|k| std::env::var(k).ok());
    install_with(
        &crate::agent::launchd::run_launchctl,
        &crate::agent::launchd::gui_domain(),
        &exe,
        &home,
        &env,
        &cfg,
    )
}

/// Stop sharing first (drain, bounded by spec §6.5's timeouts), then remove
/// the LaunchAgent via `crate::agent::launchd::uninstall`. `~/.zakuro/agent/`
/// is kept. Platform-neutral so it runs and is tested on every OS; only the
/// no-arg `uninstall()` below is macOS-gated.
pub fn uninstall_with(launchctl: Launchctl, domain: &str, home: &Path, cfg: &AgentConfig) -> i32 {
    drain_before_uninstall(cfg);
    match crate::agent::launchd::uninstall(launchctl, domain, home) {
        Ok(()) => {
            println!("✓ zc agent uninstalled ({} kept)", cfg.dir.display());
            0
        }
        Err(e) => {
            eprintln!("zc agent uninstall: {e}");
            1
        }
    }
}

/// Stop sharing through the running agent and wait for the drain (bounded
/// by spec §6.5's timeouts), so uninstalling never cuts a job off.
pub fn drain_before_uninstall(cfg: &AgentConfig) {
    if let Some(c) = AgentClient::from_dir(&cfg.dir) {
        if c.put(
            "/v1/sharing",
            serde_json::json!({ "on": false }),
            Duration::from_secs(5),
        )
        .is_ok()
        {
            let t = &cfg.timings;
            let bound = t.drain_timeout + t.kill_grace + t.broker_stop_wait;
            println!("  draining workers (up to {} s)…", bound.as_secs());
            let deadline = Instant::now() + bound;
            while Instant::now() < deadline {
                match c.summary(Duration::from_secs(2)) {
                    Ok(s)
                        if s["this_mac"]["broker"] != "running"
                            && s["this_mac"]["workers"]["running"] == 0 =>
                    {
                        break
                    }
                    Err(_) => break,
                    _ => std::thread::sleep(Duration::from_secs(1)),
                }
            }
        }
    }
}

#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
pub fn uninstall() -> i32 {
    eprintln!("zc agent uninstall is not supported on this platform yet");
    2
}

#[cfg(target_os = "linux")]
pub fn uninstall() -> i32 {
    use crate::agent::systemd;
    let cfg = match AgentConfig::from_env() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("zc agent uninstall: {e}");
            return 1;
        }
    };
    let home = std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default());
    let unit = systemd::unit_path(&home, std::env::var("XDG_CONFIG_HOME").ok().as_deref());
    drain_before_uninstall(&cfg);
    match systemd::uninstall(&systemd::run_systemctl, &unit) {
        Ok(()) => {
            println!("✓ zc agent uninstalled ({} kept)", cfg.dir.display());
            0
        }
        Err(e) => {
            eprintln!("zc agent uninstall: {e}");
            1
        }
    }
}

#[cfg(windows)]
pub fn uninstall() -> i32 {
    use crate::agent::schtasks;
    let cfg = match AgentConfig::from_env() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("zc agent uninstall: {e}");
            return 1;
        }
    };
    drain_before_uninstall(&cfg);
    match schtasks::uninstall(&schtasks::run_schtasks) {
        Ok(()) => {
            println!("✓ zc agent uninstalled ({} kept)", cfg.dir.display());
            0
        }
        Err(e) => {
            eprintln!("zc agent uninstall: {e}");
            1
        }
    }
}

#[cfg(target_os = "macos")]
pub fn uninstall() -> i32 {
    let cfg = match AgentConfig::from_env() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("zc agent uninstall: {e}");
            return 1;
        }
    };
    let home = std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default());
    uninstall_with(
        &crate::agent::launchd::run_launchctl,
        &crate::agent::launchd::gui_domain(),
        &home,
        &cfg,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::client::tests::AgentGuard;
    use crate::agent::config::AgentConfig;
    use crate::agent::files::tests::tmp;

    #[test]
    fn status_prints_the_essentials_and_every_problem() {
        let fixture: serde_json::Value =
            serde_json::from_str(include_str!("../../docs/agent-api/summary.v1.json")).unwrap();
        let out = super::format_status(&fixture);
        assert!(
            out.contains("sharing · broker running · workers 2/2 running (1 busy)"),
            "{out}"
        );
        assert!(out.contains("18 cr/h (set)"), "{out}");
        assert!(out.contains("jean · ¥1240.5"), "{out}");
        assert!(out.contains("12.4 today · 88.1 last 7 days"), "{out}");
        assert!(out.contains("2/3 online"), "{out}");
        assert!(
            out.contains("  Mesh       via the zakuro-wg container (10.13.13.7) · reachable\n"),
            "{out}"
        );
        assert!(
            out.contains("! uv is not installed — brew install uv"),
            "{out}"
        );
    }

    fn fixture() -> serde_json::Value {
        serde_json::from_str(include_str!("../../docs/agent-api/summary.v1.json")).unwrap()
    }

    /// A problem's `detail` is its next step, and it was in the JSON and
    /// nowhere on screen. It gets its own line under the problem -- but only
    /// its first line: `worker_crashloop` carries a 20-line log tail, and the
    /// status screen is not the place for it.
    #[test]
    fn a_problem_shows_its_next_step_under_it() {
        let mut s = fixture();
        s["problems"] = serde_json::json!([
            {
                "code": "hub_unreachable",
                "message": "Can't reach the Zakuro hub",
                "hint": "No cached values yet",
                "detail": "this host may answer only over a VPN tunnel: check that the tunnel carrying it is up",
            },
            {
                "code": "worker_crashloop",
                "message": "A worker keeps crashing",
                "hint": "See ~/.zakuro/agent/workers/",
                "detail": "first log line\nsecond log line\nthird log line",
            },
        ]);
        let out = format_status(&s);
        assert!(
            out.contains("  ! Can't reach the Zakuro hub — No cached values yet\n    this host may answer only over a VPN tunnel: check that the tunnel carrying it is up\n"),
            "{out}"
        );
        assert!(out.contains("    first log line…\n"), "{out}");
        assert!(
            !out.contains("second log line"),
            "a log tail is not the status screen: {out}"
        );
    }

    /// #269: a crash-loop's captured stderr tail often opens with a Python
    /// `DeprecationWarning` -- whatever the process warned about first, not
    /// why it died -- while the real cause sits further down. The line
    /// carrying the failure, not the first line of the tail, belongs on
    /// screen.
    #[test]
    fn a_worker_crashloop_shows_the_failure_not_the_leading_warning() {
        let mut s = fixture();
        let tail = "/Users/x/zakuro/worker/server.py:77: DeprecationWarning:\n\
                    \x20       on_event is deprecated, use lifespan event handlers instead.\n\
                    INFO:     Started server process [1234]\n\
                    INFO:     Waiting for application startup.\n\
                    INFO:     Application startup complete.\n\
                    INFO:     Uvicorn running on http://0.0.0.0:9100\n\
                    refusing to bind the Zakuro worker to '0.0.0.0': no caller \
                    authentication is enabled -- set ZAKURO_WORKER_AUTH or bind 127.0.0.1";
        s["problems"] = serde_json::json!([{
            "code": "worker_crashloop",
            "message": "A worker keeps crashing",
            "hint": "See ~/.zakuro/agent/workers/",
            "detail": tail,
        }]);
        let out = format_status(&s);
        assert!(
            out.contains("refusing to bind the Zakuro worker to '0.0.0.0'"),
            "the line that explains the outage should be on screen: {out}"
        );
        assert!(
            !out.contains("DeprecationWarning"),
            "the leading warning is not the reason the worker died: {out}"
        );
    }

    /// Before the first good hub answer there is nothing but this Mac to
    /// show. "Devices 0/0 online" then reads as "you have no devices", a
    /// different and alarming claim, so the line is left out entirely --
    /// while a hub that answered and listed none still says 0/0.
    #[test]
    fn with_nothing_cached_no_device_account_or_earnings_line_is_printed() {
        let mut s = fixture();
        s["account"] = serde_json::Value::Null;
        s["earnings"] = serde_json::Value::Null;
        s["devices"] = serde_json::Value::Null;
        s["devices_online"] = serde_json::json!(0);
        s["devices_total"] = serde_json::json!(0);
        s["prices"]["this_mac"] = serde_json::json!({
            "state": "inherited", "per_hour": null, "effective_per_hour": null
        });
        s["problems"] = serde_json::json!([{
            "code": "hub_unreachable",
            "message": "Can't reach the Zakuro hub",
            "hint": "No cached values yet: showing this Mac only",
            "detail": null,
        }]);
        let out = format_status(&s);
        assert!(
            out.contains("  This Mac   sharing · broker running"),
            "{out}"
        );
        assert!(!out.contains("Devices"), "no zeros to read as none: {out}");
        assert!(!out.contains("Account"), "{out}");
        assert!(!out.contains("Earnings"), "{out}");
        assert!(!out.contains("Price"), "{out}");
        assert!(
            out.contains(
                "! Can't reach the Zakuro hub — No cached values yet: showing this Mac only\n"
            ),
            "{out}"
        );

        let mut answered = fixture();
        answered["devices"] = serde_json::json!([]);
        answered["devices_online"] = serde_json::json!(0);
        answered["devices_total"] = serde_json::json!(0);
        assert!(
            format_status(&answered).contains("  Devices    0/0 online\n"),
            "the hub answered and listed none: that is a real 0/0"
        );
    }

    #[test]
    fn status_prints_the_mesh_route() {
        use serde_json::json;
        let line = |v: serde_json::Value| super::mesh_line(&v);
        assert_eq!(
            line(json!({"route": "host", "address": "10.13.13.7", "interface": "utun4", "reachable": true})).as_deref(),
            Some("host VPN utun4 (10.13.13.7) · reachable")
        );
        assert_eq!(
            line(json!({"route": "proxy", "address": "10.13.13.7", "interface": "zakuro-wg", "reachable": true})).as_deref(),
            Some("via the zakuro-wg container (10.13.13.7) · reachable")
        );
        assert_eq!(
            line(json!({"route": "proxy", "address": "10.13.13.7", "interface": "zakuro-wg", "reachable": false})).as_deref(),
            Some("via the zakuro-wg container (10.13.13.7) · not reachable")
        );
        assert_eq!(
            line(json!({"route": "none", "address": null, "interface": null, "reachable": false}))
                .as_deref(),
            Some("not connected — run zc connect")
        );
        assert_eq!(
            line(serde_json::Value::Null),
            None,
            "an agent from before the mesh route was reported sends no mesh"
        );
    }

    /// A fake `launchctl` that records every call it receives and always
    /// reports success.
    struct FakeLaunchctl {
        calls: std::sync::Mutex<Vec<Vec<String>>>,
    }

    impl FakeLaunchctl {
        fn new() -> Self {
            Self {
                calls: std::sync::Mutex::new(vec![]),
            }
        }

        fn call(&self, args: &[&str]) -> std::io::Result<std::process::ExitStatus> {
            self.calls
                .lock()
                .unwrap()
                .push(args.iter().map(|s| s.to_string()).collect());
            std::process::Command::new("true").status()
        }

        fn calls(&self) -> Vec<Vec<String>> {
            self.calls.lock().unwrap().clone()
        }
    }

    /// Like `client::tests::idle_agent`, but returns the `AgentConfig` too so
    /// `uninstall_with` can be pointed at this agent's directory and short
    /// drain timings.
    fn running_agent() -> (AgentConfig, AgentGuard) {
        let free = || {
            std::net::TcpListener::bind("127.0.0.1:0")
                .unwrap()
                .local_addr()
                .unwrap()
                .port()
        };
        let sleeper = vec![
            "sh".to_string(),
            "-c".to_string(),
            "exec sleep 30".to_string(),
        ];
        let mut cfg = AgentConfig::for_dirs(tmp("cli-uninstall"));
        cfg.port = 0;
        cfg.broker_port = free();
        cfg.max_workers = 3;
        cfg.broker_argv = sleeper.clone();
        cfg.worker_template = sleeper;
        cfg.worker_template_overridden = true;
        cfg.timings.shutdown_wait = std::time::Duration::from_secs(2);
        cfg.timings.drain_timeout = std::time::Duration::from_secs(1);
        cfg.timings.kill_grace = std::time::Duration::from_secs(0);
        cfg.timings.broker_stop_wait = std::time::Duration::from_secs(0);
        let (_, _, stop, thread) =
            crate::agent::run::start_background(cfg.clone()).expect("agent starts");
        (cfg, AgentGuard::new(stop, thread))
    }

    #[test]
    fn uninstall_turns_sharing_off_through_the_client_before_booting_out() {
        let (cfg, guard) = running_agent();
        let client =
            crate::agent::client::AgentClient::from_dir(&cfg.dir).expect("agent.json written");
        let t = std::time::Duration::from_secs(2);
        // Sharing on first, so a bootout that ran before the pause would see it on.
        client
            .put("/v1/sharing", serde_json::json!({ "on": true }), t)
            .unwrap();
        assert_eq!(client.summary(t).unwrap()["this_mac"]["sharing"], true);

        let home = tmp("cli-uninstall-home");
        std::fs::create_dir_all(&home).unwrap();
        let fake = FakeLaunchctl::new();
        // What the agent reported each time bootout ran. The fake bootout
        // doesn't stop the agent, so it can still be asked.
        let sharing_at_bootout = std::sync::Mutex::new(vec![]);
        let launchctl = |args: &[&str]| {
            if args.first() == Some(&"bootout") {
                sharing_at_bootout.lock().unwrap().push(
                    client
                        .summary(t)
                        .ok()
                        .map(|s| s["this_mac"]["sharing"].clone()),
                );
            }
            fake.call(args)
        };
        let code = uninstall_with(&launchctl, "gui/501", &home, &cfg);
        assert_eq!(code, 0);

        assert_eq!(
            *sharing_at_bootout.lock().unwrap(),
            vec![Some(serde_json::json!(false))],
            "one bootout, and sharing was already off when it ran"
        );
        assert_eq!(
            fake.calls().last().unwrap(),
            &vec!["bootout", "gui/501/ai.zakuro.agent"]
        );
        drop(guard);
    }

    /// The port `install` reports is the one the agent launchd started really
    /// bound, read back from `agent.json` once it answers, not the port in the
    /// installing shell's config.
    #[test]
    fn install_reports_the_port_the_launched_agent_answers_on() {
        let home = tmp("cli-install-home");
        std::fs::create_dir_all(&home).unwrap();
        // What "launchd" starts: the same agent dir, on a port of its own.
        let launched = crate::agent::client::tests::sleeper_cfg("cli-install");
        let mut asked = launched.clone();
        asked.port = 1; // never what an agent binds
        let started = std::sync::Mutex::new(None);
        let launchctl = |args: &[&str]| {
            if args.first() == Some(&"bootstrap") {
                let (_, _, stop, thread) =
                    crate::agent::run::start_background(launched.clone()).expect("agent starts");
                *started.lock().unwrap() = Some(AgentGuard::new(stop, thread));
            }
            // `print` exits non-zero: no old agent is loaded, so `install`
            // bootstraps straight away instead of waiting for it.
            let ok = args.first() != Some(&"print");
            std::process::Command::new(if ok { "true" } else { "false" }).status()
        };

        let port = install_and_wait(
            &launchctl,
            "gui/501",
            std::path::Path::new("/usr/local/bin/zc"),
            &home,
            &[],
            &asked,
        )
        .expect("the launched agent answers");

        let bound = crate::agent::files::load_json::<crate::agent::files::AgentFile>(
            &asked.dir.join(crate::agent::files::AGENT_FILE),
        )
        .unwrap()
        .port;
        assert_eq!(port, bound, "the port the launched agent answers on");
        assert_ne!(port, asked.port, "not the port the config asked for");
        drop(started);
    }
}