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
16.5 kB
// Typed instructions for the console. The text is turned into PROPOSED actions by the server (prompt_cmd.py: a fixed whitelist, no approving / arming /
// starting anything), shown here with the reason for each, and only run when the operator presses Apply. Questions are answered from the job's own data.
(() => {
"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));
// suggestions in two groups: things that change the plan, and questions answered from this job's own data
const EXAMPLES = [["Change the plan", ["don't paint the left window", "only paint the top half", "the wall is 9 ft high", "draw this wall to scale"]],
["Ask", ["how much paint do I need?", "what did you find?", "how accurate is this?"]]];
// Adding evidence goes through the same pickers and handlers as the rest of the console; the box only routes to them.
const ATTACH = [["view", "Photo or video of this wall", "Another angle: raises measurement confidence", "#ev-view-file"],
["job", "New job from a photo", "Start a fresh wall", "#file"],
["video", "New job from a video", "A walk past the wall", "#vfile"],
["drawing", "Drawing or plan", "PDF, PNG or JPG to set the scale", "#dfile"]];
const INTENT = /\b(add|upload|attach|take|send|use|import)\b.*\b(photos?|pictures?|images?|videos?|clips?|footage|drawings?|plans?|pdfs?|elevations?)\b/i;
const HISTORY_MAX = 20;
let proposed = [], busy = false, history = [], hpos = -1;
const store = { get(k) { try { return localStorage.getItem(k); } catch (e) { return null; } }, set(k, v) { try { localStorage.setItem(k, v); } catch (e) { /* not remembered */ } } };
async function api(path, body) {
const res = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
const data = await res.json();
if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
return data;
}
function build() {
const input = el("input", { class: "field", id: "prompt-input", placeholder: "Tell the console what to do, or ask a question", maxlength: "400", "aria-label": "Instruction or question", autocomplete: "off" });
const go = el("button", { class: "primary", id: "prompt-go", type: "button", "aria-label": "Send", title: "Send (Enter)", text: "Ask" });
const clip = el("button", { class: "prompt-attach", id: "prompt-attach", type: "button", "aria-label": "Add a photo, video or drawing", "aria-haspopup": "true", "aria-expanded": "false", title: "Add a photo, video or drawing (or drop a file here)" }, el("span", { class: "prompt-plus", "aria-hidden": "true" }));
const menu = el("div", { class: "prompt-menu", id: "prompt-menu", role: "menu", hidden: "" });
ATTACH.forEach(([mode, label, sub]) => {
const b = el("button", { class: "prompt-menu-item", type: "button", role: "menuitem", "data-mode": mode }, el("strong", { text: label }), el("small", { class: "muted", text: sub }));
b.addEventListener("click", () => { closeMenu(); pick(mode); });
menu.append(b);
});
const field = el("div", { class: "prompt-field" }, clip, input, el("kbd", { class: "prompt-key", "aria-hidden": "true", text: "/" }), go);
const head = el("button", { class: "prompt-head", type: "button", "aria-expanded": "true" }, el("span", { class: "prompt-title", text: "Ask or instruct" }),
el("span", { class: "prompt-hint small muted", text: "Plain words. Nothing runs until you press Apply." }), el("span", { class: "acc-chev", "aria-hidden": "true" }));
const chips = el("div", { class: "prompt-chips", id: "prompt-chips" });
const addG = el("div", { class: "prompt-group" }, el("span", { class: "prompt-glabel small muted", text: "Add" }));
[["view", "Add a photo or video"], ["drawing", "Add a drawing"]].forEach(([mode, t]) => { const b = el("button", { class: "prompt-chip", text: t, type: "button" }); b.addEventListener("click", () => pick(mode)); addG.append(b); });
chips.append(addG);
EXAMPLES.forEach(([label, items]) => {
const g = el("div", { class: "prompt-group" }, el("span", { class: "prompt-glabel small muted", text: label }));
items.forEach((t) => { const b = el("button", { class: "prompt-chip", text: t, type: "button" }); b.addEventListener("click", () => { input.value = t; input.focus(); }); g.append(b); });
chips.append(g);
});
const out = el("div", { class: "prompt-out", id: "prompt-out", "aria-live": "polite", hidden: "" });
const body = el("div", { class: "prompt-body" }, el("div", { class: "prompt-inner" }, field, menu, chips, out,
el("p", { class: "small muted prompt-note", text: "This box cannot approve a job, arm anything or start a robot or drone." })));
const bar = el("section", { class: "prompt-bar", id: "prompt-bar", "aria-label": "Instruction" }, head, body);
const anchor = $(".toolbar");
anchor.parentNode.insertBefore(bar, anchor);
const setOpen = (open, remember = true) => { bar.classList.toggle("collapsed", !open); head.setAttribute("aria-expanded", open ? "true" : "false"); body.inert = !open; if (remember) store.set("pv-prompt-open", open ? "1" : "0"); };
head.addEventListener("click", () => setOpen(bar.classList.contains("collapsed")));
setOpen(store.get("pv-prompt-open") !== "0", false);
go.addEventListener("click", ask);
clip.addEventListener("click", (e) => { e.stopPropagation(); menu.hidden ? openMenu() : closeMenu(); });
document.addEventListener("click", (e) => { if (!menu.hidden && !menu.contains(e.target)) closeMenu(); });
bar.addEventListener("keydown", (e) => { if (e.key === "Escape" && !menu.hidden) { closeMenu(); clip.focus(); e.stopPropagation(); } });
// drop files anywhere on the box, or paste an image into the field
let depth = 0;
bar.addEventListener("dragenter", (e) => { if (hasFiles(e)) { e.preventDefault(); depth++; bar.classList.add("dropping"); } });
bar.addEventListener("dragover", (e) => { if (hasFiles(e)) e.preventDefault(); });
bar.addEventListener("dragleave", () => { depth = Math.max(0, depth - 1); if (!depth) bar.classList.remove("dropping"); });
bar.addEventListener("drop", (e) => { if (!hasFiles(e)) return; e.preventDefault(); depth = 0; bar.classList.remove("dropping"); offer(Array.from(e.dataTransfer.files)); });
input.addEventListener("paste", (e) => { const f = Array.from((e.clipboardData && e.clipboardData.files) || []); if (f.length) { e.preventDefault(); offer(f); } });
input.addEventListener("input", () => chips.classList.toggle("tucked", input.value.length > 0));
input.addEventListener("keydown", (e) => {
if (e.key === "Enter") { e.preventDefault(); ask(); }
else if (e.key === "Escape") { if (input.value) input.value = ""; else { $("#prompt-out").hidden = true; proposed = []; input.blur(); } chips.classList.remove("tucked"); }
else if (e.key === "ArrowUp" && history.length) { e.preventDefault(); hpos = Math.min(hpos + 1, history.length - 1); input.value = history[hpos]; }
else if (e.key === "ArrowDown" && hpos >= 0) { e.preventDefault(); hpos -= 1; input.value = hpos >= 0 ? history[hpos] : ""; }
});
document.addEventListener("keydown", (e) => { // "/" jumps to the box from anywhere that is not a field
if (e.key !== "/" || e.metaKey || e.ctrlKey || /INPUT|TEXTAREA|SELECT/.test((e.target || {}).tagName || "")) return;
e.preventDefault(); if (bar.classList.contains("collapsed")) setOpen(true); input.focus();
});
}
const hasFiles = (e) => e.dataTransfer && Array.from(e.dataTransfer.types || []).includes("Files");
const openMenu = () => { $("#prompt-menu").hidden = false; $("#prompt-attach").setAttribute("aria-expanded", "true"); const f = $("#prompt-menu .prompt-menu-item"); if (f) f.focus(); };
const closeMenu = () => { const m = $("#prompt-menu"); if (m) m.hidden = true; const c = $("#prompt-attach"); if (c) c.setAttribute("aria-expanded", "false"); };
function reply(text, kind, extra) {
const out = $("#prompt-out");
out.hidden = false; out.textContent = ""; proposed = [];
out.append(el("p", { class: `prompt-reply${kind === "refused" ? " refused" : ""}`, text }));
if (extra) out.append(extra);
}
// Open the right file picker. Photos and videos for the open job are extra evidence; with no job open they start one.
function pick(mode) {
const j = getJob();
if (mode === "view" && !j) mode = "job";
if ((mode === "drawing") && !j) { reply("Open or create a job first: a drawing belongs to a wall.", "refused"); return; }
const sel = (ATTACH.find((a) => a[0] === mode) || [])[3]; const input = sel && $(sel);
if (!input) { say("That picker is not available on this page."); return; }
input.click();
}
// Hand dropped or pasted files to the console's own inputs, sorted by what they are.
function route(files, mode) {
const img = files.filter((f) => /^image\//.test(f.type)), vid = files.filter((f) => /^video\//.test(f.type)), doc = files.filter((f) => f.type === "application/pdf" || /\.pdf$/i.test(f.name));
const send = (sel, list, what) => {
const input = $(sel); if (!input || !list.length) return false;
const dt = new DataTransfer(); list.slice(0, 1).forEach((f) => dt.items.add(f)); // the console's pickers take one file at a time
input.files = dt.files; input.dispatchEvent(new Event("change", { bubbles: true })); return what;
};
const did = [];
if (doc.length || (mode === "drawing" && img.length)) { const w = send("#dfile", doc.length ? doc : img, "drawing"); if (w) did.push(w); }
else if (vid.length) { const w = send(mode === "job" ? "#vfile" : "#ev-view-file", vid, mode === "job" ? "new job from video" : "view of this wall"); if (w) did.push(w); }
else if (img.length) { const w = send(mode === "job" ? "#file" : "#ev-view-file", img, mode === "job" ? "new job" : "view of this wall"); if (w) did.push(w); }
const extra = files.length - 1;
reply(did.length ? `Added ${files[0].name} (${did[0]}).` + (extra > 0 && !doc.length ? ` Only one file is taken at a time: drop the other ${extra} again after this one finishes.` : "")
: "I can use photos, videos and PDF drawings. That file is none of those.", did.length ? "" : "refused");
}
// After a drop: if a job is open, ask once whether this is another view of it or a new wall.
function offer(files) {
if (!files.length) return;
const j = getJob(), kinds = files.map((f) => (/^image\//.test(f.type) ? "photo" : /^video\//.test(f.type) ? "video" : /pdf/.test(f.type) ? "drawing" : "file"));
if (kinds[0] === "drawing") { route(files, "drawing"); return; }
if (!j) { route(files, "job"); return; }
const row = el("div", { class: "row prompt-offer" });
const a = el("button", { class: "primary", type: "button", text: "Another view of this wall" }), b = el("button", { class: "ghost", type: "button", text: "A new job" });
a.addEventListener("click", () => route(files, "view")); b.addEventListener("click", () => route(files, "job"));
row.append(a, b);
reply(`What is ${files.length === 1 ? "this " + kinds[0] : files.length + " files"}?`, "", row);
}
async function ask() {
const j = getJob(), input = $("#prompt-input"), text = input.value.trim();
if (!text || busy) return;
const m = INTENT.exec(text);
if (m) { // "add a photo", "upload a video", "use this drawing": open the picker instead of sending it to the planner
const w = m[2].toLowerCase(), mode = /video|clip|footage/.test(w) ? (j ? "view" : "video") : /drawing|plan|pdf|elevation/.test(w) ? "drawing" : (j ? "view" : "job");
history = [text, ...history.filter((h) => h !== text)].slice(0, HISTORY_MAX); hpos = -1; input.value = "";
reply(mode === "drawing" ? "Choose the drawing (PDF, PNG or JPG)." : mode === "view" ? "Choose a photo or video of this wall." : "Choose a file to start a new job.");
pick(mode); return;
}
if (!j) { say("Open or create a job first."); return; }
busy = true; $("#prompt-go").disabled = true;
history = [text, ...history.filter((h) => h !== text)].slice(0, HISTORY_MAX); hpos = -1;
const out = $("#prompt-out");
out.hidden = false; out.textContent = "";
out.append(el("p", { class: "prompt-you", text: text }), el("p", { class: "prompt-think", text: "Thinking" }));
try { const plan = await api(`/api/jobs/${j.id}/prompt`, { text }); input.value = ""; $("#prompt-chips").classList.remove("tucked"); show(plan, text); }
catch (e) { out.hidden = true; say(e.message || e); } finally { busy = false; $("#prompt-go").disabled = false; }
}
function show(plan, asked) {
const out = $("#prompt-out");
out.hidden = false; out.textContent = "";
proposed = plan.actions || [];
if (asked) out.append(el("p", { class: "prompt-you", text: asked }));
out.append(el("p", { class: `prompt-reply${plan.refused ? " refused" : ""}`, text: plan.reply }));
if (plan.parser === "ai") out.append(el("p", { class: "small muted", text: "Translated by the AI helper (advisory); the same checks apply." }));
if (proposed.length) {
const list = el("ol", { class: "prompt-actions" });
const countApply = () => { const n = list.querySelectorAll("input:checked").length; apply.textContent = proposed.length === 1 ? "Apply" : `Apply ${n}`; apply.disabled = !n; };
proposed.forEach((a, i) => {
const cb = el("input", { type: "checkbox", checked: "", "aria-label": `Include: ${LABEL[a.type] || a.type}`, "data-i": String(i) });
cb.addEventListener("change", () => countApply());
list.append(el("li", {}, el("label", {}, cb, el("span", { class: "prompt-act" }, el("b", { text: LABEL[a.type] || a.type }), el("span", { class: "small muted", text: " " + (a.why || "") })))));
});
const apply = el("button", { class: "primary", id: "prompt-apply", text: proposed.length === 1 ? "Apply" : `Apply ${proposed.length}` });
apply.addEventListener("click", applyNow);
const drop = el("button", { class: "ghost", text: "Discard" });
drop.addEventListener("click", () => { out.hidden = true; proposed = []; });
out.append(list, el("div", { class: "row" }, apply, drop));
if (proposed.length === 1) list.querySelector("input").hidden = true; // one action: nothing to choose
}
}
const LABEL = { zone: "Zone", clear_zones: "Clear zones", set_height: "Wall height", layer: "Layer", replan: "Re-plan", twin: "Digital twin", drawing: "Drawing" };
async function applyNow() {
const j = getJob(); if (!j || !proposed.length) return;
const picked = proposed.filter((_, i) => { const cb = document.querySelector(`#prompt-out input[data-i="${i}"]`); return !cb || cb.checked; });
if (!picked.length) return;
$("#prompt-apply").disabled = true;
try {
const res = await api(`/api/jobs/${j.id}/prompt/apply`, { actions: picked });
const out = $("#prompt-out");
out.textContent = "";
res.results.forEach((r) => out.append(el("p", { class: `prompt-result ${r.ok ? "ok" : "bad"}`, text: `${r.ok ? "✓" : "✗"} ${r.detail}` })));
let reload = res.results.some((r) => r.ok && /zone|height|drawing/.test(r.type));
for (const c of res.client_actions || []) {
if (c.type === "layer") { const cb = $(`#layer-toggles input[data-layer="${c.name}"]`); if (cb && cb.checked !== c.on) cb.click(); }
if (c.type === "replan") { const b = $("#replan"); if (b && !b.disabled) b.click(); else say("Nothing to re-plan yet: change something first.", "warn"); }
}
proposed = [];
if (reload && typeof openJob === "function") await openJob(j.id);
} catch (e) { say(e.message || e); }
}
function init() { if ($(".toolbar")) build(); }
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init); else init();
window.PVPrompt = { ask, show };
})();