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>
This commit is contained in:
WolfandClaude Opus 5.5 committed 2026-09-23 12:48:12 +02:00
1 parent 24508dd6fc
commit 59a301c351
42 files changed
+2407 -998

No files matched your search

+381
View File
@@ -0,0 +1,381 @@
/* The whole stylesheet: the boilerplate's, with roledesk's palette in the
* custom properties (a quiet UI face and newsdesk's teal signal colour) and
* roledesk's own tabs in the section at the bottom. No build step.
*
* The `--desk-jobs-*` block at the bottom is how `<desk-jobs>` is themed. The
* element keeps to a shadow root and reads those properties, so an app skins
* it without forking it -- which is the deal that lets the queue ship its own
* UI and still look like it belongs here.
*/
:root {
color-scheme: light dark;
--bg: #eceff1;
--panel: #ffffff;
--fg: #1a2027;
--dim: #505c67;
--line: #d6dbdf;
--accent: #14655b;
--accent-fg: #ffffff;
--good: #15803d;
--warn: #b45309;
--error: #b91c1c;
--radius: 10px;
--gap: 1rem;
--font: "Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, Roboto,
"Helvetica Neue", Arial, sans-serif;
--mono: ui-monospace, "Cascadia Mono", Consolas, monospace;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #14181c;
--panel: #1b2126;
--fg: #e3e7ea;
--dim: #a8b2ba;
--line: #2a3238;
--accent: #4fb3a3;
--accent-fg: #14181c;
--good: #4ade80;
--warn: #fbbf24;
--error: #f87171;
}
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--fg);
font: 16px/1.55 var(--font);
}
code, pre { font-family: var(--mono); font-size: 0.9em; }
pre { overflow-x: auto; white-space: pre-wrap; word-break: break-word; }
a { color: var(--accent); }
/* -- the frame ------------------------------------------------------------ */
.top {
display: flex;
align-items: center;
gap: var(--gap);
flex-wrap: wrap;
padding: 0.75rem 1.25rem;
background: var(--panel);
border-bottom: 1px solid var(--line);
position: sticky;
top: 0;
z-index: 5;
}
.brand span { color: var(--accent); }
.brand {
font-weight: 700;
letter-spacing: 0.02em;
text-decoration: none;
color: var(--fg);
}
.top nav { display: flex; gap: 0.25rem; flex-wrap: wrap; }
.top nav a {
padding: 0.35rem 0.7rem;
border-radius: var(--radius);
text-decoration: none;
color: var(--dim);
}
.top nav a:hover { background: color-mix(in srgb, var(--accent) 12%, transparent); }
.top nav a.active { background: var(--accent); color: var(--accent-fg); }
main {
max-width: 62rem;
margin: 0 auto;
padding: 1.5rem 1.25rem 4rem;
}
h1 { font-size: 1.6rem; margin: 0 0 0.5rem; }
h2 { font-size: 1.1rem; margin: 0 0 0.75rem; }
.lede { color: var(--dim); max-width: 46rem; }
.muted { color: var(--dim); }
.small { font-size: 0.85rem; }
.note {
background: color-mix(in srgb, var(--accent) 8%, var(--panel));
border: 1px solid color-mix(in srgb, var(--accent) 35%, var(--line));
border-radius: var(--radius);
padding: 0.9rem 1rem;
max-width: 46rem;
}
.card {
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 1rem 1.15rem;
margin: 1.25rem 0;
}
.row-between {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: var(--gap);
}
.summary { display: grid; grid-template-columns: max-content 1fr; gap: 0.4rem 1rem; margin: 0; }
.summary dt { color: var(--dim); }
.summary dd { margin: 0; }
.buttons { display: flex; flex-wrap: wrap; gap: 0.5rem; }
button {
font: inherit;
padding: 0.4rem 0.9rem;
border-radius: var(--radius);
border: 1px solid transparent;
background: var(--accent);
color: var(--accent-fg);
cursor: pointer;
}
button:disabled { opacity: 0.55; cursor: progress; }
button.secondary {
background: transparent;
color: var(--fg);
border-color: var(--line);
}
.badge {
display: inline-block;
padding: 0 0.4rem;
border-radius: 999px;
background: var(--line);
color: var(--dim);
font-size: 0.8rem;
}
/* -- the notice log ------------------------------------------------------- */
.notice {
border: 1px solid var(--line);
border-left: 3px solid var(--dim);
border-radius: var(--radius);
padding: 0.6rem 0.8rem;
margin: 0.5rem 0;
}
.notice.error { border-left-color: var(--error); }
.notice.warning { border-left-color: var(--warn); }
.notice.good { border-left-color: var(--good); }
.notice-head { display: flex; justify-content: space-between; gap: var(--gap); align-items: start; }
.notice-text { font-weight: 600; }
/* -- toasts --------------------------------------------------------------- */
.toasts {
position: fixed;
right: 1rem;
bottom: 1rem;
width: min(26rem, calc(100vw - 2rem));
display: flex;
flex-direction: column;
gap: 0.5rem;
/* A popover brings its own box; this is a container, not a card. */
border: 0;
background: transparent;
padding: 0;
margin: 0;
inset: auto 1rem 1rem auto;
}
.toast {
display: flex;
gap: 0.5rem;
align-items: start;
background: var(--panel);
color: var(--fg);
border: 1px solid var(--line);
border-left: 3px solid var(--dim);
border-radius: var(--radius);
padding: 0.6rem 0.75rem;
box-shadow: 0 8px 24px rgb(0 0 0 / 18%);
animation: toast-in 160ms ease-out;
}
.toast.error { border-left-color: var(--error); }
.toast.warning { border-left-color: var(--warn); }
.toast.good { border-left-color: var(--good); }
.toast.out { opacity: 0; transition: opacity 180ms ease-in; }
.toast-body { flex: 1; min-width: 0; }
.toast-count { color: var(--dim); }
.toast-fix { color: var(--dim); }
.toast-actions { display: flex; gap: 0.5rem; align-items: center; }
.toast-actions:empty { display: none; }
.toast-close {
background: transparent;
color: var(--dim);
border: 0;
padding: 0 0.25rem;
line-height: 1;
}
@keyframes toast-in {
from { transform: translateY(6px); opacity: 0; }
to { transform: none; opacity: 1; }
}
/* -- the modules' elements ------------------------------------------------ */
/* `<desk-jobs>` and `<desk-schedules>` from the queue, `<auth-account>` from
* auth: all three read these, so they look like one application and none of
* them is forked to get it. An element the app has not got yet simply matches
* nothing. */
desk-jobs, desk-schedules, auth-account {
display: block;
--desk-jobs-bg: var(--panel);
--desk-jobs-fg: var(--fg);
--desk-jobs-dim: var(--dim);
--desk-jobs-accent: var(--accent);
--desk-jobs-error: var(--error);
--desk-jobs-font: var(--font);
--desk-jobs-gap: var(--gap);
--desk-jobs-radius: var(--radius);
}
/* -- roledesk's tabs ------------------------------------------------------ */
/* Roles, Applications, Agents and Companies, drawn by static/roles.js. */
input, select, textarea { font: inherit; color: inherit; }
.filters {
display: flex; flex-wrap: wrap; gap: .5rem; align-items: center;
padding: .75rem; margin-bottom: .5rem;
background: var(--panel);
border: 1px solid var(--line); border-radius: var(--radius);
}
.filters input[type="search"], .filters input[type="text"], .filters select {
padding: .4rem .55rem;
border: 1px solid var(--line); border-radius: .3rem;
background: var(--bg); min-width: 0;
}
.filters input[type="search"] { flex: 1 1 12rem; }
.filters input[type="text"] { flex: 1 1 8rem; }
.check {
display: flex; align-items: center; gap: .35rem;
color: var(--dim); font-size: .9rem; white-space: nowrap;
}
.check[hidden] { display: none; }
button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible,
textarea:focus-visible {
outline: 2px solid var(--accent); outline-offset: 1px;
}
.count { color: var(--dim); font-size: .85rem; margin: .75rem 0 .5rem; }
/* roles */
.roles { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: .5rem; }
.role {
background: var(--panel); border: 1px solid var(--line); border-radius: .5rem;
padding: .6rem .8rem;
display: flex; flex-direction: column; gap: .35rem;
}
.role-main { display: flex; flex-wrap: wrap; align-items: baseline; gap: .5rem; }
.role-title { font-weight: 600; text-decoration: none; }
.role-title:hover { text-decoration: underline; }
.role-company { color: var(--dim); }
.role-meta {
display: flex; flex-wrap: wrap; align-items: center; gap: .5rem;
color: var(--dim); font-size: .85rem;
}
.role-meta .badge {
background: transparent; color: var(--dim);
border: 1px solid var(--line); border-radius: 1rem;
padding: .05rem .55rem; font-size: .78rem;
}
.role-meta .badge:empty { display: none; }
.role-meta .role-score {
color: var(--accent); border-color: color-mix(in srgb, var(--accent) 45%, var(--line));
font-variant-numeric: tabular-nums;
}
.role-gated { color: var(--error); font-size: .85rem; }
.role-age { margin-left: auto; }
.role.muted, tr.muted { opacity: .55; }
.role.gated { opacity: .7; }
.affinity { display: inline-flex; gap: .15rem; }
.role-main .affinity { margin-left: auto; }
.affinity button {
background: none; border: 1px solid var(--line); border-radius: .3rem;
padding: .1rem .4rem; color: var(--dim); font-size: .85rem; line-height: 1.4;
}
.affinity button[aria-pressed="true"] {
color: var(--accent-fg); background: var(--accent); border-color: var(--accent);
}
.affinity button[data-value="-1"][aria-pressed="true"] {
background: var(--error); border-color: var(--error);
}
.save { align-self: flex-start; padding: .3rem .8rem; font-weight: 600; }
.save[disabled] {
background: var(--bg); color: var(--dim); border-color: var(--line); cursor: default;
}
/* agents */
.agents { list-style: none; margin: 0 0 1rem; padding: 0; display: flex; flex-direction: column; gap: .4rem; }
.agent {
display: flex; align-items: center; gap: .75rem; flex-wrap: wrap;
background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius);
padding: .5rem .75rem;
}
.agent a { font-weight: 600; text-decoration: none; }
.agent-meta { color: var(--dim); font-size: .85rem; flex: 1 1 12rem; }
.agent-form {
display: flex; flex-direction: column; gap: .6rem; max-width: 44rem;
background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius);
padding: .75rem 1rem;
}
.agent-form h2 { font-size: 1rem; margin: 0; }
.agent-form label { display: flex; flex-direction: column; gap: .2rem; font-size: .9rem; }
.agent-form label.inline { flex-direction: row; align-items: center; gap: .4rem; }
.agent-form input[type="text"], .agent-form textarea, .agent-form input[type="number"] {
background: var(--bg); border: 1px solid var(--line);
border-radius: .3rem; padding: .35rem .5rem; width: 100%;
}
.agent-form textarea { font-family: var(--mono); font-size: .85rem; }
.agent-form .hint { color: var(--dim); font-size: .8rem; overflow-wrap: anywhere; }
.weights { display: flex; gap: .75rem; flex-wrap: wrap; border: 1px solid var(--line); border-radius: .3rem; }
.weights label { flex: 1 1 6rem; }
.agent-actions { display: flex; gap: .5rem; flex-wrap: wrap; }
/* applications and companies */
table.list { width: 100%; border-collapse: collapse; background: var(--panel); }
table.list th, table.list td {
text-align: left; padding: .5rem .6rem; border-bottom: 1px solid var(--line);
font-size: .9rem;
}
table.list .num { text-align: right; font-variant-numeric: tabular-nums; }
table.list select { padding: .25rem .4rem; }
/* Below tablet width a table stops being a table: each row becomes a card,
its cells stacked, so nothing scrolls sideways to be read. */
@media (max-width: 640px) {
table.list thead { display: none; }
table.list, table.list tbody, table.list tr, table.list td { display: block; width: 100%; }
table.list tr { margin-bottom: .6rem; border: 1px solid var(--line); border-radius: .4rem; }
table.list td { border-bottom: none; }
table.list .num { text-align: left; }
table.list td::before {
content: attr(data-label);
display: block; font-size: .72rem; color: var(--dim); margin-bottom: .1rem;
}
}
@media (max-width: 480px) {
.role-age, .role-main .affinity { margin-left: 0; }
}
+73
View File
@@ -0,0 +1,73 @@
/* The one way this app talks to its own API.
*
* const kinds = await api("/api/jobs/kinds");
* await api("/api/jobs", { method: "POST", body: { kind: "tick" } });
*
* Every button on every tab goes through `api`, so a failure is always one
* toast carrying the server's own sentence. That is the other half of the
* bargain the exception handler in `app/main.py` makes: it promises every
* error body is `{"detail": "<one readable sentence>"}`, and this is what
* cashes the promise. Wording a failure in the browser as well would be two
* descriptions of one thing, and the client's would be the one that was wrong.
*
* `body` may be a plain object; it is JSON-encoded with the header set, since
* forgetting the header is the failure that looks like a server bug.
*/
(function () {
"use strict";
async function api(path, options) {
const o = Object.assign({}, options);
const headers = Object.assign({ Accept: "application/json" }, o.headers);
if (o.body !== undefined && typeof o.body !== "string") {
headers["Content-Type"] = "application/json";
o.body = JSON.stringify(o.body);
}
o.headers = headers;
let response;
try {
response = await fetch(path, o);
} catch (e) {
// The network, not the server: there is no `detail` to read.
window.toast.error("Could not reach the server. Is it still running?");
throw e;
}
const text = await response.text();
let data = null;
if (text) {
try { data = JSON.parse(text); } catch (e) { data = null; }
}
if (!response.ok) {
const detail = (data && data.detail)
|| `The server answered ${response.status} and said nothing about why.`;
window.toast.error(String(detail));
const error = new Error(detail);
error.status = response.status;
error.detail = detail;
throw error;
}
return data;
}
/* `window.esc` is toasts.js's — it loads first and had to have one anyway,
and two copies of an escaper is one of them being fixed. See base.html
for the load order that makes this safe. */
/* The queue's own elements do their own fetching, so their failures never
pass through `api()`. They raise an event carrying the server's `detail`
instead, and this is the same bargain kept one level out: one toast, the
server's sentence, nothing reworded here.
`desk-jobs:notice` is a notice arriving on the element's socket, which
live.js already delivers as `app:notice` — so it is deliberately not
listened for. Two toasts for one failure is the bug that listening would
buy. */
document.addEventListener("desk-schedules:error", (e) => {
const detail = (e.detail && e.detail.detail) || "That change was refused.";
window.toast.error(String(detail));
});
window.api = api;
})();
+66
View File
@@ -0,0 +1,66 @@
/* The Jobs tab: a button per kind.
*
* The list comes from `/api/jobs/kinds`, which is the registry, so a new
* `@job` in `app/jobs.py` is a new button and this file is not edited. What
* the queue is doing is `<desk-jobs>`'s business, and it draws itself.
*
* Failures are the server's sentence through `api()`, which toasts it -- so
* there is no error handling here beyond keeping the button usable.
*/
(function () {
"use strict";
const host = document.getElementById("kinds");
if (!host) return;
async function start(kind, button) {
button.disabled = true;
try {
const job = await window.api("/api/jobs", { method: "POST", body: { kind } });
window.toast.good(`${job.label || kind}: queued.`);
} catch (e) {
/* already toasted */
} finally {
button.disabled = false;
}
}
async function draw() {
let kinds;
try {
kinds = await window.api("/api/jobs/kinds");
} catch (e) {
host.innerHTML = '<span class="muted">could not read the job kinds</span>';
return;
}
if (!kinds.length) {
host.innerHTML = '<span class="muted">nothing is registered</span>';
return;
}
host.innerHTML = "";
kinds.forEach((k) => {
const button = document.createElement("button");
button.type = "button";
button.textContent = k.label || k.kind;
button.title = k.solo ? `${k.kind} -- one at a time` : k.kind;
button.dataset.kind = k.kind;
button.addEventListener("click", () => start(k.kind, button));
host.appendChild(button);
});
}
/* `<desk-jobs>` takes up no space while the queue is idle, so the line that
says so is the app's to show and hide. Off the same socket the element
reads, through live.js, rather than by asking the element: it keeps to a
shadow root and owes nobody an answer about its own height. */
document.addEventListener("app:jobs", (e) => {
const idle = document.getElementById("idle");
if (!idle) return;
const state = e.detail || {};
const busy = (state.running || []).length + (state.queued || []).length;
idle.hidden = busy > 0;
});
document.addEventListener("DOMContentLoaded", draw);
})();
+84
View File
@@ -0,0 +1,84 @@
/* The page's one connection to the server: the queue's socket.
*
* `/ws/jobs` sends two kinds of message, and this turns each into a document
* event so that no other script opens a socket of its own — five tabs each
* holding their own would be five reconnect loops to get subtly wrong:
*
* app:jobs the whole queue: {running, queued, recent, ...}. Sent on
* connect and after every change. `window.live.jobs` holds the
* latest, for a script that loads after a message.
* app:notice one notice from the log (app/notices.py), its count
* included. toasts.js shows it.
* app:schedules the schedule list, whenever one fires, is skipped or is
* edited. `<desk-schedules>` holds its own socket and does not
* need this; it is here for a page that wants to say when the
* next run is without drawing the whole table.
*
* Nothing here dispatches by hand: the name is taken from the message, so a
* fourth type is a listener somewhere and no edit to this file.
*
* Reconnects with backoff, because the server restarting is the normal case
* and a page that needs reloading after every deploy is a page people reload
* by habit and then trust less.
*/
(function () {
"use strict";
const live = { jobs: null, connected: false };
window.live = live;
let backoff = 1000;
function connect() {
const proto = location.protocol === "https:" ? "wss:" : "ws:";
const socket = new WebSocket(`${proto}//${location.host}/ws/jobs`);
socket.onopen = () => {
backoff = 1000;
live.connected = true;
};
socket.onmessage = (ev) => {
let msg;
try { msg = JSON.parse(ev.data); } catch (e) { return; }
const { type, ...body } = msg;
if (!type) return;
if (type === "jobs") live.jobs = body;
document.dispatchEvent(new CustomEvent(`app:${type}`, { detail: body }));
};
socket.onclose = () => {
live.connected = false;
setTimeout(async () => {
if (await signedOut()) return;
connect();
}, backoff);
backoff = Math.min(backoff * 2, 30000);
};
}
/* A refused handshake and a dead server look identical from here: the
middleware in `auth/` closes the socket before accepting it, which the
server turns into an HTTP 403 on the upgrade, and the browser reports the
same abnormal close it reports for "the server is gone". So one cheap
request tells them apart, and an expired session sends the page to the
door instead of leaving it reconnecting quietly against a login form for
the rest of the afternoon. `<desk-jobs>` has the same trick as its
`probe` attribute; it is done here so that it is done on every tab. */
async function signedOut() {
let answer;
try {
answer = await fetch("/api/jobs", { headers: { Accept: "application/json" } });
} catch (e) {
return false; // offline: keep the backoff going
}
if (answer.status !== 401 && answer.status !== 403) return false;
const next = location.pathname + location.search;
location.assign(`/login?next=${encodeURIComponent(next)}`);
return true;
}
document.addEventListener("DOMContentLoaded", () => {
// The login page has no session for the socket to use, and asking would
// only be a 401 every second while somebody types a password.
if (location.pathname !== "/login") connect();
});
})();
+85
View File
@@ -0,0 +1,85 @@
/* The Messages tab: the notice log as a table.
*
* `/api/notices` is the queue's own route (`pipeline/web/jobs.py`) -- the log
* belongs to the queue, the wording belongs to the app, and this page is only
* the reading of it. It redraws on `app:notice` so a failure that happens
* while you are looking at this tab appears without a reload.
*/
(function () {
"use strict";
const host = document.getElementById("notices");
const clearAll = document.getElementById("clear-all");
if (!host) return;
const esc = window.esc;
function when(iso) {
if (!iso) return "";
const d = new Date(iso);
return isNaN(d) ? iso : d.toLocaleString();
}
function row(n) {
const count = n.count > 1 ? `<span class="badge">x${n.count}</span>` : "";
return `
<article class="notice ${esc(n.level)}" data-id="${n.id}">
<div class="notice-head">
<span class="notice-text">${esc(n.text)} ${count}</span>
<button type="button" class="secondary" data-clear="${n.id}">Clear</button>
</div>
<div class="small muted">${esc(n.code)}${n.key ? " / " + esc(n.key) : ""}
-- last said ${esc(when(n.last_at))}
${n.kind === "bug" ? "-- looks like a bug rather than a bad day" : ""}</div>
${n.fix ? `<div class="small">${esc(n.fix)}</div>` : ""}
${n.detail ? `<details class="small"><summary>details</summary>
<pre>${esc(n.detail)}</pre></details>` : ""}
</article>`;
}
async function draw() {
let list;
try {
list = await window.api("/api/notices");
} catch (e) {
host.innerHTML = '<span class="muted">could not read the log</span>';
return;
}
if (!list.length) {
host.innerHTML = '<span class="muted">Nothing to report.</span>';
return;
}
host.innerHTML = list.map(row).join("");
}
host.addEventListener("click", async (e) => {
const id = e.target.dataset && e.target.dataset.clear;
if (!id) return;
e.target.disabled = true;
try {
await window.api(`/api/notices/${id}`, { method: "DELETE" });
await draw();
} catch (err) {
e.target.disabled = false;
}
});
if (clearAll) {
clearAll.addEventListener("click", async () => {
clearAll.disabled = true;
try {
const out = await window.api("/api/notices", { method: "DELETE" });
window.toast.good(`Cleared ${out.cleared}.`);
await draw();
} catch (e) {
/* already toasted */
} finally {
clearAll.disabled = false;
}
});
}
document.addEventListener("app:notice", draw);
document.addEventListener("DOMContentLoaded", draw);
})();
+524
View File
@@ -0,0 +1,524 @@
/* 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();
});
})();
+226
View File
@@ -0,0 +1,226 @@
/* Toasts: the one place on screen for messages to the user.
*
* Adapted from health's `webapp/static/toasts.js`, which is where the
* behaviour was worked out. Two sources, one look:
*
* server notices from the log (app/notices.py), delivered by live.js as
* `app:notice`. A problem (warning, error) interrupts the first
* time; a repeat within five minutes only bumps the count of a
* toast already on screen, since it is already in the log. An
* outcome (good, info) is news every time. On page load, notices
* raised since the last visit are shown too, so one raised while
* no tab was open is not lost.
* pages `toast.error(text)`, `toast.good(text)`, ... for the outcome of
* something the user just did. These are not logged: the user is
* looking at the result.
*
* Errors stay until dismissed; everything else fades. Progress of work in
* flight is not a toast -- that is what the job's progress bar is for.
*/
(function () {
"use strict";
const FADE_MS = { info: 5000, good: 5000, warning: 10000, error: 0 };
const SEEN_KEY = "app.notices.seen";
const MAX_ON_LOAD = 3;
let stack = null;
const byCode = new Map(); // "code|key" -> toast element, for server notices
/* Escaping, once for the page. This file needs one and loads first, so it
is the one that exports it: every other script here builds a little HTML
out of server strings, and a notice's detail is raw error text that has
already been through somebody else's parser once. Two copies of an
escaper is one of them being the one that gets fixed. */
function esc(s) {
return String(s === null || s === undefined ? "" : s).replace(/[&<>"']/g, (c) => ({
"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;",
})[c]);
}
window.esc = esc;
/* The stack is a manual popover, so it lives in the browser's top layer and
shows above a modal <dialog>. The top layer is ordered by opening, so it
is reopened on every new toast to stay above whatever opened since. */
const POPOVER = typeof HTMLElement.prototype.showPopover === "function";
function container() {
if (!stack) {
stack = document.createElement("div");
stack.className = "toasts";
stack.setAttribute("aria-live", "polite");
if (POPOVER) stack.setAttribute("popover", "manual");
document.body.appendChild(stack);
}
return stack;
}
/* A modal dialog makes the rest of the document inert, a popover opened
after it included: the toast would be visible but its buttons dead. So
while a modal is open the stack lives inside it, and goes back to the body
when the modal closes. */
function raise() {
const modal = document.querySelector("dialog:modal");
const home = modal || document.body;
if (stack.parentElement !== home) {
home.appendChild(stack);
if (modal) {
modal.addEventListener("close", () => {
if (stack.parentElement !== modal) return;
document.body.appendChild(stack);
if (stack.children.length) reopen();
}, { once: true });
}
}
reopen();
}
function reopen() {
if (!POPOVER) return;
if (stack.matches(":popover-open")) stack.hidePopover();
stack.showPopover();
}
/* opts: level (info|good|warning|error), text, detail, fix, count, sticky,
action {label, run}, link {label, href}, id (dedupe key) */
function show(opts) {
const o = typeof opts === "string" ? { text: opts } : opts;
const level = o.level || "info";
if (o.id && byCode.has(o.id)) {
const existing = byCode.get(o.id);
if (existing.isConnected) {
update(existing, o);
return existing;
}
byCode.delete(o.id);
}
const t = document.createElement("div");
t.className = `toast ${level}`;
t.setAttribute("role", level === "error" ? "alert" : "status");
t.innerHTML = `
<div class="toast-body">
<div class="toast-text"></div>
${o.fix ? `<div class="toast-fix small">${esc(o.fix)}</div>` : ""}
${o.detail ? `<details class="toast-detail small"><summary>details</summary>
<pre>${esc(o.detail)}</pre></details>` : ""}
<div class="toast-actions">
${o.action ? `<button type="button" data-act="action">${esc(o.action.label)}</button>` : ""}
${o.link ? `<a href="${esc(o.link.href)}">${esc(o.link.label)}</a>` : ""}
</div>
</div>
<button type="button" class="toast-close" data-act="close" aria-label="dismiss">x</button>`;
update(t, o);
t.addEventListener("click", (e) => {
const act = e.target.dataset && e.target.dataset.act;
if (act === "close") dismiss(t);
else if (act === "action" && o.action) {
o.action.run();
dismiss(t);
}
});
container().appendChild(t);
raise();
if (o.id) byCode.set(o.id, t);
const fade = o.sticky ? 0 : FADE_MS[level];
if (fade) {
let timer = setTimeout(() => dismiss(t), fade);
// Reading it keeps it: a toast does not fade from under the cursor.
t.addEventListener("mouseenter", () => clearTimeout(timer));
t.addEventListener("mouseleave", () => { timer = setTimeout(() => dismiss(t), fade); });
}
return t;
}
function update(t, o) {
const count = o.count > 1 ? ` <span class="toast-count">x${o.count}</span>` : "";
t.querySelector(".toast-text").innerHTML = esc(o.text) + count;
}
function dismiss(t) {
t.classList.add("out");
setTimeout(() => {
t.remove();
if (POPOVER && stack && !stack.children.length && stack.matches(":popover-open")) {
stack.hidePopover();
}
}, 180);
}
const toast = {
show,
info: (text, o) => show({ ...o, level: "info", text }),
good: (text, o) => show({ ...o, level: "good", text }),
warning: (text, o) => show({ ...o, level: "warning", text }),
error: (text, o) => show({ ...o, level: "error", text }),
};
window.toast = toast;
/* -- server notices ---------------------------------------------------- */
function seen() {
try { return localStorage.getItem(SEEN_KEY) || ""; } catch (e) { return ""; }
}
function markSeen(at) {
try { if (at > seen()) localStorage.setItem(SEEN_KEY, at); } catch (e) { /* convenience */ }
}
const PROBLEM = new Set(["warning", "error"]);
function fromNotice(n) {
const t = {
id: `${n.code}|${n.key || ""}`,
level: n.level,
text: n.text,
fix: n.fix,
detail: n.detail,
link: { label: "all messages", href: "/messages" },
};
if (PROBLEM.has(n.level)) t.count = n.count;
if (n.level === "good") t.action = { label: "reload", run: () => location.reload() };
return t;
}
/* When this page last showed each problem. A repeat within QUIET_MS only
bumps a count, so a burst -- a job retried in a loop -- is one toast; a
repeat after that, such as a retry the user just pressed, is shown again. */
const QUIET_MS = 5 * 60 * 1000;
const shownAt = new Map();
function onNotice(n) {
const id = `${n.code}|${n.key || ""}`;
const onScreen = byCode.get(id);
markSeen(n.last_at || "");
if (PROBLEM.has(n.level) && n.count > 1 && !(onScreen && onScreen.isConnected)
&& Date.now() - (shownAt.get(id) || 0) < QUIET_MS) return;
shownAt.set(id, Date.now());
show(fromNotice(n));
}
async function missed() {
// A browser that has never been here shows the last day's messages, not
// the whole fortnight the log keeps.
const since = seen() || new Date(Date.now() - 86400000).toISOString();
let list;
try {
const r = await fetch("/api/notices", { headers: { Accept: "application/json" } });
if (!r.ok) return;
list = await r.json();
} catch (e) { return; }
const fresh = list.filter((n) => n.last_at > since);
fresh.slice(0, MAX_ON_LOAD).forEach((n) => show(fromNotice(n)));
if (fresh.length > MAX_ON_LOAD) {
toast.info(`${fresh.length - MAX_ON_LOAD} more messages since your last visit.`,
{ link: { label: "all messages", href: "/messages" } });
}
if (fresh.length) markSeen(fresh[0].last_at);
}
document.addEventListener("app:notice", (e) => onNotice(e.detail));
document.addEventListener("DOMContentLoaded", () => {
// Not on Messages: the table is right there, in full, already.
if (location.pathname !== "/login" && location.pathname !== "/messages") missed();
});
})();