gent-link 0.2.20

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
// Only shell controls send supervisor requests. An embedded document can report
// its height for layout through postMessage.
window.gentDashboards = (() => {
  const { el, button, request, external, addRefreshIcon } = 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;
  let refreshQueued = false;
  let tray = false;

  window.addEventListener("message", event => {
    const height = event.data?.gentBoardHeight;
    if (!event.source || !Number.isSafeInteger(height) || height < 1) return;
    for (const {frame} of cards.values()) {
      if (frame?.contentWindow !== event.source) continue;
      // WebKit stores layout coordinates in signed 26.6 fixed point.
      const size = Math.min(height, 33554431) + "px";
      if (frame.style.height !== size) frame.style.height = size;
      break;
    }
  });

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

  let clock = new Intl.DateTimeFormat(undefined, {dateStyle: "medium", timeStyle: "short"});

  function updateTime(card) {
    const seconds = card.row.updated_at;
    const date = new Date(seconds * 1000);
    if (Number.isSafeInteger(seconds) && seconds > 0 && Number.isFinite(date.getTime())) {
      card.time.dateTime = date.toISOString();
      card.time.textContent = "Updated " + clock.format(date);
    } else {
      card.time.removeAttribute("datetime");
      card.time.textContent = "Update time unavailable";
    }
  }

  async function readClock() {
    const cycle = await window.gent.hourCycle?.().catch(() => null);
    const options = {dateStyle: "medium", timeStyle: "short"};
    if (cycle === "h12" || cycle === "h23") options.hourCycle = cycle;
    clock = new Intl.DateTimeFormat(undefined, options);
    for (const card of cards.values()) if (card.row.agent) updateTime(card);
  }

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

  function finishRead() {
    reading = false;
    if (refreshQueued) {
      refreshQueued = false;
      refresh();
    }
  }

  function updateRefreshButton(card) {
    if (!card.update) return;
    const busy = refreshing.has(card.row.agent) || card.row.refresh_pending === true;
    card.update.disabled = stale || busy;
    card.update.setAttribute("aria-busy", String(busy));
    const label = busy ? "Waiting for dashboard update" : "Request dashboard update";
    card.update.title = label;
    card.update.setAttribute("aria-label", label);
  }

  function schedulePoll() {
    clearTimeout(polling);
    if (!shown) return;
    const pending = refreshing.size || Array.from(cards.values()).some(card => card.row.refresh_pending);
    polling = setTimeout(() => {
      if (!reading) refresh();
      schedulePoll();
    }, pending ? 2000 : 15000);
  }

  function ownerRefresh(card) {
    const {agent, revision} = card.row;
    if (refreshing.has(agent) || card.row.refresh_pending || stale) return;
    refreshing.add(agent);
    updateRefreshButton(card);
    report("");
    schedulePoll();
    request("dashboard_refresh", {agent, revision}).catch(() => {
      refreshing.delete(agent);
      updateRefreshButton(card);
      schedulePoll();
      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.time = el("time", null, "board-updated");
      heading.append(card.time);
      card.update = describedButton("Request dashboard update", "", () => ownerRefresh(card));
      addRefreshIcon(card.update);
      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 if (w.display_value || w.chart_description) {
        group.append(el("p", w.display_value || w.chart_description));
      } else {
        let value = w.value;
        if (typeof value === "object") value = JSON.stringify(value);
        group.append(el("p", [value, 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>";
  }

  function removeDocument(card) {
    const url = card.frame?.getAttribute("src");
    card.frame?.remove();
    card.frame = null;
    if (url) window.gent.releaseBoard(url).catch(() => {});
  }

  async function showDocument(card, html, interactive) {
    if (card.source === html && card.interactive === interactive && card.frame) {
      card.frame.title = card.row.board.title;
      return;
    }
    removeDocument(card);
    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.time) updateTime(card);
    updateRefreshButton(card);
    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)) {
        removeDocument(card);
        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.
        if (card) {
          removeDocument(card);
          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) {
        if (!reply.error && card.row.revision === reply.refresh_revision) {
          card.row.refresh_pending = reply.refresh_pending === true;
        }
        updateRefreshButton(card);
      }
    }
    if (reply.error || (reply.notice && !reply.refresh_agent)) report(reply.error || reply.notice, !!reply.error);
    const hide = document.activeElement?.closest(".board-hide");
    const rowIndex = hide ? Array.from(list.children).indexOf(hide.closest(".board-card")) : -1;
    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.textContent = "Dashboards require Gent Pro for this cluster.";
        if (!tray) summary.append(" ", external("View plans", "https://gent.link/pricing"));
      } else if (!reply.rows.length && (reply.example || (tray && !reply.error))) {
        summary.textContent = reply.all_hidden ? "All dashboards are hidden." : "No chats have published a dashboard.";
      }
      summary.hidden = !summary.textContent;
      const showExample = !tray && reply.example && !reply.rows.length;
      renderRows(showExample ? [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 (restore && Array.isArray(reply.hidden)) setHidden(reply.hidden);
    if (!reply.refresh_agent && (Array.isArray(reply.rows) || reply.read_failed || reply.unchanged)) finishRead();
    schedulePoll();
    if (rowIndex >= 0 && !hide.isConnected && (tray || !restore.hidden)) {
      const adjacent = list.children[Math.min(rowIndex, list.children.length - 1)];
      const control = adjacent?.querySelector(".board-bar button:enabled") ||
        (tray ? document.getElementById("close-tray") : restore.querySelector("summary"));
      control.focus();
    }
  }

  function mount(container, options = {}) {
    tray = options.tray === true;
    summary = el("p", null, "board-summary");
    feedback = el("p", null, "board-feedback");
    feedback.setAttribute("role", "status");
    retry = button("Retry loading dashboards", refresh, "board-retry");
    summary.hidden = retry.hidden = true;
    report("Loading dashboards…");
    list = el("div", null, "board-list");
    const bay = el("div", null, "board-bay");
    bay.append(list);
    if (tray) {
      bay.tabIndex = 0;
      bay.setAttribute("role", "region");
      bay.setAttribute("aria-label", "Dashboard list");
    } else {
      restore = el("details", null, "board-restore");
      restore.append(el("summary"), el("div"));
      restore.hidden = true;
      bay.append(restore);
    }
    container.replaceChildren(summary, feedback, retry, bay);
  }

  function visible(next) {
    if (next === shown) return;
    shown = next;
    if (shown) {
      if (tray) void readClock(); // The native popup opens with a full snapshot.
      else refresh();
    } else if (tray) {
      renderRows([]);
      refreshing.clear();
      refreshQueued = reading = stale = false;
      summary.replaceChildren();
      summary.hidden = retry.hidden = true;
      report("Loading dashboards…");
      list.parentElement.scrollTop = 0;
    }
    schedulePoll();
  }

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