feat(orchestrator): hub requirements 066 to 082 and 084
Radio footer, rules page, schedules editor (System timers and Claude tasks through signed runner jobs), account usage bar, usage explorer with a streamed usage.jsonl, queue Controls tab and override, running tasks on the board, stale task prune with the generic dial, greyed card stamps, commit-tree diffs from the runner preview, VS Code path links, expired asks and decisions that stay as EXPIRED cards (asks keyed by a call digest; an async PostToolUse hook closes those answered in the terminal), the Match refresh hourglass, attachments by paste, drop and paperclip in every text field (page CSP gains img-src blob: for the thumbnails) and the limits board with profiles and a passkey to loosen. Fixes: one red accept on a red-gate commit and no release while a risk is open, the send bar footer segments share one height, the mic button survives a redraw, new Match cards queue before the release card. E2E specs were still running at commit time (operator order); their failures follow as separate fixes. 🎯 Fix: 88 % 💥 Break: 8 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 81 🚦 Gate: ⛔ fix 88 % < 90, break 8 % > 5 (committed on the operator's word) Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dc0d578eca
commit
f356083a24
149 files changed
+10646
-963
No files matched your search
@@ -0,0 +1,103 @@
|
||||
const Attachments = (() => {
|
||||
"use strict";
|
||||
const MARK = "📎 ";
|
||||
const WARN = "⚠️ ";
|
||||
const BROWSER_PASTE = "image.png";
|
||||
const two = (number) => String(number).padStart(2, "0");
|
||||
|
||||
const pathLine = (path) => `${MARK}${path}`;
|
||||
const placeholder = (name) => `${MARK}uploading ${name}…`;
|
||||
|
||||
/**
|
||||
* @param {string} name the file name.
|
||||
* @param {string} reason why the upload failed, on one or more lines.
|
||||
* @returns {string} one line naming the file and the reason; it carries no path.
|
||||
*/
|
||||
function failed(name, reason) {
|
||||
const said = String(reason).replace(/\s+/g, " ").trim().slice(0, 200);
|
||||
return `${WARN}${name}: ${said || "upload failed"}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Date} when the moment of the paste.
|
||||
* @returns {string} YYYYMMDD-HHMMSS in local time.
|
||||
*/
|
||||
function stamp(when) {
|
||||
return `${when.getFullYear()}${two(when.getMonth() + 1)}${two(when.getDate())}-${two(when.getHours())}${two(when.getMinutes())}${two(when.getSeconds())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {File} file a file from the clipboard, read for its name and type.
|
||||
* @param {Date} when the moment of the paste.
|
||||
* @returns {string} the file's own name, or paste-<stamp>.<ext> for an image without one.
|
||||
*/
|
||||
function pastedName(file, when) {
|
||||
// Trip-wire: Chromium and Firefox name every pasted screenshot "image.png", so that name counts as none.
|
||||
const own = file.name && file.name !== BROWSER_PASTE ? file.name : "";
|
||||
if (own) {
|
||||
return own;
|
||||
}
|
||||
const kind = String(file.type || "").split("/");
|
||||
const ext = kind[0] === "image" && /^[a-z0-9]+/.test(kind[1] || "") ? kind[1].match(/^[a-z0-9]+/)[0] : "png";
|
||||
return `paste-${stamp(when)}.${ext}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} value the text of the field.
|
||||
* @param {number} start the start of its selection.
|
||||
* @param {number} end the end of its selection.
|
||||
* @param {string} line the line to insert in place of the selection.
|
||||
* @param {string} gap "\n" for a textarea, " " for a one-line field.
|
||||
* @returns {Object} {value, caret}: value with line as its own line (or word) at the selection, the caret right after it.
|
||||
*/
|
||||
function placed(value, start, end, line, gap) {
|
||||
const before = value.slice(0, start);
|
||||
const after = value.slice(end);
|
||||
const lead = before && !before.endsWith(gap) ? gap : "";
|
||||
const tail = after && !after.startsWith(gap) ? gap : "";
|
||||
return {value: `${before}${lead}${line}${tail}${after}`, caret: before.length + lead.length + line.length};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} value the text of the field.
|
||||
* @param {string} from the line to replace, such as a placeholder.
|
||||
* @param {string} to its replacement.
|
||||
* @param {number} caret the caret before the swap.
|
||||
* @returns {Object} {value, caret, found}: value with the first from replaced, the caret moved with the text after it.
|
||||
*/
|
||||
function swapped(value, from, to, caret) {
|
||||
const at = value.indexOf(from);
|
||||
if (at < 0) {
|
||||
return {value, caret, found: false};
|
||||
}
|
||||
const moved = caret >= at + from.length ? caret + to.length - from.length : Math.min(caret, at + to.length);
|
||||
return {value: `${value.slice(0, at)}${to}${value.slice(at + from.length)}`, caret: moved, found: true};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} value the text of a textarea.
|
||||
* @returns {string[]} the host path of every path line, in text order.
|
||||
*/
|
||||
function paths(value) {
|
||||
return value.split("\n").filter((line) => line.startsWith(`${MARK}/`)).map((line) => line.slice(MARK.length));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} value the text of a textarea.
|
||||
* @param {string} path the host path whose line goes.
|
||||
* @returns {string} value without the first line that is exactly the path line; other lines stay as they are.
|
||||
*/
|
||||
function removed(value, path) {
|
||||
const lines = value.split("\n");
|
||||
const at = lines.indexOf(pathLine(path));
|
||||
return at < 0 ? value : [...lines.slice(0, at), ...lines.slice(at + 1)].join("\n");
|
||||
}
|
||||
|
||||
const baseName = (path) => path.slice(path.lastIndexOf("/") + 1);
|
||||
const pictured = (type) => String(type || "").startsWith("image/");
|
||||
|
||||
return {pathLine, placeholder, failed, stamp, pastedName, placed, swapped, paths, removed, baseName, pictured};
|
||||
})();
|
||||
if (typeof module === "object" && module.exports) {
|
||||
module.exports = Attachments;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
const Dial = (() => {
|
||||
"use strict";
|
||||
const SIZE = 140;
|
||||
const RADIUS = 58;
|
||||
const TICKS = 60;
|
||||
|
||||
/**
|
||||
* @param value - a value on the dial, min to max.
|
||||
* @param max - the value a full turn stands for.
|
||||
* @param radius - how far from the centre.
|
||||
* @returns the point [x, y] for that value, 0 and max at the top, clockwise.
|
||||
*/
|
||||
function point(value, max, radius) {
|
||||
const angle = (value / max) * 2 * Math.PI;
|
||||
const centre = SIZE / 2;
|
||||
return [centre + Math.sin(angle) * radius, centre - Math.cos(angle) * radius];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param value - any number.
|
||||
* @param range - {min, max}: the dial's ends.
|
||||
* @returns value rounded to a whole number and held between min and max.
|
||||
*/
|
||||
function clamp(value, range) {
|
||||
return Math.max(range.min, Math.min(range.max, Math.round(value)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param degrees - the pointer's angle from the top, clockwise, in degrees.
|
||||
* @param max - the value a full turn stands for.
|
||||
* @returns the value at that angle, unrounded.
|
||||
*/
|
||||
function fromAngle(degrees, max) {
|
||||
return ((degrees + 360) % 360) / (360 / max);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param key - a KeyboardEvent key.
|
||||
* @param value - the dial's value.
|
||||
* @param options - {min, max, page}: the ends and the Page Up and Down step.
|
||||
* @returns the value the key sets, held to the ends, or null for a key the dial ignores: the arrows step 1, Page Up and
|
||||
* Down step page, Home and End go to min and max.
|
||||
*/
|
||||
function stepped(key, value, options) {
|
||||
const steps = {ArrowRight: 1, ArrowUp: 1, ArrowLeft: -1, ArrowDown: -1, PageUp: options.page, PageDown: -options.page};
|
||||
if (key in steps) {
|
||||
return clamp(value + steps[key], options);
|
||||
}
|
||||
return key === "Home" ? options.min : key === "End" ? options.max : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param page - every page-th tick is long.
|
||||
* @returns the TICKS ticks of the face, each {at, long}: at its place on a turn of TICKS.
|
||||
*/
|
||||
function ticks(page) {
|
||||
return Array.from({length: TICKS}, (_, at) => ({at, long: at % page === 0}));
|
||||
}
|
||||
|
||||
return {SIZE, RADIUS, TICKS, point, clamp, fromAngle, stepped, ticks};
|
||||
})();
|
||||
if (typeof module === "object" && module.exports) {
|
||||
module.exports = Dial;
|
||||
}
|
||||
@@ -180,6 +180,8 @@ pre.notes { max-height: 260px; margin: 12px 0 0; padding: 10px 12px; overflow: a
|
||||
.diff-pane { padding: 0; overflow: hidden; }
|
||||
.diff-head { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; padding: 12px 16px; border-bottom: 1px solid var(--line); background: var(--sunken); }
|
||||
.diff-head .path { overflow-wrap: anywhere; font-weight: 600; }
|
||||
.path-link { min-width: 0; color: inherit; text-decoration: none; }
|
||||
.path-link:hover .path, .path-link:focus-visible .path { color: var(--accent); text-decoration: underline; }
|
||||
.pad { margin: 0; padding: 18px 16px; }
|
||||
.diff-scroll { overflow: auto; max-height: 70vh; }
|
||||
.review-stack { position: relative; overflow: auto; max-height: 70vh; overscroll-behavior: contain; }
|
||||
@@ -359,20 +361,20 @@ textarea { width: 100%; min-height: 84px; padding: 8px 10px; border: 1px solid v
|
||||
.mic-area { display: flex; flex-direction: column; width: 100%; }
|
||||
.mic-area > textarea { display: block; width: 100%; min-width: 0; }
|
||||
.mic-foot { display: flex; align-items: center; gap: 6px; min-height: 32px; padding: 2px 3px 2px 8px; border-top: 1px solid var(--line); }
|
||||
.mic { display: inline-grid; flex: none; place-items: center; min-width: 34px; padding: 0 8px; border: 0; background: transparent; color: var(--muted); cursor: pointer; }
|
||||
.mic:hover:not(:disabled) { background: var(--hover); color: var(--text); }
|
||||
.mic:disabled { cursor: not-allowed; opacity: .55; }
|
||||
:is(.mic, .mic-attach) { display: inline-grid; flex: none; place-items: center; min-width: 34px; padding: 0 8px; border: 0; background: transparent; color: var(--muted); cursor: pointer; }
|
||||
:is(.mic, .mic-attach):hover:not(:disabled) { background: var(--hover); color: var(--text); }
|
||||
:is(.mic, .mic-attach):disabled { cursor: not-allowed; opacity: .55; }
|
||||
.mic-line > .mic { border-left: 1px solid var(--line); border-radius: 0 9px 9px 0; }
|
||||
.mic-line > .mic:not(:last-child) { border-radius: 0; }
|
||||
.mic-line > button[type="submit"] { flex: none; border: 0; border-left: 1px solid var(--line); border-radius: 0 9px 9px 0; background: transparent; box-shadow: none; }
|
||||
.mic-foot > .mic { min-height: 28px; border-radius: 8px; }
|
||||
.mic-foot > :is(.mic, .mic-attach) { min-height: 28px; border-radius: 8px; }
|
||||
.palette-row > .mic-line { border: 0; border-radius: 0; }
|
||||
.mic[aria-pressed="true"] { background: var(--bad-soft); color: var(--bad); animation: mic-pulse 1.2s ease-in-out infinite; }
|
||||
.mic-live { position: fixed; left: 50%; bottom: calc(18px + env(safe-area-inset-bottom, 0px)); z-index: 60; display: flex; align-items: center; gap: 8px; max-width: calc(100vw - 32px); padding: 8px 14px; transform: translateX(-50%); border-radius: 999px; background: var(--bad); color: #fff; font-weight: 650; box-shadow: var(--shadow-lift); }
|
||||
.mic-live[hidden] { display: none; }
|
||||
.mic-live::before { content: ""; flex: none; width: 10px; height: 10px; border-radius: 50%; background: #fff; animation: mic-pulse 1s ease-in-out infinite; }
|
||||
@keyframes mic-pulse { 50% { opacity: .45; } }
|
||||
@media (max-width: 640px) { .mic { min-width: 44px; } .mic-foot > .mic { min-height: 44px; } }
|
||||
@media (max-width: 640px) { :is(.mic, .mic-attach) { min-width: 44px; } .mic-foot > :is(.mic, .mic-attach) { min-height: 44px; } }
|
||||
@media (prefers-reduced-motion: reduce) { .mic[aria-pressed="true"], .mic-live::before { animation: none; } }
|
||||
.palette-list { max-height: 55vh; margin: 0; padding: 6px; overflow: auto; list-style: none; }
|
||||
.palette-list li { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px; cursor: pointer; }
|
||||
@@ -552,6 +554,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
|
||||
<script nonce="{{ nonce }}">
|
||||
{% include "voice.js" %}
|
||||
|
||||
{% include "attachments.js" %}
|
||||
|
||||
{% include "radioset.js" %}
|
||||
|
||||
{% include "morse.js" %}
|
||||
@@ -568,6 +572,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
|
||||
|
||||
{% include "resources.js" %}
|
||||
|
||||
{% include "usagebar.js" %}
|
||||
|
||||
{% include "nav.js" %}
|
||||
|
||||
{% include "panels.js" %}
|
||||
@@ -586,6 +592,16 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
|
||||
|
||||
{% include "plan.js" %}
|
||||
|
||||
{% include "kanban-marks.js" %}
|
||||
|
||||
{% include "dial.js" %}
|
||||
|
||||
{% include "limits.js" %}
|
||||
|
||||
{% include "matchclock.js" %}
|
||||
|
||||
{% include "prune.js" %}
|
||||
|
||||
{% include "kanban.js" %}
|
||||
|
||||
{% include "organigram.js" %}
|
||||
@@ -676,6 +692,10 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
|
||||
|
||||
{% include "page-kanban.js" %}
|
||||
|
||||
{% include "page-prune.js" %}
|
||||
|
||||
{% include "page-running.js" %}
|
||||
|
||||
{% include "page-match.js" %}
|
||||
|
||||
{% include "page-choices.js" %}
|
||||
@@ -707,6 +727,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
|
||||
|
||||
{% include "page-gibberlink.js" %}
|
||||
|
||||
{% include "page-attach.js" %}
|
||||
|
||||
{% include "page-mic.js" %}
|
||||
|
||||
{% include "page-slash.js" %}
|
||||
@@ -716,8 +738,14 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
|
||||
{% include "page-alerts.js" %}
|
||||
|
||||
{% include "page-resources.js" %}
|
||||
|
||||
{% include "page-limits.js" %}
|
||||
|
||||
{% include "page-accounts.js" %}
|
||||
{% include "page-usage.js" %}
|
||||
{% include "page-account-bar.js" %}
|
||||
{% include "page-schedules.js" %}
|
||||
{% include "page-queue.js" %}
|
||||
|
||||
{% include "page-rates.js" %}
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
const KanbanMarks = (() => {
|
||||
"use strict";
|
||||
const DAY = 86400;
|
||||
const HOUR = 3600;
|
||||
const MINUTE = 60;
|
||||
const BEAT_S = 5 * MINUTE;
|
||||
const HEAD_SHOWN = 32;
|
||||
const QUEUE = "queue";
|
||||
const RUNNING = "running";
|
||||
const RESPONSIBLE = "R";
|
||||
const NOBODY = "-";
|
||||
const MARKS = [["queue", "bi-cpu", "accent"], ["agent", "bi-person-workspace", "ok"], ["hub", "bi-terminal", "info"]];
|
||||
|
||||
/**
|
||||
* @param seconds - a span in seconds.
|
||||
* @returns the span in words, cut to its two largest units: "45 s", "12 min", "2 h 5 min", "3 d 4 h".
|
||||
*/
|
||||
function span(seconds) {
|
||||
const whole = Math.max(0, Math.floor(seconds));
|
||||
if (whole < MINUTE) {
|
||||
return `${whole} s`;
|
||||
}
|
||||
if (whole < HOUR) {
|
||||
return `${Math.floor(whole / MINUTE)} min`;
|
||||
}
|
||||
const [big, unit, small, rest] = whole < DAY ? [HOUR, "h", MINUTE, "min"] : [DAY, "d", HOUR, "h"];
|
||||
const part = Math.floor((whole % big) / small);
|
||||
return part ? `${Math.floor(whole / big)} ${unit} ${part} ${rest}` : `${Math.floor(whole / big)} ${unit}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param command - a hub job's command.
|
||||
* @returns its first line, cut to HEAD_SHOWN characters with an ellipsis.
|
||||
*/
|
||||
function head(command) {
|
||||
const line = command.trim().split("\n")[0].trim();
|
||||
return line.length > HEAD_SHOWN ? `${line.slice(0, HEAD_SHOWN - 1)}…` : line;
|
||||
}
|
||||
|
||||
function queueMark(row, tasks, now) {
|
||||
const own = tasks.filter((job) => job.kind === QUEUE && job.status === RUNNING && (job.task === row.task || job.queue.parent === row.task));
|
||||
const first = own.filter((job) => job.start !== null).sort((a, b) => a.start - b.start)[0] || own[0];
|
||||
if (!first) {
|
||||
return null;
|
||||
}
|
||||
const runtime = first.start === null ? "?" : span(now - first.start);
|
||||
const more = own.length > 1 ? `, ${own.length - 1} more running` : "";
|
||||
return {text: `${first.queue.kind} · ${runtime}`, hint: `${row.task}: queue job ${first.task} runs ${first.queue.kind} for ${runtime}${more}`, at: first.start};
|
||||
}
|
||||
|
||||
function agentMark(row, beats, now) {
|
||||
const names = [row.worker, ...Object.entries(row.roles).filter(([, letters]) => letters.includes(RESPONSIBLE)).map(([party]) => party)];
|
||||
const fresh = [...new Set(names)].filter((name) => name !== NOBODY && Object.hasOwn(beats, name) && now - beats[name] >= -MINUTE && now - beats[name] <= BEAT_S);
|
||||
const name = fresh.sort((a, b) => beats[b] - beats[a])[0];
|
||||
if (!name) {
|
||||
return null;
|
||||
}
|
||||
const ago = span(now - beats[name]);
|
||||
return {text: `${name} · ${ago}`, hint: `${row.task}: ${name} works on it, last beat ${ago} ago`, at: beats[name]};
|
||||
}
|
||||
|
||||
function hubMark(row, runner, now) {
|
||||
if (!runner || runner.task !== row.task) {
|
||||
return null;
|
||||
}
|
||||
const shown = head(runner.command) || runner.job;
|
||||
return {text: shown, hint: `${row.task}: the hub runs ${runner.job} for ${span(now - runner.started)}: ${runner.command || runner.job}`, at: runner.started};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param row - a card's task row: task, worker and roles.
|
||||
* @param sources - {now, tasks, beats, runner}: now the hub's epoch seconds; tasks the hub's task rows, whose queue
|
||||
* rows are the entries of queue.json; beats the hub's {agent: epoch of its latest heartbeat}; runner the hub job
|
||||
* runner-job.json names, {job, task, started, command}, or null.
|
||||
* @returns the card's marks in MARKS order, each {key, icon, tone, text, hint, at}: queue while a queue job of the
|
||||
* task or the queue card's own job runs (its kind and runtime), agent while the task's worker or an R beat within
|
||||
* BEAT_S (the freshest of them and how long ago), hub while runner-job.json names the task (the command's head).
|
||||
*/
|
||||
function marks(row, sources) {
|
||||
const found = {queue: queueMark(row, sources.tasks, sources.now), agent: agentMark(row, sources.beats, sources.now), hub: hubMark(row, sources.runner, sources.now)};
|
||||
return MARKS.filter(([key]) => found[key]).map(([key, icon, tone]) => ({key, icon, tone, ...found[key]}));
|
||||
}
|
||||
|
||||
return {BEAT_S, MARKS, span, head, marks};
|
||||
})();
|
||||
if (typeof module === "object" && module.exports) {
|
||||
module.exports = KanbanMarks;
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
const Kanban = (() => {
|
||||
"use strict";
|
||||
const {BEAT_S, MARKS, span, head, marks} = typeof KanbanMarks === "object" ? KanbanMarks : require("./kanban-marks.js");
|
||||
const COLUMNS = [["queued", "Waiting"], ["running", "Running"], ["done", "Done"]];
|
||||
const LANES = [["p1", "P1"], ["p2", "P2"], ["p3", "P3"], ["p4", "P4+"], ["unpinned", "Unpinned"]];
|
||||
const PINS = {p1: 1, p2: 2, p3: 3};
|
||||
const FREE_FROM = 4;
|
||||
const OFF = ["command"];
|
||||
const DAY = 86400;
|
||||
const HOUR = 3600;
|
||||
const MINUTE = 60;
|
||||
const REFUSED = ["failed", "refused"];
|
||||
const QUEUE = "queue/";
|
||||
@@ -170,23 +170,6 @@ const Kanban = (() => {
|
||||
return failed.length ? {failed, applied: batch.filter((job) => job.status === "done").length, total: batch.length} : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param seconds - a span in seconds.
|
||||
* @returns the span in words, cut to its two largest units: "45 s", "12 min", "2 h 5 min", "3 d 4 h".
|
||||
*/
|
||||
function span(seconds) {
|
||||
const whole = Math.max(0, Math.floor(seconds));
|
||||
if (whole < MINUTE) {
|
||||
return `${whole} s`;
|
||||
}
|
||||
if (whole < HOUR) {
|
||||
return `${Math.floor(whole / MINUTE)} min`;
|
||||
}
|
||||
const [big, unit, small, rest] = whole < DAY ? [HOUR, "h", MINUTE, "min"] : [DAY, "d", HOUR, "h"];
|
||||
const part = Math.floor((whole % big) / small);
|
||||
return part ? `${Math.floor(whole / big)} ${unit} ${part} ${rest}` : `${Math.floor(whole / big)} ${unit}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param rows - the shown cards' rows.
|
||||
* @param line - the hub's queue_line: tasks holding a live queue entry, in grant order.
|
||||
@@ -265,7 +248,7 @@ const Kanban = (() => {
|
||||
return jobs === null ? null : jobs.map((job) => ({...job, waited_s: minutes(job.waited_s), eta_s: minutes(job.eta_s)}));
|
||||
}
|
||||
|
||||
return {COLUMNS, LANES, FREE_FROM, QUEUE_LAYERS, onBoard, columnOf, laneOf, labelOf, board, freePin, move, stage, pending, lines, why, span, queued, jobChips, whyHere, layers, queueSig};
|
||||
return {COLUMNS, LANES, FREE_FROM, QUEUE_LAYERS, BEAT_S, MARKS, onBoard, columnOf, laneOf, labelOf, board, freePin, move, stage, pending, lines, why, span, queued, jobChips, whyHere, layers, queueSig, head, marks};
|
||||
})();
|
||||
if (typeof module === "object" && module.exports) {
|
||||
module.exports = Kanban;
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
const Limits = (() => {
|
||||
"use strict";
|
||||
const METRICS = ["cpu", "ram", "swap", "disk", "psi"];
|
||||
const LEVELS = ["lower", "upper", "stop", "mayday"];
|
||||
const TARGETED = ["cpu", "ram"];
|
||||
const NAMES = {cpu: "CPU", ram: "RAM", swap: "Swap", disk: "Disk", psi: "PSI"};
|
||||
const LEVEL_NAMES = {lower: "lower", upper: "upper", stop: "STOP", mayday: "MAYDAY"};
|
||||
const ORDER = "lower < upper < STOP < MAYDAY";
|
||||
const percent = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 100;
|
||||
const plain = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
const exactly = (value, keys) => plain(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
|
||||
|
||||
/**
|
||||
* @param limits - a limits object as the page would save it.
|
||||
* @returns why it is no limits object, the same rules as kvb-org-organize limits.py problem(): exactly METRICS, each
|
||||
* with exactly LEVELS, every value a percent from 0 to 100, lower < upper < STOP < MAYDAY; null when it is one.
|
||||
*/
|
||||
function problem(limits) {
|
||||
if (!exactly(limits, METRICS)) {
|
||||
return `the limits are no object of exactly ${METRICS.join(", ")}`;
|
||||
}
|
||||
for (const metric of METRICS) {
|
||||
const levels = limits[metric];
|
||||
if (!exactly(levels, LEVELS)) {
|
||||
return `${NAMES[metric]} holds not exactly ${LEVELS.join(", ")}`;
|
||||
}
|
||||
const values = LEVELS.map((level) => levels[level]);
|
||||
if (!values.every(percent)) {
|
||||
return `${NAMES[metric]} holds a value that is no percent from 0 to 100`;
|
||||
}
|
||||
if (!values.every((value, index) => index === 0 || values[index - 1] < value)) {
|
||||
return `${NAMES[metric]} breaks ${ORDER}: ${values.join(" / ")} %`;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param next - valid limits the page would save.
|
||||
* @param held - the limits in force, null while the queue config applies.
|
||||
* @returns every value of next above the one in force as {metric, level, from, to}, from null while none is in
|
||||
* force: a higher lower or upper admits more load, a higher STOP or MAYDAY raises an alarm threshold, so each needs
|
||||
* the passkey; an empty list means every value stays or tightens.
|
||||
*/
|
||||
function loosened(next, held) {
|
||||
return METRICS.flatMap((metric) => LEVELS.map((level) => ({metric, level, from: held ? held[metric][level] : null, to: next[metric][level]})))
|
||||
.filter((change) => change.from === null || change.to > change.from);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param limits - valid limits.
|
||||
* @param metric - one of METRICS.
|
||||
* @param level - one of LEVELS.
|
||||
* @param value - the new value.
|
||||
* @returns a copy of limits with only that value changed.
|
||||
*/
|
||||
function withValue(limits, metric, level, value) {
|
||||
return {...limits, [metric]: {...limits[metric], [level]: value}};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param limits - the limits in force, or null.
|
||||
* @param profiles - {name: limits} of the hub.
|
||||
* @returns the name of the profile holding exactly these values, null for none.
|
||||
*/
|
||||
function profileOf(limits, profiles) {
|
||||
if (!limits) {
|
||||
return null;
|
||||
}
|
||||
const found = Object.entries(profiles).find(([, values]) => METRICS.every((metric) => LEVELS.every((level) => values[metric][level] === limits[metric][level])));
|
||||
return found ? found[0] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param change - one entry of loosened().
|
||||
* @returns it as words, like `CPU upper 90 → 95 %`.
|
||||
*/
|
||||
function said(change) {
|
||||
return `${NAMES[change.metric]} ${LEVEL_NAMES[change.level]} ${change.from === null ? "unset" : change.from} → ${change.to} %`;
|
||||
}
|
||||
|
||||
return {METRICS, LEVELS, TARGETED, NAMES, LEVEL_NAMES, ORDER, problem, loosened, withValue, profileOf, said};
|
||||
})();
|
||||
if (typeof module === "object" && module.exports) {
|
||||
module.exports = Limits;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
const MatchClock = (() => {
|
||||
"use strict";
|
||||
const MIN = 1;
|
||||
const MAX = 60;
|
||||
const PAGE = 5;
|
||||
const SECOND = 1000;
|
||||
|
||||
/**
|
||||
* @param seconds - the refresh interval the hub settings hold.
|
||||
* @returns seconds rounded to whole seconds and held between MIN and MAX.
|
||||
*/
|
||||
function bounded(seconds) {
|
||||
return Math.max(MIN, Math.min(MAX, Math.round(seconds)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param fetched - when the last /api/match fetch started, epoch milliseconds.
|
||||
* @param seconds - the refresh interval.
|
||||
* @returns when the next fetch is due, epoch milliseconds.
|
||||
*/
|
||||
function next(fetched, seconds) {
|
||||
return fetched + bounded(seconds) * SECOND;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param now - the time now, epoch milliseconds.
|
||||
* @param fetched - when the last fetch started, epoch milliseconds.
|
||||
* @param seconds - the refresh interval.
|
||||
* @returns how many milliseconds the timer waits for the next fetch, never below 0.
|
||||
*/
|
||||
function wait(now, fetched, seconds) {
|
||||
return Math.max(0, next(fetched, seconds) - now);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param now - the time now, epoch milliseconds.
|
||||
* @param fetched - when the last fetch started, epoch milliseconds.
|
||||
* @param seconds - the refresh interval.
|
||||
* @returns true once the next fetch is due.
|
||||
*/
|
||||
function due(now, fetched, seconds) {
|
||||
return wait(now, fetched, seconds) === 0;
|
||||
}
|
||||
|
||||
return {MIN, MAX, PAGE, SECOND, bounded, next, wait, due};
|
||||
})();
|
||||
if (typeof module === "object" && module.exports) {
|
||||
module.exports = MatchClock;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
const USAGE_DELAY = 400;
|
||||
const USAGE_STEPS = {ArrowRight: 1, ArrowUp: 1, ArrowLeft: -1, ArrowDown: -1, PageUp: 10, PageDown: -10};
|
||||
const usageTenth = (value) => Math.round(value * 10) / 10;
|
||||
const usageClamp = (value) => Math.min(100, Math.max(0, value));
|
||||
let usageSaved = Promise.resolve();
|
||||
|
||||
function forecastToggle() {
|
||||
const toggle = h("button", {type: "button", class: "btn small soft acc-switch", "data-forecast-toggle": "", "aria-pressed": String(settings.forecast),
|
||||
...named("Auto forecast", "Auto forecast: mark the share each account reaches at its reset if the tokens of the last 24 hours keep their rate")}, icon("bi-graph-up-arrow"), h("span", {}, "Auto forecast"));
|
||||
toggle.addEventListener("click", async () => {
|
||||
if (await saveSettings({...settings, forecast: !settings.forecast})) {
|
||||
drawAccounts();
|
||||
}
|
||||
});
|
||||
accountsView.toggle = toggle;
|
||||
return toggle;
|
||||
}
|
||||
|
||||
function dayTime(ms) {
|
||||
const at = new Date(ms);
|
||||
return momentText({day: at.getDay(), time: `${String(at.getHours()).padStart(2, "0")}:${String(at.getMinutes()).padStart(2, "0")}`});
|
||||
}
|
||||
|
||||
function forecastMark(row, now) {
|
||||
if (!settings.forecast || row.account.limit <= 0) {
|
||||
return null;
|
||||
}
|
||||
const expected = UsageBar.forecast(row.account.limit, row.entry, row.bar.share, now, row.next);
|
||||
const hint = expected.full === null ? `${Math.round(expected.share)} % expected at the reset, ${dayTime(row.next)}` : `100 % at ${dayTime(expected.full)}`;
|
||||
const mark = h("span", {class: "acc-forecast", "data-forecast": expected.full === null ? "reset" : "full", title: hint});
|
||||
mark.style.setProperty("--forecast", `${usageClamp(expected.share)}%`);
|
||||
return mark;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bar - the slider whose share waits to be stored.
|
||||
* @param id - the account's id.
|
||||
* @param share - the percent to store.
|
||||
* @param delay - milliseconds to wait for a further step; each step restarts it.
|
||||
* Holds the Accounts redraw until the newest calibration of the account is stored, then draws it.
|
||||
*/
|
||||
function calibrateLater(bar, id, share, delay) {
|
||||
const held = accountsView.held.get(id);
|
||||
if (held) {
|
||||
window.clearTimeout(held.timer);
|
||||
}
|
||||
const mark = {timer: 0};
|
||||
accountsView.held.set(id, mark);
|
||||
bar.setAttribute("data-pending", "");
|
||||
mark.timer = window.setTimeout(() => {
|
||||
usageSaved = usageSaved.then(async () => {
|
||||
const result = await sendJson(`/api/accounts/${id}/calibrate`, {share});
|
||||
if (result.ok && result.data) {
|
||||
accountsView.data.calibrations[id] = result.data;
|
||||
} else {
|
||||
toast("Usage: not calibrated", fail(result), false);
|
||||
}
|
||||
if (accountsView.held.get(id) === mark) {
|
||||
accountsView.held.delete(id);
|
||||
drawAccounts();
|
||||
}
|
||||
});
|
||||
}, delay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param row - an accountRows() row of an account with a limit.
|
||||
* @param now - epoch milliseconds.
|
||||
* @returns the usage bar: an ARIA slider whose fill shows the share in its flowing colour; dragging it or the arrows
|
||||
* (1 %) and Page Up and Down (10 %) calibrate the share to what the provider shows.
|
||||
*/
|
||||
function usageBar(row, now) {
|
||||
const {account} = row;
|
||||
const mark = forecastMark(row, now);
|
||||
const bar = h("div", {class: "acc-bar", role: "slider", tabindex: "0", "data-usage": account.id, "aria-label": `Usage of ${account.email}`, "aria-valuemin": "0", "aria-valuemax": "100",
|
||||
...(row.bar.calibrated ? {"data-calibrated": ""} : {})}, h("span", {class: "acc-fill"}), mark, h("span", {class: "acc-handle"}));
|
||||
let share = row.bar.share;
|
||||
const show = (value) => {
|
||||
share = value;
|
||||
bar.style.setProperty("--share", `${usageClamp(value)}%`);
|
||||
bar.style.setProperty("--fill", UsageBar.fillColor(value));
|
||||
bar.setAttribute("aria-valuenow", String(usageTenth(usageClamp(value))));
|
||||
bar.setAttribute("aria-valuetext", `${usageTenth(value)} % of ${Resources.compact(account.limit)} tokens${mark ? `; ${mark.title}` : ""}`);
|
||||
};
|
||||
const pointed = (event) => {
|
||||
const box = bar.getBoundingClientRect();
|
||||
show(usageTenth(usageClamp((100 * (event.clientX - box.left)) / box.width)));
|
||||
};
|
||||
const release = () => {
|
||||
window.removeEventListener("pointermove", pointed);
|
||||
window.removeEventListener("pointerup", release);
|
||||
window.removeEventListener("pointercancel", release);
|
||||
bar.removeAttribute("data-dragging");
|
||||
calibrateLater(bar, account.id, share, 0);
|
||||
};
|
||||
bar.addEventListener("pointerdown", (event) => {
|
||||
if (event.button !== 0) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
bar.focus({preventScroll: true});
|
||||
bar.setAttribute("data-dragging", "");
|
||||
accountsView.held.set(account.id, {timer: 0});
|
||||
pointed(event);
|
||||
window.addEventListener("pointermove", pointed);
|
||||
window.addEventListener("pointerup", release);
|
||||
window.addEventListener("pointercancel", release);
|
||||
});
|
||||
bar.addEventListener("keydown", (event) => {
|
||||
if (!(event.key in USAGE_STEPS)) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
show(usageTenth(usageClamp(usageClamp(share) + USAGE_STEPS[event.key])));
|
||||
calibrateLater(bar, account.id, share, USAGE_DELAY);
|
||||
});
|
||||
show(share);
|
||||
return bar;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
const ACCOUNT_DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
||||
const ACCOUNT_COLUMNS = ["Provider", "Email", "Renewal", "Next reset", "Resubscribe", "Autorenew", "Since reset", "Today", "Total", "Remaining", ""];
|
||||
const accountsView = {data: null, busy: false, body: null};
|
||||
const accountsView = {data: null, busy: false, body: null, toggle: null, held: new Map()};
|
||||
const momentText = (moment) => `${ACCOUNT_DAYS[moment.day]} ${moment.time}`;
|
||||
|
||||
function accountsPanel() {
|
||||
@@ -9,7 +9,7 @@
|
||||
const add = iconBtn("bi-plus-lg", "Add account", "btn small soft", () => accountSheet(null), "Add account: provider, email, renewal and weekly reset; kept on this host only");
|
||||
const panel = h("section", {class: "card res-panel res-accounts", "data-panel": "resources-accounts", "aria-label": "Accounts"},
|
||||
h("div", {class: "res-head", "data-legend-slot": ""}, h("span", {class: "res-title", title: "Accounts", "aria-label": "Accounts"}, icon("bi-person-badge")), h("span", {class: "acc-title"}, "Accounts"), h("span", {class: "spacer"}),
|
||||
accountsExportMenu(), accountsImportButton(), add), body);
|
||||
forecastToggle(), accountsExportMenu(), accountsImportButton(), add), body);
|
||||
return {panel, body};
|
||||
}
|
||||
|
||||
@@ -58,14 +58,19 @@
|
||||
}
|
||||
|
||||
/**
|
||||
* @param data - /api/accounts: {accounts, active, usage}.
|
||||
* @param data - /api/accounts: {accounts, active, usage, calibrations}.
|
||||
* @param now - epoch milliseconds.
|
||||
* @returns the table rows: each account with its next reset and usage, sorted by the next reset, then one
|
||||
* unassigned row for the tokens of no stored account, when there are any.
|
||||
* @returns the table rows: each account with its next reset, usage entry, usage and UsageBar.usage() bar (null
|
||||
* without a limit), sorted by the next reset, then one unassigned row for the tokens of no stored account, when
|
||||
* there are any.
|
||||
*/
|
||||
function accountRows(data, now) {
|
||||
const empty = {total: 0, hours: []};
|
||||
const rows = data.accounts.map((account) => ({account, next: Resources.nextMoment(account.reset, now), used: Resources.accountUsage(data.usage[account.email] || empty, account.reset, now)}));
|
||||
const rows = data.accounts.map((account) => {
|
||||
const entry = data.usage[account.email] || empty;
|
||||
const bar = account.limit === null ? null : UsageBar.usage(account.limit, entry, data.calibrations[account.id], Resources.lastMoment(account.reset, now));
|
||||
return {account, entry, bar, next: Resources.nextMoment(account.reset, now), used: Resources.accountUsage(entry, account.reset, now)};
|
||||
});
|
||||
rows.sort((a, b) => a.next - b.next || a.account.email.localeCompare(b.account.email));
|
||||
const known = new Set(data.accounts.map((account) => account.email));
|
||||
const rest = Object.entries(data.usage).filter(([email]) => !known.has(email)).map(([, entry]) => entry);
|
||||
@@ -73,20 +78,21 @@
|
||||
return unassigned.total ? [...rows, {account: null, next: null, used: Resources.accountUsage(unassigned, null, now)}] : rows;
|
||||
}
|
||||
|
||||
function accountRow(row, active) {
|
||||
function accountRow(row, active, now) {
|
||||
const count = (value) => (value === null ? "–" : Resources.compact(value));
|
||||
if (row.account === null) {
|
||||
return h("tr", {class: "acc-unassigned", "data-account": ""}, h("td", {colspan: 6}, "Unassigned: sessions the SessionStart hook mapped to no stored account"),
|
||||
h("td", {}, "–"), h("td", {}, count(row.used.today)), h("td", {}, count(row.used.total)), h("td", {}, "–"), h("td", {}));
|
||||
}
|
||||
const {account} = row;
|
||||
const remaining = account.limit === null ? null : Math.max(0, account.limit - row.used.since);
|
||||
const remaining = row.bar === null ? null : Math.max(0, account.limit - row.bar.used);
|
||||
const left = row.bar === null ? "No weekly limit set" : `Limit ${account.limit} minus the ${row.bar.calibrated ? "calibrated share and the tokens since" : "tokens since the last reset"}`;
|
||||
const isActive = account.email === active;
|
||||
return h("tr", {"data-account": account.id, ...(isActive ? {"data-active": ""} : {})},
|
||||
h("td", {}, account.provider), h("td", {}, account.email, isActive ? h("span", {class: "pill", "data-tone": "ok", title: "The account Claude Code logged in with at the last session start"}, "active") : null),
|
||||
h("td", {}, momentText(account.renewal)), h("td", {title: momentText(account.reset)}, absolute.format(new Date(row.next))), h("td", {}, account.resubscribe || "–"),
|
||||
h("td", {}, account.autorenew ? "yes" : "no"), h("td", {}, count(row.used.since)), h("td", {}, count(row.used.today)), h("td", {}, count(row.used.total)),
|
||||
h("td", {title: account.limit === null ? "No weekly limit set" : `Limit ${account.limit} minus the tokens since the last reset`}, count(remaining)),
|
||||
h("td", {title: left}, h("div", {class: "acc-left"}, h("span", {}, count(remaining)), row.bar === null ? null : usageBar(row, now))),
|
||||
h("td", {}, iconBtn("bi-pencil", `Edit ${account.email}`, "btn small ghost", () => accountSheet(account), "Edit or remove this account")));
|
||||
}
|
||||
|
||||
@@ -94,19 +100,30 @@
|
||||
if (data === null) {
|
||||
return h("p", {class: "muted"}, "…");
|
||||
}
|
||||
const rows = accountRows(data, Date.now());
|
||||
const now = Date.now();
|
||||
const rows = accountRows(data, now);
|
||||
if (!rows.length) {
|
||||
return h("p", {class: "muted"}, "No account yet. Add one: it stays on this host, in the hub's state only.");
|
||||
}
|
||||
return h("div", {class: "acc-scroll"}, h("table", {class: "acc-table"},
|
||||
h("thead", {}, h("tr", {}, ACCOUNT_COLUMNS.map((name) => h("th", {scope: "col"}, name)))),
|
||||
h("tbody", {}, rows.map((row) => accountRow(row, data.active)))));
|
||||
h("tbody", {}, rows.map((row) => accountRow(row, data.active, now)))));
|
||||
}
|
||||
|
||||
function drawAccounts() {
|
||||
const body = accountsView.body;
|
||||
if (body && body.isConnected) {
|
||||
body.replaceChildren(accountsContent(accountsView.data));
|
||||
if (accountsView.toggle) {
|
||||
accountsView.toggle.setAttribute("aria-pressed", String(settings.forecast));
|
||||
}
|
||||
if (!body || !body.isConnected || accountsView.held.size) {
|
||||
return;
|
||||
}
|
||||
const active = document.activeElement;
|
||||
const focused = active && body.contains(active) ? active.getAttribute("data-usage") : null;
|
||||
body.replaceChildren(accountsContent(accountsView.data));
|
||||
const again = focused ? body.querySelector(`[data-usage="${focused}"]`) : null;
|
||||
if (again) {
|
||||
again.focus({preventScroll: true});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -103,6 +103,7 @@
|
||||
button.disabled = true;
|
||||
if (await deliver(key, text.value, file.files[0] || null, picked(classes))) {
|
||||
text.value = "";
|
||||
text.dispatchEvent(new Event("input", {bubbles: true}));
|
||||
file.value = "";
|
||||
}
|
||||
button.disabled = false;
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
const ATTACH_HINT = "Attach files: pick them here, paste a screenshot or drop files on the field; each lands as its path line at the cursor";
|
||||
const attachThumbs = new Map();
|
||||
const attachRows = new WeakMap();
|
||||
const attachWired = new WeakSet();
|
||||
|
||||
const attachGap = (field) => (field.tagName === "TEXTAREA" ? "\n" : " ");
|
||||
const attachFiles = (transfer) => [...((transfer && transfer.files) || [])];
|
||||
const attachDrags = (event) => Boolean(event.dataTransfer && [...event.dataTransfer.types].includes("Files"));
|
||||
|
||||
function attachSet(field, value, caret) {
|
||||
field.value = value;
|
||||
field.setSelectionRange(caret, caret);
|
||||
field.dispatchEvent(new Event("input", {bubbles: true}));
|
||||
}
|
||||
|
||||
function attachPut(field, line) {
|
||||
const start = field.selectionStart ?? field.value.length;
|
||||
const next = Attachments.placed(field.value, start, field.selectionEnd ?? start, line, attachGap(field));
|
||||
attachSet(field, next.value, next.caret);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {HTMLInputElement|HTMLTextAreaElement} field the field an upload started in.
|
||||
* @param {string} line the upload's placeholder.
|
||||
* @returns {HTMLInputElement|HTMLTextAreaElement} field, or after a redraw its rebuilt twin under the same aria-label that holds the placeholder now.
|
||||
*/
|
||||
function attachHolder(field, line) {
|
||||
const key = micKey(field);
|
||||
if (field.isConnected || !key) {
|
||||
return field;
|
||||
}
|
||||
return [...document.querySelectorAll(Voice.FIELDS)].find((other) => micKey(other) === key && other.value.includes(line)) || field;
|
||||
}
|
||||
|
||||
function attachSwap(field, from, to) {
|
||||
const holder = attachHolder(field, from);
|
||||
const next = Attachments.swapped(holder.value, from, to, holder.selectionEnd ?? holder.value.length);
|
||||
if (next.found) {
|
||||
attachSet(holder, next.value, next.caret);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {HTMLInputElement|HTMLTextAreaElement} field the field the path line lands in, at its cursor.
|
||||
* @param {File} file the pasted, dropped or picked file.
|
||||
* @param {boolean} pasted true for a file from the clipboard, which gets paste-<timestamp>.png when it has no name of its own.
|
||||
*/
|
||||
async function attachUpload(field, file, pasted) {
|
||||
const name = pasted || !file.name ? Attachments.pastedName(file, new Date()) : file.name;
|
||||
const wait = Attachments.placeholder(name);
|
||||
attachPut(field, wait);
|
||||
const answer = file.size > UPLOAD_LIMIT ? null : await send(`/api/uploads?name=${encodeURIComponent(name)}`, file, "application/octet-stream");
|
||||
const path = answer && answer.ok && answer.data ? answer.data.path : "";
|
||||
if (path && Attachments.pictured(file.type)) {
|
||||
attachThumbs.set(path, URL.createObjectURL(file));
|
||||
}
|
||||
const reason = !answer ? `too large, at most ${UPLOAD_LIMIT / 1048576} MiB` : `upload failed, ${answer.status ? `${answer.status} ${answer.text}` : "hub unreachable"}`;
|
||||
attachSwap(field, wait, path ? Attachments.pathLine(path) : Attachments.failed(name, reason));
|
||||
}
|
||||
|
||||
function attachDrop(field, path) {
|
||||
const thumb = attachThumbs.get(path);
|
||||
if (thumb) {
|
||||
URL.revokeObjectURL(thumb);
|
||||
attachThumbs.delete(path);
|
||||
}
|
||||
const value = Attachments.removed(field.value, path);
|
||||
attachSet(field, value, Math.min(field.selectionEnd ?? value.length, value.length));
|
||||
field.focus();
|
||||
}
|
||||
|
||||
function attachChip(field, path) {
|
||||
const name = Attachments.baseName(path);
|
||||
const thumb = attachThumbs.get(path);
|
||||
return h("span", {class: "mic-chip", role: "listitem", title: path, "data-path": path},
|
||||
thumb ? h("img", {class: "mic-chip-thumb", src: thumb, alt: ""}) : icon("bi-file-earmark"),
|
||||
h("span", {class: "mic-chip-name"}, name),
|
||||
h("button", {type: "button", class: "mic-chip-drop", ...named(`Remove ${name}`, `Remove ${name}: the chip and its line`), on: {click: () => attachDrop(field, path)}}, "✕"));
|
||||
}
|
||||
|
||||
function attachDraw(field) {
|
||||
const row = attachRows.get(field);
|
||||
const found = Attachments.paths(field.value);
|
||||
row.replaceChildren(...found.map((path) => attachChip(field, path)));
|
||||
row.hidden = !found.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {HTMLInputElement|HTMLTextAreaElement} field a framed text field; paste and drop of files upload into it.
|
||||
*/
|
||||
function attachWire(field) {
|
||||
if (attachWired.has(field)) {
|
||||
return;
|
||||
}
|
||||
attachWired.add(field);
|
||||
field.addEventListener("paste", (event) => {
|
||||
const files = attachFiles(event.clipboardData);
|
||||
// Trip-wire: a copy from a spreadsheet or an office app carries a picture of the cells besides the text; text wins, so Ctrl+V of text never uploads.
|
||||
if (!files.length || event.clipboardData.getData("text/plain")) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
files.forEach((file) => attachUpload(field, file, true));
|
||||
});
|
||||
field.addEventListener("dragover", (event) => {
|
||||
if (attachDrags(event)) {
|
||||
event.preventDefault();
|
||||
event.dataTransfer.dropEffect = "copy";
|
||||
}
|
||||
});
|
||||
field.addEventListener("drop", (event) => {
|
||||
const files = attachDrags(event) ? attachFiles(event.dataTransfer) : [];
|
||||
if (!files.length) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
field.focus();
|
||||
files.forEach((file) => attachUpload(field, file, false));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {HTMLTextAreaElement} field the textarea the chips belong to.
|
||||
* @returns {HTMLElement} its chip row, made once and kept, redrawn from the path lines of its text on every input.
|
||||
*/
|
||||
function attachRow(field) {
|
||||
const kept = attachRows.get(field);
|
||||
if (kept) {
|
||||
return kept;
|
||||
}
|
||||
const row = h("div", {class: "mic-chips", role: "list", "aria-label": "Attachments", hidden: true});
|
||||
attachRows.set(field, row);
|
||||
field.addEventListener("input", () => attachDraw(field));
|
||||
attachDraw(field);
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {HTMLTextAreaElement} field the textarea the picked files land in.
|
||||
* @returns {HTMLElement[]} the hidden file input and the 📎 button that opens it, for the footer before the mic.
|
||||
*/
|
||||
function attachPicker(field) {
|
||||
const picker = h("input", {type: "file", multiple: true, hidden: true, tabindex: "-1", class: "mic-attach-file", "aria-label": "Attach files"});
|
||||
picker.addEventListener("change", () => {
|
||||
attachFiles(picker).forEach((file) => attachUpload(field, file, false));
|
||||
picker.value = "";
|
||||
});
|
||||
const button = h("button", {type: "button", class: "mic-attach", "aria-controls": field.id, ...named("Attach files", ATTACH_HINT), on: {click: () => picker.click()}}, icon("bi-paperclip"));
|
||||
return [picker, button];
|
||||
}
|
||||
@@ -12,6 +12,26 @@
|
||||
const HOLD_MS = 350;
|
||||
const composer = {live: null};
|
||||
|
||||
/**
|
||||
* @param {string} text a footer cell's word.
|
||||
* @returns {Element} the word as the cell label a narrow composer hides visually, its button keeping the name.
|
||||
*/
|
||||
function cellLabel(text) {
|
||||
return h("span", {class: "cell-label"}, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {HTMLTextAreaElement} text the message field; without CSS field-sizing it takes its content's height, which
|
||||
* the stylesheet caps at six lines.
|
||||
*/
|
||||
function grow(text) {
|
||||
if (CSS.supports("field-sizing", "content")) {
|
||||
return;
|
||||
}
|
||||
text.style.removeProperty("--composer-height");
|
||||
text.style.setProperty("--composer-height", `${text.scrollHeight}px`);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {boolean} silence whether a mayday holds the radio silent.
|
||||
* @returns {Object} {pressed, label, hint}: the MAYDAY toggle's face: Cancel mayday while one is active.
|
||||
@@ -25,7 +45,7 @@
|
||||
const shown = maydayFace(Boolean(state.silence));
|
||||
button.setAttribute("aria-pressed", String(shown.pressed));
|
||||
button.title = shown.hint;
|
||||
button.replaceChildren(icon("bi-life-preserver"), shown.label);
|
||||
button.replaceChildren(icon("bi-life-preserver"), cellLabel(shown.label));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -113,6 +133,7 @@
|
||||
const held = parts.ptt === "released";
|
||||
parts.ptt = "";
|
||||
parts.record.disabled = true;
|
||||
recordLabel(parts, "busy");
|
||||
try {
|
||||
const sound = context();
|
||||
if (!sound || !blob.size) {
|
||||
@@ -143,12 +164,16 @@
|
||||
toast("Recording failed", [String(error.message || error)], false);
|
||||
} finally {
|
||||
parts.record.disabled = false;
|
||||
recordLabel(parts, "idle");
|
||||
}
|
||||
}
|
||||
|
||||
function recordLabel(parts, on) {
|
||||
parts.record.setAttribute("aria-pressed", String(on));
|
||||
parts.record.replaceChildren(icon(on ? "bi-stop-fill" : "bi-record-circle"), on ? "Stop" : "Record");
|
||||
/**
|
||||
* @param {Object} parts the composer's controls.
|
||||
* @param {string} look idle, recording or busy (converting and transcribing), as recLook draws every recording control.
|
||||
*/
|
||||
function recordLabel(parts, look) {
|
||||
recLook(parts.record, look, "bi-record-circle", [cellLabel(look === "recording" ? "Stop" : look === "busy" ? "Working" : "Record")]);
|
||||
}
|
||||
|
||||
function stopRecording(parts) {
|
||||
@@ -186,14 +211,13 @@
|
||||
if (composer.live === parts) {
|
||||
composer.live = null;
|
||||
}
|
||||
recordLabel(parts, false);
|
||||
keepRecording(new Blob(chunks, {type: recorder.mimeType}), parts);
|
||||
}, {once: true});
|
||||
freeMicrophone(parts);
|
||||
Object.assign(parts, {recorder, started: Date.now()});
|
||||
composer.live = parts;
|
||||
recorder.start();
|
||||
recordLabel(parts, true);
|
||||
recordLabel(parts, "recording");
|
||||
if (parts.ptt === "released") {
|
||||
stopRecording(parts);
|
||||
}
|
||||
@@ -214,10 +238,10 @@
|
||||
const replay = h("div", {class: "voice-note", hidden: true});
|
||||
const status = h("span", {class: "muted composer-status", "aria-live": "polite"});
|
||||
const record = h("button", {type: "button", class: "btn small", "aria-pressed": "false", title: "Record: one click starts, another stops, you check the text before sending; hold it to talk, release to send"});
|
||||
const submit = h("button", {type: "submit", class: "btn primary ptt", title: "PTT: push to transmit the message; your passkey signs it"}, icon("bi-broadcast-pin"), "PTT");
|
||||
const submit = h("button", {type: "submit", class: "btn primary ptt", title: "PTT: push to transmit the message; your passkey signs it"}, icon("bi-broadcast-pin"), cellLabel("PTT"));
|
||||
const attach = h("input", {type: "checkbox", title: "Attach recording: the agents get the path of the sound file; otherwise only the checked text goes out"});
|
||||
const parts = {record, status, text, replay, attach, voice: "", recorder: null, timer: 0, started: 0, ptt: "", hold: 0, swallow: false};
|
||||
recordLabel(parts, false);
|
||||
recordLabel(parts, "idle");
|
||||
const gap = micGap();
|
||||
if (gap) {
|
||||
record.disabled = true;
|
||||
@@ -243,9 +267,14 @@
|
||||
};
|
||||
channel.addEventListener("change", sync);
|
||||
sync();
|
||||
const frame = micFrame(text, [record, status]);
|
||||
const frame = micFrame(text, [record]);
|
||||
frame.prepend(h("div", {class: "composer-grid"}, h("label", {class: "composer-channel"}, "Channel", channel), toField));
|
||||
frame.querySelector(".mic-foot").append(h("div", {class: "ptt-split", role: "group", "aria-label": "Send"}, submit, testMenu(text, channel)), mayday);
|
||||
const foot = frame.querySelector(".mic-foot");
|
||||
foot.classList.add("composer-foot");
|
||||
foot.querySelector(":scope > .spacer").remove();
|
||||
foot.append(h("div", {class: "ptt-split", role: "group", "aria-label": "Send"}, submit, testMenu(text, channel)), mayday);
|
||||
text.before(status);
|
||||
text.addEventListener("input", () => grow(text));
|
||||
const form = h("form", {class: "composer"}, frame, replay);
|
||||
const empty = () => {
|
||||
if (!text.value.trim()) {
|
||||
@@ -258,6 +287,7 @@
|
||||
mayday.disabled = true;
|
||||
if (await radioSend({to, text: text.value, upload: "", cls, voice: attach.checked ? parts.voice : ""})) {
|
||||
text.value = "";
|
||||
text.dispatchEvent(new Event("input", {bubbles: true}));
|
||||
status.textContent = "";
|
||||
attachVoice(parts, "");
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
const TO_ONE = [["post", "Post"], ["call", "Call"]];
|
||||
const STATUS = {
|
||||
running: ["running", "ok"], queued: ["waiting", "info"], blocked: ["blocked", "bad"], stale: ["stale", "warn"], pending: ["open", "warn"], done: ["done", "neutral"], stopped: ["stopped", "neutral"],
|
||||
approved: ["approved", "ok"], rejected: ["denied", "bad"], allowed: ["allowed", "ok"], denied: ["denied", "bad"], expired: ["expired", "neutral"], decided: ["decided", "ok"], failed: ["failed", "bad"], refused: ["refused", "bad"],
|
||||
approved: ["approved", "ok"], rejected: ["denied", "bad"], allowed: ["allowed", "ok"], denied: ["denied", "bad"], expired: ["expired", "neutral"], terminal: ["answered in the terminal", "neutral"], decided: ["decided", "ok"], failed: ["failed", "bad"], refused: ["refused", "bad"],
|
||||
};
|
||||
const SECTIONS = {staged: "Staged", unstaged: "Not staged", untracked: "Untracked", commits: "Commits"};
|
||||
const FILE_STATUS = {added: ["A", "ok"], deleted: ["D", "bad"], modified: ["M", "info"], renamed: ["R", "violet"], copied: ["C", "violet"], untracked: ["U", "warn"]};
|
||||
|
||||
@@ -1,62 +1,50 @@
|
||||
const DIAL_MAX = 60;
|
||||
const DIAL_PAGE = 5;
|
||||
const DIAL_SIZE = 140;
|
||||
const DIAL_RADIUS = 58;
|
||||
|
||||
/**
|
||||
* @param {number} second a value on the dial, 0 to DIAL_MAX.
|
||||
* @param {number} radius how far from the centre.
|
||||
* @returns {number[]} the point [x, y] for that second, 0 and 60 at the top, clockwise.
|
||||
* @param {Object} options value: the whole value the dial starts at; label: the slider's accessible name; name: the
|
||||
* root's own class; min, max: the ends, max a full turn; page: the Page Up and Down step and the long-tick spacing;
|
||||
* unit: the readout's unit; spoken: (value) => the aria-valuetext; readonly: true for a dial only the caller moves.
|
||||
* @returns {root, value, set}: an analog clock face with Dial.TICKS ticks and one hand, an ARIA slider: dragging the
|
||||
* hand or clicking a tick sets it, the arrows step 1, Page Up and Down page, Home and End the ends; set(value) moves it.
|
||||
*/
|
||||
function dialPoint(second, radius) {
|
||||
const angle = (second / DIAL_MAX) * 2 * Math.PI;
|
||||
const centre = DIAL_SIZE / 2;
|
||||
return [centre + Math.sin(angle) * radius, centre - Math.cos(angle) * radius];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} value the undo window in whole seconds the dial starts at.
|
||||
* @param {string} label the slider's accessible name.
|
||||
* @returns {root, value}: an analog clock face with 60 ticks and one hand, an ARIA slider:
|
||||
* dragging the hand or clicking a tick sets it, the arrows step 1 s, Page Up and Down 5 s, Home and End the ends.
|
||||
*/
|
||||
function undoDial(value, label) {
|
||||
let seconds = value;
|
||||
const ticks = Array.from({length: DIAL_MAX}, (_, second) => {
|
||||
const long = second % DIAL_PAGE === 0;
|
||||
const [x1, y1] = dialPoint(second, DIAL_RADIUS - (long ? 10 : 5));
|
||||
const [x2, y2] = dialPoint(second, DIAL_RADIUS);
|
||||
function dial(options) {
|
||||
let current = options.value;
|
||||
const centre = Dial.SIZE / 2;
|
||||
const ticks = Dial.ticks(options.page).map(({at, long}) => {
|
||||
const [x1, y1] = Dial.point(at, Dial.TICKS, Dial.RADIUS - (long ? 10 : 5));
|
||||
const [x2, y2] = Dial.point(at, Dial.TICKS, Dial.RADIUS);
|
||||
return s("line", {class: `dial-tick${long ? " long" : ""}`, x1: fixed(x1), y1: fixed(y1), x2: fixed(x2), y2: fixed(y2)});
|
||||
});
|
||||
const centre = DIAL_SIZE / 2;
|
||||
const hand = s("line", {class: "dial-hand", x1: centre, y1: centre});
|
||||
const face = s("svg", {class: "dial-face", viewBox: `0 0 ${DIAL_SIZE} ${DIAL_SIZE}`, "aria-hidden": "true", focusable: "false"},
|
||||
s("circle", {class: "dial-rim", cx: centre, cy: centre, r: DIAL_RADIUS + 4}), ticks, hand, s("circle", {class: "dial-pin", cx: centre, cy: centre, r: 4}));
|
||||
const face = s("svg", {class: "dial-face", viewBox: `0 0 ${Dial.SIZE} ${Dial.SIZE}`, "aria-hidden": "true", focusable: "false"},
|
||||
s("circle", {class: "dial-rim", cx: centre, cy: centre, r: Dial.RADIUS + 4}), ticks, hand, s("circle", {class: "dial-pin", cx: centre, cy: centre, r: 4}));
|
||||
const readout = h("output", {class: "dial-readout"});
|
||||
const root = h("div", {class: "undo-dial", role: "slider", tabindex: "0", "aria-label": label, "aria-valuemin": "0", "aria-valuemax": String(DIAL_MAX)}, face, readout);
|
||||
const root = h("div", {class: `dial ${options.name}`, role: "slider", tabindex: "0", "aria-label": options.label, "aria-valuemin": String(options.min), "aria-valuemax": String(options.max),
|
||||
"aria-readonly": options.readonly ? "true" : null}, face, readout);
|
||||
const set = (next) => {
|
||||
seconds = Math.max(0, Math.min(DIAL_MAX, Math.round(next)));
|
||||
const [x2, y2] = dialPoint(seconds, DIAL_RADIUS - 14);
|
||||
current = Dial.clamp(next, options);
|
||||
const [x2, y2] = Dial.point(current, options.max, Dial.RADIUS - 14);
|
||||
hand.setAttribute("x2", fixed(x2));
|
||||
hand.setAttribute("y2", fixed(y2));
|
||||
readout.textContent = `${seconds} s`;
|
||||
root.setAttribute("aria-valuenow", String(seconds));
|
||||
root.setAttribute("aria-valuetext", seconds ? `${seconds} seconds to undo` : "0 seconds: takes effect at once");
|
||||
readout.textContent = `${current} ${options.unit}`;
|
||||
root.setAttribute("aria-valuenow", String(current));
|
||||
root.setAttribute("aria-valuetext", options.spoken(current));
|
||||
};
|
||||
set(current);
|
||||
if (options.readonly) {
|
||||
return {root, value: () => current, set};
|
||||
}
|
||||
const pointed = (event) => {
|
||||
const box = face.getBoundingClientRect();
|
||||
const degrees = (Math.atan2(event.clientX - box.left - box.width / 2, box.top + box.height / 2 - event.clientY) * 180) / Math.PI;
|
||||
set(((degrees + 360) % 360) / (360 / DIAL_MAX));
|
||||
set(Dial.fromAngle((Math.atan2(event.clientX - box.left - box.width / 2, box.top + box.height / 2 - event.clientY) * 180) / Math.PI, options.max));
|
||||
};
|
||||
root.addEventListener("keydown", (event) => {
|
||||
const steps = {ArrowRight: 1, ArrowUp: 1, ArrowLeft: -1, ArrowDown: -1, PageUp: DIAL_PAGE, PageDown: -DIAL_PAGE};
|
||||
if (event.key in steps) {
|
||||
set(seconds + steps[event.key]);
|
||||
} else if (event.key === "Home" || event.key === "End") {
|
||||
set(event.key === "Home" ? 0 : DIAL_MAX);
|
||||
} else {
|
||||
const next = Dial.stepped(event.key, current, options);
|
||||
if (next === null) {
|
||||
return;
|
||||
}
|
||||
set(next);
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
});
|
||||
@@ -70,6 +58,15 @@
|
||||
pointed(event);
|
||||
}
|
||||
});
|
||||
set(seconds);
|
||||
return {root, value: () => seconds};
|
||||
return {root, value: () => current, set};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} value the undo window in whole seconds the dial starts at.
|
||||
* @param {string} label the slider's accessible name.
|
||||
* @returns {root, value, set}: dial() over 0 to DIAL_MAX seconds, Page Up and Down 5 s.
|
||||
*/
|
||||
function undoDial(value, label) {
|
||||
const spoken = (seconds) => (seconds ? `${seconds} seconds to undo` : "0 seconds: takes effect at once");
|
||||
return dial({value, label, name: "undo-dial", min: 0, max: DIAL_MAX, page: DIAL_PAGE, unit: "s", spoken, readonly: false});
|
||||
}
|
||||
@@ -143,7 +143,7 @@
|
||||
const hidden = hiddenFile(item, raw);
|
||||
const file = clear === undefined ? raw : {...raw, patch: clear, note: ""};
|
||||
const tone = DIFF_TONES[file.status] || "neutral";
|
||||
const head = [h("span", {class: "letter", "data-tone": tone}, file.status), h("code", {class: "path"}, revealed(file.path)),
|
||||
const head = [h("span", {class: "letter", "data-tone": tone}, file.status), pathCode(item.directory, file.path, revealed(file.path)),
|
||||
file.mode && file.mode !== "100644" ? h("code", {class: "mode", title: `mode: ${file.mode}`}, file.mode) : null, h("span", {class: "spacer"}),
|
||||
file.note ? h("span", {class: "note", title: file.note}, icon("bi-eye-slash"), file.note) : null,
|
||||
hidden ? revealButton(item, [file.path], "Reveal") : null,
|
||||
|
||||
@@ -159,7 +159,52 @@
|
||||
return button;
|
||||
}
|
||||
|
||||
const MENUS = "details.menu, details.radio-station, details.radio-notify, .ctx-menu";
|
||||
const PATH_ACTIONS = "click opens in VS Code, right-click copies the path";
|
||||
|
||||
/**
|
||||
* @param {string} path a path on the operator's machine.
|
||||
* @returns {string} the link that opens it in VS Code: vscode://file plus the absolute path, every segment
|
||||
* URI-encoded and the slashes kept; "" for a relative or empty path.
|
||||
*/
|
||||
function vscodeHref(path) {
|
||||
return typeof path === "string" && path.startsWith("/") ? `vscode://file${path.split("/").map(encodeURIComponent).join("/")}` : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} root an absolute folder, such as a card's worktree.
|
||||
* @param {string} path a path relative to root.
|
||||
* @returns {string} path below root; "" without a root or a path.
|
||||
*/
|
||||
const pathUnder = (root, path) => (root && path ? `${root.replace(/\/+$/, "")}/${path}` : "");
|
||||
|
||||
/**
|
||||
* @param {string} path the full path the link names.
|
||||
* @param {Object} attrs the link's attributes besides href and its right-click handler.
|
||||
* @param {...*} children what the link shows.
|
||||
* @returns {HTMLElement|null} a link that opens path in VS Code, whose right-click copies path with ctxCopy() and
|
||||
* opens no context menu; null for a relative or empty path.
|
||||
*/
|
||||
function pathLink(path, attrs, ...children) {
|
||||
const href = vscodeHref(path);
|
||||
return href ? h("a", {...attrs, href, on: {contextmenu: (event) => {
|
||||
event.preventDefault();
|
||||
ctxCopy(path);
|
||||
}}}, ...children) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} root the folder the diff was taken in: a card's worktree or directory.
|
||||
* @param {string} path the file's path relative to root.
|
||||
* @param {string} shown the text the head shows for the file.
|
||||
* @returns {HTMLElement} the file head's code.path, inside a pathLink() to root/path when root is absolute.
|
||||
*/
|
||||
function pathCode(root, path, shown) {
|
||||
const full = pathUnder(root, path);
|
||||
const code = h("code", {class: "path"}, shown);
|
||||
return pathLink(full, {class: "path-link", title: `${revealed(full)}: ${PATH_ACTIONS}`}, code) || code;
|
||||
}
|
||||
|
||||
const MENUS ="details.menu, details.radio-station, details.radio-notify, .ctx-menu";
|
||||
const MENU_LINGER = 3000;
|
||||
const ACTIONS_IN_MENU = "button, a[href], [role='button']";
|
||||
|
||||
|
||||
@@ -1,20 +1,19 @@
|
||||
const FIREWALL_LISTS = {"permissions.allow": "Allow", "permissions.ask": "Ask", "permissions.deny": "Deny", "sandbox.filesystem.allowWrite": "Sandbox: write", "sandbox.filesystem.denyRead": "Sandbox: no read", "sandbox.network.allowedDomains": "Sandbox: domain"};
|
||||
const LIST_TONES = {allow: "ok", ask: "warn", deny: "bad"};
|
||||
const ROW_FILTERS = [["allow", "Allow"], ["ask", "Ask"], ["deny", "Deny"], ["sandbox", "Sandbox"], ["signed", "Signed"]];
|
||||
const ACTION_ORDER = ["deny", "ask", "allow", "sandbox", "signed"];
|
||||
const ROW_FILTERS = [["allow", "Allow"], ["ask", "Ask"], ["deny", "Deny"], ["sandbox", "Sandbox"]];
|
||||
const ACTION_ORDER = ["deny", "ask", "allow", "sandbox"];
|
||||
const ENTRY_HINTS = {
|
||||
allow: "Claude Code runs a matching call without asking, so it never reaches the ask ledger.",
|
||||
ask: "Claude Code asks before a matching call; the ask reaches the Agent Orchestrator.",
|
||||
deny: "Claude Code refuses a matching call, so it never reaches the ask ledger.",
|
||||
sandbox: "Bounds what a sandboxed command may write, read or reach.",
|
||||
};
|
||||
const HUB_SOURCE = "hub";
|
||||
const SETTINGS_RESULTS = {done: ["written", "ok"], refused: ["refused", "bad"], failed: ["failed", "bad"]};
|
||||
const EVERY_AGENT = "*";
|
||||
const TARGET_GONE = "gone";
|
||||
const TARGET_PICK = "";
|
||||
const SESSION_KEY = /^(?!-)[A-Za-z0-9_-]{1,128}$/;
|
||||
const CONTROL_TABS = [["tools", "Tools", "bi-plug"], ["rules", "Rules", "bi-shield-lock"], ["groups", "Groups", "bi-people"], ["schedules", "Schedules", "bi-clock"]];
|
||||
const CONTROL_TABS = [["tools", "Tools", "bi-plug"], ["rules", "Rules", "bi-shield-lock"], ["schedules", "Schedules", "bi-clock"], ["queue", "Queue", "bi-hourglass-split"]];
|
||||
const CAPABILITY_WORDS = {deniedMcpServers: ["Unblock server", "Block server"], enabledPlugins: ["Enable plugin", "Disable plugin"], switches: ["Turn on", "Turn off"]};
|
||||
const TOOL_HINTS = {
|
||||
deniedMcpServers: "Off blocks the server before it loads, in every session and project.",
|
||||
@@ -263,7 +262,7 @@
|
||||
const name = h("input", {class: "field", type: "text", placeholder: "ci", "aria-label": "Set name"});
|
||||
const days = h("input", {class: "field", type: "number", min: 1, max: 366, value: 7, "aria-label": "Days"});
|
||||
const chosen = checkChips("Rules", state.rules.map((rule) => [rule.id, revealed(`${rule.kind} ${rule.tool} ${rule.pattern}`.replace(" ", " ")), null]),
|
||||
h("p", {class: "muted"}, "No rule yet: create one under Rules, New hub rule for automatic grants, then pick it here."));
|
||||
h("p", {class: "muted"}, "No rule yet: create one under Rules with New rule, then pick it here."));
|
||||
const form = h("form", {class: "fw-form", "aria-label": "New rule set"}, h("label", {}, "Name", name), h("label", {}, "Days", days), chosen.node,
|
||||
h("button", {type: "submit", class: "btn soft", ...named("Save set", "Save set: keep the chosen rules as one named rule set")}, icon("bi-collection"), "Save set"));
|
||||
form.addEventListener("submit", async (event) => {
|
||||
@@ -346,25 +345,14 @@
|
||||
return [...permissions, ...sandbox];
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Object[]} one row per stored hub rule, with the hits /api/firewall counted for it; pending until the next fetch counts a new rule.
|
||||
*/
|
||||
function signedRows() {
|
||||
const counted = firewall.data.rules;
|
||||
return state.rules.map((rule) => ({filter: "signed", action: `Grant ${rule.kind}`, tone: "ok", tool: rule.tool, pattern: rule.pattern, rule, ...(Object.hasOwn(counted, rule.id) ? counted[rule.id] : {hits: null, never: "", pending: true})}));
|
||||
}
|
||||
|
||||
const fileStatus = (file) => (file.error ? pill(file.error, "bad") : file.exists ? pill(`sha256 ${file.sha256.slice(0, 12)}`, "neutral") : pill("missing: a change creates it", "warn"));
|
||||
const byAction = (one, two) => ACTION_ORDER.indexOf(one.filter) - ACTION_ORDER.indexOf(two.filter);
|
||||
|
||||
function sourceGroups() {
|
||||
return [{id: HUB_SOURCE, label: "Hub rules", file: false, status: null, rows: signedRows()}, ...SettingsFiles.listed(firewall.data.files, firewall.missing).shown.map((file) => ({id: file.path, label: file.path, file: true, status: fileStatus(file), rows: fileRows(file)}))];
|
||||
return SettingsFiles.listed(firewall.data.files, firewall.missing).shown.map((file) => ({id: file.path, label: file.path, status: fileStatus(file), rows: fileRows(file)}));
|
||||
}
|
||||
|
||||
function hitsCell(row) {
|
||||
if (row.pending) {
|
||||
return h("span", {class: "muted", title: "Counted with the next refresh"}, "…");
|
||||
}
|
||||
if (row.never) {
|
||||
return h("span", {class: "muted", title: `The matcher never grants a command that ${row.never}`}, `never granted: ${row.never}`);
|
||||
}
|
||||
@@ -374,41 +362,22 @@
|
||||
return row.hits ? h("strong", {}, String(row.hits)) : ["0 ", h("span", {class: "pill", "data-tone": "warn", title: "No ask of the counted days matched this entry"}, "unused")];
|
||||
}
|
||||
|
||||
function actionCell(row) {
|
||||
const rule = row.rule;
|
||||
const action = h("span", {class: "pill", "data-tone": row.tone, title: rule ? RULE_HINTS[rule.kind] : ENTRY_HINTS[row.filter]}, row.action);
|
||||
if (!rule) {
|
||||
return action;
|
||||
}
|
||||
const until = `until ${absolute.format(stampOf(rule.expires))}`;
|
||||
return [action, rule.expires <= nowSeconds() ? pill("expired", "bad") : null, h("span", {class: "pill", "data-tone": rule.enabled ? "ok" : "neutral", title: until}, rule.enabled ? "active" : "off")];
|
||||
}
|
||||
const actionCell = (row) => h("span", {class: "pill", "data-tone": row.tone, title: ENTRY_HINTS[row.filter]}, row.action);
|
||||
|
||||
function changeCell(group, row) {
|
||||
const rule = row.rule;
|
||||
if (rule) {
|
||||
return [btn(rule.enabled ? "Turn off" : "Turn on", "btn small", () => changeRule(rule, rule.enabled ? "disable" : "enable")), btn("Delete", "btn small danger", () => {
|
||||
if (window.confirm("Delete rule?")) {
|
||||
changeRule(rule, "delete");
|
||||
}
|
||||
})];
|
||||
}
|
||||
const editable = row.entry !== null && Object.hasOwn(FIREWALL_LISTS, row.list);
|
||||
return editable ? iconBtn("bi-dash-circle", "Remove", "btn small ghost", () => stageChange(group.id, {list: row.list, op: "remove", entry: row.entry}), `Remove: stage the removal of ${revealed(row.entry)} from ${row.list}`) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} group the source the row belongs to: id, label and file, false for the hub rules.
|
||||
* @param {Object} row a row of fileRows() or signedRows().
|
||||
* @returns {HTMLTableRowElement} the row: action, tool, pattern, scope, source, hits and its change buttons.
|
||||
* @param {Object} group the settings file the row belongs to: id and label, its path.
|
||||
* @param {Object} row a row of fileRows().
|
||||
* @returns {HTMLTableRowElement} the row: action, tool, pattern, scope, source, hits and its change button.
|
||||
*/
|
||||
function ruleRow(group, row) {
|
||||
const rule = row.rule;
|
||||
const pattern = [h("code", {}, revealed(row.pattern)), rule && rule.kind !== "decision" ? h("span", {class: "muted"}, " in ", h("code", {}, rule.scope ? revealed(rule.scope) : "–")) : null];
|
||||
const source = rule ? h("span", {class: "muted"}, rule.signed ? "Hub, passkey-signed" : "Hub, unsigned: has no effect") : h("code", {class: "fw-path"}, revealed(group.label));
|
||||
return h("tr", {"data-filter": row.filter, "data-list": row.list, "data-entry": row.entry, "data-rule": rule ? rule.id : null, "data-unused": row.hits === 0},
|
||||
h("td", {}, actionCell(row)), h("td", {}, row.tool ? h("code", {}, revealed(row.tool)) : "–"), h("td", {}, pattern),
|
||||
h("td", {}, rule ? targetPill(rule.agents) : h("span", {class: "muted"}, "file")), h("td", {}, source),
|
||||
return h("tr", {"data-filter": row.filter, "data-list": row.list, "data-entry": row.entry, "data-unused": row.hits === 0},
|
||||
h("td", {}, actionCell(row)), h("td", {}, row.tool ? h("code", {}, revealed(row.tool)) : "–"), h("td", {}, h("code", {}, revealed(row.pattern))),
|
||||
h("td", {}, h("span", {class: "muted"}, "file")), h("td", {}, h("code", {class: "fw-path"}, revealed(group.label))),
|
||||
h("td", {class: "fw-hits"}, hitsCell(row)), h("td", {class: "fw-change"}, changeCell(group, row)));
|
||||
}
|
||||
|
||||
@@ -426,7 +395,7 @@
|
||||
firewall.open.add(group.id);
|
||||
}
|
||||
drawFirewall();
|
||||
}}}, icon(open ? "bi-chevron-down" : "bi-chevron-right"), group.file ? h("code", {class: "fw-path"}, revealed(group.label)) : h("strong", {}, group.label), counter(rows.length), unused ? pill(`${unused} unused`, "warn") : null);
|
||||
}}}, icon(open ? "bi-chevron-down" : "bi-chevron-right"), h("code", {class: "fw-path"}, revealed(group.label)), counter(rows.length), unused ? pill(`${unused} unused`, "warn") : null);
|
||||
return h("tbody", {"data-source": group.id}, h("tr", {class: "fw-source"}, h("th", {colspan: 7, scope: "rowgroup"}, h("div", {class: "row"}, fold, group.status))), open ? rows.map((row) => ruleRow(group, row)) : []);
|
||||
}
|
||||
|
||||
@@ -557,7 +526,7 @@
|
||||
}
|
||||
const files = data.files;
|
||||
return h("section", {class: "card stack-tight fw-rules", "aria-label": "Firewall rules"}, h("h3", {}, "Firewall rules"),
|
||||
h("p", {class: "muted"}, `Every rule in one table: the hub rules and the permissions and sandbox entries of the listed settings files as the host read them, one folded group per source. Hits count the asks of the last ${data.days} days a rule matches, with the matcher of the rule request dry run; allow, deny and sandbox entries never reach the ask ledger and show not seen. A settings change shows as a diff, is signed with your passkey and is written by the host, never by an agent.`),
|
||||
h("p", {class: "muted"}, `The permissions and sandbox entries of the listed settings files as the host read them, one folded group per file. Hits count the asks of the last ${data.days} days a rule matches, with the matcher of the rule request dry run; allow, deny and sandbox entries never reach the ask ledger and show not seen. A settings change shows as a diff, is signed with your passkey and is written by the host, never by an agent.`),
|
||||
data.error ? h("p", {class: "muted"}, data.error) : null,
|
||||
h("div", {class: "row fw-filters"}, filterChips(), missingToggle(SettingsFiles.listed(files, false).missing)), ruleTable(), files.length ? addForm(files) : null);
|
||||
}
|
||||
|
||||
@@ -191,6 +191,8 @@
|
||||
Panels.panel("tasks/match", "Tasks: Match", () => homeMatch(), "", [6, 8]);
|
||||
Panels.panel("resources-accounts", "Resources: accounts", () => homeAccounts(), "", [12, 5]);
|
||||
Panels.panel("stream/schedules", "Controls: schedules", () => schedulesContent(), "", [12, 6]);
|
||||
Panels.panel("stream/queue", "Controls: queue", () => homeQueue(), "", [12, 6]);
|
||||
Panels.panel("resources-usage", "Resources: usage", () => homeUsage(), "", [12, 6]);
|
||||
Panels.item("metric", (id, view) => metricTitle(view), (size, id, view) => homeMetric(id, view));
|
||||
Panels.capture("resources-hardware", () => resourcePin("hardware"));
|
||||
Panels.capture("resources-tokens", () => resourcePin("tokens"));
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
const KANBAN_DRAG = "application/x-kvb-task";
|
||||
const KANBAN_LAYERS = "kanban.hidden";
|
||||
const KANBAN_JOBS_SHOWN = 3;
|
||||
const kanban = {staged: [], collapsed: new Set(), old: false, dragging: null, queue: {marks: {}, line: true, jobs: true}, bound: false};
|
||||
const kanban = {staged: [], collapsed: new Set(), old: false, running: false, marks: {}, dragging: null, queue: {marks: {}, line: true, jobs: true}, bound: false};
|
||||
|
||||
function restage(next) {
|
||||
kanban.staged = next;
|
||||
@@ -129,7 +129,7 @@
|
||||
const hint = `Why ${job.id} stands at ${Kanban.whyHere(job).place}: the rules queue.py applied, in order`;
|
||||
const why = h("button", {type: "button", class: "btn small ghost queue-why", "data-job": job.id, ...named(`Why here: ${job.id}`, hint), on: {click: open}}, icon("bi-question-circle"), h("span", {class: "queue-why-text"}, "Why here?"));
|
||||
return h("li", {class: "queue-job", "data-job": job.id, "data-class": job.class || "", "data-kind": job.kind},
|
||||
h("div", {class: "queue-chips"}, chips, why), job.reason ? h("p", {class: "queue-reason", title: job.reason}, job.reason) : null);
|
||||
h("div", {class: "queue-chips"}, chips, why, job.status === "waiting" ? startNow(job) : null), job.reason ? h("p", {class: "queue-reason", title: job.reason}, job.reason) : null);
|
||||
}
|
||||
|
||||
function queueJobs(row) {
|
||||
@@ -146,8 +146,10 @@
|
||||
const open = () => taskSelect(row.task, cardOf(row.task));
|
||||
const own = (event) => !event.target.closest("button, summary, details, select, .kanban-handle");
|
||||
const after = () => kanban.dragging && kanban.dragging.mode === "after" && kanban.dragging.task !== row.task;
|
||||
const found = kanban.marks[row.task];
|
||||
return h("li", {
|
||||
class: ["task-card", "kanban-card", row.pending ? "pending" : ""].filter(Boolean).join(" "), "data-task": row.task, "data-item": `task:${row.task}`, "data-lane": lane, "data-column": column, tabindex: 0,
|
||||
"data-mark": found.length ? found[0].key : null, "data-marks": found.length ? found.map((mark) => mark.key).join(" ") : null,
|
||||
"data-pending": row.pending ? row.pending.map((argv) => argv.join(" ")).join("\n") : null, draggable: row.movable ? "true" : null,
|
||||
on: {
|
||||
click: (event) => own(event) && open(),
|
||||
@@ -181,6 +183,7 @@
|
||||
}}}, icon("bi-arrow-right-circle")) : null,
|
||||
row.movable ? kanbanMenu(row, cards) : null),
|
||||
h("span", {class: "kanban-title"}, titleOf(row)),
|
||||
markChips(row, found),
|
||||
row.worker !== "-" ? h("span", {class: "muted"}, row.worker) : null,
|
||||
queueJobs(row),
|
||||
cardWhy(row.task));
|
||||
@@ -217,7 +220,7 @@
|
||||
h("div", {class: "kanban-cells", id, hidden: !open}, TASK_COLUMNS.map(([column, label]) => kanbanCell(lane, column, label, cards))));
|
||||
}
|
||||
|
||||
function kanbanBar(hidden, stale) {
|
||||
function kanbanBar(hidden, stale, marked) {
|
||||
const count = kanban.staged.length;
|
||||
const words = `Apply ${count} changes`;
|
||||
const apply = h("button", {type: "button", class: "btn small primary", id: "kanban-apply", disabled: count === 0, ...named(words, `${words}: one passkey signs every staged move, the runner applies them through rasci.py`), on: {click: applyStaged}}, icon("bi-check2-all"), counter(count));
|
||||
@@ -230,7 +233,7 @@
|
||||
const stalled = h("span", {class: "pill", id: "kanban-stale", "data-tone": "warn", role: "img", ...named(`Stale: ${stale}`, `Stale: ${stale} tasks without a register change for ${Plan.STALE_DAYS} days, counted apart`)}, icon("bi-hourglass-bottom"), String(stale));
|
||||
const listed = count ? h("ol", {class: "kanban-staged", id: "kanban-staged", "aria-label": `${words}: the passkey signs exactly these`},
|
||||
kanban.staged.map(({task, argv}) => h("li", {"data-task": task}, h("code", {}, shownArgv(argv))))) : null;
|
||||
return [h("div", {class: "kanban-bar", role: "toolbar", "aria-label": "Board"}, apply, discard, older, stalled, queueLegend()), listed];
|
||||
return [h("div", {class: "kanban-bar", role: "toolbar", "aria-label": "Board"}, apply, discard, older, runningToggle(marked), stalled, pruneControls(stale), queueLegend()), listed];
|
||||
}
|
||||
|
||||
function queueLegend() {
|
||||
@@ -298,7 +301,11 @@
|
||||
kanban.staged = kanban.staged.filter((change) => known.has(change.task));
|
||||
}
|
||||
const ids = new Set(shown.map((row) => row.task));
|
||||
const rows = Kanban.pending(state.tasks, kanban.staged).filter((row) => ids.has(row.task) && Kanban.onBoard(row));
|
||||
const placed = Kanban.pending(state.tasks, kanban.staged).filter((row) => ids.has(row.task) && Kanban.onBoard(row));
|
||||
const sources = markSources();
|
||||
kanban.marks = Object.fromEntries(placed.map((row) => [row.task, Kanban.marks(row, sources)]));
|
||||
const marked = placed.filter((row) => kanban.marks[row.task].length);
|
||||
const rows = kanban.running ? marked : placed;
|
||||
bindLayers();
|
||||
kanban.queue = {marks: Kanban.queued(rows, state.queue_line, state.queue_jobs), ...Kanban.layers(ViewStore.get(KANBAN_LAYERS))};
|
||||
const {lanes} = Kanban.board(rows, {now: state.now, old: kanban.old});
|
||||
@@ -308,5 +315,5 @@
|
||||
const box = h("div", {class: "kanban"}, head, lanes.map((lane) => kanbanLane(lane, cards)), s("svg", {class: "kanban-lines", "aria-hidden": "true"}));
|
||||
const watch = new ResizeObserver(() => (box.isConnected ? kanbanLines(box, cards) : watch.disconnect()));
|
||||
watch.observe(box);
|
||||
return h("div", {class: "kanban-box"}, kanbanBar(Kanban.board(rows, {now: state.now, old: false}).hidden, rows.filter((row) => Plan.stale(row, state.now)).length), box);
|
||||
return h("div", {class: "kanban-box"}, kanbanBar(Kanban.board(rows, {now: state.now, old: false}).hidden, rows.filter((row) => Plan.stale(row, state.now)).length, marked.length), box);
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
const LIMIT_PROFILES = [["calm", "Calm"], ["balanced", "Balanced"], ["max", "Max"]];
|
||||
const LIMIT_DIAL = {min: 0, max: 100, page: 5};
|
||||
const LIMIT_LABEL = {gap: 3, inset: 4, step: 64};
|
||||
const limitView = {data: null, busy: false, metric: "cpu", dom: null};
|
||||
|
||||
const limitsHeld = () => (limitView.data ? limitView.data.limits || limitView.data.profiles.balanced : null);
|
||||
|
||||
async function fetchLimits() {
|
||||
if (limitView.busy) {
|
||||
return;
|
||||
}
|
||||
limitView.busy = true;
|
||||
try {
|
||||
const response = await fetch("/api/limits", {cache: "no-store"});
|
||||
if (response.ok) {
|
||||
limitView.data = await response.json();
|
||||
}
|
||||
} catch {
|
||||
ui.offline = true;
|
||||
}
|
||||
limitView.busy = false;
|
||||
drawResources();
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {HTMLElement} the row above the Hardware chart: the profile switch, which metric's limit lines the chart
|
||||
* draws, and the Limits button that opens the table of every value.
|
||||
*/
|
||||
function limitBar() {
|
||||
const profiles = LIMIT_PROFILES.map(([id, label]) => [id, label, h("button", {type: "button", "data-profile": id, "aria-pressed": "false", on: {click: () => chooseProfile(id, label)}}, label)]);
|
||||
const metrics = Limits.METRICS.map((metric) => [metric, h("button", {
|
||||
type: "button", "data-metric": metric, "aria-pressed": String(metric === limitView.metric), title: `Limit lines of ${Limits.NAMES[metric]}`, on: {click: () => {
|
||||
limitView.metric = metric;
|
||||
drawResources();
|
||||
}},
|
||||
}, Limits.NAMES[metric])]);
|
||||
const sheet = h("button", {type: "button", class: "btn small soft", id: "limits-open", ...named("Limits", "Limits: every lower, upper, STOP and MAYDAY value in one table, each with its dial"), on: {click: openLimits}},
|
||||
icon("bi-sliders"), h("span", {}, "Limits"));
|
||||
const note = h("span", {class: "muted limit-note"});
|
||||
limitView.dom = {profiles, metrics, sheet, note};
|
||||
return h("div", {class: "res-limits"},
|
||||
h("div", {class: "segmented limit-profiles", role: "group", "aria-label": "Profile"}, profiles.map((entry) => entry[2])),
|
||||
h("div", {class: "segmented limit-metrics", role: "group", "aria-label": "Limit lines"}, metrics.map((entry) => entry[1])), sheet, note);
|
||||
}
|
||||
|
||||
function drawLimitBar() {
|
||||
const dom = limitView.dom;
|
||||
if (!dom) {
|
||||
return;
|
||||
}
|
||||
const data = limitView.data;
|
||||
const chosen = data ? Limits.profileOf(data.limits, data.profiles) : null;
|
||||
for (const [id, label, button] of dom.profiles) {
|
||||
const values = data && data.profiles ? data.profiles[id] : null;
|
||||
button.setAttribute("aria-pressed", String(id === chosen));
|
||||
button.disabled = !values;
|
||||
button.title = values ? `${label}: band ${values.cpu.lower} to ${values.cpu.upper} %; sets every limit at once` : "The limits are not loaded";
|
||||
}
|
||||
for (const [metric, button] of dom.metrics) {
|
||||
button.setAttribute("aria-pressed", String(metric === limitView.metric));
|
||||
}
|
||||
dom.sheet.disabled = !data;
|
||||
dom.note.textContent = !data ? "" : data.why ? revealed(data.why) : data.limits ? "" : "No limits.json: the queue config applies";
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} frame the chart frame of resourceFrame().
|
||||
* @param {Function} y maps a percent to the chart's y.
|
||||
*/
|
||||
function limitLines(frame, y) {
|
||||
const data = limitView.data;
|
||||
if (!data || !data.limits) {
|
||||
return;
|
||||
}
|
||||
const metric = limitView.metric;
|
||||
const name = Limits.NAMES[metric];
|
||||
const target = Limits.TARGETED.includes(metric) && data.target ? data.target[metric] : null;
|
||||
if (typeof target === "number") {
|
||||
const at = fixed(y(target));
|
||||
frame.svg.append(s("g", {class: "res-target", "data-metric": metric, "data-value": String(target)}, s("title", {}, `${name} target ${target.toFixed(1)} %: the live target the queue admits up to`),
|
||||
s("line", {x1: RESOURCE.left, x2: fixed(frame.right), y1: at, y2: at}), s("text", {x: RESOURCE.left + LIMIT_LABEL.inset, y: fixed(y(target) - LIMIT_LABEL.gap)}, `target ${Math.round(target)}`)));
|
||||
}
|
||||
Limits.LEVELS.forEach((level, index) => {
|
||||
const value = data.limits[metric][level];
|
||||
const words = `${name} ${Limits.LEVEL_NAMES[level]} ${value} %`;
|
||||
const at = fixed(y(value));
|
||||
const open = () => limitDial(metric, level, null);
|
||||
const press = (event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
open();
|
||||
}
|
||||
};
|
||||
frame.svg.append(s("g", {class: `res-limit ${level}`, "data-metric": metric, "data-level": level, "data-value": String(value), role: "button", tabindex: 0, "aria-label": words, on: {click: open, keydown: press}},
|
||||
s("title", {}, `${words}: click to set it on a dial`),
|
||||
s("line", {class: "res-limit-hit", x1: RESOURCE.left, x2: fixed(frame.right), y1: at, y2: at}),
|
||||
s("line", {class: "res-limit-mark", x1: RESOURCE.left, x2: fixed(frame.right), y1: at, y2: at}),
|
||||
s("text", {x: fixed(frame.right - LIMIT_LABEL.inset - index * LIMIT_LABEL.step), y: fixed(y(value) - LIMIT_LABEL.gap), "text-anchor": "end"}, `${Limits.LEVEL_NAMES[level]} ${value}`)));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} next valid limits to save.
|
||||
* @param {string} label what the passkey prompt and the toast name.
|
||||
* @returns {Promise<boolean>} whether the hub saved them: a value that stays or tightens saves at once, a looser one
|
||||
* only once the passkey signs it; a canceled passkey sends nothing and keeps the old values.
|
||||
*/
|
||||
async function saveLimits(next, label) {
|
||||
const held = limitView.data.limits;
|
||||
const loose = Limits.loosened(next, held);
|
||||
const words = !loose.length ? label : held ? `${label}: loosens ${loose.map(Limits.said).join(", ")}` : `${label}: the first limits.json`;
|
||||
const signed = await signedProof("/api/limits/sign", {limits: next}, words);
|
||||
if (signed === null) {
|
||||
return false;
|
||||
}
|
||||
const result = await sendJson("/api/limits", {limits: next, proof: signed.proof});
|
||||
if (!result.ok || !result.data) {
|
||||
toast(`${label}: not saved`, fail(result), false);
|
||||
return false;
|
||||
}
|
||||
limitView.data = result.data;
|
||||
toast(label, [loose.length ? "Signed and saved to limits.json" : "Saved to limits.json"], true);
|
||||
drawResources();
|
||||
return true;
|
||||
}
|
||||
|
||||
async function chooseProfile(id, label) {
|
||||
const data = limitView.data;
|
||||
if (data && Limits.profileOf(data.limits, data.profiles) !== id) {
|
||||
await saveLimits(data.profiles[id], `Profile ${label}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} metric one of Limits.METRICS.
|
||||
* @param {string} level one of Limits.LEVELS.
|
||||
* @param {Function|null} back what Cancel and a save return to: the Limits sheet, or null to close.
|
||||
*/
|
||||
function limitDial(metric, level, back) {
|
||||
const held = limitsHeld();
|
||||
if (!held) {
|
||||
return;
|
||||
}
|
||||
const title = `${Limits.NAMES[metric]} ${Limits.LEVEL_NAMES[level]}`;
|
||||
const picked = dial({value: held[metric][level], label: `${title} in percent`, name: "limit-dial", ...LIMIT_DIAL, unit: "%", spoken: (value) => `${title} ${value} %`, readonly: false});
|
||||
const error = h("p", {class: "limit-error", role: "alert", hidden: true});
|
||||
const leave = back || closeSheet;
|
||||
const save = async () => {
|
||||
const value = picked.value();
|
||||
const why = Limits.problem(Limits.withValue(held, metric, level, value));
|
||||
error.hidden = why === null;
|
||||
error.textContent = why || "";
|
||||
if (why === null && await saveLimits(Limits.withValue(held, metric, level, value), `${title} ${value} %`)) {
|
||||
leave();
|
||||
}
|
||||
};
|
||||
openSheet(title, h("div", {class: "stack limit-sheet", "data-metric": metric, "data-level": level},
|
||||
h("p", {class: "muted"}, `${Limits.ORDER} per metric. A lower value applies at once; a higher one admits more load or raises an alarm threshold, so the passkey signs it.`),
|
||||
picked.root, error,
|
||||
h("div", {class: "sheet-foot"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost limit-cancel", leave), btn("Save", "btn primary limit-save", save))), false);
|
||||
picked.root.focus({preventScroll: true});
|
||||
}
|
||||
|
||||
function openLimits() {
|
||||
const data = limitView.data;
|
||||
const held = limitsHeld();
|
||||
if (!held) {
|
||||
return;
|
||||
}
|
||||
const cell = (metric, level) => {
|
||||
const words = `${Limits.NAMES[metric]} ${Limits.LEVEL_NAMES[level]} ${held[metric][level]} %`;
|
||||
return h("td", {}, h("button", {type: "button", class: "btn small soft limit-cell", "data-metric": metric, "data-level": level, ...named(words, `${words}: open its dial`), on: {click: () => limitDial(metric, level, openLimits)}},
|
||||
`${held[metric][level]} %`));
|
||||
};
|
||||
openSheet("Limits", h("div", {class: "stack limits-sheet"},
|
||||
h("p", {class: "muted"}, data.limits ? `limits.json in the council directory, ${Limits.ORDER} per metric; a click on a value opens its dial.` : "No limits.json yet, so the queue config applies: the table shows Balanced, and the first save needs the passkey."),
|
||||
data.why ? h("p", {class: "limit-error", role: "alert"}, revealed(data.why)) : null,
|
||||
h("div", {class: "table-wrap"}, h("table", {class: "limits-table", "aria-label": "Limits"},
|
||||
h("thead", {}, h("tr", {}, h("th", {scope: "col"}, "Metric"), Limits.LEVELS.map((level) => h("th", {scope: "col"}, Limits.LEVEL_NAMES[level])))),
|
||||
h("tbody", {}, Limits.METRICS.map((metric) => h("tr", {"data-metric": metric}, h("th", {scope: "row"}, Limits.NAMES[metric]), Limits.LEVELS.map((level) => cell(metric, level)))))))), false);
|
||||
}
|
||||
@@ -32,6 +32,7 @@
|
||||
render(false);
|
||||
drawTime();
|
||||
drawAgent();
|
||||
drawQueueJobs();
|
||||
drawStream(true);
|
||||
if (motion.current.size === 0 || ui.asOf !== motion.asOf) {
|
||||
const first = motion.current.size === 0;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
const MATCH_REFRESH = 2000;
|
||||
const MATCH_PEEKS = 2;
|
||||
const LONG_PRESS = 550;
|
||||
const PRESS_SLOP = 10;
|
||||
@@ -12,8 +11,33 @@
|
||||
const COMMENTS_KEPT = 5;
|
||||
const PATTERNS = ["dots", "stripes", "waves", "grid", "rings"];
|
||||
const RELEASE = "release";
|
||||
const MATCH_STAMPS = {running: "RUNNING", queued: "QUEUED", stale: "STALE", expired: "EXPIRED", blocked: "BLOCKED"};
|
||||
const lapsedCard = (card) => card.blocked_kind === "expired";
|
||||
|
||||
/**
|
||||
* @param {object} card an expired card with its expires time in epoch seconds.
|
||||
* @returns {string} the stamp's tooltip: the expiry clock time and how long ago, as "expired 14:02, 12 minutes ago".
|
||||
*/
|
||||
function expiredWords(card) {
|
||||
return `expired ${clock.format(stampOf(card.expires))}, ${ago(card.expires)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} card a card as /api/match serves it.
|
||||
* @returns {string} why it is greyed, a MATCH_STAMPS key: stale first, else its blocked_kind (running or queued), any
|
||||
* other block as blocked; "" for a card that can act.
|
||||
*/
|
||||
function greyStamp(card) {
|
||||
if (card.stale) {
|
||||
return "stale";
|
||||
}
|
||||
if (!card.blocked) {
|
||||
return "";
|
||||
}
|
||||
return Object.hasOwn(MATCH_STAMPS, card.blocked_kind) ? card.blocked_kind : "blocked";
|
||||
}
|
||||
const MOVES = {ArrowRight: "accept", d: "accept", ArrowLeft: "reject", a: "reject", ArrowUp: "later", w: "later", s: "undo"};
|
||||
const matchView = {cards: null, order: [], marks: new Map(), opened: new Map(), decisions: new Map(), toggles: new Map(), history: [], release: null, releasing: false, front: null, drag: null, dom: null, sig: "", fetched: 0, loading: false, press: null, flying: false, openBefore: 0, epoch: 0};
|
||||
const matchView = {cards: null, order: [], marks: new Map(), opened: new Map(), decisions: new Map(), toggles: new Map(), history: [], release: null, releasing: false, front: null, drag: null, dom: null, sig: "", fetched: 0, loading: false, press: null, flying: false, openBefore: 0, epoch: 0, timer: null, turn: 0};
|
||||
|
||||
/**
|
||||
* @returns {Promise<void>} settled when this read ends, at once while another runs; a response requested before
|
||||
@@ -44,15 +68,102 @@
|
||||
return;
|
||||
}
|
||||
drawMatch();
|
||||
matchCycle();
|
||||
}
|
||||
|
||||
const matchRefresh = () => MatchClock.bounded(settings.match.refresh);
|
||||
const matchShown = () => Boolean(matchView.dom && matchView.dom.stack.isConnected);
|
||||
|
||||
/**
|
||||
* @param {HTMLElement} glass a refresh hourglass of matchGlass().
|
||||
* Gives it the current turn, its sand the interval as --match-refresh and its tooltip the interval.
|
||||
*/
|
||||
function glassLook(glass) {
|
||||
const seconds = matchRefresh();
|
||||
glass.dataset.turn = String(matchView.turn);
|
||||
glass.style.setProperty("--match-refresh", `${seconds}s`);
|
||||
glass.title = `Refresh: Match fetches the cards every ${seconds} s; a click fetches now, a right-click sets the interval`;
|
||||
}
|
||||
|
||||
function matchCycle() {
|
||||
window.clearTimeout(matchView.timer);
|
||||
matchView.timer = null;
|
||||
if (!matchShown()) {
|
||||
return;
|
||||
}
|
||||
matchView.turn += 1;
|
||||
document.querySelectorAll(".match-glass").forEach((glass) => {
|
||||
glassLook(glass);
|
||||
glass.replaceChildren(glassFace());
|
||||
});
|
||||
matchView.timer = window.setTimeout(() => {
|
||||
if (matchShown()) {
|
||||
fetchMatch();
|
||||
}
|
||||
}, MatchClock.wait(Date.now(), matchView.fetched, matchRefresh()));
|
||||
}
|
||||
|
||||
function refreshDial() {
|
||||
const picked = dial({value: matchRefresh(), label: "Match refresh in seconds", name: "match-refresh-dial", min: MatchClock.MIN, max: MatchClock.MAX, page: MatchClock.PAGE, unit: "s",
|
||||
spoken: (seconds) => `Match fetches the cards every ${seconds} seconds`, readonly: false});
|
||||
const save = async () => {
|
||||
const refresh = picked.value();
|
||||
if (refresh === settings.match.refresh || await saveSettings({...settings, space: savedSpace(), match: {refresh}})) {
|
||||
closeSheet();
|
||||
fetchMatch();
|
||||
}
|
||||
};
|
||||
openSheet("Match refresh", h("div", {class: "stack match-refresh-sheet"},
|
||||
h("p", {class: "muted"}, `How often Match fetches its cards, ${MatchClock.MIN} to ${MatchClock.MAX} s. Drag the hand, click a tick, or use the arrows (1 s) and Page Up / Down (${MatchClock.PAGE} s).`), picked.root,
|
||||
h("div", {class: "sheet-foot"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), btn("Save", "btn primary match-refresh-save", save))), false);
|
||||
picked.root.focus({preventScroll: true});
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {SVGElement} a fresh hourglass face; a newly inserted face starts its flip and its sand from the top, so
|
||||
* matchCycle() swaps it in after every fetch.
|
||||
*/
|
||||
function glassFace() {
|
||||
return s("svg", {class: "match-glass-face", viewBox: "0 0 24 32", "aria-hidden": "true", focusable: "false"},
|
||||
s("path", {class: "match-glass-frame", d: "M4 2h16M4 30h16M6 3c0 7 5 9 5 13s-5 6-5 13M18 3c0 7-5 9-5 13s5 6 5 13"}),
|
||||
s("path", {class: "match-glass-top", d: "M8 7h8l-4 7z"}),
|
||||
s("path", {class: "match-glass-bottom", d: "M7.5 28h9c-1.5-3.5-3.5-4.5-4.5-4.5s-3 1-4.5 4.5z"}),
|
||||
[0, 1, 2].map((grain) => s("circle", {class: "match-grain", cx: "12", cy: "15", r: "0.8", "data-grain": String(grain)})));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} size "small" for the Match head, "large" for the empty deck.
|
||||
* @returns {HTMLElement} the refresh hourglass: it flips after every fetch and its sand runs for the interval; a click
|
||||
* fetches at once and restarts the cycle, a right-click opens the dial for the interval.
|
||||
*/
|
||||
function matchGlass(size) {
|
||||
const glass = h("button", {type: "button", class: `match-glass ${size}`, "aria-label": "Refresh", on: {click: () => fetchMatch(), contextmenu: (event) => {
|
||||
event.preventDefault();
|
||||
refreshDial();
|
||||
}}}, glassFace());
|
||||
glassLook(glass);
|
||||
return glass;
|
||||
}
|
||||
|
||||
const toFront = (id) => {
|
||||
matchView.order = [id, ...matchView.order.filter((one) => one !== id)];
|
||||
};
|
||||
const toBack = (id) => {
|
||||
matchView.order = [...matchView.order.filter((one) => one !== id), id];
|
||||
const rest = matchView.order.filter((one) => one !== id);
|
||||
const release = id === RELEASE ? -1 : rest.indexOf(RELEASE);
|
||||
matchView.order = release < 0 ? [...rest, id] : [...rest.slice(0, release), id, ...rest.slice(release)];
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {string[]} order card ids and RELEASE.
|
||||
* @param {Set<string>} open the ids of the undecided cards.
|
||||
* @returns {string[]} order with the release card last, unless it is the front card the operator sees now.
|
||||
*/
|
||||
function releaseLast(order, open) {
|
||||
const front = order.find((id) => id === RELEASE || open.has(id));
|
||||
return front === RELEASE || !order.includes(RELEASE) ? order : [...order.filter((id) => id !== RELEASE), RELEASE];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} id the card the step acts on, or RELEASE.
|
||||
* Keeps the order and the card's decision from before the step, so S can put both back.
|
||||
@@ -80,7 +191,8 @@
|
||||
const ids = new Set(cards.map((card) => card.id));
|
||||
const kept = matchView.order.filter((id) => ids.has(id) || id === RELEASE);
|
||||
const fresh = cards.filter((card) => !kept.includes(card.id)).sort((a, b) => Number(Boolean(a.blocked)) - Number(Boolean(b.blocked)) || Number(a.stale) - Number(b.stale) || (a.created_ts || 0) - (b.created_ts || 0));
|
||||
matchView.order = [...kept, ...fresh.map((card) => card.id)];
|
||||
const open = new Set(cards.filter((card) => !decisionOf(card)).map((card) => card.id));
|
||||
matchView.order = releaseLast([...kept, ...fresh.map((card) => card.id)], open);
|
||||
const byId = new Map(cards.map((card) => [card.id, card]));
|
||||
return matchView.order.filter((id) => id !== RELEASE).map((id) => byId.get(id));
|
||||
}
|
||||
@@ -175,11 +287,11 @@
|
||||
if (patched(card)) {
|
||||
const tone = DIFF_TONES[file.status] || "neutral";
|
||||
const stat = file.status === "B" ? icon("bi-file-earmark-binary") : h("span", {class: "stat"}, h("span", {class: "add"}, `+${file.additions}`), h("span", {class: "del"}, `-${file.deletions}`));
|
||||
return h("summary", {class: "diff-head"}, h("span", {class: "letter", "data-tone": tone}, file.status), h("code", {class: "path"}, revealed(file.path)), h("span", {class: "spacer"}),
|
||||
return h("summary", {class: "diff-head"}, h("span", {class: "letter", "data-tone": tone}, file.status), pathCode(card.worktree || card.directory, file.path, revealed(file.path)), h("span", {class: "spacer"}),
|
||||
file.note ? h("span", {class: "note", title: file.note}, icon("bi-eye-slash"), file.note) : null, marks, stat);
|
||||
}
|
||||
const tone = file.state === "read" ? "ok" : "bad";
|
||||
return h("summary", {class: "diff-head"}, h("span", {class: "letter", "data-tone": tone}, icon("bi-file-earmark-text")), h("code", {class: "path"}, revealed(file.path)), h("span", {class: "spacer"}),
|
||||
return h("summary", {class: "diff-head"}, h("span", {class: "letter", "data-tone": tone}, icon("bi-file-earmark-text")), pathCode(card.worktree || card.directory, file.path, revealed(file.path)), h("span", {class: "spacer"}),
|
||||
file.state === "read" ? null : h("span", {class: "note", title: file.reason}, icon("bi-exclamation-triangle"), `refused: ${file.reason}`), marks, h("span", {class: "muted"}, `${file.size} B`));
|
||||
}
|
||||
|
||||
@@ -296,8 +408,21 @@
|
||||
return parts.length > 3 ? `…/${parts.slice(-3).join("/")}` : worktree;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} place branch, repo or worktree.
|
||||
* @param {string} iconName the chip's icon.
|
||||
* @param {string} label what the chip names.
|
||||
* @param {string} value the full branch name or path.
|
||||
* @param {string} words the short text the chip shows.
|
||||
* @returns {HTMLElement} a path chip as a pathLink() when value is absolute, otherwise a button whose click copies value.
|
||||
*/
|
||||
function placeChip(place, iconName, label, value, words) {
|
||||
const full = revealed(value);
|
||||
const link = place === "branch" ? null : pathLink(value, {class: "match-where", "data-place": place, title: `${label}: ${full} (${PATH_ACTIONS})`, "aria-label": `${label}: ${full}, ${PATH_ACTIONS}`},
|
||||
icon(iconName), h("span", {}, revealed(words)));
|
||||
if (link) {
|
||||
return link;
|
||||
}
|
||||
const chip = h("button", {type: "button", class: "match-where", "data-place": place, title: `${label}: ${full} (click copies)`, "aria-label": `${label}: ${full}, click copies`},
|
||||
icon(iconName), h("span", {}, revealed(words)));
|
||||
chip.addEventListener("click", async () => {
|
||||
@@ -347,7 +472,7 @@
|
||||
matchView.toggles.delete(key);
|
||||
decide(card, "accept", "", label);
|
||||
};
|
||||
return choiceDialog({...card, id: card.ref}, {pick, toggled, chosen: kept ? kept.label : "", locked: false, hint: `picked now, sent to ${card.agent || "its agent"} at the release`, group: "match-options", other: OTHER_PROMPT});
|
||||
return choiceDialog({...card, id: card.ref}, {pick, toggled, chosen: kept ? kept.label : "", locked: lapsedCard(card), hint: `picked now, sent to ${card.agent || "its agent"} at the release`, group: "match-options", other: OTHER_PROMPT});
|
||||
}
|
||||
|
||||
function matchPayload(card) {
|
||||
@@ -359,18 +484,27 @@
|
||||
}
|
||||
if (card.kind === "ask") {
|
||||
return h("section", {class: "match-payload"}, h("p", {class: "match-directory"}, revealed(card.directory)),
|
||||
card.warnings.length ? h("p", {class: "match-warnings"}, card.warnings.map((warning) => pill(warning, "bad"))) : null);
|
||||
card.warnings.length ? h("p", {class: "match-warnings"}, card.warnings.map((warning) => pill(warning, "bad"))) : null, card.merge ? matchPreviewLine(card.merge) : null);
|
||||
}
|
||||
if (card.kind !== "command") {
|
||||
return null;
|
||||
}
|
||||
const merge = card.merge;
|
||||
const short = (oid) => oid.slice(0, 12);
|
||||
const preview = merge ? h("p", {class: "match-merge", "data-error": String(Boolean(merge.error))}, icon(merge.error ? "bi-exclamation-triangle" : "bi-sign-merge-left"),
|
||||
merge.error ? `No merge preview: ${merge.error}` : `Brings in ${short(merge.base)} → ${short(merge.target)}, onto HEAD ${short(merge.head)}`) : null;
|
||||
return h("section", {class: "match-payload"},
|
||||
h("p", {class: "match-directory"}, revealed(card.directory)),
|
||||
card.reason && card.reason !== "-" ? h("p", {class: "match-reason"}, revealed(card.reason)) : null, preview);
|
||||
card.reason && card.reason !== "-" ? h("p", {class: "match-reason"}, revealed(card.reason)) : null, card.merge ? matchPreviewLine(card.merge) : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} merge the runner preview of a card: kind merge or commit-tree, head, base, target, and error, the git
|
||||
* error line that kept the diff, "" for none.
|
||||
* @returns {HTMLElement} the line naming what the diff below shows, or its error in place of the diff.
|
||||
*/
|
||||
function matchPreviewLine(merge) {
|
||||
const short = (oid) => oid.slice(0, 12);
|
||||
const tree = merge.kind === "commit-tree";
|
||||
const words = merge.error ? `${tree ? "No commit-tree diff" : "No merge preview"}: ${merge.error}`
|
||||
: tree ? `Commits tree ${short(merge.target)} onto parent ${short(merge.base)}` : `Brings in ${short(merge.base)} → ${short(merge.target)}, onto HEAD ${short(merge.head)}`;
|
||||
return h("p", {class: "match-merge", "data-kind": merge.kind, "data-error": String(Boolean(merge.error))}, icon(merge.error ? "bi-exclamation-triangle" : tree ? "bi-git" : "bi-sign-merge-left"), words);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -387,15 +521,19 @@
|
||||
|
||||
function matchCard(card) {
|
||||
const files = card.files || [];
|
||||
const none = card.kind === "commit" ? (card.diff_error ? `No diff shipped with this stage. ${card.diff_error}` : "No diff shipped with this stage.") : card.kind === "ask" ? "Its tool call changes no file." : card.merge ? (card.merge.error ? "No diff to show." : "The merge brings no change.") : "Its command names no file.";
|
||||
const previewed = card.merge ? (card.merge.error ? "No diff to show." : card.merge.kind === "commit-tree" ? "The commit changes no file." : "The merge brings no change.") : "";
|
||||
const none = card.kind === "commit" ? (card.diff_error ? `No diff shipped with this stage. ${card.diff_error}` : "No diff shipped with this stage.") : previewed || (card.kind === "ask" ? "Its tool call changes no file." : "Its command names no file.");
|
||||
const list = files.length ? h("ol", {class: "match-files", "aria-label": `Files: ${files.length}`}, files.map((file, index) => fileBlock(card, file, index))) : card.kind === "decision" || card.kind === "rule" ? null : h("p", {class: "muted"}, none);
|
||||
const commanded = card.kind === "ask" || card.kind === "command";
|
||||
const command = commanded ? h("pre", {class: "match-command"}, h("code", {}, revealed(card.command))) : null;
|
||||
const code = command || files.length ? codeBox(card.id, "open", [command, list], commanded ? card.command : "", [], null) : list;
|
||||
const body = h("div", {class: "match-body"}, card.blocked ? h("p", {class: "match-blocked"}, icon("bi-hourglass-split"), revealed(card.blocked)) : null, matchPayload(card), code);
|
||||
body.addEventListener("scroll", () => openOnScroll(body, ".match-file"), {passive: true});
|
||||
const stamp = greyStamp(card);
|
||||
const article = h("article", {class: "card match-card front", "data-card": card.id, "data-kind": card.kind, "data-stale": String(Boolean(card.stale)), ...(card.blocked ? {"data-blocked": "", title: card.blocked} : {}), "aria-label": `${card.kind} card of ${card.agent || "an agent"}`},
|
||||
matchHead(card), body);
|
||||
matchHead(card), body, stamp ? h("span", {class: "match-stamp", "data-stamp": stamp, ...(stamp === "expired" ? {title: expiredWords(card), on: {mouseenter: (event) => {
|
||||
event.currentTarget.title = expiredWords(card);
|
||||
}}} : {"aria-hidden": "true"})}, MATCH_STAMPS[stamp]) : null);
|
||||
article.style.setProperty("--agent-hue", String(Faces.hash(card.agent) % 360));
|
||||
paint(article, card.id);
|
||||
markable(article, ".match-file tr[data-line]", (row) => commentField(article, card, row));
|
||||
@@ -477,10 +615,11 @@
|
||||
* @returns {boolean} whether the card can not act here; the toast then names its reason under the verdict.
|
||||
*/
|
||||
function refusedHere(card, verdict) {
|
||||
if (card.blocked) {
|
||||
const refused = Boolean(card.blocked) && !(verdict === "Reject" && lapsedCard(card));
|
||||
if (refused) {
|
||||
toast(`${verdict}: not possible now`, [card.blocked], false);
|
||||
}
|
||||
return Boolean(card.blocked);
|
||||
return refused;
|
||||
}
|
||||
|
||||
function acceptCard(card) {
|
||||
@@ -511,7 +650,7 @@
|
||||
if (refusedHere(card, "Reject")) {
|
||||
return;
|
||||
}
|
||||
if (pickOnly(card)) {
|
||||
if (pickOnly(card) && !lapsedCard(card)) {
|
||||
toast("Reject: not possible", ["A choice is answered with one of its options."], false);
|
||||
return;
|
||||
}
|
||||
@@ -519,7 +658,7 @@
|
||||
const words = h("textarea", {class: "field match-feedback", rows: 6, maxlength: FEEDBACK_LIMIT, "aria-label": "Feedback", "data-skills": card.repo || ""});
|
||||
words.value = (kept && kept.verdict === "reject" ? kept.feedback : feedbackOf(card)).slice(0, FEEDBACK_LIMIT);
|
||||
const confirm = h("button", {type: "button", class: "btn danger match-feedback-reject"}, icon("bi-x-lg"), "Reject");
|
||||
const pair = card.kind === "decision" ? Answers.pair(card) : null;
|
||||
const pair = card.kind === "decision" && !lapsedCard(card) ? Answers.pair(card) : null;
|
||||
confirm.addEventListener("click", () => {
|
||||
closeSheet();
|
||||
decide(card, "reject", words.value.trim(), pair ? Answers.declined(pair.no, words.value, OTHER_LIMIT) : "");
|
||||
@@ -560,7 +699,7 @@
|
||||
return Boolean(run);
|
||||
}
|
||||
const card = matchView.front;
|
||||
if (card) {
|
||||
if (card && !(move === "accept" && lapsedCard(card))) {
|
||||
({accept: acceptCard, reject: rejectCard, later: laterCard})[move](card);
|
||||
}
|
||||
return Boolean(card);
|
||||
@@ -579,7 +718,8 @@
|
||||
const [dx, dy] = [event.clientX - drag.x, event.clientY - drag.y];
|
||||
const up = -dy > Math.abs(dx);
|
||||
article.style.transform = `translate(${dx}px, ${Math.min(0, dy)}px) rotate(${dx / 40}deg)`;
|
||||
article.dataset.leaning = up ? "later" : dx > 0 ? "accept" : dx < 0 ? "reject" : "";
|
||||
const lean = up ? "later" : dx > 0 ? "accept" : dx < 0 ? "reject" : "";
|
||||
article.dataset.leaning = acts[lean] ? lean : "";
|
||||
article.style.setProperty("--lean", String(Math.min(1, up ? -dy / SWIPE_UP : Math.abs(dx) / (SWIPE_SHARE * article.getBoundingClientRect().width))));
|
||||
}
|
||||
};
|
||||
@@ -629,7 +769,7 @@
|
||||
function matchEntry(card, decision) {
|
||||
const kind = card.entry || (card.kind === "commit" ? "review" : "operator");
|
||||
const entry = {kind, id: card.ref, verb: decision.verdict === "accept" ? "approve" : "reject", label: decision.verdict === "accept" ? decision.label || "" : "", sha256: kind === "operator" ? card.sha256 || "" : ""};
|
||||
if (card.kind === "decision" && Answers.pair(card)) {
|
||||
if (card.kind === "decision" && Answers.pair(card) && !lapsedCard(card)) {
|
||||
return {...entry, verb: "approve", label: decision.label};
|
||||
}
|
||||
if (decision.verdict === "reject") {
|
||||
@@ -657,7 +797,7 @@
|
||||
* @param {Array<Array>} picked [card, decision] pairs from decided().
|
||||
* @returns {object} lone: risk-accepted red-gate commits, each signed on its own first; rest: every other decision
|
||||
* signed together; gone: withdrawn rejects, sent by radio only; held: red-gate commits whose risk is not accepted,
|
||||
* left out of the release and back to the stack once it ran.
|
||||
* which block the release until each is risk-accepted or sent back to the stack.
|
||||
*/
|
||||
function releasePlan(picked) {
|
||||
const signed = picked.filter(([card]) => !card.withdrawn);
|
||||
@@ -671,7 +811,7 @@
|
||||
|
||||
async function releaseMatch(cards) {
|
||||
const plan = releasePlan(decided(cards));
|
||||
if (matchView.releasing || !(plan.lone.length + plan.rest.length + plan.gone.length)) {
|
||||
if (matchView.releasing || plan.held.length || !(plan.lone.length + plan.rest.length + plan.gone.length)) {
|
||||
return;
|
||||
}
|
||||
matchView.releasing = true;
|
||||
@@ -687,7 +827,6 @@
|
||||
return;
|
||||
}
|
||||
done.push(...plan.rest, ...plan.gone);
|
||||
plan.held.forEach(([card]) => matchView.decisions.delete(card.id));
|
||||
} finally {
|
||||
matchView.releasing = false;
|
||||
if (done.length) {
|
||||
@@ -741,11 +880,12 @@
|
||||
toFront(card.id);
|
||||
drawMatch(true);
|
||||
});
|
||||
const held = risky(card, decision) && !decision.risk;
|
||||
const note = card.withdrawn ? "Card withdrawn: the feedback goes to its agent by radio call at the release." : decision.verdict === "reject" && decision.hash !== card.hash ? "Card changed since your reject." : held ? "Left out of the release until you accept its risk: it goes back to the stack." : "";
|
||||
const risk = risky(card, decision);
|
||||
const held = risk && !decision.risk;
|
||||
const note = card.withdrawn ? "Card withdrawn: the feedback goes to its agent by radio call at the release." : decision.verdict === "reject" && decision.hash !== card.hash ? "Card changed since your reject." : held ? "Accept its risk or send it back to the stack: the release waits until you do." : "";
|
||||
return h("li", {class: "match-decision", "data-card": card.id, "data-verdict": decision.verdict, "data-withdrawn": String(Boolean(card.withdrawn)), "data-held": String(held)},
|
||||
h("div", {class: "row"}, agentFace(card.agent || "-", false), h("span", {class: "pill", "data-tone": kindTone}, icon(kindIcon), kindName), h("strong", {class: "match-decision-title"}, revealed(card.title)), h("span", {class: "spacer"}),
|
||||
h("span", {class: "pill match-verdict", "data-tone": tone}, icon(mark), decision.label ? revealed(`${word}: ${shownPick(decision.label)}`) : word), risky(card, decision) ? riskButton(decision) : null, decision.verdict === "reject" ? iconBtn("bi-pencil", "Edit feedback", "btn small ghost match-edit", () => rejectCard(card)) : null, flip, back),
|
||||
risk ? riskButton(decision) : h("span", {class: "pill match-verdict", "data-tone": tone}, icon(mark), decision.label ? revealed(`${word}: ${shownPick(decision.label)}`) : word), decision.verdict === "reject" ? iconBtn("bi-pencil", "Edit feedback", "btn small ghost match-edit", () => rejectCard(card)) : null, flip, back),
|
||||
note ? h("p", {class: "muted match-decision-note"}, icon("bi-info-circle"), note) : null,
|
||||
decision.verdict === "reject" ? h("pre", {class: "match-decision-feedback"}, revealedLines(decision.feedback === "" ? "no feedback text" : decision.feedback)) : null);
|
||||
}
|
||||
@@ -759,7 +899,8 @@
|
||||
function releaseCard(cards, open) {
|
||||
const picked = decided(cards);
|
||||
const plan = releasePlan(picked);
|
||||
const count = plan.lone.length + plan.rest.length + plan.gone.length;
|
||||
const held = plan.held.length;
|
||||
const count = held ? 0 : plan.lone.length + plan.rest.length + plan.gone.length;
|
||||
const signatures = plan.lone.length ? `${plan.lone.length === 1 ? "The risk-accepted commit gets its own" : `Each of the ${plan.lone.length} risk-accepted commits gets its own`} passkey signature first, then one signature releases the rest` : "One passkey signature releases every decision";
|
||||
const run = () => releaseMatch(cards);
|
||||
const back = open ? () => {
|
||||
@@ -767,12 +908,11 @@
|
||||
toBack(RELEASE);
|
||||
drawMatch(true);
|
||||
} : null;
|
||||
const release = h("button", {type: "button", class: "btn primary match-release", disabled: !count, title: count ? `${signatures}; after each signature ${undoWords()}.` : "Nothing to release yet."},
|
||||
icon("bi-key"), `Release ${decisionWords(count)}`);
|
||||
release.addEventListener("click", run);
|
||||
const release = held ? h("p", {class: "muted match-release-held"}, icon("bi-shield-exclamation"), `${held === 1 ? "One red-gate commit waits" : `${held} red-gate commits wait`} for your risk accept or its way back to the stack.`)
|
||||
: h("button", {type: "button", class: "btn primary match-release", disabled: !count, title: count ? `${signatures}; after each signature ${undoWords()}.` : "Nothing to release yet.", on: {click: run}}, icon("bi-key"), `Release ${decisionWords(count)}`);
|
||||
const article = h("article", {class: "card match-card front match-release-card match-overview", "data-card": "release", "aria-label": "Release card: the decisions"},
|
||||
h("header", {class: "match-head"}, widenToggle(), h("h2", {class: "match-title"}, icon("bi-key"), "Release"),
|
||||
h("p", {class: "muted match-release-hint"}, open ? "D, → or a right swipe releases; A, W, ← or a left swipe goes on to the next card; S undoes the last step." : "D, → or a right swipe releases; S undoes the last step.")),
|
||||
h("p", {class: "muted match-release-hint"}, [count ? "D, → or a right swipe releases" : "", open ? "A, W, ← or a left swipe goes on to the next card" : "", "S undoes the last step."].filter(Boolean).join("; "))),
|
||||
h("div", {class: "match-body"},
|
||||
h("p", {class: "muted"}, "Nothing has run yet. Accepted commits get the operator's signature for their exact tree, accepted commands run once as jobs under Waits on Operator, accepted asks are granted, every picked option and every rejection goes to its agent by radio call."),
|
||||
picked.length ? h("ol", {class: "match-decisions"}, picked.map(([card, decision]) => overviewRow(card, decision))) : h("p", {class: "muted"}, "No decision yet."),
|
||||
@@ -807,12 +947,13 @@
|
||||
keep(STORE.peeks, !peeksShown());
|
||||
drawMatch(true);
|
||||
}}}, icon("bi-collection"));
|
||||
matchView.dom = {stack, count, decisions, tally, peeks};
|
||||
const glass = matchGlass("small");
|
||||
matchView.dom = {stack, count, decisions, tally, peeks, glass};
|
||||
matchView.sig = "";
|
||||
if (matchView.drag) {
|
||||
matchView.drag.end();
|
||||
}
|
||||
const bar = boxHead("Match", "task-toolbar", h("strong", {class: "box-title"}, icon("bi-stack"), "Match"), count, h("span", {class: "spacer"}), decisions, peeks,
|
||||
const bar = boxHead("Match", "task-toolbar", h("strong", {class: "box-title"}, icon("bi-stack"), "Match"), glass, count, h("span", {class: "spacer"}), decisions, peeks,
|
||||
iconBtn("bi-list-check", "Tasks", "btn small soft", () => go("tasks", null), "Tasks: back to the task list"));
|
||||
fetchMatch();
|
||||
return h("div", {class: "graph tasks match", "data-panel": "tasks/match"}, bar, stack);
|
||||
@@ -830,7 +971,7 @@
|
||||
const host = h("div", {class: "match-home"}, matchScreen());
|
||||
host.querySelectorAll("[data-panel]").forEach((node) => node.removeAttribute("data-panel"));
|
||||
host.querySelector(".task-toolbar").remove();
|
||||
homeView.heads.set("tasks/match", h("div", {role: "toolbar", "aria-label": "Match"}, matchView.dom.count, matchView.dom.decisions, matchView.dom.peeks));
|
||||
homeView.heads.set("tasks/match", h("div", {role: "toolbar", "aria-label": "Match"}, matchView.dom.glass, matchView.dom.count, matchView.dom.decisions, matchView.dom.peeks));
|
||||
homeView.hosts.set("tasks/match", host);
|
||||
window.setTimeout(() => drawMatch(true), 0);
|
||||
return host;
|
||||
@@ -841,7 +982,7 @@
|
||||
if (!dom || !dom.stack.isConnected) {
|
||||
return;
|
||||
}
|
||||
if (!matchView.loading && Date.now() - matchView.fetched > MATCH_REFRESH) {
|
||||
if (!matchView.loading && MatchClock.due(Date.now(), matchView.fetched, matchRefresh())) {
|
||||
fetchMatch();
|
||||
}
|
||||
if (matchView.cards === null) {
|
||||
@@ -874,7 +1015,7 @@
|
||||
const byOpen = new Map(open.map((card) => [card.id, card]));
|
||||
const rotation = matchView.order.filter((id) => id === RELEASE || byOpen.has(id));
|
||||
const releasing = rotation[0] === RELEASE;
|
||||
const sig = JSON.stringify([cards.map((card) => [card.id, card.hash, card.live_hash, card.stale, card.born, card.gate, card.files ? card.files.length : null]), [...matchView.decisions].map(([id, decision]) => [id, decision.verdict, decision.feedback, decision.label, decision.hash, decision.risk]), rotation, Math.floor(state.now / DAY)]);
|
||||
const sig = JSON.stringify([cards.map((card) => [card.id, card.hash, card.live_hash, card.stale, card.born, card.gate, card.files ? card.files.length : null, card.merge ? [card.merge.kind, card.merge.target, card.merge.error] : null]), [...matchView.decisions].map(([id, decision]) => [id, decision.verdict, decision.feedback, decision.label, decision.hash, decision.risk]), rotation, Math.floor(state.now / DAY)]);
|
||||
if (!force && sig === matchView.sig && !cleared) {
|
||||
return;
|
||||
}
|
||||
@@ -886,7 +1027,9 @@
|
||||
matchView.release = null;
|
||||
if (!rotation.length) {
|
||||
matchView.front = null;
|
||||
dom.stack.replaceChildren(emptyState("No card waits", "Nothing waits on the operator."));
|
||||
const empty = emptyState("No card waits", "Nothing waits on the operator.");
|
||||
empty.querySelector(".empty-mark").replaceWith(matchGlass("large"));
|
||||
dom.stack.replaceChildren(empty);
|
||||
return;
|
||||
}
|
||||
const behind = rotation.slice(1).filter((id) => id !== RELEASE).map((id) => byOpen.get(id));
|
||||
@@ -914,14 +1057,15 @@
|
||||
const hint = front.blocked ? `Accept: not possible now. ${front.blocked}` : front.stale ? `Accept: refused while the card is stale (${front.stale_reason})` : front.kind === "rule" ? "Accept: opens its row, where the passkey signs exactly this rule" : front.kind === "decision" ? (needsPick(front) ? "Accept: pick one of its options" : `Accept: ${shownPick(acceptLabel(front))} (D, right arrow, swipe right)`) : "Accept (D, right arrow, swipe right)";
|
||||
const accept = act("match-accept", "bi-check-lg", "Accept", revealed(hint), Boolean(front.blocked || front.stale) || needsPick(front), () => acceptCard(front));
|
||||
const declining = front.kind === "decision" && Answers.pair(front) ? `Reject: ${shownPick(Answers.pair(front).no)}, with an optional comment on what to do instead (A, left arrow, swipe left)` : "Reject with feedback (A, left arrow, swipe left)";
|
||||
const rejectHint = front.blocked ? `Reject: not possible now. ${front.blocked}` : pickOnly(front) ? "Reject: a choice is answered with one of its options" : declining;
|
||||
const reject = act("match-reject", "bi-x-lg", "Reject", revealed(rejectHint), Boolean(front.blocked) || pickOnly(front), () => rejectCard(front));
|
||||
const lapsed = lapsedCard(front);
|
||||
const rejectHint = lapsed ? "Reject: it expired before you decided, its agent gets your feedback by radio (A, left arrow, swipe left)" : front.blocked ? `Reject: not possible now. ${front.blocked}` : pickOnly(front) ? "Reject: a choice is answered with one of its options" : declining;
|
||||
const reject = act("match-reject", "bi-x-lg", "Reject", revealed(rejectHint), !lapsed && (Boolean(front.blocked) || pickOnly(front)), () => rejectCard(front));
|
||||
const later = act("match-later", "bi-arrow-up", "Later", "Later: on to the next card, this one to the back (W, up arrow, swipe up); S undoes the last step", rotation.length < 2, () => laterCard(front));
|
||||
const peeks = peekRow(rest);
|
||||
const scrolled = before && before.dataset.card === front.id ? before.querySelector(".match-body").scrollTop : 0;
|
||||
const shown = matchCard(front);
|
||||
shown.dataset.fresh = String(!before || before.dataset.card !== front.id);
|
||||
draggable(shown, {accept: () => acceptCard(front), reject: () => rejectCard(front), later: () => laterCard(front)}, (swiped) => (swiped === "accept" && flies(front)) || swiped === "later");
|
||||
draggable(shown, {accept: lapsed ? null : () => acceptCard(front), reject: () => rejectCard(front), later: () => laterCard(front)}, (swiped) => (swiped === "accept" && flies(front)) || swiped === "later");
|
||||
keepTyping(dom.stack, () => dom.stack.replaceChildren(h("div", {class: "match-deck"}, layersOf(rest), shown), h("div", {class: "match-actions"}, reject, later, accept), ...(peeks ? [peeks] : [])));
|
||||
shown.querySelector(".match-body").scrollTop = scrolled;
|
||||
}
|
||||
@@ -19,11 +19,25 @@
|
||||
button.title = reason || MIC_HINT;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {HTMLButtonElement} button a recording control: a field's mic or the composer's Record.
|
||||
* @param {string} look idle, recording or busy; busy is the spinning hourglass every recording control shows while its sound becomes text.
|
||||
* @param {string} idle the icon at rest.
|
||||
* @param {Node[]} label what follows the icon; [] for an icon-only control.
|
||||
*/
|
||||
function recLook(button, look, idle, label) {
|
||||
button.dataset.rec = look;
|
||||
button.setAttribute("aria-pressed", String(look === "recording"));
|
||||
button.setAttribute("aria-busy", String(look === "busy"));
|
||||
button.replaceChildren(icon(look === "recording" ? "bi-stop-fill" : look === "busy" ? "bi-hourglass-split" : idle), ...label);
|
||||
}
|
||||
|
||||
const micKey = (field) => field.getAttribute("aria-label") || "";
|
||||
|
||||
function micLook(button, look) {
|
||||
const recording = look === "recording";
|
||||
button.setAttribute("aria-pressed", String(recording));
|
||||
button.setAttribute("aria-label", recording ? "Stop voice input" : "Voice input");
|
||||
button.replaceChildren(icon(recording ? "bi-stop-fill" : look === "busy" ? "bi-hourglass-split" : "bi-mic"));
|
||||
recLook(button, look, "bi-mic", []);
|
||||
button.setAttribute("aria-label", recording ? "Stop voice input" : look === "busy" ? "Voice input: transcribing" : "Voice input");
|
||||
micLive().hidden = !recording;
|
||||
if (look === "busy") {
|
||||
button.disabled = true;
|
||||
@@ -49,7 +63,12 @@
|
||||
micButtons.set(field, button);
|
||||
micFields.set(button, field);
|
||||
field.dataset.mic = "on";
|
||||
micLook(button, "idle");
|
||||
// Trip-wire: polled views (choice dialogs, cards) rebuild a field while it records; its rebuilt twin under the same aria-label takes over the recording, or the new mic stays dead and the text lands in a detached field.
|
||||
const twin = mic.field && mic.field !== field && !mic.field.isConnected && micKey(field) && micKey(mic.field) === micKey(field);
|
||||
if (twin) {
|
||||
Object.assign(mic, {field, button});
|
||||
}
|
||||
micLook(button, twin ? (mic.busy ? "busy" : "recording") : "idle");
|
||||
button.addEventListener("click", () => toggleMic(field, button));
|
||||
return button;
|
||||
}
|
||||
@@ -60,13 +79,15 @@
|
||||
* @param {HTMLInputElement|HTMLTextAreaElement} field the text field; it moves into the frame.
|
||||
* @param {Node[]} extras for a textarea what belongs to it besides its mic, on the footer's left (Record, a count); for a
|
||||
* one-line field the segments after the mic (its form's submit button); [] for none.
|
||||
* @returns {HTMLElement} one frame around field and mic: for a one-line field the mic and then the extras as its last
|
||||
* segments, for a textarea a footer row below it whose last child is the mic.
|
||||
* @returns {HTMLElement} one frame around field and mic, which takes pasted and dropped files: for a one-line field the
|
||||
* mic and then the extras as its last segments, for a textarea its chip row of attachments and a footer row below it
|
||||
* whose last child is the mic, the 📎 picker right before it.
|
||||
*/
|
||||
function micFrame(field, extras) {
|
||||
const button = micButton(field);
|
||||
attachWire(field);
|
||||
if (field.tagName === "TEXTAREA") {
|
||||
return h("div", {class: "mic-frame mic-area"}, field, h("div", {class: "mic-foot"}, extras, h("span", {class: "spacer"}), button));
|
||||
return h("div", {class: "mic-frame mic-area"}, field, attachRow(field), h("div", {class: "mic-foot"}, extras, h("span", {class: "spacer"}), attachPicker(field), button));
|
||||
}
|
||||
return h("span", {class: "mic-frame mic-line"}, field, button, extras);
|
||||
}
|
||||
@@ -144,6 +165,10 @@
|
||||
|
||||
async function toggleMic(field, button) {
|
||||
if (mic.button) {
|
||||
if (!mic.button.isConnected) {
|
||||
Object.assign(mic, {field, button});
|
||||
micLook(button, mic.busy ? "busy" : "recording");
|
||||
}
|
||||
if (mic.button === button && mic.recorder) {
|
||||
stopMic(false);
|
||||
}
|
||||
@@ -173,14 +198,13 @@
|
||||
recorder.addEventListener("stop", () => {
|
||||
media.getTracks().forEach((track) => track.stop());
|
||||
window.clearInterval(mic.timer);
|
||||
const cancelled = mic.cancel;
|
||||
micLook(button, "idle");
|
||||
if (cancelled) {
|
||||
mic.recorder = null;
|
||||
if (mic.cancel) {
|
||||
micLook(mic.button, "idle");
|
||||
micDone();
|
||||
return;
|
||||
}
|
||||
mic.recorder = null;
|
||||
micTranscribe(new Blob(chunks, {type: recorder.mimeType}), field, button);
|
||||
micTranscribe(new Blob(chunks, {type: recorder.mimeType}));
|
||||
}, {once: true});
|
||||
Object.assign(mic, {recorder, started: Date.now()});
|
||||
recorder.start();
|
||||
@@ -198,23 +222,28 @@
|
||||
field.dispatchEvent(new Event("input", {bubbles: true}));
|
||||
}
|
||||
|
||||
async function micTranscribe(blob, field, button) {
|
||||
/**
|
||||
* @param {Blob} blob the recorded sound; its text lands in mic.field, which a rebuilt twin may have replaced meanwhile.
|
||||
*/
|
||||
async function micTranscribe(blob) {
|
||||
const sound = context();
|
||||
if (!sound || !blob.size) {
|
||||
micLook(mic.button, "idle");
|
||||
micDone();
|
||||
return;
|
||||
}
|
||||
mic.busy = true;
|
||||
micLook(button, "busy");
|
||||
micLook(mic.button, "busy");
|
||||
try {
|
||||
const result = await send("/api/stt", await wavOf(blob, sound, state.speech.input), "audio/wav");
|
||||
if (!result.ok || !result.data) {
|
||||
throw new Error(`${result.status} ${result.text}`.trim());
|
||||
}
|
||||
micInsert(field, result.data.text || "");
|
||||
micInsert(mic.field, result.data.text || "");
|
||||
} catch (error) {
|
||||
toast("Voice input failed", [String(error.message || error)], false);
|
||||
} finally {
|
||||
const button = mic.button;
|
||||
micDone();
|
||||
micLook(button, "idle");
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
...ACTIONS.map(([id, label]) => ({label, hint: id === "clear-mayday" ? "Mayday" : "Day/Night", scope: "general", run: () => confirmAct(id, [])})),
|
||||
{label: "Priority …", hint: "agent order in the hierarchy", scope: "agents", run: openAgentOrder},
|
||||
{label: "Controls …", hint: "tools, rules, groups and schedules", scope: "stream", run: () => go("rules", null)},
|
||||
{label: "Schedules …", hint: "switch off or retime the reminders, timers and hooks", scope: "stream", run: () => go("rules", "schedules")},
|
||||
{label: "Schedules …", hint: "switch off or retime every timer, reminder and Claude task", scope: "stream", run: () => go("rules", "schedules")},
|
||||
{label: "Settings …", hint: "Ambience, location, colors, music, notifications, internet radio", scope: "general", run: settingsSheet},
|
||||
{label: settings.music.on ? "Music off" : "Music on", hint: "Ambience", scope: "general", run: toggleMusic},
|
||||
{label: space.look ? "Leave the sky" : "Look at the sky", hint: "h", scope: "general", run: () => skyLook(!space.look)},
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
const PRUNE_TICK = 1000;
|
||||
const pruneView = {days: Prune.STALE_DAYS, ticked: new Set(), dial: null, body: null, timer: null};
|
||||
|
||||
const pruneNow = () => Date.now() / 1000;
|
||||
const pruneClock = (epoch) => new Date(epoch * 1000).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit"});
|
||||
const pruneStale = () => Prune.stale(state.tasks, markSources(), pruneView.days);
|
||||
|
||||
function pruneTick() {
|
||||
const pending = Prune.pending(state.jobs || [], pruneNow());
|
||||
const chip = document.getElementById("kanban-prune");
|
||||
if (chip && pending) {
|
||||
chip.querySelector(".prune-left").textContent = Prune.clock(pending.left);
|
||||
}
|
||||
const body = pruneView.body;
|
||||
if (body && body.isConnected && pending && pruneView.dial && pruneView.dial.root.getAttribute("aria-readonly") === "true") {
|
||||
pruneView.dial.set(Math.ceil(pending.left / Prune.MINUTE));
|
||||
body.querySelector(".prune-left").textContent = Prune.clock(pending.left);
|
||||
}
|
||||
if (!pending && !(body && body.isConnected)) {
|
||||
window.clearInterval(pruneView.timer);
|
||||
pruneView.timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function pruneTicking() {
|
||||
if (pruneView.timer === null) {
|
||||
pruneView.timer = window.setInterval(pruneTick, PRUNE_TICK);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} stale how many cards Plan.stale counts on the board.
|
||||
* @returns {HTMLElement[]} the Prune button, which opens the prune dialog, and while a signed prune waits for its
|
||||
* deadline the countdown chip naming its tasks and deadline.
|
||||
*/
|
||||
function pruneControls(stale) {
|
||||
const pending = Prune.pending(state.jobs || [], pruneNow());
|
||||
const open = h("button", {type: "button", class: "btn small", id: "kanban-prune-open", disabled: !stale && !pending, ...named("Prune", "Prune stale tasks: one passkey signs the list and a deadline; the agents can keep a task until then")}, icon("bi-scissors"), "Prune");
|
||||
open.addEventListener("click", openPrune);
|
||||
if (!pending) {
|
||||
return [open];
|
||||
}
|
||||
pruneTicking();
|
||||
const words = `Prune at ${pruneClock(pending.deadline)}: ${pending.tasks.join(", ")}`;
|
||||
const chip = h("span", {class: "pill prune-chip", id: "kanban-prune", "data-tone": "warn", "data-deadline": String(pending.deadline), role: "timer", ...named(`Prune in ${Prune.clock(pending.left)}`, words)},
|
||||
icon("bi-hourglass-split"), h("span", {class: "prune-left"}, Prune.clock(pending.left)));
|
||||
return [open, chip];
|
||||
}
|
||||
|
||||
function pruneRows(list, count) {
|
||||
const rows = pruneStale();
|
||||
pruneView.ticked = new Set([...pruneView.ticked].filter((task) => rows.some((row) => row.task === task)));
|
||||
count.textContent = String(pruneView.ticked.size);
|
||||
list.replaceChildren(...(rows.length ? rows.map((row) => h("li", {"data-task": row.task}, h("label", {class: "check"},
|
||||
h("input", {type: "checkbox", checked: pruneView.ticked.has(row.task), "aria-label": `Prune ${row.task}`, on: {change: (event) => {
|
||||
if (event.target.checked) {
|
||||
pruneView.ticked.add(row.task);
|
||||
} else {
|
||||
pruneView.ticked.delete(row.task);
|
||||
}
|
||||
count.textContent = String(pruneView.ticked.size);
|
||||
count.closest("button").disabled = !pruneView.ticked.size;
|
||||
}}}), h("code", {class: "task-id"}, row.task), h("span", {class: "muted"}, `${Math.floor((state.now - row.updated) / 86400)} d`))))
|
||||
: [h("li", {class: "muted"}, `No task without a register change for ${pruneView.days} days.`)]));
|
||||
count.closest("button").disabled = !pruneView.ticked.size;
|
||||
}
|
||||
|
||||
function retick(list, count) {
|
||||
pruneView.ticked = new Set(pruneStale().map((row) => row.task));
|
||||
pruneRows(list, count);
|
||||
}
|
||||
|
||||
async function signPrune(body) {
|
||||
const tasks = pruneStale().map((row) => row.task).filter((task) => pruneView.ticked.has(task));
|
||||
const since = Math.floor(pruneNow());
|
||||
const items = Prune.items(tasks, pruneView.days, since, pruneView.dial.value());
|
||||
const label = `Prune ${tasks.length} stale tasks`;
|
||||
const signed = await proofFor(items, label);
|
||||
if (signed === null) {
|
||||
return;
|
||||
}
|
||||
const result = await sendJson("/api/prune", {items, proof: signed.proof});
|
||||
toast(result.ok ? label : `${label}: not queued`, result.ok ? [`Sécurité now, stopped at ${pruneClock(since + pruneView.dial.value() * Prune.MINUTE)} unless kept`] : fail(result), result.ok);
|
||||
if (result.ok) {
|
||||
await load();
|
||||
taskView.sig = "";
|
||||
drawTasks();
|
||||
drawPrune(body);
|
||||
}
|
||||
}
|
||||
|
||||
function pruneCountdown(body, pending) {
|
||||
pruneView.dial = dial({value: Math.ceil(pending.left / Prune.MINUTE), label: "Minutes until the prune", name: "prune-dial", min: 0, max: Prune.MINUTES.max, page: Prune.MINUTES.page,
|
||||
unit: "min", spoken: (minutes) => `${minutes} minutes until the prune`, readonly: true});
|
||||
pruneTicking();
|
||||
body.replaceChildren(h("p", {}, `Signed: the hub runner stops these tasks at ${pruneClock(pending.deadline)} unless an agent keeps one (rasci.py keep <task>) or changes it first.`),
|
||||
h("div", {class: "prune-wait"}, pruneView.dial.root, h("strong", {class: "prune-left", role: "timer"}, Prune.clock(pending.left))),
|
||||
h("ul", {class: "prune-list", "aria-label": "Signed tasks"}, pending.tasks.map((task) => h("li", {"data-task": task}, h("code", {class: "task-id"}, task)))));
|
||||
}
|
||||
|
||||
function drawPrune(body) {
|
||||
pruneView.body = body;
|
||||
const pending = Prune.pending(state.jobs || [], pruneNow());
|
||||
if (pending) {
|
||||
pruneCountdown(body, pending);
|
||||
return;
|
||||
}
|
||||
const range = Prune.MINUTES;
|
||||
pruneView.dial = dial({value: range.value, label: "Answer window in minutes", name: "prune-dial", min: range.min, max: range.max, page: range.page, unit: "min",
|
||||
spoken: (minutes) => `${minutes} minutes for the agents to keep a task`, readonly: false});
|
||||
const count = h("span", {class: "count"}, "0");
|
||||
const go = h("button", {type: "button", class: "btn primary", id: "prune-sign", ...named("Prune", "Prune: one passkey signs the ticked tasks and the deadline; the hub sends a Sécurité to all at once")}, icon("bi-scissors"), "Prune", count);
|
||||
go.addEventListener("click", () => signPrune(body));
|
||||
const list = h("ul", {class: "prune-list", "aria-label": "Stale tasks"});
|
||||
const field = h("input", {class: "field", type: "text", inputmode: "numeric", id: "prune-days", value: String(pruneView.days), "aria-label": "Days without a register change", on: {change: (event) => {
|
||||
const days = Prune.daysOf(event.target.value);
|
||||
event.target.setAttribute("aria-invalid", String(days === null));
|
||||
if (days !== null) {
|
||||
pruneView.days = days;
|
||||
retick(list, count);
|
||||
}
|
||||
}}});
|
||||
body.replaceChildren(h("label", {class: "prune-days"}, h("span", {class: "muted"}, "Stale after days"), field), list,
|
||||
h("div", {class: "prune-wait"}, pruneView.dial.root, h("p", {class: "muted"}, "Answer window: the agents keep a task until then; every other ticked task is set stopped.")),
|
||||
h("div", {class: "actions"}, go));
|
||||
retick(list, count);
|
||||
}
|
||||
|
||||
function openPrune() {
|
||||
pruneView.days = Prune.STALE_DAYS;
|
||||
const body = h("div", {class: "stack prune-dialog"});
|
||||
openSheet("Prune stale tasks", body, false);
|
||||
drawPrune(body);
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
const QUEUE_SETTINGS = [["budget_percent.ram", "Budget RAM %"], ["budget_percent.cpu", "Budget CPU %"], ["load_limits.cpu_percent", "Live guard CPU %"], ["load_limits.mem_percent", "Live guard RAM %"], ["load_limits.band_low", "Band low %"], ["load_limits.band_high", "Band high %"], ["load_limits.sample_seconds", "Load sample s"]];
|
||||
const QUEUE_KIND_SETTINGS = [["slot_limits", "Slot cap"], ["ram_cap_percent", "RAM cap %"]];
|
||||
const QUEUE_NUMBER = /^(0|[1-9][0-9]{0,5})(\.[0-9]{1,3})?$/;
|
||||
const QUEUE_REFRESH = 20000;
|
||||
const queueTab = {data: null, busy: false, staged: {}, dom: null, at: 0};
|
||||
|
||||
const queueNumber = (value) => (value === null || value === undefined ? "–" : Number(value).toFixed(1).replace(/\.0$/, ""));
|
||||
|
||||
/**
|
||||
* @param {string} key a setting as `<section>.<name>`.
|
||||
* @returns {number|null} its value in the learnings queue.py printed last, null when the config holds none.
|
||||
*/
|
||||
function queueSetting(key) {
|
||||
const [section, name] = key.split(".");
|
||||
const values = queueTab.data ? queueTab.data[section] : null;
|
||||
return values && Object.hasOwn(values, name) ? values[name] : null;
|
||||
}
|
||||
|
||||
async function fetchQueue() {
|
||||
if (queueTab.busy) {
|
||||
return;
|
||||
}
|
||||
queueTab.busy = true;
|
||||
queueTab.at = Date.now();
|
||||
try {
|
||||
const response = await fetch("/api/queue", {cache: "no-store"});
|
||||
if (response.ok) {
|
||||
queueTab.data = (await response.json()).learned;
|
||||
}
|
||||
} catch {
|
||||
ui.offline = true;
|
||||
}
|
||||
queueTab.busy = false;
|
||||
drawQueue();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} argvs the queue.py arguments of each change; one passkey assertion signs them all.
|
||||
* @param {string} label what the passkey prompt and the toast name.
|
||||
* @returns {Promise<boolean>} whether the hub handed every change to the runner.
|
||||
*/
|
||||
async function signQueue(argvs, label) {
|
||||
const items = argvs.map((argv) => ({kind: "queue", argv}));
|
||||
const signed = await proofFor(items, label);
|
||||
if (signed === null) {
|
||||
return false;
|
||||
}
|
||||
const result = await sendJson("/api/queue", {items, proof: signed.proof});
|
||||
toast(result.ok ? `Queue: ${label}` : `Queue: ${label}: not applied`, result.ok ? [`${items.length} → runner`] : fail(result), result.ok);
|
||||
return result.ok;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} job a waiting row of state.queue_jobs.
|
||||
* @returns {HTMLElement} Start now: one passkey signs `queue.py override <id>`; the job then starts past the band while the live guard allows.
|
||||
*/
|
||||
function startNow(job) {
|
||||
const hint = job.override ? `${job.id}: Start now is signed; it starts once the live guard and the disk allow` : `Start now: ${job.id} skips the band, slots, reservations and rank; the live guard and the disk still hold it`;
|
||||
return h("button", {type: "button", class: "btn small primary queue-start", "data-start": job.id, disabled: job.override, ...named(`Start now: ${job.id}`, hint), on: {click: async (event) => {
|
||||
event.stopPropagation();
|
||||
if (await signQueue([["override", job.id]], `Start now ${job.id}`)) {
|
||||
await load();
|
||||
}
|
||||
}}}, icon("bi-lightning-charge"), job.override ? "Start asked" : "Start now");
|
||||
}
|
||||
|
||||
function stageSetting(key, text) {
|
||||
const current = queueSetting(key);
|
||||
if (QUEUE_NUMBER.test(text) && Number(text) !== current) {
|
||||
queueTab.staged[key] = text;
|
||||
} else {
|
||||
delete queueTab.staged[key];
|
||||
}
|
||||
drawQueue();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} key a setting as `<section>.<name>`.
|
||||
* @param {string} label its field label.
|
||||
* @returns {HTMLElement} its number field, holding the staged value or the current one.
|
||||
*/
|
||||
function settingField(key, label) {
|
||||
const staged = Object.hasOwn(queueTab.staged, key);
|
||||
const current = queueSetting(key);
|
||||
return h("label", {class: `queue-setting${staged ? " staged" : ""}`, "data-setting": key}, h("span", {class: "muted"}, label),
|
||||
h("input", {class: "field", type: "text", inputmode: "decimal", value: staged ? queueTab.staged[key] : current === null ? "" : String(current), placeholder: "unset", "aria-label": `${label}: ${key}`,
|
||||
on: {change: (event) => stageSetting(key, event.target.value.trim())}}));
|
||||
}
|
||||
|
||||
function queueTable(label, head, rows) {
|
||||
return h("div", {class: "table-wrap"}, h("table", {class: "queue-table", "aria-label": label},
|
||||
h("thead", {}, h("tr", {}, head.map((cell) => h("th", {scope: "col"}, cell)))),
|
||||
h("tbody", {}, rows.length ? rows : h("tr", {}, h("td", {colspan: head.length, class: "muted"}, "nothing learned yet")))));
|
||||
}
|
||||
|
||||
function kindRows() {
|
||||
return Object.entries(queueTab.data.kinds).map(([kind, stats]) => h("tr", {"data-kind": kind},
|
||||
h("th", {scope: "row"}, kind, stats.light ? pill("light", "ok") : null), h("td", {}, String(stats.runs)), h("td", {}, queueNumber(stats.ram_share)), h("td", {}, queueNumber(stats.cpu_share)),
|
||||
h("td", {}, `${stats.slot_limit} (${stats.slot_source})`), QUEUE_KIND_SETTINGS.map(([section, label]) => h("td", {}, settingField(`${section}.${kind}`, label)))));
|
||||
}
|
||||
|
||||
function signatureRows() {
|
||||
return queueTab.data.signatures.map((row) => h("tr", {"data-signature": `${row.kind}: ${row.signature}`},
|
||||
h("th", {scope: "row"}, h("code", {}, row.signature)), h("td", {}, row.kind), h("td", {}, String(row.runs)), h("td", {}, queueNumber(row.minutes)),
|
||||
h("td", {}, queueNumber(row.disk_gb)), h("td", {}, queueNumber(row.ram_share)), h("td", {}, queueNumber(row.cpu_share)), h("td", {}, dash(row.need_gb))));
|
||||
}
|
||||
|
||||
function historyRows() {
|
||||
return [...queueTab.data.history].reverse().map((row) => h("tr", {"data-row": row.id},
|
||||
h("td", {}, when(row.end)), h("td", {}, row.kind), h("td", {}, h("code", {}, row.signature)), h("td", {}, queueNumber(row.minutes)),
|
||||
h("td", {}, pill(String(row.exit), row.exit === 0 ? "ok" : "bad")), h("td", {}, row.override ? pill("override", "warn") : "–")));
|
||||
}
|
||||
|
||||
function waitingJobs() {
|
||||
const waiting = (state.queue_jobs || []).filter((job) => job.status === "waiting");
|
||||
return h("ul", {class: "queue-waiting", "aria-label": "Waiting jobs"}, waiting.length ? waiting.map((job) => h("li", {class: "queue-job", "data-job": job.id},
|
||||
h("strong", {}, job.id), h("span", {class: "muted"}, `${job.kind} · ${job.agent}`), job.reason ? h("span", {class: "queue-reason", title: job.reason}, job.reason) : null, startNow(job)))
|
||||
: h("li", {class: "muted"}, "No job waits."));
|
||||
}
|
||||
|
||||
function queueApplyBar() {
|
||||
const keys = Object.keys(queueTab.staged);
|
||||
if (!keys.length) {
|
||||
return [];
|
||||
}
|
||||
const apply = async () => {
|
||||
if (await signQueue(keys.map((key) => ["config", "set", key, queueTab.staged[key]]), `Apply ${keys.length} settings`)) {
|
||||
queueTab.staged = {};
|
||||
window.setTimeout(fetchQueue, 3000);
|
||||
}
|
||||
drawQueue();
|
||||
};
|
||||
return [h("ul", {class: "mini", "aria-label": "Staged settings"}, keys.map((key) => h("li", {"data-staged": key}, h("code", {}, `${key} = ${queueTab.staged[key]}`)))), h("span", {class: "spacer"}),
|
||||
iconBtn("bi-arrow-counterclockwise", "Discard", "btn ghost", () => {
|
||||
queueTab.staged = {};
|
||||
drawQueue();
|
||||
}, "Discard: drop every staged setting"),
|
||||
h("button", {type: "button", class: "btn primary", "data-queue-apply": "", title: "Apply: one passkey signs every staged setting; the runner sets each through queue.py config set", on: {click: apply}}, icon("bi-send-check"), `Apply (${keys.length})`)];
|
||||
}
|
||||
|
||||
function queueContent() {
|
||||
if (!queueTab.data) {
|
||||
return [h("p", {class: "muted"}, "The installed queue.py has not listed its learnings: it lacks `learned --json`, or the hub cannot read the queue config.")];
|
||||
}
|
||||
return [h("div", {class: "queue-settings", role: "group", "aria-label": "Settings"}, QUEUE_SETTINGS.map(([key, label]) => settingField(key, label))),
|
||||
h("h3", {}, "Kinds"), queueTable("Kinds", ["Kind", "Runs", "p90 RAM %", "Median CPU %", "Slot limit", "Slot cap", "RAM cap %"], kindRows()),
|
||||
h("h3", {}, "Signatures"), queueTable("Signatures", ["Signature", "Kind", "Runs", "Median min", "p90 disk GB", "p95 RAM %", "p95 CPU %", "Need GB"], signatureRows()),
|
||||
h("h3", {}, "Last runs"), queueTable("Last runs", ["Ended", "Kind", "Signature", "Minutes", "Exit", "Override"], historyRows())];
|
||||
}
|
||||
|
||||
function drawQueue() {
|
||||
const dom = queueTab.dom;
|
||||
if (!dom || !dom.body.isConnected) {
|
||||
return;
|
||||
}
|
||||
dom.body.replaceChildren(...queueContent());
|
||||
const bar = queueApplyBar();
|
||||
dom.bar.hidden = !bar.length;
|
||||
dom.bar.replaceChildren(...bar);
|
||||
}
|
||||
|
||||
function drawQueueJobs() {
|
||||
const dom = queueTab.dom;
|
||||
if (dom && dom.jobs.isConnected) {
|
||||
dom.jobs.replaceChildren(waitingJobs());
|
||||
if (Date.now() - queueTab.at >= QUEUE_REFRESH) {
|
||||
fetchQueue();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function homeQueue() {
|
||||
homeFetch("queue", fetchQueue);
|
||||
return h("div", {class: "stack queue-tab"}, waitingJobs(), ...queueContent(), ...queueApplyBar());
|
||||
}
|
||||
|
||||
function queuePanel() {
|
||||
queueTab.dom = {jobs: h("div", {}), body: h("div", {class: "stack"}), bar: h("div", {class: "apply-bar", role: "region", "aria-label": "Apply queue settings", hidden: true})};
|
||||
window.setTimeout(() => {
|
||||
drawQueueJobs();
|
||||
drawQueue();
|
||||
fetchQueue();
|
||||
}, 0);
|
||||
return h("section", {class: "card stack queue-tab", "data-panel": "stream/queue", "aria-label": "Queue"}, queueTab.dom.jobs, queueTab.dom.body, queueTab.dom.bar);
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
unknown: ["#bi-question-circle", (mark) => `${mark.name} unknown: no reading`, 0],
|
||||
};
|
||||
const RESOURCE_BURN = {done: "Done", scope: "Scope"};
|
||||
const RESOURCE_PICKS = [["hardware", "Hardware"], ["tokens", "Tokens"], ["combined", "Combined"], ["accounts", "Accounts"]];
|
||||
const RESOURCE_PICKS = [["hardware", "Hardware"], ["tokens", "Tokens"], ["combined", "Combined"], ["accounts", "Accounts"], ["usage", "Usage"]];
|
||||
const resourceView = {data: null, dom: null, busy: false, key: "", at: 0, timer: 0, series: {}};
|
||||
const resourceKey = () => JSON.stringify([ui.preset, ui.asOf]);
|
||||
const resourcesStale = () => resourceKey() !== resourceView.key || nowSeconds() - resourceView.at >= RESOURCE.stale;
|
||||
@@ -42,11 +42,12 @@
|
||||
const legend = h("div", {class: "res-legend"});
|
||||
const plot = h("div", {class: "res-plot"});
|
||||
const panel = h("section", {class: `card res-panel res-${kind}`, "data-panel": `resources-${kind}`, "aria-label": label, hidden: kind === "combined"},
|
||||
h("div", {class: "res-head", "data-legend-slot": ""}, h("span", {class: "res-title", title: label, "aria-label": label}, icon(name)), legend), plot);
|
||||
h("div", {class: "res-head", "data-legend-slot": ""}, h("span", {class: "res-title", title: label, "aria-label": label}, icon(name)), legend), kind === "hardware" ? limitBar() : null, plot);
|
||||
return {kind, label, legend, plot, panel};
|
||||
});
|
||||
const accounts = accountsPanel();
|
||||
resourceView.dom = {count, switches, picks, panels, accounts};
|
||||
const usage = usagePanel();
|
||||
resourceView.dom = {count, switches, picks, panels, accounts, usage};
|
||||
if (!resourceView.timer) {
|
||||
resourceView.timer = window.setInterval(pollResources, RESOURCE.poll);
|
||||
window.addEventListener("resize", drawResources);
|
||||
@@ -60,10 +61,13 @@
|
||||
const reload = iconBtn("bi-arrow-clockwise", "Reload", "btn small soft", () => {
|
||||
fetchResources();
|
||||
fetchAccounts();
|
||||
}, "Reload: read the sampler files and the accounts again");
|
||||
if (!usage.panel.hidden) {
|
||||
fetchUsage();
|
||||
}
|
||||
}, "Reload: read the sampler files, the accounts and the usage again");
|
||||
return h("div", {class: "graph resources"},
|
||||
boxHead("Resources", "", h("div", {class: "toolbar"}, reload, switches.tokens, picks.menu, count)),
|
||||
h("div", {class: "res-panels"}, panels.map((entry) => entry.panel), accounts.panel));
|
||||
h("div", {class: "res-panels"}, panels.map((entry) => entry.panel), accounts.panel, usage.panel));
|
||||
}
|
||||
|
||||
function pollResources() {
|
||||
@@ -82,6 +86,7 @@
|
||||
}
|
||||
resourceView.busy = true;
|
||||
resourceView.key = resourceKey();
|
||||
fetchLimits();
|
||||
try {
|
||||
const response = await fetch(`/api/resources?${windowQuery()}`, {cache: "no-store"});
|
||||
if (response.ok) {
|
||||
@@ -262,6 +267,7 @@
|
||||
const y = resourceScale(frame, [0, 50, 100], percentOf, "left");
|
||||
resourceBackdrop(frame, y, parts.marks, span);
|
||||
resourceLines(frame, y, parts.hardware.filter((line) => !parts.hidden.has(line.id)));
|
||||
limitLines(frame, y);
|
||||
return {svg: frame.svg, series: RESOURCE_SERIES.hardware(parts), path: "resources.hidden"};
|
||||
}
|
||||
|
||||
@@ -380,6 +386,12 @@
|
||||
}
|
||||
dom.accounts.panel.hidden = !view.panels.includes("accounts");
|
||||
drawAccounts();
|
||||
dom.usage.panel.hidden = !view.panels.includes("usage");
|
||||
if (!dom.usage.panel.hidden && usageView.ask === 0) {
|
||||
fetchUsage();
|
||||
}
|
||||
drawUsage();
|
||||
drawLimitBar();
|
||||
if (data === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
const ref = item ? keyOf(item) : null;
|
||||
const list = fileList(review.id);
|
||||
const treeNav = h("nav", {class: "card tree", "aria-label": "Changed files"}, treePane(list));
|
||||
const diff = h("section", {class: "card diff-pane", "aria-label": "Diff"}, diffPane(list, ref));
|
||||
const diff = h("section", {class: "card diff-pane", "aria-label": "Diff"}, diffPane(list, ref, review.worktree));
|
||||
const notes = h("div", {class: "review-notes"}, ref ? feedbackList(ref) : null);
|
||||
const id = ui.review;
|
||||
const head = h("article", {class: "card"},
|
||||
@@ -68,7 +68,7 @@
|
||||
}
|
||||
openSheet(review.title, [head, split], true);
|
||||
ui.review = id;
|
||||
reviewDom = {tree: treeNav, diff, notes, ref};
|
||||
reviewDom = {tree: treeNav, diff, notes, ref, root: review.worktree};
|
||||
}
|
||||
|
||||
function repaintReview() {
|
||||
@@ -80,7 +80,7 @@
|
||||
const top = stack.scrollTop;
|
||||
const opened = [...stack.querySelectorAll(REVIEW_FILE)].map((file) => file.open);
|
||||
stack.replaceChildren(...list.map((file, index) => {
|
||||
const node = reviewFile(file, index, reviewDom.ref);
|
||||
const node = reviewFile(file, index, reviewDom.ref, reviewDom.root);
|
||||
node.open = opened[index];
|
||||
return node;
|
||||
}));
|
||||
@@ -181,11 +181,11 @@
|
||||
return h("tr", {class: line.kind, "data-line": line.new || line.old || null}, h("td", {class: "num"}, line.old), h("td", {class: "num"}, line.new), h("td", {class: "sign"}, SIGNS[line.kind] || " "), h("td", {class: "code"}, line.text));
|
||||
}
|
||||
|
||||
function diffPane(list, ref) {
|
||||
function diffPane(list, ref, root) {
|
||||
if (!Array.isArray(list) || !list.length) {
|
||||
return h("p", {class: "muted pad"}, list === "loading" ? "Loading changes …" : "No diff available.");
|
||||
}
|
||||
const stack = h("div", {class: "review-stack"}, list.map((file, index) => reviewFile(file, index, ref)));
|
||||
const stack = h("div", {class: "review-stack"}, list.map((file, index) => reviewFile(file, index, ref, root)));
|
||||
stack.addEventListener("scroll", () => followScroll(stack), {passive: true});
|
||||
return stack;
|
||||
}
|
||||
@@ -195,13 +195,14 @@
|
||||
* @param {number} index its place in that list.
|
||||
* @param {string|null} ref the keyOf() of the review's inbox item, whose line comments its rows show; null when it
|
||||
* waits on nobody.
|
||||
* @param {string} root the review's worktree, whose file heads link to root/path.
|
||||
*/
|
||||
function reviewFile(file, index, ref) {
|
||||
function reviewFile(file, index, ref, root) {
|
||||
const [letter, tone] = FILE_STATUS[file.status] || ["?", "neutral"];
|
||||
return h("details", {class: "review-file", "data-index": index, "data-path": ref ? file.path : null, open: index === ui.file},
|
||||
h("summary", {class: "diff-head"},
|
||||
h("span", {class: "letter", "data-tone": tone}, letter),
|
||||
h("code", {class: "path"}, file.old ? `${file.old} → ${file.path}` : file.path),
|
||||
pathCode(root, file.path, file.old ? `${file.old} → ${file.path}` : file.path),
|
||||
file.tags.map((tag) => pill(tag, "neutral")),
|
||||
h("span", {class: "spacer"}),
|
||||
stat(file)),
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
const RULE_KINDS = {ask: "Ask: tool + command pattern", review: "Review: branch pattern + gate green", decision: "Decision: take the recommendation"};
|
||||
const RULE_HINTS = Glossary.RULE_HINTS;
|
||||
const RULE_GROUPS = [["ask", "Ask"], ["review", "Review"], ["decision", "Decision"]];
|
||||
const RECORD_WORDS = {ask: "asks", review: "reviews", decision: "decisions"};
|
||||
const EXPIRY_WARN_DAYS = 2;
|
||||
const DRAFT_DELAY = 300;
|
||||
const rulesView = {open: {}};
|
||||
|
||||
/**
|
||||
* @param {Object} rule the stored rule to turn on again, which widens what agents may do.
|
||||
@@ -22,12 +27,128 @@
|
||||
await load();
|
||||
}
|
||||
|
||||
function rulesScreen() {
|
||||
/**
|
||||
* @param {string} id the key rulesView keeps the section's open state under across redraws.
|
||||
* @param {boolean} fallback whether the section starts open before the operator toggles it.
|
||||
* @param {Array} head the summary's nodes.
|
||||
* @param {HTMLElement} body what the section folds.
|
||||
* @returns {HTMLDetailsElement} the collapsible section.
|
||||
*/
|
||||
function foldSection(id, fallback, head, body) {
|
||||
const open = Object.hasOwn(rulesView.open, id) ? rulesView.open[id] : fallback;
|
||||
const section = h("details", {class: "rule-fold", "data-fold": id, open}, h("summary", {title: "Show or hide"}, icon("bi-chevron-right", "rule-fold-mark"), head), body);
|
||||
section.addEventListener("toggle", () => {
|
||||
rulesView.open[id] = section.open;
|
||||
});
|
||||
return section;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} rule a stored rule with expires in epoch seconds.
|
||||
* @returns {HTMLElement} the chip with the days left, red under EXPIRY_WARN_DAYS days and once expired.
|
||||
*/
|
||||
function expiryChip(rule) {
|
||||
const days = (rule.expires - nowSeconds()) / DAY;
|
||||
const whole = Math.floor(days);
|
||||
const text = days <= 0 ? "expired" : whole < 1 ? "under a day left" : `${whole} ${whole === 1 ? "day" : "days"} left`;
|
||||
return h("span", {class: "pill", "data-tone": days < EXPIRY_WARN_DAYS ? "bad" : "neutral", "data-expiry": "", title: `until ${absolute.format(stampOf(rule.expires))}`}, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} counted matched and of, as the hub counts a rule or a draft.
|
||||
* @param {string} kind the rule kind, which names the records counted.
|
||||
* @returns {string} N of the last M asks, reviews or decisions.
|
||||
*/
|
||||
const matchWords = (counted, kind) => `${counted.matched} of the last ${counted.of} ${RECORD_WORDS[kind]}`;
|
||||
|
||||
function ruleSwitch(rule) {
|
||||
return h("input", {type: "checkbox", role: "switch", class: "switch", checked: rule.enabled, "aria-label": revealed(`Rule ${rule.pattern}: on`), on: {change: async (event) => {
|
||||
await changeRule(rule, rule.enabled ? "disable" : "enable");
|
||||
event.target.checked = rule.enabled;
|
||||
}}});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} rule a stored rule of state.rules.
|
||||
* @returns {HTMLLIElement} the row: switch, tool for an ask rule, pattern, directory, applies-to, expiry chip, match count and delete.
|
||||
*/
|
||||
function hubRuleRow(rule) {
|
||||
const remove = () => {
|
||||
if (window.confirm("Delete rule?")) {
|
||||
changeRule(rule, "delete");
|
||||
}
|
||||
};
|
||||
return h("li", {class: "hub-rule", "data-rule": rule.id, "data-kind": rule.kind, "data-on": String(rule.enabled)},
|
||||
ruleSwitch(rule), rule.kind === "ask" ? h("code", {class: "hub-rule-tool", title: "Tool"}, revealed(rule.tool)) : null,
|
||||
h("code", {class: "hub-rule-pattern", title: "Pattern"}, revealed(rule.pattern)), h("code", {class: "hub-rule-scope", title: "Directory"}, revealed(rule.scope)),
|
||||
targetPill(rule.agents), rule.signed ? null : pill("unsigned: has no effect", "warn"), expiryChip(rule),
|
||||
h("span", {class: "hub-rule-count", "data-matched": rule.matched, title: "Counted with the matcher that applies the rule, on or off, expired or not"}, matchWords(rule, rule.kind)),
|
||||
h("span", {class: "spacer"}), iconBtn("bi-trash3", "Delete rule", "btn small danger", remove, revealed(`Delete rule ${rule.pattern}`)));
|
||||
}
|
||||
|
||||
function ruleGroups() {
|
||||
return RULE_GROUPS.map(([kind, label]) => {
|
||||
const rows = state.rules.filter((rule) => rule.kind === kind);
|
||||
const body = rows.length ? h("ul", {class: "hub-rules"}, rows.map(hubRuleRow)) : h("p", {class: "muted"}, `No ${label.toLowerCase()} rule yet.`);
|
||||
return foldSection(kind, true, [h("strong", {}, label), counter(rows.length)], body);
|
||||
});
|
||||
}
|
||||
|
||||
function rulesList() {
|
||||
const add = h("button", {type: "button", class: "btn primary", "data-new-rule": "", ...named("New rule", "New rule: draft a rule and sign it with your passkey"), on: {click: openRuleSheet}}, icon("bi-plus-lg"), "New rule");
|
||||
return h("section", {class: "card stack-tight hub-rule-list", "aria-label": "Hub rules"}, h("div", {class: "row"}, h("h3", {}, "Hub rules"), h("span", {class: "spacer"}), add),
|
||||
h("p", {class: "muted"}, "Rules the hub applies by itself once your passkey signed them. Each counts how many of the last asks, reviews or decisions of its kind it would have granted."), ruleGroups());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Function} read returns the draft as POST /api/rules/match takes it.
|
||||
* @param {HTMLElement} out where the live count shows.
|
||||
* @returns {Function} what schedules a count DRAFT_DELAY ms after the last change; only the newest answer shows.
|
||||
*/
|
||||
function draftCounter(read, out) {
|
||||
let timer = 0;
|
||||
let ticket = 0;
|
||||
return () => {
|
||||
window.clearTimeout(timer);
|
||||
timer = window.setTimeout(async () => {
|
||||
ticket += 1;
|
||||
const mine = ticket;
|
||||
const fields = read();
|
||||
const result = await sendJson("/api/rules/match", fields);
|
||||
if (mine === ticket) {
|
||||
out.dataset.matched = result.ok && result.data ? String(result.data.matched) : "";
|
||||
out.textContent = result.ok && result.data ? `Would grant ${matchWords(result.data, fields.kind)}` : `Not counted: ${result.text}`.trim();
|
||||
}
|
||||
}, DRAFT_DELAY);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} fields the draft as ruleDraft() reads it.
|
||||
* @param {boolean} enabled whether the rule starts on.
|
||||
* @returns {Promise<boolean>} whether the hub stored the signed rule.
|
||||
*/
|
||||
async function createRule(fields, enabled) {
|
||||
const prepared = await sendJson("/api/rules/sign", fields);
|
||||
if (!prepared.ok || !prepared.data) {
|
||||
toast("Rule not created", fail(prepared), false);
|
||||
return false;
|
||||
}
|
||||
const signed = prepared.data.sign ? await assertion(prepared.data, "Rule") : null;
|
||||
if (prepared.data.sign && !signed) {
|
||||
return false;
|
||||
}
|
||||
const result = await sendJson("/api/rules", {rule: prepared.data.payload, assertion: signed, enabled});
|
||||
toast(result.ok ? "Rule created" : "Rule not created", result.ok ? [] : fail(result), result.ok);
|
||||
return result.ok;
|
||||
}
|
||||
|
||||
function ruleForm() {
|
||||
const kind = h("select", {class: "field", "aria-label": "Kind"}, Object.entries(RULE_KINDS).map(([value, label]) => h("option", {value}, label)));
|
||||
const target = targetSelect("Applies to", null);
|
||||
const targetField = h("label", {}, "Applies to", target);
|
||||
const tool = h("input", {class: "field", type: "text", placeholder: "Bash", value: "Bash"});
|
||||
const pattern = h("input", {class: "field", type: "text", placeholder: "make test*"});
|
||||
const pattern = h("input", {class: "field", type: "text", placeholder: "make test*", "aria-label": "Pattern"});
|
||||
const scope = h("input", {class: "field", type: "text", value: "*", placeholder: "/home/…/Repositories/*"});
|
||||
const expiry = new Date(Date.now() + 7 * DAY * 1000);
|
||||
const expires = h("input", {class: "field", type: "date", value: localInput(expiry.getTime() / 1000).slice(0, 10), required: true});
|
||||
@@ -35,6 +156,7 @@
|
||||
const toolField = h("label", {}, "Tool (glob)", tool);
|
||||
const scopeField = h("label", {}, "Directory (glob)", scope);
|
||||
const hint = h("p", {class: "muted"});
|
||||
const live = h("p", {class: "muted", "data-live-count": "", "aria-live": "polite"}, "Counting …");
|
||||
const sync = () => {
|
||||
toolField.hidden = kind.value !== "ask";
|
||||
scopeField.hidden = kind.value === "decision";
|
||||
@@ -46,11 +168,9 @@
|
||||
};
|
||||
kind.addEventListener("change", sync);
|
||||
sync();
|
||||
const form = h("form", {class: "rule-form"}, h("label", {}, "Kind", kind), targetField, toolField, h("label", {}, "Pattern (glob)", pattern), scopeField, h("label", {}, "Expires on", expires), h("label", {class: "check"}, enabled, "active"), h("button", {type: "submit", class: "btn primary", "data-sign": ""}, "Create rule"));
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const read = () => {
|
||||
const end = Date.parse(`${expires.value}T23:59:59`) / 1000;
|
||||
const fields = {
|
||||
return {
|
||||
kind: kind.value,
|
||||
tool: kind.value === "ask" ? tool.value.trim() : "",
|
||||
pattern: pattern.value.trim() || (kind.value === "decision" ? "*" : ""),
|
||||
@@ -58,20 +178,28 @@
|
||||
expires: Number.isFinite(end) ? end : 0,
|
||||
agents: ruleAgents(kind.value, target.value),
|
||||
};
|
||||
const prepared = await sendJson("/api/rules/sign", fields);
|
||||
if (!prepared.ok || !prepared.data) {
|
||||
toast("Rule not created", fail(prepared), false);
|
||||
return;
|
||||
};
|
||||
const form = h("form", {class: "rule-form", "aria-label": "New rule"}, h("label", {}, "Kind", kind), targetField, toolField, h("label", {}, "Pattern (glob)", pattern), scopeField, h("label", {}, "Expires on", expires), h("label", {class: "check"}, enabled, "active"), h("button", {type: "submit", class: "btn primary", "data-sign": ""}, "Create rule"));
|
||||
const recount = draftCounter(read, live);
|
||||
form.addEventListener("input", recount);
|
||||
form.addEventListener("change", recount);
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
if (await createRule(read(), enabled.checked)) {
|
||||
closeSheet();
|
||||
}
|
||||
const signed = prepared.data.sign ? await assertion(prepared.data, "Rule") : null;
|
||||
if (prepared.data.sign && !signed) {
|
||||
return;
|
||||
}
|
||||
const result = await sendJson("/api/rules", {rule: prepared.data.payload, assertion: signed, enabled: enabled.checked});
|
||||
toast(result.ok ? "Rule created" : "Rule not created", result.ok ? [] : fail(result), result.ok);
|
||||
await load();
|
||||
});
|
||||
recount();
|
||||
return [hint, live, form];
|
||||
}
|
||||
|
||||
function openRuleSheet() {
|
||||
openSheet("New rule", ruleForm(), false);
|
||||
}
|
||||
|
||||
function rulesScreen() {
|
||||
const dom = firewallSections();
|
||||
const ruleCard = h("div", {class: "card"}, h("h3", {}, "New hub rule for automatic grants"), hint, form);
|
||||
return controlsPage({tools: [dom.tools], rules: [dom.settings, ruleCard, dom.patterns], groups: [dom.groups, dom.sets], schedules: [schedulesPanel()]}, dom.bar);
|
||||
const below = [["settings", "Settings files", dom.settings], ["patterns", "Never granted", dom.patterns], ["groups", "Agent groups", dom.groups], ["sets", "Rule sets", dom.sets]];
|
||||
return controlsPage({tools: [dom.tools], rules: [rulesList(), ...below.map(([id, label, node]) => foldSection(id, false, [h("strong", {}, label)], node))], schedules: [schedulesPanel()], queue: [queuePanel()]}, dom.bar);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
const RUNNING_WORDS = {queue: "Queue job running", agent: "Agent working", hub: "Hub job running"};
|
||||
|
||||
const markSources = () => ({now: state.now, tasks: state.tasks, beats: state.beats, runner: state.runner});
|
||||
|
||||
/**
|
||||
* @param row - a card's task row.
|
||||
* @param found - Kanban.marks of the row.
|
||||
* @returns {HTMLElement|null} one labelled chip per mark, null without any.
|
||||
*/
|
||||
function markChips(row, found) {
|
||||
if (!found.length) {
|
||||
return null;
|
||||
}
|
||||
const hint = (mark) => (mark.at === null ? mark.hint : `${mark.hint}, since ${absolute.format(stampOf(mark.at))}`);
|
||||
return h("div", {class: "kanban-marks", role: "group", "aria-label": `Running now: ${row.task}`}, found.map((mark) =>
|
||||
h("span", {class: "pill kanban-mark", "data-mark": mark.key, "data-tone": mark.tone, role: "img", ...named(`${RUNNING_WORDS[mark.key]}: ${mark.text}`, hint(mark))}, icon(mark.icon), mark.text)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param count - the shown cards with at least one mark.
|
||||
* @returns {HTMLElement} the board's Running toggle: pressed, it shows only marked cards.
|
||||
*/
|
||||
function runningToggle(count) {
|
||||
const words = `Running: ${count} cards a queue job, an agent or the hub works on now`;
|
||||
return h("button", {type: "button", class: "btn small", id: "kanban-running", "aria-pressed": String(kanban.running), ...named("Running", `${words}, ${kanban.running ? "only these shown" : "every card shown"}`), on: {click: () => {
|
||||
kanban.running = !kanban.running;
|
||||
taskView.sig = "";
|
||||
drawTasks();
|
||||
}}}, icon("bi-activity"), "Running", counter(count));
|
||||
}
|
||||
@@ -1,86 +1,205 @@
|
||||
const SCHEDULE_ROWS = {
|
||||
coach: ["Coach reminder", "bi-heart-pulse", "A one-line health tip at the top of an agent's answer, once across all agents."],
|
||||
dream: ["Dream reminder", "bi-moon-stars", "A /kvb-dream hint, once per agent session."],
|
||||
"dream-popup": ["Dream popup", "bi-bell", "A GNOME notification to run /kvb-dream."],
|
||||
"queue-cleanup": ["Queue cleanup", "bi-trash3", "Deletes the queue jobs no living process holds."],
|
||||
"code-graph": ["Code graph", "bi-diagram-3", "Keeps the codebase-memory-mcp daemon watching every graph."],
|
||||
coach: ["Coach reminder", "A one-line health tip at the top of an agent's answer, once across all agents; every N hours."],
|
||||
dream: ["Dream reminder", "A /kvb-dream hint, once per agent session; every N hours."],
|
||||
"dream-popup": ["Dream popup", "A GNOME notification to run /kvb-dream; daily times like 17:00, 21:30 or an OnCalendar expression."],
|
||||
"queue-cleanup": ["Queue cleanup", "Deletes the queue jobs no living process holds; daily times or an OnCalendar expression."],
|
||||
"code-graph": ["Code graph", "Keeps the codebase-memory-mcp daemon watching every graph; on or off only."],
|
||||
};
|
||||
const SCHEDULE_UNITS = {"dream-popup": "kvb-dream-notify.timer", "queue-cleanup": "kvb-org-queue-cleanup.timer", "code-graph": "kvb-code-graph.service"};
|
||||
const SCHEDULE_HOURS = [1, 24];
|
||||
const SCHEDULE_SOURCES = [["skills", "Skills"], ["hub", "Hub"], ["claude", "Claude"], ["system", "System"]];
|
||||
const SCHEDULE_CLOCK = /^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/;
|
||||
const SCHEDULE_START = "systemctl --user start kvb-schedules.service";
|
||||
const SCHEDULE_HINTS = {
|
||||
hours: "Click to edit: whole hours from 1 to 24; Enter saves.",
|
||||
timer: "Click to edit: daily times like 17:00, 21:30 or a raw OnCalendar expression, which the reconciler checks with systemd-analyze; Enter saves.",
|
||||
cron: "Click to edit: a 5-field cron like 0 9 * * 1-5; Enter saves with the passkey.",
|
||||
};
|
||||
const scheduleShown = new Set(SCHEDULE_SOURCES.map(([id]) => id));
|
||||
|
||||
async function saveSchedule(name, value) {
|
||||
const result = await sendJson("/api/schedules", {row: name, value});
|
||||
if (result.ok && result.data) {
|
||||
state.schedules = result.data;
|
||||
} else {
|
||||
const scheduleHost = (unit) => state.schedules.host.rows.find((row) => row.unit === unit) || null;
|
||||
const scheduleText = (row) => (Object.hasOwn(row, "every") ? `${row.every} h` : Object.hasOwn(row, "at") ? row.at.join(", ") : row.calendar || "");
|
||||
const scheduleOverride = (row) => (Object.hasOwn(row, "at") ? {at: row.at} : Object.hasOwn(row, "calendar") ? {calendar: row.calendar} : {});
|
||||
|
||||
/**
|
||||
* @param {string} text what the operator typed into a timer's schedule field.
|
||||
* @returns {Object} {at} for daily times, else {calendar} with the raw OnCalendar expression.
|
||||
*/
|
||||
function scheduleTiming(text) {
|
||||
const times = text.split(",").map((part) => part.trim()).filter(Boolean);
|
||||
return times.length && times.every((time) => SCHEDULE_CLOCK.test(time)) ? {at: times} : {calendar: text.trim()};
|
||||
}
|
||||
|
||||
async function saveSchedule(body) {
|
||||
const result = await sendJson("/api/schedules", body);
|
||||
if (!result.ok) {
|
||||
toast("Schedule not changed", fail(result), false);
|
||||
}
|
||||
await load();
|
||||
}
|
||||
|
||||
const scheduleHost = (unit) => state.schedules.host.rows.find((row) => row.unit === unit) || null;
|
||||
const scheduleTimes = (text) => text.split(",").map((part) => part.trim()).filter(Boolean);
|
||||
|
||||
/**
|
||||
* @param {Object} host a row of the host view, or null.
|
||||
* @returns {HTMLElement} its next and last run, or why there is none yet.
|
||||
* @param {string[]} argv the schedules.py arguments of one System timer or Claude task change.
|
||||
* @param {string} label what the passkey prompt and the toast name.
|
||||
*/
|
||||
function scheduleRuns(host) {
|
||||
if (!host || (host.next === null && host.last === null)) {
|
||||
return h("span", {class: "muted"}, "no run known");
|
||||
async function signSchedule(argv, label) {
|
||||
const items = [{kind: "schedule", argv}];
|
||||
const signed = await proofFor(items, label);
|
||||
if (signed === null) {
|
||||
return;
|
||||
}
|
||||
return h("span", {class: "muted sched-runs"}, host.next === null ? null : ["next ", when(host.next)], host.next !== null && host.last !== null ? " · " : null, host.last === null ? null : ["last ", when(host.last)]);
|
||||
const result = await sendJson("/api/schedules", {items, proof: signed.proof});
|
||||
toast(result.ok ? `Schedule: ${label}` : `Schedule: ${label}: not changed`, result.ok ? ["→ runner"] : fail(result), result.ok);
|
||||
await load();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} name a key of SCHEDULE_ROWS.
|
||||
* @param {Object} row its stored row: on, plus every or at.
|
||||
* @returns {HTMLElement} the row: switch, its timing field and its runs.
|
||||
* @returns {Object} its table row: the stored row of schedules.json, the runs of its unit and how it saves.
|
||||
*/
|
||||
function scheduleRow(name, row) {
|
||||
const [label, glyph, hint] = SCHEDULE_ROWS[name];
|
||||
const change = (key, value) => saveSchedule(name, {...state.schedules.rows[name], [key]: value});
|
||||
const toggle = h("input", {type: "checkbox", role: "switch", checked: row.on, "aria-label": `${label}: on`, on: {change: (event) => change("on", event.target.checked)}});
|
||||
const timing = [];
|
||||
if (Object.hasOwn(row, "every")) {
|
||||
timing.push(h("label", {class: "sched-field"}, "every", h("input", {class: "field sched-hours", type: "number", min: SCHEDULE_HOURS[0], max: SCHEDULE_HOURS[1], step: 1, value: row.every, "aria-label": `${label}: every hours`,
|
||||
on: {change: (event) => change("every", Number(event.target.value))}}), "h"));
|
||||
}
|
||||
if (Object.hasOwn(row, "at")) {
|
||||
timing.push(h("label", {class: "sched-field"}, "at", h("input", {class: "field sched-times", type: "text", value: row.at.join(", "), placeholder: "17:00, 21:30", "aria-label": `${label}: at times`,
|
||||
on: {change: (event) => change("at", scheduleTimes(event.target.value))}})));
|
||||
}
|
||||
const unit = SCHEDULE_UNITS[name];
|
||||
return h("li", {class: `sched-row${row.on ? "" : " off"}`, "data-schedule": name},
|
||||
h("label", {class: "sched-switch"}, toggle, icon(glyph), h("span", {class: "sched-name"}, label)),
|
||||
h("span", {class: "sched-hint muted"}, hint), ...timing, unit ? scheduleRuns(scheduleHost(unit)) : null);
|
||||
function skillsRow(name) {
|
||||
const row = state.schedules.rows[name];
|
||||
const host = SCHEDULE_UNITS[name] ? scheduleHost(SCHEDULE_UNITS[name]) : null;
|
||||
const save = (value) => saveSchedule({row: name, value});
|
||||
const input = Object.hasOwn(row, "every") ? "hours" : Object.keys(scheduleOverride(row)).length ? "timer" : null;
|
||||
return {key: name, source: "skills", name: SCHEDULE_ROWS[name][0], hint: SCHEDULE_ROWS[name][1], schedule: scheduleText(row), input, host, on: row.on, reset: null,
|
||||
toggle: (on) => save({...row, on}),
|
||||
edit: (text) => save(input === "hours" ? {on: row.on, every: Number(text.replace(/\s*h$/, ""))} : {on: row.on, ...scheduleTiming(text)})};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} host a host view row the hub must not switch: a hub unit or a foreign timer or hook.
|
||||
* @returns {HTMLElement} its schedule, runs and, for a foreign row, its off command to copy.
|
||||
* @param {Object} host a hub timer of the host view.
|
||||
* @returns {Object} its table row; its override in schedules.json, if any, wins over what the host last saw.
|
||||
*/
|
||||
function scheduleForeign(host) {
|
||||
return h("li", {class: "sched-row foreign", "data-schedule-foreign": host.name},
|
||||
h("span", {class: "sched-name"}, host.name), h("span", {class: `chip ${host.owner === "hub" ? "ok" : ""}`}, host.owner),
|
||||
h("code", {class: "sched-hint"}, host.kind === "hook" ? host.command : dash(host.schedule)), host.kind === "hook" ? null : scheduleRuns(host),
|
||||
host.off ? h("span", {class: "sched-off"}, h("code", {}, host.off), host.kind === "hook" ? null : copyButton(host.off)) : null);
|
||||
function hubRow(host) {
|
||||
const override = state.schedules.units[host.unit] || null;
|
||||
const timing = override ? scheduleOverride(override) : {};
|
||||
const on = override ? override.on : host.on;
|
||||
const save = (value) => saveSchedule({unit: host.unit, value});
|
||||
return {key: host.unit, source: "hub", name: host.name, hint: host.file, schedule: Object.keys(timing).length ? scheduleText(timing) : host.schedule, input: "timer", host, on,
|
||||
reset: host.dropin || Object.keys(timing).length ? () => save({on}) : null,
|
||||
toggle: (value) => save({on: value, ...timing}), edit: (text) => save({on, ...scheduleTiming(text)})};
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {HTMLElement} the Schedules panel: the first-party rows, then every other timer and hook the host
|
||||
* reconciler last saw; a hint with its start command before its first run.
|
||||
* @param {Object} host a System timer of the host view.
|
||||
* @returns {Object} its table row; every change is signed with the passkey and runs through the host runner.
|
||||
*/
|
||||
function systemRow(host) {
|
||||
const sign = (rest, label) => signSchedule(["timer", host.unit, ...rest], `${label} ${host.unit}`);
|
||||
return {key: host.unit, source: "system", name: host.name, hint: host.file, schedule: host.schedule, input: "timer", host, on: host.on,
|
||||
reset: host.dropin ? () => sign(["--reset"], "Reset") : null,
|
||||
toggle: (on) => sign([on ? "--on" : "--off"], on ? "Switch on" : "Switch off"),
|
||||
edit: (text) => {
|
||||
const timing = scheduleTiming(text);
|
||||
sign(timing.at ? ["--at", ...timing.at] : ["--calendar", timing.calendar], "Retime");
|
||||
}};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} host a Claude task of the host view.
|
||||
* @returns {Object} its table row; switching it off removes the task from its scheduled_tasks.json, signed with the passkey.
|
||||
*/
|
||||
function claudeRow(host) {
|
||||
const sign = (rest, label) => signSchedule(["cron", host.file, host.task, ...rest], `${label} ${host.name}`);
|
||||
return {key: `${host.file}#${host.task}`, source: "claude", name: host.name, hint: host.command || host.file, schedule: host.schedule, input: "cron", host, on: true, reset: null,
|
||||
toggle: (on) => (on ? null : sign(["--remove"], "Remove")), edit: (text) => sign(["--cron", text.trim()], "Retime")};
|
||||
}
|
||||
|
||||
function scheduleRows() {
|
||||
const others = state.schedules.host.rows;
|
||||
const of = (source, build) => others.filter((row) => row.source === source).map(build);
|
||||
return [...Object.keys(SCHEDULE_ROWS).map(skillsRow), ...of("hub", hubRow), ...of("claude", claudeRow), ...of("system", systemRow)];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {HTMLElement} cell the schedule cell of a row.
|
||||
* @param {Object} row the table row, with its schedule and edit().
|
||||
*/
|
||||
function scheduleField(cell, row) {
|
||||
const field = h("input", {class: "field sched-input", type: "text", value: row.schedule, "aria-label": `${row.name}: schedule`, title: SCHEDULE_HINTS[row.input],
|
||||
on: {keydown: (event) => {
|
||||
if (event.key === "Enter" && field.value.trim()) {
|
||||
event.preventDefault();
|
||||
row.edit(field.value);
|
||||
} else if (event.key === "Escape") {
|
||||
cell.replaceChildren(scheduleCellText(row));
|
||||
}
|
||||
}}});
|
||||
cell.replaceChildren(field);
|
||||
field.focus();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} row a table row.
|
||||
* @returns {HTMLElement} its schedule as text.
|
||||
*/
|
||||
function scheduleCellText(row) {
|
||||
return h("code", {}, dash(row.schedule));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} row a table row.
|
||||
* @returns {HTMLElement} its schedule cell; a click turns it into a field when the row takes a schedule.
|
||||
*/
|
||||
function scheduleCell(row) {
|
||||
const cell = h("td", {class: "sched-cell", "data-edit": row.input || "", title: row.input ? SCHEDULE_HINTS[row.input] : "on or off only"});
|
||||
cell.append(scheduleCellText(row));
|
||||
if (row.input) {
|
||||
cell.addEventListener("click", () => cell.querySelector("input") || scheduleField(cell, row));
|
||||
}
|
||||
return cell;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} row a table row.
|
||||
* @returns {HTMLElement} its line: source, name with its error, schedule, next and last run, the switch and a Reset where a drop-in exists.
|
||||
*/
|
||||
function scheduleLine(row) {
|
||||
const host = row.host;
|
||||
const error = host && host.error ? h("span", {class: "pill", "data-tone": "bad", title: host.error}, "error") : null;
|
||||
const toggle = h("input", {type: "checkbox", role: "switch", checked: row.on, disabled: row.source === "claude" && !row.on, "aria-label": `${row.name}: on`,
|
||||
title: row.source === "claude" ? "Off removes the task, signed with the passkey" : row.source === "system" ? "Signed with the passkey" : null,
|
||||
on: {change: (event) => row.toggle(event.target.checked)}});
|
||||
const reset = row.reset ? h("button", {type: "button", class: "btn small ghost", "data-reset": "", ...named(`Reset ${row.name}`, "Reset: remove the schedule.conf drop-in, keep the unit file"), on: {click: row.reset}}, "Reset") : null;
|
||||
return h("tr", {class: row.on ? null : "off", "data-schedule": row.key, "data-source": row.source},
|
||||
h("td", {}, pill(row.source, row.source === "skills" || row.source === "hub" ? "ok" : "warn")), h("th", {scope: "row", title: row.hint}, row.name, error),
|
||||
scheduleCell(row), h("td", {}, host && host.next !== null ? when(host.next) : "–"), h("td", {}, host && host.last !== null ? when(host.last) : "–"),
|
||||
h("td", {class: "sched-on"}, toggle, reset));
|
||||
}
|
||||
|
||||
function scheduleChips(redraw) {
|
||||
return h("div", {class: "chips", role: "group", "aria-label": "Show sources"}, SCHEDULE_SOURCES.map(([id, label]) => h("button", {type: "button", class: "chip", "data-source-chip": id, "aria-pressed": String(scheduleShown.has(id)), on: {click: () => {
|
||||
if (scheduleShown.has(id)) {
|
||||
scheduleShown.delete(id);
|
||||
} else {
|
||||
scheduleShown.add(id);
|
||||
}
|
||||
redraw();
|
||||
}}}, label)));
|
||||
}
|
||||
|
||||
function scheduleTable() {
|
||||
const rows = scheduleRows().filter((row) => scheduleShown.has(row.source));
|
||||
return h("div", {class: "fw-table-wrap"}, h("table", {class: "fw-table sched-table", "aria-label": "Schedules"},
|
||||
h("thead", {}, h("tr", {}, ["Source", "Name", "Schedule", "Next", "Last", "On"].map((cell) => h("th", {scope: "col"}, cell)))),
|
||||
h("tbody", {}, rows.map(scheduleLine))));
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {HTMLElement} the Schedules panel: the reconciler's last run once in the header, one chip per source and one table of
|
||||
* every first-party row, hub timer, Claude task and System timer.
|
||||
*/
|
||||
function schedulesContent() {
|
||||
const {rows, host} = state.schedules;
|
||||
const others = host.rows.filter((row) => row.owner !== "skills");
|
||||
return h("div", {class: "stack sched"},
|
||||
h("ul", {class: "sched-list", "aria-label": "Switchable"}, Object.keys(SCHEDULE_ROWS).map((name) => scheduleRow(name, rows[name]))),
|
||||
host.at === null
|
||||
? h("p", {class: "muted"}, "The host has not listed its timers and hooks yet: ", h("code", {}, SCHEDULE_START), copyButton(SCHEDULE_START))
|
||||
: h("div", {}, h("h3", {}, "Other timers and hooks"), h("p", {class: "muted"}, "Seen ", when(host.at), "; the hub never switches these."),
|
||||
h("ul", {class: "sched-list", "aria-label": "Read only"}, others.map(scheduleForeign))));
|
||||
const box = h("div", {class: "stack sched"});
|
||||
const draw = () => {
|
||||
const at = state.schedules.host.at;
|
||||
const head = at === null
|
||||
? h("p", {class: "muted"}, "The host has not listed its timers and tasks yet: ", h("code", {}, SCHEDULE_START), copyButton(SCHEDULE_START))
|
||||
: h("p", {class: "muted sched-head"}, "Reconciler ran ", when(at));
|
||||
box.replaceChildren(h("div", {class: "row sched-bar"}, scheduleChips(draw), head), scheduleTable());
|
||||
};
|
||||
draw();
|
||||
return box;
|
||||
}
|
||||
|
||||
function schedulesPanel() {
|
||||
|
||||
@@ -163,6 +163,7 @@
|
||||
bubbles: settings.bubbles,
|
||||
rates: settings.rates,
|
||||
undo: undo.value(),
|
||||
match: settings.match,
|
||||
};
|
||||
if (await saveSettings(next)) {
|
||||
closeSheet();
|
||||
|
||||
@@ -210,7 +210,7 @@
|
||||
stage3d("tasks", dom.stage);
|
||||
}
|
||||
const q = taskView.q.trim().toLowerCase();
|
||||
const sig = JSON.stringify([state.tasks, operatorItems().map((item) => [item.id, item.title, item.blocked]), state.jobs, state.task_edges, state.queue_line, Kanban.queueSig(state.queue_jobs), settings.estimation, settings.trend, taskView.filter, taskView.sort, taskView.descending, taskView.forecast, taskView.scope, q, waitingCount(), Math.floor(nowSeconds() / 60)]);
|
||||
const sig = JSON.stringify([state.tasks, operatorItems().map((item) => [item.id, item.title, item.blocked]), state.jobs, state.task_edges, state.queue_line, Kanban.queueSig(state.queue_jobs), state.beats, state.runner, settings.estimation, settings.trend, taskView.filter, taskView.sort, taskView.descending, taskView.forecast, taskView.scope, q, waitingCount(), Math.floor(nowSeconds() / 60)]);
|
||||
if (sig === taskView.sig) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
const USAGE_GROUPS = [["skill", "Skill"], ["tool", "Tool"], ["subagent", "Subagent"], ["repo", "Repository"], ["model", "Model"], ["agent", "Agent"], ["account", "Account"], ["hour", "Hour"], ["day", "Day"]];
|
||||
const USAGE_PERIODS = [[3600, "Last hour"], [86400, "Last 24 h"], [7 * 86400, "Last 7 days"], [30 * 86400, "Last 30 days"], [90 * 86400, "Last 90 days"]];
|
||||
const USAGE_COUNTS = [["input", "Input"], ["output", "Output"], ["cache_read", "Cache read"], ["cache_write", "Cache write"], ["total", "Total"]];
|
||||
const USAGE_COLUMNS = [["key", "Name"], ...USAGE_COUNTS, ["share", "Share"], ["cost", "Est. $"], ["hit_rate", "Cache hit rate"]];
|
||||
const USAGE_EMPTY = {skill: "(no skill)", tool: "(text only)", subagent: "(main thread)", repo: "(no repository)", model: "(no model)", agent: "(no agent)", account: "(unmapped)"};
|
||||
const USAGE_SPANS = {hour: 3600, day: 86400};
|
||||
const USAGE_CONTEXT = ["Day", "Agent", "Turns", "Median", "p90", "Compactions"];
|
||||
const usageView = {data: null, ask: 0, body: null, controls: null, group: "skill", period: 86400, span: null, filters: {}, sort: {key: "total", down: true}};
|
||||
const usageCount = (value) => Resources.compact(value);
|
||||
const usageDay = new Intl.DateTimeFormat("en-GB", {dateStyle: "medium", timeZone: "UTC"});
|
||||
const usageTime = (t, group) => (group === "day" ? usageDay : absolute).format(stampOf(t));
|
||||
|
||||
function usagePanel() {
|
||||
const group = h("select", {class: "field use-select", "aria-label": "Group by", title: "Group the tokens by one dimension", "data-usage-group": "", on: {change: () => usageGroup(group.value)}},
|
||||
USAGE_GROUPS.map(([value, label]) => h("option", {value}, label)));
|
||||
const period = h("select", {class: "field use-select", "aria-label": "Period", title: "The period the tokens fall in", "data-usage-period": "", on: {change: () => usagePeriod(Number(period.value))}},
|
||||
USAGE_PERIODS.map(([value, label]) => h("option", {value: String(value)}, label)));
|
||||
const body = h("div", {class: "use-body"});
|
||||
usageView.body = body;
|
||||
usageView.controls = {group, period};
|
||||
const panel = h("section", {class: "card res-panel res-usage", "data-panel": "resources-usage", "aria-label": "Usage"},
|
||||
h("div", {class: "res-head", "data-legend-slot": ""}, h("span", {class: "res-title", title: "Usage", "aria-label": "Usage"}, icon("bi-pie-chart")), h("span", {class: "acc-title"}, "Usage"), h("span", {class: "spacer"}), group, period), body);
|
||||
return {panel, body};
|
||||
}
|
||||
|
||||
function usageGroup(group) {
|
||||
usageView.group = group;
|
||||
fetchUsage();
|
||||
}
|
||||
|
||||
function usagePeriod(seconds) {
|
||||
usageView.period = seconds;
|
||||
usageView.span = null;
|
||||
fetchUsage();
|
||||
}
|
||||
|
||||
function usageQuery() {
|
||||
const span = usageView.span || {since: Math.floor(nowSeconds() - usageView.period), until: null};
|
||||
const pairs = [["group", usageView.group], ["since", String(span.since)], ...(span.until === null ? [] : [["until", String(span.until)]]), ...Object.entries(usageView.filters)];
|
||||
return pairs.map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`).join("&");
|
||||
}
|
||||
|
||||
async function fetchUsage() {
|
||||
usageView.ask += 1;
|
||||
const ask = usageView.ask;
|
||||
try {
|
||||
const response = await fetch(`/api/usage?${usageQuery()}`, {cache: "no-store"});
|
||||
if (response.ok && ask === usageView.ask) {
|
||||
usageView.data = await response.json();
|
||||
}
|
||||
} catch {
|
||||
ui.offline = true;
|
||||
}
|
||||
if (ask === usageView.ask) {
|
||||
drawUsage();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param key - the clicked row's group key: a dimension's value, or the start of an hour or day.
|
||||
*/
|
||||
function usageDrill(key) {
|
||||
const group = usageView.group;
|
||||
if (Object.hasOwn(USAGE_SPANS, group)) {
|
||||
usageView.span = {since: key, until: key + USAGE_SPANS[group]};
|
||||
} else {
|
||||
usageView.filters = {...usageView.filters, [group]: key};
|
||||
}
|
||||
fetchUsage();
|
||||
}
|
||||
|
||||
function usageUnfilter(name) {
|
||||
if (name === "span") {
|
||||
usageView.span = null;
|
||||
} else {
|
||||
usageView.filters = Object.fromEntries(Object.entries(usageView.filters).filter(([key]) => key !== name));
|
||||
}
|
||||
fetchUsage();
|
||||
}
|
||||
|
||||
function usageSort(key) {
|
||||
usageView.sort = {key, down: usageView.sort.key === key ? !usageView.sort.down : key !== "key"};
|
||||
drawUsage();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param rows - /api/usage rows.
|
||||
* @returns the rows ordered by usageView.sort, a null value last in either direction.
|
||||
*/
|
||||
function usageSorted(rows) {
|
||||
const {key, down} = usageView.sort;
|
||||
return [...rows].sort((a, b) => {
|
||||
const left = a[key];
|
||||
const right = b[key];
|
||||
if (left === right) {
|
||||
return 0;
|
||||
}
|
||||
if (left === null || right === null) {
|
||||
return left === null ? 1 : -1;
|
||||
}
|
||||
const order = typeof left === "number" && typeof right === "number" ? left - right : String(left).localeCompare(String(right));
|
||||
return down ? -order : order;
|
||||
});
|
||||
}
|
||||
|
||||
function usageName(group, key) {
|
||||
if (Object.hasOwn(USAGE_SPANS, group)) {
|
||||
return usageTime(key, group);
|
||||
}
|
||||
return key === "" ? USAGE_EMPTY[group] : key;
|
||||
}
|
||||
|
||||
function usageCells(row) {
|
||||
const cost = row.cost === null ? "–" : `$${row.cost.toFixed(2)}`;
|
||||
return [
|
||||
...USAGE_COUNTS.map(([name]) => h("td", {"data-column": name}, usageCount(row[name]))),
|
||||
h("td", {"data-column": "share"}, row.share === null ? "–" : `${row.share} %`),
|
||||
h("td", {"data-column": "cost", title: row.cost === null ? "A model without a known price counts in this row" : ""}, cost),
|
||||
h("td", {"data-column": "hit_rate"}, row.hit_rate === null ? "–" : `${Math.round(row.hit_rate * 1000) / 10} %`),
|
||||
];
|
||||
}
|
||||
|
||||
function usageRow(row, group) {
|
||||
const press = (event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
usageDrill(row.key);
|
||||
}
|
||||
};
|
||||
const label = usageName(group, row.key);
|
||||
return h("tr", {class: "use-row", tabindex: 0, "data-key": String(row.key), title: `Show only ${label}`, on: {click: () => usageDrill(row.key), keydown: press}},
|
||||
h("td", {"data-column": "key"}, label), usageCells(row));
|
||||
}
|
||||
|
||||
function usageHead() {
|
||||
return h("tr", {}, USAGE_COLUMNS.map(([key, label]) => {
|
||||
const active = usageView.sort.key === key;
|
||||
return h("th", {scope: "col", "aria-sort": active ? (usageView.sort.down ? "descending" : "ascending") : "none"},
|
||||
h("button", {type: "button", class: "use-sort", "data-sort": key, title: `Sort by ${label}`, on: {click: () => usageSort(key)}}, label));
|
||||
}));
|
||||
}
|
||||
|
||||
function usageTable(data) {
|
||||
if (!data.rows.length) {
|
||||
return h("p", {class: "muted"}, "No tokens in this period and filter.");
|
||||
}
|
||||
return h("div", {class: "acc-scroll"}, h("table", {class: "acc-table use-table", "data-usage-table": ""},
|
||||
h("thead", {}, usageHead()),
|
||||
h("tbody", {}, usageSorted(data.rows).map((row) => usageRow(row, data.group))),
|
||||
h("tfoot", {}, h("tr", {class: "use-total"}, h("th", {scope: "row"}, "Total"), usageCells(data.total)))));
|
||||
}
|
||||
|
||||
function usageFilters() {
|
||||
const chip = (name, words) => h("button", {type: "button", class: "btn small soft use-filter", "data-filter": name, ...named(words, `Remove the filter ${words}`), on: {click: () => usageUnfilter(name)}}, h("span", {}, words), icon("bi-x-lg"));
|
||||
const chips = Object.entries(usageView.filters).map(([name, value]) => chip(name, `${name}: ${usageName(name, value)}`));
|
||||
if (usageView.span) {
|
||||
chips.push(chip("span", `from ${absolute.format(stampOf(usageView.span.since))}`));
|
||||
}
|
||||
return chips.length ? h("div", {class: "use-filters", role: "group", "aria-label": "Filters"}, chips) : null;
|
||||
}
|
||||
|
||||
function usageContext(list) {
|
||||
if (!list.length) {
|
||||
return null;
|
||||
}
|
||||
const size = (value) => (value === null ? "–" : usageCount(value));
|
||||
return h("div", {class: "use-context"}, h("span", {class: "acc-title"}, "Context per turn"), h("div", {class: "acc-scroll"}, h("table", {class: "acc-table use-table", "data-usage-context": ""},
|
||||
h("thead", {}, h("tr", {}, USAGE_CONTEXT.map((name) => h("th", {scope: "col"}, name)))),
|
||||
h("tbody", {}, list.map((row) => h("tr", {"data-day": row.day, "data-agent": row.agent},
|
||||
h("td", {}, usageTime(row.day, "day")), h("td", {}, row.agent), h("td", {}, String(row.turns)), h("td", {}, size(row.median)), h("td", {}, size(row.p90)), h("td", {}, String(row.compactions))))))));
|
||||
}
|
||||
|
||||
function usageContent(data) {
|
||||
if (data === null) {
|
||||
return [h("p", {class: "muted"}, "…")];
|
||||
}
|
||||
return [
|
||||
usageFilters(),
|
||||
usageTable(data),
|
||||
data.split ? h("p", {class: "muted use-note", "data-usage-split": ""}, "A message with several tools counts under each of them, so the shares can sum above 100 %.") : null,
|
||||
h("p", {class: "muted use-note", title: data.prices.source}, `Est. $ from the list prices of ${data.prices.date}; a model without a known price shows –.`),
|
||||
usageContext(data.context),
|
||||
].filter(Boolean);
|
||||
}
|
||||
|
||||
function homeUsage() {
|
||||
homeFetch("usage", fetchUsage);
|
||||
return h("div", {class: "use-body"}, usageContent(usageView.data));
|
||||
}
|
||||
|
||||
function drawUsage() {
|
||||
const body = usageView.body;
|
||||
if (!body || !body.isConnected) {
|
||||
return;
|
||||
}
|
||||
usageView.controls.group.value = usageView.group;
|
||||
usageView.controls.period.value = String(usageView.period);
|
||||
body.replaceChildren(...usageContent(usageView.data));
|
||||
}
|
||||
@@ -11,7 +11,8 @@ const Plan = (() => {
|
||||
const DAY = 86400;
|
||||
const STALE_DAYS = 3;
|
||||
|
||||
const stale = (row, now) => !row.ended && typeof row.updated === "number" && now - row.updated >= STALE_DAYS * DAY;
|
||||
const staleFor = (row, now, days) => !row.ended && typeof row.updated === "number" && now - row.updated >= days * DAY;
|
||||
const stale = (row, now) => staleFor(row, now, STALE_DAYS);
|
||||
|
||||
function median(values) {
|
||||
const sorted = values.filter((value) => Number.isFinite(value)).sort((a, b) => a - b);
|
||||
@@ -332,7 +333,7 @@ const Plan = (() => {
|
||||
return keyed.map((entry) => entry.row);
|
||||
}
|
||||
|
||||
return {FORECASTS, ESTIMATIONS, TRENDS, SORTS, SERIES, TRENDED, STATUS_ORDER, STALE_DAYS, median, medians, forecastLength, bars, etas, stale, scoped, burn, steps, trend, finishes, lineAt, overlaySeries, overlayLabels, overlayTop, sortRows};
|
||||
return {FORECASTS, ESTIMATIONS, TRENDS, SORTS, SERIES, TRENDED, STATUS_ORDER, STALE_DAYS, median, medians, staleFor, forecastLength, bars, etas, stale, scoped, burn, steps, trend, finishes, lineAt, overlaySeries, overlayLabels, overlayTop, sortRows};
|
||||
})();
|
||||
if (typeof module === "object" && module.exports) {
|
||||
module.exports = Plan;
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
const Prune = (() => {
|
||||
"use strict";
|
||||
const {staleFor, STALE_DAYS} = typeof Plan === "object" ? Plan : require("./plan.js");
|
||||
const {marks} = typeof KanbanMarks === "object" ? KanbanMarks : require("./kanban-marks.js");
|
||||
const KIND = "prune";
|
||||
const ANNOUNCE = "announce";
|
||||
const APPLY = "prune";
|
||||
const MINUTE = 60;
|
||||
const MINUTES = {value: 10, min: 1, max: 60, page: 5};
|
||||
const DAYS = {min: 1, max: 999};
|
||||
|
||||
/**
|
||||
* @param rows - the hub's task rows.
|
||||
* @param sources - the mark sources of KanbanMarks.marks: {now, tasks, beats, runner}.
|
||||
* @param days - N: how many days without a register change make a task stale.
|
||||
* @returns the stale tasks, oldest change first: register tasks the operator may change (editable: open, no
|
||||
* operator/ or hotfix/ record) without a register change for N days and without a running mark.
|
||||
*/
|
||||
function stale(rows, sources, days) {
|
||||
const found = rows.filter((row) => row.editable && staleFor(row, sources.now, days) && !marks(row, sources).length);
|
||||
return found.sort((a, b) => a.updated - b.updated || a.task.localeCompare(b.task));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param tasks - the ticked task slugs.
|
||||
* @param days - N of the stale list.
|
||||
* @param since - the epoch the list was taken at; a register change after it keeps a task.
|
||||
* @param minutes - the answer window on the dial.
|
||||
* @returns the two items one passkey assertion signs: the announce job, run at once, and the rasci.py prune job,
|
||||
* which the runner holds back until the deadline since + minutes.
|
||||
*/
|
||||
function items(tasks, days, since, minutes) {
|
||||
const deadline = since + minutes * MINUTE;
|
||||
return [
|
||||
{kind: KIND, argv: [ANNOUNCE, "--days", String(days), "--deadline", String(deadline), ...tasks]},
|
||||
{kind: KIND, argv: [APPLY, "--since", String(since), ...tasks], not_before: deadline},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param jobs - the hub's runner jobs (state.jobs).
|
||||
* @param now - the hub's epoch seconds.
|
||||
* @returns the queued apply job of a signed prune nearest its deadline as {job, deadline, tasks, left}, left the whole
|
||||
* seconds until the deadline and never below 0; null without one.
|
||||
*/
|
||||
function pending(jobs, now) {
|
||||
const queued = jobs.filter((job) => job.kind === KIND && job.status === "queued" && typeof job.not_before === "number" && Array.isArray(job.argv) && job.argv[0] === APPLY);
|
||||
const next = queued.sort((a, b) => a.not_before - b.not_before)[0];
|
||||
return next ? {job: next.id, deadline: next.not_before, tasks: next.argv.slice(3), left: Math.max(0, Math.ceil(next.not_before - now))} : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param seconds - whole seconds left.
|
||||
* @returns them as m:ss.
|
||||
*/
|
||||
function clock(seconds) {
|
||||
return `${Math.floor(seconds / MINUTE)}:${String(seconds % MINUTE).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param text - what the operator typed in the days field.
|
||||
* @returns the whole number of days between DAYS.min and DAYS.max it names, else null.
|
||||
*/
|
||||
function daysOf(text) {
|
||||
const value = /^[0-9]{1,3}$/.test(text.trim()) ? Number(text.trim()) : NaN;
|
||||
return value >= DAYS.min && value <= DAYS.max ? value : null;
|
||||
}
|
||||
|
||||
return {KIND, MINUTE, MINUTES, DAYS, STALE_DAYS, stale, items, pending, clock, daysOf};
|
||||
})();
|
||||
if (typeof module === "object" && module.exports) {
|
||||
module.exports = Prune;
|
||||
}
|
||||
@@ -56,16 +56,39 @@
|
||||
.apply-list { flex: 1 1 260px; min-width: 0; }
|
||||
.apply-list > summary { font-weight: 600; cursor: pointer; }
|
||||
.apply-list ul { max-height: 40vh; margin: 8px 0 0; overflow: auto; }
|
||||
@media (prefers-reduced-motion: reduce) { .tool-row, .switch, .switch::after { transition: none; } }
|
||||
.rule-fold > summary { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 6px 2px; list-style: none; cursor: pointer; }
|
||||
.rule-fold > summary::-webkit-details-marker { display: none; }
|
||||
.rule-fold > summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 6px; }
|
||||
.rule-fold-mark { transition: transform .15s; }
|
||||
.rule-fold[open] > summary .rule-fold-mark { transform: rotate(90deg); }
|
||||
.hub-rule-list > .row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
.hub-rule-list h3 { margin: 0; }
|
||||
.hub-rules { display: grid; gap: 4px; margin: 0; padding: 0; list-style: none; }
|
||||
.hub-rule { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; min-width: 0; padding: 7px 10px; border-radius: 9px; background: var(--panel); font-size: var(--fs-sm); }
|
||||
.hub-rule code { min-width: 0; overflow-wrap: anywhere; }
|
||||
.hub-rule-scope, .hub-rule-count, .hub-rule[data-on="false"] .hub-rule-pattern { color: var(--muted); }
|
||||
.hub-rule-count { font-variant-numeric: tabular-nums; }
|
||||
[data-live-count] { margin: 0; font-variant-numeric: tabular-nums; }
|
||||
@media (prefers-reduced-motion: reduce) { .tool-row, .switch, .switch::after, .rule-fold-mark { transition: none; } }
|
||||
.passkey-prompt { position: fixed; top: 18px; left: 50%; z-index: 60; width: min(440px, calc(100vw - 36px)); transform: translateX(-50%); }
|
||||
.sched-list { display: grid; gap: 6px; margin: 0; padding: 0; list-style: none; }
|
||||
.sched-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; padding: 8px 10px; border-radius: 9px; background: var(--panel); }
|
||||
.sched-row.off .sched-name { opacity: .6; }
|
||||
.sched-switch { display: inline-flex; align-items: center; gap: 8px; font-weight: 600; cursor: pointer; }
|
||||
.sched-name { overflow-wrap: anywhere; }
|
||||
.sched-hint { flex: 1 1 220px; min-width: 0; overflow-wrap: anywhere; }
|
||||
.sched-field { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.sched-hours { width: 5em; }
|
||||
.sched-times { width: 12em; max-width: 100%; }
|
||||
.sched-off { display: inline-flex; flex-wrap: wrap; align-items: center; gap: 6px; min-width: 0; }
|
||||
.sched-off code { overflow-wrap: anywhere; }
|
||||
.sched-bar { flex-wrap: wrap; gap: 6px 12px; }
|
||||
.sched-bar > .chips { margin-bottom: 0; }
|
||||
.sched-head { margin: 0; }
|
||||
.sched-table { min-width: 560px; }
|
||||
.sched-table tr.off th { opacity: .6; }
|
||||
.sched-cell[data-edit]:not([data-edit=""]) { cursor: text; }
|
||||
.sched-cell code { overflow-wrap: anywhere; }
|
||||
.sched-input { width: 100%; min-width: 10em; }
|
||||
.sched-on { white-space: nowrap; }
|
||||
.sched-on .btn { margin-left: 6px; }
|
||||
.queue-settings { display: flex; flex-wrap: wrap; gap: 8px 16px; }
|
||||
.queue-setting { display: inline-flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||
.queue-setting .field { width: 7em; max-width: 100%; }
|
||||
.queue-setting.staged .field { outline: 2px solid var(--warn, #b7791f); }
|
||||
.queue-tab .table-wrap { overflow-x: auto; max-width: 100%; }
|
||||
.queue-table { border-collapse: collapse; width: 100%; font-size: var(--fs-sm, 0.9em); }
|
||||
.queue-table th, .queue-table td { padding: 2px 6px; text-align: left; vertical-align: top; }
|
||||
.queue-waiting { display: flex; flex-direction: column; gap: 6px; padding: 0; margin: 0; list-style: none; }
|
||||
.queue-waiting .queue-job { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; min-width: 0; }
|
||||
.queue-waiting .queue-reason { flex: 1 1 12em; min-width: 0; overflow-wrap: anywhere; }
|
||||
.queue-start { padding: 0 6px; }
|
||||
@@ -15,6 +15,17 @@
|
||||
.kanban-card.pending { border-style: dashed; border-color: var(--accent); }
|
||||
.kanban-card:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
||||
.kanban-title { overflow-wrap: anywhere; }
|
||||
.kanban-card[data-mark] { position: relative; padding: 7px 9px; border-width: 2px; border-color: var(--mark); }
|
||||
.kanban-card[data-mark="queue"] { --mark: var(--accent); }
|
||||
.kanban-card[data-mark="agent"] { --mark: var(--ok); }
|
||||
.kanban-card[data-mark="hub"] { --mark: var(--info); }
|
||||
.kanban-card[data-mark]::after { content: ""; position: absolute; inset: -2px; border-radius: inherit; box-shadow: 0 0 12px 2px var(--mark); opacity: 0; pointer-events: none; animation: kanban-glow 3s ease-in-out infinite; }
|
||||
@keyframes kanban-glow { 0%, 100% { opacity: 0; } 50% { opacity: .6; } }
|
||||
@media (prefers-reduced-motion: reduce) { .kanban-card[data-mark]::after { animation: none; } }
|
||||
.kanban-marks { display: flex; flex-wrap: wrap; gap: 3px; min-width: 0; }
|
||||
.kanban-mark { max-width: 100%; padding: 0 6px; line-height: 18px; white-space: normal; overflow-wrap: anywhere; }
|
||||
.kanban-mark::before { display: none; }
|
||||
.kanban-mark[data-tone="accent"] { background: var(--accent-soft); color: var(--accent); }
|
||||
.kanban-handle { display: inline-flex; color: var(--muted); cursor: grab; }
|
||||
.kanban-pending, .kanban-wait { display: inline-flex; color: var(--accent); }
|
||||
.kanban-stale { display: inline-flex; align-items: center; gap: 2px; }
|
||||
@@ -50,3 +61,12 @@ svg .burn-finish-line { fill: none; stroke: var(--c); stroke-width: 2; stroke-da
|
||||
svg .burn-finish-end { fill: var(--c); }
|
||||
svg.burn .k-fixed, .burn-key.k-fixed { --c: var(--violet); }
|
||||
svg.burn .k-growing, .burn-key.k-growing { --c: var(--teal); }
|
||||
.prune-chip { font-variant-numeric: tabular-nums; }
|
||||
.prune-dialog .prune-days { display: inline-flex; align-items: center; gap: var(--sp-2); }
|
||||
.prune-dialog .prune-days .field { width: 6ch; }
|
||||
.prune-list { display: grid; gap: var(--sp-1); max-height: 40vh; margin: 0; padding: 0; overflow-y: auto; list-style: none; }
|
||||
.prune-list li { min-width: 0; }
|
||||
.prune-list label.check { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; }
|
||||
.prune-list .task-id { overflow-wrap: anywhere; }
|
||||
.prune-wait { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-3); }
|
||||
.prune-wait .prune-left { font-size: var(--fs-lg); font-variant-numeric: tabular-nums; }
|
||||
@@ -12,7 +12,12 @@
|
||||
.match-peeks { display: flex; flex-wrap: wrap; gap: var(--sp-1); min-width: 0; }
|
||||
.match-peek { display: inline-flex; align-items: center; gap: 6px; max-width: 100%; min-width: 0; padding: 4px 10px 4px 4px; border: 1px solid var(--line); border-radius: 999px; background: var(--panel); color: inherit; font: inherit; font-size: var(--fs-sm); cursor: pointer; }
|
||||
.match-peek[data-stale="true"] { border-color: var(--bad); }
|
||||
.match-peek[data-blocked], .match-card.front[data-blocked] { filter: grayscale(1); opacity: 0.62; }
|
||||
.match-peek[data-blocked], .match-card.front[data-blocked] > :not(.match-stamp) { filter: grayscale(1); opacity: 0.62; }
|
||||
.match-stamp { position: absolute; top: 50%; left: 50%; z-index: 3; padding: 4px 14px; border: 4px solid currentColor; border-radius: 12px; background: color-mix(in srgb, var(--panel) 75%, transparent); font-size: 1.9rem; font-weight: 800; letter-spacing: 0.08em; transform: translate(-50%, -50%) rotate(-8deg); pointer-events: none; }
|
||||
.match-stamp[data-stamp="running"] { color: var(--info); }
|
||||
.match-stamp[data-stamp="queued"] { color: var(--warn); }
|
||||
.match-stamp[data-stamp="stale"], .match-stamp[data-stamp="blocked"] { color: var(--muted); }
|
||||
.match-stamp[data-stamp="expired"] { color: var(--bad); pointer-events: auto; cursor: help; }
|
||||
.match-blocked { display: flex; align-items: center; gap: 6px; margin: 0 0 var(--sp-2); color: var(--muted); font-size: var(--fs-sm); }
|
||||
.match-peek .match-peek-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
|
||||
.match-deck { position: relative; isolation: isolate; display: grid; grid-template-rows: minmax(0, 1fr); min-height: 0; padding-top: 24px; overflow-x: clip; }
|
||||
@@ -59,6 +64,7 @@
|
||||
.match-where { display: inline-flex; align-items: center; gap: 5px; max-width: 100%; min-width: 0; padding: 2px 10px; border: 1px solid var(--line); border-radius: 999px; background: color-mix(in srgb, var(--panel) 80%, transparent); color: var(--muted); font: inherit; font-size: var(--fs-sm); cursor: copy; }
|
||||
.match-where span { overflow: hidden; font-family: var(--mono); text-overflow: ellipsis; white-space: nowrap; }
|
||||
.match-where:hover { border-color: var(--line-strong); color: var(--text); }
|
||||
a.match-where { text-decoration: none; cursor: pointer; }
|
||||
.match-where[data-place="branch"] { border-color: color-mix(in srgb, var(--accent) 35%, transparent); background: var(--accent-soft); color: var(--accent); font-weight: 650; }
|
||||
.match-title { margin: 0; font-size: var(--fs-md); overflow-wrap: anywhere; }
|
||||
.match-stale { display: flex; align-items: center; gap: 6px; margin: 0; color: var(--bad); font-size: var(--fs-sm); }
|
||||
@@ -101,8 +107,29 @@ table.diff tr.match-mark td, table.diff tr.match-comment td { padding: 4px 10px;
|
||||
.match-confetti { position: absolute; inset: 0; pointer-events: none; }
|
||||
.match-confetti i { position: absolute; top: -12px; left: var(--x); width: 9px; height: 14px; border-radius: 2px; background: hsl(var(--c) 85% 60%); animation: match-confetti 1.4s ease-in var(--d) forwards; opacity: 0; }
|
||||
@keyframes match-confetti { 0% { opacity: 1; transform: translateY(0) rotate(0); } 100% { opacity: 0; transform: translateY(70vh) rotate(var(--r)); } }
|
||||
.match-glass { display: inline-grid; place-items: center; padding: 0; border: 0; background: none; color: var(--accent); cursor: pointer; }
|
||||
.match-glass.small { width: 22px; height: 28px; }
|
||||
.match-glass.large { width: 72px; height: 96px; margin-bottom: var(--sp-2); }
|
||||
.match-glass:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; border-radius: 6px; }
|
||||
.match-glass-face { width: 100%; height: 100%; overflow: visible; animation: match-flip 0.6s ease-out; }
|
||||
.match-glass-frame { fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; }
|
||||
.match-glass-top, .match-glass-bottom { fill: currentColor; opacity: 0.85; transform-box: fill-box; transform-origin: 50% 100%; }
|
||||
.match-glass-top { animation: match-drain var(--match-refresh) linear forwards; }
|
||||
.match-glass-bottom { animation: match-fill var(--match-refresh) linear forwards; }
|
||||
.match-grain { fill: currentColor; opacity: 0; animation: match-grain 0.9s linear infinite; }
|
||||
.match-grain[data-grain="1"] { animation-delay: 0.3s; }
|
||||
.match-grain[data-grain="2"] { animation-delay: 0.6s; }
|
||||
@keyframes match-flip { from { transform: rotate(180deg); } to { transform: rotate(0deg); } }
|
||||
@keyframes match-drain { from { transform: scaleY(1); } to { transform: scaleY(0.05); } }
|
||||
@keyframes match-fill { from { transform: scaleY(0.15); } to { transform: scaleY(1); } }
|
||||
@keyframes match-grain { 0% { opacity: 1; transform: translateY(0); } 90% { opacity: 1; } 100% { opacity: 0; transform: translateY(11px); } }
|
||||
.match-refresh-sheet { display: grid; justify-items: center; gap: var(--sp-2); }
|
||||
.match-refresh-sheet .sheet-foot { justify-self: stretch; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.match-card.front, .match-card.front .match-who .avatar, .match-confetti i { animation: none !important; }
|
||||
.match-glass-face, .match-glass-top, .match-glass-bottom, .match-grain { animation: none !important; }
|
||||
.match-glass-top { transform: scaleY(0.6); }
|
||||
.match-glass-bottom { transform: scaleY(0.5); }
|
||||
.match-act-face { transition: none; }
|
||||
}
|
||||
.match-open-overview { display: inline-flex; align-items: center; gap: 4px; }
|
||||
@@ -111,6 +138,7 @@ table.diff tr.match-mark td, table.diff tr.match-comment td { padding: 4px 10px;
|
||||
.match-release-card .match-body { display: grid; align-content: start; gap: var(--sp-2); }
|
||||
.match-release-card .match-title { display: inline-flex; align-items: center; gap: 8px; font-size: var(--fs-lg); }
|
||||
.match-release-hint { margin: 0; font-size: var(--fs-sm); }
|
||||
.match-release-held { margin: 0; display: inline-flex; align-items: center; gap: 6px; color: var(--bad); }
|
||||
.match-card.front.match-release-card[data-leaning="accept"]::after { content: "RELEASE"; }
|
||||
.match-card.front.match-release-card[data-leaning="reject"]::after { content: "NEXT"; color: var(--muted); }
|
||||
.match-overview .actions { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-1); }
|
||||
@@ -129,5 +157,5 @@ table.diff tr.match-mark td, table.diff tr.match-comment td { padding: 4px 10px;
|
||||
.match-body { padding: var(--sp-1) var(--sp-2) var(--sp-2); }
|
||||
.match-act-face { width: 64px; height: 64px; font-size: 1.7rem; }
|
||||
.match-later .match-act-face { width: 52px; height: 52px; font-size: 1.3rem; }
|
||||
.match-card.front[data-leaning]::after { font-size: 1.4rem; }
|
||||
.match-card.front[data-leaning]::after, .match-stamp { font-size: 1.4rem; }
|
||||
}
|
||||
@@ -5,7 +5,7 @@ body.fit .graph.resources > .res-panels { flex: 1; }
|
||||
.res-head { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 12px; min-width: 0; color: var(--muted); font-size: var(--fs-xs); }
|
||||
.res-title { display: inline-flex; color: var(--text); font-size: var(--fs-md); }
|
||||
.res-legend { display: flex; flex: 1; min-width: 0; font-variant-numeric: tabular-nums; }
|
||||
.res-switch[aria-pressed="true"] { background: var(--accent-soft); color: var(--accent); }
|
||||
.res-switch[aria-pressed="true"], .acc-switch[aria-pressed="true"] { background: var(--accent-soft); color: var(--accent); }
|
||||
.res-panels-menu { position: relative; }
|
||||
.res-panels-menu > summary { padding: 4px 10px; }
|
||||
.res-panels-menu .menu-box { gap: 2px; min-width: 11rem; padding: 6px; }
|
||||
@@ -20,10 +20,35 @@ body.fit .graph.resources > .res-panels { flex: 1; }
|
||||
.acc-table tr[data-active] td { background: var(--accent-soft); }
|
||||
.acc-table .pill { margin-left: 6px; }
|
||||
.acc-unassigned td { color: var(--muted); }
|
||||
.acc-left { display: flex; align-items: center; gap: 8px; }
|
||||
.acc-bar { position: relative; flex: 0 0 auto; width: 8rem; height: 10px; border-radius: 999px; background: var(--line); cursor: ew-resize; touch-action: none; --share: 0%; --fill: var(--ok); --forecast: 0%; }
|
||||
.acc-bar:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
|
||||
.acc-fill { position: absolute; inset: 0 auto 0 0; width: var(--share); border-radius: inherit; background: var(--fill); transition: width 160ms ease, background-color 160ms ease; }
|
||||
.acc-handle { position: absolute; top: 50%; left: var(--share); width: 14px; height: 14px; border: 2px solid var(--panel); border-radius: 50%; background: var(--fill); box-shadow: 0 0 0 1px var(--line-strong); transform: translate(-50%, -50%); transition: left 160ms ease; }
|
||||
.acc-forecast { position: absolute; top: -4px; bottom: -4px; left: var(--forecast); width: 2px; border-radius: 1px; background: var(--text); transform: translateX(-50%); }
|
||||
.acc-forecast[data-forecast="full"] { background: var(--bad); }
|
||||
.acc-bar[data-dragging] .acc-fill, .acc-bar[data-dragging] .acc-handle { transition: none; }
|
||||
@media (prefers-reduced-motion: reduce) { .acc-fill, .acc-handle { transition: none; } }
|
||||
.acc-form { display: grid; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); gap: var(--sp-2) var(--sp-3); }
|
||||
.acc-field { display: grid; gap: 4px; font-size: var(--fs-sm); }
|
||||
.acc-pair { display: flex; gap: 6px; }
|
||||
.acc-pair > * { flex: 1; min-width: 0; }
|
||||
.res-usage { flex: 0 1 auto; min-height: 0; overflow: visible; }
|
||||
.use-select { width: auto; max-width: 100%; padding: 2px 8px; font-size: var(--fs-sm); }
|
||||
.use-body { display: grid; gap: var(--sp-2); min-width: 0; }
|
||||
.use-filters { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.use-filter { display: inline-flex; align-items: center; gap: 6px; max-width: 100%; }
|
||||
.use-filter > span { overflow: hidden; text-overflow: ellipsis; }
|
||||
.use-table td:not(:first-child), .use-table th:not(:first-child) { text-align: right; }
|
||||
.use-table tfoot th, .use-table tfoot td { font-weight: 650; border-top: 1px solid var(--line-strong); }
|
||||
.use-sort { padding: 0; border: 0; background: none; color: inherit; font: inherit; cursor: pointer; }
|
||||
.use-sort:focus-visible, .use-row:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
th[aria-sort="descending"] .use-sort::after { content: " \2193"; }
|
||||
th[aria-sort="ascending"] .use-sort::after { content: " \2191"; }
|
||||
.use-row { cursor: pointer; }
|
||||
.use-row:hover td { background: var(--accent-soft); }
|
||||
.use-note { margin: 0; font-size: var(--fs-xs); }
|
||||
.use-context { display: grid; gap: 4px; }
|
||||
.res-plot { position: relative; flex: 1; min-height: 0; }
|
||||
.res-plot > svg { position: absolute; inset: 0; width: 100%; height: 100%; }
|
||||
svg .band.idle { fill: var(--ok-soft); }
|
||||
@@ -44,6 +69,23 @@ svg .res-icon.hung { fill: var(--violet); pointer-events: none; }
|
||||
svg .res-icon.asleep, svg .res-icon.unknown { fill: var(--muted); }
|
||||
svg .res-bar { fill: var(--c); }
|
||||
svg .res-bar.faint { opacity: 0.35; }
|
||||
.res-limits { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; min-width: 0; font-size: var(--fs-xs); }
|
||||
.res-limits .segmented button { padding: 2px 8px; font-size: var(--fs-xs); }
|
||||
.limit-note { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.limit-error { margin: 0; color: var(--bad); }
|
||||
.limits-table { border-collapse: collapse; font-size: var(--fs-sm); font-variant-numeric: tabular-nums; }
|
||||
.limits-table th, .limits-table td { padding: 3px 6px; border-bottom: 1px solid var(--line); text-align: left; white-space: nowrap; }
|
||||
svg .res-limit { cursor: pointer; outline: none; }
|
||||
svg .res-limit.lower { --c: var(--ok); }
|
||||
svg .res-limit.upper { --c: var(--warn); }
|
||||
svg .res-limit.stop { --c: var(--bad); }
|
||||
svg .res-limit.mayday { --c: var(--violet); }
|
||||
svg .res-limit-hit { stroke: transparent; stroke-width: 10; }
|
||||
svg .res-limit-mark { stroke: var(--c); stroke-width: 1.2; stroke-dasharray: 6 3; }
|
||||
svg .res-limit:hover .res-limit-mark, svg .res-limit:focus-visible .res-limit-mark { stroke-width: 2.4; }
|
||||
svg .res-limit text { fill: var(--c); font-size: var(--fs-2xs); }
|
||||
svg .res-target line { stroke: var(--text); stroke-width: 0.8; stroke-dasharray: 2 2; }
|
||||
svg .res-target text { fill: var(--muted); font-size: var(--fs-2xs); }
|
||||
.res-c0 { --c: var(--info); }
|
||||
.res-c1 { --c: var(--ok); }
|
||||
.res-c2 { --c: var(--accent); }
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
.rule-form .field, .settings .grid .field { width: 100%; min-width: 0; }
|
||||
.settings fieldset { min-width: 0; margin: 0; padding: 0; border: 0; }
|
||||
.settings legend { margin-bottom: var(--sp-2); padding: 0; color: var(--muted); font-size: var(--fs-sm); }
|
||||
.undo-dial { display: inline-grid; justify-items: center; gap: 4px; padding: 4px; border-radius: 50%; cursor: pointer; touch-action: none; }
|
||||
.undo-dial:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
|
||||
.dial { display: inline-grid; justify-items: center; gap: 4px; padding: 4px; border-radius: 50%; cursor: pointer; touch-action: none; }
|
||||
.dial:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
|
||||
.dial[aria-readonly="true"] { cursor: default; touch-action: auto; }
|
||||
.dial-face { width: 140px; height: 140px; }
|
||||
.dial-rim { fill: var(--sunken); stroke: var(--line-strong); stroke-width: 2; }
|
||||
.dial-tick { stroke: var(--muted); stroke-width: 1; }
|
||||
@@ -88,20 +89,49 @@ body.fit .spot-host { flex: none; }
|
||||
.composer-grid label + label { border-inline-start: 1px solid var(--line); }
|
||||
.composer-grid .composer-channel { min-width: max-content; }
|
||||
.composer-grid .field { flex: 1 1 auto; width: 100%; min-width: 0; border: 0; border-radius: 0; background: transparent; }
|
||||
.composer textarea { min-height: 64px; }
|
||||
.composer [hidden] { display: none; }
|
||||
.composer .mic-frame { --composer-radius: 10px; --composer-edge: 1px; border-width: var(--composer-edge); border-radius: var(--composer-radius); }
|
||||
.composer .mic-area { container: composer-foot / inline-size; }
|
||||
.composer textarea { min-height: 64px; max-height: calc(6lh + 16px); height: var(--composer-height, auto); overflow-y: auto; resize: none; field-sizing: content; }
|
||||
.composer [hidden], .composer .composer-status:empty { display: none; }
|
||||
.composer .composer-status { padding: 4px 12px 0; font-size: var(--fs-sm); }
|
||||
.composer .actions { flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 0; }
|
||||
.composer .mic-foot { flex-wrap: wrap; row-gap: 4px; }
|
||||
.composer .mayday-toggle { border-radius: 999px; }
|
||||
.composer .composer-foot { flex-wrap: nowrap; align-items: stretch; gap: 0; min-height: 36px; padding: 0; }
|
||||
.composer .composer-foot .ptt-split { display: contents; }
|
||||
.composer .composer-foot .ptt-menu { display: flex; align-self: stretch; }
|
||||
.composer .composer-foot :is(button, summary) { display: inline-flex; align-self: stretch; align-items: center; justify-content: center; gap: 6px; min-width: 0; min-height: 0; height: auto; margin: 0; padding: 0 12px; border: 0; border-radius: 0; box-shadow: none; white-space: nowrap; list-style: none; transform: none; transition: background-color 150ms ease, color 150ms ease; }
|
||||
.composer .composer-foot :is(button, summary):focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
|
||||
.composer .composer-foot > :is(button:first-child, .mayday-toggle), .composer .composer-foot .ptt { flex: 1 1 auto; }
|
||||
.composer .composer-foot > button:first-child { border-end-start-radius: calc(var(--composer-radius) - var(--composer-edge)); }
|
||||
.composer .composer-foot > .mayday-toggle { border-end-end-radius: calc(var(--composer-radius) - var(--composer-edge)); }
|
||||
.composer .composer-foot > :is(.mic-attach, .mic, .mayday-toggle), .composer .composer-foot .ptt-split > * { border-inline-start: 1px solid var(--line); }
|
||||
.composer .composer-foot > .mic[aria-pressed="true"] { animation: none; }
|
||||
.composer .composer-foot > :is(button:first-child, .mic)[aria-pressed="true"] > .bi { animation: mic-pulse 1.2s ease-in-out infinite; }
|
||||
.composer .composer-foot .ptt-more { padding-inline: 8px; }
|
||||
.composer .composer-foot .ptt-more::-webkit-details-marker { display: none; }
|
||||
.composer .mayday-toggle[aria-pressed="true"] { background: var(--bad); color: #fff; }
|
||||
.composer .ptt-split { display: inline-flex; }
|
||||
@container composer-foot (max-width: 480px) {
|
||||
.composer .cell-label { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .composer .composer-foot .bi { animation: none; } }
|
||||
[data-rec="busy"] > .bi { animation: presence-spin 1.2s linear infinite; }
|
||||
@media (prefers-reduced-motion: reduce) { [data-rec="busy"] > .bi { animation: none; } }
|
||||
.mic-area > .mayday-confirm { border-top: 1px solid var(--line); border-radius: 0; }
|
||||
.mic-chips { display: flex; flex-wrap: wrap; gap: 4px; min-width: 0; padding: 4px 8px; border-top: 1px solid var(--line); }
|
||||
.mic-chips[hidden] { display: none; }
|
||||
.mic-chip { display: inline-flex; align-items: center; gap: 4px; max-width: 100%; min-width: 0; padding: 2px 2px 2px 4px; border: 1px solid var(--line); border-radius: 999px; background: var(--sunken); font-size: var(--fs-sm); }
|
||||
.mic-chip > .mic-chip-thumb { flex: none; width: 24px; height: 24px; border-radius: 50%; object-fit: cover; }
|
||||
.mic-chip > .bi { flex: none; color: var(--muted); }
|
||||
.mic-chip-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.mic-chip-drop { display: inline-grid; flex: none; place-items: center; width: 22px; height: 22px; padding: 0; border: 0; border-radius: 50%; background: transparent; color: var(--muted); cursor: pointer; }
|
||||
.mic-chip-drop:hover { background: var(--hover); color: var(--text); }
|
||||
.mic-chip-drop:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
|
||||
@media (max-width: 640px) { .mic-chip-drop { width: 32px; height: 32px; } }
|
||||
.radio-home-radio-speak .composer { flex: 1 1 0; grid-template-rows: minmax(0, 1fr); min-height: 0; }
|
||||
.radio-home-radio-speak .mic-area { min-height: 0; }
|
||||
.radio-home-radio-speak .mic-area > textarea { flex: 1 1 0; min-height: 2rem; resize: none; }
|
||||
.ptt-split > .ptt { border-start-start-radius: 999px; border-end-start-radius: 999px; border-start-end-radius: 0; border-end-end-radius: 0; }
|
||||
.ptt-menu > summary.ptt-more { height: 100%; padding-inline: 6px; border-inline-start: 1px solid color-mix(in srgb, currentColor 30%, transparent); border-start-start-radius: 0; border-end-start-radius: 0; border-start-end-radius: 999px; border-end-end-radius: 999px; list-style: none; }
|
||||
.ptt-menu > summary.ptt-more::-webkit-details-marker { display: none; }
|
||||
.radio-home-radio-speak .mic-area > textarea { flex: 1 1 0; min-height: 2rem; max-height: none; resize: none; }
|
||||
.home-body:has(> .radio-home-radio-speak) { padding: 0; }
|
||||
.radio-home-radio-speak .composer .mic-frame { --composer-radius: 0px; --composer-edge: 0px; }
|
||||
.radio-home-radio-speak .composer .mic-frame:focus-within { outline-offset: -2px; }
|
||||
.mayday-confirm { display: flex; flex-wrap: wrap; align-items: center; gap: 6px var(--sp-2); padding: 6px 10px; border-radius: 10px; background: color-mix(in srgb, var(--bad) 14%, transparent); }
|
||||
.mayday-confirm > p { flex: 1 1 14em; margin: 0; font-size: var(--fs-sm); }
|
||||
.mayday-confirm > .actions { margin: 0 0 0 auto; }
|
||||
@@ -291,7 +321,7 @@ body.fit .spot-host { flex: none; }
|
||||
.radio-spot .radio-speak .composer-grid .field { padding-block: 2px; }
|
||||
.radio-spot .radio-speak .mic-area > textarea { height: 32px; min-height: 32px; }
|
||||
.radio-spot .radio-speak .mic-foot { min-height: 0; padding-block: 0; }
|
||||
.radio-spot .radio-speak .composer-status { flex: 1 1 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.radio-spot .radio-speak .composer-status { padding-block: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.radio-spot .radio-speak .composer { display: contents; }
|
||||
.radio-spot .radio-speak .composer > .mic-area { grid-area: 1 / 2 / 3; min-width: 0; }
|
||||
.radio-spot .radio-speak .voice-note { grid-area: 2 / 1; gap: 0 4px; width: min-content; }
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
const UsageBar = (() => {
|
||||
"use strict";
|
||||
const COLORS = {green: [0.72, 0.19, 145], yellow: [0.88, 0.18, 95], orange: [0.76, 0.17, 60], red: [0.63, 0.23, 27]};
|
||||
const STOPS = [[0, COLORS.green], [50, COLORS.yellow], [75, COLORS.orange], [100, COLORS.red]];
|
||||
const DAY = 86400000;
|
||||
const clamp = (value) => Math.min(100, Math.max(0, value));
|
||||
const tokensFrom = (entry, bound) => entry.hours.filter(([t]) => t * 1000 >= bound).reduce((sum, [, tokens]) => sum + tokens, 0);
|
||||
|
||||
/**
|
||||
* @param share - percent of the limit used.
|
||||
* @returns [l, c, h] in OKLCH, linear between the stops 0 green, 50 yellow, 75 orange and 100 red; a share
|
||||
* outside 0 to 100 takes the nearest end.
|
||||
*/
|
||||
function fillStop(share) {
|
||||
const at = clamp(share);
|
||||
const upper = STOPS.findIndex(([stop]) => stop >= at);
|
||||
const [to, high] = STOPS[upper];
|
||||
if (to === at) {
|
||||
return high;
|
||||
}
|
||||
const [from, low] = STOPS[upper - 1];
|
||||
const part = (at - from) / (to - from);
|
||||
return low.map((value, index) => value + (high[index] - value) * part);
|
||||
}
|
||||
|
||||
const css = ([l, c, h]) => `oklch(${l.toFixed(3)} ${c.toFixed(3)} ${h.toFixed(1)})`;
|
||||
const fillColor = (share) => css(fillStop(share));
|
||||
|
||||
/**
|
||||
* @param limit - the account's weekly token limit, a whole number from 0.
|
||||
* @param entry - the account's usage from /api/accounts: {total, hours: [[t, tokens]]}, t in epoch seconds.
|
||||
* @param calibration - {share, at} from /api/accounts, at in epoch seconds, or undefined.
|
||||
* @param last - the account's last reset, epoch milliseconds.
|
||||
* @returns {share, used, calibrated}: share the percent of the limit used since the last reset, the calibration's
|
||||
* share plus the tokens of the hours from its at when it is not older than the reset, else the tokens of the hours
|
||||
* from the reset; used the tokens that share stands for. An hour counts once its start is at or after the bound.
|
||||
*/
|
||||
function usage(limit, entry, calibration, last) {
|
||||
const calibrated = Boolean(calibration) && calibration.at * 1000 >= last;
|
||||
const counted = tokensFrom(entry, calibrated ? calibration.at * 1000 : last);
|
||||
const percent = limit > 0 ? (100 * counted) / limit : counted > 0 ? 100 : 0;
|
||||
const share = (calibrated ? calibration.share : 0) + percent;
|
||||
return {share, used: Math.round((share * limit) / 100), calibrated};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param limit - the account's weekly token limit, above 0.
|
||||
* @param entry - the account's usage as usage() takes it.
|
||||
* @param share - usage().share now.
|
||||
* @param now - epoch milliseconds.
|
||||
* @param next - the account's next reset, epoch milliseconds.
|
||||
* @returns {share, full}: share the percent expected at next when the tokens of the hours of the last 24 h keep
|
||||
* their rate; full the epoch milliseconds the share reaches 100 % when that comes before next, else null.
|
||||
*/
|
||||
function forecast(limit, entry, share, now, next) {
|
||||
const rate = (100 * tokensFrom(entry, now - DAY)) / limit / DAY;
|
||||
const full = share >= 100 ? now : rate > 0 ? now + (100 - share) / rate : Infinity;
|
||||
return {share: share + rate * (next - now), full: full < next ? full : null};
|
||||
}
|
||||
|
||||
return {COLORS, STOPS, fillStop, fillColor, css, usage, forecast};
|
||||
})();
|
||||
if (typeof module === "object" && module.exports) {
|
||||
module.exports = UsageBar;
|
||||
}
|
||||
Reference in new issue
Block a user