Skip to content

armgit / moss

Public Imported from GitHub
0

MOSS: a small, mostly 3D-printed litter-picking rover. Cleaner streets, one maker at a time.

Python
69.5 KB
Raw Blame
/* MOSS cockpit page.
 *
 * Talks only to the server that served it (relative paths, no other host: the
 * field has no internet). Contract: tools/moss_cockpit.py.
 *
 *   GET  /state.json  1 Hz        GET /scan.json  3 Hz      GET /path.json 1 Hz
 *   (both state and scan carry the pose: the robot marker takes the younger one, 3 Hz)
 *   GET  /map_meta    1 Hz, then /map.png only when map_meta.stamp changed
 *   GET  /log.json    0.5 Hz      GET /preflight.json on load and after a check
 *   GET  /decisions.json?n=30  1 Hz  (the stack's decisions read from its log, and the word for now)
 *   GET  /launch.json while a stack command runs (the page's, or one the cockpit runs itself: the idle stop)
 *   POST /cmd/<explore|goal|stop|episode|stack|keepalive>   (keepalive: the idle line, a button)
 *
 * Each poller waits for its answer before scheduling the next one, so a slow
 * Jetson never gets a queue of requests. Pollers sleep while the tab is hidden.
 */
"use strict";

var POLL = { state: 1000, meta: 1000, scan: 333, path: 1000, log: 2000, launch: 1000, decisions: 1000 };
var FETCH_TIMEOUT_MS = 2500;
var TAP_SLOP_PX = 6;          // a pointer that moved less than this is a tap, not a drag
var STALE_S = 3;              // a topic older than this is shown as stale
var LIVE_S = 2;               // telemetry, scan and path older than this are not drawn or read as live
var RELOAD_AFTER_AWAY_MS = 3000;   // the server gone this long = restarted: reload the page when it is back
var EP_FULL_S = 300;          // the bottom progress line is full after 5 min of episode
var RUN_FULL_S = 1800;        // ... or after 30 min of run when no episode records
var CAM_RETRY_MS = 3000;      // reconnect the MJPEG stream this long after it ended or failed, forever
var CAM_GRACE_MS = 6000;      // a stream younger than this is not judged dead (first frame wait + a state poll)
var STALL_HOLD_S = 4;         // the STALLED badge stays up at least this long after the stall count goes up
var DEPTH_COLOR = "rgba(255,193,94,.95)";   // amber: depth-camera obstacles, apart from the mint lidar scan
var DECISION_ROWS = 30;       // the decision feed shows this many, newest on top
var IDLE_WARN_S = 60;         // the idle line under the chip turns to the warning colour this close to the stop
// The commanded-motion arrow at the robot: the path a constant (vx, wz) drives in CMD_ARROW_S,
// so 0.45 m/s is 0.6 m on the map, drawn from the marker's edge (its nose, its tail in reverse)
// and never shorter on screen than CMD_MIN_RUN; a pivot is an arc around the robot sweeping the
// turn of PIVOT_ARROW_S, between PIVOT_MIN_RAD and PIVOT_MAX_RAD.
var CMD_ARROW_S = 0.6 / 0.45;
var PIVOT_ARROW_S = 3;
var PIVOT_MIN_RAD = Math.PI / 4, PIVOT_MAX_RAD = 1.5 * Math.PI;
var CMD_VX_EPS = 0.02;        // m/s: slower than this the command does not translate (a pivot, or nothing)
var CMD_WZ_EPS = 0.02;        // rad/s: slower than this the command does not turn
var PIVOT_RADIUS_M = 0.1;     // a turn about a centre this close (under the robot) is drawn as a pivot
var CMD_STEPS = 16;           // segments of a drawn path
var CMD_W = 4;                // px: the arrow's line, thicker than the 2.25 px path
var CMD_HEAD = 10;            // px: arrowhead length (its half width is 0.5 of it)
var CMD_MIN_RUN = 22;         // px past the marker's edge, at least: the head and 12 px of line. At the
                              // fitted zoom (~37 px/m) 0.2 m/s is 10 px of map, which the marker would hide
var PIVOT_R_PX = 17;          // px: the pivot arc's radius, just outside the robot marker
var MARK_L = 15, MARK_B = 8;  // px: the robot marker's length and half width; nose .62 L ahead, tail .38 L behind
var MINT = "#6CF8C7";
var HALO = "#080F1A";         // navy (--moss-navy) outline round the arrow: it reads over white walls, and
                              // over the mint path (2.25 px, no outline) it is a separate, outlined shape

var S = {
  online: false, state: null,
  meta: null, mapImg: null, mapStamp: null, scan: null, scanAt: 0, path: null,
  preflight: null, launchBusy: false, launchAction: null,
  view: { scale: 40, x: -3, y: 3 }, fitted: false,
  pendingGoal: null, camPaused: false, camOk: false, camAt: 0, camLost: null, pfAll: false,
  stateAt: 0, stallLatch: { count: null, until: 0 },
  decisions: null, decHtml: null, decKeys: null,
  ui: "advanced", simpleCam: "nose", say: null, lastLog: null,   // the Simple view: which view, its camera, its status line
  noteTs: undefined             // the launcher note last seen (undefined: no state yet)
};

function $(id) { return document.getElementById(id); }

// ---------------------------------------------------------------- utilities

function fetchJSON(url, opts) {
  var ctl = ("AbortController" in window) ? new AbortController() : null;
  var t = ctl ? setTimeout(function () { ctl.abort(); }, FETCH_TIMEOUT_MS) : null;
  var o = opts || {};
  if (ctl) o.signal = ctl.signal;
  o.cache = "no-store";
  return fetch(url, o).then(function (r) {
    if (t) clearTimeout(t);
    if (r.status === 404) return { __missing: true };
    return r.json().then(function (d) {
      if (!r.ok && d && typeof d === "object" && !("ok" in d)) d.ok = false;
      return d;
    });
  }, function (e) { if (t) clearTimeout(t); throw e; });
}

function post(name, body) {
  return fetchJSON("/cmd/" + name, {
    method: "POST", headers: { "Content-Type": "application/json", "X-Requested-With": "moss-cockpit" },
    body: JSON.stringify(body || {})
  });
}

function poller(fn, period) {
  function tick() {
    if (document.hidden) { setTimeout(tick, period); return; }
    var p;
    try { p = fn(); } catch (e) { p = null; }
    Promise.resolve(p).catch(function () {}).then(function () { setTimeout(tick, period); });
  }
  tick();
}

function num(v, d) { return (typeof v === "number" && isFinite(v)) ? v.toFixed(d) : "--"; }
function signed(v, d) { return (typeof v === "number" && isFinite(v)) ? ((v >= 0 ? "+" : "") + v.toFixed(d)) : "--"; }
function pad2(n) { return (n < 10 ? "0" : "") + n; }
function clock(s) {
  if (typeof s !== "number" || !isFinite(s) || s < 0) return "--:--";
  s = Math.floor(s);
  var h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
  return (h ? h + ":" + pad2(m) : m) + ":" + pad2(sec);
}
function span(s) {               // long durations (machine uptime): days and hours read better than 254:08:52
  if (typeof s !== "number" || !isFinite(s) || s < 0) return "--";
  if (s < 86400) return clock(s);
  return Math.floor(s / 86400) + " d " + Math.floor((s % 86400) / 3600) + " h";
}
function dur(s) {
  if (typeof s !== "number" || !isFinite(s)) return "--";
  if (s < 90) return Math.round(s) + " s";
  if (s < 5400) return Math.round(s / 60) + " min";
  return Math.round(s / 3600) + " h";
}
function ago(s) {
  if (typeof s !== "number" || !isFinite(s)) return "--";
  return s < 1 ? "now" : dur(s) + " ago";
}
function setText(id, t) { var el = $(id); if (el && el.textContent !== t) el.textContent = t; }
function meter(id, frac, attn) {
  var el = $(id); if (!el) return;
  var f = (typeof frac === "number" && isFinite(frac)) ? Math.max(0, Math.min(1, frac)) : 0;
  el.firstElementChild.style.width = (f * 100).toFixed(1) + "%";
  el.classList.toggle("attn", !!attn);
}

var sayTimer = null;
function say(text, bad) {
  var el = $("say");
  el.textContent = text;
  el.className = bad ? "err" : "ok";
  S.say = { text: text, bad: !!bad, at: Date.now() }; renderSimpleLog();
  clearTimeout(sayTimer);
  // a success line fades after a while; an error stays until the next action
  if (!bad) sayTimer = setTimeout(function () { if (el.textContent === text) el.textContent = ""; }, 8000);
}

function answer(d, okText) {
  if (d && d.ok) { say(okText || ("Sent on " + (d.sent || "the bus") + "."), false); return true; }
  say((d && d.error) ? d.error : "The cockpit refused the command.", true);
  return false;
}

// ---------------------------------------------------------------- state

function stack() { return (S.state && S.state.stack) || { running: false }; }
function blueprint() { var b = stack().blueprint || ""; return String(b); }
function isExploreStack() { return stack().running && /explore/.test(blueprint()); }
function isDemo() { return !!(S.state && S.state.mode === "demo"); }
function canGoal() { return S.online && (isExploreStack() || isDemo()); }
function exploring() { return !!(S.state && S.state.nav && S.state.nav.exploring); }

// seconds since the last state the cockpit answered: the server's ages froze then
function offlineFor() { return S.online || !S.stateAt ? 0 : Math.max(0, (Date.now() - S.stateAt) / 1000); }

// seconds since the last state answer, online or not: what to add to an age the state carries
function sinceState() { return S.stateAt ? Math.max(0, (Date.now() - S.stateAt) / 1000) : 0; }

// a bus topic's age as the server measured it now, or null when it is silent or unknown
function topicAge(name) {
  var t = S.state && S.state.topics && S.state.topics[name];
  return t && typeof t.age_s === "number" ? t.age_s + offlineFor() : null;
}

function pollState() {
  return fetchJSON("/state.json").then(function (d) {
    if (!d || d.__missing) throw new Error("no state");
    var wasOffline = !S.online && S.stateAt > 0;
    // the cockpit server was away long enough to have been restarted (a deploy): the page
    // reloads itself, so a window left open never shows a stale or blank page; a short blip
    // only reconnects the camera stream
    if (wasOffline && S.offlineSince && Date.now() - S.offlineSince > RELOAD_AFTER_AWAY_MS) { location.reload(); return; }
    S.state = d; S.online = true; S.stateAt = Date.now(); S.offlineSince = 0;
    if (wasOffline) camRestart("Cockpit back. Reconnecting the stream.");   // its stream died with it
    followLaunch(d.launch, d.stack);
    render();
  }, function () {
    if (S.online || !S.offlineSince) S.offlineSince = Date.now();
    S.online = false;
    render();
  });
}

function render() {
  document.body.classList.toggle("offline", !S.online);
  renderHeader();
  renderIdle();
  renderBase();
  renderSystem();
  renderControls();
  renderCaption();
  renderCamera();
  renderPreflightWhen();
  requestDraw();
}

function renderHeader() {
  var st = stack(), chip = $("chip"), cls, label;
  if (!S.online) { cls = "off"; label = "OFFLINE"; }
  else if (st.running && exploring()) { cls = "on"; label = "EXPLORING"; }
  else if (st.running) { cls = "on"; label = "MAPPING"; }
  else { cls = "idle"; label = "IDLE"; }
  chip.className = "chip " + cls;
  setText("chip", label);
  var name = st.running ? (st.run_id || st.blueprint || "stack") : "no stack";
  if (isDemo()) name += "  ·  demo data";
  setText("run-name", name);
}

// The idle stop (/state.json "idle"): how long the stack has seen no activity and when the
// cockpit stops it, one line under the chip: {text, cls, keep}, or null to hide it (no stack the
// stop applies to, the rule off, a cockpit that cannot see the bus). Dim until half the limit,
// plain after, the warning colour in the last IDLE_WARN_S seconds. The line is a button: `keep`
// while a press can still keep the stack up.
function idleView(idle, st) {
  if (!st || !st.running || !idle || !idle.enabled) return null;
  var i = idle.idle_s, left = idle.stop_in_s, lim = idle.limit_s;
  if (typeof i !== "number" || typeof left !== "number" || typeof lim !== "number") return null;
  var cls = left < IDLE_WARN_S ? "attn" : i < lim / 2 ? "dim" : "";
  if (left <= 0) return { text: "idle " + clock(i) + ": stopping the stack to preserve battery", cls: cls, keep: false };
  return { text: "idle " + clock(i) + ", stops at " + clock(lim) + " to preserve battery  ·  keep the stack up",
           cls: cls, keep: true };
}

function renderIdle() {
  var v = idleView(S.state && S.state.idle, stack()), el = $("idle-note");
  el.hidden = !v;
  if (!v) return;
  setText("idle-note", v.text);
  el.className = ("num " + v.cls).trim();
  el.disabled = !v.keep || !S.online;
}

// A press on the idle line: the cockpit's count starts again (POST /cmd/keepalive) and the line
// shows it at once, from the "idle" the answer carries.
function keepUp() {
  return post("keepalive", {}).then(function (d) {
    if (!answer(d, "Idle count restarted: the stack stays up.")) return;
    if (S.state && d.idle) { S.state.idle = d.idle; renderIdle(); }
  }, function () { say("The cockpit did not answer.", true); });
}

// "14:05" from epoch seconds, this browser's clock
function hhmm(ts) { var d = new Date(ts * 1000); return pad2(d.getHours()) + ":" + pad2(d.getMinutes()); }

// A stack command the page did not send (the cockpit's own idle stop, another page's launch):
// its lines go to the stack tail like the page's own, and the cockpit's note (why it ran) goes
// to the status line with its time ("..., stopped at 14:05"), where it stays until the next action.
// On the first state a note is said only when no stack runs: then it is why the stack is down, not
// news about a later stack. The cockpit keeps the note in memory: a restarted cockpit has none.
function followLaunch(l, st) {
  var n = l && l.note, key = n && n.text ? n.ts : null;
  var said = key !== null && key !== S.noteTs && (S.noteTs !== undefined || !(st && st.running));
  if (said) say(String(n.text) + (typeof n.ts === "number" && isFinite(n.ts) ? ", stopped at " + hhmm(n.ts) : ""), true);
  S.noteTs = key;
  if (l && l.running) S.launchBusy = true;
  if (said || (l && l.running)) watchLaunch();
}

function modeName(b) {
  if (b.mode_name) return b.mode_name;
  return ({ 0: "off", 1: "ready", 2: "drive", 3: "test" })[b.mode] || "--";
}

function setTrack(barId, valId, v) {
  var bar = $(barId);
  var p = (typeof v === "number" && isFinite(v)) ? Math.max(-100, Math.min(100, v)) : 0;
  var h = Math.abs(p) / 2;                      // 100 % fills half the bar
  bar.style.height = h + "%";
  bar.style.bottom = p >= 0 ? "50%" : (50 - h) + "%";
  bar.classList.toggle("rev", p < 0);
  setText(valId, (typeof v === "number") ? String(Math.round(v)) : "--");
}

// The base's stall guard (a commanded track whose encoder did not move for 1 s stops it) sets
// `stalled` and adds one to `stall_count`. The base clears `stalled` on its next accepted
// command, which can come before the page's 1 Hz read of the 2 Hz telemetry, so the badge is
// latched on the counter: when stall_count goes up, the badge holds STALL_HOLD_S from the
// moment the page sees it, whatever `stalled` says. latch = {count, until}: the last count
// seen and the page time (ms) the hold ends. The first count the page sees, and a count that
// went down (a new run), only set the reference, with no hold. A missing count (no telemetry,
// or telemetry from before the guard) keeps the last one, so a stall across a gap still holds.
function stallLatch(latch, count, nowMs) {
  var last = latch ? latch.count : null, until = latch ? latch.until : 0;
  if (typeof count !== "number" || !isFinite(count)) return { count: last, until: until };
  if (typeof last === "number" && count > last) until = nowMs + STALL_HOLD_S * 1000;
  return { count: count, until: until };
}

// The STALLED badge shows while `stalled` is true or the latch holds (holdUntil, page ms);
// the row counts the stalls of the run. Telemetry from before the guard carries neither key:
// no badge, "--".
function stallView(b, holdUntil, nowMs) {
  return { badge: (!!b && b.stalled === true) || nowMs < holdUntil,
           count: b && typeof b.stall_count === "number" && isFinite(b.stall_count) ? String(b.stall_count) : "--" };
}

function renderBase() {
  var b = S.state && S.state.base;
  var sec = $("mod-base");
  var now = Date.now();
  S.stallLatch = stallLatch(S.stallLatch, b ? b.stall_count : null, now);
  var stall = stallView(b, S.stallLatch.until, now);
  $("b-stall").hidden = !stall.badge;
  setText("b-stalls", stall.count);
  if (!b) {
    setText("base-title", S.online ? "No telemetry." : "Cockpit offline.");
    setText("b-volt", "--"); setText("b-pct", "--"); meter("b-meter", 0);
    setTrack("t-l", "t-lv", null); setTrack("t-r", "t-rv", null);
    ["b-mode", "b-ticks", "b-fw", "b-age"].forEach(function (id) { setText(id, "--"); });
    setText("t-target", "target -- / --");
    return;
  }
  var low = typeof b.battery_v === "number" && b.battery_v < 10.8;
  // age of the data = time since the cockpit got the message + its age when it was sent
  var age = (typeof b.age_s === "number" ? b.age_s : 0) + (typeof b.firmware_age_s === "number" ? b.firmware_age_s : 0)
            + offlineFor();
  var stale = age > LIVE_S;
  var title;
  if (stale) title = "No telemetry for " + dur(age) + ".";
  else if (b.ina_ok === false) title = "Battery sensor not seen.";
  else if (low) title = "Battery low. Land it.";
  else if (b.mode === 2) title = "Driving.";
  else if (b.mode === 1) title = "Armed, ready.";
  else title = "Disarmed.";
  if (b.mock && !stale) title = "Fake firmware. " + title;
  setText("base-title", title);
  $("base-title").classList.toggle("attn", stale || low || b.ina_ok === false);
  setText("b-volt", num(b.battery_v, 2));
  setText("b-pct", typeof b.battery_pct === "number" ? String(Math.round(b.battery_pct)) : "--");
  $("b-volt").parentNode.classList.toggle("attn", low);
  meter("b-meter", (b.battery_pct || 0) / 100, low);
  var o = b.output_pct || [], t = b.target_pct || [];
  setTrack("t-l", "t-lv", o[0]); setTrack("t-r", "t-rv", o[1]);
  setText("t-target", "target " + (t.length ? Math.round(t[0]) + " / " + Math.round(t[1]) : "-- / --"));
  setText("b-mode", modeName(b) + (b.reason && b.reason !== modeName(b) ? "  ·  " + b.reason : ""));
  setText("b-ticks", b.ticks ? b.ticks[0] + " / " + b.ticks[1] : "--");
  setText("b-fw", (b.fw || "--") + (b.driver ? "  ·  " + b.driver : ""));
  setText("b-age", stale ? "stale  ·  " + ago(age) : ago(age));
  sec.classList.toggle("stale", stale);
}

var TOPIC_ORDER = ["odom", "lidar", "global_costmap", "path", "cmd_vel", "base_telemetry", "color_image", "wrist_image"];

function renderSystem() {
  var s = S.state && S.state.system;
  if (s) {
    setText("s-cpu", num(s.cpu_percent, 0) + " %");
    setText("s-ram", num(s.ram_used_gb, 1) + " / " + num(s.ram_total_gb, 1) + " GB");
    var tp = s.temps || {}, parts = [];
    if (typeof tp.cpu === "number") parts.push("CPU " + tp.cpu.toFixed(0) + "°");
    if (typeof tp.gpu === "number") parts.push("GPU " + tp.gpu.toFixed(0) + "°");
    setText("s-temp", parts.length ? parts.join("  ·  ") : "--");
    setText("s-load", num(s.load_1m, 2));
    setText("s-up", span(s.uptime_s));
    meter("s-cpu-m", (s.cpu_percent || 0) / 100, s.cpu_percent > 90);
    meter("s-ram-m", (s.ram_percent || 0) / 100, s.ram_percent > 90);
    var dl = $("s-disks"), html = "";
    (s.disks || []).forEach(function (d) {
      html += "<dt>Disk " + esc(d.mountpoint) + "</dt><dd>" + num(d.free_gb, 0) + " GB free</dd>";
    });
    if (dl.innerHTML !== html) dl.innerHTML = html;
    setText("sys-title", s.cpu_percent > 90 || s.ram_percent > 90 ? "Jetson under load." : "Jetson.");
  }
  var topics = (S.state && S.state.topics) || {}, rows = "";
  var names = TOPIC_ORDER.filter(function (n) { return n in topics; });
  Object.keys(topics).forEach(function (n) { if (names.indexOf(n) < 0) names.push(n); });
  names.forEach(function (n) {
    var t = topics[n] || {}, fresh = typeof t.age_s === "number" && t.age_s <= STALE_S;
    rows += '<span class="n">' + esc(n) + '</span><span class="r ' + (fresh ? "" : "dim") + '">'
         + (typeof t.hz === "number" ? t.hz.toFixed(1) + " Hz" : "--") + '</span><span class="r '
         + (fresh ? "" : "attn") + '">' + (typeof t.age_s === "number" ? ago(t.age_s) : "silent") + "</span>";
  });
  if (!names.length) rows = '<span class="n">no topic yet</span><span></span><span></span>';
  if ($("bus").innerHTML !== rows) $("bus").innerHTML = rows;
}

function esc(s) {
  return String(s == null ? "" : s).replace(/[&<>"]/g, function (c) {
    return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c];
  });
}

function renderControls() {
  var st = stack(), on = S.online, busy = S.launchBusy;
  $("b-map").disabled = !on || st.running || busy;
  $("b-explore").disabled = !on || st.running || busy;
  $("b-stack-stop").disabled = !on || (!st.running && !busy);
  var exOk = on && (isExploreStack() || isDemo());
  $("b-ex-start").disabled = !exOk || exploring();
  $("b-ex-stop").disabled = !exOk || !exploring();
  if (!exOk) $("ex-confirm").hidden = true;
  setText("ex-note", exOk ? (exploring() ? "Exploring. A pad stick or Stop exploration takes over."
                                         : "Armed only by this button or EXPLORE=1 moss-fly.sh explore.")
                          : "Needs the explore stack (Launch explore).");
  var rec = (S.state && S.state.recording) || {}, ep = rec.episode;
  var canRec = on && (st.running || isDemo());
  $("b-ep").disabled = !canRec;
  $("b-ep").textContent = ep ? "Stop" : "Start";
  $("b-ep").classList.toggle("primary", !ep && canRec);
  $("ep-name").disabled = !!ep;
  if (ep && document.activeElement !== $("ep-name")) $("ep-name").value = ep.name || "";
  var note;
  if (ep) note = "Recording " + ep.name + "  ·  " + clock(epElapsed(ep));
  else if (rec.exists) note = "Run database " + num(rec.size_mb, 1) + " MB. An episode adds markers to it.";
  else note = "The run records to its database while the stack is up.";
  setText("rec-note", note);
  var title;
  if (!on) title = "Cockpit offline.";
  else if (st.running && exploring()) title = "Exploring on its own.";
  else if (st.running) title = "Stack up. Nothing moves by itself.";
  else title = "Nothing moves by itself.";
  setText("ctl-title", title);
  renderSimple();
}

function epElapsed(ep) {
  if (!ep || ep.started_at == null) return null;
  var t0 = typeof ep.started_at === "number" ? ep.started_at : Date.parse(ep.started_at) / 1000;
  var now = (S.state && S.state.ts) || Date.now() / 1000;
  return isFinite(t0) ? Math.max(0, now - t0) : null;
}

function renderCaption() {
  var st = stack(), nav = (S.state && S.state.nav) || {};
  var bp = (st.blueprint || "none").replace(/^[a-z0-9-]+\./, "");
  setText("cap-kicker", "RUN / " + bp.toUpperCase());
  var mins = st.running && typeof st.uptime_s === "number" ? Math.floor(st.uptime_s / 60) : 0;
  setText("cap-num", pad2(mins));
  var title, sub = "";
  if (!S.online) title = "Cockpit offline. Last values shown.";
  else if (!st.running) title = isDemo() ? "Demo data. Nothing is connected." : "No stack running.";
  else if (exploring()) title = "Exploring on its own.";
  else if (nav.goal && nav.goal_reached !== true) title = "Heading to a goal.";
  else if (/explore/.test(bp)) title = "Mapping. Exploration not armed.";
  else title = "Mapping. Drive with the pad.";
  if (nav.explore_done) sub = "Exploration finished: no frontier left.";
  else if (nav.goal) sub = "Goal " + signed(nav.goal.x, 2) + ", " + signed(nav.goal.y, 2) + " m"
                        + (nav.goal_reached === true ? "  ·  reached" : nav.goal_reached === false ? "  ·  not reached" : "");
  var c = nav.last_cmd_vel;
  if (c && typeof c.age_s === "number" && c.age_s < 2) sub += (sub ? "  ·  " : "") + "cmd " + num(c.vx, 2) + " m/s  " + num(c.wz, 2) + " rad/s";
  setText("cap-title", title);
  setText("cap-sub", sub);
  setText("map-title", S.meta ? (st.running ? "Live costmap." : "Last costmap.") : "Waiting for a map.");
  // the costmap writes nothing until its mission gate opens: explore_cmd, or 5 cm from the boot pose
  setText("map-empty-why", !S.online ? "No map yet. The cockpit is offline."
    : !st.running ? "No map yet. Launch a stack to build one."
    : /explore/.test(bp) ? "No map yet. It opens when exploration starts or the rover moves 5 cm."
    : "No map yet. It opens once the rover has moved 5 cm.");

  var rec = (S.state && S.state.recording) || {}, ep = rec.episode, frac, left, right;
  if (ep) {
    var e = epElapsed(ep) || 0;
    frac = (e % EP_FULL_S) / EP_FULL_S;
    left = "EPISODE / " + String(ep.name || "").toUpperCase();
    right = clock(e);
  } else if (st.running) {
    frac = Math.min(1, (st.uptime_s || 0) / RUN_FULL_S);
    left = "no episode recording";
    right = "run " + clock(st.uptime_s);
  } else { frac = 0; left = "no episode"; right = ""; }
  $("cap-progress").style.width = (frac * 100).toFixed(2) + "%";
  setText("cap-left", left);
  setText("cap-right", right);
}

// ---------------------------------------------------------------- cameras

// Two MJPEG streams under the map: the nose (RealSense colour) and the wrist
// (the arm's camera). Each has its own state; one "Pause video" covers both.
var CAMS = {
  nose:  { img: "cam-img",   ph: "cam-ph",   why: "cam-why",   topic: "color_image", src: "/camera.mjpg?cam=nose" },
  wrist: { img: "wrist-img", ph: "wrist-ph", why: "wrist-why", topic: "wrist_image", src: "/camera.mjpg?cam=wrist" }
};
var camState = {};
Object.keys(CAMS).forEach(function (n) { camState[n] = { ok: false, at: 0, lost: null, timer: null, wasSilent: true }; });

function camSilent(n) {
  var t = S.state && S.state.topics && S.state.topics[CAMS[n].topic];
  return !(t && typeof t.age_s === "number" && t.age_s <= STALE_S);
}

function camConnect(n) {
  var c = CAMS[n], st = camState[n], img = $(c.img);
  if (S.camPaused || document.hidden || !camWanted(n)) { img.removeAttribute("src"); st.ok = false; return; }
  if (!img.getAttribute("src")) { st.at = Date.now(); img.src = c.src + "&t=" + Date.now(); }
}
function camConnectAll() { Object.keys(CAMS).forEach(camConnect); }

// Drop the stream and ask again, with a fresh URL, CAM_RETRY_MS later. An MJPEG
// stream the server closes cleanly fires no error (the browser holds the last
// frame as a finished image), so this also runs when the state says it is gone.
function camRestart(n, why) {
  var st = camState[n];
  $(CAMS[n].img).removeAttribute("src");
  st.ok = false; st.lost = why;
  if (!st.timer) st.timer = setTimeout(function () { st.timer = null; camConnect(n); renderCamera(); }, CAM_RETRY_MS);
}

function camWatch(n) {
  var st = camState[n];
  if (S.camPaused || document.hidden || !S.online || st.timer || !camWanted(n)) return;
  if (!$(CAMS[n].img).getAttribute("src")) { camConnect(n); return; }
  var silent = camSilent(n) && !isDemo();
  if (Date.now() - st.at < CAM_GRACE_MS) { st.wasSilent = silent; return; }
  // the topic is back after a silence (a stack restart): the stream we hold belongs to
  // the old run and may never show a new frame, ask for a fresh one
  if (st.wasSilent && !silent) { st.wasSilent = false; camRestart(n, "The camera is back. Reconnecting."); return; }
  st.wasSilent = silent;
  var cam = S.state && S.state.camera && S.state.camera[n];
  if (cam && cam.clients === 0) camRestart(n, "The stream ended. Reconnecting.");          // the server holds no stream: ours is gone
  else if (st.ok && silent) camRestart(n, "The camera topic went silent. Reconnecting.");
}

function renderCamera() {
  Object.keys(CAMS).forEach(function (n) {
    camWatch(n);
    var st = camState[n], ph = $(CAMS[n].ph), why;
    if (S.camPaused) why = "Video paused in this browser.";
    else if (!S.online) why = "Cockpit offline.";
    else if (!st.ok && st.timer) why = st.lost || "Reconnecting.";
    else if (!st.ok && camSilent(n) && !isDemo() && Date.now() - st.at >= CAM_GRACE_MS) why = "The camera topic is silent. Waiting for frames.";
    else if (!st.ok) why = "Connecting to the stream.";
    else if (camSilent(n) && !isDemo()) why = "The camera topic is silent.";
    ph.hidden = !why;
    if (why) setText(CAMS[n].why, why);
  });
  setText("b-cam", S.camPaused ? "Resume video" : "Pause video");
}

(function () {
  Object.keys(CAMS).forEach(function (n) {
    var img = $(CAMS[n].img), st = camState[n];
    img.addEventListener("load", function () { st.ok = true; st.lost = null; renderCamera(); });
    img.addEventListener("error", function () {
      if (!img.getAttribute("src")) return;              // our own removeAttribute, not a failure
      camRestart(n, "No stream from the cockpit. Retrying every " + CAM_RETRY_MS / 1000 + " s."); renderCamera();
    });
  });
  try { S.camPaused = localStorage.getItem("moss.cockpit.camPaused") === "1"; } catch (e) {}
  $("b-cam").addEventListener("click", function () {
    S.camPaused = !S.camPaused;
    try { localStorage.setItem("moss.cockpit.camPaused", S.camPaused ? "1" : "0"); } catch (e) {}
    camConnectAll(); renderCamera();
  });
  // MJPEG is the heaviest thing the Jetson serves: drop it while nobody looks.
  document.addEventListener("visibilitychange", camConnectAll);
})();

// ---------------------------------------------------------------- map

var cv = $("map"), ctx = cv.getContext("2d"), wrap = $("map-wrap");
var drawQueued = false;

function sx(x) { return (x - S.view.x) * S.view.scale; }
function sy(y) { return (S.view.y - y) * S.view.scale; }
function wx(px) { return S.view.x + px / S.view.scale; }
function wy(py) { return S.view.y - py / S.view.scale; }
function W() { return cv.clientWidth; }
function H() { return cv.clientHeight; }

function resize() {
  var r = window.devicePixelRatio || 1;
  cv.width = Math.max(1, Math.round(W() * r));
  cv.height = Math.max(1, Math.round(H() * r));
  ctx.setTransform(r, 0, 0, r, 0, 0);
  requestDraw();
}

function fitView() {
  var m = S.meta; if (!m) return;
  var w = m.width * m.res, h = m.height * m.res;
  // leave the lower third to the caption: fit into the top 74 % of the pane
  var avH = H() * 0.74, s = Math.min(W() / w, avH / h) * 0.96;
  if (!isFinite(s) || s <= 0) return;
  S.view.scale = s;
  S.view.x = m.ox - (W() / s - w) / 2;
  S.view.y = m.oy + h + (avH / s - h) / 2;
  S.fitted = true;
  requestDraw();
}

function requestDraw() {
  if (drawQueued) return;
  drawQueued = true;
  requestAnimationFrame(function () { drawQueued = false; draw(); });
}

function drawGrid() {
  // 1 m grid, only over the map itself: outside it the pane stays bare studio
  var m = S.meta;
  if (S.view.scale < 14 || !m) return;
  var x0 = Math.ceil(Math.max(wx(0), m.ox)), x1 = Math.floor(Math.min(wx(W()), m.ox + m.width * m.res));
  var y0 = Math.ceil(Math.max(wy(H()), m.oy)), y1 = Math.floor(Math.min(wy(0), m.oy + m.height * m.res));
  var gx0 = sx(m.ox), gx1 = sx(m.ox + m.width * m.res), gy0 = sy(m.oy + m.height * m.res), gy1 = sy(m.oy);
  ctx.strokeStyle = "rgba(234,240,239,.07)";
  ctx.lineWidth = 1;
  ctx.beginPath();
  for (var x = x0; x <= x1; x++) { var X = Math.round(sx(x)) + .5; ctx.moveTo(X, gy0); ctx.lineTo(X, gy1); }
  for (var y = y0; y <= y1; y++) { var Y = Math.round(sy(y)) + .5; ctx.moveTo(gx0, Y); ctx.lineTo(gx1, Y); }
  ctx.stroke();
}

// The robot's pose comes with /state.json (1 Hz) and with /scan.json (3 Hz). Each age_s is
// the server's at its answer; the time since that answer (ms in *At) is added, and the younger
// pose (the more recent odometry message) is the one drawn. A pose of null says "no pose"
// (a stopped stack, a new run): from the later answer it hides the marker, whatever the other
// answer still holds; undefined is "no answer yet". Returns {x, y, yaw, age_s} or null.
function freshestPose(statePose, stateAt, scanPose, scanAt, nowMs) {
  function aged(p, at) {
    if (!p || typeof p.x !== "number" || typeof p.y !== "number") return null;
    var age = (typeof p.age_s === "number" ? p.age_s : 0) + Math.max(0, (nowMs - at) / 1000);
    return { x: p.x, y: p.y, yaw: p.yaw, age_s: age };
  }
  if (statePose === null && stateAt >= scanAt) return null;
  if (scanPose === null && scanAt > stateAt) return null;
  var a = aged(statePose, stateAt), b = aged(scanPose, scanAt);
  return b && (!a || b.age_s < a.age_s) ? b : a;
}

function pose() {
  return freshestPose(S.state ? S.state.pose : undefined, S.stateAt,
                      S.scan ? S.scan.pose : undefined, S.scanAt, Date.now());
}

// key: "points" (lidar returns, the default) or "camera" (depth-camera obstacle points)
function scanWorld(key) {
  var sc = S.scan, pts = sc && sc[key || "points"]; if (!pts) return [];
  if (sc.frame === "world") return pts;
  var p = pose();                    // lidar frame: place it at the robot
  var px = p ? p.x : 0, py = p ? p.y : 0, c = Math.cos(p ? p.yaw : 0), s = Math.sin(p ? p.yaw : 0);
  return pts.map(function (q) { return [px + c * q[0] - s * q[1], py + s * q[0] + c * q[1]]; });
}

// The server keeps the last scan and path however old they are: only fresh ones
// are drawn as live. The scan's own age_s is cached with it, so the bus age wins.
function scanLive() {
  var sc = S.scan; if (!sc) return false;
  var topics = (S.state && S.state.topics) || {};
  var a = sc.source in topics ? topicAge(sc.source)
        : (typeof sc.age_s === "number" ? sc.age_s + offlineFor() : null);
  return a !== null && a < LIVE_S;
}
// One /path message per plan, not a stream: a plan stays valid while the stack runs.
function pathLive() {
  var pa = S.path, a = pa && typeof pa.age_s === "number" ? pa.age_s + offlineFor() : null;
  if (a !== null && a < LIVE_S) return true;
  var odom = topicAge("odom");
  return stack().running && odom !== null && odom < LIVE_S;
}

function draw() {
  var w = W(), h = H();
  ctx.clearRect(0, 0, w, h);
  var m = S.meta;
  if (S.mapImg && m) {
    ctx.imageSmoothingEnabled = false;
    ctx.drawImage(S.mapImg, sx(m.ox), sy(m.oy + m.height * m.res), m.width * m.res * S.view.scale, m.height * m.res * S.view.scale);
  }
  drawGrid();

  // path: mint line, dimmed once the stack that planned it is gone
  var pts = S.path && S.path.points;
  if (pts && pts.length > 1) {
    ctx.strokeStyle = pathLive() ? "#6CF8C7" : "rgba(108,248,199,.3)";
    ctx.lineWidth = 2.25; ctx.lineJoin = "round"; ctx.lineCap = "round";
    ctx.beginPath(); ctx.moveTo(sx(pts[0][0]), sy(pts[0][1]));
    for (var i = 1; i < pts.length; i++) ctx.lineTo(sx(pts[i][0]), sy(pts[i][1]));
    ctx.stroke();
  }

  // scan: mint dots, only while the lidar speaks (an old scan is not where the robot is)
  var live = scanLive(), sc = live ? scanWorld() : [], r = Math.max(1.1, Math.min(2.4, S.view.scale / 40));
  ctx.fillStyle = "rgba(108,248,199,.9)";
  for (var k = 0; k < sc.length; k++) {
    var X = sx(sc[k][0]), Y = sy(sc[k][1]);
    if (X < -4 || Y < -4 || X > w + 4 || Y > h + 4) continue;
    ctx.fillRect(X - r / 2, Y - r / 2, r, r);
  }
  // depth camera: amber round dots over the scan, larger, so a single obstacle point shows
  var cam = live ? scanWorld("camera") : [], rc = r / 2 + 1.6;
  if (cam.length) {
    ctx.fillStyle = DEPTH_COLOR;
    ctx.beginPath();
    for (var j = 0; j < cam.length; j++) {
      var CX = sx(cam[j][0]), CY = sy(cam[j][1]);
      if (CX < -6 || CY < -6 || CX > w + 6 || CY > h + 6) continue;
      ctx.moveTo(CX + rc, CY); ctx.arc(CX, CY, rc, 0, 2 * Math.PI);
    }
    ctx.fill();
  }
  var cn = S.scan && S.scan.camera_n;
  setText("hud-cam", "camera obstacles: " + (!live ? "--" : typeof cn === "number" ? String(cn) : "no depth"));

  // goal: salmon ring (dashed while it waits for confirmation)
  var nav = S.state && S.state.nav;
  if (nav && nav.goal) ring(nav.goal.x, nav.goal.y, false);
  if (S.pendingGoal) ring(S.pendingGoal.x, S.pendingGoal.y, true);

  // pose: white triangle pointing along yaw (the younger of the two poses, freshestPose)
  var p = pose();
  // commanded motion: what the planner asks of the tracks now, out of the marker's nose (tail in reverse);
  // drawn first so the marker stays whole where the line's round cap meets it
  var cmd = cmdArrow(nav && nav.last_cmd_vel, p, sinceState());
  if (cmd) drawCmd(cmd);
  if (p && typeof p.x === "number") {
    var cx = sx(p.x), cy = sy(p.y), a = -(p.yaw || 0), L = MARK_L, B = MARK_B;
    ctx.save(); ctx.translate(cx, cy); ctx.rotate(a);
    ctx.beginPath(); ctx.moveTo(L * .62, 0); ctx.lineTo(-L * .38, B); ctx.lineTo(-L * .2, 0); ctx.lineTo(-L * .38, -B); ctx.closePath();
    ctx.fillStyle = (typeof p.age_s === "number" && p.age_s > STALE_S) ? "rgba(234,240,239,.5)" : "#EAF0EF";
    ctx.strokeStyle = "rgba(8,15,26,.65)"; ctx.lineWidth = 1.2;
    ctx.fill(); ctx.stroke(); ctx.restore();
  }
  positionChip();
}

function ring(x, y, dashed) {
  ctx.save();
  ctx.strokeStyle = "#FF947E"; ctx.lineWidth = 2.25;
  if (dashed) ctx.setLineDash([4, 4]);
  ctx.beginPath(); ctx.arc(sx(x), sy(y), 9, 0, 2 * Math.PI); ctx.stroke();
  ctx.setLineDash([]);
  ctx.beginPath(); ctx.arc(sx(x), sy(y), 2, 0, 2 * Math.PI); ctx.fillStyle = "#FF947E"; ctx.fill();
  ctx.restore();
}

// The commanded motion (nav.last_cmd_vel: vx m/s, forward positive; wz rad/s, left positive;
// age_s on the server's clock) as a shape in the world frame at pose p ({x, y, yaw}), or null
// when there is nothing to draw: no pose, no command, a command LIVE_S old or more once
// extraAge (s since the server answered) is added, or a zero command.
//   {kind: "path", x, y, yaw, sign, len, pts: [[x, y], ...], tip: {x, y, ux, uy}}: the path a
//       constant (vx, wz) drives in CMD_ARROW_S from the pose, straight or bent (an arc), behind the
//       robot in reverse (sign -1); len = its length, m; tip = its end and the unit direction the
//       robot moves there. drawCmd moves it to the marker's edge on screen.
//   {kind: "pivot", x, y, yaw, dir, sweep}: a turn on the spot (|vx| under CMD_VX_EPS, or a turn
//       radius |vx / wz| under PIVOT_RADIUS_M), dir 1 = left (counterclockwise), -1 = right;
//       sweep = the turn of PIVOT_ARROW_S, rad, kept between PIVOT_MIN_RAD and PIVOT_MAX_RAD
function cmdArrow(c, p, extraAge) {
  if (!c || !p || typeof p.x !== "number" || typeof p.y !== "number") return null;
  var vx = c.vx, wz = c.wz;
  if (typeof vx !== "number" || typeof wz !== "number" || !isFinite(vx) || !isFinite(wz)) return null;
  var age = (typeof c.age_s === "number" ? c.age_s : Infinity) + (extraAge || 0);
  if (!(age < LIVE_S)) return null;
  var yaw = typeof p.yaw === "number" && isFinite(p.yaw) ? p.yaw : 0;
  if (Math.abs(vx) < CMD_VX_EPS || (Math.abs(wz) >= CMD_WZ_EPS && Math.abs(vx / wz) < PIVOT_RADIUS_M)) {
    if (Math.abs(wz) < CMD_WZ_EPS) return null;
    return { kind: "pivot", x: p.x, y: p.y, yaw: yaw, dir: wz > 0 ? 1 : -1,
             sweep: Math.max(PIVOT_MIN_RAD, Math.min(PIVOT_MAX_RAD, Math.abs(wz) * PIVOT_ARROW_S)) };
  }
  var c0 = Math.cos(yaw), s0 = Math.sin(yaw), pts = [];
  for (var i = 0; i <= CMD_STEPS; i++) {
    var t = CMD_ARROW_S * i / CMD_STEPS, fx, fy;     // robot frame at the pose: x forward, y left
    if (Math.abs(wz) < 1e-9) { fx = vx * t; fy = 0; }
    else { fx = vx / wz * Math.sin(wz * t); fy = vx / wz * (1 - Math.cos(wz * t)); }
    pts.push([p.x + c0 * fx - s0 * fy, p.y + s0 * fx + c0 * fy]);
  }
  var h = yaw + wz * CMD_ARROW_S, sg = vx > 0 ? 1 : -1, end = pts[CMD_STEPS];
  return { kind: "path", x: p.x, y: p.y, yaw: yaw, sign: sg, len: Math.abs(vx) * CMD_ARROW_S, pts: pts,
           tip: { x: end[0], y: end[1], ux: sg * Math.cos(h), uy: sg * Math.sin(h) } };
}

// A screen polyline ([[x, y], ...], px) without its last `cut` px, [] when it is not longer.
function trimEnd(sp, cut) {
  var total = 0, run = 0, i, d;
  for (i = 1; i < sp.length; i++) total += Math.hypot(sp[i][0] - sp[i - 1][0], sp[i][1] - sp[i - 1][1]);
  var keep = total - cut, out = [sp[0]];
  if (!(keep > 0)) return [];
  for (i = 1; i < sp.length; i++) {
    d = Math.hypot(sp[i][0] - sp[i - 1][0], sp[i][1] - sp[i - 1][1]);
    if (run + d >= keep) {
      var f = d > 0 ? (keep - run) / d : 0;
      out.push([sp[i - 1][0] + f * (sp[i][0] - sp[i - 1][0]), sp[i - 1][1] + f * (sp[i][1] - sp[i - 1][1])]);
      return out;
    }
    run += d; out.push(sp[i]);
  }
  return out;
}

// Draws cmdArrow's shape at the robot: a navy outline, the mint line, then the arrowhead, whose
// tip is the end of the path (or of the pivot arc) and which points the way the robot moves.
// A path starts at the marker's edge, its nose (its tail in reverse), not under the marker, and
// runs its metres at the map's scale past that edge, or CMD_MIN_RUN px when that is longer: the
// same shape scaled, so the turn over it stays wz * CMD_ARROW_S. The line stops under the head.
// Screen angles turn clockwise (y down): a world angle a is -a.
function drawCmd(a) {
  var line = null, tip;          // line() builds the shaft; tip = [x, y, ux, uy], screen px and direction
  if (a.kind === "pivot") {
    var cx = sx(a.x), cy = sy(a.y), a0 = -a.yaw, a1 = a0 - a.dir * a.sweep, back = CMD_HEAD / PIVOT_R_PX;
    var aEnd = a1 + a.dir * back * .7;
    line = function () { ctx.beginPath(); ctx.arc(cx, cy, PIVOT_R_PX, a0, aEnd, a.dir > 0); };
    var tx = cx + PIVOT_R_PX * Math.cos(a1), ty = cy + PIVOT_R_PX * Math.sin(a1);
    var bx = cx + PIVOT_R_PX * Math.cos(a1 + a.dir * back), by = cy + PIVOT_R_PX * Math.sin(a1 + a.dir * back);
    var l = Math.hypot(tx - bx, ty - by) || 1;      // the head lies along the chord, on the arc
    tip = [tx, ty, (tx - bx) / l, (ty - by) / l];
  } else {
    var c0 = sx(a.x), c1 = sy(a.y), edge = a.sign > 0 ? MARK_L * .62 : MARK_L * .38;
    var px = a.len * S.view.scale, k = px > 0 ? Math.max(CMD_MIN_RUN, px) / px : 1;
    var ox = c0 + a.sign * edge * Math.cos(a.yaw), oy = c1 - a.sign * edge * Math.sin(a.yaw);
    var sp = a.pts.map(function (q) { return [ox + k * (sx(q[0]) - c0), oy + k * (sy(q[1]) - c1)]; });
    tip = [sp[sp.length - 1][0], sp[sp.length - 1][1], a.tip.ux, -a.tip.uy];
    sp = trimEnd(sp, CMD_HEAD * .7);
    if (sp.length > 1) line = function () {
      ctx.beginPath(); ctx.moveTo(sp[0][0], sp[0][1]);
      for (var i = 1; i < sp.length; i++) ctx.lineTo(sp[i][0], sp[i][1]);
    };
  }
  var hx = tip[0] - tip[2] * CMD_HEAD, hy = tip[1] - tip[3] * CMD_HEAD;
  var nx = -tip[3] * CMD_HEAD * .5, ny = tip[2] * CMD_HEAD * .5;
  function head() {
    ctx.beginPath(); ctx.moveTo(tip[0], tip[1]); ctx.lineTo(hx + nx, hy + ny); ctx.lineTo(hx - nx, hy - ny); ctx.closePath();
  }
  ctx.save();
  ctx.lineCap = "round"; ctx.lineJoin = "round";
  ctx.strokeStyle = HALO;
  if (line) { ctx.lineWidth = CMD_W + 4; line(); ctx.stroke(); }
  ctx.lineWidth = 4; head(); ctx.stroke();
  ctx.strokeStyle = MINT; ctx.fillStyle = MINT;
  if (line) { ctx.lineWidth = CMD_W; line(); ctx.stroke(); }
  head(); ctx.fill();
  ctx.restore();
}

function pollMeta() {
  return fetchJSON("/map_meta").then(function (m) {
    if (!m || m.__missing || m.error || !(m.width > 0)) {
      $("map-empty").hidden = !!S.mapImg; return;
    }
    var stamp = String(m.stamp != null ? m.stamp : (m.map_mtime != null ? m.map_mtime : ""));
    if (stamp === S.mapStamp && S.mapImg) return;
    return new Promise(function (ok) {
      var img = new Image();
      img.onload = function () {
        // /map.png is a second request: the server may have decoded a newer, differently
        // cropped costmap in between. The crop only grows, so a size mismatch catches it;
        // keep the old pair and leave the stamp, the next poll fetches both again.
        if (img.naturalWidth !== m.width || img.naturalHeight !== m.height) { ok(); return; }
        // swap image and metadata together, so the transform always matches the picture
        S.mapImg = img; S.meta = m; S.mapStamp = stamp;
        $("map-empty").hidden = true;
        if (!S.fitted) fitView();
        renderCaption(); requestDraw(); ok();
      };
      img.onerror = function () { ok(); };
      img.src = "/map.png?stamp=" + encodeURIComponent(stamp);
    });
  }, function () {});
}

function pollScan() {
  return fetchJSON("/scan.json").then(function (d) {
    if (d && !d.__missing && d.points) { S.scan = d; S.scanAt = Date.now(); requestDraw(); }
  }, function () {});
}

function pollPath() {
  return fetchJSON("/path.json").then(function (d) {
    S.path = (d && !d.__missing && d.points) ? d : null; requestDraw();
  }, function () {});
}

// pointer events: drag = pan, wheel / pinch = zoom around the cursor, tap = goal
var ptrs = {}, gesture = null;

function local(e) { var b = cv.getBoundingClientRect(); return { x: e.clientX - b.left, y: e.clientY - b.top }; }
function ptrList() { return Object.keys(ptrs).map(function (k) { return ptrs[k]; }); }

cv.addEventListener("pointerdown", function (e) {
  if (e.button !== undefined && e.button > 0) return;
  cv.setPointerCapture(e.pointerId);
  ptrs[e.pointerId] = local(e);
  var l = ptrList();
  if (l.length === 1) {
    gesture = { kind: "pan", start: l[0], vx: S.view.x, vy: S.view.y, moved: false };
  } else if (l.length === 2) {
    var mx = (l[0].x + l[1].x) / 2, my = (l[0].y + l[1].y) / 2;
    gesture = { kind: "pinch", d0: Math.hypot(l[0].x - l[1].x, l[0].y - l[1].y) || 1, s0: S.view.scale,
                wx: wx(mx), wy: wy(my), moved: true };
  }
});

cv.addEventListener("pointermove", function (e) {
  var p = local(e);
  setText("hud-xy", "x " + signed(wx(p.x), 2) + " m   y " + signed(wy(p.y), 2) + " m");
  if (!(e.pointerId in ptrs)) return;
  ptrs[e.pointerId] = p;
  if (!gesture) return;
  var l = ptrList();
  if (gesture.kind === "pan" && l.length === 1) {
    var dx = p.x - gesture.start.x, dy = p.y - gesture.start.y;
    if (!gesture.moved && Math.abs(dx) + Math.abs(dy) > TAP_SLOP_PX) { gesture.moved = true; cv.classList.add("grabbing"); }
    if (gesture.moved) { S.view.x = gesture.vx - dx / S.view.scale; S.view.y = gesture.vy + dy / S.view.scale; requestDraw(); }
  } else if (gesture.kind === "pinch" && l.length >= 2) {
    var d = Math.hypot(l[0].x - l[1].x, l[0].y - l[1].y) || 1;
    var mx = (l[0].x + l[1].x) / 2, my = (l[0].y + l[1].y) / 2;
    zoomTo(gesture.s0 * d / gesture.d0, gesture.wx, gesture.wy, mx, my);
  }
});

function endPointer(e) {
  var was = gesture, p = ptrs[e.pointerId] || local(e);
  delete ptrs[e.pointerId];
  cv.classList.remove("grabbing");
  var left = ptrList().length;
  if (left === 0) {
    gesture = null;
    if (e.type === "pointerup" && was && was.kind === "pan" && !was.moved) tap(p);
  } else if (left === 1) {
    var q = ptrList()[0];             // pinch -> pan with the remaining finger, never a tap
    gesture = { kind: "pan", start: q, vx: S.view.x, vy: S.view.y, moved: true };
  }
}
cv.addEventListener("pointerup", endPointer);
cv.addEventListener("pointercancel", endPointer);
cv.addEventListener("pointerleave", function () { setText("hud-xy", "x -- m   y -- m"); });

function zoomTo(scale, wxp, wyp, px, py) {
  S.view.scale = Math.max(4, Math.min(600, scale));
  S.view.x = wxp - px / S.view.scale;
  S.view.y = wyp + py / S.view.scale;
  requestDraw();
}

cv.addEventListener("wheel", function (e) {
  e.preventDefault();
  var p = local(e);
  zoomTo(S.view.scale * Math.pow(1.0015, -e.deltaY), wx(p.x), wy(p.y), p.x, p.y);
}, { passive: false });

$("b-fit").addEventListener("click", fitView);

// tap on the map -> inline confirm chip, never a modal
function tap(p) {
  var x = wx(p.x), y = wy(p.y);
  if (!canGoal()) {
    S.pendingGoal = null;
    showChip(p, "Goals need the explore stack running.", false);
    return;
  }
  S.pendingGoal = { x: x, y: y, px: p.x, py: p.y };
  showChip(p, "Send goal (" + signed(x, 2) + ", " + signed(y, 2) + ")? Stops exploration first.", true);
  requestDraw();
}

var chipTimer = null;
function showChip(p, text, ask) {
  var chip = $("goal-chip");
  setText("goal-text", text);
  $("b-goal-yes").hidden = !ask;
  $("b-goal-no").textContent = ask ? "Cancel" : "OK";
  chip.hidden = false;
  chip.dataset.px = p.x; chip.dataset.py = p.y;
  positionChip();
  clearTimeout(chipTimer);
  if (ask) $("b-goal-yes").focus({ preventScroll: true });
  else chipTimer = setTimeout(hideChip, 4000);
}

function positionChip() {
  var chip = $("goal-chip");
  if (chip.hidden) return;
  var px = S.pendingGoal ? sx(S.pendingGoal.x) : +chip.dataset.px;
  var py = S.pendingGoal ? sy(S.pendingGoal.y) : +chip.dataset.py;
  var cw = chip.offsetWidth, ch = chip.offsetHeight;
  var left = Math.max(0, Math.min(W() - cw, px - cw / 2));
  var top = py - ch - 18;
  if (top < 44) top = py + 18;
  chip.style.left = left + "px";
  chip.style.top = Math.max(0, Math.min(H() - ch, top)) + "px";
}

function hideChip() { $("goal-chip").hidden = true; S.pendingGoal = null; requestDraw(); }

$("b-goal-no").addEventListener("click", hideChip);
$("b-goal-yes").addEventListener("click", function () {
  var g = S.pendingGoal; if (!g) return;
  hideChip();
  post("goal", { x: +g.x.toFixed(3), y: +g.y.toFixed(3) }).then(function (d) {
    answer(d, "Goal sent: " + signed(g.x, 2) + ", " + signed(g.y, 2) + " m.");
    pollState();
  }, function () { say("Goal not sent: the cockpit did not answer.", true); });
});

window.addEventListener("keydown", function (e) {
  if (e.key === "Escape") { hideChip(); $("ex-confirm").hidden = true; }
});

// ---------------------------------------------------------------- commands

function stackCmd(action, okText) {
  S.launchBusy = true; S.launchAction = action; renderControls();
  post("stack", { action: action }).then(function (d) {
    if (!answer(d, okText)) { S.launchBusy = false; renderControls(); return; }
    watchLaunch();
  }, function () { S.launchBusy = false; renderControls(); say("The cockpit did not answer.", true); });
}

var launchWatching = false;
function watchLaunch() {
  if (launchWatching) return;
  launchWatching = true;
  (function step() {
    fetchJSON("/launch.json").then(function (d) {
      var lines = (d && (d.lines || d.tail)) || [];
      var ul = $("launch-tail"), html = "";
      lines.slice(-5).forEach(function (l) { html += "<li>" + esc(l) + "</li>"; });
      ul.innerHTML = html;
      if (lines.length) { S.lastLog = { text: String(lines[lines.length - 1]), warn: false }; renderSimpleLog(); }
      if (d && d.running) { setTimeout(step, POLL.launch); return; }
      launchWatching = false;
      var was = S.launchAction;
      S.launchBusy = false; S.launchAction = null;
      renderControls();
      if (was) loadPreflight();          // check, map and explore all rewrite preflight.json
      pollState();
    }, function () { setTimeout(step, POLL.launch * 2); });
  })();
}

$("b-map").addEventListener("click", function () { stackCmd("map", "Launching the mapping stack."); });
$("b-explore").addEventListener("click", function () { stackCmd("explore", "Launching the explore stack. Exploration stays off."); });
$("b-stack-stop").addEventListener("click", function () { stackCmd("stop", "Stopping the stack."); });
$("idle-note").addEventListener("click", keepUp);
$("b-check").addEventListener("click", function () { stackCmd("check", "Flight check running."); });
$("b-check2").addEventListener("click", function () { stackCmd("check", "Flight check running."); });

$("b-ex-start").addEventListener("click", function () { $("ex-confirm").hidden = false; $("b-ex-yes").focus(); });
$("b-ex-no").addEventListener("click", function () { $("ex-confirm").hidden = true; });
$("b-ex-yes").addEventListener("click", function () {
  $("ex-confirm").hidden = true;
  post("explore", { action: "start" }).then(function (d) { answer(d, "Exploration started."); pollState(); },
                                            function () { say("The cockpit did not answer.", true); });
});
$("b-map-clear").addEventListener("click", function () {
  // the page drops its own copy first: a cleared map must not stay on screen until the next one
  post("map", { action: "clear" }).then(function (d) {
    if (d && d.ok) { S.mapImg = null; S.mapStamp = null; S.meta = null; requestDraw(); }
    answer(d, "Map cleared: a fresh grid from here.");
  }, function () { say("The cockpit did not answer.", true); });
});
$("b-ex-stop").addEventListener("click", function () {
  post("explore", { action: "stop" }).then(function (d) { answer(d, "Exploration stopped."); pollState(); },
                                           function () { say("The cockpit did not answer.", true); });
});

$("b-ep").addEventListener("click", function () {
  var rec = (S.state && S.state.recording) || {}, ep = rec.episode;
  var name = ep ? ep.name : ($("ep-name").value.trim() || "ep1");
  post("episode", { action: ep ? "stop" : "start", name: name }).then(function (d) {
    if (answer(d, ep ? "Episode " + name + " closed." : "Episode " + name + " started.") && ep) {
      var m = /^(.*?)(\d+)$/.exec(name);
      $("ep-name").value = m ? m[1] + (parseInt(m[2], 10) + 1) : name + "-2";
    }
    pollState();
  }, function () { say("The cockpit did not answer.", true); });
});

var stopTimer = null;
function stopShow(label, bad) {         // #say may be scrolled away: the button that was pressed tells too
  ["b-stop", "stop-fab", "b-s-stop"].forEach(function (id) { var b = $(id); b.textContent = label; b.classList.toggle("fail", !!bad); });
  clearTimeout(stopTimer);
  stopTimer = setTimeout(function () { stopShow("STOP", false); }, bad ? 8000 : 2500);
}
function softStop() {
  hideChip();
  post("stop", {}).then(function (d) {
    stopShow(answer(d, "Soft stop sent: exploration, navigation, zero twist.") ? "STOP SENT" : "STOP NOT SENT", !(d && d.ok));
    pollState();
  }, function () {
    stopShow("STOP NOT SENT", true);
    say("STOP NOT SENT: the cockpit did not answer. Use the pad or moss-fly.sh stop.", true);
  });
}
$("b-stop").addEventListener("click", softStop);
$("stop-fab").addEventListener("click", softStop);

// ---------------------------------------------------------------- Simple view

// Two views of one page. Advanced is everything above: the modules, the map, the feed. Simple is
// the column for a phone or a tablet (#simple in index.html): the word for now and the battery,
// one camera, STOP, the stack, one line of log. ?view=simple or ?view=advanced picks a view and
// the device remembers it; otherwise the remembered choice; otherwise a first visit narrower than
// SIMPLE_MAX_W opens Simple. The cameras' elements move into #simple and back, so the streams and
// their watch are the same code; the camera not shown is not streamed (camWanted).
var SIMPLE_MAX_W = 700;
var VIEW_KEY = "moss.cockpit.view";
var SAY_SIMPLE_MS = 8000;     // a press's answer holds the Simple status line this long; an error until the next action
var BATTERY_LOW_V = 10.8;     // the base module's own line

function viewFor(query, stored, width) {
  if (query === "simple" || query === "advanced") return query;
  if (stored === "simple" || stored === "advanced") return stored;
  return typeof width === "number" && width < SIMPLE_MAX_W ? "simple" : "advanced";
}

function storedView() { try { return localStorage.getItem(VIEW_KEY); } catch (e) { return null; } }

function camWanted(n) { return S.ui !== "simple" || S.simpleCam === n; }

// The word for now in Simple, from the state: {word, cls, detail}. One word, the worst thing first,
// and a line that says what it means for the hand on the pad.
function simpleView(state, online, busy, stalled) {
  var st = (state && state.stack) || { running: false };
  if (!online) return { word: "OFFLINE", cls: "attn",
                        detail: "The cockpit does not answer. The pad still drives; the firmware stops the tracks 300 ms after its last command." };
  if (busy) return { word: "LAUNCHING", cls: "", detail: "The stack is starting; its last line is below." };
  if (!st.running) return { word: "NO STACK", cls: "dim", detail: "Launch map: the lidar map and the pad." };
  var b = state.base;
  if (!b) return { word: "NO TELEMETRY", cls: "dim", detail: "Stack up; the base has not spoken yet." };
  var age = (typeof b.age_s === "number" ? b.age_s : 0) + (typeof b.firmware_age_s === "number" ? b.firmware_age_s : 0);
  if (age > LIVE_S) return { word: "NO TELEMETRY", cls: "attn", detail: "Nothing from the base for " + dur(age) + "." };
  if (typeof b.battery_v === "number" && b.battery_v < BATTERY_LOW_V) return { word: "BATTERY LOW", cls: "attn", detail: "Land it." };
  if (stalled) return { word: "STALLED", cls: "attn",
                        detail: "A commanded track did not move and the base stopped it. Centre the sticks, then drive again." };
  if (state.nav && state.nav.exploring) return { word: "EXPLORING", cls: "accent", detail: "On its own. A stick or STOP takes over." };
  if (b.mode === 2) return { word: "DRIVING", cls: "accent", detail: "The pad drives." };
  if (b.mode === 1) return { word: "READY", cls: "", detail: "Armed. Centred sticks, tracks stopped." };
  return { word: "DISARMED", cls: "dim", detail: "Stack up, base disarmed." };
}

function renderSimple() {
  if (S.ui !== "simple") return;
  var v = simpleView(S.state, S.online, S.launchBusy, !$("b-stall").hidden);
  setText("s-word", v.word);
  $("s-word").className = ("s-word " + v.cls).trim();
  setText("s-detail", v.detail);
  var b = S.state && S.state.base, low = !!(b && typeof b.battery_v === "number" && b.battery_v < BATTERY_LOW_V);
  setText("s-volt", b ? num(b.battery_v, 2) : "--");
  setText("s-pct", b && typeof b.battery_pct === "number" ? Math.round(b.battery_pct) + " %"
                   : (b && b.ina_ok === false ? "battery sensor not seen" : ""));
  $("s-batt").classList.toggle("attn", low);
  var st = stack(), on = S.online, busy = S.launchBusy;
  $("b-s-launch").disabled = !on || st.running || busy;
  $("b-s-stack-stop").disabled = !on || (!st.running && !busy);
  renderSimpleLog();
}

// The Simple status line: what the page just said (a press's answer) while it is fresh, else the
// newest log line (the launcher's while a stack starts): {text, cls}.
function simpleLogView(said, last, nowMs) {
  if (said && (said.bad || nowMs - said.at < SAY_SIMPLE_MS)) return { text: said.text, cls: said.bad ? "attn" : "ok" };
  if (last) return { text: last.text, cls: last.warn ? "attn" : "dim" };
  return { text: "No stack, no log.", cls: "dim" };
}

function renderSimpleLog() {
  var v = simpleLogView(S.say, S.lastLog, Date.now());
  setText("s-log", v.text);
  $("s-log").className = "s-log num " + v.cls;
}

function applyView(v) {
  S.ui = v;
  var simple = v === "simple";
  document.body.classList.toggle("simple", simple);
  $("simple").hidden = !simple;
  $("b-view").textContent = simple ? "Advanced" : "Simple";
  $("b-view").setAttribute("aria-pressed", simple ? "true" : "false");
  var home = simple ? $("s-cam") : $("cams");
  ["nose", "wrist"].forEach(function (n) {
    var el = $("cam-" + n);
    if (el.parentNode !== home) home.insertBefore(el, simple ? $("b-s-cam") : null);
    el.hidden = simple && n !== S.simpleCam;
  });
  $("b-s-cam").textContent = S.simpleCam === "nose" ? "WRIST" : "NOSE";
  try { localStorage.setItem(VIEW_KEY, v); } catch (e) {}
  camConnectAll(); renderCamera();
  if (!simple) { S.fitted = false; resize(); fitView(); }
  renderSimple();
}

$("b-view").addEventListener("click", function () { applyView(S.ui === "simple" ? "advanced" : "simple"); });
$("b-s-cam").addEventListener("click", function () { S.simpleCam = S.simpleCam === "nose" ? "wrist" : "nose"; applyView("simple"); });
$("b-s-stop").addEventListener("click", softStop);
$("b-s-launch").addEventListener("click", function () { stackCmd("map", "Launching the mapping stack."); });
$("b-s-stack-stop").addEventListener("click", function () { stackCmd("stop", "Stopping the stack."); });

// ---------------------------------------------------------------- flight check

function loadPreflight() {
  return fetchJSON("/preflight.json").then(function (d) {
    if (!d || d.__missing || d.available === false || !d.checks) { S.preflight = null; }
    else S.preflight = d;
    renderPreflight();
  }, function () {});
}

function renderPreflight() {
  var d = S.preflight, list = $("pf-list");
  $("pf-empty").hidden = !!d;
  list.hidden = !d;
  $("pf-again").hidden = !d;
  if (!d) { setText("pf-title", "No flight check yet."); setText("pf-when", ""); return; }
  var ko = typeof d.ko_count === "number" ? d.ko_count : d.checks.filter(function (c) { return !c.ok; }).length;
  setText("pf-title", ko ? ko + (ko > 1 ? " checks" : " check") + " to fix." : "Ready to fly.");
  $("pf-title").classList.toggle("attn", ko > 0);
  renderPreflightWhen();
  // Brief by default: what needs fixing stays in view, the passing rows fold
  // away so the base and system modules are not pushed off the screen.
  var html = "", sec = null, pass = 0, skippedN = 0;
  d.checks.forEach(function (c) {
    if (c.section && c.section !== sec) {
      sec = c.section;
      html += '<li class="sec"><span class="kicker">' + esc(String(sec).toUpperCase()) + "</span></li>";
    }
    var skipped = c.ok && /skipp|held by the stack/i.test(c.detail || "");
    var mark = skipped ? '<span class="v na">--</span>' : c.ok ? '<span class="v ok">OK</span>' : '<span class="v ko">KO</span>';
    if (c.ok && !skipped) pass++;
    if (skipped) skippedN++;
    html += '<li class="' + (c.ok ? "pass" : "fail") + '">' + mark + '<span class="lb">' + esc(c.label) + "</span>"
         + (c.detail ? '<span class="dt">' + esc(c.detail) + "</span>" : "") + "</li>";
  });
  var skipTxt = skippedN ? ", " + skippedN + " skipped" : "";
  html += '<li class="passline">' + (pass + skippedN === d.checks.length ? pass + " checks pass" + skipTxt + "."
                                     : pass + " passing " + (pass === 1 ? "check" : "checks") + " folded" + skipTxt + ".") + "</li>";
  list.innerHTML = html;
  list.classList.toggle("brief", !S.pfAll);
  setText("b-pf-all", S.pfAll ? "Fold passing checks" : "Show passing checks");
  $("b-pf-all").setAttribute("aria-expanded", S.pfAll ? "true" : "false");
}

// the check's age on the Jetson's clock (no NTP in the field), refreshed by every state poll
function renderPreflightWhen() {
  var d = S.preflight;
  if (!d) return;
  var now = (S.state && typeof S.state.ts === "number") ? S.state.ts + offlineFor() : Date.now() / 1000;
  var when = typeof d.ts === "number" ? ago(now - d.ts) : "";
  setText("pf-when", (d.summary || "") + (when ? "  ·  " + when : ""));
}

$("b-pf-all").addEventListener("click", function () { S.pfAll = !S.pfAll; renderPreflight(); });

// ---------------------------------------------------------------- log

function fmtTs(ts) {
  if (typeof ts === "number") { var d = new Date(ts * 1000); return pad2(d.getHours()) + ":" + pad2(d.getMinutes()) + ":" + pad2(d.getSeconds()); }
  // dimOS stamps main.jsonl in UTC ISO with a "Z": parse it, show local time
  var t = typeof ts === "string" && /^\d{4}-\d{2}-\d{2}T/.test(ts) ? new Date(ts) : null;
  if (t && !isNaN(t.getTime())) return pad2(t.getHours()) + ":" + pad2(t.getMinutes()) + ":" + pad2(t.getSeconds());
  var m = /(\d{2}:\d{2}:\d{2})/.exec(String(ts || ""));
  return m ? m[1] : "";
}

function pollLog() {
  return fetchJSON("/log.json?n=20").then(function (d) {
    var lines = Array.isArray(d) ? d : (d && (d.lines || d.log)) || [];
    var el = $("log"), html = "";
    lines.slice(-20).forEach(function (l) {
      var lv = String(l.level || "").toLowerCase(), warn = /warn|error|crit/.test(lv);
      html += '<li class="' + (warn ? "warn" : "") + '"><span class="t">' + esc(fmtTs(l.ts)) + '</span><span class="e">'
           + esc(l.event) + (l.logger ? ' <span class="lg">' + esc(String(l.logger).split(".").pop()) + "</span>" : "")
           + "</span></li>";
    });
    if (!html) html = '<li><span class="t"></span><span class="e dim">' + (stack().running ? "Log is empty." : "No stack, no log.") + "</span></li>";
    if (el.innerHTML !== html) el.innerHTML = html;
    var last = lines.length ? lines[lines.length - 1] : null;
    S.lastLog = last ? { text: fmtTs(last.ts) + "  " + last.event,
                         warn: /warn|error|crit/.test(String(last.level || "").toLowerCase()) }
                     : { text: stack().running ? "Log is empty." : "No stack, no log.", warn: false };
    renderSimpleLog();
  }, function () {});
}

// ---------------------------------------------------------------- decisions

// What the stack decides, read by the server from the stack's own log (/decisions.json): the
// events {ts, kind, text, src, seq}, oldest first, and the word for now {word, detail, since}.
// A kind's colour says what happened: the robot touched something (warn), something is in the
// planner's way (caution), it heads somewhere (accent), it waits or gives a goal up (dim).
var KIND_CLASS = {
  contact: "warn", push: "warn", imu: "warn",
  obstacle: "caution", replan: "caution", pivot_fallback: "caution",
  goal: "accent", new_goal: "accent", reached: "accent",
  waiting: "dim", goal_dropped: "dim", retry: "dim",
  mission: ""
};
var KIND_LABEL = {
  goal: "GOAL", new_goal: "NEW GOAL", reached: "REACHED", obstacle: "OBSTACLE", replan: "REPLAN",
  contact: "CONTACT", push: "PUSH", imu: "IMU", pivot_fallback: "PIVOT", waiting: "WAITING",
  goal_dropped: "DROPPED", retry: "RETRY", mission: "MISSION"
};
var WORD_CLASS = {
  "OBSTACLE": "warn", "BACKING OFF": "warn", "STUCK": "warn", "HEADING": "accent",
  "IDLE": "dim", "READY": "dim", "WAITING": "dim", "DONE": "dim", "STOPPED": "dim"
};
var WORD_DETAIL = { "IDLE": "No stack running.", "READY": "Stack up. Exploration not armed." };

// A log time as epoch seconds: a number as it is, an ISO string parsed (dimOS writes UTC with
// a "Z"; without a zone it is the browser's local time), anything else null.
function tsSeconds(ts) {
  if (typeof ts === "number") return isFinite(ts) ? ts : null;
  if (typeof ts !== "string" || !/^\d{4}-\d{2}-\d{2}T/.test(ts)) return null;
  var t = Date.parse(ts);
  return isFinite(t) ? t / 1000 : null;
}

// minutes and seconds on the local clock: the log's hh:mm:ss without the hour
function minSec(ts) {
  var t = tsSeconds(ts);
  if (t === null) { var m = /\d{2}:(\d{2}:\d{2})/.exec(String(ts == null ? "" : ts)); return m ? m[1] : "--:--"; }
  var d = new Date(t * 1000);
  return pad2(d.getMinutes()) + ":" + pad2(d.getSeconds());
}

// The server's events as the feed's rows, newest on top, at most n: {seq, time, cls, label, text}.
// Ordered by seq when every event has one, else by position (the server sends oldest first).
// Anything that is not an object is dropped.
function decisionRows(events, n) {
  var list = (Array.isArray(events) ? events : []).filter(function (e) { return e && typeof e === "object"; });
  var bySeq = list.every(function (e) { return typeof e.seq === "number" && isFinite(e.seq); });
  var rows = list.map(function (e, i) {
    var k = String(e.kind == null ? "" : e.kind);
    return { at: bySeq ? e.seq : i, seq: bySeq ? e.seq : null, time: minSec(e.ts), cls: KIND_CLASS[k] || "",
             label: KIND_LABEL[k] || k.replace(/_/g, " ").toUpperCase() || "--",
             text: e.text == null ? "" : String(e.text) };
  });
  rows.sort(function (a, b) { return b.at - a.at; });
  return rows.slice(0, n).map(function (r) { delete r.at; return r; });
}

// Which rows are new since the previous answer, by what they say (time, kind, text; a repeat of
// the same line counted from the oldest), not by seq: {keys, fresh: [bool per row]}. prevKeys
// null (the first answer) flashes nothing; an answer with nothing in common with a non-empty
// previous one is a new run or a restarted server, and flashes nothing either.
function freshRows(rows, prevKeys) {
  var seen = {}, keys = [], fresh = [], i;
  for (i = rows.length - 1; i >= 0; i--) {
    var k = rows[i].time + "|" + rows[i].label + "|" + rows[i].text;
    seen[k] = (seen[k] || 0) + 1;
    keys[i] = k + "#" + seen[k];
  }
  var prev = {}, common = 0;
  (prevKeys || []).forEach(function (k) { prev[k] = true; });
  keys.forEach(function (k) { if (prev[k]) common++; });
  var flash = Array.isArray(prevKeys) && (prevKeys.length === 0 || common > 0);
  keys.forEach(function (k, j) { fresh[j] = flash && !prev[k]; });
  return { keys: keys, fresh: fresh };
}

// The feed's html; fresh[i] true makes row i flash once.
function decisionsHtml(rows, fresh) {
  return rows.map(function (r, i) {
    var cls = (r.cls + (fresh && fresh[i] ? " fresh" : "")).trim();
    return "<li" + (cls ? ' class="' + cls + '"' : "") + '><span class="t">' + esc(r.time) + '</span><span class="k">'
         + esc(r.label) + '</span><span class="x">' + esc(r.text) + "</span></li>";
  }).join("");
}

// The word for now as the page shows it: {word, cls, detail, since}. nowS is the server's clock
// now (epoch s), so the time since the word was set reads on the clock that stamped it.
function nowView(now, nowS) {
  if (!now || typeof now !== "object" || !now.word) return { word: "--", cls: "dim", detail: "", since: "" };
  var word = String(now.word).toUpperCase(), t = tsSeconds(now.since);
  return { word: word, cls: WORD_CLASS[word] || "",
           detail: now.detail ? String(now.detail) : (WORD_DETAIL[word] || ""),
           since: t !== null && typeof nowS === "number" && isFinite(nowS) ? "for " + dur(Math.max(0, nowS - t)) : "" };
}

// the server's clock now (no NTP in the field): its last state's ts plus the time since that answer
function serverNow() {
  return S.state && typeof S.state.ts === "number" ? S.state.ts + sinceState() : Date.now() / 1000;
}

function pollDecisions() {
  return fetchJSON("/decisions.json?n=" + DECISION_ROWS).then(function (d) {
    S.decisions = d || null;
    renderDecisions();
  }, function () {});
}

// An answer with an error and no events ({error}, the server's 500) says nothing about the
// decisions: the feed and its keys stay as they were, only the word and its detail say so.
function renderDecisions() {
  var d = S.decisions, nv, html = null;
  if (!d) return;
  if (d.__missing) {
    nv = { word: "--", cls: "dim", detail: "This cockpit server has no decision feed.", since: "" };
    html = '<li class="empty">No /decisions.json on this cockpit server.</li>';
  } else {
    nv = nowView(d.now, serverNow());
    if (d.error && !d.now) nv.detail = "Decision feed error: " + String(d.error);
    if (!d.error || Array.isArray(d.events)) {
      var rows = decisionRows(d.events, DECISION_ROWS), fr = freshRows(rows, S.decKeys);
      html = decisionsHtml(rows, fr.fresh);
      S.decKeys = fr.keys;
      if (!html) html = '<li class="empty">' + (stack().running ? "No decision yet." : "No stack, no decisions.") + "</li>";
    }
  }
  setText("now-word", nv.word);
  $("now-word").className = nv.cls;
  setText("now-detail", nv.detail);
  setText("now-since", nv.since);
  if (html !== null && html !== S.decHtml) { $("decisions").innerHTML = html; S.decHtml = html; }
}

// ---------------------------------------------------------------- go

if ("ResizeObserver" in window) new ResizeObserver(function () { resize(); if (!S.fitted) fitView(); }).observe(wrap);
window.addEventListener("resize", resize);
applyView(viewFor(window.URLSearchParams ? new URLSearchParams(location.search).get("view") : null, storedView(), window.innerWidth));
resize();
camConnectAll();
renderCamera();
loadPreflight();
fetchJSON("/launch.json").then(function (d) { if (d && d.running) { S.launchBusy = true; watchLaunch(); } }, function () {});
poller(pollState, POLL.state);
poller(pollMeta, POLL.meta);
poller(pollScan, POLL.scan);
poller(pollPath, POLL.path);
poller(pollLog, POLL.log);
poller(pollDecisions, POLL.decisions);