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);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, clap::ValueEnum)]
#[serde(rename_all = "snake_case")]
pub(crate) enum WaitForMode {
#[default]
Auto,
Build,
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()),
)
}