nativeview-cli 0.1.0-rc.1

Developer CLI (`nv`) for Native View Engine: dev hot-reload, builds, pairing, SDK management, app scaffolding, and docs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Settlement evaluation and status/timeout response formatting for [`super::control`].

use std::path::PathBuf;
use std::time::Duration;

use serde::{Deserialize, Serialize};

use super::control::CoordinatorState;
use super::session::CompilerDiagnostic;

pub(crate) const WEB_RELOAD_GRACE: Duration = Duration::from_secs(6);

/// Wait mode for `nv dev wait`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, clap::ValueEnum)]
#[serde(rename_all = "snake_case")]
pub(crate) enum WaitForMode {
    /// Wait for host acks when at least one host is connected; otherwise return on build completion.
    #[default]
    Auto,
    /// Return as soon as the daemon finishes patching/building (do not wait for host acks).
    Build,
    /// Require host acknowledgement (fails fast if zero hosts are connected).
    Ack,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "cmd", rename_all = "snake_case")]
pub(crate) enum ControlRequest {
    Status,
    Settle {
        paths: Vec<PathBuf>,
        timeout_ms: u64,
        wait_for: WaitForMode,
        require_host: bool,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct HostSummary {
    pub kind: String,
    pub id: String,
    pub last_acked_generation: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_acked_wire_seq: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bundle_hash: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct ControlResponse {
    pub ok: bool,
    pub status: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pid: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub package: Option<String>,
    pub seq: u64,
    pub generation: u64,
    pub tier: String,
    pub build_ms: u64,
    pub ack_ms: u64,
    pub connected_hosts: usize,
    pub acked_hosts: usize,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub hosts: Vec<HostSummary>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub watched_roots: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub diagnostics: Vec<CompilerDiagnostic>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hint: Option<String>,
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn make_error_resp(
    status: &str,
    tier: &str,
    seq: u64,
    generation: u64,
    build_ms: u64,
    hosts: Vec<HostSummary>,
    watched_roots: Vec<String>,
    error: String,
    hint: Option<String>,
) -> ControlResponse {
    ControlResponse {
        ok: false,
        status: status.to_owned(),
        pid: None,
        package: None,
        seq,
        generation,
        tier: tier.to_owned(),
        build_ms,
        ack_ms: 0,
        connected_hosts: hosts.len(),
        acked_hosts: 0,
        hosts,
        watched_roots,
        diagnostics: Vec::new(),
        error: Some(error),
        hint,
    }
}

pub(crate) fn collect_hosts(st: &CoordinatorState) -> Vec<HostSummary> {
    let mut out = Vec::with_capacity(st.ws_hosts.len() + st.pair_hosts.len());
    for (&id, h) in &st.ws_hosts {
        out.push(HostSummary {
            kind: h.client_kind.clone(),
            id: format!("ws-{id}"),
            last_acked_generation: h.last_acked_gen,
            last_acked_wire_seq: None,
            bundle_hash: (!h.bundle_hash.is_empty()).then(|| h.bundle_hash.clone()),
        });
    }
    for (&sid, h) in &st.pair_hosts {
        out.push(HostSummary {
            kind: "pair".to_owned(),
            id: format!("pair-{sid}"),
            last_acked_generation: h.last_acked_gen,
            last_acked_wire_seq: Some(h.last_acked_seq),
            bundle_hash: None,
        });
    }
    out
}

pub(crate) fn build_status_response(st: &CoordinatorState) -> ControlResponse {
    let hosts = collect_hosts(st);
    let watched_roots = st.watched_roots.iter().map(|r| r.display().to_string()).collect();
    if let Some(ref c) = st.last_cycle {
        let acked_ws = st
            .ws_hosts
            .values()
            .filter(|h| h.last_acked_gen >= c.generation && h.last_ack_ok)
            .count();
        let acked_pair = match c.pair_target_wire_seq {
            Some(target) => st
                .pair_hosts
                .values()
                .filter(|p| {
                    p.last_acked_seq >= target
                        && p.last_ack_status == nativeview_wire::FRAME_ACK_STATUS_APPLIED
                })
                .count(),
            None if c.pair_done && c.pair_error.is_none() => st.pair_hosts.len(),
            None => 0,
        };
        let acked_hosts = if st.in_flight || !c.ok { 0 } else { acked_ws + acked_pair };
        ControlResponse {
            ok: c.ok && c.pair_error.is_none(),
            status: if st.in_flight {
                "building"
            } else if c.ok {
                "ready"
            } else {
                "build_error"
            }
            .to_owned(),
            pid: Some(st.pid),
            package: Some(st.package.clone()),
            seq: c.seq,
            generation: c.generation,
            tier: c.tier.clone(),
            build_ms: c.build_ms,
            ack_ms: 0,
            connected_hosts: hosts.len(),
            acked_hosts,
            hosts,
            watched_roots,
            diagnostics: c.diagnostics.clone(),
            error: c.error.clone().or_else(|| c.pair_error.clone()),
            hint: None,
        }
    } else {
        ControlResponse {
            ok: true,
            status: "starting".to_owned(),
            pid: Some(st.pid),
            package: Some(st.package.clone()),
            seq: 0,
            generation: 0,
            tier: "initial".to_owned(),
            build_ms: 0,
            ack_ms: 0,
            connected_hosts: hosts.len(),
            acked_hosts: 0,
            hosts,
            watched_roots,
            diagnostics: Vec::new(),
            error: None,
            hint: None,
        }
    }
}

pub(crate) fn evaluate_settled(
    st: &CoordinatorState,
    wait_for: WaitForMode,
    require_host: bool,
) -> Option<ControlResponse> {
    let cycle = st.last_cycle.as_ref()?;
    let hosts = collect_hosts(st);
    let watched_roots: Vec<String> = st.watched_roots.iter().map(|r| r.display().to_string()).collect();

    if !cycle.ok {
        let mut resp = make_error_resp(
            "build_error",
            &cycle.tier,
            cycle.seq,
            cycle.generation,
            cycle.build_ms,
            hosts,
            watched_roots,
            cycle.error.clone().unwrap_or_else(|| "build failed".to_owned()),
            Some("Fix the compiler/build error above and save again.".to_owned()),
        );
        resp.diagnostics = cycle.diagnostics.clone();
        return Some(resp);
    }

    if cycle.tier == "noop" || wait_for == WaitForMode::Build {
        return Some(ControlResponse {
            ok: true,
            status: if cycle.tier == "noop" { "noop" } else { "built" }.to_owned(),
            pid: None,
            package: None,
            seq: cycle.seq,
            generation: cycle.generation,
            tier: cycle.tier.clone(),
            build_ms: cycle.build_ms,
            ack_ms: 0,
            connected_hosts: hosts.len(),
            acked_hosts: 0,
            hosts,
            watched_roots,
            diagnostics: Vec::new(),
            error: None,
            hint: None,
        });
    }

    if !cycle.pair_done {
        return None;
    }
    if let Some(ref pair_err) = cycle.pair_error {
        return Some(make_error_resp(
            "host_error",
            &cycle.tier,
            cycle.seq,
            cycle.generation,
            cycle.build_ms,
            hosts,
            watched_roots,
            pair_err.clone(),
            None,
        ));
    }
    if let Some((err_gen, ref msg)) = st.host_disconnect_err
        && err_gen == cycle.generation
    {
        return Some(make_error_resp(
            "host_disconnected",
            &cycle.tier,
            cycle.seq,
            cycle.generation,
            cycle.build_ms,
            hosts,
            watched_roots,
            msg.clone(),
            Some("The connected host closed before applying the reload.".to_owned()),
        ));
    }

    if let Some(&(cnt, t0)) = st.pending_web_reloads.get(&cycle.generation)
        && cnt > 0
    {
        if t0.elapsed() < WEB_RELOAD_GRACE {
            return None;
        }
        return Some(make_error_resp(
            "host_disconnected",
            &cycle.tier,
            cycle.seq,
            cycle.generation,
            cycle.build_ms,
            hosts,
            watched_roots,
            format!("web host did not reconnect after reloading generation {}", cycle.generation),
            Some("The browser tab closed or threw during reload; check browser console.".to_owned()),
        ));
    }
    let total_hosts = st.ws_hosts.len() + st.pair_hosts.len();
    if total_hosts == 0 {
        if require_host || wait_for == WaitForMode::Ack {
            return Some(make_error_resp(
                "no_hosts_connected",
                &cycle.tier,
                cycle.seq,
                cycle.generation,
                cycle.build_ms,
                hosts,
                watched_roots,
                "build succeeded, but no host is connected to acknowledge it".to_owned(),
                Some("Connect Skia (`--skia`), Web (`http://127.0.0.1:<web_port>`), or iOS Simulator (`cargo nv run -t ios-sim --pair-dev`), or pass `--wait-for build`.".to_owned()),
            ));
        }
        return Some(ControlResponse {
            ok: true,
            status: "built".to_owned(),
            pid: None,
            package: None,
            seq: cycle.seq,
            generation: cycle.generation,
            tier: cycle.tier.clone(),
            build_ms: cycle.build_ms,
            ack_ms: 0,
            connected_hosts: 0,
            acked_hosts: 0,
            hosts,
            watched_roots,
            diagnostics: Vec::new(),
            error: None,
            hint: None,
        });
    }
    let mut acked = 0usize;
    let mut max_ack_ms = 0u64;
    for (&id, h) in &st.ws_hosts {
        if h.last_acked_gen < cycle.generation {
            return None;
        }
        if !h.last_ack_ok {
            return Some(make_error_resp(
                "host_error",
                &cycle.tier,
                cycle.seq,
                cycle.generation,
                cycle.build_ms,
                hosts,
                watched_roots,
                h.last_ack_detail.clone().unwrap_or_else(|| {
                    format!("{} host (ws-{id}) failed to apply generation {}", h.client_kind, cycle.generation)
                }),
                None,
            ));
        }
        acked += 1;
        max_ack_ms = max_ack_ms.max(h.last_ack_ms);
    }

    if let Some(target_seq) = cycle.pair_target_wire_seq {
        for (&sid, p) in &st.pair_hosts {
            if p.last_acked_seq < target_seq {
                return None;
            }
            if p.last_ack_status != nativeview_wire::FRAME_ACK_STATUS_APPLIED {
                return Some(make_error_resp(
                    "host_error",
                    &cycle.tier,
                    cycle.seq,
                    cycle.generation,
                    cycle.build_ms,
                    hosts,
                    watched_roots,
                    format!("paired peer-{sid} reported decode error on wire seq {}", p.last_acked_seq),
                    None,
                ));
            }
            acked += 1;
            max_ack_ms = max_ack_ms.max(p.last_ack_ms);
        }
    } else {
        acked += st.pair_hosts.len();
    }

    Some(ControlResponse {
        ok: true,
        status: "applied".to_owned(),
        pid: None,
        package: None,
        seq: cycle.seq,
        generation: cycle.generation,
        tier: cycle.tier.clone(),
        build_ms: cycle.build_ms,
        ack_ms: max_ack_ms,
        connected_hosts: total_hosts,
        acked_hosts: acked,
        hosts,
        watched_roots,
        diagnostics: Vec::new(),
        error: None,
        hint: None,
    })
}

pub(crate) fn build_timeout_response(st: &CoordinatorState) -> ControlResponse {
    let hosts = collect_hosts(st);
    let watched_roots = st.watched_roots.iter().map(|r| r.display().to_string()).collect();
    let (seq, generation, tier, build_ms) = st.last_cycle.as_ref().map_or(
        (0, 0, "initial".to_owned(), 0),
        |c| (c.seq, c.generation, c.tier.clone(), c.build_ms),
    );
    let hint = if st.in_flight {
        "Build is still running; increase `--timeout-ms` for cold Tier-2 compiles."
    } else if !hosts.is_empty() {
        "Build finished, but a connected host did not acknowledge the frame in time (check host console)."
    } else {
        "Daemon did not settle before timeout."
    };
    make_error_resp(
        "timeout",
        &tier,
        seq,
        generation,
        build_ms,
        hosts,
        watched_roots,
        "timed out waiting for `nv dev` to settle".to_owned(),
        Some(hint.to_owned()),
    )
}