Files
jobboard/app/static/roles.js
T
WolfandClaude Opus 5.5 59a301c351 Wire the app like the boilerplate: door, queue, schedules, eight tabs
app/main.py assembles it in the boilerplate's order, auth.connect first,
then the queue with the scheduler and the pages. TABS is Roles,
Applications, Agents, Companies, Jobs, Schedules, Messages and Account:
the alpha page's three views become templates on the boilerplate's
base.html, driven by static/roles.js (the old app.js) through api() and
toasts.js, over the unchanged JSON routes. Companies lists every board with
its open roles and the affinity control. A 422 is one sentence, so a toast
never reads [object Object].

Config takes the boilerplate's shape: APP_CONFIG or config.yaml, a missing
file is the defaults, an unknown key is an error. roles.yaml is gone;
config.yaml is the committed default and carries the starter agents.

pull is now a job that asks for the pull cascade, because a schedule
enqueues a job kind; its default schedule, every 6h, is declared beside it
in app/jobs/cascade.py. pull_batch's targets are keyword-only so the Jobs
tab offers no batch button. `app worker` is the boilerplate's; `app job`
still drains a queue of its own and fires no schedules.

test_coupling holds pipeline, auth and desk apart (desk may import
pipeline) and plugins to desk; test_architecture keeps app's layers, now
with main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 12:48:12 +02:00

525 lines
18 KiB
JavaScript

/* roledesk's four tabs: Roles, Applications, Agents and Companies.
*
* Each template renders an empty shell; everything on screen comes from the
* JSON routes in app/web/api.py, and every action (Save, an affinity click, a
* status change, an agent saved) is a fetch from here, not a form post. One
* script for the four, because they share the company list and the affinity
* control; `init` looks at which containers the page has.
*
* Every request goes through `api()` from app.js, so a failure is one toast
* carrying the server's own sentence. The catch blocks here only put the
* control back the way it was.
*/
(function () {
"use strict";
const api = window.api;
/** @type {Map<string, object>} company_key -> row from /api/companies */
let companies = new Map();
/** @type {Map<string, object>} role_uid -> application, for roles already tracked */
let trackedByRole = new Map();
/** @type {object[]} the last /api/roles response, already muted-filtered by the server */
let roles = [];
/** @type {object[]} every search agent, from /api/agents */
let agents = [];
const $ = (sel, root = document) => root.querySelector(sel);
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
function count(n, one, many) {
return `${n} ${n === 1 ? one : many || `${one}s`}`;
}
async function loadCompanies() {
const rows = await api("/api/companies");
companies = new Map(rows.map((c) => [c.key, c]));
}
async function loadApplications() {
const applications = await api("/api/applications");
trackedByRole = new Map(applications.filter((a) => a.role_uid).map((a) => [a.role_uid, a]));
return applications;
}
async function loadAgents() {
agents = await api("/api/agents");
}
function cell(tr, label, content) {
const td = document.createElement("td");
td.dataset.label = label;
if (typeof content === "string") td.textContent = content;
else td.appendChild(content);
tr.appendChild(td);
return td;
}
// ---------------------------------------------------------------- affinity
const AFFINITY_LEVELS = [
{ value: -1, label: "Mute" },
{ value: 0, label: "Neutral" },
{ value: 1, label: "Like" },
{ value: 2, label: "Favourite" },
];
/* The four buttons. `onChange` runs after the server accepted the change,
so each tab decides what a change means for it: the role list refetches,
since muting changes which roles come back, and the company table redraws. */
function affinityControl(companyKey, current, onChange) {
const span = document.createElement("span");
span.className = "affinity";
span.setAttribute("role", "group");
span.setAttribute("aria-label", "Company affinity");
for (const level of AFFINITY_LEVELS) {
const button = document.createElement("button");
button.type = "button";
button.dataset.value = String(level.value);
button.textContent = level.label[0];
button.title = level.label;
button.setAttribute("aria-label", level.label);
button.setAttribute("aria-pressed", String(level.value === current));
button.addEventListener("click", () => setAffinity(companyKey, level.value, onChange));
span.appendChild(button);
}
return span;
}
async function setAffinity(companyKey, affinity, onChange) {
if (!companyKey) return;
let updated;
try {
updated = await api(`/api/companies/${encodeURIComponent(companyKey)}/affinity`, {
method: "POST", body: { affinity },
});
} catch (err) {
return;
}
const company = companies.get(companyKey);
if (company) company.affinity = updated.affinity;
await onChange();
}
// ------------------------------------------------------------------- roles
function filterParams() {
const params = new URLSearchParams();
for (const key of ["q", "company", "place"]) {
const value = $(`#f-${key}`).value.trim();
if (value) params.set(key, value);
}
for (const key of ["function", "remote", "days"]) {
const value = $(`#f-${key}`).value;
if (value) params.set(key, value);
}
if ($("#f-show-muted").checked) params.set("show_muted", "true");
const agent = $("#f-agent").value;
if (agent) {
params.set("agent", agent);
if ($("#f-gated").checked) params.set("gated", "1");
}
return params;
}
async function loadRoles() {
try {
roles = await api(`/api/roles?${filterParams().toString()}`);
} catch (err) {
return;
}
renderRoles();
}
function relativeAge(iso) {
const then = new Date(iso);
const minutes = Math.max(0, Math.floor((Date.now() - then.getTime()) / 60000));
if (minutes < 60) return `${minutes} min ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours} h ago`;
return `${Math.floor(hours / 24)} d ago`;
}
function renderRoles() {
const list = $("#roles-list");
const template = $("#role-row");
list.replaceChildren();
for (const role of roles) {
const node = template.content.cloneNode(true);
const li = node.querySelector(".role");
const company = companies.get(role.company_key);
if (company && company.affinity === -1) li.classList.add("muted");
const titleLink = node.querySelector(".role-title");
titleLink.textContent = role.title || "(untitled)";
titleLink.href = role.original_url || "#";
node.querySelector(".role-company").textContent = role.company || "";
node.querySelector(".role-place").textContent = role.place || "";
node.querySelector(".role-remote").textContent = role.remote || "";
node.querySelector(".role-function").textContent = role.function || "";
node.querySelector(".role-age").textContent = relativeAge(role.first_seen);
if (role.score !== null && role.score !== undefined) {
const badge = node.querySelector(".role-score");
badge.textContent = role.gated_reason ? "gated" : role.score.toFixed(2);
badge.title = "Score for the selected agent";
node.querySelector(".role-gated").textContent = role.gated_reason || "";
if (role.gated_reason) li.classList.add("gated");
}
node.querySelector(".affinity").replaceWith(
affinityControl(role.company_key, company ? company.affinity : 0, loadRoles));
const saveButton = node.querySelector(".save");
setSaveButton(saveButton, role.uid);
saveButton.addEventListener("click", () => saveRole(role.uid, saveButton));
list.appendChild(node);
}
$("#roles-count").textContent = count(roles.length, "role");
}
function setSaveButton(button, uid) {
const saved = trackedByRole.has(uid);
button.textContent = saved ? "Saved" : "Save";
button.disabled = saved;
}
async function saveRole(uid, button) {
button.disabled = true;
button.textContent = "Saving…";
try {
const application = await api("/api/applications", {
method: "POST", body: { role_uid: uid, status: "saved" },
});
trackedByRole.set(uid, application);
setSaveButton(button, uid);
} catch (err) {
button.disabled = false;
button.textContent = "Save";
}
}
// The filter bar's order: "Newest", or one agent's score. Keeps the current
// choice when the list is refreshed, unless that agent is gone.
function renderAgentSelect() {
const select = $("#f-agent");
const current = select.value;
select.replaceChildren(new Option("Newest", ""));
for (const agent of agents) {
const label = agent.enabled ? agent.name : `${agent.name} (off)`;
select.appendChild(new Option(label, String(agent.id)));
}
select.value = agents.some((a) => String(a.id) === current) ? current : "";
$("#show-gated").hidden = !select.value;
}
/* `?q=`, `?company=`, `?place=` and `?agent=` prefill the filter bar, which
is how the Companies and Agents tabs link into this one. */
function prefill() {
const query = new URLSearchParams(location.search);
for (const key of ["q", "company", "place"]) {
if (query.get(key)) $(`#f-${key}`).value = query.get(key);
}
const agent = query.get("agent");
if (agent && agents.some((a) => String(a.id) === agent)) {
$("#f-agent").value = agent;
$("#show-gated").hidden = false;
}
}
async function initRoles() {
try {
await Promise.all([loadCompanies(), loadApplications(), loadAgents()]);
} catch (err) {
return;
}
renderAgentSelect();
prefill();
await loadRoles();
const refetch = debounce(loadRoles, 300);
for (const key of ["q", "company", "place"]) {
$(`#f-${key}`).addEventListener("input", refetch);
}
for (const sel of ["#f-function", "#f-remote", "#f-days", "#f-show-muted", "#f-gated"]) {
$(sel).addEventListener("change", loadRoles);
}
$("#f-agent").addEventListener("change", () => {
$("#show-gated").hidden = !$("#f-agent").value;
loadRoles();
});
$("#filters").addEventListener("submit", (e) => e.preventDefault());
}
// ------------------------------------------------------------ applications
// `ROLEDESK_STATUSES` is set by applications.html from the same `STATUSES`
// tuple the store validates against, so this list can never drift from
// what a `POST .../status` will accept.
function statusSelect(current) {
const select = document.createElement("select");
for (const status of window.ROLEDESK_STATUSES) {
const option = document.createElement("option");
option.value = status;
option.textContent = status[0].toUpperCase() + status.slice(1);
option.selected = status === current;
select.appendChild(option);
}
return select;
}
function renderApplications(applications) {
const body = $("#applications-list");
body.replaceChildren();
for (const application of applications) {
const tr = document.createElement("tr");
if (application.url) {
const link = document.createElement("a");
link.href = application.url;
link.target = "_blank";
link.rel = "noopener";
link.textContent = application.role_title || "(untitled)";
cell(tr, "Role", link);
} else {
cell(tr, "Role", application.role_title || "(untitled)");
}
const company = companies.get(application.company_key);
cell(tr, "Company", company ? company.name : application.company_key);
const select = statusSelect(application.status);
select.addEventListener("change", () => setStatus(application.id, select));
cell(tr, "Status", select);
cell(tr, "Next", [application.next_action, application.next_date]
.filter(Boolean).join(" · "));
body.appendChild(tr);
}
$("#applications-count").textContent =
count(applications.length, "tracked application");
}
async function setStatus(id, select) {
select.disabled = true;
try {
await api(`/api/applications/${encodeURIComponent(id)}/status`, {
method: "POST", body: { status: select.value },
});
renderApplications(await loadApplications());
} catch (err) {
select.disabled = false;
}
}
async function initApplications() {
try {
const [, applications] = await Promise.all([loadCompanies(), loadApplications()]);
renderApplications(applications);
} catch (err) {
/* already toasted */
}
}
// ------------------------------------------------------------------ agents
function renderAgents() {
const list = $("#agents-list");
list.replaceChildren();
for (const agent of agents) {
const li = document.createElement("li");
li.className = "agent";
const name = document.createElement("a");
name.href = `/?agent=${agent.id}`;
name.title = "Roles, ordered by this agent's score";
name.textContent = agent.name;
const meta = document.createElement("span");
meta.className = "agent-meta";
const gates = agent.gates.map((g) => `${g.mode} ${g.field}`).join(", ") || "no gates";
meta.textContent = `${agent.enabled ? "" : "off · "}${gates}`;
const edit = document.createElement("button");
edit.type = "button";
edit.className = "secondary";
edit.textContent = "Edit";
edit.addEventListener("click", () => fillAgentForm(agent));
li.append(name, meta, edit);
list.appendChild(li);
}
$("#agents-count").textContent = count(agents.length, "agent");
}
function fillAgentForm(agent) {
$("#agent-form-title").textContent = agent ? `Edit ${agent.name}` : "New agent";
$("#a-id").value = agent ? String(agent.id) : "";
$("#a-name").value = agent ? agent.name : "";
$("#a-intent").value = agent ? agent.intent : "";
$("#a-gates").value = JSON.stringify(agent ? agent.gates : [], null, 2);
const weights = agent ? agent.weights : { fit: 0.6, recency: 0.2, affinity: 0.2 };
$("#a-fit").value = weights.fit;
$("#a-recency").value = weights.recency;
$("#a-affinity").value = weights.affinity;
$("#a-enabled").checked = agent ? agent.enabled : true;
$("#a-delete").hidden = !agent;
$("#agent-status").textContent = "";
}
async function saveAgent(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 id = $("#a-id").value;
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),
},
enabled: $("#a-enabled").checked,
};
if (id) body.id = Number(id);
let saved;
try {
saved = await api("/api/agents", { method: "POST", body });
} catch (err) {
status.textContent = "";
return;
}
try {
await loadAgents();
renderAgents();
} catch (err) {
/* already toasted; the save itself landed */
}
fillAgentForm(saved);
await rescore(status, saved);
}
async function deleteAgent() {
const id = $("#a-id").value;
if (!id || !confirm("Delete this agent and its scores?")) return;
try {
await api(`/api/agents/${encodeURIComponent(id)}`, { method: "DELETE" });
fillAgentForm(null);
await loadAgents();
renderAgents();
} catch (err) {
/* already toasted */
}
}
// 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, agent) {
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 roles";
status.appendChild(link);
return;
}
status.textContent = "Saved. Scoring is still running; see the Jobs tab.";
}
async function initAgents() {
try {
await loadAgents();
} catch (err) {
return;
}
renderAgents();
$("#agent-form").addEventListener("submit", saveAgent);
$("#a-new").addEventListener("click", () => fillAgentForm(null));
$("#a-delete").addEventListener("click", deleteAgent);
}
// --------------------------------------------------------------- companies
function renderCompanies() {
const q = $("#c-q").value.trim().toLowerCase();
const affinity = $("#c-affinity").value;
const rows = [...companies.values()]
.filter((c) => !q || c.name.toLowerCase().includes(q) || c.board.includes(q))
.filter((c) => affinity === "" || String(c.affinity) === affinity)
.sort((a, b) => b.open_roles - a.open_roles || a.name.localeCompare(b.name));
const body = $("#companies-list");
body.replaceChildren();
for (const company of rows) {
const tr = document.createElement("tr");
if (company.affinity === -1) tr.classList.add("muted");
const link = document.createElement("a");
link.href = `/?company=${encodeURIComponent(company.name)}`;
link.title = "This company's open roles";
link.textContent = company.name;
cell(tr, "Company", link);
cell(tr, "Board", company.board || "");
cell(tr, "Open roles", String(company.open_roles)).className = "num";
cell(tr, "Affinity",
affinityControl(company.key, company.affinity, async () => renderCompanies()));
body.appendChild(tr);
}
const open = rows.reduce((sum, c) => sum + c.open_roles, 0);
$("#companies-count").textContent =
`${count(rows.length, "company", "companies")}, ${count(open, "open role")}`;
}
async function initCompanies() {
try {
await loadCompanies();
} catch (err) {
return;
}
renderCompanies();
$("#c-q").addEventListener("input", debounce(renderCompanies, 150));
$("#c-affinity").addEventListener("change", renderCompanies);
}
// -------------------------------------------------------------------- init
document.addEventListener("DOMContentLoaded", () => {
if ($("#roles-list")) initRoles();
if ($("#applications-list")) initApplications();
if ($("#agents-list")) initAgents();
if ($("#companies-list")) initCompanies();
});
})();