Skip to content
1        10        20        30        40        50        60        70        80        90        100       110       120       130       140       150       160       170       180       190       2001/* Ino console. The page talks only to this local console, which holds the2 * server key and forwards each call. Server-supplied text is always inserted3 * with textContent or attributes, never as HTML. */4(() => {5  "use strict";67  const SVG_NS = "http://www.w3.org/2000/svg";8  const NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;9  const POLL_MS = 15000;10  const FOLLOW_MS = 3000;11  const FEED_FOLLOW_MS = 5000;12  const RESTART_WAIT_MS = 90000;13  const ERROR_WORDS = /\b(error|errors|err|fatal|panic|exception|traceback|critical)\b/i;14  const WARNING_WORDS = /\b(warn|warning|warnings|fail|failed|failure)\b/i;15  const STAMP_PATTERN = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?Z /;1617  const ICONS = {18    eye: "M2 12s3.6-6.5 10-6.5S22 12 22 12s-3.6 6.5-10 6.5S2 12 2 12Z M12 9.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5Z",19    eyeOff: "M3 3l18 18 M10.6 6.1A10 10 0 0 1 12 5.5c6.5 0 10 6.5 10 6.5a17 17 0 0 1-3.1 3.7 M6.3 6.8A17 17 0 0 0 2 12s3.5 6.5 10 6.5c1.7 0 3.2-.4 4.5-1 M9.9 9.9a2.5 2.5 0 0 0 3.6 3.6",20    copy: "M9 9h10v11H9z M5 15V5h10",21    x: "M6 6l12 12 M18 6L6 18",22    plus: "M12 5v14 M5 12h14",23    play: "M8 5.5v13l10.5-6.5z",24    stop: "M7 7h10v10H7z",25    refresh: "M20 12a8 8 0 1 1-2.3-5.6 M20 4v4.5h-4.5",26  };2728  const state = {29    apps: [],30    view: "apps",31    filter: "all",32    query: "",33    selected: null,34    detail: null,35    tab: "env",36    env: null,37    logs: { tail: 100, follow: false, timer: null },38    feed: {39      app: "all",40      tail: 100,41      query: "",42      problems: false,43      follow: false,44      timer: null,45      run: 0,46      lines: [],47      notes: [],48      shown: [],49      updated: null,50    },51    exec: { history: [], last: null },52  };5354  const $ = (id) => document.getElementById(id);55  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));56  const appPath = (host) => `/apps/${encodeURIComponent(host)}`;57  const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;5859  // ---------- DOM helpers ----------6061  function el(tag, props = {}, ...children) {62    const node = document.createElement(tag);63    for (const [key, value] of Object.entries(props)) {64      if (value === undefined || value === null || value === false) continue;65      if (key === "class") node.className = value;66      else if (key === "text") node.textContent = value;67      else if (key === "value" || key === "checked") node[key] = value;68      else if (key.startsWith("on")) node.addEventListener(key.slice(2), value);69      else if (value === true) node.setAttribute(key, "");70      else node.setAttribute(key, String(value));71    }72    for (const child of children.flat()) {73      if (child === undefined || child === null || child === false) continue;74      node.append(child instanceof Node ? child : document.createTextNode(String(child)));75    }76    return node;77  }7879  function icon(name) {80    const svg = document.createElementNS(SVG_NS, "svg");81    const attributes = {82      viewBox: "0 0 24 24",83      width: 16,84      height: 16,85      fill: "none",86      stroke: "currentColor",87      "stroke-width": 1.8,88      "stroke-linecap": "round",89      "stroke-linejoin": "round",90      "aria-hidden": "true",91    };92    for (const [attribute, value] of Object.entries(attributes)) {93      svg.setAttribute(attribute, String(value));94    }95    const path = document.createElementNS(SVG_NS, "path");96    path.setAttribute("d", ICONS[name]);97    svg.append(path);98    return svg;99  }100101  /** Replaces a node's children. Conditional slots that evaluate to null are left out. */102  function fill(node, ...children) {103    node.replaceChildren(...children.filter((child) => child !== null && child !== undefined && child !== false));104  }105106  function fact(label, value, mono) {107    return el(108      "div",109      { class: "fact" },110      el("dt", {}, label),111      el("dd", { class: mono ? "mono" : "" }, value),112    );113  }114115  function toast(message, kind = "ok") {116    const node = el("div", { class: "toast", role: "status", "data-kind": kind, text: message });117    $("toasts").append(node);118    setTimeout(() => node.classList.add("leaving"), 4200);119    setTimeout(() => node.remove(), 4600);120  }121122  function setLink(level, text) {123    $("link-state").dataset.state = level;124    $("link-text").textContent = text;125  }126127  async function copyText(text, message = "Copied.") {128    try {129      await navigator.clipboard.writeText(text);130      toast(message);131    } catch {132      toast("Could not copy. Select the text and copy it by hand.", "warn");133    }134  }135136  // ---------- API ----------137138  class ApiError extends Error {139    constructor(status, code, message) {140      super(message);141      this.status = status;142      this.code = code;143    }144  }145146  /** Calls the server through the console. `root` is `/api/v1` unless a console route is named. */147  async function api(path, { method = "GET", body, root = "/api/v1" } = {}) {148    const headers = {};149    const init = { method, headers, cache: "no-store" };150    if (body !== undefined) {151      headers["content-type"] = "application/json";152      init.body = JSON.stringify(body);153    }154    let response;155    try {156      response = await fetch(`${root}${path}`, init);157    } catch {158      throw new ApiError(0, "console_offline", "The console stopped responding. Check the terminal running ino once server ui.");159    }160    const text = await response.text();161    let data = null;162    if (text) {163      try {164        data = JSON.parse(text);165      } catch {166        data = null;167      }168    }169    if (!response.ok) {170      const error = (data && data.error) || {};171      throw new ApiError(172        response.status,173        error.code || `http_${response.status}`,174        error.message || response.statusText || "The request failed.",175      );176    }177    return data;178  }179180  function linkLevelFor(error) {181    switch (error.code) {182      case "console_offline":183        return ["error", "Console offline"];184      case "server_unreachable":185        return ["warn", "Server unreachable"];186      case "unauthorized":187        return ["error", "Key rejected by server"];188      default:189        return ["ok", "Connected"];190    }191  }192193  function reportError(error, { quiet = false } = {}) {194    const [level, text] = linkLevelFor(error);195    setLink(level, text);196    if (!quiet) toast(error.message || "Something went wrong.", "error");197  }198199  /** The server replaced itself while the request was in flight. Wait for it to answer again. */200  async function waitForServer() {201    setLink("warn", "Server restarting…");202    const started = Date.now();203    while (Date.now() - started < RESTART_WAIT_MS) {204      await sleep(2000);205      try {206        await api("/apps");207        setLink("ok", "Connected");208        return true;209      } catch {210        // Keep waiting until the replacement container answers.211      }212    }213    setLink("error", "Server did not come back");214    return false;215  }216217  async function recoverFromRestart(error) {218    if (error.code !== "server_unreachable") return false;219    if (await waitForServer()) {220      toast("The server restarted and is answering again.");221      await refreshAll();222    }223    return true;224  }225226  // ---------- Loading ----------227228  async function loadSession() {229    try {230      const response = await fetch("/_console/session", { cache: "no-store" });231      if (!response.ok) return;232      const data = await response.json();233      $("server-line").textContent = `Managing ${data.server}`;234    } catch {235      // The tagline stays generic; the link indicator reports real failures.236    }237  }238239  async function pulse() {240    try {241      const response = await fetch("/up", { cache: "no-store" });242      if (!response.ok) {243        setLink("warn", "Server unreachable");244        return;245      }246    } catch {247      setLink("error", "Console offline");248      return;249    }250    await loadApps({ quiet: true });251  }252253  async function loadApps({ quiet = false } = {}) {254    try {255      const apps = await api("/apps");256      state.apps = apps;257      setLink("ok", "Connected");258      renderRail();259      if (state.view === "logs") renderFeedSources();260      if (state.selected && state.detail) {261        const summary = apps.find((app) => app.host === state.selected);262        if (summary) {263          Object.assign(state.detail, summary);264          renderHeader();265          if (state.tab === "overview") renderDetail();266        } else {267          toast(`${state.detail.name} is no longer on the server.`, "warn");268          clearSelection();269        }270      }271    } catch (error) {272      reportError(error, { quiet });273    }274  }275276  async function refreshSelected() {277    const host = state.selected;278    if (!host) return;279    try {280      const detail = await api(appPath(host));281      if (state.selected !== host) return;282      state.detail = detail;283      renderDetail();284    } catch (error) {285      if (!(await recoverFromRestart(error))) reportError(error);286    }287  }288289  async function refreshAll() {290    await loadApps({ quiet: true });291    await refreshSelected();292  }293294  // ---------- Rail ----------295296  function versionOf(image) {297    const leaf = image.split("@")[0].split("/").pop() || "";298    const colon = leaf.lastIndexOf(":");299    return colon === -1 ? "latest" : leaf.slice(colon + 1);300  }301302  function appCard(app) {303    return el(304      "li",305      {},306      el(307        "button",308        {309          class: "app-card",310          type: "button",311          "aria-current": String(app.host === state.selected),312          onclick: () => selectApp(app.host),313        },314        el("span", { class: "bloom", "data-running": String(app.running), "aria-hidden": "true" }),315        el(316          "span",317          { class: "app-text" },318          el("span", { class: "name" }, app.name, app.isServer ? el("span", { class: "tag" }, "server") : null),319          el("span", { class: "host" }, app.host),320        ),321        el("span", { class: "version" }, versionOf(app.image)),322      ),323    );324  }325326  /** Apps in rail order: the Ino server last, then by name and host. */327  function sortApps(apps) {328    return [...apps].sort((a, b) => Number(a.isServer) - Number(b.isServer) || a.name.localeCompare(b.name) || a.host.localeCompare(b.host));329  }330331  function renderRail() {332    const running = state.apps.filter((app) => app.running).length;333    $("count-all").textContent = String(state.apps.length);334    $("count-running").textContent = String(running);335    $("count-stopped").textContent = String(state.apps.length - running);336337    const query = state.query.trim().toLowerCase();338    const visible = sortApps(339      state.apps340        .filter((app) => state.filter === "all" || (state.filter === "running") === app.running)341        .filter((app) => {342          if (!query) return true;343          return [app.name, app.host, app.image].some((field) => field.toLowerCase().includes(query));344        }),345    );346347    $("app-list").replaceChildren(...visible.map(appCard));348    const empty = $("rail-empty");349    empty.hidden = visible.length > 0;350    empty.textContent = state.apps.length === 0351      ? "No apps yet. Plant one with New app."352      : "Nothing matches this view.";353  }354355  // ---------- Selection and header ----------356357  function selectApp(host) {358    state.selected = host;359    state.detail = null;360    state.env = null;361    $("welcome").hidden = true;362    $("detail").hidden = false;363    $("detail-eyebrow").textContent = "App";364    $("detail-name").textContent = host;365    $("detail-url").removeAttribute("href");366    $("detail-url").textContent = "";367    $("detail-status").textContent = "";368    $("detail-status").removeAttribute("data-running");369    $("panel").replaceChildren(el("p", { class: "muted" }, "Loading…"));370    renderRail();371    loadSelection(host);372  }373374  async function loadSelection(host) {375    try {376      const [detail, environment] = await Promise.all([377        api(appPath(host)),378        api(`${appPath(host)}/env`),379      ]);380      if (state.selected !== host) return;381      state.detail = detail;382      state.env = makeEditor(environment);383      renderDetail();384    } catch (error) {385      if (state.selected === host) reportError(error);386    }387  }388389  function clearSelection() {390    state.selected = null;391    state.detail = null;392    state.env = null;393    syncFollow();394    $("detail").hidden = true;395    $("welcome").hidden = false;396    renderRail();397  }398399  function renderHeader() {400    const detail = state.detail;401    if (!detail) return;402    $("detail-eyebrow").textContent = detail.isServer ? "Ino server" : "App";403    $("detail-name").textContent = detail.name;404    const link = $("detail-url");405    if (detail.url) {406      link.href = detail.url;407      link.textContent = detail.url.replace(/^https?:\/\//, "");408    } else {409      link.removeAttribute("href");410      link.textContent = `${detail.host} · no public address`;411    }412    const status = $("detail-status");413    status.dataset.running = String(detail.running);414    status.textContent = detail.running ? "Running" : "Stopped";415  }416417  function renderDetail() {418    const detail = state.detail;419    if (!detail) return;420    renderHeader();421    document.querySelectorAll(".tab").forEach((tab) => {422      tab.setAttribute("aria-selected", String(tab.dataset.tab === state.tab));423    });424    const panel = $("panel");425    syncFollow();426    switch (state.tab) {427      case "overview":428        return renderOverview(panel, detail);429      case "logs":430        return renderLogs(panel);431      case "console":432        return renderConsole(panel, detail);433      case "settings":434        return renderSettings(panel, detail);435      default:436        return state.env ? renderEnv(panel, detail) : undefined;437    }438  }439440  // ---------- Environment ----------441442  let rowSeq = 0;443444  function newRow(key = "", value = "") {445    rowSeq += 1;446    return { id: rowSeq, key, value, error: "", nodes: null };447  }448449  function makeEditor(data, reveal = false) {450    const entries = Object.entries(data.env || {}).sort(([a], [b]) => a.localeCompare(b));451    return {452      original: Object.fromEntries(entries),453      reserved: new Set(data.reserved || []),454      rows: entries.map(([key, value]) => newRow(key, value)),455      reveal,456      saving: false,457    };458  }459460  /** Validates every row and reports what would be saved. */461  function analyze(editor) {462    const counts = new Map();463    for (const row of editor.rows) {464      if (row.key) counts.set(row.key, (counts.get(row.key) || 0) + 1);465    }466    const env = {};467    let problems = 0;468    for (const row of editor.rows) {469      let message = "";470      const blank = row.key === "" && row.value === "";471      if (!blank) {472        if (!row.key) message = "Give this variable a name.";473        else if (row.key.length > 128 || !NAME_PATTERN.test(row.key)) {474          message = "Use letters, digits and underscores, and do not start with a digit.";475        } else if (editor.reserved.has(row.key)) message = "Ino manages this one, so it cannot be set here.";476        else if (counts.get(row.key) > 1) message = "This name appears more than once.";477        else if (row.value.includes("\u0000")) message = "Values cannot contain NUL characters.";478      }479      row.error = message;480      if (message) problems += 1;481      else if (row.key) env[row.key] = row.value;482    }483    const changes = countChanges(editor.original, env);484    return { env, problems, changes };485  }486487  function countChanges(original, env) {488    const keys = new Set([...Object.keys(original), ...Object.keys(env)]);489    let changed = 0;490    for (const key of keys) {491      if (original[key] !== env[key]) changed += 1;492    }493    return changed;494  }495496  function rowIsDirty(editor, row) {497    if (!row.key) return row.value !== "";498    return editor.original[row.key] !== row.value;499  }500501  function refreshEnv() {502    const editor = state.env;503    if (!editor || !$("env-list")) return;504    const result = analyze(editor);505    for (const row of editor.rows) {506      const nodes = row.nodes;507      if (!nodes) continue;508      nodes.error.textContent = row.error;509      nodes.root.classList.toggle("invalid", Boolean(row.error));510      nodes.root.classList.toggle("dirty", !row.error && rowIsDirty(editor, row));511    }512    const summary = $("env-summary");513    if (result.problems) {514      summary.textContent = `${plural(result.problems, "line")} to fix`;515    } else if (result.changes) {516      summary.replaceChildren(517        el("strong", {}, String(result.changes)),518        ` unsaved ${result.changes === 1 ? "change" : "changes"}`,519      );520    } else {521      summary.textContent = "Everything is saved.";522    }523    summary.dataset.dirty = String(result.changes > 0 && result.problems === 0);524    const running = state.detail ? state.detail.running : false;525    $("env-save").disabled = result.problems > 0 || result.changes === 0 || editor.saving || !running;526    $("env-discard").disabled = result.changes === 0 || editor.saving;527  }528529  function buildRow(editor, row) {530    const keyInput = el("input", {531      class: "key",532      value: row.key,533      placeholder: "NAME",534      spellcheck: "false",535      autocomplete: "off",536      autocapitalize: "off",537      "aria-label": "Variable name",538      oninput: (event) => {539        row.key = event.target.value;540        refreshEnv();541      },542    });543    const valueInput = el("input", {544      type: editor.reveal ? "text" : "password",545      value: row.value,546      placeholder: "value",547      spellcheck: "false",548      autocomplete: "off",549      autocapitalize: "off",550      "aria-label": "Variable value",551      oninput: (event) => {552        row.value = event.target.value;553        refreshEnv();554      },555    });556    const revealButton = el(557      "button",558      {559        class: "icon-btn",560        type: "button",561        title: "Show or hide this value",562        "aria-label": "Show or hide this value",563        onclick: () => {564          valueInput.type = valueInput.type === "password" ? "text" : "password";565          revealButton.querySelector("path").setAttribute("d", valueInput.type === "password" ? ICONS.eye : ICONS.eyeOff);566        },567      },568      icon("eye"),569    );570    const root = el(571      "div",572      { class: "env-row" },573      el("div", { class: "field-control" }, keyInput),574      el("div", { class: "field-control value" }, valueInput, revealButton),575      el(576        "div",577        { class: "actions" },578        el("button", {579          class: "icon-btn",580          type: "button",581          title: "Copy value",582          "aria-label": "Copy value",583          onclick: () => copyText(row.value),584        }, icon("copy")),585        el("button", {586          class: "icon-btn danger",587          type: "button",588          title: "Remove variable",589          "aria-label": "Remove variable",590          onclick: () => removeEnvRow(row.id),591        }, icon("x")),592      ),593      el("p", { class: "row-error", "aria-live": "polite" }),594    );595    row.nodes = { root, keyInput, valueInput, error: root.querySelector(".row-error") };596    return root;597  }598599  function renderEnvRows() {600    const editor = state.env;601    const list = $("env-list");602    if (!editor || !list) return;603    if (editor.rows.length === 0) {604      list.replaceChildren(el("div", { class: "env-empty" }, "No variables yet. Add one, or paste a .env file."));605    } else {606      list.replaceChildren(...editor.rows.map((row) => buildRow(editor, row)));607    }608    refreshEnv();609  }610611  function addEnvRow() {612    const row = newRow();613    state.env.rows.push(row);614    renderEnvRows();615    row.nodes.keyInput.focus();616  }617618  function removeEnvRow(id) {619    state.env.rows = state.env.rows.filter((row) => row.id !== id);620    renderEnvRows();621  }622623  /** Parses .env-style lines. Comments and blank lines are skipped; malformed lines are reported. */624  function parseEnvText(text) {625    const pairs = [];626    for (const raw of text.split(/\r?\n/)) {627      let line = raw.trim();628      if (!line || line.startsWith("#")) continue;629      if (line.startsWith("export ")) line = line.slice("export ".length).trim();630      const separator = line.indexOf("=");631      if (separator < 1) {632        pairs.push({ error: raw });633        continue;634      }635      const key = line.slice(0, separator).trim();636      let value = line.slice(separator + 1).trim();637      if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.at(-1) === value[0]) {638        value = value.slice(1, -1);639      }640      pairs.push({ key, value });641    }642    return pairs;643  }644645  function importEnv(text) {646    const editor = state.env;647    const pairs = parseEnvText(text);648    let added = 0;649    let updated = 0;650    let skipped = 0;651    for (const pair of pairs) {652      if (pair.error !== undefined) {653        skipped += 1;654        continue;655      }656      const existing = editor.rows.find((row) => row.key === pair.key);657      if (existing) {658        existing.value = pair.value;659        updated += 1;660      } else {661        editor.rows.push(newRow(pair.key, pair.value));662        added += 1;663      }664    }665    $("env-paste-text").value = "";666    $("env-paste").hidden = true;667    renderEnvRows();668    const message = `Imported ${added} new and ${updated} updated${skipped ? `; skipped ${skipped} line${skipped === 1 ? "" : "s"} without NAME=value` : ""}.`;669    toast(message, skipped ? "warn" : "ok");670  }671672  function renderEnv(panel, detail) {673    const editor = state.env;674    fill(675      panel,676      el("p", { class: "panel-intro" }, "Each variable is stored on the app. Saving redeploys it with the new set, and its image stays as it is."),677      detail.isServer678        ? el("p", { class: "note" }, "This is the Ino server. Saving restarts it, so the connection may pause briefly.")679        : null,680      detail.running681        ? null682        : el("p", { class: "note quiet" }, "This app is stopped. Start it from Overview before changing its variables."),683      el(684        "div",685        { class: "env-toolbar" },686        el(687          "div",688          { class: "left" },689          el("button", { class: "btn small", type: "button", onclick: addEnvRow }, icon("plus"), "Add variable"),690          el("button", {691            class: "btn small ghost",692            type: "button",693            onclick: () => {694              const paste = $("env-paste");695              paste.hidden = !paste.hidden;696              if (!paste.hidden) $("env-paste-text").focus();697            },698          }, "Paste .env"),699        ),700        el(701          "label",702          { class: "switch" },703          el("input", {704            type: "checkbox",705            checked: editor.reveal,706            onchange: (event) => {707              editor.reveal = event.target.checked;708              for (const row of editor.rows) {709                if (row.nodes) row.nodes.valueInput.type = editor.reveal ? "text" : "password";710              }711            },712          }),713          "Show values",714        ),715      ),716      el(717        "div",718        { class: "paste", id: "env-paste", hidden: true },719        el("span", { class: "muted" }, "Paste NAME=value lines. Matching names are updated and everything else is kept."),720        el("textarea", {721          id: "env-paste-text",722          rows: 6,723          spellcheck: "false",724          placeholder: "DATABASE_URL=postgres://…\n# comments are skipped\nexport API_TOKEN=\"quoted value\"",725        }),726        el(727          "div",728          { class: "paste-actions" },729          el("button", {730            class: "btn ghost small",731            type: "button",732            onclick: () => {733              $("env-paste").hidden = true;734            },735          }, "Close"),736          el("button", {737            class: "btn primary small",738            type: "button",739            onclick: () => importEnv($("env-paste-text").value),740          }, "Import"),741        ),742      ),743      el("div", { class: "env-head" }, el("span", {}, "Name"), el("span", {}, "Value"), el("span", {}, "")),744      el("div", { class: "env-list", id: "env-list" }),745      el(746        "div",747        { class: "env-footer" },748        el("span", { class: "summary", id: "env-summary" }),749        el(750          "div",751          { class: "lifecycle" },752          el("button", { class: "btn ghost", type: "button", id: "env-discard", onclick: discardEnv }, "Discard"),753          el("button", { class: "btn primary", type: "button", id: "env-save", onclick: saveEnv }, "Save and redeploy"),754        ),755      ),756    );757    renderEnvRows();758  }759760  function discardEnv() {761    const editor = state.env;762    state.env = makeEditor({ env: editor.original, reserved: [...editor.reserved] }, editor.reveal);763    renderDetail();764  }765766  async function saveEnv() {767    const editor = state.env;768    const host = state.selected;769    const result = analyze(editor);770    if (result.problems) {771      toast("Fix the highlighted variables first.", "warn");772      return;773    }774    if (!result.changes) return;775    editor.saving = true;776    refreshEnv();777    try {778      const saved = await api(`${appPath(host)}/env`, { method: "PUT", body: { env: result.env } });779      if (state.selected !== host) return;780      state.env = makeEditor(saved, editor.reveal);781      renderDetail();782      toast(`Saved. ${state.detail.name} is redeployed with ${plural(Object.keys(result.env).length, "variable")}.`);783      loadApps({ quiet: true });784    } catch (error) {785      if (error.code === "application_state_conflict") {786        toast("Start the app before changing its variables.", "warn");787      } else if (!(await recoverFromRestart(error))) {788        toast(error.message, "error");789      }790    } finally {791      editor.saving = false;792      refreshEnv();793    }794  }795796  // ---------- Overview ----------797798  async function lifecycle(action) {799    const detail = state.detail;800    if (!detail) return;801    const past = { start: "Started", stop: "Stopped", restart: "Restarted" }[action];802    try {803      await api(`${appPath(detail.host)}/${action}`, { method: "POST" });804      toast(`${past} ${detail.name}.`);805      await refreshAll();806    } catch (error) {807      if (!(await recoverFromRestart(error))) toast(error.message, "error");808    }809  }810811  function renderOverview(panel, detail) {812    const serverNote = detail.isServer813      ? "The Ino server cannot start, stop or remove itself. Use the ino command on the VPS for that."814      : null;815    fill(816      panel,817      el("p", { class: "panel-intro" }, "How this app is running right now. Variables, settings and logs have their own tabs."),818      el(819        "dl",820        { class: "facts" },821        fact("Image", detail.image, true),822        fact("Address", detail.url ? detail.url.replace(/^https?:\/\//, "") : "Not published", true),823        fact("Image updates", detail.autoUpdate ? "Follow the image" : "Manual", false),824        fact("HTTPS", detail.disableTLS ? "Off" : "On", false),825        fact("CPUs", detail.resources.cpus ? String(detail.resources.cpus) : "No limit", false),826        fact("Memory", detail.resources.memoryMB ? `${detail.resources.memoryMB} MB` : "No limit", false),827        fact(828          "Backups",829          detail.backup.path830            ? `${detail.backup.path}${detail.backup.autoBackup ? " · automatic" : ""}`831            : "Not configured",832          true,833        ),834      ),835      el("h3", {}, "Lifecycle"),836      el(837        "div",838        { class: "lifecycle" },839        el("button", {840          class: "btn",841          type: "button",842          disabled: detail.isServer || detail.running,843          onclick: () => lifecycle("start"),844        }, icon("play"), "Start"),845        el("button", {846          class: "btn",847          type: "button",848          disabled: detail.isServer || !detail.running,849          onclick: () => lifecycle("stop"),850        }, icon("stop"), "Stop"),851        el("button", {852          class: "btn",853          type: "button",854          disabled: detail.isServer || !detail.running,855          onclick: () => lifecycle("restart"),856        }, icon("refresh"), "Restart"),857        serverNote ? el("span", { class: "hint" }, serverNote) : null,858      ),859    );860  }861862  // ---------- Logs ----------863864  function syncFollow() {865    clearInterval(state.logs.timer);866    state.logs.timer = null;867    if (state.view === "apps" && state.tab === "logs" && state.logs.follow && state.selected) {868      state.logs.timer = setInterval(fetchLogs, FOLLOW_MS);869    }870  }871872  function renderLogs(panel) {873    fill(874      panel,875      el(876        "div",877        { class: "toolbar" },878        el(879          "select",880          {881            class: "select",882            "aria-label": "Number of lines",883            onchange: (event) => {884              state.logs.tail = Number(event.target.value);885              fetchLogs();886            },887          },888          ...[100, 300, 500].map((count) =>889            el("option", { value: count, selected: count === state.logs.tail }, `Last ${count} lines`),890          ),891        ),892        el("button", { class: "btn small ghost", type: "button", onclick: fetchLogs }, icon("refresh"), "Refresh"),893        el(894          "label",895          { class: "switch" },896          el("input", {897            type: "checkbox",898            checked: state.logs.follow,899            onchange: (event) => {900              state.logs.follow = event.target.checked;901              syncFollow();902              if (state.logs.follow) fetchLogs();903            },904          }),905          "Follow",906        ),907      ),908      el("p", { class: "muted", id: "log-note" }),909      el("pre", { class: "terminal", id: "log-output", "aria-label": "Application logs" }),910    );911    fetchLogs();912  }913914  async function fetchLogs() {915    const host = state.selected;916    if (!host) return;917    try {918      const data = await api(`${appPath(host)}/logs?tail=${state.logs.tail}`);919      const output = $("log-output");920      if (state.selected !== host || !output) return;921      const pinned = output.scrollTop + output.clientHeight >= output.scrollHeight - 24;922      output.textContent = data.output || "";923      $("log-note").textContent = data.truncated924        ? "Showing the newest output. Older lines were cut to keep the response small."925        : "";926      if (state.logs.follow || pinned) output.scrollTop = output.scrollHeight;927    } catch (error) {928      if (!(await recoverFromRestart(error))) reportError(error, { quiet: state.logs.follow });929    }930  }931932  // ---------- Views ----------933934  function setView(view) {935    state.view = view;936    document.querySelectorAll(".view").forEach((tab) => {937      tab.setAttribute("aria-selected", String(tab.dataset.view === view));938    });939    $("view-apps").hidden = view !== "apps";940    $("view-deploy").hidden = view !== "deploy";941    $("view-logs").hidden = view !== "logs";942    syncFollow();943    syncFeedFollow();944    if (view === "logs") {945      renderFeedSources();946      fetchFeed();947    }948  }949950  /** Refreshes what the current view shows. */951  async function refreshCurrent() {952    if (state.view === "logs") {953      await loadApps({ quiet: true });954      await fetchFeed();955    } else {956      await refreshAll();957    }958  }959960  // ---------- All logs ----------961962  function syncFeedFollow() {963    clearInterval(state.feed.timer);964    state.feed.timer = null;965    if (state.view === "logs" && state.feed.follow) {966      state.feed.timer = setInterval(fetchFeed, FEED_FOLLOW_MS);967    }968  }969970  /** Lists every app, the Ino server included, in the source picker. Keeps the picked app when it still exists. */971  function renderFeedSources() {972    const select = $("feed-app");973    const apps = sortApps(state.apps);974    const signature = apps.map((app) => app.host).join("\n");975    if (select.dataset.signature !== signature) {976      select.dataset.signature = signature;977      select.replaceChildren(978        el("option", { value: "all" }, "All apps"),979        ...apps.map((app) => el("option", { value: app.host }, app.isServer ? `${app.name} · Ino server` : app.name)),980      );981    }982    if (state.feed.app !== "all" && !apps.some((app) => app.host === state.feed.app)) {983      state.feed.app = "all";984      fetchFeed();985    }986    select.value = state.feed.app;987  }988989  /** Splits one app's output into lines. The trailing newline does not start an extra line. */990  function splitLines(output) {991    if (!output) return [];992    return output.replace(/\r?\n$/, "").split(/\r?\n/);993  }994995  /** Takes the RFC 3339 time Docker puts in front of a line. Servers that predate timestamps send none. */996  function splitStamp(line) {997    const match = STAMP_PATTERN.exec(line);998    if (!match) return { time: null, text: line };999    const millis = Date.parse(`${match[1]}Z`) + Number(`${match[2] || ""}000`.slice(0, 3));1000    return { time: millis, text: line.slice(match[0].length) };1001  }10021003  /** Shows the clock time, with the date when the line is not from today. */1004  function formatStamp(millis) {1005    const date = new Date(millis);1006    const clock = date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false });1007    const day = date.toDateString() === new Date().toDateString()1008      ? ""1009      : `${date.toLocaleDateString([], { month: "short", day: "numeric" })} `;1010    return `${day}${clock}.${String(date.getMilliseconds()).padStart(3, "0")}`;1011  }10121013  function levelOf(text) {1014    if (ERROR_WORDS.test(text)) return "error";1015    if (WARNING_WORDS.test(text)) return "warn";1016    return "";1017  }10181019  /** Reads the tail of each selected app's logs. Each app is read on its own, so one failure does not hide the rest. */1020  async function fetchFeed() {1021    if (state.view !== "logs") return;1022    const { app, tail } = state.feed;1023    const run = state.feed.run + 1;1024    state.feed.run = run;1025    const targets = sortApps(state.apps).filter((item) => app === "all" || item.host === app);1026    $("feed-status").textContent = "Loading…";1027    if (targets.length === 0) {1028      state.feed.lines = [];1029      state.feed.notes = [];1030      state.feed.updated = new Date();1031      renderFeed();1032      return;1033    }10341035    const results = await Promise.allSettled(1036      targets.map((item) => api(`${appPath(item.host)}/logs?tail=${tail}&timestamps=true`)),1037    );1038    if (run !== state.feed.run || state.view !== "logs") return;10391040    const lines = [];1041    const notes = [];1042    let unreachable = null;1043    results.forEach((result, index) => {1044      const item = targets[index];1045      if (result.status === "rejected") {1046        if (result.reason.code === "server_unreachable") unreachable = result.reason;1047        notes.push(`${item.name} could not be read: ${result.reason.message}`);1048        return;1049      }1050      if (result.value.truncated) {1051        notes.push(`${item.name} shows its newest output; older lines were cut to keep the response small.`);1052      }1053      // An untimed line takes the time of the line before it, so it stays in place.1054      let time = 0;1055      for (const raw of splitLines(result.value.output)) {1056        const stamp = splitStamp(raw);1057        if (stamp.time !== null) time = stamp.time;1058        lines.push({1059          app: item.host,1060          label: item.name,1061          time,1062          known: stamp.time !== null,1063          text: stamp.text,1064          level: levelOf(stamp.text),1065        });1066      }1067    });1068    if (unreachable && (await recoverFromRestart(unreachable))) return;1069    // Apps are merged oldest first. The sort is stable, so untimed lines keep their app order.1070    lines.sort((a, b) => a.time - b.time);10711072    const failure = results.find((result) => result.status === "rejected");1073    if (failure) reportError(failure.reason, { quiet: true });1074    state.feed.lines = lines;1075    state.feed.notes = notes;1076    state.feed.updated = new Date();1077    renderFeed();1078  }10791080  /** Wraps each case-insensitive match of the search in a mark element. */1081  function highlight(text, needle) {1082    if (!needle) return [text];1083    const lower = text.toLowerCase();1084    // Lowercasing can change the length of some characters, which would shift the matches.1085    if (lower.length !== text.length) return [text];1086    const parts = [];1087    let cursor = 0;1088    let index = lower.indexOf(needle);1089    while (index !== -1) {1090      if (index > cursor) parts.push(text.slice(cursor, index));1091      parts.push(el("mark", {}, text.slice(index, index + needle.length)));1092      cursor = index + needle.length;1093      index = lower.indexOf(needle, cursor);1094    }1095    if (cursor < text.length) parts.push(text.slice(cursor));1096    return parts;1097  }10981099  function feedLine(line, needle) {1100    return el(1101      "div",1102      { class: "feed-line", "data-level": line.level },1103      el("span", { class: "feed-time" }, line.known ? formatStamp(line.time) : ""),1104      el("span", { class: "feed-app", title: line.label }, line.label),1105      el("span", { class: "feed-text" }, highlight(line.text, needle)),1106    );1107  }11081109  /** Applies the search and level filters to the fetched lines. Nothing is fetched again. */1110  function renderFeed() {1111    const { lines, notes, query, problems, updated } = state.feed;1112    const needle = query.trim().toLowerCase();1113    const shown = lines.filter(1114      (line) => (!problems || line.level !== "") && (!needle || line.text.toLowerCase().includes(needle)),1115    );1116    state.feed.shown = shown;11171118    const output = $("feed-output");1119    const pinned = output.scrollTop + output.clientHeight >= output.scrollHeight - 24;1120    output.replaceChildren(...shown.map((line) => feedLine(line, needle)));1121    if (shown.length === 0) {1122      let message = "No lines match this filter.";1123      if (state.apps.length === 0) message = "No apps yet. Logs show up here once an app is planted.";1124      else if (lines.length === 0) message = "No log lines yet.";1125      output.append(el("p", { class: "feed-empty" }, message));1126    }1127    if (state.feed.follow || pinned) output.scrollTop = output.scrollHeight;11281129    $("feed-status").textContent = updated1130      ? `${shown.length} of ${plural(lines.length, "line")} shown · updated ${updated.toLocaleTimeString()}`1131      : "";1132    const note = $("feed-note");1133    note.hidden = notes.length === 0;1134    note.textContent = notes.join(" ");1135  }11361137  function copyShownLines() {1138    const shown = state.feed.shown;1139    if (shown.length === 0) {1140      toast("No lines to copy.", "warn");1141      return;1142    }1143    const text = shown1144      .map((line) => `${line.known ? `${formatStamp(line.time)} ` : ""}${line.label} ${line.text}`)1145      .join("\n");1146    copyText(text, `Copied ${plural(shown.length, "line")}.`);1147  }11481149  function initFeed() {1150    $("feed-search").addEventListener("input", (event) => {1151      state.feed.query = event.target.value;1152      renderFeed();1153    });1154    $("feed-search").addEventListener("keydown", (event) => {1155      if (event.key === "Escape" && event.target.value) {1156        event.target.value = "";1157        state.feed.query = "";1158        renderFeed();1159      }1160    });1161    document.querySelectorAll("#view-logs .chip").forEach((chip) => {1162      chip.addEventListener("click", () => {1163        state.feed.problems = chip.dataset.level === "problems";1164        document.querySelectorAll("#view-logs .chip").forEach((other) => {1165          other.setAttribute("aria-pressed", String(other === chip));1166        });1167        renderFeed();1168      });1169    });1170    $("feed-app").addEventListener("change", (event) => {1171      state.feed.app = event.target.value;1172      fetchFeed();1173    });1174    $("feed-tail").addEventListener("change", (event) => {1175      state.feed.tail = Number(event.target.value);1176      fetchFeed();1177    });1178    $("feed-refresh").addEventListener("click", refreshCurrent);1179    $("feed-copy").addEventListener("click", copyShownLines);1180    $("feed-follow").addEventListener("change", (event) => {1181      state.feed.follow = event.target.checked;1182      syncFeedFollow();1183      if (state.feed.follow) fetchFeed();1184    });1185  }11861187  function initViews() {1188    document.querySelectorAll(".view").forEach((tab) => {1189      tab.addEventListener("click", () => setView(tab.dataset.view));1190    });1191  }11921193  // ---------- Console (exec) ----------11941195  /** Splits a command line on whitespace, honouring single and double quotes. */1196  function tokenize(line) {1197    return (line.match(/"[^"]*"|'[^']*'|\S+/g) || []).map((part) => {1198      const quoted = part.length >= 2 && (part[0] === '"' || part[0] === "'") && part.at(-1) === part[0];1199      return quoted ? part.slice(1, -1) : part;1200    });1201  }12021203  async function runExec(host, line) {1204    const command = tokenize(line);1205    if (!command.length) return;1206    const node = $("exec-result");1207    if (node) node.replaceChildren(el("p", { class: "muted" }, "Running…"));1208    try {1209      const data = await api(`${appPath(host)}/exec`, { method: "POST", body: { command } });1210      state.exec.last = { host, line, ...data };1211    } catch (error) {1212      if (await recoverFromRestart(error)) return;1213      state.exec.last = { host, line, error: error.message };1214    }1215    renderExecResult();1216  }12171218  function renderExecResult() {1219    const node = $("exec-result");1220    if (!node) return;1221    const last = state.exec.last;1222    if (!last || last.host !== state.selected) {1223      node.replaceChildren();1224      return;1225    }1226    if (last.error) {1227      node.replaceChildren(el("p", { class: "note" }, last.error));1228      return;1229    }1230    fill(1231      node,1232      el(1233        "div",1234        { class: "result-meta" },1235        el("span", { class: "code-badge", "data-ok": String(last.exitCode === 0) }, `exit ${last.exitCode}`),1236        el("span", { class: "mono" }, last.line),1237        last.truncated ? el("span", {}, "· output trimmed") : null,1238      ),1239      el("pre", { class: "terminal", "aria-label": "Standard output" }, last.stdout || null),1240      last.stderr ? el("pre", { class: "terminal stderr", "aria-label": "Standard error" }, last.stderr) : null,1241    );1242  }12431244  function renderConsole(panel, detail) {1245    const input = el("input", {1246      placeholder: "ls /storage",1247      "aria-label": "Command to run",1248      spellcheck: "false",1249      autocomplete: "off",1250      autocapitalize: "off",1251    });1252    let cursor = state.exec.history.length;1253    input.addEventListener("keydown", (event) => {1254      if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return;1255      event.preventDefault();1256      const step = event.key === "ArrowUp" ? -1 : 1;1257      cursor = Math.min(state.exec.history.length, Math.max(0, cursor + step));1258      input.value = state.exec.history[cursor] ?? "";1259    });1260    const host = detail.host;1261    fill(1262      panel,1263      el("p", { class: "panel-intro" }, "Runs one command inside this app's container, without a terminal. Quote arguments that contain spaces."),1264      detail.running ? null : el("p", { class: "note quiet" }, "Start the app to run commands in it."),1265      el(1266        "form",1267        {1268          class: "exec-line",1269          onsubmit: (event) => {1270            event.preventDefault();1271            const line = input.value.trim();1272            if (!line) return;1273            state.exec.history.push(line);1274            cursor = state.exec.history.length;1275            input.value = "";1276            runExec(host, line);1277          },1278        },1279        el("span", { class: "prompt", "aria-hidden": "true" }, "$"),1280        input,1281        el("button", { class: "btn primary small", type: "submit", disabled: !detail.running }, "Run"),1282      ),1283      el("div", { id: "exec-result" }),1284    );1285    renderExecResult();1286    input.focus();1287  }12881289  // ---------- Settings ----------12901291  async function saveSettings(detail) {1292    const data = new FormData($("settings-form"));1293    const body = {};1294    const settings = {};12951296    const image = String(data.get("image") || "").trim();1297    if (image && image !== detail.image) body.image = image;12981299    const host = String(data.get("host") || "").trim();1300    if (host && host !== detail.host) settings.host = host;13011302    const wantsTLS = data.get("tls") === "on";1303    if (wantsTLS === detail.disableTLS) settings.disableTLS = !wantsTLS;13041305    const autoUpdate = data.get("autoUpdate") === "on";1306    if (autoUpdate !== detail.autoUpdate) settings.autoUpdate = autoUpdate;13071308    const cpus = Number(data.get("cpus"));1309    const memoryMB = Number(data.get("memoryMB"));1310    if (![cpus, memoryMB].every((value) => Number.isInteger(value) && value >= 0)) {1311      toast("CPUs and memory must be whole numbers, zero or more.", "warn");1312      return;1313    }1314    if (cpus !== detail.resources.cpus || memoryMB !== detail.resources.memoryMB) {1315      settings.resources = { cpus, memoryMB };1316    }13171318    if (!body.image && Object.keys(settings).length === 0) {1319      toast("Nothing has changed.");1320      return;1321    }1322    if (Object.keys(settings).length) body.settings = settings;13231324    try {1325      await api(appPath(detail.host), { method: "PATCH", body });1326      toast("Settings saved.");1327      state.selected = settings.host || detail.host;1328      await refreshAll();1329    } catch (error) {1330      if (!(await recoverFromRestart(error))) toast(error.message, "error");1331    }1332  }13331334  function renderSettings(panel, detail) {1335    fill(1336      panel,1337      el("p", { class: "panel-intro" }, "Saving redeploys the app with these settings. Only changed fields are sent."),1338      el(1339        "form",1340        {1341          class: "form",1342          id: "settings-form",1343          onsubmit: (event) => {1344            event.preventDefault();1345            saveSettings(detail);1346          },1347        },1348        el(1349          "label",1350          { class: "field wide" },1351          el("span", {}, "Image"),1352          el("input", { name: "image", value: detail.image, spellcheck: "false", autocomplete: "off" }),1353        ),1354        el(1355          "label",1356          { class: "field" },1357          el("span", {}, "Hostname"),1358          el("input", { name: "host", value: detail.host, spellcheck: "false", autocomplete: "off" }),1359          el("small", { class: "muted" }, "Changing it moves the app to a new address."),1360        ),1361        el(1362          "div",1363          { class: "toggles wide" },1364          el(1365            "label",1366            { class: "toggle" },1367            el("input", { type: "checkbox", name: "tls", checked: !detail.disableTLS }),1368            "Serve over HTTPS",1369          ),1370          el(1371            "label",1372            { class: "toggle" },1373            el("input", { type: "checkbox", name: "autoUpdate", checked: detail.autoUpdate }),1374            "Follow the image when it changes",1375          ),1376        ),1377        el(1378          "label",1379          { class: "field" },1380          el("span", {}, "CPUs ", el("small", {}, "0 means no limit")),1381          el("input", { type: "number", min: "0", step: "1", name: "cpus", value: detail.resources.cpus }),1382        ),1383        el(1384          "label",1385          { class: "field" },1386          el("span", {}, "Memory in MB ", el("small", {}, "0 means no limit")),1387          el("input", { type: "number", min: "0", step: "1", name: "memoryMB", value: detail.resources.memoryMB }),1388        ),1389        el(1390          "div",1391          { class: "form-actions wide" },1392          el("button", { class: "btn primary", type: "submit" }, "Save settings"),1393        ),1394      ),1395      el(1396        "div",1397        { class: "danger-zone" },1398        el(1399          "div",1400          {},1401          el("h3", {}, "Remove app"),1402          el(1403            "p",1404            { class: "muted" },1405            detail.isServer1406              ? "The Ino server cannot remove itself. Use the ino command on the VPS."1407              : "Stops the app and removes its container. Stored data stays unless you choose to delete it.",1408          ),1409        ),1410        detail.isServer1411          ? null1412          : el("button", { class: "btn danger", type: "button", onclick: openRemove }, "Remove app…"),1413      ),1414    );1415  }14161417  // ---------- Deploy from Git ----------14181419  const JOB_POLL_MS = 400;1420  const JOB_LOG_LINES = 600;14211422  /** The repository being deployed: its URL, last check, and whether a job runs. */1423  const repo = { url: "", view: null, busy: false };14241425  function initDeploy() {1426    $("repo-form").addEventListener("submit", (event) => {1427      event.preventDefault();1428      const url = String(new FormData(event.currentTarget).get("url") || "").trim();1429      if (url) checkRepo(url);1430    });1431  }14321433  function setDeployStatus(text) {1434    $("deploy-status").textContent = text;1435  }14361437  /** Shows an error above the job and result. Build output can span lines, so it keeps its line breaks. */1438  function showRepoError(message) {1439    const node = $("repo-error");1440    node.textContent = message || "";1441    node.hidden = !message;1442  }14431444  /** Disables every control that would start another job while one runs. */1445  function setRepoBusy(busy, status = "") {1446    repo.busy = busy;1447    setDeployStatus(status);1448    $("repo-check").disabled = busy;1449    const action = $("repo-action-submit");1450    if (action) action.disabled = busy || action.dataset.blocked === "true";1451  }14521453  // ---------- Jobs ----------14541455  /** The steps of the job on screen. A step is running until the next one starts. */1456  const jobView = { steps: [] };14571458  function showJob(title) {1459    jobView.steps = [];1460    $("job-title").textContent = title;1461    $("job-steps").replaceChildren();1462    $("job-log").replaceChildren();1463    $("repo-job").hidden = false;1464  }14651466  function renderSteps() {1467    fill(1468      $("job-steps"),1469      ...jobView.steps.map((step) =>1470        el("li", { class: "job-step", "data-state": step.state }, el("span", { class: "job-mark", "aria-hidden": "true" }), el("span", { text: step.text })),1471      ),1472    );1473  }14741475  function addStep(text) {1476    const last = jobView.steps.at(-1);1477    if (last && last.state === "running") last.state = "done";1478    jobView.steps.push({ text, state: "running" });1479    renderSteps();1480  }14811482  /** Ends the last step: done when the job succeeded, failed otherwise. */1483  function endSteps(succeeded) {1484    const last = jobView.steps.at(-1);1485    if (succeeded) jobView.steps.forEach((step) => (step.state = "done"));1486    else if (last && last.state === "running") last.state = "failed";1487    renderSteps();1488  }14891490  function addLogLine(text) {1491    const log = $("job-log");1492    log.append(document.createTextNode(`${text}\n`));1493    while (log.childNodes.length > JOB_LOG_LINES) log.firstChild.remove();1494    log.scrollTop = log.scrollHeight;1495  }14961497  function applyJobEvent(event) {1498    if (event.type === "step") addStep(event.message);1499    else if (event.type === "output") addLogLine(event.line);1500    else if (event.type === "notice") addLogLine(`note: ${event.message}`);1501  }15021503  /** Starts a job on the console and follows its events until it finishes. With `show` false the events stay off screen. */1504  async function runJob(kind, body, { show = true } = {}) {1505    const started = await api(`/jobs/${kind}`, { method: "POST", body, root: "/_console" });1506    let after = 0;1507    for (;;) {1508      const snapshot = await api(`/jobs/${started.id}?after=${after}`, { root: "/_console" });1509      if (show) snapshot.events.forEach(applyJobEvent);1510      after = snapshot.next;1511      if (snapshot.status !== "running") {1512        if (show) endSteps(snapshot.status === "succeeded");1513        return snapshot;1514      }1515      await sleep(JOB_POLL_MS);1516    }1517  }15181519  // ---------- Check and release ----------15201521  async function checkRepo(url, { show = true } = {}) {1522    if (repo.busy) return;1523    repo.url = url;1524    repo.view = null;1525    showRepoError("");1526    setRepoBusy(true, "Checking the repository");1527    if (show) showJob("Checking the repository");1528    try {1529      const snapshot = await runJob("check", { url }, { show });1530      if (snapshot.status === "succeeded") repo.view = snapshot.result;1531      else showRepoError(snapshot.error);1532    } catch (error) {1533      showRepoError(error.message);1534    } finally {1535      setRepoBusy(false);1536      renderRepo();1537    }1538  }15391540  function renderRepo() {1541    const panel = $("repo-result");1542    const view = repo.view;1543    if (!view) {1544      panel.hidden = true;1545      fill(panel);1546      return;1547    }1548    panel.hidden = false;1549    const target = view.target;1550    const deployed = view.deployed;1551    fill(1552      panel,1553      el(1554        "dl",1555        { class: "facts" },1556        fact("Repository", repo.url, true),1557        fact("Branch", view.subject ? `${view.branch} · ${view.subject}` : view.branch),1558        fact("Commit", view.commit.slice(0, 12), true),1559        fact("Version", view.version, true),1560        fact("Deploys to", target ? `${target.host} on ${target.server}` : "Not set"),1561        fact("Deployed", deployed ? `${deployed.version}${deployed.running ? "" : " (stopped)"}` : "Not deployed", true),1562      ),1563      releasePanel(view),1564    );1565  }15661567  /** What the page offers for the repository: a create form, a deploy button, or a note. */1568  function releasePanel(view) {1569    if (view.problem) {1570      return el("p", { class: "note quiet" }, view.problem);1571    }1572    if (!view.deployed) {1573      return el(1574        "form",1575        { class: "repo-action", id: "repo-action", onsubmit: (event) => releaseRepo(event, "create") },1576        el(1577          "p",1578          { class: "note quiet" },1579          `Nothing on the server runs this repository yet. Creating ${view.target.host} releases ${view.version}, pushes it, and starts the app.`,1580        ),1581        el(1582          "label",1583          { class: "field wide" },1584          el("span", {}, "Environment ", el("small", {}, "optional · one NAME=value per line")),1585          el("textarea", { name: "env", rows: "5", placeholder: "RAILS_ENV=production", spellcheck: "false" }),1586        ),1587        el(1588          "div",1589          { class: "form-actions" },1590          el("button", { class: "btn primary", type: "submit", id: "repo-action-submit" }, "Create app"),1591        ),1592      );1593    }1594    const upToDate = view.deployed.version === view.version;1595    const submit = el(1596      "button",1597      { class: "btn primary", type: "submit", id: "repo-action-submit", "data-blocked": String(upToDate) },1598      upToDate ? "Up to date" : "Release and deploy",1599    );1600    submit.disabled = upToDate || repo.busy;1601    return el(1602      "form",1603      { class: "repo-action", id: "repo-action", onsubmit: (event) => releaseRepo(event, "update") },1604      el(1605        "p",1606        { class: "note quiet" },1607        upToDate1608          ? `${view.target.host} already runs ${view.version}. Nothing to deploy.`1609          : `${view.target.host} runs ${view.deployed.version}. Releasing bumps the version, commits, builds ${view.image}, and updates the app.`,1610      ),1611      el("div", { class: "form-actions" }, submit),1612    );1613  }16141615  async function releaseRepo(event, action) {1616    event.preventDefault();1617    const view = repo.view;1618    if (repo.busy || !view) return;1619    const env = {};1620    if (action === "create") {1621      const data = new FormData(event.currentTarget);1622      const pairs = parseEnvText(String(data.get("env") || ""));1623      const malformed = pairs.filter((pair) => pair.error !== undefined).length;1624      if (malformed) {1625        toast(`Check ${plural(malformed, "line")}: each needs NAME=value.`, "warn");1626        return;1627      }1628      for (const pair of pairs) env[pair.key] = pair.value;1629    }1630    const plan =1631      action === "create"1632        ? `Create ${view.target.host} on ${view.target.server}`1633        : `Release and deploy ${view.target.host} on ${view.target.server}`;1634    if (!window.confirm(`${plan}? Ino bumps the version, commits and pushes ${view.branch} to origin, builds and pushes the image, then ${action === "create" ? "creates" : "updates"} the app.`)) return;16351636    const url = repo.url;1637    let succeeded = null;1638    setRepoBusy(true, "Releasing. This can take several minutes.");1639    showRepoError("");1640    showJob(plan);1641    try {1642      const snapshot = await runJob("release", { url, action, env });1643      if (snapshot.status === "succeeded") {1644        succeeded = snapshot.result;1645      } else {1646        showRepoError(snapshot.error);1647      }1648    } catch (error) {1649      showRepoError(error.message);1650    } finally {1651      setRepoBusy(false);1652    }1653    if (succeeded) {1654      toast(succeeded.message);1655      await loadApps({ quiet: true });1656      await checkRepo(url, { show: false });1657    }1658  }16591660  // ---------- Dialogs ----------16611662  let pendingRemoval = null;16631664  function openNewApp() {1665    const dialog = $("new-app-dialog");1666    $("new-app-form").reset();1667    dialog.showModal();1668    dialog.querySelector('input[name="image"]').focus();1669  }16701671  function openRemove() {1672    const detail = state.detail;1673    if (!detail) return;1674    pendingRemoval = detail.host;1675    const form = $("confirm-form");1676    form.reset();1677    $("confirm-body").textContent = `This stops ${detail.name} at ${detail.host} and removes its container.`;1678    $("confirm-submit").disabled = true;1679    $("confirm-dialog").showModal();1680    form.elements.namedItem("confirm").focus();1681  }16821683  function initDialogs() {1684    document.querySelectorAll("[data-close]").forEach((button) => {1685      button.addEventListener("click", () => button.closest("dialog").close());1686    });16871688    $("new-app-form").addEventListener("submit", async (event) => {1689      event.preventDefault();1690      const form = event.currentTarget;1691      const data = new FormData(form);1692      const pairs = parseEnvText(String(data.get("env") || ""));1693      const malformed = pairs.filter((pair) => pair.error !== undefined).length;1694      if (malformed) {1695        toast(`Check ${plural(malformed, "line")}: each needs NAME=value.`, "warn");1696        return;1697      }1698      const env = {};1699      for (const pair of pairs) env[pair.key] = pair.value;1700      const submit = $("new-app-submit");1701      submit.disabled = true;1702      submit.textContent = "Deploying…";1703      try {1704        const created = await api("/apps", {1705          method: "POST",1706          body: {1707            image: String(data.get("image") || "").trim(),1708            settings: {1709              host: String(data.get("host") || "").trim(),1710              disableTLS: data.get("tls") !== "on",1711              autoUpdate: data.get("autoUpdate") === "on",1712              env,1713            },1714          },1715        });1716        $("new-app-dialog").close();1717        toast(`Planted ${created.name} at ${created.host}.`);1718        setView("apps");1719        await loadApps({ quiet: true });1720        selectApp(created.host);1721      } catch (error) {1722        if (error.code === "host_conflict") toast("Another app already uses that hostname.", "warn");1723        else if (!(await recoverFromRestart(error))) toast(error.message, "error");1724      } finally {1725        submit.disabled = false;1726        submit.textContent = "Deploy";1727      }1728    });17291730    const confirmInput = $("confirm-form").elements.namedItem("confirm");1731    confirmInput.addEventListener("input", () => {1732      $("confirm-submit").disabled = !pendingRemoval || confirmInput.value.trim() !== pendingRemoval;1733    });17341735    $("confirm-form").addEventListener("submit", async (event) => {1736      event.preventDefault();1737      if (!pendingRemoval) return;1738      const host = pendingRemoval;1739      const removeData = $("confirm-form").elements.namedItem("removeData").checked;1740      try {1741        await api(`${appPath(host)}?remove_data=${removeData}`, { method: "DELETE" });1742        $("confirm-dialog").close();1743        pendingRemoval = null;1744        toast(`Removed ${host}.`);1745        if (state.selected === host) clearSelection();1746        await loadApps({ quiet: true });1747      } catch (error) {1748        if (!(await recoverFromRestart(error))) toast(error.message, "error");1749      }1750    });17511752    $("confirm-dialog").addEventListener("close", () => {1753      pendingRemoval = null;1754    });1755  }17561757  // ---------- Wiring ----------17581759  function initRail() {1760    $("search").addEventListener("input", (event) => {1761      state.query = event.target.value;1762      renderRail();1763    });1764    $("search").addEventListener("keydown", (event) => {1765      if (event.key === "Escape" && event.target.value) {1766        event.target.value = "";1767        state.query = "";1768        renderRail();1769      }1770    });1771    document.querySelectorAll(".rail .chip").forEach((chip) => {1772      chip.addEventListener("click", () => {1773        state.filter = chip.dataset.filter;1774        document.querySelectorAll(".rail .chip").forEach((other) => {1775          other.setAttribute("aria-pressed", String(other === chip));1776        });1777        renderRail();1778      });1779    });1780  }17811782  function isTyping() {1783    const active = document.activeElement;1784    return Boolean(active && (/^(INPUT|TEXTAREA|SELECT)$/.test(active.tagName) || active.isContentEditable));1785  }17861787  function init() {1788    initRail();1789    initDialogs();1790    initViews();1791    initFeed();1792    initDeploy();17931794    document.querySelectorAll(".tab").forEach((tab) => {1795      tab.addEventListener("click", () => {1796        state.tab = tab.dataset.tab;1797        renderDetail();1798      });1799    });18001801    $("refresh-btn").addEventListener("click", refreshCurrent);1802    $("new-app-btn").addEventListener("click", openNewApp);18031804    document.addEventListener("keydown", (event) => {1805      if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;1806      if (document.querySelector("dialog[open]") || isTyping()) return;1807      if (event.key === "/") {1808        event.preventDefault();1809        $(state.view === "logs" ? "feed-search" : "search").focus();1810      } else if (event.key === "n") {1811        openNewApp();1812      } else if (event.key === "r") {1813        refreshCurrent();1814      }1815    });18161817    loadSession();1818    pulse();1819    setInterval(pulse, POLL_MS);1820  }18211822  init();1823})();