// Read-only observer: only server-rendered goalHtml is trusted HTML. const token = location.hash.slice(1); const $ = (id) => document.getElementById(id); function el(tag, className, text) { const node = document.createElement(tag); if (className) node.className = className; if (text !== undefined) node.textContent = String(text); return node; } function clock(ms) { return new Date(ms).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", }); } function seconds(ms) { return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(1)}s`; } function duration(ms) { const minutes = Math.round(ms / 60000); return minutes < 60 ? `${minutes}m` : `${Math.floor(minutes / 60)}h ${minutes % 60}m`; } function shortId(id) { return id.slice(0, 8); } function budget(label, used, limit) { const node = el("span", "budget", `${label} `); node.append(el("b", "", limit === null ? `${used}` : `${used}/${limit}`)); return node; } function renderRun(run) { $("run").hidden = false; const status = $("status"); status.className = `status st-${run.status}`; status.textContent = `${run.status === "paused" || run.status === "stopped" ? "■" : "●"} ${run.status.toUpperCase()}`; $("run-id").textContent = `run ${shortId(run.id)}`; $("attempt").textContent = `attempt ${run.attempts}`; $("turn").textContent = `turn ${run.turns}`; const goal = $("goal"); // Avoid replacing selected text on gate-output ticks; never insert raw goal HTML. if (goal.dataset.source !== run.goal) { if (typeof run.goalHtml === "string") goal.innerHTML = run.goalHtml; else goal.textContent = run.goal; goal.dataset.source = run.goal; } const banner = $("banner"); banner.replaceChildren(); banner.hidden = true; if (run.status === "succeeded") { banner.hidden = false; banner.className = "banner ok"; const text = el("span"); text.append( el("span", "big", "All gates exited 0 · run complete"), `${run.attempts} attempts · ${run.turns} turns · ${duration(run.updatedAt - run.createdAt)} · goal met by configured gates`, ); banner.append(text); } else if (run.status === "paused" || run.status === "stopped") { banner.hidden = false; banner.className = "banner pause"; const text = el("span"); text.append( el( "span", "big", `${run.status === "paused" ? "Paused" : "Stopped"} · ${run.reason}`, ), run.status === "paused" ? "Resume re-arms the loop; the time budget restarts on resume" : "Stopped runs cannot resume", ); banner.append(text); if (run.status === "paused") { // The site never controls Pi; it hands the user the command to run there. const command = `/loop resume ${shortId(run.id)}`; const button = el("button", "resume", `⏵ copy ${command}`); button.type = "button"; button.title = "Copy the resume command, then run it in Pi"; button.addEventListener("click", async () => { try { await navigator.clipboard.writeText(command); button.textContent = "✓ copied, run it in Pi"; } catch { button.textContent = command; } }); banner.append(button); } } const budgets = $("budgets"); budgets.replaceChildren(); if (run.deadline !== null && run.status === "active") { const left = el("span", "budget", "time "); left.append( el("b", "", `${duration(Math.max(0, run.deadline - Date.now()))} left`), ); budgets.append(left); } else if (run.budgets.minutes !== null) { budgets.append(budget("time", `${run.budgets.minutes}m`, null)); } budgets.append( budget("turns", run.turns, run.budgets.turns), budget("attempts", run.attempts, run.budgets.attempts), ); const gates = $("gates"); gates.replaceChildren(); const pass = run.lastPass; run.gates.forEach((gate, index) => { const result = pass?.results[index]; const ok = result && result.exitCode === 0 && result.error === null; const running = run.runningGate === index; const node = el( "div", `gate${running ? " running" : result ? (ok ? " pass" : " fail") : ""}`, ); node.dataset.gate = gate.label; const row = el("div", "row"); row.append( el("span", "dot"), el("span", "", gate.label), el("span", "command mono", gate.command), ); const code = running ? `running · ${seconds(Math.max(0, Date.now() - (run.runningSince ?? Date.now())))}` : result ? `exit ${result.exitCode ?? "none"} · ${seconds(result.durationMs)}` : "not run"; row.append(el("span", "code mono", code)); node.append(row); if (running && run.liveOutput) { const pre = el("pre", "live-output"); if (run.liveOutput.stderr) pre.append(el("span", "err", run.liveOutput.stderr)); if (run.liveOutput.stdout) pre.append(run.liveOutput.stdout); node.append( el( "div", "mono", `Live output${run.liveOutput.truncated ? " (bounded tail)" : ""}`, ), pre, ); } else if (!running && result && !ok) { const drawer = el("details"); drawer.open = true; drawer.append( el( "summary", "", `exit ${result.exitCode ?? "none"} · attempt ${pass.attempt} · ${clock(result.endedAt)} · output${result.truncated ? " (tail)" : ""}`, ), ); const pre = el("pre"); if (result.error) pre.append(el("span", "err", `${result.error}\n`)); if (result.stderr) pre.append(el("span", "err", result.stderr)); if (result.stdout) pre.append(result.stdout); if (!pre.textContent) pre.textContent = "(no output)"; drawer.append(pre); node.append(drawer); } gates.append(node); }); } function renderTimeline(run, timeline) { const section = $("timeline"); section.hidden = timeline.length === 0; const track = $("track"); track.replaceChildren(el("div", "axis")); const start = run.createdAt; const end = Math.max(Date.now(), timeline.at(-1)?.at ?? start, start + 1); timeline.forEach((mark, index) => { const node = el( "div", `mark ${mark.kind}${index === timeline.length - 1 ? " latest" : ""}`, ); node.tabIndex = 0; node.style.left = `${2 + ((mark.at - start) / (end - start)) * 96}%`; const text = mark.kind === "turn" ? `turn ${mark.n} · ${clock(mark.at)}` : mark.kind === "pass" ? `attempt ${mark.n} · all gates passed` : `attempt ${mark.n} · ${mark.label} exit ${mark.exitCode ?? "none"}`; node.setAttribute("aria-label", text); node.append(el("span", "tip", text)); track.append(node); }); } function renderEvents(events) { $("events").hidden = events.length === 0; $("feed").replaceChildren( ...events.map((event) => { const row = el("div", "ev"); const time = el("time", "mono", clock(event.at)); time.dateTime = new Date(event.at).toISOString(); row.append( time, el("span", "k", event.kind), el("span", "", event.summary), ); return row; }), ); } function renderHistory(history) { const details = $("history"); details.hidden = history.length === 0; $("history-title").textContent = `Run history · ${history.length} run${history.length === 1 ? "" : "s"}`; $("history-rows").replaceChildren( ...history.map((run) => { const row = el("div", "hrow"); row.append( el("span", "mono", shortId(run.id)), el("span", `st-${run.status}`, run.status), el("span", "", run.goal), el( "span", "", `${run.attempts} attempts · ${duration(run.updatedAt - run.createdAt)}`, ), ); return row; }), ); } let currentRun; setInterval(() => { if (currentRun?.status !== "active" || currentRun.runningGate == null) return; const code = document.querySelector(".gate.running .code"); if (code) code.textContent = `running · ${seconds(Math.max(0, Date.now() - (currentRun.runningSince ?? Date.now())))}`; }, 1000); function render(snapshot) { if (snapshot.error) return; currentRun = snapshot.run; $("empty").hidden = snapshot.run !== null; if (!snapshot.run) return; renderRun(snapshot.run); renderTimeline(snapshot.run, snapshot.timeline); renderEvents(snapshot.events); renderHistory(snapshot.history); } function connect() { const conn = $("conn"); if (!token) { conn.textContent = "○ missing token: open the link from /loop view"; return; } const source = new EventSource(`/events?token=${encodeURIComponent(token)}`); source.addEventListener("open", () => { conn.className = "conn ok mono"; conn.textContent = "● live"; }); source.addEventListener("snapshot", (event) => render(JSON.parse(event.data)), ); source.addEventListener("error", () => { conn.className = "conn mono"; conn.textContent = "○ reconnecting"; }); } connect();