constructelligence's picture
Update code: real-machine G-code adapter, commissioning gate, machine_job runner, pump watchdog firmware, twin completion gate, realism and masking modules (card and weights unchanged)
4eecd03 verified
Raw History Blame Contribute Delete
25.7 kB
// Drone twin panel: the open job as a painting job a drone is flying. Set the launch point, upload a flight log (CSV), and see what the
// twin believes is painted, what is left, and what the log says about how the drone really flew. The heat map overlay is off by default.
// (Separate from the wall twin in twin.js, which fuses photos and video in millimetres.)
"use strict";
(() => {
const $ = (sel) => document.querySelector(sel);
const toggles = $("#layer-toggles"), stage = $("#stage"), anchor = $("#reasons");
if (!toggles || !stage || !anchor) return;
const st = { loaded: false, loading: false, info: null, jobId: null };
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
const num = (v) => { const n = parseFloat(v); return Number.isFinite(n) ? n : null; };
// overlay layer + switch
const chip = document.createElement("label");
chip.className = "chip";
chip.innerHTML = `<input type="checkbox" data-layer="dronetwin"><i class="sw sw-dtwin"></i>Drone twin`;
toggles.appendChild(chip);
const box = chip.querySelector("input");
const img = document.createElement("img");
img.className = "layer off dtwin-layer";
img.alt = "";
img.dataset.layer = "dronetwin";
(document.querySelector('img.layer[data-layer="paint"]:not(.edge)') || $("#photo")).after(img);
// next sortie: the passes the belief still wants, drawn over the photo (own switch in the panel, off by default)
const NS = "http://www.w3.org/2000/svg";
const nextSvg = document.createElementNS(NS, "svg");
nextSvg.setAttribute("class", "layer dtwin-next");
nextSvg.setAttribute("preserveAspectRatio", "none");
nextSvg.style.display = "none";
img.after(nextSvg);
// marked pass: one line picked from the audit table, so a bad pass can be pointed at on the photo
const passSvg = document.createElementNS(NS, "svg");
passSvg.setAttribute("class", "layer dtwin-marks");
passSvg.setAttribute("preserveAspectRatio", "none");
passSvg.style.display = "none";
nextSvg.after(passSvg);
// panel
const panel = document.createElement("section");
panel.id = "dtwin-panel";
panel.innerHTML = `
<h2 class="section">Drone twin</h2>
<div class="dt-card">
<div class="dt-setup">
<label>Launch point <span class="muted small">lat, lon, altitude (m)</span>
<span class="dt-row"><input class="field" id="dt-lat" inputmode="decimal" placeholder="lat"><input class="field" id="dt-lon" inputmode="decimal" placeholder="lon"><input class="field narrow" id="dt-alt" inputmode="decimal" placeholder="alt"></span></label>
<label class="dt-check"><input type="checkbox" id="dt-masked" checked> Windows and doors are masked <span class="muted small">(lets passes run to their edge)</span></label>
<button class="ghost" id="dt-setup">Set up the twin</button>
</div>
<div class="dt-status" id="dt-status" hidden></div>
<div class="dt-history" id="dt-history" hidden></div>
<div class="dt-actions" id="dt-actions" hidden>
<label class="ghost button">Upload flight log (CSV)<input type="file" id="dt-log" accept=".csv,text/csv,text/plain" hidden></label>
<label class="ghost button">Add re-scan photo<input type="file" id="dt-scan" accept="image/*" hidden></label>
<label class="dt-check dt-next-toggle"><input type="checkbox" id="dt-next"> Show next sortie</label>
<a class="ghost button" id="dt-plan" hidden>Flight plan (.plan)</a>
<a class="ghost button" id="dt-json" download>Twin JSON</a>
<a class="ghost button" id="dt-geo" download>GeoJSON</a>
<button class="ghost" id="dt-copy" type="button">Copy report</button>
</div>
<details class="dt-whatif" id="dt-whatif" hidden>
<summary>What if… <span class="muted small">wind and position error, before flying</span></summary>
<label>Position error <input type="range" id="dt-wi-pos" min="0.5" max="10" step="0.5" value="2"><b id="dt-wi-pos-v">2.0 cm</b></label>
<label>Wind <input type="range" id="dt-wi-wind" min="0" max="8" step="0.5" value="2"><b id="dt-wi-wind-v">2.0 m/s</b></label>
<div class="dt-wi-out" id="dt-wi-out"><span class="small muted">Move a slider to see the plan's predicted film.</span></div>
</details>
<details class="dt-passes" id="dt-passes" hidden>
<summary>Pass audit <span class="muted small">click a pass to mark it on the photo</span></summary>
<ul class="dt-passrows" id="dt-passrows"></ul>
<p class="small muted">Rows come from the sorties flown in this session; the twin's JSON keeps the summary.</p>
</details>
<div class="dt-next" id="dt-next-info" hidden></div>
<p class="small muted" id="dt-note">Without a flight log the twin only knows the plan. A log adds what the drone really flew and how well; nothing here claims a wall is finished unless the belief says so and a camera has looked recently.</p>
</div>`;
anchor.parentNode.insertBefore(panel, anchor.nextSibling);
async function api(path, options = {}) {
const r = await fetch(path, options);
const body = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(body.error || r.statusText);
return body;
}
const j = () => (typeof job !== "undefined" && job ? job : null);
const ago = (sec) => (sec == null ? "never" : sec < 90 ? `${Math.round(sec)} s ago` : sec < 5400 ? `${Math.round(sec / 60)} min ago` : `${(sec / 3600).toFixed(1)} h ago`);
function render(info) {
const s = info.status, c = info.calibration || {};
const words = { complete: "Complete", another_sortie: "Another sortie needed", hand_finish: "Hand finish left", needs_look: "Needs a look" };
const cls = { complete: "ok", another_sortie: "warn", hand_finish: "warn", needs_look: "bad" }[s.verdict] || "";
$("#dt-status").hidden = false;
const au = info.spray_audit, arows = au && Array.isArray(au.passes) ? au.passes : [];
const starved = au ? (au.starved_passes || arows.filter((p) => (p.flags || []).includes("starved_end")).map((p) => p.id)) : [];
const heavy = au ? (au.heavy_passes || arows.filter((p) => (p.flags || []).includes("heavy_end")).map((p) => p.id)) : [];
const pct = (v) => Math.round((v || 0) * 100);
const action = {
complete: "Nothing to fly. Keep the last re-scan with the job and hand it over.",
another_sortie: "Fly the next sortie below, then upload a re-scan photo.",
needs_look: "Take a re-scan photo: the belief is old, or parts of the wall were never seen.",
hand_finish: "What is left is narrower than the fan: hand finish, then re-scan to confirm.",
}[s.verdict] || "";
const tol = 0.15 * (Number((info.setup || {}).standoff_mm) || 300); // ±15 % film budget, in mm of standoff
const sag = au && au.standoff_sag_mm != null ? Number(au.standoff_sag_mm) : null;
const sagPct = sag == null ? null : Math.max(2, Math.min(100, Math.round((sag / tol) * 100)));
const spray = sag == null ? "" : `
<div class="dt-spray">
<div class="dt-spray-head"><span>Spray push on the nozzle</span><b>${au.reaction_n} N</b></div>
<div class="dt-spray-bar" role="img" aria-label="standoff sag ${sag} mm of a ${Math.round(tol)} mm budget">
<i class="${sagPct > 66 ? "bad" : sagPct > 40 ? "warn" : "ok"}" style="width:${sagPct}%"></i></div>
<div class="small muted">sag ${sag} mm of ±${Math.round(tol)} mm budget${au.standoff_bias_mm ? ` · setpoint biased ${au.standoff_bias_mm} mm` : ""}</div>
</div>`;
const fixes = starved.length + heavy.length;
// when nearly every pass shares one fault, the count is useless and the cause is what matters: say it
const medSpeed = (() => {
const v = arows.map((p) => Number(p.speed_mm_s)).filter((x) => Number.isFinite(x) && x > 0).sort((a, b) => a - b);
return v.length ? v[Math.floor(v.length / 2)] : null;
})();
const share = (k) => arows.filter((p) => Number(p[k + "_share"] || 0) > 0.2).length;
const plan = Number(((au && au.design) || {}).speed_mm_s);
let diag = "";
if (arows.length >= 5 && plan > 0 && medSpeed) {
if (share("heavy") >= 0.7 * arows.length && plan > medSpeed) {
diag = `Almost every pass came out heavy: the log averages ${Math.round(medSpeed)} mm/s against the plan's ${Math.round(plan)} mm/s, so each metre got about ${(plan / medSpeed).toFixed(1)}× the paint it was planned for.`;
} else if (share("starved") >= 0.7 * arows.length && medSpeed > plan) {
diag = `Almost every pass came out thin: the log averages ${Math.round(medSpeed)} mm/s against the plan's ${Math.round(plan)} mm/s, so each metre got about ${(medSpeed / plan).toFixed(1)}× too much speed for full film.`;
}
}
const diagEl = diag ? `<p class="dt-diag">${esc(diag)}</p>` : "";
const onT = Number(au && au.on_target_pct);
const audit = au ? `
<div class="dt-chips">
<span class="dt-chip ${Number.isFinite(onT) ? (onT >= 98 ? "ok" : onT >= 95 ? "warn" : "bad") : ""}"><small>Paint on target</small><b>${Number.isFinite(onT) ? onT + "%" : "—"}</b></span>
<span class="dt-chip ${Number(au.waste_l || 0) < 0.5 ? "ok" : "warn"}"><small>Waste</small><b>${Number.isFinite(Number(au.waste_l)) ? Number(au.waste_l).toFixed(2) + " L" : "—"}</b></span>
<span class="dt-chip ${fixes ? "warn" : "ok"}"><small>Passes flagged</small><b>${fixes || "none"}</b></span>
<span class="dt-chip"><small>Passes audited</small><b>${au.pass_count || arows.length || "—"}</b></span>
</div>${spray}` : "";
const missing = (s.missing || []).filter(Boolean);
const why = missing.length && s.verdict !== "complete"
? `<details class="dt-why"><summary>Why it is not done (${missing.length})</summary><ul class="dt-missing">${missing.map((m) => `<li>${esc(m)}</li>`).join("")}</ul></details>` : "";
$("#dt-status").innerHTML = `
<div class="dt-verdict ${cls}"><strong>${esc(words[s.verdict] || s.verdict)}</strong>
<span>${pct(s.believed_painted)}% believed painted · ${s.gap_m2} m² still bare</span></div>
<p class="dt-action"><b>Next:</b> ${esc(action)}</p>
<div class="dt-chips">
<span class="dt-chip ${s.fresh >= 0.9 ? "ok" : s.fresh >= 0.5 ? "warn" : "bad"}"><small>Camera-verified</small><b>${pct(s.fresh)}%</b><i>last look ${ago(s.last_observed_s)}</i></span>
<span class="dt-chip ${s.never_seen > 0.02 ? "bad" : s.never_seen > 0.001 ? "warn" : "ok"}"><small>Never photographed</small><b>${pct(s.never_seen)}%</b></span>
<span class="dt-chip ${s.stale > 0.02 ? "bad" : s.stale > 0.001 ? "warn" : "ok"}"><small>Stale</small><b>${pct(s.stale)}%</b><i>over ${Math.round((s.max_age_s || 0) / 60)} min</i></span>
<span class="dt-chip ${s.uncertain > 0.02 ? "warn" : "ok"}"><small>Unsure</small><b>${pct(s.uncertain)}%</b></span>
</div>
${audit}${diagEl}${why}
<dl class="dt-dl">
<dt>Facade</dt><dd>${info.facade.width_m} × ${info.facade.height_m} m</dd>
<dt>Fan / pass spacing</dt><dd>${Math.round(info.spray.fan_width_mm)} / ${Math.round(info.spray.pass_spacing_mm)} mm</dd>
<dt>Sorties logged</dt><dd>${info.sorties}</dd>
${c.source ? `<dt>Flown accuracy</dt><dd>±${(c.positioning_m * 100).toFixed(1)} cm · standoff ±${(c.standoff_error_rms_m * 100).toFixed(1)} cm</dd>` : ""}
${c.tpr ? `<dt>Camera hit / false alarm</dt><dd>${Math.round(c.tpr * 100)}% / ${Math.round(c.fpr * 100)}%</dd>` : ""}
</dl>`;
st.info = info; st.loaded = true; st.jobId = j().id;
renderPasses(arows);
const wi = $("#dt-whatif");
wi.hidden = false;
if (!wi.dataset.asked) { wi.dataset.asked = "1"; runWhatIf(); }
$("#dt-actions").hidden = false;
$("#dt-json").href = `/api/jobs/${j().id}/dronetwin.json`;
$("#dt-geo").href = `/api/jobs/${j().id}/dronetwin_geojson.json`;
const v = `?v=${Date.now()}`;
img.src = `/api/jobs/${j().id}/dronetwin_heatmap.png${v}`;
const sc = info.setup;
if (sc.home) { $("#dt-lat").value = sc.home[0]; $("#dt-lon").value = sc.home[1]; $("#dt-alt").value = sc.home[2] ?? ""; }
$("#dt-masked").checked = !!sc.masked_openings;
drawHistory(info.history || []);
st.info = info; st.loaded = true; st.jobId = j().id; st.next = null;
if ($("#dt-next").checked) showNext(); else { $("#dt-next-info").hidden = true; $("#dt-plan").hidden = true; }
if (typeof applyLayerToggles === "function") applyLayerToggles();
}
// the audit's own rows: the worst passes first, click one to mark where it was flown
function renderPasses(rows) {
const box = $("#dt-passes"), list = $("#dt-passrows");
list.textContent = "";
const usable = (rows || []).filter((p) => Array.isArray(p.line_mm) && p.line_mm.length === 4);
if (!usable.length) { box.hidden = true; passSvg.style.display = "none"; return; }
const flagged = (p) => (p.flags || []).length > 0;
const worst = usable.slice().sort((a, b) => (flagged(b) - flagged(a)) ||
(Number(a.film_median || 0) - Number(b.film_median || 0))).slice(0, 12);
worst.forEach((p) => {
const li = document.createElement("li");
li.className = "dt-passrow" + (flagged(p) ? " flagged" : "");
const b = document.createElement("button");
b.type = "button";
b.dataset.id = String(p.id);
b.dataset.line = JSON.stringify(p.line_mm);
b.innerHTML = `<b>#${esc(p.id)}</b><span>${Number(p.film_median || 0).toFixed(2)} film</span>` +
`<span>${Math.round((p.starved_share || 0) * 100)}% thin</span><span>${esc((p.flags || []).join(", ") || "ok")}</span>`;
li.append(b);
list.append(li);
});
box.hidden = false;
list.onclick = (e) => {
const b = e.target.closest("button[data-line]");
if (!b) return;
list.querySelectorAll("button").forEach((x) => x.classList.toggle("on", x === b));
markPass(JSON.parse(b.dataset.line), b.dataset.id);
};
}
function markPass(line, id) {
const info = st.info, jb = j();
if (!info || !jb || !Array.isArray(line) || line.length !== 4) return;
const mm = Number(info.facade.mm_per_px), H = Number(info.height);
if (!(mm > 0) || !(H > 0)) return;
const [x0, z0, x1, z1] = line.map(Number);
const a = [x0 / mm, H - z0 / mm], b = [x1 / mm, H - z1 / mm];
passSvg.setAttribute("viewBox", `0 0 ${jb.width} ${jb.height}`);
passSvg.innerHTML = `<line x1="${a[0].toFixed(1)}" y1="${a[1].toFixed(1)}" x2="${b[0].toFixed(1)}" y2="${b[1].toFixed(1)}" class="mark"/>` +
`<circle cx="${a[0].toFixed(1)}" cy="${a[1].toFixed(1)}" r="5" class="markdot"/>` +
`<circle cx="${b[0].toFixed(1)}" cy="${b[1].toFixed(1)}" r="5" class="markdot"/>`;
passSvg.style.display = "";
say(`Pass ${id} marked on the photo.`);
}
// what-if: the twin's own prediction under a different position error and wind
let wiTimer = 0;
function wiLabels() {
$("#dt-wi-pos-v").textContent = `${Number($("#dt-wi-pos").value).toFixed(1)} cm`; // the slider is in cm, the API wants m
$("#dt-wi-wind-v").textContent = `${Number($("#dt-wi-wind").value).toFixed(1)} m/s`;
}
async function runWhatIf() {
if (!j() || !st.loaded) return;
wiLabels();
const out = $("#dt-wi-out");
out.innerHTML = `<span class="small muted">Computing…</span>`;
const p = (Number($("#dt-wi-pos").value) / 100).toFixed(3), w = Number($("#dt-wi-wind").value).toFixed(1);
try {
const r = await api(`/api/jobs/${j().id}/dronetwinwhatif?positioning=${p}&wind=${w}&trials=3`);
const tone = r.good >= 0.9 ? "ok" : r.good >= 0.8 ? "warn" : "bad";
out.innerHTML = `<span class="dt-wi-chip ${tone}"><small>Good film</small><b>${Math.round(r.good * 100)}%</b></span>` +
`<span class="dt-wi-chip"><small>Thin</small><b>${Math.round(r.thin * 100)}%</b></span>` +
`<span class="dt-wi-chip"><small>On openings</small><b>${Math.round(r.overspray_on_openings * 100)}%</b></span>` +
`<span class="dt-wi-chip"><small>Hand finish</small><b>${Number(r.hand_finish_m2 || 0).toFixed(1)} m²</b></span>` +
`<span class="dt-wi-chip"><small>Margin off glass</small><b>${Math.round(r.margin_mm)} mm</b></span>` +
`<span class="dt-wi-chip"><small>Confidence</small><b>${r.trials} trial${r.trials === 1 ? "" : "s"}</b></span>`;
} catch (e) {
out.innerHTML = `<span class="small muted">What-if unavailable: ${esc(e.message)}</span>`;
}
}
// belief over time: one point per sortie or re-scan, from the event ledger
function drawHistory(h) {
const el = $("#dt-history");
if (h.length < 2) { el.hidden = true; return; }
const W = 240, H = 46, P = 4, tMax = Math.max(...h.map((e) => e[0]), 1);
const x = (t) => P + (t / tMax) * (W - 2 * P), y = (v) => H - P - v * (H - 2 * P);
const line = h.map((e, i) => `${i ? "L" : "M"}${x(e[0]).toFixed(1)},${y(e[2]).toFixed(1)}`).join("");
const dots = h.slice(1).map((e) => `<circle cx="${x(e[0]).toFixed(1)}" cy="${y(e[2]).toFixed(1)}" r="3" class="${e[1] === "observe" ? "obs" : "sortie"}"><title>${esc(e[1] === "observe" ? "Re-scan" : "Sortie")}: ${Math.round(e[2] * 100)}%</title></circle>`).join("");
const last = h[h.length - 1][2];
el.hidden = false;
el.innerHTML = `<div class="dt-hist-head"><span>Believed painted over time</span><strong>${Math.round(last * 100)}%</strong></div>
<svg viewBox="0 0 ${W} ${H}" class="dt-spark" role="img" aria-label="Believed painted after each sortie and re-scan">
<line x1="${P}" x2="${W - P}" y1="${y(1)}" y2="${y(1)}" class="goal"/><path d="${line}" class="ln"/>${dots}</svg>
<div class="dt-legend small muted"><span><i class="sortie"></i>sortie</span><span><i class="obs"></i>re-scan photo</span></div>`;
}
async function showNext() {
if (!j() || !st.loaded) { nextSvg.style.display = "none"; return; }
try {
if (!st.next) st.next = await api(`/api/jobs/${j().id}/dronetwinnext`);
} catch (e) { say(`Next sortie unavailable: ${e.message}`); return; }
const n = st.next, jb = j();
nextSvg.setAttribute("viewBox", `0 0 ${jb.width} ${jb.height}`);
const defs = `<defs><marker id="dt-arrow" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="5" markerHeight="5" orient="auto-start-reverse"><path d="M0,0 L8,4 L0,8 Z"/></marker></defs>`;
nextSvg.innerHTML = defs + (n.strokes || []).map((s, i) => {
const d = s.map((p, k) => `${k ? "L" : "M"}${p[0].toFixed(1)},${p[1].toFixed(1)}`).join("");
const [ex, ey] = s[s.length - 1], [sx, sy] = s[0];
return `<g class="dt-pass"><title>Pass ${i + 1} of ${n.passes}</title>` +
`<path d="${d}" class="halo"/><path d="${d}" class="pass" marker-end="url(#dt-arrow)"/>` +
`<circle cx="${sx}" cy="${sy}" r="3.5" class="pump"/><circle cx="${ex}" cy="${ey}" r="4" class="end"/></g>` +
(i === 0 ? `<circle cx="${sx}" cy="${sy}" r="7" class="start"/>` : "");
}).join("");
nextSvg.style.display = "";
const info = $("#dt-next-info");
info.hidden = false;
if (!n.passes) { info.innerHTML = `<strong>Nothing left for a sortie.</strong> <span class="muted">${esc(n.note || "")}</span>`; $("#dt-plan").hidden = true; return; }
const g = n.gate, so = n.sorties || [];
const paint = so.reduce((a, s) => a + (s.paint_l || 0), 0), spray = so.reduce((a, s) => a + (s.spray_s || 0), 0);
info.innerHTML = `<div class="dt-next-head"><strong>Next sortie: ${n.passes} pass${n.passes === 1 ? "" : "es"}</strong>` +
(so.length ? `<span class="muted small">${so.length} flight${so.length === 1 ? "" : "s"} · ${Math.round(spray)} s spray · ${paint.toFixed(2)} L</span>` : "") + `</div>` +
(n.reaction ? `<div class="small muted">push ${n.reaction.reaction_n} N · setpoint ${Math.round(n.reaction.setpoint_mm)} mm + ${n.reaction.sag_mm} mm sag</div>` : "") +
(g ? `<div class="dt-gate ${g.go ? "ok" : "bad"}">${g.go ? "Go: inside the drone's limits" : "No-go: " + esc((g.reasons || []).join("; "))}</div>` : `<div class="small muted">Set a launch point to get a flight plan.</div>`) +
(n.refused ? `<div class="small muted">The passes are shown, but no flight plan is offered for download until the gate passes.</div>` : "");
const a = $("#dt-plan");
if (n.mission && n.mission.length) {
a.hidden = false;
const body = n.mission.length === 1 ? n.mission[0] : n.mission;
if (a.href.startsWith("blob:")) URL.revokeObjectURL(a.href);
a.href = URL.createObjectURL(new Blob([JSON.stringify(body, null, 2)], { type: "application/json" }));
a.download = n.mission.length === 1 ? `next-sortie-${jb.id}.plan` : `next-sorties-${jb.id}.json`;
a.textContent = n.mission.length === 1 ? "Flight plan (.plan)" : `Flight plans (${n.mission.length})`;
} else a.hidden = true;
}
const say = (m) => { $("#dt-note").textContent = m; };
// collapse.js wraps this panel as an accordion card and starts it folded; switching the twin on should open it, or the
// first thing the user sees is a bare header (the folded body is inert, so nothing in it is clickable).
function openCard() {
const card = $("#dtwin-panel"), head = card && card.querySelector(":scope > .acc-head");
if (head && card.classList.contains("collapsed")) head.click(); // same path the user takes, so the state is remembered
}
async function ensure(request) {
if (st.loading) return;
if (!j()) { say("Open a job first: the twin is built from its photo and its scale."); return; }
openCard();
st.loading = true; say("Building the twin…");
try {
const info = request
? await api(`/api/jobs/${j().id}/dronetwin`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(request) })
: await api(`/api/jobs/${j().id}/dronetwin`);
render(info);
say("Heat map: green painted, yellow-green barely painted, orange barely bare, red bare. Faded = no camera look inside the evidence window (inferred from the flight log, or old).");
} catch (e) { say(`Twin unavailable: ${e.message}`); } finally { st.loading = false; }
}
$("#dt-setup").addEventListener("click", () => {
const lat = num($("#dt-lat").value), lon = num($("#dt-lon").value), alt = num($("#dt-alt").value);
const req = { masked_openings: $("#dt-masked").checked };
if (lat !== null && lon !== null) req.home = alt === null ? [lat, lon] : [lat, lon, alt];
ensure(req);
});
$("#dt-log").addEventListener("change", async (e) => {
const file = e.target.files[0]; e.target.value = "";
if (!file || !j()) return;
say(`Reading ${file.name}…`);
try {
const out = await api(`/api/jobs/${j().id}/dronetwinlog?sortie=${encodeURIComponent((st.info ? st.info.sorties : 0) + 1)}`, { method: "POST", body: await file.arrayBuffer() });
render(out);
const q = out.ingest.quality;
say(`Log added: ${out.ingest.strokes} spraying runs, ${q.spray_seconds} s of spray, cross-track ±${(q.cross_track_rms_m * 100).toFixed(1)} cm, standoff ${(q.standoff_mean_m * 100).toFixed(0)} cm.`);
} catch (err) { say(err.message); }
});
$("#dt-scan").addEventListener("change", async (e) => {
const file = e.target.files[0]; e.target.value = "";
if (!file || !j()) return;
say(`Lining ${file.name} up with the job photo…`);
try {
const out = await api(`/api/jobs/${j().id}/dronetwinobserve`, { method: "POST", body: await file.arrayBuffer() });
render(out);
const a = out.alignment;
say(`Re-scan fused: ${a.inliers} matched points (${Math.round(a.inlier_share * 100)}% agree), it saw ${Math.round(out.observed_share_of_target * 100)}% of the wall. Parts it did not see stay as they were.`);
} catch (err) { say(`Re-scan not used: ${err.message}`); }
});
$("#dt-next").addEventListener("change", (e) => {
if (e.target.checked) showNext();
else { nextSvg.style.display = "none"; $("#dt-next-info").hidden = true; }
});
box.addEventListener("change", () => { if (typeof applyLayerToggles === "function") applyLayerToggles(); if (box.checked && !st.loaded) ensure(); });
$("#dt-wi-pos").addEventListener("input", () => { wiLabels(); clearTimeout(wiTimer); wiTimer = setTimeout(runWhatIf, 250); });
$("#dt-wi-wind").addEventListener("input", () => { wiLabels(); clearTimeout(wiTimer); wiTimer = setTimeout(runWhatIf, 250); });
$("#dt-copy").addEventListener("click", async () => {
const info = st.info;
if (!info) return;
const body = JSON.stringify({ job: j().id, status: info.status, spray_audit: info.spray_audit, facade: info.facade,
setup: info.setup, calibration: info.calibration }, null, 1);
try {
await navigator.clipboard.writeText(body);
say("Report copied: status, spray audit and setup as JSON.");
} catch {
say("The browser blocked the clipboard: use Twin JSON instead.");
}
});
const prev = showJob;
showJob = function (job_) {
prev(job_);
st.loaded = false; st.info = null; st.next = null; img.removeAttribute("src");
nextSvg.innerHTML = ""; nextSvg.style.display = "none"; $("#dt-next").checked = false;
passSvg.innerHTML = ""; passSvg.style.display = "none"; $("#dt-passes").hidden = true;
$("#dt-whatif").hidden = true; delete $("#dt-whatif").dataset.asked;
$("#dt-history").hidden = true; $("#dt-next-info").hidden = true; $("#dt-plan").hidden = true;
$("#dt-status").hidden = true; $("#dt-actions").hidden = true;
if (box.checked) ensure();
};
})();