Files
jobboard/pipeline/web/static/jobs.js
T
WolfandClaude Fable 5.1 c74546d959 Refresh pipeline/ from boilerplate: schedules on a phone
git archive of boilerplate main (21c5faa), which gives desk-schedules a
two-line narrow layout below 40rem, a data-label per cell, and phone-sized
touch targets in both desk-jobs and desk-schedules. pipeline/README.md
gained the matching lines.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 21:37:49 +02:00

293 lines
9.5 KiB
JavaScript

/* The queue, on screen, for an app that has not written a UI yet.
*
* <script type="module" src="/_jobs/jobs.js"></script>
* <desk-jobs></desk-jobs>
*
* That is the whole of it. The element finds `/ws/jobs` itself, shows what is
* running with a progress bar and a Kill button each, says how many are
* waiting, and reconnects when the server restarts under you.
*
* One file, and the styles are in it rather than beside it, because the
* shadow root scopes them anyway and a second file is a second route, a
* second cache header and a second thing to forget to copy. Themed from
* outside through the custom properties at the top of `CSS` — set them on
* `desk-jobs` or on `:root` and nothing here has to be forked.
*
* What it deliberately does not do is talk about failures. It raises a
* `desk-jobs:notice` event and leaves the wording to the app, because a
* useful sentence names things only the app knows — its backends, its feeds,
* its config keys. `pipeline/notices.py` is the same split on the server.
*
* Attributes, all optional:
* base="/api" prefix for the HTTP calls, if the router is mounted deeper
* socket="..." the socket's URL, if it is not `/ws/jobs` on this origin
* probe="/api/status"
* an authenticated endpoint to try when the socket closes. A
* refused handshake and a dead server look identical from
* here — the server rejects an unauthenticated upgrade before
* completing it, so the browser reports the same abnormal
* close for "your session expired" as for "the server is
* gone". One cheap request tells them apart. Without this the
* element assumes the server went away, which is the more
* common reason and the less confusing thing to be wrong about.
* idle="hide" with nothing running or queued, take up no space. The
* default, since a chip that is always there is furniture.
*/
const CSS = `
:host {
--desk-jobs-bg: #16181d;
--desk-jobs-fg: #e7e9ee;
--desk-jobs-dim: #9aa1ad;
--desk-jobs-accent: #4c8dff;
--desk-jobs-error: #ff6b6b;
--desk-jobs-radius: 10px;
--desk-jobs-font: system-ui, -apple-system, "Segoe UI", sans-serif;
--desk-jobs-gap: 8px;
display: block;
font-family: var(--desk-jobs-font);
font-size: 13px;
color: var(--desk-jobs-fg);
}
:host([hidden]) { display: none; }
.strip {
display: flex;
flex-direction: column;
gap: var(--desk-jobs-gap);
background: var(--desk-jobs-bg);
border-radius: var(--desk-jobs-radius);
padding: 10px 12px;
}
.job { display: grid; grid-template-columns: 1fr auto; gap: 2px 10px; align-items: center; }
.what { font-weight: 600; }
.said { color: var(--desk-jobs-dim); grid-column: 1; }
.count { color: var(--desk-jobs-dim); font-variant-numeric: tabular-nums; }
/* A bar only when there is a fraction to draw. A handler that reports no
* total is working on one thing, and an empty trough reads as stalled. */
.bar {
grid-column: 1 / -1;
height: 3px;
border-radius: 2px;
background: color-mix(in srgb, var(--desk-jobs-fg) 15%, transparent);
overflow: hidden;
}
.bar > i { display: block; height: 100%; background: var(--desk-jobs-accent); transition: width .2s; }
button {
font: inherit;
color: var(--desk-jobs-dim);
background: none;
border: 1px solid currentColor;
border-radius: 6px;
padding: 1px 8px;
cursor: pointer;
}
button:hover { color: var(--desk-jobs-error); }
button[disabled] { opacity: .4; cursor: default; }
.offline { color: var(--desk-jobs-error); }
/* A finger: Kill is a thumb's height. Sizes only; the layout is the width
* query below, and neither reads the other. */
@media (pointer: coarse) {
button { min-height: 2.5rem; padding: 4px 12px; }
}
/* A phone: the app's card around the strip is the gutter, and a second one
* inside it wasted a fifth of the width. 40rem is app.css's number. */
@media (max-width: 40rem) {
.strip { padding: 0; }
}
`;
/** Backing off rather than hammering. The usual reason a socket closed is the
* server restarting under --reload, which comes back inside a second; the
* ceiling is for when it is not coming back at all. */
const FIRST_WAIT = 500;
const LONGEST_WAIT = 30000;
/** How long down is long enough to say so. A reload blinks the socket every
* time a file is saved, and a warning that flashes on every save is one you
* stop reading — which would cost us the case that matters, where the server
* really is gone and the strip is quietly showing state from a minute ago. */
const QUIET_ABOUT_IT_FOR = 4000;
class DeskJobs extends HTMLElement {
#root;
#socket = null;
#wait = FIRST_WAIT;
#timer = null;
#state = { running: [], queued: [], recent: [] };
#offline = false;
#killing = new Set();
constructor() {
super();
this.#root = this.attachShadow({ mode: "open" });
const style = document.createElement("style");
style.textContent = CSS;
this.#root.append(style, document.createElement("div"));
}
connectedCallback() { this.#connect(); this.#render(); }
disconnectedCallback() {
clearTimeout(this.#timer);
this.#socket?.close();
this.#socket = null;
}
get #base() { return this.getAttribute("base") ?? ""; }
get #socketUrl() {
const given = this.getAttribute("socket");
if (given) return given;
const scheme = location.protocol === "https:" ? "wss" : "ws";
return `${scheme}://${location.host}${this.#base}/ws/jobs`;
}
#connect() {
let socket;
try {
socket = new WebSocket(this.#socketUrl);
} catch {
this.#reconnect(); // a malformed URL, or no network
return;
}
this.#socket = socket;
socket.onopen = () => {
this.#wait = FIRST_WAIT;
this.#offline = false;
this.#render();
};
socket.onmessage = (event) => {
let message;
try { message = JSON.parse(event.data); } catch { return; }
if (message.type === "jobs") {
const { type, ...state } = message;
this.#state = state;
this.#render();
} else if (message.type === "notice") {
// The app's to word. Composed, so a listener on `document` hears it
// through the shadow boundary.
this.dispatchEvent(new CustomEvent("desk-jobs:notice", {
detail: message, bubbles: true, composed: true,
}));
}
};
socket.onerror = () => socket.close();
socket.onclose = async () => {
if (this.#socket !== socket) return; // a later connection owns us now
this.#socket = null;
await this.#whyClosed();
this.#reconnect();
};
}
/** Ask before assuming. See the `probe` attribute. */
async #whyClosed() {
const probe = this.getAttribute("probe");
if (!probe) return;
try {
const answer = await fetch(this.#base + probe, { credentials: "same-origin" });
if (answer.status === 401 || answer.status === 403) {
this.dispatchEvent(new CustomEvent("desk-jobs:signed-out", {
bubbles: true, composed: true,
}));
}
} catch { /* offline; the strip says so below */ }
}
#reconnect() {
if (this.#wait >= QUIET_ABOUT_IT_FOR) {
this.#offline = true;
this.#render();
}
clearTimeout(this.#timer);
this.#timer = setTimeout(() => this.#connect(), this.#wait);
this.#wait = Math.min(this.#wait * 2, LONGEST_WAIT);
}
async #kill(id) {
this.#killing.add(id);
this.#render();
try {
await fetch(`${this.#base}/api/jobs/${id}/cancel`,
{ method: "POST", credentials: "same-origin" });
} finally {
// The socket reports the actual ending — a running job stops at its next
// checkpoint, so the button going quiet is the whole of what happens here.
this.#killing.delete(id);
}
}
#render() {
const { running = [], queued = [] } = this.#state;
const strip = this.#root.lastElementChild;
this.hidden = this.getAttribute("idle") !== "show"
&& !running.length && !queued.length && !this.#offline;
strip.className = "strip";
strip.replaceChildren();
if (this.#offline) {
const said = document.createElement("div");
said.className = "offline";
said.textContent = "Not connected — what you see here may be out of date.";
strip.append(said);
}
for (const job of running) {
strip.append(this.#row(job));
}
if (queued.length) {
const waiting = document.createElement("div");
waiting.className = "count";
waiting.textContent = `${queued.length} waiting`;
strip.append(waiting);
}
}
#row(job) {
const row = document.createElement("div");
row.className = "job";
const what = document.createElement("span");
what.className = "what";
what.textContent = job.label || job.kind;
row.append(what);
const kill = document.createElement("button");
kill.textContent = "Kill";
kill.disabled = this.#killing.has(job.id) || job.cancel_requested;
kill.addEventListener("click", () => this.#kill(job.id));
row.append(kill);
if (job.message) {
const said = document.createElement("span");
said.className = "said";
said.textContent = job.message;
row.append(said);
}
if (job.total > 0) {
const bar = document.createElement("div");
bar.className = "bar";
const fill = document.createElement("i");
fill.style.width = `${Math.min(100, (job.done / job.total) * 100)}%`;
bar.append(fill);
row.append(bar);
}
return row;
}
}
if (!customElements.get("desk-jobs")) {
customElements.define("desk-jobs", DeskJobs);
}
export { DeskJobs };