gent-link 0.2.0

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
// Controls shared by the trusted presenter pages. Supervisor data is always text.
window.gentUI = (() => {
  const byId = id => document.getElementById(id);
  function el(tag, text, className) {
    const node = document.createElement(tag);
    if (text != null) node.textContent = String(text);
    if (className) node.className = className;
    return node;
  }
  function notice(id, message, error = false) {
    const field = byId(id);
    delete field.dataset.readError;
    field.textContent = message || "";
    field.hidden = !message;
    field.classList.toggle("error", error);
  }
  function readNotice(id, error) {
    const field = byId(id);
    if (error) {
      notice(id, error, true);
      field.dataset.readError = "true";
    } else if (field.dataset.readError) {
      notice(id, "");
    }
  }
  function send(request) {
    return window.gent.send(request).catch(() => {
      notice("bridge-error", "Gent Desktop could not reach its supervisor.", true);
      throw new Error("Supervisor unavailable");
    });
  }
  function request(op, fields) { return send({ op, ...fields }); }
  function button(title, run, style) {
    const b = el("button", title, style);
    b.type = "button";
    b.addEventListener("click", run);
    return b;
  }
  const dialog = byId("dialog"), body = byId("dialog-body"), footer = byId("dialog-buttons");
  function closeDialog() { if (dialog.open) dialog.close(); }
  dialog.addEventListener("close", () => {
    if (dialog.open) return;
    body.replaceChildren();
    footer.replaceChildren();
    byId("dialog-form").onsubmit = null;
  });
  function present(title, fields, submitLabel, onSubmit, paragraphs = [], focusCancel = false) {
    closeDialog();
    byId("dialog-title").textContent = title;
    body.replaceChildren();
    for (const line of paragraphs.filter(Boolean)) body.append(el("p", line, "lines"));
    const inputs = new Map();
    for (const field of fields) {
      const label = el("label", field.title, "field");
      const input = el(field.choices ? "select" : "input");
      if (field.choices) {
        for (const [value, text] of field.choices) input.append(new Option(text, value));
      } else {
        input.type = field.secret ? "password" : "text";
        input.autocomplete = "off";
        input.spellcheck = false;
      }
      if (field.value != null) input.value = field.value;
      input.required = true;
      label.append(input); body.append(label);
      inputs.set(field.key, input);
    }
    const cancel = button("Cancel", closeDialog), submit = el("button", submitLabel, "primary");
    submit.type = "submit";
    const enable = () => { submit.disabled = [...inputs.values()].some(input => !input.value.trim()); };
    inputs.forEach(input => input.addEventListener("input", enable));
    enable();
    footer.replaceChildren(cancel, submit);
    byId("dialog-form").onsubmit = event => {
      event.preventDefault();
      if (submit.disabled) return;
      const values = Object.fromEntries([...inputs].map(([key, input]) => [key, input.value.trim()]));
      closeDialog();
      onSubmit(values);
    };
    dialog.showModal();
    (focusCancel ? cancel : inputs.values().next().value || cancel).focus();
  }
  function privateCode(title, code) {
    closeDialog();
    byId("dialog-title").textContent = title;
    const label = el("label", "Private invitation code", "field"), input = el("input");
    input.readOnly = true; input.value = code; input.autocomplete = "off";
    label.append(input);
    body.replaceChildren(el("p", "Enter this code on the new node within 15 minutes."), label);
    footer.replaceChildren(button("Done", closeDialog));
    byId("dialog-form").onsubmit = event => event.preventDefault();
    dialog.showModal(); input.focus(); input.select();
  }
  const bars = new Map();
  let managing = null;
  function available(spec, row) {
    if (!spec.row) return true;
    if (!row || ["Revoked", "Retired"].includes(row.state)) return false;
    if (["remove_node","node_role"].includes(spec.kind)) return row.state !== "local" && row.role !== "Owner";
    return true;
  }
  function updateActions() {
    for (const { container, specs, selected } of bars.values()) {
      specs.forEach((spec, i) => { container.children[i].disabled = !!managing || !available(spec, selected()); });
    }
  }
  function setActions(page, specs = [], selected = () => null) {
    const container = byId(page + "-actions");
    const previous = bars.get(page);
    if (previous && JSON.stringify(previous.specs) === JSON.stringify(specs)) {
      previous.selected = selected; updateActions(); return;
    }
    bars.set(page, { container, specs, selected });
    function open(spec) {
      const row = spec.row ? bars.get(page).selected() : null;
      if (managing || !available(spec,row)) return;
      const action = { ...spec.values, kind: spec.kind };
      if (row) action.id = row.id;
      const run = extra => {
        managing = page; updateActions();
        notice(page + "-notice", action.kind === "sign_in" ? "Waiting for sign-in in your browser…" : "Working…");
        request("manage", {action:{...action,...extra}}).catch(() => {
          managing = null; updateActions(); notice(page + "-notice", "Request could not be sent.", true);
        });
      };
      const fields = (spec.fields || []).map(f => {
        if (f.key === "role" && row) return {...f,value:row.role === "Admin" ? "admin" : "member"};
        return {...f,value:row?.[f.key]};
      });
      if (!fields.length && !spec.confirm) { run({}); return; }
      const title = spec.title.replace(/…$/, "");
      present(title, fields, spec.submit || title, run,
        [row && row.name + "\n" + row.id, spec.confirm || spec.hint], !!spec.confirm);
    }
    container.replaceChildren(...specs.map(spec => button(spec.title, () => open(spec))));
    updateActions();
  }
  function completed(reply) {
    if (reply.page === managing) managing = null;
    updateActions();
    notice(reply.page + "-notice", reply.error || reply.notice, !!reply.error);
    if (reply.private_code) privateCode(reply.notice || "Node invitation", reply.private_code);
  }
  function external(label, url) {
    if (!url) return document.createTextNode(label);
    const a = el("a", label);
    a.href = url;
    a.addEventListener("click", event => {
      event.preventDefault();
      window.gent.open(url).catch(() => notice("bridge-error", "Could not open the link.", true));
    });
    return a;
  }
  function directory(page, columns) {
    const outer = byId(page + "-directory");
    const tools = el("div", null, "directory-tools"), filter = el("input"), count = el("span", null, "directory-count");
    const wrap = el("div", null, "table-wrap"), table = el("table"), head = table.createTHead().insertRow();
    const tbody = table.createTBody(), empty = el("p", null, "empty");
    const actions = el("div", null, "actions"), status = el("p", null, "notice"), detail = el("p", null, "muted");
    let rows = [], selected = null, sort = null, descending = false, initialized = false;
    filter.type = "search"; filter.placeholder = "Filter " + page; filter.setAttribute("aria-label",filter.placeholder);
    actions.id = page + "-actions"; status.id = page + "-notice"; status.setAttribute("role","status");
    table.setAttribute("aria-label", page === "nodes" ? "Cluster nodes" : "Registered chats");
    wrap.tabIndex = 0; wrap.setAttribute("role","region"); wrap.setAttribute("aria-label",table.getAttribute("aria-label"));
    tools.append(filter, count); wrap.append(table, empty); outer.append(tools,wrap,actions,detail,status);
    const choice = () => rows.find(r => r.id === selected);
    function select(id) {
      selected = id;
      for (const tr of tbody.rows) {
        const radio = tr.querySelector("input");
        tr.dataset.selected = String(radio.value === id); radio.checked = radio.value === id;
      }
      detail.textContent = choice()?.status_detail || ""; detail.hidden = !detail.textContent;
      updateActions();
    }
    function draw() {
      const query = filter.value.trim().toLocaleLowerCase();
      const shown = rows.filter(row => columns.some(([k]) => String(row[k] ?? "").toLocaleLowerCase().includes(query)));
      if (sort) shown.sort((a,b) => String(a[sort] ?? "").localeCompare(String(b[sort] ?? ""),undefined,{numeric:true}) * (descending ? -1 : 1));
      const focus = document.activeElement?.closest("tbody") === tbody ? document.activeElement.value : null;
      tbody.replaceChildren();
      for (const row of shown) {
        const tr = tbody.insertRow();
        columns.forEach(([key],i) => {
          const cell = tr.insertCell(), value = row[key] || "—";
          if (i === 0) {
            const label = el("label"), radio = el("input");
            radio.type = "radio"; radio.name = page + "-selection"; radio.value = row.id;
            radio.addEventListener("change", () => select(row.id));
            label.append(radio, document.createTextNode(value)); cell.append(label);
            if (row.id === focus) radio.focus({preventScroll:true});
          } else cell.textContent = value;
          if (key === "id") cell.className = "identifier";
        });
        if (row.status_detail) tr.title = row.status_detail;
        tr.addEventListener("click", event => { if (!getSelection()?.toString() && !event.target.closest("label,input")) select(row.id); });
      }
      select(shown.some(r => r.id===selected) ? selected : null);
      count.textContent = shown.length + " of " + rows.length + " " + page;
      empty.textContent = query ? "No matching " + page + "." : "No " + page + " to show.";
      empty.hidden = !!shown.length;
      for (const th of head.cells) th.setAttribute("aria-sort", th.dataset.key === sort ? (descending ? "descending" : "ascending") : "none");
    }
    columns.forEach(([key,title]) => {
      const th = el("th"); th.scope="col"; th.dataset.key=key;
      th.append(button(title,() => { descending = sort === key && !descending; sort=key; draw(); }));
      head.append(th);
    });
    filter.addEventListener("input",draw);
    return reply => {
      if (!initialized || JSON.stringify(rows)!==JSON.stringify(reply.rows || [])) {
        rows=reply.rows || []; initialized=true; draw();
      }
      setActions(page, reply.actions || [], choice);
      readNotice(status.id, reply.error);
    };
  }
  return {byId,el,notice,readNotice,send,request,button,present,closeDialog,setActions,completed,external,directory};
})();