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
27.7 kB
// Digital twin panel: the open job's wall as a model in true millimetres, fused from every observation and compared with the plan.
// It shows what was LAST OBSERVED, with the age of that evidence, and it never fills in cells nobody has seen. It does not declare a wall finished:
// "verified" only means the evidence on file meets the stated thresholds (the server lists what is missing). Built here, independent of the rest of the markup.
(() => {
"use strict";
const $ = (s, r = document) => r.querySelector(s);
const el = (tag, attrs = {}, ...kids) => {
const e = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) { if (k === "class") e.className = v; else if (k === "text") e.textContent = v; else e.setAttribute(k, v); }
kids.forEach((c) => e.append(c));
return e;
};
const getJob = () => (typeof job !== "undefined" ? job : null);
const say = (m, k = "error") => (window.toast ? window.toast(m, k) : console.warn(m));
const LAYERS = [["plan", "Plan vs built"], ["painted", "Painted"], ["relief", "Relief"], ["confidence", "Confidence"], ["surface", "Surface"]];
const LEGEND = {
plan: [["#3cbe6e", "planned, painted"], ["#e15a46", "planned, seen, not painted"], ["#f0c83c", "planned, never seen (unknown)"], ["#5a8cf0", "painted outside the plan"], ["#ff8c1e", "damage"]],
painted: [["#3cbe6e", "painted"], ["#e17850", "not painted"], ["#606670", "not paintable"], ["#3c3e44", "never seen (unknown)"], ["#ff8c1e", "damage"]],
confidence: [["#3caa5a", "recent, well supported"], ["#e1503c", "old or thin evidence"], ["#3c3e44", "never seen"]],
relief: [["#1c6fb8", "recess (deeper than the wall)"], ["#e8e8e8", "flat (within 8 mm)"], ["#d42a1a", "protrusion (proud of the wall)"], ["#3c3e44", "no depth/scan data"]],
surface: [["#d2aa6e", "bare"], ["#50be78", "painted"], ["#6eb4e6", "window"], ["#96563c", "door"], ["#b464c8", "outlet/switch"], ["#3c3e44", "unknown"]],
};
let panel = null, layer = "plan", timer = 0, busy = false, jobId = null, last = null;
async function api(path, options = {}) {
const res = await fetch(path, options);
const type = res.headers.get("Content-Type") || "";
const body = type.includes("json") ? await res.json() : await res.arrayBuffer();
if (!res.ok) { const e = new Error((body && body.error) || `HTTP ${res.status}`); e.status = res.status; throw e; }
return body;
}
const pct = (v) => (v == null ? "—" : `${Math.round(100 * v)}%`);
const sqft = (v) => (v == null ? "—" : `${v < 10 ? v.toFixed(1) : Math.round(v)} sq ft`);
const ago = (s) => (s == null ? "—" : s < 90 ? `${Math.round(s)} s ago` : s < 5400 ? `${Math.round(s / 60)} min ago` : `${(s / 3600).toFixed(1)} h ago`);
function build() {
const status = el("span", { class: "twin-pill off", id: "twin-pill", text: "NO TWIN" });
const height = el("input", { class: "field narrow", id: "twin-height", inputmode: "decimal", placeholder: "wall height ft", maxlength: "6", "aria-label": "Wall height in feet (optional)" });
const make = el("button", { class: "ghost", id: "twin-build", text: "Quick build (photo only)" });
const pipe = el("button", { class: "primary", id: "twin-pipeline", text: "Build from all evidence" });
const update = el("button", { class: "ghost", id: "twin-update", text: "Update from views", disabled: "" });
const seg = el("div", { class: "seg", id: "twin-seg", role: "radiogroup", "aria-label": "Twin layer" });
LAYERS.forEach(([k, name]) => { const b = el("button", { "data-layer-t": k, "aria-pressed": k === layer ? "true" : "false", text: name }); if (k === layer) b.className = "on"; seg.append(b); });
seg.addEventListener("click", (e) => { const b = e.target.closest("button[data-layer-t]"); if (b) setLayer(b.dataset.layerT); });
const img = el("img", { id: "twin-img", alt: "The wall in true proportions, one colour per state", hidden: "" });
const empty = el("div", { class: "twin-empty", id: "twin-empty", text: "No twin for this job yet. Build one from the photo: the wall's size comes from the measured height you give, or an assumed ceiling height (which the twin flags)." });
const legend = el("div", { class: "twin-legend", id: "twin-legend" });
const overlay = el("div", { class: "twin-overlay", id: "twin-overlay", "aria-hidden": "true" });
const probe = el("div", { class: "twin-probe small", id: "twin-probe", "aria-live": "polite", text: "Hover the wall to inspect a point; press Measure, then click two points for a true distance." });
const measureBtn = el("button", { class: "ghost small", id: "twin-measure", "aria-pressed": "false", text: "Measure" });
const stats = el("div", { class: "twin-stats", id: "twin-stats" });
const block = el("ul", { class: "twin-block", id: "twin-block", "aria-live": "polite" });
const hist = el("div", { class: "twin-hist", id: "twin-hist", "aria-label": "Observations over time" });
const acc = el("div", { class: "twin-acc", id: "twin-acc", hidden: "" });
const pipeBox = el("div", { class: "twin-pipe", id: "twin-pipe", hidden: "", "aria-live": "polite" });
const opt = (id, text) => el("label", { class: "small muted twin-opt" }, el("input", { type: "checkbox", id }), document.createTextNode(" " + text));
const pipeOpts = el("div", { class: "twin-pipe-opts" }, opt("twin-opt-drawing", "Let a matched drawing set the scale (never over a measured one)"), opt("twin-opt-ai", "Add an AI read-through (advisory; only if a key is set)"));
const num = (id, ph, label) => el("label", { class: "small muted twin-field" }, document.createTextNode(label), el("input", { class: "field narrow", id, inputmode: "decimal", placeholder: ph, maxlength: "8", "aria-label": label }));
const upSel = el("select", { class: "field", id: "twin-up", "aria-label": "Which scan axis points up" });
[["z", "up = +Z"], ["y", "up = +Y"], ["x", "up = +X"], ["-z", "up = −Z"], ["-y", "up = −Y"], ["-x", "up = −X"]].forEach(([v, t]) => upSel.append(el("option", { value: v, text: t })));
const inputs = el("details", { class: "twin-inputs", id: "twin-inputs" },
el("summary", { text: "Add measurements to make the model more accurate" }),
el("div", { class: "twin-in-row" }, el("strong", { class: "small", text: "Laser distance meter (metres)" }),
el("div", { class: "twin-in-fields" }, num("twin-lw", "e.g. 4.20", "Width"), num("twin-lh", "e.g. 2.60", "Height"), num("twin-ld", "optional", "Diagonal"), num("twin-lacc", "2", "± mm")),
el("button", { class: "ghost small", id: "twin-laser-add", text: "Add laser readings" })),
el("div", { class: "twin-in-row" }, el("strong", { class: "small", text: "Laser scan point cloud (PLY / XYZ / CSV, metres)" }),
el("div", { class: "twin-in-fields" }, upSel, el("label", { class: "small muted twin-field" }, el("input", { type: "checkbox", id: "twin-flip" }), document.createTextNode(" mirror left–right"))),
el("label", { class: "ghost button small", for: "twin-scan-file", text: "Choose scan file" }), el("input", { type: "file", id: "twin-scan-file", accept: ".ply,.xyz,.csv,.txt", hidden: "" }),
el("p", { class: "small muted", text: "A scan's axes are arbitrary: say which one is up. The result repeats that assumption." })),
el("div", { class: "twin-in-row" }, el("strong", { class: "small", text: "Photos, video and depth" }),
el("div", { class: "twin-in-fields" }, el("button", { class: "ghost small", id: "twin-more-views", text: "Add photo or video" }), el("button", { class: "ghost small", id: "twin-more-depth", text: "Add depth / LiDAR map" })),
el("p", { class: "small muted", text: "More views of the same wall fuse into one whole wall. Rebuild afterwards to use them." })));
const note = el("p", { class: "small muted twin-note", id: "twin-note", text: "A twin shows what was last observed, with the age of the evidence. Cells nobody has seen stay unknown. It does not declare a wall finished." });
panel = el("section", { class: "twin-panel", id: "twin-panel", hidden: "", "aria-label": "Digital twin" },
el("div", { class: "twin-head" }, el("h2", { class: "section", text: "Digital twin" }), status),
el("div", { class: "twin-ctl" }, height, pipe, make, update, seg),
pipeOpts,
el("div", { class: "twin-body" }, el("div", { class: "twin-viewcol" }, el("div", { class: "twin-view" }, img, overlay, empty, legend), el("div", { class: "twin-tools" }, measureBtn, probe)), el("div", { class: "twin-side" }, acc, pipeBox, stats, block, hist)),
inputs,
note);
const anchor = $("#live-panel") || $("#robot-bar") || $(".legend");
(anchor && anchor.parentNode ? anchor.parentNode : document.body).insertBefore(panel, anchor || null);
const btn = el("button", { class: "ghost twin-open", id: "twin-open", "aria-pressed": "false", text: "Digital twin" });
(($(".group.views") || $(".toolbar")) || document.body).append(btn);
btn.addEventListener("click", toggle);
make.addEventListener("click", create);
pipe.addEventListener("click", runPipeline);
$("#twin-laser-add", panel).addEventListener("click", addLaser);
$("#twin-scan-file", panel).addEventListener("change", addScan);
$("#twin-more-views", panel).addEventListener("click", () => { const f = $("#ev-view-file"); if (f) f.click(); else say("The evidence card is not available on this page."); });
$("#twin-more-depth", panel).addEventListener("click", () => { const f = $("#ev-depth-file"); if (f) f.click(); else say("The evidence card is not available on this page."); });
update.addEventListener("click", refreshFromViews);
measureBtn.addEventListener("click", () => { measuring = !measuring; pts = []; measureBtn.setAttribute("aria-pressed", measuring ? "true" : "false"); measureBtn.classList.toggle("on", measuring); overlay.parentNode.dataset.measuring = measuring ? "1" : "0"; drawMeasure(); probeText(measuring ? "Click the first point." : ""); });
overlay.parentNode.addEventListener("mousemove", onMove);
overlay.parentNode.addEventListener("click", onClick);
overlay.parentNode.addEventListener("mouseleave", () => { if (!measuring || pts.length !== 1) probeText(""); });
}
let measuring = false, pts = [], probeTimer = 0, probeSeq = 0;
const probeText = (t) => { const p = $("#twin-probe"); if (p) p.textContent = t || "Hover the wall to inspect a point; press Measure, then click two points for a true distance."; };
function wallPoint(e) {
const img = $("#twin-img"); if (!last || img.hidden) return null;
const r = img.getBoundingClientRect(); if (!r.width) return null;
const fx = (e.clientX - r.left) / r.width, fy = (e.clientY - r.top) / r.height;
if (fx < 0 || fx >= 1 || fy < 0 || fy >= 1) return null;
return { fx, fy, x: fx * last.wall_mm[0], y: fy * last.wall_mm[1] };
}
const m2 = (mm) => (mm >= 1000 ? `${(mm / 1000).toFixed(2)} m` : `${Math.round(mm)} mm`);
function onMove(e) {
const p = wallPoint(e); if (!p) return;
if (measuring && pts.length === 2) return; // keep a finished measurement on screen
if (measuring && pts.length === 1) { drawMeasure(p); const d = Math.hypot(p.x - pts[0].x, p.y - pts[0].y); probeText(`${m2(d)} (across ${m2(Math.abs(p.x - pts[0].x))}, down ${m2(Math.abs(p.y - pts[0].y))})`); return; }
clearTimeout(probeTimer);
const seq = ++probeSeq, j = getJob();
probeTimer = setTimeout(async () => {
try {
const c = await api(`/api/jobs/${j.id}/twin/cell?x=${p.x.toFixed(0)}&y=${p.y.toFixed(0)}`);
if (seq !== probeSeq) return;
const bits = [`${m2(c.x_mm)} across, ${m2(c.y_mm)} down`, c.opening ? `${c.surface} ${c.opening}` : c.surface];
if (c.painted_fraction != null) bits.push(c.painted_fraction >= 0.5 ? "painted" : "unpainted");
if (c.age_s != null) bits.push(`seen ${ago(c.age_s)}`);
if (c.relief_mm != null) bits.push(`relief ${c.relief_mm} mm`);
if (c.damage) bits.push("damage");
if (c.planned) bits.push("planned");
probeText(bits.join(" · "));
} catch { /* the probe is a convenience */ }
}, 120);
}
function onClick(e) {
if (!measuring) return;
const p = wallPoint(e); if (!p) return;
clearTimeout(probeTimer); probeSeq++; // a pending hover read-out must not overwrite the measurement
if (pts.length >= 2) pts = [];
pts.push(p); drawMeasure();
if (pts.length === 2) { const d = Math.hypot(pts[1].x - pts[0].x, pts[1].y - pts[0].y); probeText(`Distance ${m2(d)} (across ${m2(Math.abs(pts[1].x - pts[0].x))}, down ${m2(Math.abs(pts[1].y - pts[0].y))}). ${last.provenance && last.provenance.scale_assumed ? "The wall's size is ASSUMED, so this is not a real measurement." : "Click again to start a new one."}`); }
else probeText("Click the second point.");
}
function drawMeasure(live) {
const o = $("#twin-overlay"); o.textContent = "";
const all = pts.length === 1 && live ? [pts[0], live] : pts.slice();
const box = o.getBoundingClientRect();
all.forEach((p) => { const d = el("i", { class: "twin-dot" }); d.style.left = `${100 * p.fx}%`; d.style.top = `${100 * p.fy}%`; o.append(d); });
if (all.length === 2) {
const x0 = all[0].fx * box.width, y0 = all[0].fy * box.height, x1 = all[1].fx * box.width, y1 = all[1].fy * box.height;
const ln = el("i", { class: "twin-line" });
ln.style.left = `${x0}px`; ln.style.top = `${y0}px`; ln.style.width = `${Math.hypot(x1 - x0, y1 - y0)}px`; ln.style.transform = `rotate(${Math.atan2(y1 - y0, x1 - x0)}rad)`;
o.append(ln);
}
}
async function toggle() {
const open = panel.hidden;
panel.hidden = !open;
$("#twin-open").setAttribute("aria-pressed", open ? "true" : "false");
clearInterval(timer);
if (open) { await poll(true); timer = setInterval(poll, 2000); }
}
function setLayer(k) {
layer = k;
document.querySelectorAll("#twin-seg button").forEach((b) => { const on = b.dataset.layerT === k; b.classList.toggle("on", on); b.setAttribute("aria-pressed", on ? "true" : "false"); });
if (last) showImage(true);
renderLegend();
}
async function create() {
const j = getJob();
if (!j) { say("Open or create a job first."); return; }
const raw = $("#twin-height").value.trim();
if (raw && !(Number(raw) >= 4 && Number(raw) <= 40)) { say("Wall height should be between 4 and 40 ft (or leave it empty to assume 8 ft)."); return; }
$("#twin-build").disabled = true;
try {
render(await api(`/api/jobs/${j.id}/twin`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(raw ? { wall_height_ft: Number(raw) } : {}) }));
say(raw ? "Twin built with your measured height." : "Twin built with an ASSUMED 8 ft ceiling: areas are not trustworthy until you give the real height.", raw ? "ok" : "warn");
} catch (e) { say(e.message || e); } finally { $("#twin-build").disabled = false; }
}
const STAGE_LABEL = { inventory: "Evidence on file", perceive: "Vision model", drawings: "Drawings", scale: "Scale", twin: "Twin", design: "Built vs drawn", model: "Model & takeoff", verify: "Accuracy", ai: "AI read-through" };
async function runPipeline() {
const j = getJob();
if (!j) { say("Open or create a job first."); return; }
const body = { apply_drawing_scale: $("#twin-opt-drawing").checked, ai: $("#twin-opt-ai").checked };
const raw = $("#twin-height").value.trim();
if (raw) { if (!(Number(raw) >= 4 && Number(raw) <= 40)) { say("Wall height should be between 4 and 40 ft."); return; } body.wall_height_ft = Number(raw); }
$("#twin-pipeline").disabled = true;
try {
const rep = await api(`/api/jobs/${j.id}/twin/pipeline`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
renderPipeline(rep, j.id);
await poll(true);
say(rep.ok ? "Twin built from all the evidence on file." : "The pipeline could not build a twin: see the stages.", rep.ok ? "ok" : "warn");
} catch (e) { say(e.message || e); } finally { $("#twin-pipeline").disabled = false; }
}
function renderPipeline(rep, id) {
const box = $("#twin-pipe");
box.textContent = "";
if (!rep) { box.hidden = true; return; }
box.hidden = false;
const list = el("ol", { class: "twin-stages" });
rep.stages.forEach((s) => {
const tone = s.status === "done" ? "ok" : s.status === "failed" ? "bad" : s.status === "attention" ? "warn" : "skip";
list.append(el("li", { class: tone }, el("b", { text: STAGE_LABEL[s.name] || s.name }), el("span", { class: "twin-stage-state", text: s.status }), el("span", { class: "small muted", text: s.detail || "" })));
});
box.append(el("h3", { class: "small", text: "Pipeline" }), list);
const ai = rep.stages.find((s) => s.name === "ai" && s.answer);
if (ai) box.append(el("p", { class: "small twin-ai", text: `AI (advisory): ${ai.answer}` }));
if (rep.warnings.length) box.append(el("ul", { class: "twin-warns small" }, ...rep.warnings.map((w) => el("li", { text: w }))));
if (rep.needs.length) box.append(el("p", { class: "small muted", text: "To improve it:" }), el("ul", { class: "twin-needs small" }, ...rep.needs.map((n) => el("li", { text: n }))));
const links = el("p", { class: "small twin-exports" }, document.createTextNode("Export: "));
[["openings.json", "openings (JSON)"], ["openings.csv", "openings (CSV)"], ["defects.json", "defects"], ["quantities.json", "paint takeoff"], ["model.obj", "3D mesh (OBJ)"]].forEach(([f, t]) => links.append(el("a", { href: `/api/jobs/${id}/twin/${f}?download=1`, text: t }), document.createTextNode(" ")));
box.append(links);
api(`/api/jobs/${id}/twin/history`).then((h) => {
const sn = h.snapshots || [];
if (sn.length < 2) { if (sn.length === 1) box.append(el("p", { class: "small muted twin-progress", text: `First snapshot saved (${sn[0].painted_ft2} of ${sn[0].paintable_ft2} sq ft painted). Run again later to see progress.` })); return; }
const a = sn[0], b = sn[sn.length - 1], ch = b.change && b.change.comparable ? b.change : null;
box.append(el("p", { class: "small twin-progress", text: `Progress over ${sn.length} snapshots: painted ${a.painted_ft2} → ${b.painted_ft2} sq ft of ${b.paintable_ft2}` + (ch ? `; last step +${ch.newly_painted_ft2} sq ft painted` + (ch.new_damage_ft2 ? `, ${ch.new_damage_ft2} sq ft new damage` : "") : "") + "." }));
}).catch(() => { /* history is a convenience */ });
}
const mm = (id) => { const v = $(id).value.trim(); return v === "" ? null : Math.round(Number(v) * 1000 * 10) / 10; };
async function rebuild() {
const j = getJob(); if (!j) return;
const raw = $("#twin-height").value.trim();
render(await api(`/api/jobs/${j.id}/twin`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(raw ? { wall_height_ft: Number(raw) } : {}) }), true);
}
async function addLaser() {
const j = getJob(); if (!j) { say("Open or create a job first."); return; }
const w = mm("#twin-lw"), h = mm("#twin-lh"), d = mm("#twin-ld"), acc = $("#twin-lacc").value.trim();
if (w == null || h == null) { say("Enter both the wall's width and height in metres (a laser meter reads each in a second)."); return; }
try {
const r = await api(`/api/jobs/${j.id}/laser`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ width_mm: w, height_mm: h, diagonal_mm: d, accuracy_mm: acc ? Number(acc) : null }) });
await rebuild();
const dc = r.laser.diagonal_check;
say(dc && !dc.ok ? `Laser readings added, but the diagonal does not match (${dc.gap_mm} mm off): ${dc.meaning}.` : "Laser readings added: the twin's size now comes from them.", dc && !dc.ok ? "warn" : "ok");
} catch (e) { say(e.message || e); }
}
async function addScan(e) {
const file = e.target.files[0]; e.target.value = "";
const j = getJob(); if (!file) return;
if (!j) { say("Open or create a job first."); return; }
const q = new URLSearchParams({ filename: file.name, up: $("#twin-up").value, flip: $("#twin-flip").checked ? "1" : "0" });
say("Fitting the wall plane to the scan…", "ok");
try {
const r = await api(`/api/jobs/${j.id}/scan?${q}`, { method: "POST", body: await file.arrayBuffer() });
await rebuild();
const s2 = r.scan;
say(`Scan used: wall ${(s2.dims_mm[0] / 1000).toFixed(3)} × ${(s2.dims_mm[1] / 1000).toFixed(3)} m, plane scatter ${s2.plane_rms_mm} mm, ${Math.round(100 * s2.inlier_fraction)}% of points on the wall.` + (s2.warnings.length ? ` ${s2.warnings[0]}` : ""), s2.warnings.length ? "warn" : "ok");
} catch (err) { say(err.message || err); }
}
async function refreshFromViews() {
const j = getJob(); if (!j) return;
try {
const st = await api(`/api/jobs/${j.id}/twin/update`, { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" });
render(st);
say(st.added_views.length ? `${st.added_views.length} new view${st.added_views.length === 1 ? "" : "s"} folded into the twin.` : "No new registered views to add.", st.added_views.length ? "ok" : "warn");
} catch (e) { say(e.message || e); }
}
async function poll(force) {
if (busy || !panel || panel.hidden) return;
const j = getJob();
if (!j) { render(null); return; }
busy = true;
try {
if (jobId !== j.id) { jobId = j.id; last = null; try { const h = await api(`/api/jobs/${j.id}/twin/pipeline`); renderPipeline(h.last, j.id); } catch { renderPipeline(null); } }
const st = await api(`/api/jobs/${j.id}/twin`);
render(st.built === false ? null : st, force);
} catch (e) { /* keep the last picture */ } finally { busy = false; }
}
function renderLegend() {
const lg = $("#twin-legend");
lg.textContent = "";
(LEGEND[layer] || []).forEach(([c, t]) => { const sw = el("i"); sw.style.background = c; lg.append(el("span", { class: "twin-lg" }, sw, document.createTextNode(t))); });
}
function showImage(force) {
const j = getJob(); if (!j || !last) return;
const key = `${j.id}|${layer}|${last.observations}|${last.latest_age_s == null ? "" : Math.floor(last.latest_age_s / 20)}`;
const img = $("#twin-img");
if (force || img.dataset.key !== key) { img.dataset.key = key; img.src = `/api/jobs/${j.id}/twin/${layer}.png?k=${encodeURIComponent(key)}`; }
}
function stat(label, value, tone) { return el("div", { class: `twin-stat ${tone || ""}` }, el("small", { text: label }), el("b", { text: value })); }
function render(st, force) {
last = st;
const pill = $("#twin-pill"), img = $("#twin-img"), empty = $("#twin-empty");
$("#twin-update").disabled = !st;
$("#twin-build").textContent = st ? "Rebuild" : "Build twin";
if (!st) {
pill.textContent = "NO TWIN"; pill.className = "twin-pill off";
img.hidden = true; empty.hidden = false;
$("#twin-stats").textContent = ""; $("#twin-block").textContent = ""; $("#twin-hist").textContent = "";
renderLegend(); return;
}
empty.hidden = true; img.hidden = false;
const ok = st.verified_complete;
pill.textContent = st.provenance.scale_assumed ? "ASSUMED SCALE" : ok ? "EVIDENCE MEETS THRESHOLDS" : "IN PROGRESS";
pill.className = `twin-pill ${st.provenance.scale_assumed ? "warn" : ok ? "ok" : "info"}`;
const p = st.plan;
const stats = $("#twin-stats");
stats.textContent = "";
stats.append(
stat("Wall", `${(st.wall_mm[0] / 1000).toFixed(2)} × ${(st.wall_mm[1] / 1000).toFixed(2)} m`, st.provenance.scale_assumed ? "warn" : ""),
stat("Observed", pct(st.observed_share_of_wall), ""),
stat("Painted (of seen)", pct(st.painted_share_of_observed_paintable), ""),
stat("Last look", ago(st.latest_age_s), st.latest_age_s != null && st.latest_age_s > 300 ? "warn" : ""),
stat("Stale evidence", pct(st.stale_share), st.stale_share > 0.3 ? "warn" : ""),
stat("Observations", String(st.observations), ""));
if (p) stats.append(stat("Planned", sqft(p.planned_area_ft2), ""), stat("Planned, not painted", sqft(p.planned_not_painted_ft2), p.planned_not_painted_ft2 > 0 ? "bad" : "ok"),
stat("Planned, never seen", sqft(p.planned_unobserved_ft2), p.planned_unobserved_ft2 > 0 ? "warn" : "ok"), stat("Painted outside plan", sqft(p.painted_outside_plan_ft2), p.painted_outside_plan_ft2 > 0.5 ? "warn" : ""));
if (st.damage_area_ft2 > 0) stats.append(stat("Damage seen", sqft(st.damage_area_ft2), "bad"));
renderAccuracy(st);
const bl = $("#twin-block");
bl.textContent = "";
if (ok) bl.append(el("li", { class: "ok", text: "The evidence on file meets every threshold. This is not a finish sign-off." }));
(st.verification_blockers || []).forEach((b) => bl.append(el("li", { text: b })));
const h = $("#twin-hist");
h.textContent = "";
const hist = (st.history || []).slice(-24), mx = Math.max(1, ...hist.map((x) => x.cells || 0));
hist.forEach((x) => { const bar = el("i", { title: `${x.source}: ${x.cells} cells` }); bar.style.height = `${Math.max(8, Math.round(100 * (x.cells || 0) / mx))}%`; bar.className = x.source === "live frame" ? "live" : ""; h.append(bar); });
renderLegend();
showImage(force);
}
function renderAccuracy(st) {
const box = $("#twin-acc");
box.textContent = "";
const m = st.model_accuracy, a = st.accuracy;
if (!m || !a) { box.hidden = true; return; }
box.hidden = false;
box.dataset.level = m.label.toLowerCase();
const head = el("div", { class: "twin-acc-head" }, el("span", { class: "twin-acc-pct", text: `${m.score}%` }), el("span", { class: "twin-acc-label", text: `${m.label} model accuracy` }));
const basis = a.sources.map((x) => x.kind + (x.uncertainty_mm ? ` (±${x.uncertainty_mm} mm)` : x.assumed ? " (assumed)" : "")).join(" + ");
box.append(head, el("p", { class: "small", text: `Size from: ${basis}. ${a.views_fused} view${a.views_fused === 1 ? "" : "s"} fused${a.wall_complete_in_view ? ", whole wall in view" : ", wall NOT fully in view"}.` }),
el("p", { class: "small muted", text: `Expected size of the error: ${m.expected_error}.` }));
(a.checks || []).forEach((c) => {
const t = c.name.startsWith("photo") ? `Photo size vs laser: width ${c.width_pct > 0 ? "+" : ""}${c.width_pct}%, height ${c.height_pct > 0 ? "+" : ""}${c.height_pct}%` : `${c.name}: ${c.gap_mm} mm off`;
box.append(el("div", { class: `twin-check ${c.ok ? "ok" : "bad"}`, text: `${c.ok ? "✓" : "✗"} ${t}${c.ok ? "" : " — " + (c.meaning || "")}` }));
});
if (st.provenance && st.provenance.scan_vs_laser_pct) { const v = st.provenance.scan_vs_laser_pct; box.append(el("div", { class: "twin-check ok", text: `Scan vs laser meter: width ${v.width}%, height ${v.height}%` })); }
if (m.conflict) box.append(el("div", { class: "twin-check bad", text: `✗ ${m.conflict}` }));
if (st.relief) box.append(el("p", { class: "small muted", text: `Relief: up to ${st.relief.max_protrusion_mm} mm proud, ${st.relief.max_recess_mm} mm recessed over ${Math.round(100 * st.relief.observed_share)}% of the wall.` }));
if (m.next && m.next.length) box.append(el("p", { class: "small muted", text: `To raise it: ${m.next.slice(0, 2).map((n) => `${n.do} (+${n.gain})`).join("; ")}.` }));
}
function init() { build(); }
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init); else init();
window.PVTwin = { poll, render };
})();