gent-link 0.2.4

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
// Only the shell creates controls that send supervisor requests. Board documents
// have their own opaque browsing contexts and no message channel into this page.
window.gentDashboards = (() => {
  const { el, button, request, external } = window.gentUI;
  const cards = new Map();
  const refreshing = new Set();
  let list, summary, feedback, restore, retry;
  let shown = false, polling = null, reading = false, stale = false;

  function report(text, error = false) {
    feedback.textContent = text || "";
    feedback.hidden = !text;
    feedback.classList.toggle("error", error);
  }

  function refresh() {
    if (!shown || reading) return;
    reading = true;
    retry.disabled = true;
    request("dashboard").catch(() => {
      reading = false;
      retry.hidden = retry.disabled = false;
      report("Could not load dashboards.", true);
    });
  }

  function ownerRefresh(card) {
    const {agent, revision} = card.row;
    if (refreshing.has(agent) || stale) return;
    refreshing.add(agent);
    card.update.disabled = true;
    report("Requesting an update…");
    request("dashboard_refresh", {agent, revision}).catch(() => {
      refreshing.delete(agent);
      card.update.disabled = stale;
      report("Could not request a dashboard update.", true);
    });
  }

  function describedButton(label, text, click) {
    const control = button(text, click);
    control.title = label;
    control.setAttribute("aria-label", label);
    return control;
  }

  function createCard(row) {
    const node = el("article", null, "board-card");
    const header = el("header", null, "board-bar");
    const heading = el("div", null, "board-heading");
    const title = el("h2"), chat = el("span", null, "board-publisher");
    heading.append(title, chat);
    header.append(heading);
    const body = el("div", null, "board-document");
    const actions = el("div", null, "board-actions");
    node.append(header, body, actions);
    const card = {node, title, chat, body, actions, row, source: null, frame: null};
    if (row.agent) {
      card.update = describedButton("Request dashboard update", "", () => ownerRefresh(card));
      card.update.append(document.querySelector("#refresh svg").cloneNode(true));
      const hide = describedButton("Hide dashboard", "×", () => {
        request("dashboard_hide", {agent: card.row.agent}).catch(() => report("Could not hide dashboard.", true));
      });
      hide.className = "board-hide";
      header.append(card.update, hide);
    }
    return card;
  }

  // Old widget snapshots can still be read while their publisher upgrades.
  // Serialize text nodes, including labels and chart descriptions, as inert HTML.
  function legacyDocument(board) {
    const body = el("main");
    for (const w of board.widgets || []) {
      if (w.kind === "button") continue;
      if (w.unit === "Gent published HTML v1") {
        body.append(el("p", "Waiting for the published document."));
        continue;
      }
      const group = el("section");
      group.append(el("h2", w.label));
      if (w.kind === "image" && /^data:image\/(png|jpeg);base64,/.test(w.value)) {
        const img = el("img");
        img.alt = w.label;
        img.src = w.value;
        group.append(img);
      } else if (w.kind === "events" && Array.isArray(w.value)) {
        const entries = el("ul");
        for (const line of w.value) entries.append(el("li", line));
        group.append(entries);
      } else {
        let value = w.chart_description || w.value;
        if (typeof value === "object") value = JSON.stringify(value);
        group.append(el("p", [value, w.chart_description ? "" : w.unit].filter(v => v != null && v !== "").join(" ")));
      }
      body.append(group);
    }
    body.append(el("p", "Use Refresh to ask the publishing chat for a web dashboard."));
    const head = '<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>:root{color-scheme:light dark;font:15px/1.5 system-ui}body{margin:1rem}main{display:grid;gap:1rem}h2{font-size:1rem;margin:0}p,ul{margin:.3rem 0;white-space:pre-wrap;overflow-wrap:anywhere}img{max-width:100%;height:auto}</style>';
    const doc = head + body.outerHTML + '</html>';
    return new TextEncoder().encode(doc).length <= 65536 ? doc :
      head + "<p>Use Refresh to ask the publishing chat to convert this dashboard to HTML.</p></html>";
  }

  async function showDocument(card, html, interactive) {
    if (card.source === html && card.interactive === interactive && card.frame) {
      card.frame.title = card.row.board.title;
      return;
    }
    card.source = html;
    card.interactive = interactive;
    const frame = el("iframe");
    frame.setAttribute("sandbox", interactive ? "allow-scripts" : "");
    frame.referrerPolicy = "no-referrer";
    frame.title = card.row.board.title;
    card.frame = frame;
    card.body.replaceChildren();
    try {
      const url = await window.gent.board(html, interactive);
      if (card.frame !== frame || !card.node.isConnected) {
        await window.gent.releaseBoard(url);
        return;
      }
      frame.src = url;
      card.body.replaceChildren(frame);
    } catch {
      if (card.frame === frame && card.node.isConnected) {
        card.frame = null;
        card.body.replaceChildren(el("p", "Could not open this dashboard.", "board-placeholder"));
      }
    }
  }

  function updateActions(card, widgets) {
    const area = card.actions;
    const existing = new Map(Array.from(area.children, node => [node.dataset.widget, node]));
    const focused = area.contains(document.activeElement) ? document.activeElement : null;
    widgets.forEach(({id, label}, i) => {
      const action = existing.get(id) || button(label, () => request("dashboard_click", {
        agent: card.row.agent, revision: card.row.revision, widget: id
      }).catch(() => report("Could not send dashboard action.", true)));
      existing.delete(id);
      action.dataset.widget = id;
      if (action.textContent !== label) action.textContent = label;
      action.disabled = stale;
      if (area.children[i] !== action) area.insertBefore(action, area.children[i] || null);
    });
    for (const obsolete of existing.values()) obsolete.remove();
    if (focused?.isConnected && focused !== document.activeElement) focused.focus({preventScroll:true});
  }

  function renderCard(card, row) {
    card.row = row;
    card.title.textContent = row.board.title;
    card.chat.textContent = row.chat;
    if (card.update) card.update.disabled = refreshing.has(row.agent) || stale;
    const widgets = row.agent ? (row.board.widgets || []).filter(w => w.kind === "button") : [];
    updateActions(card, widgets);
    const interactive = typeof row.board.html === "string";
    const source = interactive ? row.board.html : row.board.static_html ?? legacyDocument(row.board);
    showDocument(card, source, interactive);
  }

  function renderRows(rows) {
    const keys = new Set(rows.map(row => row.agent || "example"));
    for (const [key, card] of cards) {
      if (!keys.has(key)) {
        card.node.remove();
        cards.delete(key);
      }
    }
    rows.forEach((row, i) => {
      const key = row.agent || "example";
      let card = cards.get(key);
      if (!card || list.children[i] !== card.node) {
        // Moving a mounted iframe reloads its one-use URL in WebKit.
        card?.node.remove();
        card = createCard(row);
        cards.set(key, card);
        list.insertBefore(card.node, list.children[i] || null);
      }
      renderCard(card, row);
    });
  }

  function setHidden(labels) {
    const label = restore.querySelector("summary"), choices = restore.lastElementChild;
    const focused = restore.contains(document.activeElement) ? document.activeElement : null;
    const buttons = new Map(Array.from(choices.children, b => [b.dataset.agent, b]));
    labels.forEach(({agent, title, chat}, i) => {
      const choice = buttons.get(agent) || button("", () => {
        request("dashboard_restore", {agent}).then(refresh)
          .catch(() => report("Could not restore dashboard.", true));
      });
      buttons.delete(agent);
      choice.dataset.agent = agent;
      const name = title + " · " + chat;
      if (choice.textContent !== name) choice.textContent = name;
      if (choices.children[i] !== choice) choices.insertBefore(choice, choices.children[i] || null);
    });
    for (const obsolete of buttons.values()) obsolete.remove();
    label.textContent = "Restore hidden dashboards (" + labels.length + ")";
    restore.hidden = !labels.length;
    if (restore.hidden) restore.open = false;
    if (focused && (restore.hidden || focused !== document.activeElement)) {
      if (!restore.hidden) (focused.isConnected ? focused : label).focus();
      else {
        const update = cards.get(focused.dataset.agent)?.update;
        (update && !update.disabled ? update : document.getElementById("tab-dashboard")).focus();
      }
    }
  }

  function receive(reply) {
    if (reply.read_failed) {
      retry.hidden = retry.disabled = false;
    } else if (!retry.hidden && !reply.error && (Array.isArray(reply.rows) || reply.unchanged)) {
      retry.hidden = true;
      report("");
    }
    if (reply.refresh_agent) {
      refreshing.delete(reply.refresh_agent);
      const card = cards.get(reply.refresh_agent);
      if (card?.update) card.update.disabled = stale;
    } else {
      reading = false;
    }
    if (reply.error || reply.notice) report(reply.error || reply.notice, !!reply.error);
    const hide = document.activeElement?.closest(".board-hide");
    if (Array.isArray(reply.rows)) {
      // An account switch can replace the whole view in lieu of a refresh acknowledgment.
      if (reply.pro_required || (reply.error && !reply.rows.length && !reply.stale)) refreshing.clear();
      stale = !!reply.stale;
      if (!reply.error && !reply.notice) report("");
      summary.replaceChildren();
      if (reply.pro_required) {
        summary.append("Dashboards require Gent Pro for this cluster. ", external("View plans", "https://gent.link/pricing"));
      } else if (reply.example && !reply.rows.length) {
        summary.textContent = reply.all_hidden ? "All dashboards are hidden." : "No chats have published a dashboard.";
      }
      summary.hidden = !summary.textContent;
      renderRows(reply.example && !reply.rows.length ? [reply.example] : reply.rows);
    } else if (reply.stale && !stale) {
      stale = true;
      for (const card of cards.values()) {
        if (card.update) card.update.disabled = true;
        for (const action of card.actions.children) action.disabled = true;
      }
    } else if (reply.unchanged) {
      for (const card of cards.values()) {
        if (!card.frame) renderCard(card, card.row);
      }
    }
    if (Array.isArray(reply.hidden)) setHidden(reply.hidden);
    if (hide && !hide.isConnected && !restore.hidden) restore.querySelector("summary").focus();
  }

  function mount(container) {
    summary = el("p", null, "board-summary");
    feedback = el("p", null, "board-feedback");
    feedback.setAttribute("role", "status");
    retry = button("Retry loading dashboards", refresh, "board-retry");
    restore = el("details", null, "board-restore");
    restore.append(el("summary"), el("div"));
    summary.hidden = restore.hidden = retry.hidden = true;
    report("Loading dashboards…");
    list = el("div", null, "board-list");
    container.replaceChildren(summary, feedback, retry, list, restore);
  }

  function visible(next) {
    if (next === shown) return;
    shown = next;
    clearInterval(polling);
    if (shown) {
      refresh();
      polling = setInterval(refresh, 15000);
    }
  }

  return Object.freeze({mount, visible, receive, refresh});
})();