zc2 0.0.38

P2P compute broker with credit-based 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
//! Summary v1: the JSON contract between `zc agent` and the macOS app and
//! widget (spec §6.3). `docs/agent-api/summary.v1.json` is the fixture both
//! sides test against: a change here that breaks it is a `v` bump.

use serde::{Deserialize, Serialize};

pub const SUMMARY_VERSION: u32 = 1;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Summary {
    pub v: u32,
    pub agent_version: String,
    pub as_of: String,
    pub env: String,
    pub hub: HubStatus,
    pub problems: Vec<Problem>,
    pub account: Option<Account>,
    pub earnings: Option<Earnings>,
    pub prices: Prices,
    pub this_mac: ThisMac,
    /// Added without a `v` bump: older apps ignore it, and a summary from an
    /// older agent decodes with the default (`"none"`).
    #[serde(default)]
    pub mesh: MeshStatus,
    pub devices: Option<Vec<Device>>,
    pub devices_online: u32,
    pub devices_total: u32,
    pub links: Links,
    /// Rolling hourly usage/earnings, oldest first (`agent::history`). Added
    /// without a `v` bump: omitted entirely until there is something to show,
    /// so an older reader is unaffected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub history: Option<HourlyHistory>,
    /// Network-wide resource capacity (network contract §5), from the hub's
    /// `GET /api/status/network`. Added without a `v` bump: omitted entirely
    /// (never null) whenever there is nothing fresh enough to report --
    /// e.g. this Mac has never reached that endpoint, or the last good
    /// answer is more than 5 minutes old -- so an older reader is unaffected
    /// and a stale figure is never shown as current.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub network: Option<NetworkCapacity>,
}

/// The wire shape of both the hub's `GET /api/status/network` response (the
/// four pre-existing capacity fields plus the four `_busy` ones the network
/// contract adds) and this summary's `network` field -- the contract gives
/// them identical names, so one struct serves both directions. "Available" is
/// never carried on the wire: `available = total - busy`, computed at the
/// display edge (network contract §6).
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct NetworkCapacity {
    pub workers: u32,
    #[serde(default)]
    pub workers_busy: u32,
    pub cpu_cores: u32,
    #[serde(default)]
    pub cpu_cores_busy: u32,
    pub ram_gb: u32,
    #[serde(default)]
    pub ram_gb_busy: u32,
    pub gpus: u32,
    #[serde(default)]
    pub gpus_busy: u32,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HubStatus {
    pub reachable: bool,
    pub last_ok: Option<String>,
    pub error: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Problem {
    pub code: String,
    pub message: String,
    pub hint: Option<String>,
    pub detail: Option<String>,
}

impl Problem {
    /// A problem from the spec §6.3 catalog (plus `broker_crashloop`), with
    /// its user-facing message and hint.
    pub fn new(code: &str) -> Self {
        let (message, hint): (&str, Option<&str>) = match code {
            "not_logged_in" => (
                "This Mac is not signed in to Zakuro",
                Some("Run `zc login`"),
            ),
            "hub_unreachable" => (
                "Can't reach the Zakuro hub",
                Some("Showing the last known values"),
            ),
            "hub_too_old" => (
                "The hub doesn't support the widget yet",
                Some("Local status only until the hub is updated"),
            ),
            "uv_missing" => ("uv is not installed", Some("brew install uv")),
            "docker_missing" => (
                "Docker isn't running, and this Mac's workers are containers",
                Some("Start Docker, or set ZAKURO_SHARE_RUNTIME=host to share with a host process"),
            ),
            "zakuro_dir_missing" => (
                "The zakuro worker directory can't be found",
                Some("Clone zak-zakuro into ~/.zakuro/zak-zakuro, or set ZAKURO_WORKER_DIR"),
            ),
            "unmanaged_broker" => (
                "A broker the agent didn't start is running",
                Some("Run `zc down` so the agent can manage sharing"),
            ),
            "port_in_use" => (
                "A port the agent needs is taken",
                Some("No free port for the broker (9000–9010 and a random port were all unavailable)"),
            ),
            "broker_port_unrelayable" => (
                "Ports 9000–9010 are all taken; the mesh relay only covers those",
                Some("Free one of them, or connect through a host VPN (the WireGuard app) instead of the zakuro-wg container"),
            ),
            "worker_crashloop" => (
                "A worker keeps crashing",
                Some("See ~/.zakuro/agent/workers/"),
            ),
            "drain_timeout" => (
                "A worker took too long to finish its job and was stopped",
                Some("Check the worker's log for a stuck request"),
            ),
            "broker_crashloop" => (
                "The broker keeps crashing",
                Some("Check ~/.zakuro/agent/agent.log"),
            ),
            _ => ("Unexpected problem", None),
        };
        Self {
            code: code.to_string(),
            message: message.to_string(),
            hint: hint.map(str::to_string),
            detail: None,
        }
    }

    /// `hub_unreachable`, whose hint depends on whether there is anything
    /// cached to fall back on. With an empty cache "Showing the last known
    /// values" promises values that do not exist: this run has never had a
    /// good answer, so there is nothing to show but this Mac's own state.
    pub fn hub_unreachable(cached: bool) -> Self {
        let mut p = Self::new("hub_unreachable");
        if !cached {
            p.hint = Some("No cached values yet: showing this Mac only".to_string());
        }
        p
    }

    pub fn with_detail(mut self, detail: String) -> Self {
        self.detail = Some(detail);
        self
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Account {
    pub username: String,
    pub email: String,
    pub credits_balance: f64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Earnings {
    pub today: f64,
    pub last_7d: f64,
    pub tz: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Prices {
    pub bounds: PriceBounds,
    pub default_per_hour: Option<f64>,
    pub this_mac: ThisMacPrice,
}

/// Integers on the wire (`{"min": 1, "max": 120, "step": 1}`), like the hub's.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct PriceBounds {
    pub min: u32,
    pub max: u32,
    pub step: u32,
}

impl Default for PriceBounds {
    fn default() -> Self {
        Self {
            min: 1,
            max: 120,
            step: 1,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ThisMacPrice {
    /// One of four values: `"set"` (every one of this Mac's workers has the
    /// same explicit price), `"inherited"` (all of them are `null`, so the
    /// account default applies), `"mixed"` (anything else — `per_hour` is
    /// `null` and `effective_per_hour` is the minimum across workers), or
    /// `"disabled"` (every one of this Mac's workers is disabled on the hub —
    /// `per_hour` and `effective_per_hour` are both `null`).
    pub state: String,
    pub per_hour: Option<f64>,
    pub effective_per_hour: Option<f64>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ThisMac {
    pub node_pubkey: String,
    pub name: String,
    pub sharing: bool,
    /// `running` | `starting` | `stopping` | `stopped` | `unmanaged` | `error`.
    pub broker: String,
    pub workers: WorkerCounts,
    pub requests: Requests,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct WorkerCounts {
    pub desired: u32,
    pub running: u32,
    pub busy: u32,
    pub draining: u32,
    pub max: u32,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct Requests {
    pub last_5h: u64,
    pub last_1w: u64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Device {
    pub node_pubkey: String,
    pub name: String,
    pub this_mac: bool,
    pub freshness: String,
    pub last_seen_at: Option<String>,
    pub workers: u32,
    pub effective_price_per_hour: Option<PriceRange>,
    pub link: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct PriceRange {
    pub min: f64,
    pub max: f64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Links {
    pub hub: Option<String>,
    pub this_mac: Option<String>,
}

/// How this Mac reaches the mesh (mesh-routes §5). `route` is `"host"`,
/// `"proxy"` or `"none"`. `interface` is the host interface (`utun4`) or the
/// container (`zakuro-wg`). `reachable` says whether peers can reach this
/// Mac's broker; v1 doesn't probe a real round trip.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MeshStatus {
    pub route: String,
    pub address: Option<String>,
    pub interface: Option<String>,
    pub reachable: bool,
}

/// The `history` field's wire shape: at most 12 hourly buckets, oldest first,
/// UTC, one per clock hour, the last one the current partial hour. An hour
/// the agent wasn't running for is absent, not zeroed (`agent::history`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HourlyHistory {
    pub hours: Vec<HourBucket>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HourBucket {
    /// RFC 3339 UTC with a `Z`, aligned to the top of the hour.
    pub start: String,
    pub requests: u64,
    pub credits: f64,
}

impl Default for MeshStatus {
    fn default() -> Self {
        Self {
            route: "none".to_string(),
            address: None,
            interface: None,
            reachable: false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const FIXTURE: &str = include_str!("../../docs/agent-api/summary.v1.json");
    const PK: &str = "q8X2n0Lr4mH6vB9sK3wT7yP1cF5gJ0dZ2aE4uR8iO6s=";
    const LINK: &str = "https://stg.hub.zakuro-ai.com/provide?device=a1b2c3d4-w0";

    fn fixture_summary() -> Summary {
        Summary {
            v: SUMMARY_VERSION,
            agent_version: "0.0.26".into(),
            as_of: "2026-09-13T01:42:00Z".into(),
            env: "staging".into(),
            hub: HubStatus {
                reachable: true,
                last_ok: Some("2026-09-13T01:41:30Z".into()),
                error: None,
            },
            problems: vec![Problem::new("uv_missing")],
            account: Some(Account {
                username: "jean".into(),
                email: "jean@zakuro-ai.com".into(),
                credits_balance: 1240.5,
            }),
            earnings: Some(Earnings {
                today: 12.4,
                last_7d: 88.1,
                tz: "Asia/Tokyo".into(),
            }),
            prices: Prices {
                bounds: PriceBounds::default(),
                default_per_hour: Some(18.0),
                this_mac: ThisMacPrice {
                    state: "set".into(),
                    per_hour: Some(18.0),
                    effective_per_hour: Some(18.0),
                },
            },
            this_mac: ThisMac {
                node_pubkey: PK.into(),
                name: "jeans-mbp".into(),
                sharing: true,
                broker: "running".into(),
                workers: WorkerCounts {
                    desired: 2,
                    running: 2,
                    busy: 1,
                    draining: 0,
                    max: 5,
                },
                requests: Requests {
                    last_5h: 31,
                    last_1w: 410,
                },
            },
            mesh: MeshStatus {
                route: "proxy".into(),
                address: Some("10.13.13.7".into()),
                interface: Some("zakuro-wg".into()),
                reachable: true,
            },
            devices: Some(vec![
                Device {
                    node_pubkey: PK.into(),
                    name: "jeans-mbp".into(),
                    this_mac: true,
                    freshness: "fresh".into(),
                    last_seen_at: Some("2026-09-13T01:41:30Z".into()),
                    workers: 2,
                    effective_price_per_hour: Some(PriceRange {
                        min: 18.0,
                        max: 18.0,
                    }),
                    link: Some(LINK.into()),
                },
                Device {
                    node_pubkey: "Vb3kT9qL2xN7mR4wY8pC1zF6hJ0sD5gA2eU9iO3tK7c=".into(),
                    name: "studio-mini".into(),
                    this_mac: false,
                    freshness: "fresh".into(),
                    last_seen_at: Some("2026-09-13T01:41:12Z".into()),
                    workers: 3,
                    effective_price_per_hour: Some(PriceRange {
                        min: 12.0,
                        max: 20.0,
                    }),
                    link: Some("https://stg.hub.zakuro-ai.com/provide?device=e5f6a7b8-w0".into()),
                },
                // Gone, its only worker offline and disabled: no price, no link.
                Device {
                    node_pubkey: "Hn5wQ2cX8bL4tZ7kP1mV9rG3yS6dF0jA5uE2oI8hN4g=".into(),
                    name: "old-imac".into(),
                    this_mac: false,
                    freshness: "gone".into(),
                    last_seen_at: Some("2026-09-10T08:03:55Z".into()),
                    workers: 1,
                    effective_price_per_hour: None,
                    link: None,
                },
            ]),
            devices_online: 2,
            devices_total: 3,
            links: Links {
                hub: Some("https://stg.hub.zakuro-ai.com/provide".into()),
                this_mac: Some(LINK.into()),
            },
            history: Some(HourlyHistory {
                hours: vec![
                    HourBucket {
                        start: "2026-09-13T00:00:00Z".into(),
                        requests: 5,
                        credits: 0.8,
                    },
                    HourBucket {
                        start: "2026-09-13T01:00:00Z".into(),
                        requests: 12,
                        credits: 1.2,
                    },
                ],
            }),
            network: Some(NetworkCapacity {
                workers: 31,
                workers_busy: 4,
                cpu_cores: 96,
                cpu_cores_busy: 12,
                ram_gb: 512,
                ram_gb_busy: 64,
                gpus: 8,
                gpus_busy: 2,
            }),
        }
    }

    #[test]
    fn serializes_exactly_to_the_committed_fixture() {
        let ours = serde_json::to_value(fixture_summary()).unwrap();
        let fixture: serde_json::Value = serde_json::from_str(FIXTURE).unwrap();
        assert_eq!(
            ours, fixture,
            "Summary v1 drifted from docs/agent-api/summary.v1.json"
        );
    }

    #[test]
    fn the_fixture_decodes_and_round_trips() {
        let decoded: Summary = serde_json::from_str(FIXTURE).unwrap();
        assert_eq!(decoded, fixture_summary());
    }

    /// The first device exactly as the fixture has always listed it: the macOS
    /// app's tests decode `devices.first`, `last_seen_at` included.
    const FIRST_DEVICE: &str = r#"{"node_pubkey": "q8X2n0Lr4mH6vB9sK3wT7yP1cF5gJ0dZ2aE4uR8iO6s=", "name": "jeans-mbp", "this_mac": true, "freshness": "fresh",
     "last_seen_at": "2026-09-13T01:41:30Z", "workers": 2, "effective_price_per_hour": {"min": 18.0, "max": 18.0},
     "link": "https://stg.hub.zakuro-ai.com/provide?device=a1b2c3d4-w0"}"#;

    /// The fixture obeys what `build_summary` guarantees: `devices_total` is
    /// the length of `devices`, `devices_online` counts the `fresh` ones.
    #[test]
    fn the_fixture_counts_match_its_device_list() {
        let s: Summary = serde_json::from_str(FIXTURE).unwrap();
        let devices = s.devices.as_ref().expect("the fixture lists devices");
        assert_eq!(s.devices_total as usize, devices.len());
        assert_eq!(
            s.devices_online as usize,
            devices.iter().filter(|d| d.freshness == "fresh").count()
        );
        assert_eq!(
            (s.devices_online, s.devices_total),
            (2, 3),
            "the macOS app's tests pin \"2 of 3 online\""
        );
        assert!(
            FIXTURE.contains(FIRST_DEVICE),
            "the first device must stay byte-for-byte"
        );
        assert!(devices[0].this_mac && devices.iter().filter(|d| d.this_mac).count() == 1);
    }

    /// A summary with no fresh network data (never polled yet, or the last
    /// good answer aged out) omits the `network` field entirely -- never
    /// `null` -- and decodes back with `None`, the same convention `history`
    /// already established.
    #[test]
    fn a_summary_with_no_network_data_omits_the_field() {
        let mut v: serde_json::Value = serde_json::from_str(FIXTURE).unwrap();
        v.as_object_mut().unwrap().remove("network");
        let s: Summary = serde_json::from_value(v.clone()).unwrap();
        assert_eq!(s.network, None);
        assert!(!v.as_object().unwrap().contains_key("network"));

        let no_network = Summary {
            network: None,
            ..fixture_summary()
        };
        let encoded = serde_json::to_value(&no_network).unwrap();
        assert!(!encoded.as_object().unwrap().contains_key("network"));
    }

    /// The `network` field's JSON shape, pinned against the network
    /// contract's documented example (§5).
    #[test]
    fn network_matches_the_documented_contract_shape() {
        let network = NetworkCapacity {
            workers: 31,
            workers_busy: 4,
            cpu_cores: 96,
            cpu_cores_busy: 12,
            ram_gb: 512,
            ram_gb_busy: 64,
            gpus: 8,
            gpus_busy: 2,
        };
        let expected: serde_json::Value = serde_json::from_str(
            r#"{"workers": 31, "workers_busy": 4, "cpu_cores": 96, "cpu_cores_busy": 12,
                "ram_gb": 512, "ram_gb_busy": 64, "gpus": 8, "gpus_busy": 2}"#,
        )
        .unwrap();
        assert_eq!(serde_json::to_value(network).unwrap(), expected);
    }

    #[test]
    fn every_problem_code_has_a_message() {
        for code in [
            "not_logged_in",
            "hub_unreachable",
            "hub_too_old",
            "uv_missing",
            "zakuro_dir_missing",
            "docker_missing",
            "unmanaged_broker",
            "port_in_use",
            "broker_port_unrelayable",
            "worker_crashloop",
            "drain_timeout",
            "broker_crashloop",
        ] {
            let p = Problem::new(code);
            assert_eq!(p.code, code);
            assert!(!p.message.is_empty(), "{code} needs a message");
            assert!(p.hint.is_some(), "{code} needs a hint");
        }
        assert_eq!(
            Problem::new("worker_crashloop")
                .with_detail("boom".into())
                .detail
                .as_deref(),
            Some("boom")
        );
    }

    #[test]
    fn a_summary_from_an_older_agent_decodes_with_no_mesh_route() {
        let mut v: serde_json::Value = serde_json::from_str(FIXTURE).unwrap();
        v.as_object_mut().unwrap().remove("mesh");
        let s: Summary = serde_json::from_value(v).unwrap();
        assert_eq!(s.mesh, MeshStatus::default());
    }

    /// A summary with no history yet (an older agent, or one that hasn't
    /// sampled anything) omits the field entirely, and decodes back with
    /// `None`, not an empty series.
    #[test]
    fn a_summary_with_no_history_omits_the_field() {
        let mut v: serde_json::Value = serde_json::from_str(FIXTURE).unwrap();
        v.as_object_mut().unwrap().remove("history");
        let s: Summary = serde_json::from_value(v.clone()).unwrap();
        assert_eq!(s.history, None);
        assert!(!v.as_object().unwrap().contains_key("history"));

        let no_history = Summary {
            history: None,
            ..fixture_summary()
        };
        let encoded = serde_json::to_value(&no_history).unwrap();
        assert!(!encoded.as_object().unwrap().contains_key("history"));
    }

    /// The `history` field's JSON shape, pinned against the contract's
    /// documented example (docs/agent-api.md).
    #[test]
    fn history_matches_the_documented_contract_shape() {
        let history = HourlyHistory {
            hours: vec![
                HourBucket {
                    start: "2026-09-16T04:00:00Z".into(),
                    requests: 0,
                    credits: 0.0,
                },
                HourBucket {
                    start: "2026-09-16T05:00:00Z".into(),
                    requests: 12,
                    credits: 0.0041,
                },
            ],
        };
        let got = serde_json::to_value(&history).unwrap();
        let want: serde_json::Value = serde_json::from_str(
            r#"{
              "hours": [
                { "start": "2026-09-16T04:00:00Z", "requests": 0,  "credits": 0.0 },
                { "start": "2026-09-16T05:00:00Z", "requests": 12, "credits": 0.0041 }
              ]
            }"#,
        )
        .unwrap();
        assert_eq!(got, want);
    }

    #[test]
    fn an_unrelayable_broker_port_names_the_relay_range() {
        assert_eq!(
            Problem::new("broker_port_unrelayable").message,
            "Ports 9000–9010 are all taken; the mesh relay only covers those"
        );
    }
}