/* The Search agents page: what Best match on the Roles tab is measured * against, one agent at a time. * * The list is `/api/agents`; the form edits the agent picked from it, New * clears it, Delete removes it. Votes, liked companies and scores are the * agent's, so a delete takes them with it, and the confirm says so. * * Every request goes through `api()` from app.js, so a failure is one toast * carrying the server's own sentence. */ (function () { "use strict"; const { api, count } = window; const $ = (sel, root = document) => root.querySelector(sel); const DEFAULT_WEIGHTS = { fit: 0.6, recency: 0.2, affinity: 0.2, taste: 0.2 }; /** @type {object[]} every agent, as the server lists them */ let agents = []; /** @type {object | null} the agent the form edits, null for a new one */ let agent = null; function byId(rows) { return [...rows].sort((a, b) => a.id - b.id); } // ---------------------------------------------------------------- the list function onSwitch(row) { const box = document.createElement("input"); box.type = "checkbox"; box.checked = Boolean(row.enabled); box.setAttribute("aria-label", `Enable ${row.name}`); box.addEventListener("change", async () => { box.disabled = true; try { const saved = await api("/api/agents", { method: "POST", body: Object.assign({}, row, { enabled: box.checked }), }); Object.assign(row, saved); } catch (err) { box.checked = !box.checked; } box.disabled = false; render(); }); return box; } function render() { const body = $("#agents-list"); body.replaceChildren(); for (const row of byId(agents)) { const div = document.createElement("div"); div.className = "crow"; if (!row.enabled) div.dataset.hidden = "true"; if (agent && agent.id === row.id) div.dataset.current = "true"; const name = document.createElement("span"); name.className = "name"; name.textContent = row.name; div.appendChild(name); div.appendChild(onSwitch(row)); const sub = document.createElement("span"); sub.className = "sub"; const w = Object.assign({}, DEFAULT_WEIGHTS, row.weights); sub.append(`fit ${w.fit} · newness ${w.recency} · companies ${w.affinity} · liked ${w.taste}`, " "); const edit = document.createElement("button"); edit.type = "button"; edit.className = "linky"; edit.textContent = "Edit"; edit.addEventListener("click", () => fill(row)); const remove = document.createElement("button"); remove.type = "button"; remove.className = "linky"; remove.textContent = "Delete"; remove.addEventListener("click", () => removeAgent(row)); sub.append(edit, " ", remove); div.appendChild(sub); body.appendChild(div); } $("#agents-count").textContent = agents.length ? count(agents.length, "search agent") : "No search agents yet. Describe one below."; } // ---------------------------------------------------------------- the form function fill(row) { agent = row; const weights = Object.assign({}, DEFAULT_WEIGHTS, row ? row.weights : {}); $("#agent-form-title").textContent = row ? `Edit ${row.name}` : "New agent"; $("#a-name").value = row ? row.name : ""; $("#a-intent").value = row ? row.intent : ""; $("#a-gates").value = JSON.stringify(row ? row.gates : [], null, 2); $("#a-fit").value = weights.fit; $("#a-recency").value = weights.recency; $("#a-affinity").value = weights.affinity; $("#a-taste").value = weights.taste; $("#a-delete").hidden = !row; $("#agent-status").textContent = ""; render(); if (row) $("#agent-form").scrollIntoView({ behavior: "smooth", block: "start" }); } async function save(event) { event.preventDefault(); const status = $("#agent-status"); let gates; try { gates = JSON.parse($("#a-gates").value || "[]"); } catch (err) { window.toast.error(`Gates are not valid JSON: ${err.message}`); return; } const body = { name: $("#a-name").value.trim(), intent: $("#a-intent").value, gates, weights: { fit: Number($("#a-fit").value), recency: Number($("#a-recency").value), affinity: Number($("#a-affinity").value), taste: Number($("#a-taste").value), }, // Saving an agent means it is wanted, so a new one starts on; the // list's checkbox is where an existing one is switched. enabled: agent ? agent.enabled : true, }; if (agent) body.id = agent.id; const button = $("#agent-form button[type=submit]"); button.disabled = true; let saved; try { saved = await api("/api/agents", { method: "POST", body }); await load(); } catch (err) { status.textContent = ""; button.disabled = false; return; } agent = agents.find((a) => a.id === saved.id) || saved; $("#agent-form-title").textContent = `Edit ${agent.name}`; $("#a-delete").hidden = false; render(); await rescore(status); button.disabled = false; } async function removeAgent(row) { if (!window.confirm(`Delete ${row.name}? Its votes and liked companies go with it.`)) { return; } try { await api(`/api/agents/${row.id}`, { method: "DELETE" }); } catch (err) { return; } agents = agents.filter((a) => a.id !== row.id); if (agent && agent.id === row.id) fill(null); else render(); } // Start the `score` job and wait for it, so "Saved and scored" means the // Roles tab already orders by what was saved. async function rescore(status) { status.textContent = "Saved. Scoring…"; let job; try { job = await api("/api/jobs", { method: "POST", body: { kind: "score", payload: {} } }); } catch (err) { status.textContent = "Saved, but scoring did not start."; return; } for (let i = 0; i < 300; i += 1) { await new Promise((resolve) => setTimeout(resolve, 1000)); let snapshot; try { snapshot = await api("/api/jobs"); } catch (err) { return; } const busy = [...snapshot.running, ...snapshot.queued].some((j) => j.id === job.id); if (busy) continue; const done = snapshot.recent.find((j) => j.id === job.id); if (done && done.state !== "done") { status.textContent = `Saved. Scoring ${done.state}.`; if (done.error) window.toast.error(`Scoring ${done.state}: ${done.error}`); return; } status.replaceChildren("Saved and scored. "); const link = document.createElement("a"); link.href = `/?agent=${agent.id}`; link.textContent = "See the best matches"; status.appendChild(link); return; } status.replaceChildren("Saved. Scoring is still running; "); const link = document.createElement("a"); link.href = "/settings/sources#runs"; link.textContent = "follow it under Runs"; status.append(link, "."); } // -------------------------------------------------------------------- init async function load() { agents = await api("/api/agents"); } document.addEventListener("DOMContentLoaded", async () => { if (!$("#agents-list")) return; try { await load(); } catch (err) { return; } // The default agent, the enabled one with the lowest id, is what the // Roles tab and the company list fall back to, so it is what opens. const first = byId(agents).find((a) => a.enabled) || byId(agents)[0] || null; fill(first); $("#agent-form").addEventListener("submit", save); $("#a-new").addEventListener("click", () => fill(null)); $("#a-delete").addEventListener("click", () => agent && removeAgent(agent)); }); })();