gent-link 0.2.4

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;
  }
  let bridgeSequence = 0, lastBridgeResult = 0;
  function notice(id, message, error = false, sequence) {
    if (id === "bridge-error") {
      const order = sequence ?? ++bridgeSequence;
      if (order < lastBridgeResult) return;
      lastBridgeResult = order;
    }
    const field = byId(id);
    delete field.dataset.readError;
    delete field.dataset.queuedRename;
    delete field.dataset.queuedUnregister;
    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) {
    const sequence = ++bridgeSequence;
    return window.gent.send(request).then(reply => {
      notice("bridge-error", "", false, sequence);
      return reply;
    }, () => {
      notice("bridge-error", "Gent Desktop could not reach its supervisor.", true, sequence);
      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();
  }
  let managing = null;
  function manageButton(title, run, style) {
    const control = button(title, event => { if (!managing) run(event); }, style);
    control.dataset.manage = "";
    control.setAttribute("aria-disabled",String(!!managing));
    return control;
  }
  function updateActions() {
    for (const control of document.querySelectorAll("button[data-manage]")) control.setAttribute("aria-disabled",String(!!managing));
  }
  function openAction(page, spec, row) {
    if (managing || (spec.row && !row?.actions.includes(spec.kind))) return;
    const action = {...spec.values, kind:spec.kind};
    if (row) action.id = row.id;
    if (spec.kind === "rename_chat") action.expected_generation = row.generation;
    const run = values => {
      managing = page; updateActions();
      notice(page + "-notice", action.kind === "sign_in" ? "Waiting for sign-in in your browser…" : "Working…");
      request("manage", {action:{...action,...values}}).catch(() => {
        managing = null; updateActions(); notice(page + "-notice", "Request could not be sent.", true);
      });
    };
    const fields = (spec.fields || []).map(field => ({
      ...field, value:field.key === "role" && row ? (row.role === "Admin" ? "admin" : "member") : row?.[field.key]
    }));
    if (!fields.length && !spec.confirm) { run({}); return; }
    const title = spec.title.replace(/…$/, "");
    present(title, fields, spec.submit || title, run,
      [row && [row.name, row.node, row.id].filter(Boolean).join("\n"), spec.confirm || spec.hint], !!spec.confirm);
  }
  const bars = new Map();
  function setActions(page, specs = []) {
    const key = JSON.stringify(specs);
    if (bars.get(page) === key) return;
    bars.set(page,key);
    byId(page + "-actions").replaceChildren(...specs.map(spec =>
      manageButton(spec.title, () => openAction(page,spec))));
  }
  function completed(reply) {
    if (reply.page === managing) managing = null;
    updateActions();
    notice(reply.page + "-notice", reply.error || reply.notice, !!reply.error);
    if (reply.queued_rename) byId(reply.page + "-notice").dataset.queuedRename = "true";
    if (reply.queued_unregister) byId(reply.page + "-notice").dataset.queuedUnregister = reply.queued_unregister;
    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;
  }
  let menu = null, opener = null;
  function closeMenu(restore = false) {
    if (!menu) return;
    const trigger = opener;
    menu.remove(); menu = null; opener = null;
    trigger.setAttribute("aria-expanded","false");
    trigger.removeAttribute("aria-controls");
    if (restore) trigger.focus({preventScroll:true});
  }
  function positionMenu() {
    if (!menu) return;
    const rect = opener.getBoundingClientRect();
    let left = Math.max(rect.left,0), right = Math.min(rect.right,innerWidth);
    let top = Math.max(rect.top,0), bottom = Math.min(rect.bottom,innerHeight);
    for (const frame of [opener.closest(".table-wrap"), opener.closest(".page")]) {
      const bounds = frame.getBoundingClientRect();
      left = Math.max(left,bounds.left+frame.clientLeft);
      right = Math.min(right,bounds.left+frame.clientLeft+frame.clientWidth);
      top = Math.max(top,bounds.top+frame.clientTop);
      bottom = Math.min(bottom,bounds.top+frame.clientTop+frame.clientHeight);
    }
    if (right <= left || bottom <= top) { closeMenu(true); return; }
    menu.style.left = Math.max(4, Math.min(innerWidth-menu.offsetWidth-4,right-menu.offsetWidth)) + "px";
    menu.style.top = (bottom+menu.offsetHeight+4 <= innerHeight ? bottom+2 : Math.max(4,top-menu.offsetHeight-2)) + "px";
  }
  function showMenu(trigger, specs, page, row, last = false) {
    if (managing) return;
    if (trigger === opener) { closeMenu(true); return; }
    closeMenu();
    opener = trigger;
    menu = el("div",null,"directory-menu");
    menu.id = "directory-menu";
    menu.setAttribute("role","menu"); menu.setAttribute("aria-label",trigger.getAttribute("aria-label"));
    for (const spec of specs) {
      const item = button(spec.title, () => { closeMenu(true); openAction(page,spec,row); });
      item.setAttribute("role","menuitem"); item.tabIndex = -1;
      menu.append(item);
    }
    trigger.setAttribute("aria-expanded","true");
    trigger.setAttribute("aria-controls",menu.id);
    trigger.closest(".page").append(menu);
    trigger.scrollIntoView({block:"nearest",inline:"nearest"});
    positionMenu();
    if (!menu) return;
    (last ? menu.lastElementChild : menu.firstElementChild).focus({preventScroll:true});
    menu.onkeydown = event => {
      const items = [...menu.children], i = items.indexOf(document.activeElement);
      const positions = {ArrowDown:(i+1)%items.length,ArrowUp:(i+items.length-1)%items.length,Home:0,End:items.length-1};
      if (event.key in positions) { event.preventDefault(); items[positions[event.key]].focus(); }
      else if (event.key === "Escape") { event.preventDefault(); closeMenu(true); }
      else if (event.key === "Tab") closeMenu(true);
    };
  }
  function outside(event) {
    if (menu && !menu.contains(event.target) && !opener.contains(event.target)) closeMenu();
  }
  document.addEventListener("pointerdown",outside);
  document.addEventListener("focusin",outside);
  document.addEventListener("scroll",positionMenu,true);
  window.addEventListener("resize",positionMenu);

  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");
    const inactive = el("label"), includeInactive = el("input");
    let rows = [], specs = [], sort = null, descending = false, lastReply;
    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);
    if (page === "chats") {
      includeInactive.type = "checkbox";
      inactive.append(includeInactive," Show inactive chats"); inactive.hidden = true; tools.append(inactive);
      includeInactive.onchange = draw;
    }
    tools.append(count,actions); wrap.append(table,empty); outer.append(tools,wrap,status);

    function rowControls(tr,row) {
      const cell = tr.insertCell(); cell.className = "directory-actions";
      const eligible = specs.filter(spec => row.actions?.includes(spec.kind));
      const label = row.name + " (" + row.id + ")";
      const more = eligible.filter(spec => !spec.destructive);
      if (more.length) {
        const trigger = manageButton("⋯",() => showMenu(trigger,more,page,row),"row-action");
        trigger.setAttribute("aria-label","More actions for " + label);
        trigger.title = "More actions for " + row.name;
        trigger.dataset.control = "menu"; trigger.setAttribute("aria-haspopup","menu");
        trigger.setAttribute("aria-expanded","false");
        trigger.onkeydown = event => {
          if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
          event.preventDefault(); showMenu(trigger,more,page,row,event.key === "ArrowUp");
        };
        cell.append(trigger);
      }
      const remove = eligible.find(spec => spec.destructive);
      if (remove) {
        const control = manageButton("×",() => { control.focus(); openAction(page,remove,row); },"row-action remove");
        const verb = remove.title.replace(/…$/,"");
        control.title = verb + " · " + row.name;
        control.dataset.control = remove.kind;
        control.setAttribute("aria-label",verb + " " + label); cell.append(control);
      }
    }
    function draw() {
      const active = menu && tbody.contains(opener) ? opener : document.activeElement;
      const focusId = active.closest("tr")?.dataset.id, focusControl = active.dataset.control;
      if (menu && tbody.contains(opener)) closeMenu();
      const query = filter.value.trim().toLocaleLowerCase();
      const current = page === "chats" && !includeInactive.checked ? rows.filter(row => row.state === "Registered") : rows;
      const shown = current.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));
      let restore;
      tbody.replaceChildren();
      for (const row of shown) {
        const tr = tbody.insertRow(); tr.dataset.id = row.id;
        for (const [key] of columns) {
          const cell = tr.insertCell(); cell.textContent = row[key] || "—";
          if (key === "id") cell.className = "identifier";
          if (key === "state") {
            if (row.status_detail) cell.append(el("small",row.status_detail,"row-detail"));
            const receipt = row.rename_request;
            if (receipt) {
              const outcomes = {
                queued: "Rename to “" + receipt.name + "” queued. Refresh to check.",
                applied: "Rename to “" + receipt.name + "” applied.",
                unconfirmed: "Rename to “" + receipt.name + "” unconfirmed. " + (receipt.reason || "No decision received from the hosting node."),
                rejected: "Rename to “" + receipt.name + "” rejected. " + (receipt.reason || "")
              };
              if (outcomes[receipt.state]) cell.append(el("small",outcomes[receipt.state],"row-detail"));
            }
          }
        }
        rowControls(tr,row);
        if (row.id === focusId && focusControl) {
          restore = [...tr.querySelectorAll("button")].find(b => b.dataset.control === focusControl);
        }
      }
      if (focusId && focusControl) (restore || filter).focus({preventScroll:true});
      inactive.hidden = !rows.some(row => row.state !== "Registered");
      count.textContent = shown.length + " of " + current.length + " " + page;
      empty.textContent = query ? "No matching " + page + "." : "No " + page + " to show.";
      empty.hidden = !!shown.length;
      for (const th of head.querySelectorAll("[data-key]")) 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);
    });
    const actionHead = el("th","Actions","directory-actions"); actionHead.scope = "col"; head.append(actionHead);
    filter.addEventListener("input",draw);
    return reply => {
      const key = JSON.stringify([reply.rows,reply.actions]);
      if (key !== lastReply) {
        rows = reply.rows || []; specs = (reply.actions || []).filter(s => s.row);
        setActions(page,(reply.actions || []).filter(s => !s.row)); draw(); lastReply = key;
      }
      if (!reply.error && status.dataset.queuedRename) notice(status.id,"");
      const pending = status.dataset.queuedUnregister;
      if (!reply.error && pending && rows.some(row => row.id === pending && row.state === "Revoked")) {
        notice(status.id,"Chat unregistered.");
      }
      readNotice(status.id,reply.error);
    };
  }
  return {byId,el,notice,readNotice,send,request,button,present,closeDialog,setActions,completed,external,directory};
})();