<script>
    (function () {
      function render(data) {
        var hb = data.status.last_heartbeat;
        document.getElementById("last-heartbeat").textContent = hb
          ? (hb.ok ? "ok" : "failed") + " at " + hb.at + " (" + hb.device_count + " devices)"
          : "never";
        var current = data.status.current_assignment;
        document.getElementById("current-assignment").textContent = current
          ? current.task_id + " on " + current.device_id + " (started " + current.started_at + ")"
          : "none";
        var progress = data.status.progress;
        document.getElementById("current-progress").textContent = progress
          ? "step " + progress.step_index + " \u2014 " + progress.step_status + ": " + progress.summary
          : "";
        var policy = data.status.host_policy;
        document.getElementById("host-policy").textContent = policy
          ? "revision " + policy.revision + "; self-submission "
            + (policy.self_submission_enabled ? "enabled" : "disabled")
            + "; max active tasks " + (policy.max_active_tasks || "unlimited")
            + "; daily token budget " + (policy.daily_token_budget || "unmetered")
          : "no Cloud policy cached";
        var body = document.getElementById("device-status-body");
        body.innerHTML = "";
        data.devices.forEach(function (device) {
          var row = document.createElement("tr");
          ["id", "name", "driver_type", "status"].forEach(function (key) {
            var cell = document.createElement("td");
            cell.textContent = device[key] || "";
            row.appendChild(cell);
          });
          body.appendChild(row);
        });
      }
      function poll() {
        fetch("/api/status", { credentials: "same-origin" })
          .then(function (response) { return response.ok ? response.json() : null; })
          .then(function (data) { if (data) render(data); })
          .catch(function () {});
      }
      setInterval(poll, 5000);
    })();
    </script>
