diff --git a/orchestrator/kvb_orchestrator/matching.py b/orchestrator/kvb_orchestrator/matching.py index 61dd40f..5fb951f 100644 --- a/orchestrator/kvb_orchestrator/matching.py +++ b/orchestrator/kvb_orchestrator/matching.py @@ -27,6 +27,27 @@ EXPIRED_REASONS = { } +HEADLINE = 120 + + +def headline(card: dict) -> dict: + """Args: + card: a Match card with its uncut title. + + Returns: + The card with title cut to at most HEADLINE characters at the last + word boundary (inside a single long word when there is none) and + ended by "…", plus title_full with the uncut title; unchanged when + the title fits. + """ + title = card["title"] + if len(title) <= HEADLINE: + return card + cut = title[: HEADLINE - 1] + space = cut.rstrip().rfind(" ") + return {**card, "title": f"{(cut[:space] if space > 0 else cut).rstrip()}…", "title_full": title} + + def expired_card(card: dict, expires: float) -> dict: """Args: card: the waiting_card() of an ask or decision lapsed_of() keeps. @@ -126,7 +147,7 @@ class Matching: for snapshot in store.listed(): if snapshot["id"] not in listed: store.remove(snapshot["id"]) - return {"now": now, "cards": cards} + return {"now": now, "cards": [headline(card) for card in cards]} def match_closed(self) -> dict: """Returns: diff --git a/orchestrator/templates/dial.js b/orchestrator/templates/dial.js index 2ccfca9..3296157 100644 --- a/orchestrator/templates/dial.js +++ b/orchestrator/templates/dial.js @@ -3,6 +3,9 @@ const Dial = (() => { const SIZE = 140; const RADIUS = 58; const TICKS = 60; + const READOUT = 24; + const MINUTE = 60; + const SECOND = 1000; /** * @param value - a value on the dial, min to max. @@ -57,7 +60,66 @@ const Dial = (() => { return Array.from({length: TICKS}, (_, at) => ({at, long: at % page === 0})); } - return {SIZE, RADIUS, TICKS, point, clamp, fromAngle, stepped, ticks}; + /** + * @param value - a value on the dial, fractions allowed. + * @param max - the value a full turn stands for. + * @returns the hand's angle from the top, clockwise, in degrees. + */ + function angle(value, max) { + return (value * 360) / max; + } + + /** + * @param seconds - seconds left, rounded up to whole seconds and never below 0. + * @returns them as m:ss, the readout of a clock that runs out. + */ + function countdown(seconds) { + const whole = Math.max(0, Math.ceil(seconds)); + return `${Math.floor(whole / MINUTE)}:${String(whole % MINUTE).padStart(2, "0")}`; + } + + /** + * @param epoch - a moment in epoch milliseconds. + * @returns its local time of day as HH:MM:SS, the readout of a wall clock. + */ + function wall(epoch) { + const at = new Date(epoch); + return [at.getHours(), at.getMinutes(), at.getSeconds()].map((part) => String(part).padStart(2, "0")).join(":"); + } + + /** + * @param until - the epoch seconds the clock runs out at. + * @param per - how many seconds one value of the dial stands for: 60 on a face of minutes, 1 on one of seconds. + * @returns (epoch milliseconds) => {at, value, text}: at the hand's exact place in dial values, value the whole + * values left rounded up, text the seconds left as m:ss; all three stop at 0. + */ + function counting(until, per) { + return (epoch) => { + const left = Math.max(0, until - epoch / SECOND); + return {at: left / per, value: Math.ceil(left / per), text: countdown(left)}; + }; + } + + /** + * @returns (epoch milliseconds) => {at, value, text}: a wall clock on a face of 60, its hand sweeping the seconds + * of the minute, value the whole second and text the local time of day as HH:MM:SS. + */ + function walled() { + return (epoch) => { + const at = new Date(epoch); + return {at: at.getSeconds() + at.getMilliseconds() / SECOND, value: at.getSeconds(), text: wall(epoch)}; + }; + } + + /** + * @param progress - how far a sweep is, 0 to 1. + * @returns the share of the way the hand has turned: fast at first, slowing into its place. + */ + function eased(progress) { + return 1 - (1 - progress) ** 3; + } + + return {SIZE, RADIUS, TICKS, READOUT, point, clamp, fromAngle, stepped, ticks, angle, countdown, wall, counting, walled, eased}; })(); if (typeof module === "object" && module.exports) { module.exports = Dial; diff --git a/orchestrator/templates/index.html.j2 b/orchestrator/templates/index.html.j2 index ca2df6d..0e4689a 100644 --- a/orchestrator/templates/index.html.j2 +++ b/orchestrator/templates/index.html.j2 @@ -85,7 +85,6 @@ h1 { margin: 0; font-size: var(--fs-lg); font-weight: 680; letter-spacing: -.01e .menu-box.end { right: 0; } .menu-box h3 { margin: 0; color: var(--muted); font-size: var(--fs-xs); font-weight: 650; letter-spacing: .04em; text-transform: uppercase; } .toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2) var(--sp-3); } -.classes { display: flex; flex-wrap: wrap; gap: var(--sp-1) var(--sp-3); } .updated { display: inline-flex; align-items: center; gap: 7px; color: var(--muted); font-size: var(--fs-sm); white-space: nowrap; } .updated::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--ok); box-shadow: 0 0 0 3px var(--ok-soft); } .updated.offline::before { background: var(--bad); box-shadow: 0 0 0 3px var(--bad-soft); } @@ -544,7 +543,7 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
- + diff --git a/orchestrator/templates/kanban-marks.js b/orchestrator/templates/kanban-marks.js index 20d216f..4aba58b 100644 --- a/orchestrator/templates/kanban-marks.js +++ b/orchestrator/templates/kanban-marks.js @@ -9,7 +9,7 @@ const KanbanMarks = (() => { const RUNNING = "running"; const RESPONSIBLE = "R"; const NOBODY = "-"; - const MARKS = [["queue", "bi-cpu", "accent"], ["agent", "bi-person-workspace", "ok"], ["hub", "bi-terminal", "info"]]; + const MARKS = [["queue", "bi-cpu"], ["agent", "bi-person-workspace"], ["hub", "bi-terminal"]]; /** * @param seconds - a span in seconds. @@ -72,13 +72,13 @@ const KanbanMarks = (() => { * @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 + * @returns the card's marks in MARKS order, each {key, icon, 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 MARKS.filter(([key]) => found[key]).map(([key, icon]) => ({key, icon, ...found[key]})); } return {BEAT_S, MARKS, span, head, marks}; diff --git a/orchestrator/templates/kanban.js b/orchestrator/templates/kanban.js index b2b4949..072102c 100644 --- a/orchestrator/templates/kanban.js +++ b/orchestrator/templates/kanban.js @@ -12,7 +12,6 @@ const Kanban = (() => { const QUEUE = "queue/"; const RUNNING = "run"; const QUEUE_LAYERS = [["line", "Queue line", "k-queue-line"], ["jobs", "Queue jobs", "k-queue-jobs"]]; - const CLASS_TONES = {hotfix: "bad", fix: "warn", feature: "info", main: "violet"}; const onBoard = (row) => !OFF.includes(row.kind); const laneOf = (prio) => (prio === null ? "unpinned" : prio >= FREE_FROM ? "p4" : `p${Math.max(prio, 1)}`); @@ -203,7 +202,7 @@ const Kanban = (() => { const running = job.position === RUNNING; const chips = [{key: "position", text: placeOf(job), hint: `${job.id}: ${running ? "granted, running now" : `grant position ${placeOf(job)}`}`, tone: "neutral"}]; if (job.class) { - chips.push({key: "class", text: job.class, hint: `${job.id}: class ${job.class}`, tone: CLASS_TONES[job.class]}); + chips.push({key: "class", text: job.class, hint: `${job.id}: class ${job.class}`, tone: "neutral"}); } if (job.prio !== null) { chips.push({key: "prio", text: `P${job.prio}`, hint: `${job.id}: its task is pinned P${job.prio}`, tone: "neutral"}); diff --git a/orchestrator/templates/limits.js b/orchestrator/templates/limits.js index 1098675..8618e26 100644 --- a/orchestrator/templates/limits.js +++ b/orchestrator/templates/limits.js @@ -6,7 +6,16 @@ const Limits = (() => { 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 SHOWN = [...LEVELS, "target"]; + const SHOWN_NAMES = {...LEVEL_NAMES, target: "target"}; + const MEANINGS = { + lower: "the floor of the band: while CPU and RAM sit below it the queue starts the next job, and the live target climbs 2 points per poll while memory pressure stays calm", + upper: "the queue starts no job whose footprint would lift the load above it; for RAM, swap, PSI and disk the watch warns above it, and a load above it drops the live target", + stop: "above it the live guard holds every new job and the watch calls stop; for disk it is the floor below which the queue starts nothing", + mayday: "the last alarm: above it the watch raises MAYDAY, for disk the critical alarm", + target: "the live AIMD target between lower and upper, read only: the queue admits a job only while the load plus its footprint stays within it; it climbs 2 points per calm poll and drops to the middle of lower and itself on overload, rising PSI or swap-out", + }; + 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)); @@ -79,7 +88,92 @@ const Limits = (() => { 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}; + /** + * @param level - one of SHOWN. + * @returns what the level means and does, led by its name, for the tooltips of its lines, its menu entry and its + * matrix column. + */ + function meaning(level) { + return `${SHOWN_NAMES[level]}: ${MEANINGS[level]}`; + } + + /** + * @param y - a y in the chart's coordinates. + * @param top - the y of 100 %. + * @param bottom - the y of 0 %. + * @returns the whole percent from 0 to 100 at y, the inverse of pixelOf(); a y beyond either edge gives that edge. + */ + function valueAt(y, top, bottom) { + return Math.min(100, Math.max(0, Math.round((1 - (y - top) / (bottom - top)) * 100))); + } + + /** + * @param value - a percent. + * @param top - the y of 100 %. + * @param bottom - the y of 0 %. + * @returns the y of value on the chart. + */ + function pixelOf(value, top, bottom) { + return top + (1 - value / 100) * (bottom - top); + } + + /** + * @param base - valid limits the staged values apply to. + * @param staged - {".": value} of the moved lines. + * @returns a copy of base with every staged value in place. + */ + function applied(base, staged) { + return Object.entries(staged).reduce((limits, [key, value]) => { + const [metric, level] = key.split("."); + return withValue(limits, metric, level, value); + }, base); + } + + /** + * @param next - limits with the staged values in place. + * @param staged - {".": value} of the moved lines. + * @returns the first order break of next as {metric, level, words}, level the staged line of the broken pair (its + * upper one when neither or both are staged) and words naming it; a staged value that is no percent breaks first; + * null without a break. + */ + function orderBreak(next, staged) { + for (const metric of METRICS) { + const bad = LEVELS.find((level) => Object.hasOwn(staged, `${metric}.${level}`) && !percent(next[metric][level])); + if (bad) { + return {metric, level: bad, words: `${NAMES[metric]} ${LEVEL_NAMES[bad]} is no percent from 0 to 100`}; + } + } + for (const metric of METRICS) { + const values = LEVELS.map((level) => next[metric][level]); + const index = values.findIndex((value, at) => at > 0 && !(values[at - 1] < value)); + if (index > 0) { + const [low, high] = [LEVELS[index - 1], LEVELS[index]]; + const level = !Object.hasOwn(staged, `${metric}.${high}`) && Object.hasOwn(staged, `${metric}.${low}`) ? low : high; + const words = level === low ? `must stay below ${LEVEL_NAMES[high]} ${values[index]} %` : `must stay above ${LEVEL_NAMES[low]} ${values[index - 1]} %`; + return {metric, level, words: `${NAMES[metric]} ${LEVEL_NAMES[level]} ${next[metric][level]} % breaks ${ORDER}: it ${words}`}; + } + } + return null; + } + + /** + * @param base - valid limits the lines show: those in force, or a profile while none is. + * @param held - the limits in force, null while the queue config applies. + * @param staged - {".": value} of the moved lines. + * @returns {next, changes, loose, broken}: next the limits Save would send; changes every staged value apart from + * base as {metric, level, from, to, kind}, kind tighter for a lower value and looser for a higher one; loose + * loosened() of next against held, so one passkey signature covers the whole batch once it is not empty; broken + * orderBreak(), which blocks Save. + */ + function review(base, held, staged) { + const next = applied(base, staged); + const changes = METRICS.flatMap((metric) => LEVELS.filter((level) => Object.hasOwn(staged, `${metric}.${level}`) && staged[`${metric}.${level}`] !== base[metric][level]) + .map((level) => ({metric, level, from: base[metric][level], to: next[metric][level], kind: next[metric][level] < base[metric][level] ? "tighter" : "looser"}))); + const broken = orderBreak(next, staged); + return {next, changes, loose: broken ? [] : loosened(next, held), broken}; + } + + return {METRICS, LEVELS, TARGETED, NAMES, LEVEL_NAMES, ORDER, SHOWN, SHOWN_NAMES, problem, loosened, withValue, profileOf, said, meaning, valueAt, pixelOf, applied, review}; })(); if (typeof module === "object" && module.exports) { module.exports = Limits; diff --git a/orchestrator/templates/page-agent.js b/orchestrator/templates/page-agent.js index 77c5038..e9fc05d 100644 --- a/orchestrator/templates/page-agent.js +++ b/orchestrator/templates/page-agent.js @@ -64,23 +64,6 @@ placePopup(); } - async function deliver(key, text, file, cls) { - let upload = ""; - if (file) { - if (file.size > UPLOAD_LIMIT) { - toast("File too large", [`${file.name}: at most 50 MiB`], false); - return false; - } - const stored = await send(`/api/uploads?name=${encodeURIComponent(file.name)}`, file, "application/octet-stream"); - if (!stored.ok || !stored.data) { - toast("Upload failed", [`${stored.status} ${stored.text}`.trim()], false); - return false; - } - upload = stored.data.id; - } - return message(nameOf(key), text, upload, cls); - } - function message(to, text, upload, cls) { return radioSend({to, text, upload, cls, voice: ""}); } @@ -89,22 +72,22 @@ const key = agentKey(who); const name = nameOf(key); const text = h("textarea", {"aria-label": `Message to ${name}`, placeholder: `Message to ${name} …`, "data-skills": ""}); - const file = h("input", {type: "file", class: "field", "aria-label": "Attach file"}); - const button = h("button", {type: "submit", class: "btn primary icon-only", ...named("Send")}, icon("bi-send")); - const classes = choice("to-one", TO_ONE, "post"); - const form = h("form", {class: "popup-form"}, micFrame(text, []), file, classes, - h("p", {class: "muted"}, "Post arrives at the end of the turn, Call at once with a read receipt; your passkey signs, verifiable with operator_message."), - h("div", {class: "actions"}, h("span", {class: "spacer"}), button)); + const button = h("button", {type: "submit", class: "btn primary small icon-only agent-send", ...named("Send", "Send: your passkey signs the message, verifiable with operator_message")}, icon("bi-send")); + const classes = choice("to-one", TO_ONE, "post", CHANNEL_HINTS); + const frame = micFrame(text, [classes]); + const foot = frame.querySelector(":scope > .mic-foot"); + foot.classList.add("agent-foot"); + foot.append(button); + const form = h("form", {class: "popup-form"}, frame); form.addEventListener("submit", async (event) => { event.preventDefault(); if (!text.value.trim()) { return; } button.disabled = true; - if (await deliver(key, text.value, file.files[0] || null, picked(classes))) { + if (await message(name, text.value, "", picked(classes))) { text.value = ""; text.dispatchEvent(new Event("input", {bubbles: true})); - file.value = ""; } button.disabled = false; }); diff --git a/orchestrator/templates/page-alerts.js b/orchestrator/templates/page-alerts.js index de32196..4284a09 100644 --- a/orchestrator/templates/page-alerts.js +++ b/orchestrator/templates/page-alerts.js @@ -101,7 +101,7 @@ for (const batch of state.pending) { if (!known.batches.has(batch.id)) { known.batches.add(batch.id); - const source = batch.source.startsWith("rule:") ? "Rule" : "Grant"; + const source = batch.source.startsWith("rule:") ? "Rule" : batch.items.every((item) => item.verb === "dismiss") ? "Delete" : "Grant"; undoToast(batch, `${source}: ${batch.items.map((item) => short(item.title)).join(", ")}`); } } diff --git a/orchestrator/templates/page-board.js b/orchestrator/templates/page-board.js index 5c1741b..d8a1f83 100644 --- a/orchestrator/templates/page-board.js +++ b/orchestrator/templates/page-board.js @@ -33,8 +33,15 @@ } } - function choice(name, options, picked) { - return h("div", {class: "classes", role: "radiogroup", "aria-label": "Class"}, options.map(([id, label]) => h("label", {class: "check"}, + /** + * @param {string} name the name of the radio group. + * @param {Array>} options [id, label] of each class, one segment each. + * @param {string} picked the id checked at first. + * @param {Object} hints the tooltip of each id: how that class delivers. + * @returns {HTMLElement} a small segmented switch of native radios. + */ + function choice(name, options, picked, hints) { + return h("div", {class: "segmented to-one", role: "radiogroup", "aria-label": "Class"}, options.map(([id, label]) => h("label", {title: hints[id] || label}, h("input", {type: "radio", name, value: id, checked: id === picked}), label))); } diff --git a/orchestrator/templates/page-bubbles.js b/orchestrator/templates/page-bubbles.js index 27542fb..4be2f2f 100644 --- a/orchestrator/templates/page-bubbles.js +++ b/orchestrator/templates/page-bubbles.js @@ -45,7 +45,7 @@ if (projected && inView(projected)) { return projected; } - for (const node of document.querySelectorAll(`[data-face="${CSS.escape(key)}"]`)) { + for (const node of document.querySelectorAll(`[data-face="${CSS.escape(key)}"]:not(#bubbles *)`)) { const box = node.getBoundingClientRect(); const shown = inView(box) ? clipsOf(node).reduce(clipped, box) : null; if (shown && inView(shown)) { @@ -56,8 +56,37 @@ } function bubbleNode(item) { - const words = h("span", {class: "bubble-words"}); - return {node: h("div", {class: "speech-bubble", "data-who": item.who}, h("strong", {class: "bubble-who"}, nameOf(item.who)), words), words}; + const words = h("span", {class: "bubble-words", "aria-hidden": "true"}); + const name = nameOf(item.who); + const skip = iconBtn("bi-x-lg", `Skip message from ${name}`, "bubble-skip", () => skipBubble(item), `Skip this message from ${name} and go on with the next`); + return {node: h("div", {class: "speech-bubble", "data-who": item.who}, h("span", {class: "bubble-head"}, face(item.who), h("strong", {class: "bubble-who"}, name), skip), words), words}; + } + + /** + * @param {object} item the read-aloud, silent, queued or quiet item whose docked bubble the operator closes. + */ + function skipBubble(item) { + const view = bubbles.shown.get(item); + bubbles.shown.delete(item); + if (bubbles.quiet.includes(item)) { + window.clearTimeout(item.timer); + bubbles.quiet = bubbles.quiet.filter((other) => other !== item); + } else if (speech.pending.includes(item)) { + speech.pending = speech.pending.filter((other) => other !== item); + } else if (speech.item === item && speech.timer) { + endSilent(); + drawSpeaker(); + pump(); + } else if (speech.item === item) { + const playing = speech.source; + Object.assign(speech, {item: null, current: null, source: null, loading: speech.loading === item ? null : speech.loading}); + if (playing) { + playing.stop(); + } + drawSpeaker(); + } + vanish(view && view.node); + drawBubbles(); } function placeBubble(view, box, scale) { diff --git a/orchestrator/templates/page-composer.js b/orchestrator/templates/page-composer.js index 2bc4b67..3a1fb36 100644 --- a/orchestrator/templates/page-composer.js +++ b/orchestrator/templates/page-composer.js @@ -55,10 +55,10 @@ * @returns {Promise} true on yes, false on Cancel or Escape; nothing leaves the page before. */ function inlineConfirm(form, question, yes) { - form.querySelectorAll(".mayday-confirm").forEach((node) => node.remove()); + form.querySelectorAll(".mayday-confirm").forEach((node) => vanish(node)); return new Promise((resolve) => { const done = (answer) => { - box.remove(); + vanish(box); resolve(answer); }; const accept = h("button", {type: "button", class: "btn small danger", on: {click: () => done(true)}}, yes); diff --git a/orchestrator/templates/page-console.js b/orchestrator/templates/page-console.js index 25c7eab..a4c0b98 100644 --- a/orchestrator/templates/page-console.js +++ b/orchestrator/templates/page-console.js @@ -42,6 +42,7 @@ view.out.textContent = text; } view.box.dataset.status = job.status; + view.line.classList.toggle("is-working", job.status === "running"); view.line.replaceChildren(status(job.status), h("span", {}, consoleWords(job))); } diff --git a/orchestrator/templates/page-constants.js b/orchestrator/templates/page-constants.js index fcf6022..788c9de 100644 --- a/orchestrator/templates/page-constants.js +++ b/orchestrator/templates/page-constants.js @@ -25,8 +25,9 @@ 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"], terminal: ["answered in the terminal", "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 Claude", "neutral"], claude: ["open in Claude", "info"], ended: ["session ended", "neutral"], decided: ["decided", "ok"], failed: ["failed", "bad"], refused: ["refused", "bad"], }; + const IN_CLAUDE_HINT = "Open in Claude: answer it there"; 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"]}; const SIGNS = {add: "+", del: "-", ctx: " ", meta: " "}; @@ -37,7 +38,7 @@ const MOVE = 2000; const RELAYOUT = 60000; const SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/; - const STORE = {views: "kvb-orchestrator.views", status: "kvb-orchestrator.status", comments: "kvb-orchestrator.match-comments", peeks: "kvb-orchestrator.match-peeks", wide: "kvb-orchestrator.match-wide", dropped: "kvb-orchestrator.match-dropped"}; + const STORE = {views: "kvb-orchestrator.views", status: "kvb-orchestrator.status", comments: "kvb-orchestrator.match-comments", peeks: "kvb-orchestrator.match-peeks", wide: "kvb-orchestrator.match-wide", dropped: "kvb-orchestrator.match-dropped", show: "kvb-orchestrator.match-show"}; const PRESENCE = { working: ["Working", "bi-gear-fill", "info"], alive: ["Alive", "bi-heart-pulse-fill", "ok"], diff --git a/orchestrator/templates/page-context.js b/orchestrator/templates/page-context.js index eb65ee4..93acfb0 100644 --- a/orchestrator/templates/page-context.js +++ b/orchestrator/templates/page-context.js @@ -1,5 +1,7 @@ - const ctxMenu = {node: null, back: null}; + const ctxMenu = {node: null, back: null, checks: []}; const CTX_FIELDS = ["INPUT", "TEXTAREA", "SELECT"]; + const CTX_ITEMS = '[role="menuitem"], [role="menuitemcheckbox"]'; + const CTX_MATCH = ".graph.match, .match-hidden"; const CTX_GAP = 8; const CTX_MODIFIERS = ["Shift", "Control", "Alt", "Meta"]; const CTX_OPENS = {task: "Open task", message: "Open message", artifact: "Open artifact"}; @@ -118,8 +120,8 @@ /** * @param target - the element the menu is for. - * @returns [{scope, title, items}]: the element's own items, then the current tab's, then the general ones; empty - * sections left out. + * @returns [{scope, title, items}]: the element's own items, inside Match its Show filter, then the current tab's, + * then the general ones; empty sections left out. */ function ctxSections(target) { const found = ctxFound(target); @@ -129,6 +131,7 @@ const tab = Nav.TABS.find(([id]) => id === Nav.tabOf(ui.screen)); return [ {scope: "element", title: own.title, items: own.items}, + {scope: "match-show", title: "Show", items: target.closest(CTX_MATCH) ? matchShowItems() : []}, ...(tab ? [{scope: tab[0], title: tab[1], items: items.filter((item) => item.scope === tab[0])}] : []), {scope: "general", title: "General", items: items.filter((item) => item.scope === "general")}, ].filter((section) => section.items.length); @@ -151,9 +154,19 @@ return ctxMenu.node; } + /** + * @param item - {label, hint, run, face}; with checked, a function telling whether it is ticked now, it is a + * checkbox whose click keeps the menu open. + * @returns the menu entry. + */ function ctxItem(item) { - return h("button", {type: "button", role: "menuitem", tabindex: -1, class: "ctx-item", title: revealed(item.hint), on: {click: () => ctxRun(item)}}, + const check = typeof item.checked === "function"; + const node = h("button", {type: "button", role: check ? "menuitemcheckbox" : "menuitem", tabindex: -1, class: "ctx-item", title: revealed(item.hint), ...(check ? {"aria-checked": String(item.checked())} : {}), on: {click: () => ctxRun(item)}}, check ? h("span", {class: "ctx-check", "aria-hidden": "true"}, icon("bi-check-lg")) : null, item.face ? face(item.face, false) : null, h("span", {class: "ctx-label"}, revealed(item.label)), h("span", {class: "muted"}, revealed(item.hint))); + if (check) { + ctxMenu.checks.push([node, item]); + } + return node; } function ctxGroup(section, index) { @@ -176,10 +189,11 @@ */ function ctxShow(sections, at) { const node = ctxNode(); + ctxMenu.checks = []; node.replaceChildren(...sections.flatMap(ctxGroup).filter(Boolean)); node.hidden = false; ctxPlace(node, at); - const first = node.querySelector('[role="menuitem"]'); + const first = node.querySelector(CTX_ITEMS); if (first) { first.focus({preventScroll: true}); } @@ -197,15 +211,22 @@ return; } const back = ctxMenu.back; - ctxMenu.back = null; - ctxMenu.node.hidden = true; - ctxMenu.node.replaceChildren(); + const node = ctxMenu.node; + Object.assign(ctxMenu, {back: null, node: null, checks: []}); + node.classList.add("closing"); + node.hidden = true; + vanish(node); if (restore && back && back.isConnected && typeof back.focus === "function") { back.focus({preventScroll: true}); } } function ctxRun(item) { + if (typeof item.checked === "function") { + item.run(); + ctxMenu.checks.forEach(([node, check]) => node.setAttribute("aria-checked", String(check.checked()))); + return; + } ctxClose(true); item.run(); } @@ -220,7 +241,7 @@ } function ctxKeys(event) { - const items = [...ctxMenu.node.querySelectorAll('[role="menuitem"]')]; + const items = [...ctxMenu.node.querySelectorAll(CTX_ITEMS)]; const at = items.indexOf(document.activeElement); const moves = {ArrowDown: at + 1, ArrowUp: Math.max(at, 0) - 1, Home: 0, End: items.length - 1}; if (Object.hasOwn(moves, event.key)) { diff --git a/orchestrator/templates/page-dial.js b/orchestrator/templates/page-dial.js index 198fd9a..5f58096 100644 --- a/orchestrator/templates/page-dial.js +++ b/orchestrator/templates/page-dial.js @@ -1,38 +1,86 @@ const DIAL_MAX = 60; const DIAL_PAGE = 5; + const DIAL_SWEEP = 200; /** * @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. + * readout: (value) => the text inside the face below the pivot; spoken: (value) => the aria-valuetext; readonly: true + * for a dial only the caller moves; live: null, or the source of a running clock, (epoch milliseconds) => {at, value, + * text} such as Dial.counting() or Dial.walled(), which then turns the hand and sets value and readout every frame. + * @returns {root, value, set}: an analog clock face with Dial.TICKS ticks, one hand and the readout, 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. The hand sweeps to each new value over DIAL_SWEEP ms and a live hand never stops; the frames end + * on the first one that finds the root out of the page, so the caller attaches the root in the same task. */ function dial(options) { - let current = options.value; + let current = null; + let shown = 0; + let sweep = {from: 0, to: 0, start: 0}; + let frame = 0; 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 hand = s("line", {class: "dial-hand", x1: centre, y1: centre}); + const hand = s("line", {class: "dial-hand", x1: centre, y1: centre, x2: centre, y2: fixed(centre - Dial.RADIUS + 14)}); + const readout = s("text", {class: "dial-readout", x: centre, y: centre + Dial.READOUT}); 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"}); + s("circle", {class: "dial-rim", cx: centre, cy: centre, r: Dial.RADIUS + 4}), ticks, readout, hand, s("circle", {class: "dial-pin", cx: centre, cy: centre, r: 4})); 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) => { - 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 = `${current} ${options.unit}`; - root.setAttribute("aria-valuenow", String(current)); - root.setAttribute("aria-valuetext", options.spoken(current)); + "aria-readonly": options.readonly || options.live ? "true" : null}, face); + const turn = (degrees) => { + shown = degrees; + hand.setAttribute("transform", `rotate(${degrees.toFixed(3)} ${centre} ${centre})`); }; - set(current); - if (options.readonly) { + const show = (value, words) => { + if (value === current && readout.textContent === words) { + return; + } + current = value; + readout.textContent = words; + root.setAttribute("aria-valuenow", String(value)); + root.setAttribute("aria-valuetext", options.spoken(value)); + }; + const running = () => { + const at = options.live(Date.now()); + turn(Dial.angle(Math.min(at.at, options.max), options.max)); + show(Dial.clamp(at.value, options), at.text); + }; + const step = (now) => { + frame = 0; + if (!root.isConnected) { + return; + } + if (options.live) { + running(); + } else { + const progress = Math.max(0, Math.min(1, (now - sweep.start) / DIAL_SWEEP)); + turn(sweep.from + (sweep.to - sweep.from) * Dial.eased(progress)); + if (progress === 1) { + return; + } + } + frame = window.requestAnimationFrame(step); + }; + const set = (next) => { + const value = Dial.clamp(next, options); + show(value, options.readout(value)); + sweep = {from: shown, to: Dial.angle(value, options.max), start: performance.now()}; + if (!frame) { + frame = window.requestAnimationFrame(step); + } + }; + if (options.live) { + running(); + frame = window.requestAnimationFrame(step); + } else { + const value = Dial.clamp(options.value, options); + show(value, options.readout(value)); + turn(Dial.angle(value, options.max)); + } + if (options.readonly || options.live) { return {root, value: () => current, set}; } const pointed = (event) => { @@ -68,5 +116,5 @@ */ 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}); + return dial({value, label, name: "undo-dial", min: 0, max: DIAL_MAX, page: DIAL_PAGE, readout: Dial.countdown, spoken, readonly: false, live: null}); } diff --git a/orchestrator/templates/page-diff.js b/orchestrator/templates/page-diff.js index 48e4e1e..c3c222e 100644 --- a/orchestrator/templates/page-diff.js +++ b/orchestrator/templates/page-diff.js @@ -219,8 +219,8 @@ if (picked.inline) { const box = h("div", {class: "match-comment-box"}, head, chips, words); const field = picked.anchor.tagName === "TR" ? h("tr", {class: "match-comment"}, h("td", {colspan: picked.anchor.children.length}, box)) : h("div", {class: "match-comment"}, box); - box.append(h("div", {class: "actions"}, btn("Cancel", "btn small ghost", () => field.remove()), saveButton("btn small primary", () => field.remove()))); - document.querySelectorAll("#sheet .match-comment").forEach((open) => open.remove()); + box.append(h("div", {class: "actions"}, btn("Cancel", "btn small ghost", () => vanish(field)), saveButton("btn small primary", () => vanish(field)))); + document.querySelectorAll("#sheet .match-comment").forEach((open) => vanish(open)); picked.anchor.after(field); } else { openSheet("Comment", [h("div", {class: "who"}, icon("bi-chat-left-text"), person(picked.to), head), h("p", {class: "muted"}, LINE_NOTES_GO), chips, words, diff --git a/orchestrator/templates/page-dom.js b/orchestrator/templates/page-dom.js index 84f742b..664588b 100644 --- a/orchestrator/templates/page-dom.js +++ b/orchestrator/templates/page-dom.js @@ -91,7 +91,7 @@ }; const presenceMark = (key, labelled) => { const value = presenceOf(key); - return value ? h("span", {class: "presence", "data-state": value, "data-tone": PRESENCE[value][2], role: "img", ...named(PRESENCE[value][0])}, icon(PRESENCE[value][1], "glyph"), labelled ? PRESENCE[value][0] : null) : null; + return value ? h("span", {class: value === "working" ? "presence is-working" : "presence", "data-state": value, "data-tone": PRESENCE[value][2], role: "img", ...named(PRESENCE[value][0])}, icon(PRESENCE[value][1], "glyph"), labelled ? PRESENCE[value][0] : null) : null; }; const presenceGlyph = (key, x, y, size) => { const value = presenceOf(key); @@ -127,11 +127,144 @@ }; const stamp = (life) => [life.born ? `🐣 ${life.born}` : "", life.died ? `🪦 ${life.died}` : ""].filter(Boolean).join(" · "); + /** + * @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 and undoToast() puts one in each countdown. + */ + 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)}))); + } + + const VANISH_MS = 180; + const VANISH_SLACK = 150; + const VANISH_EDGES = ["Top", "Bottom"]; + const VANISH_SIDES = ["Left", "Right"]; + + /** + * @param {Element} el an element in the page. + * @returns {Keyframe[]} its fade to opacity 0 from the opacity it shows now; an element in the flow also gives up its + * room: its height (its width when it is inline) with its margins and paddings along that axis. + */ + function vanishFrames(el) { + const look = window.getComputedStyle(el); + const from = {opacity: look.opacity}; + const to = {opacity: 0}; + if (look.position === "absolute" || look.position === "fixed" || look.display.startsWith("table")) { + return [from, to]; + } + const inline = look.display.startsWith("inline"); + const [size, edges] = inline ? ["width", VANISH_SIDES] : ["height", VANISH_EDGES]; + from[size] = `${el.getBoundingClientRect()[size]}px`; + to[size] = "0px"; + for (const edge of edges) { + for (const box of ["margin", "padding"]) { + from[`${box}${edge}`] = look[`${box}${edge}`]; + to[`${box}${edge}`] = "0px"; + } + } + return [from, to]; + } + + /** + * @param {Element|null} el the element to take out of the page. + * @param {Function} [then] runs once el has left the DOM. + * Fades el and collapses its room in VANISH_MS before it leaves the DOM; at once under prefers-reduced-motion and for + * a detached or unrendered el. A second call on an element already leaving does nothing. + */ + function vanish(el, then) { + if (!el || (el.dataset && el.dataset.vanishing)) { + return; + } + let gone = false; + const done = () => { + if (!gone) { + gone = true; + el.remove(); + if (then) { + then(); + } + } + }; + if (!el.isConnected || typeof el.animate !== "function" || !el.getClientRects().length || calm.matches) { + done(); + return; + } + el.dataset.vanishing = "true"; + el.style.overflow = "hidden"; + el.style.pointerEvents = "none"; + el.animate(vanishFrames(el), {duration: VANISH_MS, easing: "ease-in", fill: "forwards"}).finished.then(done, done); + window.setTimeout(done, VANISH_MS + VANISH_SLACK); + } + + const SWAP_KEYS = ["data-key", "data-item", "data-card", "data-task", "data-job", "data-ref"]; + const SWAP_KEYED = SWAP_KEYS.map((name) => `[${name}]`).join(", "); + const swapsDue = new WeakMap(); + + /** + * @param {Array} nodes elements and text. + * @returns {Set} the key of every keyed element in nodes and below them, as "attribute=value" of the first + * SWAP_KEYS attribute the element holds. + */ + function swapKeys(nodes) { + const keyed = nodes.filter((node) => node instanceof Element).flatMap((node) => [node, ...node.querySelectorAll(SWAP_KEYED)]).filter((node) => node.matches(SWAP_KEYED)); + return new Set(keyed.map((node) => { + const name = SWAP_KEYS.find((key) => node.hasAttribute(key)); + return `${name}=${node.getAttribute(name)}`; + })); + } + + /** + * @param {Element} box a container about to get new children. + * @param {Array} nodes the new children. + * @returns {boolean} whether a keyed element box shows now is missing from nodes, so it leaves the page; false + * without View Transitions, for a detached or unrendered box and while a field has the focus, whose typing a + * transition would freeze. + */ + function swapLeaves(box, nodes) { + if (!document.startViewTransition || !box.isConnected || !box.getClientRects().length) { + return false; + } + const field = document.activeElement; + if (field && field.matches("input, textarea, select, [contenteditable]")) { + return false; + } + const next = swapKeys(nodes); + return [...swapKeys([...box.children])].some((key) => !next.has(key)); + } + + /** + * @param {Element} box a visible container whose children a re-render replaces. + * @param {Array} nodes its new children. + * @param {Function} [around] called as around(box, swap) in place of swap(), for a keeper such as keepTyping() or for + * work that needs nodes in the page. + * @returns {Promise} settles once box holds nodes. When a keyed child leaves, the swap runs inside fadeTransition() + * so it fades out; else at once. Only the newest nodes given for box land, so a late transition never undoes a + * newer swap. + */ + function fadeSwap(box, nodes, around) { + swapsDue.set(box, nodes); + const swap = () => { + if (swapsDue.get(box) === nodes) { + box.replaceChildren(...nodes); + } + }; + const run = around ? () => around(box, swap) : swap; + if (!swapLeaves(box, nodes)) { + run(); + return Promise.resolve(); + } + return fadeTransition(run); + } + function toast(title, lines, good) { const box = h("div", {class: `toast${good ? "" : " bad"}`, role: "status", title: "Close"}, h("strong", {}, title), lines.length ? h("pre", {}, lines.join("\n")) : null); - box.addEventListener("click", () => box.remove()); + box.addEventListener("click", () => vanish(box)); document.getElementById("toasts").append(box); - window.setTimeout(() => box.remove(), good ? 9000 : 20000); + window.setTimeout(() => vanish(box), good ? 9000 : 20000); return box; } @@ -248,9 +381,13 @@ }); } + /** + * @param {Element|null} [keep] the menu a click landed in: it stays open, and so does every menu around it, such as + * the Tasks Actions menu holding Request choices. + */ function closeMenus(keep) { for (const menu of document.querySelectorAll(MENUS)) { - if (menu.open && menu !== keep) { + if (menu.open && menu !== keep && !(keep && menu.contains(keep))) { const inside = menu.contains(document.activeElement); menu.open = false; if (inside) { @@ -270,10 +407,25 @@ sheet.hidden = false; } + /** + * @param {HTMLElement} overlay a fixed overlay such as #sheet or #palette. + * Sets overlay hidden at once, so every check of its hidden flag sees it closed, while its boxes fade out through + * vanish(); the closing class keeps it drawn without taking clicks until the last box has left. + */ + function fadeShut(overlay) { + const shut = () => { + if (!overlay.children.length) { + overlay.classList.remove("closing"); + } + }; + overlay.classList.add("closing"); + overlay.hidden = true; + [...overlay.children].forEach((box) => vanish(box, shut)); + shut(); + } + function closeSheet() { - const sheet = document.getElementById("sheet"); - sheet.hidden = true; - sheet.replaceChildren(); + fadeShut(document.getElementById("sheet")); reviewDom = null; ui.review = null; } diff --git a/orchestrator/templates/page-home.js b/orchestrator/templates/page-home.js index b7aa937..b0e30aa 100644 --- a/orchestrator/templates/page-home.js +++ b/orchestrator/templates/page-home.js @@ -150,7 +150,7 @@ function homeBoard() { const board = kanbanBoard(shownTasks()); - homeView.heads.set("tasks/board", board.querySelector(".kanban-bar")); + homeView.heads.set("tasks/board", kanban.bar); return board; } @@ -649,7 +649,7 @@ const keys = new Set(pins.map(Panels.keyOf)); for (const [key, tile] of homeView.tiles) { if (!keys.has(key)) { - tile.remove(); + vanish(tile); homeView.tiles.delete(key); } } diff --git a/orchestrator/templates/page-inbox.js b/orchestrator/templates/page-inbox.js index 5597bdb..6504160 100644 --- a/orchestrator/templates/page-inbox.js +++ b/orchestrator/templates/page-inbox.js @@ -1,6 +1,95 @@ let inboxDoneOpen = false; const GONE_NOTICE = "already done or removed elsewhere"; const doneItem = (item) => Boolean(item.held || (item.job && !jobOpen(item.job))); + const REQUEST_CHIPS = [["open", "Open", "bi-play-circle"], ["expired", "Expired", "bi-hourglass-bottom"], ["stale", "Stale", "bi-exclamation-triangle"], ["failed", "Failed", "bi-x-octagon"], ["all", "All", "bi-list-check"]]; + const REQUEST_TONES = {open: "info", expired: "neutral", stale: "warn", failed: "bad"}; + const TRIAGE_FOOTER = "footer"; + const triage = {chip: "all", picked: new Map(), footer: false}; + + /** + * @param {Object} item a request of requestItems(). + * @returns {boolean} whether its hook stopped waiting, so the hub takes no answer for it: an expired ask or decision, + * or one whose dialog is open in Claude (claude), which counts as open. + */ + const dialogLapsed = (item) => item.request === "expired" || Boolean(item.claude); + + /** + * @returns {Object[]} every request the snapshot lists: the inbox and the lapsed asks and decisions, each with its + * request kind (open, expired, stale or failed); one open in Claude is open; a decision row already answered is none. + */ + const requestItems = () => [...state.inbox, ...(state.lapsed || [])].filter((item) => !item.answered); + const requestsOf = (chip) => requestItems().filter((item) => chip === "all" || item.request === chip); + const listedInbox = () => requestsOf(triage.chip).filter((item) => ui.snoozed || !item.until); + + /** + * @param {string} scope the chip the items are listed under, or TRIAGE_FOOTER for the Stream's stale requests. + * @param {Object[]} items the requests listed there. + * @returns {HTMLElement} the select-all checkbox and the "Delete N" button over items. The tick keeps the keys it saw, + * so a request that arrives later is never deleted with them; the box shows indeterminate until it is ticked again. + */ + function triagePicker(scope, items) { + const keys = items.map(keyOf); + const picked = (triage.picked.get(scope) || []).filter((key) => keys.includes(key)); + const chosen = items.filter((item) => picked.includes(keyOf(item))); + const redraw = () => (scope === TRIAGE_FOOTER ? drawStream() : drawInbox()); + const all = h("input", {type: "checkbox", class: "triage-all", checked: Boolean(keys.length) && picked.length === keys.length, disabled: !keys.length || ui.busy, ...named("Select all", `Select all ${keys.length} listed here`), on: {change: (event) => { + triage.picked.set(scope, event.target.checked ? keys : []); + redraw(); + }}}); + all.indeterminate = picked.length > 0 && picked.length < keys.length; + const hint = `Delete ${chosen.length}: dismissed in the hub for every browser, no agent gets a message; one passkey signature, then ${undoWords()}`; + const remove = h("button", {type: "button", class: "btn small danger triage-delete", disabled: !chosen.length || ui.busy, ...named(`Delete ${chosen.length}`, hint), on: {click: () => deleteRequests(scope, chosen)}}, icon("bi-trash"), `Delete ${chosen.length}`); + return h("div", {class: "triage-pick", "data-scope": scope}, h("label", {class: "check"}, all, "Select all"), remove); + } + + /** + * @param {string} scope the chip the items were picked under, or TRIAGE_FOOTER; the hub refuses a request of another + * kind than the chip, so an open one is deleted only from Open or All. + * @param {Object[]} items the requests to dismiss. + * @returns {Promise} whether the hub took the dismissal; its undo toast then runs, every browser drops them at + * its next poll and the undo brings them back. + */ + async function deleteRequests(scope, items) { + const entries = items.map((item) => ({kind: "dismiss", target: item.kind, id: item.id, scope: scope === TRIAGE_FOOTER ? item.request : scope})); + const label = `Delete ${items.length} ${items.length === 1 ? "request" : "requests"}`; + const names = new Map(items.map((item) => [item.id, short(item.title)])); + ui.busy = true; + const signed = await proofFor(entries, label, (result) => namedRefusal(result, label, names)); + if (signed === null) { + ui.busy = false; + await load(); + return false; + } + const result = await sendJson("/api/requests/dismiss", {items: entries, proof: signed.proof}); + ui.busy = false; + if (!result.ok || !result.data) { + if (!namedRefusal(result, label, names)) { + toast(`${label}: not possible`, fail(result), false); + } + await load(); + return false; + } + triage.picked.delete(scope); + known.batches.add(result.data.id); + undoToast(result.data, label); + await load(); + return true; + } + + /** + * @returns {HTMLElement} the request chips of Tasks → Operator, Open · Expired · Stale · Failed · All, each with its + * count and listing exactly its kind, and the select all and Delete N of the chosen chip. + */ + function triageBar() { + const chips = REQUEST_CHIPS.map(([id, label, name]) => { + const total = requestsOf(id).length; + return h("button", {type: "button", class: "chip", "data-request": id, "aria-pressed": String(triage.chip === id), ...named(`${label} ${total}`, `${label}: ${total} requests`), on: {click: () => { + triage.chip = id; + drawInbox(); + }}}, icon(name), label, counter(total)); + }); + return h("div", {class: "triage-bar"}, h("div", {class: "chips", role: "group", "aria-label": "Request kinds"}, chips), triagePicker(triage.chip, requestsOf(triage.chip))); + } function closeGone(result, keys, label) { if (result.status !== 404 || !keys.length) { @@ -42,7 +131,7 @@ } const status = typeof result.data.status === "string" ? result.data.status : "refused"; refusedIds.set(id, status); - toast(`${label}: not possible`, [`${(names && names.get(id)) || id}: ${status}. Change or drop its row, then release again.`], false); + toast(`${label}: not possible`, [`${(names && names.get(id)) || id}: ${status}`], false); return true; } @@ -98,6 +187,26 @@ * or "it takes effect at once" for 0. */ const undoWords = () => (settings.undo > 0 ? `${settings.undo} s remain to undo` : "it takes effect at once"); + const undoView = {box: null, live: new Map()}; + + /** + * @param {Object} entry a running undo window: {id, label, due, undo, left}. + * @returns {HTMLElement} its Undo entry for the Actions menu of the Tasks toolbar, with the seconds left; entry.left + * keeps that readout so the toast's timer ticks both. + */ + function undoItem(entry) { + entry.left = h("span", {class: "undo-left"}, `${Math.max(0, Math.ceil(entry.due - nowSeconds()))} s`); + return h("button", {type: "button", class: "btn small ghost", "data-key": `undo:${entry.id}`, ...named(`Undo: ${entry.label}`, `Undo ${entry.label}: possible until its undo window ends`), on: {click: entry.undo}}, + icon("bi-arrow-counterclockwise"), h("span", {class: "tool-word"}, "Undo"), h("span", {class: "undo-label"}, short(entry.label)), entry.left); + } + + function drawUndo() { + if (!undoView.box) { + return; + } + const entries = [...undoView.live.values()]; + fadeSwap(undoView.box, entries.length ? entries.map(undoItem) : [h("p", {class: "muted", "data-key": "undo:none"}, "Nothing to undo")]); + } function undoToast(batch, label) { if (!(batch.due > nowSeconds())) { @@ -107,28 +216,42 @@ } const left = h("span", {class: "muted"}); const button = h("button", {type: "button", class: "btn small", ...named("Undo")}, icon("bi-arrow-counterclockwise"), "Undo"); - const box = h("div", {class: "toast wait", role: "status"}, h("strong", {}, label), h("div", {class: "undo-row"}, left, h("span", {class: "spacer"}), button)); + const glass = h("span", {class: "undo-glass", "aria-hidden": "true"}, glassFace()); + glass.style.animationDuration = `${Math.max(0, batch.due - nowSeconds())}s`; + const box = h("div", {class: "toast wait", role: "status"}, h("strong", {}, label), h("div", {class: "undo-row"}, left, h("span", {class: "spacer"}), button, glass)); let timer = 0; + const entry = {id: batch.id, label, due: batch.due, undo: null, left: null}; + const settle = () => { + window.clearInterval(timer); + undoView.live.delete(batch.id); + drawUndo(); + }; const count = () => { const rest = Math.ceil(batch.due - nowSeconds()); if (rest <= 0) { - window.clearInterval(timer); - box.remove(); + settle(); + vanish(box); load(); return; } left.textContent = `takes effect in ${rest} s`; + if (entry.left) { + entry.left.textContent = `${rest} s`; + } }; - timer = window.setInterval(count, 250); - button.addEventListener("click", async () => { - window.clearInterval(timer); + entry.undo = async () => { + settle(); button.disabled = true; const result = await send(`/api/inbox/undo/${encodeURIComponent(batch.id)}`, "", "application/json"); - box.remove(); + vanish(box); toast(result.ok ? `Undone: ${label}` : "Too late: already in effect", result.ok ? [] : [`${result.status} ${result.text}`.trim()], result.ok); await load(); - }); + }; + timer = window.setInterval(count, 250); + button.addEventListener("click", entry.undo); + undoView.live.set(batch.id, entry); document.getElementById("toasts").append(box); + drawUndo(); count(); } @@ -311,7 +434,7 @@ } const key = keyOf(item); flip(key); - ui.cursor = Math.max(visibleInbox().findIndex((entry) => keyOf(entry) === key), 0); + ui.cursor = Math.max(listedInbox().findIndex((entry) => keyOf(entry) === key), 0); drawInbox(); drawGrant(); } @@ -412,7 +535,8 @@ function inboxItem(item, index) { const red = item.kind === "review" && item.gate !== "pass"; const wait = waitOf(item); - const actions = actionsFor(item); + const actions = dialogLapsed(item) ? [] : actionsFor(item); + const triaged = item.claude ? status("claude") : item.request && item.request !== "open" ? pill(item.request, REQUEST_TONES[item.request]) : null; const code = itemCode(item, actions); const classes = ["item", "entry", `k-${item.kind}`, "waiting", isGreen(item) ? "green" : "", red ? "red" : "", item.held ? "held" : "", wait ? "pending" : "", index === ui.cursor ? "cursor" : ""].filter(Boolean).join(" "); const done = doneItem(item); @@ -422,6 +546,7 @@ when(item.ts), wait ? h("span", {class: "wait-spin", role: "status", "aria-label": wait, title: wait}) : null, done ? pill("done", "ok") : null, + triaged, asked(item) ? pill("Decision", KIND_TONES.decision) : pill(ITEM_LABELS[item.kind], KIND_TONES[item.kind]), item.kind === "review" ? pill(item.gate === "pass" ? "Gate green" : "Gate red", item.gate === "pass" ? "ok" : "bad") : null, reviewsPill(item), @@ -439,7 +564,7 @@ code, item.job ? consoleOf(item.job) : null, item.kind === "rule" ? ruleRequestBody(item) : null, - choiceOf(item, () => {}), + dialogLapsed(item) ? null : choiceOf(item, () => {}), feedbackList(keyOf(item))), h("div", {class: "item-actions line-actions"}, code ? null : actions, @@ -459,7 +584,7 @@ if (!inboxDom) { return; } - const items = visibleInbox(); + const items = listedInbox(); ui.cursor = Math.min(ui.cursor, Math.max(items.length - 1, 0)); const present = new Set(items.map(keyOf)); for (const key of [...ui.selected]) { @@ -468,7 +593,8 @@ } } const mode = grantMode(); - const sig = JSON.stringify([mode, items.map(withoutOutput), [...ui.selected], [...choices], [...sending], ui.cursor, ui.snoozed, ui.busy, Math.floor(nowSeconds() / 60), diffView.version, state.messages.map((message) => message.id)]); + const requests = requestItems().map((item) => [keyOf(item), item.request]); + const sig = JSON.stringify([mode, items.map(withoutOutput), [...ui.selected], [...choices], [...sending], ui.cursor, ui.snoozed, ui.busy, Math.floor(nowSeconds() / 60), diffView.version, state.messages.map((message) => message.id), requests, triage.chip, [...triage.picked]]); if (sig === inboxSig) { repaintConsoles(items); return; @@ -479,12 +605,15 @@ ui.snoozed = event.target.checked; drawInbox(); }}}); - keepTyping(inboxDom, () => inboxDom.replaceChildren( + fadeSwap(inboxDom, [ h("div", {class: "inbox-head"}, h("h2", {class: "group-title"}, "Waits on Operator", counter(waitingCount())), h("span", {class: "spacer"}), hidden ? h("label", {class: "check"}, snoozed, `${hidden} snoozed`) : null), onLocalhost() ? "" : h("p", {class: "muted"}, "The passkey signs grants only under ", localLink()), - ...inboxRows(items))); - settleConsoles(items); + triageBar(), + ...inboxRows(items)], (root, swap) => { + keepTyping(root, swap); + settleConsoles(items); + }); } /** @@ -517,8 +646,8 @@ asked(item) && item.detail && item.detail !== "-" ? h("p", {class: "text reason"}, revealed(item.detail)) : null, item.kind === "rule" ? ruleRequestBody(item) : null, meta([["Directory", item.directory], ["Warnings", item.warnings.join(", ")], ["Id", item.id]]), - choiceOf(item, closeSheet), - h("div", {class: "actions"}, h("span", {class: "spacer"}), actionsFor(item).map((node) => { + dialogLapsed(item) ? null : choiceOf(item, closeSheet), + h("div", {class: "actions"}, h("span", {class: "spacer"}), (dialogLapsed(item) ? [] : actionsFor(item)).map((node) => { node.addEventListener("click", closeSheet); return node; })), diff --git a/orchestrator/templates/page-kanban.js b/orchestrator/templates/page-kanban.js index 2a9bda8..a4edff4 100644 --- a/orchestrator/templates/page-kanban.js +++ b/orchestrator/templates/page-kanban.js @@ -1,9 +1,60 @@ - const KANBAN_LABELS = {blocked: ["Blocked", "bad"], stopped: ["Stopped", "neutral"]}; + const KANBAN_LABELS = {blocked: "Blocked", stopped: "Stopped"}; const KANBAN_COLUMN_ICONS = {queued: "bi-hourglass", running: "bi-play-circle", done: "bi-check2-circle"}; 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, running: false, marks: {}, dragging: null, queue: {marks: {}, line: true, jobs: true}, bound: false}; + const KANBAN_STATES = [ + {key: "running", tone: "ok", line: "solid", label: "Running", states: ["running", "claimed"]}, + {key: "operator", tone: "warn", line: "solid", label: "Waits on the operator: an open card of its owner waits for an answer", states: ["operator"]}, + {key: "queued", tone: "info", line: "solid", label: "Queued or waiting for a grant", states: ["queued", "awaiting"]}, + {key: "blocked", tone: "bad", line: "solid", label: "Blocked, or a queue job that failed", states: ["blocked", "failed"]}, + {key: "stale", tone: "faint", line: "dashed", label: `Stale: no register change for ${Plan.STALE_DAYS} days`, states: ["stale"]}, + {key: "ended", tone: "line-strong", line: "solid", label: "Ended: done or stopped", states: ["done", "stopped"]}, + ]; + const kanban = {staged: [], collapsed: new Set(), old: false, running: false, stale: false, marks: {}, waiting: new Set(), dragging: null, queue: {marks: {}, line: true, jobs: true}, bound: false, bar: null}; + + const queueFailed = (row) => row.kind === "queue" && row.queue !== null && typeof row.queue.exit === "number" && row.queue.exit !== 0; + + /** + * @param row - a card's task row. + * @returns {string} its owner: the worker, else the first R holder, else "". + */ + const cardOwner = (row) => (row.worker && row.worker !== "-" ? row.worker : (Object.entries(row.roles || {}).find(([, letters]) => letters.includes("R")) || [""])[0]); + + /** + * @param row - a card's task row, staged changes applied. + * @param found - {operator, stale, working}: whether an open card of its owner waits on the operator, whether + * Plan.stale counts it and whether it carries the heartbeat (taskWorking). + * @returns {Object} the card's KANBAN_STATES entry. An ended row reads failed for a queue job that ended with a + * non-zero exit, else its status; an open row waits on the operator, else is blocked, else stale unless it works, + * else its status. A status no entry lists reads as queued, as the hub reads a row without one. + */ + function cardState(row, found) { + const open = found.operator ? "operator" : row.status === "blocked" ? "blocked" : found.stale && !found.working ? "stale" : row.status; + const key = row.ended ? (queueFailed(row) ? "failed" : row.status) : open; + return KANBAN_STATES.find((entry) => entry.states.includes(key)) || KANBAN_STATES.find((entry) => entry.states.includes("queued")); + } + + /** + * @param {Element} node a card or a legend swatch. + * @param {Object} entry its KANBAN_STATES entry. + * @returns {Element} node with --card-state set to the entry's theme token and --card-line to its border style. + */ + function stateTint(node, entry) { + node.style.setProperty("--card-state", `var(--${entry.tone})`); + node.style.setProperty("--card-line", entry.line); + return node; + } + + function stateLegend() { + return h("div", {class: "legend kanban-legend", "data-legend-slot": "", role: "group", "aria-label": "Card colours"}, KANBAN_STATES.map((entry) => + h("span", {class: "kanban-key", "data-card-state": entry.key}, stateTint(h("i", {class: "kanban-swatch", "aria-hidden": "true"}), entry), entry.label))); + } + + function ownerFace(row, owner) { + const nobody = () => h("span", {class: "avatar kanban-nobody", role: "img", ...named("No owner", `${row.task}: no worker and no R holder`)}, icon("bi-person-circle")); + return h("span", {class: "kanban-owner", "data-owner": owner}, owner ? agentFace(owner, false) : nobody()); + } function restage(next) { kanban.staged = next; @@ -68,16 +119,15 @@ }; } - function cardLabels(row) { + function cardLabels(row, stale) { const label = Kanban.labelOf(row); - const stale = Plan.stale(row, state.now); const stop = stale && row.editable ? iconBtn("bi-stop-circle", "Stop", "btn small ghost kanban-stop", (event) => { event.stopPropagation(); stageMove(row.task, [{status: "stopped"}]); }, `Stop ${row.task}: stage the status stopped`) : null; return [ - label ? h("span", {class: "pill", "data-tone": KANBAN_LABELS[label][1], "data-label": label}, KANBAN_LABELS[label][0]) : null, - stale ? h("span", {class: "pill kanban-stale", "data-tone": "warn", "data-label": "stale"}, "Stale", stop) : null, + label ? h("span", {class: "pill", "data-tone": "neutral", "data-label": label}, KANBAN_LABELS[label]) : null, + stale ? h("span", {class: "pill kanban-stale", "data-tone": "neutral", "data-label": "stale"}, "Stale", stop) : null, ]; } @@ -128,7 +178,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}, + return h("li", {class: job.status === "active" ? "queue-job is-working" : "queue-job", "data-job": job.id, "data-class": job.class || "", "data-kind": job.kind}, 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); } @@ -147,8 +197,13 @@ 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, + const working = taskWorking(row, found); + const stale = Plan.stale(row, state.now); + const owner = cardOwner(row); + const look = cardState(row, {operator: Boolean(owner) && kanban.waiting.has(agentKey(owner)), stale, working}); + return stateTint(h("li", { + class: ["task-card", "kanban-card", row.pending ? "pending" : "", working ? "is-working" : ""].filter(Boolean).join(" "), "data-task": row.task, "data-item": `task:${row.task}`, "data-lane": lane, "data-column": column, tabindex: 0, + "data-card-state": look.key, title: `${row.task}: ${look.label}`, "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: { @@ -175,7 +230,8 @@ }, }, }, - h("div", {class: "head-row"}, queuePlace(row), h("code", {class: "task-id"}, row.task), cardLabels(row), h("span", {class: "spacer"}), + ownerFace(row, owner), + h("div", {class: "head-row"}, queuePlace(row), h("code", {class: "task-id"}, row.task), cardLabels(row, stale), h("span", {class: "spacer"}), row.pending ? h("span", {class: "kanban-pending", role: "img", ...named("Staged", row.pending.map(shownArgv).join("\n"))}, icon("bi-pencil")) : null, openJobs(row.task).length ? h("span", {class: "kanban-wait", role: "img", ...named("At the runner", `${row.task}: a signed change waits for the runner`)}, icon("bi-hourglass-split")) : null, row.editable ? h("span", {class: "kanban-handle", role: "img", draggable: "true", ...named("Follows", `Drag onto the card that waits for ${row.task}`), on: {dragstart: dragFrom(row.task, "after"), dragend: () => { @@ -186,7 +242,7 @@ markChips(row, found), row.worker !== "-" ? h("span", {class: "muted"}, row.worker) : null, queueJobs(row), - cardWhy(row.task)); + cardWhy(row.task)), look); } function kanbanCell(lane, column, label, cards) { @@ -220,20 +276,42 @@ h("div", {class: "kanban-cells", id, hidden: !open}, TASK_COLUMNS.map(([column, label]) => kanbanCell(lane, column, label, cards)))); } + /** + * @param {number} hidden the Done cards older than 24 h. + * @param {number} stale the shown cards Plan.stale counts. + * @param {number} marked the shown cards with a running mark. + * @returns {Object} bar: the board's controls in three groups by data-tools: + * "status" (the stale count while there is one, the prune countdown while one waits), "filters" (Running, Stale, + * Older Done, the queue layers) and "actions" (Apply, Discard, Prune stale); a Home tile shows the bar in its head, + * the Tasks toolbar moves each group into its place. listed: the staged moves, null without any. + */ 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)); - const discard = h("button", {type: "button", class: "btn small icon-only", id: "kanban-discard", disabled: count === 0, ...named("Discard", "Discard the staged moves"), on: {click: () => restage([])}}, icon("bi-x-circle")); - const older = h("button", {type: "button", class: "btn small", id: "kanban-old", "aria-pressed": String(kanban.old), ...named("Older Done", `Done cards older than 24 h: ${hidden}, ${kanban.old ? "shown" : "hidden"}`), on: {click: () => { - kanban.old = !kanban.old; + const redraw = () => { taskView.sig = ""; drawTasks(); - }}}, icon(kanban.old ? "bi-eye" : "bi-eye-slash"), counter(hidden)); - 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 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"), h("span", {class: "tool-word"}, "Apply"), counter(count)); + const discard = h("button", {type: "button", class: "btn small", id: "kanban-discard", disabled: count === 0, ...named("Discard", "Discard the staged moves"), on: {click: () => restage([])}}, icon("bi-x-circle"), h("span", {class: "tool-word"}, "Discard")); + const flipOld = () => { + kanban.old = !kanban.old; + redraw(); + }; + const flipStale = () => { + kanban.stale = !kanban.stale; + redraw(); + }; + const older = h("button", {type: "button", class: "btn small", id: "kanban-old", "aria-pressed": String(kanban.old), ...named("Older Done", `Done cards older than 24 h: ${hidden}, ${kanban.old ? "shown" : "hidden"}`), on: {click: flipOld}}, icon(kanban.old ? "bi-eye" : "bi-eye-slash"), h("span", {class: "tool-word"}, "Older Done"), counter(hidden)); + const only = h("button", {type: "button", class: "btn small", id: "kanban-stale-only", "aria-pressed": String(kanban.stale), ...named("Stale", `Stale: ${stale} cards without a register change for ${Plan.STALE_DAYS} days, ${kanban.stale ? "only these shown" : "every card shown"}`), on: {click: flipStale}}, icon("bi-hourglass-bottom"), h("span", {class: "tool-word"}, "Stale"), counter(stale)); + const stalled = stale ? h("span", {class: "pill", id: "kanban-stale", "data-key": "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)) : null; + const prune = pruneControls(stale); + const tools = (key, label, nodes) => h("div", {class: "kanban-tools", "data-tools": key, role: "group", "aria-label": label}, nodes); 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, runningToggle(marked), stalled, pruneControls(stale), queueLegend()), listed]; + const bar = h("div", {class: "kanban-bar", role: "toolbar", "aria-label": "Board"}, tools("status", "Board status", [stalled, prune.chip]), + tools("filters", "Board filters", [runningToggle(marked), only, older, queueLegend()]), tools("actions", "Board actions", [apply, discard, prune.open])); + return {bar, listed}; } function queueLegend() { @@ -304,8 +382,11 @@ 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)])); + kanban.waiting = new Set(openInbox().filter((item) => !item.until && item.agent).map((item) => agentKey(item.agent))); const marked = placed.filter((row) => kanban.marks[row.task].length); - const rows = kanban.running ? marked : placed; + const running = kanban.running ? marked : placed; + const stale = running.filter((row) => Plan.stale(row, state.now)); + const rows = kanban.stale ? stale : running; 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}); @@ -315,5 +396,7 @@ 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, marked.length), box); + const {bar, listed} = kanbanBar(Kanban.board(rows, {now: state.now, old: false}).hidden, stale.length, marked.length); + kanban.bar = bar; + return h("div", {class: "kanban-box"}, listed, stateLegend(), box); } diff --git a/orchestrator/templates/page-keyboard.js b/orchestrator/templates/page-keyboard.js index 11ceef2..eeb2182 100644 --- a/orchestrator/templates/page-keyboard.js +++ b/orchestrator/templates/page-keyboard.js @@ -8,7 +8,7 @@ } function moveCursor(delta) { - const items = visibleInbox(); + const items = listedInbox(); if (!items.length) { return; } @@ -52,7 +52,7 @@ return; } const inInbox = ui.screen === "inbox"; - const current = inInbox ? visibleInbox()[ui.cursor] : null; + const current = inInbox ? listedInbox()[ui.cursor] : null; const index = Number(event.key) - 1; if (/^[1-9]$/.test(event.key) && index < Nav.TABS.length) { event.preventDefault(); @@ -65,7 +65,7 @@ toggle(current); } else if (inInbox && event.key === "a") { event.preventDefault(); - if (current && !current.held) { + if (current && !current.held && !dialogLapsed(current)) { approveOne(current); } } else if (event.key === "f" && feedbackKey()) { diff --git a/orchestrator/templates/page-legend.js b/orchestrator/templates/page-legend.js index e0eb273..507bf46 100644 --- a/orchestrator/templates/page-legend.js +++ b/orchestrator/templates/page-legend.js @@ -44,7 +44,7 @@ const made = legendView.buttons.get(owner); if (!place) { if (made) { - made.remove(); + vanish(made); legendView.buttons.delete(owner); } if (owner.dataset.legend) { diff --git a/orchestrator/templates/page-limits.js b/orchestrator/templates/page-limits.js index de3c453..e49cdc7 100644 --- a/orchestrator/templates/page-limits.js +++ b/orchestrator/templates/page-limits.js @@ -1,9 +1,44 @@ 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 LIMIT_STEPS = {ArrowUp: 1, ArrowDown: -1, PageUp: 5, PageDown: -5}; + const LIMIT_SHOWN_KEY = "kvb-orchestrator.limit-levels"; + const limitView = {data: null, busy: false, metric: "cpu", dom: null, staged: {}, drag: null, saving: false, shown: null, sheet: null, cells: []}; const limitsHeld = () => (limitView.data ? limitView.data.limits || limitView.data.profiles.balanced : null); + const limitShownOf = (value) => Object.fromEntries(Limits.SHOWN.map((level) => [level, !(value && value[level] === false)])); + const limitShown = () => limitView.shown || limitShownOf(null); + + /** + * @returns {Object|null} Limits.review() of the staged values against the limits the lines show, null while the + * limits are not loaded. + */ + function limitReview() { + const base = limitsHeld(); + return base ? Limits.review(base, limitView.data.limits, limitView.staged) : null; + } + + function limitValue(metric, level) { + const key = `${metric}.${level}`; + return Object.hasOwn(limitView.staged, key) ? limitView.staged[key] : limitsHeld()[metric][level]; + } + + /** + * @param {string} metric one of Limits.METRICS. + * @param {string} level one of Limits.LEVELS. + * @param {number} value the value to stage; the value the lines show unstages it. + */ + function stageLimit(metric, level, value) { + const base = limitsHeld(); + const key = `${metric}.${level}`; + if (!base) { + return; + } + if (value === base[metric][level]) { + delete limitView.staged[key]; + } else { + limitView.staged[key] = value; + } + } async function fetchLimits() { if (limitView.busy) { @@ -23,24 +58,82 @@ } /** - * @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. + * @returns {Object} the bar of staged lines: {root, note, error, save, discard}; Save sends every staged value in one + * request, Discard drops them all. + */ + function limitStageBar() { + const note = h("span", {class: "muted limit-stage-note"}); + const error = h("span", {class: "limit-error", role: "alert", hidden: true}); + const discard = h("button", {type: "button", class: "btn small ghost limit-discard", title: "Discard: drop every staged value, the lines return to the limits in force", on: {click: discardStaged}}, "Discard"); + const save = h("button", {type: "button", class: "btn small primary limit-save", on: {click: saveStaged}}, "Save"); + return {root: h("div", {class: "limit-stage", role: "group", "aria-label": "Staged limits", hidden: true}, note, error, discard, save), note, error, save, discard}; + } + + /** + * @returns {HTMLElement} the row above the Hardware chart: the Limits menu (a checkbox per level, the profiles and + * the matrix), which metric's limit lines the chart draws, a note on the limits file and the bar of staged lines. */ function limitBar() { + limitView.shown = limitShownOf(stored(LIMIT_SHOWN_KEY, null)); + const levels = Limits.SHOWN.map((level) => { + const box = h("input", {type: "checkbox", "data-level": level, "aria-label": `${Limits.SHOWN_NAMES[level]} lines`, on: {change: () => showLevel(level, box.checked)}}); + return {level, box, row: h("label", {class: "menu-item res-pick limit-level", title: Limits.meaning(level)}, box, h("span", {class: `limit-swatch ${level}`, "aria-hidden": "true"}), h("span", {}, Limits.SHOWN_NAMES[level]))}; + }); 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 matrix = h("button", {type: "button", class: "btn small soft limit-matrix", id: "limits-open", ...named("Matrix…", "Matrix: every lower, upper, STOP and MAYDAY value of every metric in one table; a right click on the chart opens it too"), on: {click: openLimits}}, icon("bi-table"), h("span", {}, "Matrix…")); + const menu = h("details", {class: "menu res-limits-menu"}, h("summary", {...named("Limits", "Limits: show or hide the lines of each level, pick a profile, or open the matrix of every value")}, icon("bi-sliders"), h("span", {}, "Limits"), caret()), + h("div", {class: "menu-box", role: "group", "aria-label": "Limits"}, + h("h3", {}, "Lines"), levels.map((entry) => entry.row), + h("h3", {}, "Profile"), h("div", {class: "segmented limit-profiles", role: "group", "aria-label": "Profile"}, profiles.map((entry) => entry[2])), matrix)); 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); + const stage = limitStageBar(); + limitView.dom = {levels, profiles, metrics, menu, matrix, note, stage}; + return h("div", {class: "res-limits"}, menu, + h("div", {class: "segmented limit-metrics", role: "group", "aria-label": "Limit lines"}, metrics.map((entry) => entry[1])), note, stage.root); + } + + function showLevel(level, on) { + limitView.shown = {...limitShown(), [level]: on}; + keep(LIMIT_SHOWN_KEY, limitView.shown); + drawResources(); + } + + /** + * @param {Object} bar a limitStageBar(). + * @param {Object|null} review limitReview(). + */ + function drawLimitStage(bar, review) { + const count = review ? review.changes.length : 0; + const broken = review ? review.broken : null; + bar.root.hidden = count === 0 && !broken; + bar.save.textContent = `Save ${count} change${count === 1 ? "" : "s"}`; + bar.save.disabled = count === 0 || Boolean(broken) || limitView.saving; + bar.discard.disabled = limitView.saving; + bar.save.title = broken ? `Not possible: ${broken.words}` : review && review.loose.length ? "Save: one passkey signature covers every looser value of this batch" : "Save: tighter values save without the passkey"; + bar.note.textContent = review ? `${review.changes.map(Limits.said).join(", ")}${review.loose.length ? " · passkey" : ""}` : ""; + bar.error.hidden = !broken; + bar.error.textContent = broken ? broken.words : ""; + } + + function drawLimitCells() { + const held = limitsHeld(); + for (const input of limitView.cells) { + const metric = input.getAttribute("data-metric"); + const level = input.getAttribute("data-level"); + const value = limitValue(metric, level); + const moved = value !== held[metric][level]; + input.setAttribute("class", `limit-cell${moved ? " moved" : ""}`); + input.title = `${Limits.NAMES[metric]} ${Limits.LEVEL_NAMES[level]}${moved ? ` was ${held[metric][level]} %` : ""}: ${Limits.meaning(level)}`; + if (input !== document.activeElement) { + input.value = Number.isFinite(value) ? String(value) : ""; + } + } } function drawLimitBar() { @@ -53,14 +146,146 @@ 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.disabled = !values || limitView.saving; 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; + const shown = limitShown(); + for (const {level, box} of dom.levels) { + box.checked = shown[level]; + } + dom.matrix.disabled = !data; dom.note.textContent = !data ? "" : data.why ? revealed(data.why) : data.limits ? "" : "No limits.json: the queue config applies"; + const review = limitReview(); + drawLimitStage(dom.stage, review); + if (limitView.sheet && limitView.sheet.root.isConnected) { + drawLimitStage(limitView.sheet, review); + drawLimitCells(); + } + } + + /** + * @param {SVGElement} node a limit line's group of limitLine(). + * @param {Object} frame the chart frame of resourceFrame(). + * @param {Function} y maps a percent to the chart's y. + * Draws the line at its staged value: solid at the value in force, dashed with the new and the old value once moved. + */ + function limitPaint(node, frame, y) { + const metric = node.getAttribute("data-metric"); + const level = node.getAttribute("data-level"); + const held = limitView.data.limits[metric][level]; + const value = limitValue(metric, level); + const moved = value !== held; + const words = `${Limits.NAMES[metric]} ${Limits.LEVEL_NAMES[level]}`; + const at = fixed(y(value)); + const label = `${Limits.LEVEL_NAMES[level]} ${value}${moved ? ` (was ${held})` : ""}`; + node.setAttribute("class", `res-limit ${level}${moved ? " moved" : ""}`); + node.setAttribute("data-value", String(value)); + node.setAttribute("aria-label", words); + node.setAttribute("aria-valuenow", String(value)); + node.setAttribute("aria-valuetext", moved ? `${value} %, was ${held} %` : `${value} %`); + const was = moved ? s("line", {class: "res-limit-was", x1: RESOURCE.left, x2: fixed(frame.right), y1: fixed(y(held)), y2: fixed(y(held))}) : null; + const parts = [ + s("title", {}, `${words} ${value} %${moved ? ` (was ${held} %)` : ""}: ${Limits.meaning(level)}. Drag it, or focus it and press the arrow keys, to stage a new value.`), + was, + 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 - Limits.LEVELS.indexOf(level) * LIMIT_LABEL.step), y: fixed(y(value) - LIMIT_LABEL.gap), "text-anchor": "end"}, label), + ]; + node.replaceChildren(...parts.filter(Boolean)); + } + + /** + * @param {PointerEvent} event a pointer event over the chart. + * @param {SVGSVGElement} svg the chart. + * @returns {number} the event's y in the chart's coordinates. + */ + function limitChartY(event, svg) { + const box = svg.getBoundingClientRect(); + return (event.clientY - box.top) * (svg.viewBox.baseVal.height / box.height); + } + + /** + * @param {PointerEvent} event a pointerdown on a limit line. + * @param {SVGElement} node the line's group. + * Grabs the line nearest to the pointer, as the hit strokes of lines a few points apart overlap. + */ + function limitGrab(event, node) { + if (event.button !== 0 || limitView.saving) { + return; + } + event.preventDefault(); + const svg = node.ownerSVGElement; + const at = limitChartY(event, svg); + const gap = (line) => Math.abs(Number(line.querySelector(".res-limit-mark").getAttribute("y1")) - at); + const grabbed = [...svg.querySelectorAll("g.res-limit")].reduce((best, line) => (gap(line) < gap(best) ? line : best), node); + // A synthetic pointerdown names no active pointer, and capturing it throws NotFoundError. + if (event.isTrusted) { + grabbed.setPointerCapture(event.pointerId); + } + grabbed.setAttribute("data-dragging", ""); + limitView.drag = {node: grabbed}; + } + + /** + * @param {PointerEvent} event a pointermove over or captured by a limit line. + * @param {SVGElement} node the line's group. + * @param {Object} frame the chart frame of resourceFrame(). + * @param {Function} y maps a percent to the chart's y. + * Stages the percent under the pointer and redraws only that line and the staged bar, so the capture survives. + */ + function limitMove(event, node, frame, y) { + if (!limitView.drag || limitView.drag.node !== node) { + return; + } + const value = Limits.valueAt(limitChartY(event, node.ownerSVGElement), frame.top, frame.bottom); + stageLimit(node.getAttribute("data-metric"), node.getAttribute("data-level"), value); + limitPaint(node, frame, y); + drawLimitBar(); + } + + function limitDrop() { + if (!limitView.drag) { + return; + } + limitView.drag = null; + drawResources(); + } + + /** + * @param {KeyboardEvent} event a key on a focused limit line: the arrows move it by 1, Page Up and Down by 5, Escape + * drops its staged value. + * @param {string} metric one of Limits.METRICS. + * @param {string} level one of Limits.LEVELS. + */ + function limitKey(event, metric, level) { + if (event.key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + stageLimit(metric, level, limitsHeld()[metric][level]); + } else if (Object.hasOwn(LIMIT_STEPS, event.key)) { + event.preventDefault(); + const value = limitValue(metric, level); + stageLimit(metric, level, Math.min(100, Math.max(0, Math.round(Number.isFinite(value) ? value : 0) + LIMIT_STEPS[event.key]))); + } else { + return; + } + drawResources(); + } + + function limitLine(frame, y, metric, level) { + const node = s("g", {"data-metric": metric, "data-level": level, "data-line": level, role: "slider", tabindex: 0, "aria-valuemin": 0, "aria-valuemax": 100, "aria-orientation": "vertical", on: { + pointerdown: (event) => limitGrab(event, node), + pointermove: (event) => limitMove(event, node, frame, y), + pointerup: limitDrop, + pointercancel: limitDrop, + lostpointercapture: limitDrop, + keydown: (event) => limitKey(event, metric, level), + }}); + limitPaint(node, frame, y); + return node; } /** @@ -69,41 +294,39 @@ */ function limitLines(frame, y) { const data = limitView.data; - if (!data || !data.limits) { + if (!data || !data.limits || !resourceView.show.limits) { return; } const metric = limitView.metric; const name = Limits.NAMES[metric]; + const shown = limitShown(); const target = Limits.TARGETED.includes(metric) && data.target ? data.target[metric] : null; - if (typeof target === "number") { + if (typeof target === "number" && shown.target) { 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`), + frame.svg.append(s("g", {class: "res-target", "data-metric": metric, "data-value": String(target)}, s("title", {}, `${name} target ${target.toFixed(1)} %: ${Limits.meaning("target")}`), 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}`))); - }); + for (const level of Limits.LEVELS.filter((entry) => shown[entry])) { + frame.svg.append(limitLine(frame, y, metric, level)); + } + } + + /** + * @param {MouseEvent} event a right click on the Hardware chart; it opens the matrix in place of the context menu. + */ + function limitContext(event) { + if (limitsHeld()) { + event.preventDefault(); + openLimits(); + } } /** * @param {Object} next valid limits to save. * @param {string} label what the passkey prompt and the toast name. * @returns {Promise} 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. + * only once the passkey signs the whole object in one assertion; a canceled passkey sends nothing and keeps the old + * values and the staged ones. */ async function saveLimits(next, label) { const held = limitView.data.limits; @@ -119,46 +342,35 @@ return false; } limitView.data = result.data; + limitView.staged = {}; 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) { + async function saveStaged() { + const review = limitReview(); + if (!review || review.broken || !review.changes.length || limitView.saving) { 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}); + limitView.saving = true; + drawLimitBar(); + const count = review.changes.length; + await saveLimits(review.next, `Save ${count} limit change${count === 1 ? "" : "s"} (${review.changes.map(Limits.said).join(", ")})`); + limitView.saving = false; + drawResources(); + } + + function discardStaged() { + limitView.staged = {}; + drawResources(); + } + + async function chooseProfile(id, label) { + const data = limitView.data; + if (data && !limitView.saving && Limits.profileOf(data.limits, data.profiles) !== id) { + await saveLimits(data.profiles[id], `Profile ${label}`); + } } function openLimits() { @@ -167,15 +379,23 @@ if (!held) { return; } + limitView.cells = []; 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]} %`)); + const input = h("input", {type: "number", class: "limit-cell", min: 0, max: 100, step: 1, value: String(limitValue(metric, level)), "data-metric": metric, "data-level": level, "aria-label": `${Limits.NAMES[metric]} ${Limits.LEVEL_NAMES[level]} in percent`, on: {input: () => { + stageLimit(metric, level, input.valueAsNumber); + drawResources(); + }}}); + limitView.cells.push(input); + return h("td", {}, input); }; + const rows = Limits.METRICS.map((metric) => h("tr", {"data-metric": metric}, h("th", {scope: "row"}, Limits.NAMES[metric]), Limits.LEVELS.map((level) => cell(metric, level)))); + limitView.sheet = limitStageBar(); 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."), + h("p", {class: "muted"}, data.limits ? `limits.json in the council directory, ${Limits.ORDER} per metric. A changed value is staged beside the lines; Save sends them all, and a looser one needs the passkey.` : "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); + h("thead", {}, h("tr", {}, h("th", {scope: "col"}, "Metric"), Limits.LEVELS.map((level) => h("th", {scope: "col", "data-level": level, title: Limits.meaning(level)}, Limits.LEVEL_NAMES[level])))), + h("tbody", {}, rows))), + limitView.sheet.root), false); + drawLimitBar(); } diff --git a/orchestrator/templates/page-load.js b/orchestrator/templates/page-load.js index aa560f4..05fa1b8 100644 --- a/orchestrator/templates/page-load.js +++ b/orchestrator/templates/page-load.js @@ -71,3 +71,33 @@ fetchEvents(); } } + + const CLOSED_POLL = 2000; + const closedWatch = {seen: null, busy: false}; + + /** + * @returns {Promise} settled once the hub's count of closed cards (/api/match/closed) is read; when it moved + * since the last read, the first read included, an open Match deck fetches its cards and the state reloads at once + * instead of at their next interval, so a card answered in Claude or another browser leaves within one CLOSED_POLL. + */ + async function watchClosed() { + if (closedWatch.busy) { + return; + } + closedWatch.busy = true; + try { + const response = await fetch("/api/match/closed", {cache: "no-store"}); + const data = response.ok ? await response.json() : null; + if (data && data.closed !== closedWatch.seen) { + closedWatch.seen = data.closed; + if (matchShown()) { + fetchMatch(); + } + refresh(); + } + } catch { + closedWatch.seen = null; + } finally { + closedWatch.busy = false; + } + } diff --git a/orchestrator/templates/page-match.js b/orchestrator/templates/page-match.js index a24a14b..509ef49 100644 --- a/orchestrator/templates/page-match.js +++ b/orchestrator/templates/page-match.js @@ -2,25 +2,29 @@ const LONG_PRESS = 550; const PRESS_SLOP = 10; const MATCH_KINDS = {commit: ["Commit", "info", "bi-git"], command: ["Command", "warn", "bi-terminal"], ask: ["Ask", "warn", "bi-shield-lock"], decision: ["Decision", "info", "bi-signpost-split"], rule: ["Rule", "neutral", "bi-shield-check"]}; - const MATCH_VERDICTS = {accept: ["Accept", "ok", "bi-check-lg"], reject: ["Reject", "bad", "bi-x-lg"]}; + const MATCH_VERDICTS = {accept: ["Accept", "ok", "bi-check-lg"], reject: ["Reject", "bad", "bi-x-lg"], drop: ["Drop (expired)", "neutral", "bi-trash"]}; const SWIPE_SHARE = 0.25; const SWIPE_UP = 80; const FEEDBACK_LIMIT = 2000; const FLY_MS = 400; const CONFETTI = 28; + const CONFETTI_GONE = 9000; const DROPS_KEPT = 200; 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"; + const MATCH_STAMPS = {running: "RUNNING", queued: "QUEUED", stale: "STALE", expired: "EXPIRED", claude: "IN CLAUDE", blocked: "BLOCKED"}; + const lapsedCard = (card) => card.blocked_kind === "expired" || card.blocked_kind === "claude"; + const droppable = (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". + * @param {object} card a lapsed card (lapsedCard()) with its expires time in epoch seconds. + * @returns {string} the stamp's tooltip: the clock time its hook stopped waiting and how long ago, as "expired 14:02, + * 12 minutes ago", for a card whose dialog is still open in Claude as "open in Claude since 14:02, 12 minutes ago". */ function expiredWords(card) { - return `expired ${clock.format(stampOf(card.expires))}, ${ago(card.expires)}`; + const since = `${clock.format(stampOf(card.expires))}, ${ago(card.expires)}`; + return card.blocked_kind === "claude" ? `open in Claude since ${since}` : `expired ${since}`; } /** @@ -37,6 +41,85 @@ } return Object.hasOwn(MATCH_STAMPS, card.blocked_kind) ? card.blocked_kind : "blocked"; } + + const MATCH_SHOWS = [...Object.entries(MATCH_KINDS).map(([kind, [word]]) => [kind, word]), ["expired", "Expired"], ["stale", "Stale"], ["greyed", "Greyed"]]; + const SHOW_STATES = {stale: "stale", expired: "expired", claude: "expired", running: "greyed", queued: "greyed", blocked: "greyed"}; + const showState = (card) => SHOW_STATES[greyStamp(card)] || ""; + const shownCard = (card, hidden) => !hidden.has(card.kind) && !hidden.has(showState(card)); + const hiddenWords = (count) => `${count} hidden`; + const allHiddenWords = (count) => `All ${count} ${count === 1 ? "card" : "cards"} hidden by the Show filter`; + + /** + * @returns {Set} the MATCH_SHOWS keys this browser's Show filter hides; any other stored value is ignored. + */ + function matchHidden() { + const kept = stored(STORE.show, []); + return new Set(Array.isArray(kept) ? kept.filter((key) => MATCH_SHOWS.some(([one]) => one === key)) : []); + } + + /** + * @param {Array} cards the cards in stack order. + * @param {Set} hidden the MATCH_SHOWS keys the Show filter hides. + * @returns {object} open: the undecided cards; shown: those of them the filter lets through; hidden: how many it + * hides. A decided card is never hidden: it stays on the release card and goes out with the release. + */ + function showSplit(cards, hidden) { + const open = cards.filter((card) => !decisionOf(card)); + const shown = open.filter((card) => shownCard(card, hidden)); + return {open, shown, hidden: open.length - shown.length}; + } + + /** + * @param {Array} open the undecided cards. + * @returns {object} per MATCH_SHOWS key how many of them it covers: each card counts once for its kind and once for + * its state (showState()), an acting card for no state. + */ + function showCounts(open) { + return Object.fromEntries(MATCH_SHOWS.map(([key]) => [key, open.filter((card) => card.kind === key || showState(card) === key).length])); + } + + /** + * @param {string} key a MATCH_SHOWS key: shown again when hidden, hidden when shown, remembered in this browser. + */ + function toggleShow(key) { + const hidden = matchHidden(); + if (hidden.has(key)) { + hidden.delete(key); + } else { + hidden.add(key); + } + keep(STORE.show, [...hidden]); + drawMatch(true); + } + + function showAll() { + keep(STORE.show, []); + drawMatch(true); + } + + /** + * @returns {Array} the Show items of the context menu: per MATCH_SHOWS key a checkbox with the count of the + * undecided cards it covers, then Show all; none before the first fetch. + */ + function matchShowItems() { + if (!matchView.cards) { + return []; + } + const counts = showCounts(showSplit(matchView.cards, new Set()).open); + return [...MATCH_SHOWS.map(([key, word]) => ({label: word, hint: String(counts[key]), checked: () => !matchHidden().has(key), run: () => toggleShow(key)})), + {label: "Show all", hint: "every kind and state", run: showAll}]; + } + + /** + * @param {Event} event the click on the "N hidden" button of the Match head: it opens the context menu under it and + * stops there, since menuClick() on the document would close the menu again at once. + */ + function openShowMenu(event) { + const button = event.currentTarget; + const box = button.getBoundingClientRect(); + event.stopPropagation(); + ctxOpen(button, {x: box.left, y: box.bottom}); + } 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, timer: null, turn: 0}; @@ -106,8 +189,8 @@ } 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 picked = dial({value: matchRefresh(), label: "Match refresh in seconds", name: "match-refresh-dial", min: MatchClock.MIN, max: MatchClock.MAX, page: MatchClock.PAGE, readout: Dial.countdown, + spoken: (seconds) => `Match fetches the cards every ${seconds} seconds`, readonly: false, live: null}); const save = async () => { const refresh = picked.value(); if (refresh === settings.match.refresh || await saveSettings({...settings, space: savedSpace(), match: {refresh}})) { @@ -122,24 +205,11 @@ } /** - * @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. + * @returns {HTMLElement} the refresh hourglass of the empty deck: 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 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) => { + function matchGlass() { + const glass = h("button", {type: "button", class: "match-glass large", "aria-label": "Refresh", on: {click: () => fetchMatch(), contextmenu: (event) => { event.preventDefault(); refreshDial(); }}}, glassFace()); @@ -212,12 +282,12 @@ /** * @param {object} card a card as /api/match serves it now. - * @returns {object|undefined} its decision: a reject by card id whatever the card's hash, an accept only for the - * exact hash it was made on. + * @returns {object|undefined} its decision: a reject or drop by card id whatever the card's hash, an accept only for + * the exact hash it was made on. */ function decisionOf(card) { const decision = matchView.decisions.get(card.id); - return decision && (decision.verdict === "reject" || decision.hash === card.hash) ? decision : undefined; + return decision && (decision.verdict !== "accept" || decision.hash === card.hash) ? decision : undefined; } /** @@ -320,10 +390,7 @@ } function closeComment(card) { - const open = card.querySelector(".match-comment"); - if (open) { - open.remove(); - } + vanish(card.querySelector(".match-comment:not([data-vanishing])")); } function commentField(card, data, row) { @@ -458,7 +525,7 @@ h("div", {class: "states"}, h("span", {class: "pill", "data-tone": kindTone}, icon(kindIcon), kindName), card.gate ? pill(`gate ${card.gate}`, card.gate === "pass" ? "ok" : "bad") : null, card.score && !metrics.length ? h("span", {class: "pill", "data-tone": "neutral"}, revealed(card.score)) : null, card.stale ? h("span", {class: "pill match-stale-pill", "data-tone": "bad"}, icon("bi-hourglass-split"), "stale") : null), placeRow(card), - h("h2", {class: "match-title"}, revealed(card.title)), + h("h2", {class: "match-title", title: card.title_full || null}, revealed(card.title)), card.stale ? h("p", {class: "match-stale"}, icon("bi-exclamation-triangle"), revealed(card.stale_reason)) : null); } @@ -534,7 +601,7 @@ 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, stamp ? h("span", {class: "match-stamp", "data-stamp": stamp, ...(stamp === "expired" ? {title: expiredWords(card), on: {mouseenter: (event) => { + matchHead(card), body, stamp ? h("span", {class: "match-stamp", "data-stamp": stamp, ...(lapsedCard(card) ? {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)); @@ -604,15 +671,39 @@ }); } + /** + * @param {object} card an expired card (droppable()): it leaves the deck at once with the vanish() fade, without a + * feedback sheet or a radio message, and the next release dismisses it in the hub for every browser; S puts it back. + */ + function dropCard(card) { + logStep(card.id); + refusedIds.delete(card.ref); + matchView.decisions.set(card.id, {verdict: "drop", feedback: "", label: "", hash: card.hash, card, risk: false}); + drawMatch(true); + } + function confetti() { - return h("div", {class: "match-confetti", "aria-hidden": "true"}, Array.from({length: CONFETTI}, (_, index) => { + document.querySelectorAll(".confetti-rain").forEach((old) => vanish(old)); + if (calm.matches) { + return; + } + const bar = document.getElementById("head"); + const top = bar ? Math.max(0, Math.round(bar.getBoundingClientRect().bottom)) : 0; + const layer = h("div", {class: "confetti-rain", "aria-hidden": "true"}, Array.from({length: CONFETTI}, (_, index) => { const bit = h("i", {}); - bit.style.setProperty("--x", `${(index * 37) % 100}%`); + bit.style.setProperty("--x", String(((index * 37) % 100) / 100)); bit.style.setProperty("--c", String((index * 47) % 360)); - bit.style.setProperty("--r", `${(index % 2 ? 1 : -1) * (180 + index * 23)}deg`); - bit.style.setProperty("--d", `${(index % 7) * 0.06}s`); + bit.style.setProperty("--r", `${(index % 2 ? 1 : -1) * 180 * (1 + (index % 3))}deg`); + bit.style.setProperty("--d", `${(index % 7) * 0.1}s`); + bit.style.setProperty("--t", `${1.4 + (index % 5) * 0.25}s`); return bit; })); + layer.style.setProperty("--top", `${top}px`); + layer.style.setProperty("--fall", `${Math.max(0, window.innerHeight - top)}px`); + const end = () => vanish(layer); + layer.addEventListener("animationend", (event) => event.target === layer && end()); + window.setTimeout(end, CONFETTI_GONE); + document.body.append(layer); } /** @@ -654,6 +745,10 @@ if (refusedHere(card, "Reject")) { return; } + if (droppable(card)) { + dropCard(card); + return; + } if (pickOnly(card) && !lapsedCard(card)) { toast("Reject: not possible", ["A choice is answered with one of its options."], false); return; @@ -767,11 +862,14 @@ * @param {object} card a decided match card. * @param {object} decision its {verdict, feedback, label}. * @returns {object} the inbox entry the release signs: an approval of the review or the ask, the picked option of a - * decision, the operator row bound to the payload hash the card showed, or a rejection carrying the feedback as a - * radio call to the card's agent. + * decision, the operator row bound to the payload hash the card showed, a rejection carrying the feedback as a + * radio call to the card's agent, or for a drop the hub-wide dismissal of the expired request, which tells no agent. */ function matchEntry(card, decision) { const kind = card.entry || (card.kind === "commit" ? "review" : "operator"); + if (decision.verdict === "drop") { + return {kind: "dismiss", target: kind, id: card.ref, scope: "expired"}; + } 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) && !lapsedCard(card)) { return {...entry, verb: "approve", label: decision.label}; @@ -801,7 +899,7 @@ * @param {object} card a card on the release card. * @param {object} decision its decision. * @returns {string} why the release cannot carry the row now, "" when it can: the hub refused it last time, it was - * accepted and expired since, or it is blocked; a reject of an expired card still goes by radio. + * accepted and expired since, or it is blocked; a reject or drop of a lapsed card still releases. */ function unreleasable(card, decision) { if (card.withdrawn) { @@ -815,15 +913,16 @@ if (lapsed && decision.verdict === "accept") { return `${expiredWords(card)}: can no longer be granted; reject or drop it`; } - return card.blocked && !(lapsed && decision.verdict === "reject") ? `not possible now: ${card.blocked}; drop it or send it back to the stack` : ""; + return card.blocked && !(lapsed && decision.verdict !== "accept") ? `not possible now: ${card.blocked}; drop it or send it back to the stack` : ""; } /** * @param {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, - * which block the release until each is risk-accepted or sent back to the stack; bad: rows unreleasable() names, - * which block the release until each is changed or dropped. + * @returns {object} lone: risk-accepted red-gate commits, each signed on its own first; rest: every other accept and + * reject, signed together with dismissals: the dropped expired cards, dismissed in the hub without a radio message; + * gone: withdrawn rejects, sent by radio only, a withdrawn drop needing nothing; held: red-gate commits whose risk is + * not accepted, which block the release until each is risk-accepted or sent back to the stack; bad: rows + * unreleasable() names, which block the release until each is changed or dropped. */ function releasePlan(picked) { const signed = picked.filter(([card]) => !card.withdrawn); @@ -831,8 +930,9 @@ const good = signed.filter((pair) => !bad.includes(pair)); return { lone: good.filter(([card, decision]) => risky(card, decision) && decision.risk), - rest: good.filter(([card, decision]) => !risky(card, decision)), - gone: picked.filter(([card]) => card.withdrawn), + rest: good.filter(([card, decision]) => !risky(card, decision) && decision.verdict !== "drop"), + dismissals: good.filter(([, decision]) => decision.verdict === "drop"), + gone: picked.filter(([card, decision]) => card.withdrawn && decision.verdict !== "drop"), held: good.filter(([card, decision]) => risky(card, decision) && !decision.risk), bad, }; @@ -868,11 +968,12 @@ toast("Release: not possible", plan.bad.map(([card, decision]) => `${card.title}: ${unreleasable(card, decision)}`), false); return; } - if (matchView.releasing || plan.held.length || !(plan.lone.length + plan.rest.length + plan.gone.length)) { + const together = [...plan.rest, ...plan.dismissals]; + if (matchView.releasing || plan.held.length || !(plan.lone.length + together.length + plan.gone.length)) { return; } matchView.releasing = true; - const names = new Map([...plan.lone, ...plan.rest].map(([card]) => [card.ref, card.title])); + const names = new Map([...plan.lone, ...together].map(([card]) => [card.ref, card.title])); const done = []; try { for (const pair of plan.lone) { @@ -881,10 +982,10 @@ } done.push(pair); } - if (plan.rest.length && !(await submit(plan.rest.map((pair) => matchEntry(...pair)), `Release: ${decisionWords(plan.rest.length)}`, names))) { + if (together.length && !(await submit(together.map((pair) => matchEntry(...pair)), `Release: ${decisionWords(together.length)}`, names))) { return; } - done.push(...plan.rest, ...plan.gone); + done.push(...together, ...plan.gone); } finally { matchView.releasing = false; if (done.length) { @@ -965,8 +1066,8 @@ /** * @param {object} card a card on the release card, not withdrawn. * @param {object} decision its decision. - * @returns {HTMLElement} its verdict pill as a menu: each option of a decision card, Accept, Reject and Back to the - * stack, an impossible entry greyed with its reason. + * @returns {HTMLElement} its verdict pill as a menu: each option of a decision card, Accept, Reject (Drop for an + * expired card) and Back to the stack, an impossible entry greyed with its reason. */ function verdictMenu(card, decision) { const [word, tone, mark] = MATCH_VERDICTS[decision.verdict]; @@ -976,7 +1077,7 @@ const rejectWhy = card.blocked && !lapsed ? `not possible now: ${card.blocked}` : pickOnly(card) && !lapsed ? "a choice is answered with one of its options" : ""; return h("details", {class: "menu match-verdict-menu"}, h("summary", {class: "pill match-verdict", "data-tone": tone, ...named(`${word}: change`, "Change this decision")}, icon(mark), decision.label ? revealed(`${word}: ${shownPick(decision.label)}`) : word, caret()), - h("div", {class: "menu-box end", role: "group", "aria-label": "Change the decision"}, options, accept, menuEntry("Reject …", "bi-x-lg", rejectWhy, () => rejectCard(card)), menuEntry("Back to the stack", "bi-stack", "", () => backToStack(card)))); + h("div", {class: "menu-box end", role: "group", "aria-label": "Change the decision"}, options, accept, droppable(card) ? menuEntry("Drop (expired)", "bi-trash", "", () => dropCard(card)) : menuEntry("Reject …", "bi-x-lg", rejectWhy, () => rejectCard(card)), menuEntry("Back to the stack", "bi-stack", "", () => backToStack(card)))); } function overviewRow(card, decision) { @@ -986,8 +1087,9 @@ const risk = risky(card, decision); const held = risk && !decision.risk; const bad = unreleasable(card, decision); - const note = bad ? `Cannot be released: ${bad}.` : 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." : ""; - const verdict = card.withdrawn ? h("span", {class: "pill match-verdict", "data-tone": tone}, icon(mark), word) : verdictMenu(card, decision); + const dropped = decision.verdict === "drop"; + const note = bad ? `Cannot be released: ${bad}.` : card.withdrawn ? "Card withdrawn: the feedback goes to its agent by radio call at the release." : dropped ? "Dismissed in the hub for every browser at the release; its agent gets no message." : 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." : ""; + const verdict = card.withdrawn || dropped ? h("span", {class: "pill match-verdict", "data-tone": tone}, icon(mark), word) : verdictMenu(card, decision); return h("li", {class: "match-decision", "data-card": card.id, "data-verdict": decision.verdict, "data-withdrawn": String(Boolean(card.withdrawn)), "data-held": String(held), "data-bad": String(Boolean(bad))}, 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"}), risk && !bad ? riskButton(decision) : verdict, decision.verdict === "reject" && !card.withdrawn ? iconBtn("bi-pencil", "Edit feedback", "btn small ghost match-edit", () => rejectCard(card)) : null, back), @@ -995,40 +1097,57 @@ decision.verdict === "reject" ? h("pre", {class: "match-decision-feedback"}, revealedLines(decision.feedback === "" ? "no feedback text" : decision.feedback)) : null); } + /** + * @param {string} cls the button's classes after match-act: its tone and its role. + * @param {string} iconName the icon on its round face. + * @param {string} word the label under the face. + * @param {string} hint its tooltip. + * @param {boolean} disabled whether it is greyed and takes no click. + * @param {Function} run what a click runs. + * @returns {HTMLElement} one button of the deck's action row; every card's row holds three of the same width. + */ + function matchAct(cls, iconName, word, hint, disabled, run) { + return h("button", {type: "button", class: `match-act ${cls}`, disabled, ...named(word, hint), on: {click: run}}, + h("span", {class: "match-act-face", "aria-hidden": "true"}, icon(iconName)), h("span", {class: "match-act-label"}, word)); + } + /** * @param {Array} cards the cards in stack order. * @param {number} open how many cards wait undecided behind it. - * @returns {HTMLElement} the release card: front card of the deck with every decision, its own moves (D or a - * right swipe releases, A, W or a left swipe goes on to the next card) mirrored in matchView.release for the keys. + * @returns {object} card: the release card, front card of the deck with every decision; actions: its row of the + * deck, Cancel on the left, Skip, Release on the right; its moves (D or a right swipe releases, A, W or a left + * swipe skips to the next card) mirrored in matchView.release for the keys. */ function releaseCard(cards, open) { const picked = decided(cards); const plan = releasePlan(picked); const held = plan.held.length; const bad = plan.bad.length; - const count = held || bad ? 0 : plan.lone.length + plan.rest.length + plan.gone.length; + const count = held || bad ? 0 : plan.lone.length + plan.rest.length + plan.dismissals.length + plan.gone.length; const badWhy = plan.bad.map(([card, decision]) => `${card.title}: ${unreleasable(card, decision)}`).join("\n"); + const heldWhy = `Release waits: ${held === 1 ? "one red-gate commit waits" : `${held} red-gate commits wait`} for your risk accept or its way back to the stack.\n${plan.held.map(([card]) => card.title).join("\n")}`; 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 ? () => { + const skip = open ? () => { logStep(RELEASE); toBack(RELEASE); drawMatch(true); } : null; - 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 || bad), "aria-disabled": String(Boolean(bad)), title: revealed(bad ? `Release waits: drop or change ${bad === 1 ? "this row" : `these ${bad} rows`} first.\n${badWhy}` : count ? `${signatures}; after each signature ${undoWords()}.` : "Nothing to release yet."), on: {click: run}}, icon("bi-key"), `Release ${decisionWords(count || plan.lone.length + plan.rest.length + plan.gone.length + bad)}`); - const cancel = h("button", {type: "button", class: "btn danger match-drop", disabled: !bad, title: revealed(bad ? `Cancel: drop the ${bad === 1 ? "row" : `${bad} rows`} that cannot be released, and their cards leave the deck.\n${badWhy}` : "Cancel: no row is blocked, nothing to drop."), on: {click: () => dropUnreleasable(plan.bad)}}, icon("bi-x-lg"), bad ? `Cancel ${bad}` : "Cancel"); + const releaseHint = held ? heldWhy : bad ? `Release waits: drop or change ${bad === 1 ? "this row" : `these ${bad} rows`} first.\n${badWhy}` : count ? `Release (D, right arrow, swipe right): ${signatures}; after each signature ${undoWords()}.` : "Nothing to release yet."; + const release = matchAct("match-release", "bi-key", "Release", revealed(releaseHint), !(count || bad), run); + release.setAttribute("aria-disabled", String(Boolean(bad))); + const skipHint = open ? `Skip: on to the next card, the release card to the back (A, W, left or up arrow, swipe left); S undoes the last step` : "Skip: no other card waits"; + const cancel = matchAct("match-drop", "bi-x-lg", "Cancel", revealed(bad ? `Cancel: drop the ${bad === 1 ? "row" : `${bad} rows`} that cannot be released, and their cards leave the deck.\n${badWhy}` : "Cancel: no row is blocked, nothing to drop."), !bad, () => dropUnreleasable(plan.bad)); 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"}, [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("p", {class: "muted match-release-hint"}, [count ? "D, → or a right swipe releases" : "", open ? "A, W, ← or a left swipe skips 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."), - h("div", {class: "actions"}, cancel, back ? iconBtn("bi-stack", `Back to the stack (${open})`, "btn ghost match-back", back) : null, h("span", {class: "spacer"}), release))); + 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, every dropped expired card is dismissed in the hub for every browser without a message."), + picked.length ? h("ol", {class: "match-decisions"}, picked.map(([card, decision]) => overviewRow(card, decision))) : h("p", {class: "muted"}, "No decision yet."))); paint(article, "release"); - matchView.release = {accept: count || bad ? run : null, reject: back, later: back}; + matchView.release = {accept: count || bad ? run : null, reject: skip, later: skip}; draggable(article, matchView.release, () => false); - return article; + return {card: article, actions: h("div", {class: "match-actions"}, cancel, matchAct("match-skip", "bi-arrow-up", "Skip", skipHint, !skip, skip), release)}; } /** @@ -1055,13 +1174,14 @@ keep(STORE.peeks, !peeksShown()); drawMatch(true); }}}, icon("bi-collection")); - const glass = matchGlass("small"); - matchView.dom = {stack, count, decisions, tally, peeks, glass}; + const hiddenCount = h("span", {class: "match-hidden-count"}); + const hidden = h("button", {type: "button", class: "btn small soft match-hidden", hidden: true, "aria-haspopup": "menu", ...named("Hidden cards", "Hidden cards: the Show filter hides them; a click opens the menu to show them again"), on: {click: openShowMenu}}, icon("bi-eye-slash"), hiddenCount); + matchView.dom = {stack, count, decisions, tally, peeks, hidden, hiddenCount}; matchView.sig = ""; if (matchView.drag) { matchView.drag.end(); } - const bar = boxHead("Match", "task-toolbar", h("strong", {class: "box-title"}, icon("bi-stack"), "Match"), glass, count, h("span", {class: "spacer"}), decisions, peeks, + const bar = boxHead("Match", "task-toolbar", h("strong", {class: "box-title"}, icon("bi-stack"), "Match"), count, hidden, 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); @@ -1079,7 +1199,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.glass, matchView.dom.count, matchView.dom.decisions, matchView.dom.peeks)); + homeView.heads.set("tasks/match", h("div", {role: "toolbar", "aria-label": "Match"}, matchView.dom.count, matchView.dom.hidden, matchView.dom.decisions, matchView.dom.peeks)); homeView.hosts.set("tasks/match", host); window.setTimeout(() => drawMatch(true), 0); return host; @@ -1094,21 +1214,24 @@ fetchMatch(); } if (matchView.cards === null) { - dom.stack.replaceChildren(h("p", {class: "muted"}, "Loading cards …")); + fadeSwap(dom.stack, [h("p", {class: "muted"}, "Loading cards …")]); return; } const cards = matchOrder(matchView.cards); const byId = new Map(cards.map((card) => [card.id, card])); [...matchView.decisions].forEach(([id, decision]) => { const card = byId.get(id); - if (decision.verdict === "accept" && (!card || card.stale || card.hash !== decision.hash)) { + const lapsedAway = decision.verdict === "drop" && !card; + if (lapsedAway || (decision.verdict === "accept" && (!card || card.stale || card.hash !== decision.hash))) { matchView.decisions.delete(id); if (card && card.hash !== decision.hash) { toast(`Accept dropped: ${card.title}`, ["The card changed since your accept: decide it again."], false); } } }); - const open = cards.filter((card) => !decisionOf(card)); + const filter = matchHidden(); + const split = showSplit(cards, filter); + const open = split.open; const waiting = open.filter((card) => !card.stale && !card.blocked); if (!matchView.decisions.size) { matchView.order = matchView.order.filter((id) => id !== RELEASE); @@ -1116,64 +1239,85 @@ matchView.order.push(RELEASE); } const cleared = matchView.openBefore > 0 && !waiting.length && matchView.decisions.size > 0; - matchView.openBefore = waiting.length; if (cleared) { toFront(RELEASE); } - const byOpen = new Map(open.map((card) => [card.id, card])); + const byOpen = new Map(split.shown.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, 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)]); + 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, [...filter], Math.floor(state.now / DAY)]); if (!force && sig === matchView.sig && !cleared) { + matchView.openBefore = waiting.length; return; } + const before = dom.stack.querySelector(".match-card.front"); + if (before && !before.dataset.fly && before.dataset.card !== (rotation[0] || null)) { + Object.assign(matchView, {front: null, release: null}); + vanish(before, () => drawMatch(true)); + return; + } + matchView.openBefore = waiting.length; matchView.sig = sig; - dom.count.textContent = open.length === 1 ? "1 card waits" : `${open.length} cards wait`; + dom.count.textContent = split.shown.length === 1 ? "1 card waits" : `${split.shown.length} cards wait`; + dom.hidden.hidden = !split.hidden; + dom.hiddenCount.textContent = hiddenWords(split.hidden); dom.tally.textContent = String(matchView.decisions.size); dom.peeks.setAttribute("aria-pressed", String(peeksShown())); dom.decisions.hidden = !matchView.decisions.size || releasing; matchView.release = null; + if (!rotation.length && split.hidden) { + matchView.front = null; + const empty = emptyState(allHiddenWords(split.hidden), "The Show filter of the right-click menu hides them; Show all brings every card back."); + empty.classList.add("match-empty", "match-all-hidden"); + empty.querySelector(".empty-mark").replaceWith(h("span", {class: "match-hidden-mark", "aria-hidden": "true", title: allHiddenWords(split.hidden)}, icon("bi-eye-slash"))); + empty.append(h("button", {type: "button", class: "btn primary match-show-all", ...named("Show all", "Show all: every card kind and state back in the deck"), on: {click: showAll}}, icon("bi-eye"), "Show all")); + fadeSwap(dom.stack, [h("div", {class: "match-deck"}, empty)]); + return; + } if (!rotation.length) { matchView.front = null; const empty = emptyState("No card waits", "Nothing waits on the operator."); - empty.querySelector(".empty-mark").replaceWith(matchGlass("large")); - dom.stack.replaceChildren(empty); + empty.classList.add("match-empty"); + empty.querySelector(".empty-mark").replaceWith(matchGlass()); + fadeSwap(dom.stack, [h("div", {class: "match-deck"}, empty)]); return; } const behind = rotation.slice(1).filter((id) => id !== RELEASE).map((id) => byOpen.get(id)); dom.stack.dataset.wide = String(matchWide()); - const before = dom.stack.querySelector(".match-card.front"); const peekRow = (rest) => (rest.length && peeksShown() ? h("div", {class: "match-peeks", role: "group", "aria-label": `${rest.length} more cards`}, rest.map(peekTab)) : null); if (releasing) { matchView.front = null; const scrolledRelease = before && before.dataset.card === "release" ? before.querySelector(".match-body").scrollTop : 0; - const shown = releaseCard(cards, behind.length); + const {card: shown, actions} = releaseCard(cards, behind.length); shown.dataset.fresh = String(!before || before.dataset.card !== "release"); if (cleared) { - shown.prepend(confetti()); + confetti(); } const peeksBelow = peekRow(behind); - dom.stack.replaceChildren(h("div", {class: "match-deck"}, layersOf(behind), shown), ...(peeksBelow ? [peeksBelow] : [])); - shown.querySelector(".match-body").scrollTop = scrolledRelease; + fadeSwap(dom.stack, [h("div", {class: "match-deck"}, layersOf(behind), shown), actions, ...(peeksBelow ? [peeksBelow] : [])], (root, swap) => { + swap(); + shown.querySelector(".match-body").scrollTop = scrolledRelease; + }); return; } const front = byOpen.get(rotation[0]); const rest = behind; matchView.front = front; - const act = (cls, iconName, word, hint, disabled, run) => h("button", {type: "button", class: `match-act ${cls}`, disabled, ...named(word, hint), on: {click: run}}, - h("span", {class: "match-act-face", "aria-hidden": "true"}, icon(iconName)), h("span", {class: "match-act-label"}, word)); 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 accept = matchAct("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 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 lapseHint = front.blocked_kind === "claude" ? "Reject: its dialog is open in Claude, answer it there; a reject here sends your feedback to its agent by radio (A, left arrow, swipe left)" : "Reject: it expired before you decided; it leaves the deck at once, without feedback or a message, and the release dismisses it for every browser (A, left arrow, swipe left; S undoes)"; + const rejectHint = lapsed ? lapseHint : front.blocked ? `Reject: not possible now. ${front.blocked}` : pickOnly(front) ? "Reject: a choice is answered with one of its options" : declining; + const reject = matchAct("match-reject", "bi-x-lg", "Reject", revealed(rejectHint), !lapsed && (Boolean(front.blocked) || pickOnly(front)), () => rejectCard(front)); + const later = matchAct("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: 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; + fadeSwap(dom.stack, [h("div", {class: "match-deck"}, layersOf(rest), shown), h("div", {class: "match-actions"}, reject, later, accept), ...(peeks ? [peeks] : [])], (root, swap) => { + keepTyping(root, swap); + shown.querySelector(".match-body").scrollTop = scrolled; + }); } diff --git a/orchestrator/templates/page-palette.js b/orchestrator/templates/page-palette.js index 2b82963..5e78ae2 100644 --- a/orchestrator/templates/page-palette.js +++ b/orchestrator/templates/page-palette.js @@ -154,6 +154,9 @@ } function closePalette() { - document.getElementById("palette").hidden = true; + const box = document.getElementById("palette"); + if (!box.hidden) { + fadeShut(box); + } palette.plan = null; } diff --git a/orchestrator/templates/page-passkey.js b/orchestrator/templates/page-passkey.js index 97dcc55..7a6d7ea 100644 --- a/orchestrator/templates/page-passkey.js +++ b/orchestrator/templates/page-passkey.js @@ -32,7 +32,7 @@ toast(`${label}: not signed`, [`${(error && error.name) || error}: KeePassXC locked or canceled; nothing was sent.`], false); return null; } finally { - prompt.remove(); + vanish(prompt); } } diff --git a/orchestrator/templates/page-prune.js b/orchestrator/templates/page-prune.js index bcde0f2..4006c02 100644 --- a/orchestrator/templates/page-prune.js +++ b/orchestrator/templates/page-prune.js @@ -1,5 +1,5 @@ const PRUNE_TICK = 1000; - const pruneView = {days: Prune.STALE_DAYS, ticked: new Set(), dial: null, body: null, timer: null}; + const pruneView = {days: Prune.STALE_DAYS, ticked: new Set(), filter: "", collapsed: new Set(), dial: null, timer: null}; const pruneNow = () => Date.now() / 1000; const pruneClock = (epoch) => new Date(epoch * 1000).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit"}); @@ -7,16 +7,11 @@ 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)) { + if (pending) { + for (const left of document.querySelectorAll(".prune-left")) { + left.textContent = Dial.countdown(pending.left); + } + } else { window.clearInterval(pruneView.timer); pruneView.timer = null; } @@ -30,48 +25,145 @@ /** * @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. + * @returns {Object} open: the Prune stale entry of the Actions menu, which opens + * the prune dialog and, while a signed prune waits for its deadline, shows the countdown; chip: for that wait the + * compact countdown chip of the toolbar naming its tasks and deadline, else null. */ function pruneControls(stale) { const pending = Prune.pending(state.jobs || [], pruneNow()); - const open = h("button", {type: "button", class: "btn small icon-only", 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")); + const left = pending ? Dial.countdown(pending.left) : ""; + const hint = pending ? `Prune stale: signed, stops ${pending.tasks.join(", ")} at ${pruneClock(pending.deadline)}; opens the countdown` : "Prune stale tasks: one passkey signs the list and a deadline; the agents can keep a task until then"; + const open = h("button", {type: "button", class: "btn small", id: "kanban-prune-open", disabled: !stale && !pending, ...named("Prune stale", hint)}, + icon("bi-scissors"), h("span", {class: "tool-word"}, "Prune stale"), pending ? h("span", {class: "prune-left"}, left) : null); open.addEventListener("click", openPrune); if (!pending) { - return [open]; + return {open, chip: null}; } 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]; + const chip = h("span", {class: "pill prune-chip", id: "kanban-prune", "data-key": "kanban-prune", "data-tone": "warn", "data-deadline": String(pending.deadline), role: "timer", ...named(`Prune in ${left}`, words)}, + icon("bi-hourglass-split"), h("span", {class: "prune-left"}, 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"}, + const pruneChosen = (rows) => rows.filter((row) => pruneView.ticked.has(row.task) && Prune.matches(row, pruneView.filter)).map((row) => row.task); + + /** + * @param {Object} dom the open dialog: {groups, rows, none, count, go}. + * Brings every row and group in line with pruneView: rows outside the filter hidden, each row's tick, each group's + * count of shown rows and its checkbox (checked when every shown row is ticked, indeterminate when some are), and + * "Prune N" with N the ticked rows the filter shows. + */ + function pruneSync(dom) { + const shown = new Set(dom.rows.filter((row) => Prune.matches(row, pruneView.filter)).map((row) => row.task)); + for (const item of dom.groups.querySelectorAll("li[data-task]")) { + item.hidden = !shown.has(item.dataset.task); + item.querySelector("input[type=checkbox]").checked = pruneView.ticked.has(item.dataset.task); + } + for (const section of dom.groups.querySelectorAll(".prune-group")) { + const tasks = [...section.querySelectorAll("li[data-task]")].map((item) => item.dataset.task).filter((task) => shown.has(task)); + const ticked = tasks.filter((task) => pruneView.ticked.has(task)).length; + const all = section.querySelector(".prune-group-check"); + section.hidden = !tasks.length; + section.querySelector(".prune-group-head .count").textContent = String(tasks.length); + all.checked = tasks.length > 0 && ticked === tasks.length; + all.indeterminate = ticked > 0 && ticked < tasks.length; + } + if (dom.none) { + dom.none.hidden = shown.size > 0; + } + const chosen = pruneChosen(dom.rows).length; + dom.count.textContent = String(chosen); + dom.go.disabled = !chosen; + } + + function pruneRow(row, dom) { + const owner = Prune.owner(row); + const days = Math.floor((state.now - row.updated) / 86400); + return 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; + pruneSync(dom); + }}}), + h("span", {class: "prune-owner", title: owner === "-" ? "No owner" : revealed(owner)}, face(owner, false)), + h("code", {class: "task-id"}, row.task), + h("span", {class: "pill prune-age", "data-tone": "neutral", title: `No register change for ${days} days`}, `${days} d`))); } - function retick(list, count) { - pruneView.ticked = new Set(pruneStale().map((row) => row.task)); - pruneRows(list, count); + function pruneGroup(group, dom) { + const open = !pruneView.collapsed.has(group.prefix); + const id = `prune-group-${group.prefix}`; + const list = h("ul", {class: "prune-list", id, hidden: !open, "aria-label": `${group.prefix} tasks`}, group.rows.map((row) => pruneRow(row, dom))); + const all = h("input", {type: "checkbox", class: "prune-group-check", "aria-label": `Prune every shown ${group.prefix} task`, on: {change: (event) => { + for (const item of list.querySelectorAll("li[data-task]:not([hidden])")) { + if (event.target.checked) { + pruneView.ticked.add(item.dataset.task); + } else { + pruneView.ticked.delete(item.dataset.task); + } + } + pruneSync(dom); + }}}); + const toggle = h("button", {type: "button", class: "prune-group-toggle", "aria-expanded": String(open), "aria-controls": id, title: `${group.prefix}: ${open ? "collapse" : "expand"}`, on: {click: () => { + const opening = list.hidden; + if (opening) { + pruneView.collapsed.delete(group.prefix); + } else { + pruneView.collapsed.add(group.prefix); + } + list.hidden = !opening; + toggle.setAttribute("aria-expanded", String(opening)); + toggle.title = `${group.prefix}: ${opening ? "collapse" : "expand"}`; + toggle.firstChild.replaceWith(icon(opening ? "bi-chevron-down" : "bi-chevron-right")); + }}}, icon(open ? "bi-chevron-down" : "bi-chevron-right"), h("span", {class: "prune-prefix"}, `${group.prefix}/`), counter(group.rows.length)); + return h("section", {class: "prune-group", "data-key": `prune-group:${group.prefix}`, "data-group": group.prefix}, + h("div", {class: "prune-group-head"}, all, toggle), list); + } + + /** + * @param {Object} dom the open dialog: {groups, rows, none, count, go}. + * Lists the stale tasks for pruneView.days in one section per prefix, dropping ticks of tasks no longer stale; + * fadeSwap() fades the rows that leave. + */ + function pruneRender(dom) { + dom.rows = pruneStale(); + const tasks = new Set(dom.rows.map((row) => row.task)); + pruneView.ticked = new Set([...pruneView.ticked].filter((task) => tasks.has(task))); + dom.none = dom.rows.length ? h("p", {class: "muted prune-none", hidden: true}, "No stale task matches the filter.") : null; + const nodes = dom.rows.length ? [...Prune.groups(dom.rows).map((group) => pruneGroup(group, dom)), dom.none] + : [h("p", {class: "muted"}, `No task without a register change for ${pruneView.days} days.`)]; + fadeSwap(dom.groups, nodes, (box, swap) => { + swap(); + pruneSync(dom); + }); + } + + function pruneDays(dom, field) { + const days = Prune.daysOf(field.value); + field.setAttribute("aria-invalid", String(days === null)); + if (days !== null) { + pruneView.days = days; + pruneView.ticked = new Set(pruneStale().map((row) => row.task)); + pruneRender(dom); + } + } + + function pruneStepper(dom) { + const field = h("input", {class: "field", type: "number", inputmode: "numeric", min: Prune.DAYS.min, max: Prune.DAYS.max, step: 1, id: "prune-days", value: String(pruneView.days), "aria-label": "Days without a register change", on: {change: () => pruneDays(dom, field)}}); + const step = (by, glyph, label) => h("button", {type: "button", class: "btn small icon-only", ...named(label, `${label}: the stale age, ${Prune.DAYS.min} to ${Prune.DAYS.max} days`), on: {click: () => { + field.value = String(Math.min(Prune.DAYS.max, Math.max(Prune.DAYS.min, pruneView.days + by))); + pruneDays(dom, field); + }}}, icon(glyph)); + return h("div", {class: "prune-days"}, h("label", {class: "muted", for: "prune-days"}, "Stale after days"), + h("span", {class: "prune-stepper"}, step(-1, "bi-dash-lg", "One day less"), field, step(1, "bi-plus-lg", "One day more"))); } async function signPrune(body) { - const tasks = pruneStale().map((row) => row.task).filter((task) => pruneView.ticked.has(task)); + const tasks = pruneChosen(pruneStale()); const since = Math.floor(pruneNow()); const items = Prune.items(tasks, pruneView.days, since, pruneView.dial.value()); const label = `Prune ${tasks.length} stale tasks`; @@ -91,43 +183,38 @@ 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(); + readout: (minutes) => Dial.countdown(minutes * Prune.MINUTE), spoken: (minutes) => `${minutes} minutes until the prune`, readonly: true, live: Dial.counting(pending.deadline, Prune.MINUTE)}); body.replaceChildren(h("p", {}, `Signed: the hub runner stops these tasks at ${pruneClock(pending.deadline)} unless an agent keeps one (rasci.py keep ) or changes it first.`), - h("div", {class: "prune-wait"}, pruneView.dial.root, h("strong", {class: "prune-left", role: "timer"}, Prune.clock(pending.left))), + h("div", {class: "prune-wait"}, pruneView.dial.root), 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}); + pruneView.dial = dial({value: range.value, label: "Answer window in minutes", name: "prune-dial", min: range.min, max: range.max, page: range.page, + readout: (minutes) => Dial.countdown(minutes * Prune.MINUTE), spoken: (minutes) => `${minutes} minutes for the agents to keep a task`, readonly: false, live: null}); 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); + const go = h("button", {type: "button", class: "btn primary", id: "prune-sign", ...named("Prune", "Prune: one passkey signs the ticked tasks the filter shows 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); - } + const dom = {groups: h("div", {class: "prune-groups", role: "group", "aria-label": "Stale tasks"}), rows: [], none: null, count, go}; + const filter = h("input", {class: "field prune-filter", type: "search", id: "prune-filter", value: pruneView.filter, placeholder: "Filter tasks", "aria-label": "Filter the stale tasks", on: {input: (event) => { + pruneView.filter = event.target.value; + pruneSync(dom); }}}); - 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); + body.replaceChildren(h("div", {class: "prune-tools"}, pruneStepper(dom), filter), dom.groups, + h("div", {class: "prune-foot"}, 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))); + pruneView.ticked = new Set(pruneStale().map((row) => row.task)); + pruneRender(dom); } function openPrune() { - pruneView.days = Prune.STALE_DAYS; + Object.assign(pruneView, {days: Prune.STALE_DAYS, filter: "", collapsed: new Set()}); const body = h("div", {class: "stack prune-dialog"}); openSheet("Prune stale tasks", body, false); drawPrune(body); diff --git a/orchestrator/templates/page-queue.js b/orchestrator/templates/page-queue.js index 19cfe60..c79430b 100644 --- a/orchestrator/templates/page-queue.js +++ b/orchestrator/templates/page-queue.js @@ -162,7 +162,7 @@ function drawQueueJobs() { const dom = queueTab.dom; if (dom && dom.jobs.isConnected) { - dom.jobs.replaceChildren(waitingJobs()); + fadeSwap(dom.jobs, [waitingJobs()]); if (Date.now() - queueTab.at >= QUEUE_REFRESH) { fetchQueue(); } diff --git a/orchestrator/templates/page-radio.js b/orchestrator/templates/page-radio.js index e31b5ad..7ec046a 100644 --- a/orchestrator/templates/page-radio.js +++ b/orchestrator/templates/page-radio.js @@ -44,7 +44,7 @@ } radioStatus(kind, label, note); if (told) { - told.box.remove(); + vanish(told.box); } const stream = settings.streams[radio.index]; const box = toast(`Radio ${kind === "blocked" ? "blocked" : "silent"}: ${stream ? stream.name : radio.url}`, [note], false); diff --git a/orchestrator/templates/page-radiolog.js b/orchestrator/templates/page-radiolog.js index cc6f501..c81190f 100644 --- a/orchestrator/templates/page-radiolog.js +++ b/orchestrator/templates/page-radiolog.js @@ -92,7 +92,7 @@ } function patchList(list, lines) { - const before = [...list.children]; + const before = [...list.children].filter((child) => !child.dataset.vanishing); const focused = before.find((node) => node.contains(document.activeElement)) || null; const old = new Map(before.filter((node) => node.dataset.key).map((node) => [node.dataset.key, node])); const wanted = lines.map((line) => { @@ -101,17 +101,18 @@ return kept ? keepLine(kept, line) : line; }); const keep = new Set(wanted); - for (const node of before.filter((child) => !keep.has(child))) { - node.remove(); - } + const gone = before.filter((child) => !keep.has(child)); + gone.forEach((node) => vanish(node)); + const staying = () => [...list.children].filter((child) => !child.dataset.vanishing); wanted.forEach((node, index) => { - if (list.children[index] !== node) { - list.insertBefore(node, list.children[index] || null); + const at = staying()[index]; + if (at !== node) { + list.insertBefore(node, at || null); } }); - if (focused && !focused.isConnected) { + if (focused && gone.includes(focused)) { const at = before.indexOf(focused); - const near = before.filter((node) => node.isConnected && node.querySelector(".radio-pick")).sort((a, b) => Math.abs(before.indexOf(a) - at) - Math.abs(before.indexOf(b) - at))[0]; + const near = before.filter((node) => keep.has(node) && node.querySelector(".radio-pick")).sort((a, b) => Math.abs(before.indexOf(a) - at) - Math.abs(before.indexOf(b) - at))[0]; (near ? near.querySelector(".radio-pick") : list).focus({preventScroll: true}); } } diff --git a/orchestrator/templates/page-resources.js b/orchestrator/templates/page-resources.js index 9bad324..6cf5fe5 100644 --- a/orchestrator/templates/page-resources.js +++ b/orchestrator/templates/page-resources.js @@ -7,11 +7,20 @@ blocked: ["#bi-sign-stop", (mark) => revealed(`${mark.head} waited ${Math.round(mark.peak / 60)} min: ${mark.reason}`), 1], hung: ["#bi-pause-circle", (mark) => revealed(`suspect hung: ${mark.hung.join(", ")}`), 2], asleep: ["#bi-moon", (mark) => `${mark.name} asleep`, 0], - unknown: ["#bi-question-circle", (mark) => `${mark.name} unknown: no reading`, 0], + unknown: ["#bi-question-circle", (mark) => revealed(`${mark.name} unknown: ${mark.causes.length ? mark.causes.join("; ") : "no reading"}`), 0], }; const RESOURCE_BURN = {done: "Done", scope: "Scope"}; 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 RESOURCE_SHOW = [ + ["legend", "Legend", "the series chips above each chart; a chip still switches its series on and off"], + ["queue", "Queue markers", "the spans of a queue head blocked for 10 minutes and of suspect hung jobs"], + ["waits", "Wait bands", "the spans where jobs waited while CPU and RAM stayed under 50 %"], + ["limits", "Limit lines", "lower, upper, STOP, MAYDAY and the live target of the picked metric"], + ]; + const RESOURCE_SHOW_KEY = "kvb-orchestrator.resources-view"; + const RESOURCE_SHOW_MARKS = {wait: "waits", blocked: "queue", hung: "queue"}; + const resourceView = {data: null, dom: null, busy: false, key: "", at: 0, timer: 0, series: {}, show: {legend: true, queue: true, waits: true, limits: true}}; + const resourceShowOf = (value) => Object.fromEntries(RESOURCE_SHOW.map(([key]) => [key, !(value && value[key] === false)])); const resourceKey = () => JSON.stringify([ui.preset, ui.asOf]); const resourcesStale = () => resourceKey() !== resourceView.key || nowSeconds() - resourceView.at >= RESOURCE.stale; const compactCount = Resources.compact; @@ -33,22 +42,42 @@ return {menu, boxes}; } + /** + * @returns {Object} {menu, boxes}: the View menu, a checkbox each for the legend, the queue markers, the wait bands + * and the limit lines, every choice kept in this browser. + */ + function resourceShowMenu() { + const boxes = RESOURCE_SHOW.map(([key, label, hint]) => { + const box = h("input", {type: "checkbox", "data-show": key, "aria-label": label, on: {change: () => { + resourceView.show = {...resourceView.show, [key]: box.checked}; + keep(RESOURCE_SHOW_KEY, resourceView.show); + drawResources(); + }}}); + return {key, box, row: h("label", {class: "menu-item res-pick", title: `${label}: ${hint}`}, box, h("span", {}, label))}; + }); + const menu = h("details", {class: "menu res-view-menu"}, h("summary", {...named("View", "View: show or hide the legend, the queue markers, the wait bands and the limit lines; this browser keeps the choice")}, icon("bi-eye"), h("span", {}, "View"), caret()), + h("div", {class: "menu-box end", role: "group", "aria-label": "View"}, boxes.map((entry) => entry.row))); + return {menu, boxes}; + } + function resourcesScreen() { const count = h("span", {class: "count", title: "Samples", "aria-label": "Samples"}, "0"); const switches = { tokens: resourceSwitch("tokens", (mode) => (mode === "accumulated" ? "interval" : "accumulated"), "bi-graph-up-arrow", "Accumulated", "Accumulated: per-agent running sums of the tokens instead of the tokens per hour"), }; const picks = resourcePicks(); + resourceView.show = resourceShowOf(stored(RESOURCE_SHOW_KEY, null)); + const shows = resourceShowMenu(); const panels = RESOURCE_PANELS.map(([kind, name, label]) => { const legend = h("div", {class: "res-legend"}); - const plot = h("div", {class: "res-plot"}); + const plot = h("div", {class: "res-plot", ...(kind === "hardware" ? {on: {contextmenu: limitContext}} : {})}); 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), kind === "hardware" ? limitBar() : null, plot); return {kind, label, legend, plot, panel}; }); const accounts = accountsPanel(); const usage = usagePanel(); - resourceView.dom = {count, switches, picks, panels, accounts, usage}; + resourceView.dom = {count, switches, picks, shows, panels, accounts, usage}; if (!resourceView.timer) { resourceView.timer = window.setInterval(pollResources, RESOURCE.poll); window.addEventListener("resize", drawResources); @@ -67,7 +96,7 @@ } }, "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)), + boxHead("Resources", "", h("div", {class: "toolbar"}, reload, switches.tokens, picks.menu, shows.menu, count)), h("div", {class: "res-panels"}, panels.map((entry) => entry.panel), accounts.panel, usage.panel)); } @@ -379,11 +408,14 @@ function drawResources() { const dom = resourceView.dom; const data = resourceView.data; - if (!dom || !dom.count.isConnected) { + if (!dom || !dom.count.isConnected || limitView.drag) { return; } const view = ViewStore.get("resources"); dom.switches.tokens.setAttribute("aria-pressed", String(view.tokens === "accumulated")); + for (const {key, box} of dom.shows.boxes) { + box.checked = resourceView.show[key]; + } for (const {kind, box} of dom.picks.boxes) { box.checked = view.panels.includes(kind); box.disabled = box.checked && view.panels.length === 1; @@ -405,8 +437,10 @@ } const active = document.activeElement; const focused = active && typeof active.getAttribute === "function" ? active.getAttribute("data-chip") : null; + const line = active && typeof active.getAttribute === "function" ? active.getAttribute("data-line") : null; const span = {from: data.since, to: Math.max(data.until, data.since + 60)}; const parts = resourceParts(data, view, span); + parts.marks = parts.marks.filter((mark) => !Object.hasOwn(RESOURCE_SHOW_MARKS, mark.kind) || resourceView.show[RESOURCE_SHOW_MARKS[mark.kind]]); dom.count.textContent = String(data.samples.length); for (const entry of dom.panels) { if (entry.panel.hidden) { @@ -421,9 +455,14 @@ resourceView.series[entry.kind] = {ids: drawn.series.map((line) => line.id), shown: drawn.series.map((line) => line.id).filter((id) => !hidden.has(id)), tokens: view.tokens}; entry.plot.replaceChildren(...(resourceSmall(size) ? [] : [drawn.svg])); entry.legend.replaceChildren(LegendChips.render(drawn.series, drawn.path, "hidden")); + entry.legend.hidden = !resourceView.show.legend; const chip = focused === null ? null : [...entry.legend.querySelectorAll("[data-chip]")].find((node) => node.getAttribute("data-chip") === focused); if (chip) { chip.focus(); } + const limit = line === null || entry.kind !== "hardware" ? null : entry.plot.querySelector(`g.res-limit[data-line="${line}"]`); + if (limit) { + limit.focus(); + } } } diff --git a/orchestrator/templates/page-running.js b/orchestrator/templates/page-running.js index a29b2e6..c9bf7d1 100644 --- a/orchestrator/templates/page-running.js +++ b/orchestrator/templates/page-running.js @@ -2,6 +2,14 @@ const markSources = () => ({now: state.now, tasks: state.tasks, beats: state.beats, runner: state.runner}); + /** + * @param row - a task row. + * @param found - Kanban.marks of the row. + * @returns {boolean} whether the row works right now: it runs and a queue job, an agent beat or the hub job backs + * that, so it carries the heartbeat class is-working; a queued, waiting, stale or ended row stays still. + */ + const taskWorking = (row, found) => row.status === "running" && !row.ended && found.length > 0; + /** * @param row - a card's task row. * @param found - Kanban.marks of the row. @@ -13,7 +21,7 @@ } 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))); + h("span", {class: "pill kanban-mark", "data-mark": mark.key, "data-tone": "neutral", role: "img", ...named(`${RUNNING_WORDS[mark.key]}: ${mark.text}`, hint(mark))}, icon(mark.icon), mark.text))); } /** @@ -26,5 +34,5 @@ kanban.running = !kanban.running; taskView.sig = ""; drawTasks(); - }}}, icon("bi-activity"), counter(count)); + }}}, icon("bi-activity"), h("span", {class: "tool-word"}, "Running"), counter(count)); } diff --git a/orchestrator/templates/page-screens.js b/orchestrator/templates/page-screens.js index 481c73b..500667c 100644 --- a/orchestrator/templates/page-screens.js +++ b/orchestrator/templates/page-screens.js @@ -43,17 +43,40 @@ window.setTimeout(() => homeOpen(route.open, route.screen, HOME_TRIES), 0); } }; - if (document.startViewTransition && drawn.screen && !calm.matches) { - document.startViewTransition(show).ready.catch((error) => { - if (error.name !== "AbortError") { - throw error; - } - }); + if (drawn.screen) { + fadeTransition(show); } else { show(); } } + const viewShift = {running: false}; + + /** + * @param {Function} run changes the DOM. + * @returns {Promise} settles once run has changed the DOM. Inside a View Transition, so what leaves fades out; at once + * without the API, under prefers-reduced-motion and while another transition runs, whose live new view then shows + * the change. + */ + function fadeTransition(run) { + if (!document.startViewTransition || calm.matches || viewShift.running) { + run(); + return Promise.resolve(); + } + viewShift.running = true; + const shift = document.startViewTransition(run); + const done = () => { + viewShift.running = false; + }; + shift.finished.then(done, done); + shift.ready.catch((error) => { + if (error.name !== "AbortError") { + throw error; + } + }); + return shift.updateCallbackDone; + } + function signature() { if (ui.screen === "agents") { return JSON.stringify([ui.views.agents]); diff --git a/orchestrator/templates/page-settings.js b/orchestrator/templates/page-settings.js index 26cb1ae..92ba4c1 100644 --- a/orchestrator/templates/page-settings.js +++ b/orchestrator/templates/page-settings.js @@ -69,7 +69,7 @@ h("div", {class: "days"}, days.map((box, index) => h("label", {class: "check"}, box, WEEKDAYS[index])), h("label", {class: "check"}, on, "active"), h("span", {class: "spacer"}), btn("Remove", "btn small danger", () => { rows.splice(rows.indexOf(entry), 1); - entry.row.remove(); + vanish(entry.row); }))); rows.push(entry); list.append(entry.row); @@ -132,6 +132,7 @@ const musicOn = h("input", {type: "checkbox", checked: settings.music.on}); const volume = h("input", {type: "range", min: 0, max: 1, step: 0.05, value: settings.music.volume, "aria-label": "Overall volume"}); const undo = undoDial(settings.undo, "Undo window in seconds"); + const hookWait = h("input", {class: "field hook-wait", type: "number", min: 1, max: 60, step: 1, value: settings.hook.wait, required: true, "aria-label": "Hook wait in minutes"}); const form = h("form", {class: "settings"}, ambience(), h("section", {}, h("h3", {}, "Location"), h("p", {class: "muted"}, "Sun, moon and stars stand where you see them from here, looking south; under 🔭 Sky (key h) you turn the view. Decimal degrees, north and east positive."), @@ -140,6 +141,8 @@ h("section", {}, h("h3", {}, "Music"), h("p", {class: "muted"}, "Generative ambient music, made offline: calm with an empty inbox, a little tenser when something waits, quieter under messages."), h("div", {class: "grid"}, h("label", {class: "check"}, musicOn, "Music on"), h("label", {}, "Overall volume (music and radio)", volume))), h("section", {class: "undo-window"}, h("h3", {}, "Undo window"), h("p", {class: "muted"}, "Seconds between a passkey signature and the moment it takes effect, to undo it; 0 takes effect at once. Drag the hand, click a tick, or use the arrows (1 s) and Page Up / Down (5 s)."), undo.root), + h("section", {class: "hook-wait-section"}, h("h3", {}, "Claude dialogs"), h("p", {class: "muted"}, "Minutes the permission hook waits for your answer here while Claude shows the same dialog, 1 to 60; whichever side answers first wins, and an answer in Claude closes the card at once. After the wait the card reads \"open in Claude\" until Claude answers it. Takes effect after make orchestrator-hook and a restart of the Claude sessions."), + h("label", {}, "Hook wait in minutes", hookWait)), passkeySection(), h("div", {class: "sheet-foot"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), h("button", {type: "submit", class: "btn primary"}, "Save"))); form.addEventListener("submit", async (event) => { @@ -164,6 +167,7 @@ rates: settings.rates, undo: undo.value(), match: settings.match, + hook: {wait: Number(hookWait.value)}, }; if (await saveSettings(next)) { closeSheet(); diff --git a/orchestrator/templates/page-spawn.js b/orchestrator/templates/page-spawn.js index 5855a6b..f05a25a 100644 --- a/orchestrator/templates/page-spawn.js +++ b/orchestrator/templates/page-spawn.js @@ -92,8 +92,8 @@ const open = entry.kind === "twig" ? () => focusSub(entry.session, entry.row.id) : entry.kind === "operator" ? null : () => select(entry.id); const name = open ? h("button", {type: "button", class: "linkish", title: entry.kind === "twig" ? "Show transcript in the stream" : `Open ${entry.label}`, "data-pick": entry.kind === "twig" ? null : entry.id, on: {click: open}}, entry.label) : h("strong", {}, entry.label); const meta = entry.kind === "twig" ? h("span", {class: "muted"}, `Depth ${entry.row.depth} · `, when(entry.row.started)) : h("span", {class: "muted"}, NODE_KINDS[entry.kind]); - return h("li", {"data-kind": entry.kind, "data-running": entry.running === null ? null : String(entry.running)}, - h("div", {class: "spawn-row"}, h("span", {class: "state", role: "img", ...named(NODE_KINDS[entry.kind] || "Subagent")}, icon(SPAWN_KINDS[entry.kind])), name, entry.kind === "session" || entry.kind === "chair" ? presenceMark(entry.id, false) : null, running, meta), + return h("li", {"data-key": entry.id, "data-kind": entry.kind, "data-running": entry.running === null ? null : String(entry.running)}, + h("div", {class: entry.running ? "spawn-row is-working" : "spawn-row"}, h("span", {class: "state", role: "img", ...named(NODE_KINDS[entry.kind] || "Subagent")}, icon(SPAWN_KINDS[entry.kind])), name, entry.kind === "session" || entry.kind === "chair" ? presenceMark(entry.id, false) : null, running, meta), entry.children.length ? h("ul", {class: "spawn-tree"}, entry.children.map(spawnItem)) : null); } @@ -115,8 +115,8 @@ const root = spawnTree(); const all = spawnFlat(root).map(({entry}) => entry).filter((entry) => entry.running !== null); const running = all.filter((entry) => entry.running).length; - spawn.dom.list.replaceChildren( + fadeSwap(spawn.dom.list, [ h("div", {class: "inbox-head"}, h("h2", {class: "group-title"}, "Spawn tree", counter(all.length)), h("span", {class: "muted"}, `${running} running · ${all.length - running} finished · Operator → Chair → Sessions → Subagents`)), agentAncestry(root), - h("ul", {class: "spawn-tree root"}, spawnItem(root))); + h("ul", {class: "spawn-tree root"}, spawnItem(root))]); } diff --git a/orchestrator/templates/page-stream.js b/orchestrator/templates/page-stream.js index a8c6025..a4e275e 100644 --- a/orchestrator/templates/page-stream.js +++ b/orchestrator/templates/page-stream.js @@ -50,7 +50,7 @@ entry.text = data.text; entry.ref.truncated = false; holder.textContent = data.text; - button.remove(); + vanish(button); } else { button.textContent = "No longer available"; } @@ -172,7 +172,7 @@ const renamed = entry.now && entry.now !== entry.agent ? h("span", {title: `now: ${entry.now}`}, agentLink(entry.agent)) : agentLink(entry.agent); const who = entry.agent ? renamed : entry.session ? h("strong", {title: entry.session}, entry.session.slice(0, 8)) : null; const headline = entry.kind === "transcript" || entry.kind === "ask" || entry.kind === "operator" ? null : h("span", {class: "headline"}, Receipts.headline(entry)); - const blocked = (item && item.blocked) || (entry.kind === "operator" && entry.ref.blocked) || ""; + const blocked = (item && item.blocked) || (entry.kind === "operator" && entry.ref.blocked) || (entry.ref && entry.ref.status === "claude" ? IN_CLAUDE_HINT : "") || ""; return h("li", {class: `entry k-${entry.kind}${entry.waiting && !answered ? " waiting" : ""}${alarm ? " alarm" : ""}`, "data-ref": item ? keyOf(item) : null, "data-item": `message:${entry.ts}/${entry.id}`, "data-to": item && item.to ? item.to : null, "data-blocked": blocked ? "" : null, "data-answered": answered ? "" : null, title: blocked || null}, h("div", {class: "msg-meta"}, when(entry.ts), kindPill(entry), extras(entry)), @@ -187,31 +187,75 @@ item && !code ? h("div", {class: "line-actions"}, actionsFor(item)) : null)); } + const BEHIND_FOOTER = ["expired", "stale"]; + /** - * @param {boolean} [polled] true from a poll: the rows stay when the shown entries, their inbox items and the error - * are unchanged; any other call redraws them. + * @returns {Object[]} the expired and stale requests the Stream keeps behind its footer line, the newest first; one + * open in Claude is open and stays inline with its "open in Claude" status. + */ + const staleRequests = () => [...state.inbox, ...(state.lapsed || [])].filter((item) => BEHIND_FOOTER.includes(item.request)).sort((a, b) => b.ts - a.ts); + + /** + * @param {Object} entry a stream entry. + * @param {Set} behind kind:id of every staleRequests() item. + * @param {Set} told the hub jobs of the failed rows whose operator entry the feed shows. + * @returns {boolean} whether the feed leaves the entry out: an expired or stale request, which only the footer lists, + * and the runner's line of a failed row the feed already shows once. + */ + function streamHides(entry, behind, told) { + const ref = entry.ref || {}; + return behind.has(`${entry.kind}:${entry.kind === "operator" ? ref.task : ref.id}`) || (entry.kind === "run" && told.has(ref.job)); + } + + /** + * @param {Object[]} items staleRequests(). + * @returns {HTMLElement|null} one collapsed line naming how many stale requests wait and the count per kind; opened it + * lists them in place with select all and Delete N. Null without any. + */ + function staleFooter(items) { + if (!items.length) { + return null; + } + const words = BEHIND_FOOTER.map((kind) => [kind, items.filter((item) => item.request === kind).length]).filter(([, count]) => count).map(([kind, count]) => `${count} ${kind}`).join(" · "); + const row = (item) => h("li", {class: `entry k-${item.kind}`, "data-ref": keyOf(item), "data-request": item.request}, + h("div", {class: "msg-meta"}, when(item.ts), pill(ITEM_LABELS[item.kind], KIND_TONES[item.kind]), pill(item.request, REQUEST_TONES[item.request]), item.agent ? agentLink(item.agent) : null), + h("p", {class: "text stale-title"}, revealed(item.title))); + return h("details", {class: "card stale-footer", "data-key": "stale-footer", open: triage.footer, on: {toggle: (event) => { + triage.footer = event.currentTarget.open; + }}}, h("summary", {title: `Expired and stale requests: ${words}; open to select and delete them`}, `${items.length} stale ${items.length === 1 ? "request" : "requests"}`, h("span", {class: "muted"}, ` · ${words}`)), + triagePicker(TRIAGE_FOOTER, items), h("ol", {class: "stale-list"}, items.map(row))); + } + + /** + * @param {boolean} [polled] true from a poll: the rows stay when the shown entries, their inbox items, the stale + * requests and the error are unchanged; any other call redraws them. */ function drawStream(polled) { if (!stream.dom || ui.screen !== "stream") { return; } + const backlog = staleRequests(); + const behind = new Set(backlog.map((item) => `${item.kind}:${item.id}`)); + const told = new Set(state.inbox.filter((item) => item.request === "failed" && !item.settled).map((item) => item.job.id)); const floor = live() && ui.preset > 0 ? nowSeconds() - ui.preset : -Infinity; - const rows = [...stream.events, ...stream.entries.filter((entry) => entry.ts >= floor)].sort((a, b) => b.ts - a.ts || (a.id < b.id ? 1 : -1)); + const rows = [...stream.events, ...stream.entries.filter((entry) => entry.ts >= floor)].filter((entry) => !streamHides(entry, behind, told)).sort((a, b) => b.ts - a.ts || (a.id < b.id ? 1 : -1)); const shown = rows.slice(0, FEED_LIMIT); stream.dom.count.textContent = `${rows.length} entries${live() ? " · following live" : ""}`; - const drawn = JSON.stringify([shown, shown.map((entry) => entry.waiting ? inboxOf(entry) : null), rows.length, stream.error, rows.length ? null : [stream.busy, activeWaiting()]]); + const footing = backlog.length ? [backlog.map((item) => [item.kind, item.id, item.request, item.title, item.ts]), triage.footer, triage.picked.get(TRIAGE_FOOTER) || [], ui.busy] : null; + const drawn = JSON.stringify([shown, shown.map((entry) => entry.waiting ? inboxOf(entry) : null), rows.length, stream.error, rows.length ? null : [stream.busy, activeWaiting()], footing]); if (polled === true && drawn === stream.dom.drawn) { return; } stream.dom.drawn = drawn; if (stream.error) { - stream.dom.list.replaceChildren(emptyState("Stream not readable", stream.error)); + fadeSwap(stream.dom.list, [emptyState("Stream not readable", stream.error)]); return; } - keepTyping(stream.dom.list, () => keepScroll(stream.dom.list, () => stream.dom.list.replaceChildren(rows.length + fadeSwap(stream.dom.list, [rows.length ? h("div", {class: "card flush"}, h("ol", {class: "feed"}, shown.map(eventRow)), rows.length > shown.length ? h("p", {class: "footnote"}, `${rows.length - shown.length} older entries hidden; narrow down with a filter or the time range.`) : null) - : emptyState(stream.busy ? "Loading …" : "No entries", activeWaiting() ? "Nothing is waiting for you right now." : "Nothing in the chosen time range and filter.")))); + : emptyState(stream.busy ? "Loading …" : "No entries", activeWaiting() ? "Nothing is waiting for you right now." : "Nothing in the chosen time range and filter."), staleFooter(backlog)], + (root, swap) => keepTyping(root, () => keepScroll(root, swap))); } function streamScreen() { diff --git a/orchestrator/templates/page-tasks-gantt.js b/orchestrator/templates/page-tasks-gantt.js index 1da69da..fb10488 100644 --- a/orchestrator/templates/page-tasks-gantt.js +++ b/orchestrator/templates/page-tasks-gantt.js @@ -310,7 +310,10 @@ taskView.sort = event.target.value; drawTasks(); }}}, Plan.SORTS.map(([id, label]) => h("option", {value: id, selected: id === taskView.sort}, label))); - const turn = (button) => relabel(button, taskView.descending ? "bi-sort-up" : "bi-sort-down", taskView.descending ? "Descending" : "Ascending", `${taskView.descending ? "Descending" : "Ascending"}: click to reverse`); + const turn = (button) => { + relabel(button, taskView.descending ? "bi-sort-up" : "bi-sort-down", taskView.descending ? "Descending" : "Ascending", `${taskView.descending ? "Descending" : "Ascending"}: click to reverse`); + button.setAttribute("aria-pressed", String(taskView.descending)); + }; const direction = h("button", {type: "button", class: "btn small icon-only", "data-direction": "", on: {click: (event) => { taskView.descending = !taskView.descending; turn(event.currentTarget); @@ -324,7 +327,7 @@ const value = fibonacciPicker("Business value of the selection", 8); const count = counter(0); const button = h("button", {type: "button", class: "btn small primary", id: "bulk-value", disabled: true, ...named("Set business value", "Set business value: of every selected task as Operator, signed once with the passkey"), on: {click: () => bulkValue(Number(value.value))}}, - icon("bi-gem"), count); + icon("bi-gem"), h("span", {class: "tool-word"}, "Set business value"), count); taskView.bulk = {button, count}; return h("div", {class: "plan-group", role: "group", "aria-label": "Business value of the selection"}, value, button); } @@ -352,14 +355,20 @@ }}}, choices.map(([id, label]) => h("option", {value: id, selected: id === taskView.scope}, label))); } + /** + * @param {string} view the Tasks view: list, board, rasci, gantt, burn or 3d. + * @returns {Object} view: what the Filter menu shows under View (the + * estimation switch, then the sort of the list, the forecast of the Gantt, or the scope and trend of the burn chart); + * actions: what the Actions menu shows under Plan (Request estimates, and in the list the bulk business value). + */ function planTools(view) { const modes = h("div", {class: "segmented", role: "group", "aria-label": "Estimation"}, Plan.ESTIMATIONS.map(([id, label]) => h("button", { type: "button", class: "icon-only", "data-estimation": id, "aria-pressed": String(estimation() === id), ...named(label, `${label}: ${id === "points" ? "the Fibonacci complexity of rasci.py estimate" : "every task counts 1"}`), on: {click: () => chooseEstimation(id)}, }, icon(ESTIMATION_ICONS[id])))); - const request = h("button", {type: "button", class: "btn small icon-only", id: "request-estimates", hidden: estimation() !== "points", ...named("Request estimates", "Request estimates: one newsletter asks every agent with a RASCI role in an unestimated task for business value and complexity"), on: {click: requestEstimates}}, icon("bi-send-check")); + const request = h("button", {type: "button", class: "btn small", id: "request-estimates", hidden: estimation() !== "points", ...named("Request estimates", "Request estimates: one newsletter asks every agent with a RASCI role in an unestimated task for business value and complexity"), on: {click: requestEstimates}}, icon("bi-send-check"), h("span", {class: "tool-word"}, "Request estimates")); taskView.plan = {modes, request, trend: null}; - const own = {list: () => [sortControls(), bulkControls()], gantt: forecastControl, burn: () => [scopeControl(), trendControls()]}[view]; - return [modes, request, own ? own() : null]; + const shown = {list: () => [sortControls()], gantt: () => [forecastControl()], burn: () => [scopeControl(), trendControls()]}[view]; + return {view: [modes, ...(shown ? shown() : [])], actions: [request, ...(view === "list" ? [bulkControls()] : [])]}; } function syncPlan() { diff --git a/orchestrator/templates/page-tasks.js b/orchestrator/templates/page-tasks.js index a707e17..d3ad049 100644 --- a/orchestrator/templates/page-tasks.js +++ b/orchestrator/templates/page-tasks.js @@ -68,7 +68,7 @@ } function taskItem(row, eta) { - const classes = ["task-row", row.open_work.length ? "open-work" : "", row.ended ? "ended" : ""].filter(Boolean).join(" "); + const classes = ["task-row", row.open_work.length ? "open-work" : "", row.ended ? "ended" : "", taskWorking(row, Kanban.marks(row, markSources())) ? "is-working" : ""].filter(Boolean).join(" "); const pick = row.editable ? h("input", {type: "checkbox", class: "task-pick", "aria-label": `Select ${row.task}`, title: `Select ${row.task} for a bulk business value`, checked: taskView.picked.has(row.task), on: {change: (event) => pickTask(row.task, event.target.checked)}}) : null; return h("li", {class: classes, "data-task": row.task, "data-item": `task:${row.task}`, "data-kind": row.kind, "data-status": row.status}, h("div", {class: "head-row"}, pick, h("code", {class: "task-id"}, row.task), taskBadges(row, true), h("span", {class: "spacer"}), etaMark(eta), @@ -142,14 +142,80 @@ } } + function resetTaskFilter() { + kanban.running = false; + kanban.stale = false; + taskView.sig = ""; + chooseTaskFilter("all"); + } + + /** + * @param rows - every task of the register. + * @param inbox - whether Waits on Operator shows. + * @returns {HTMLElement[]} the status tabs as one radio group of the Filter menu, each with its count. + */ function taskChips(rows, inbox) { return TASK_FILTERS.map(([id, label, name, test]) => { const total = test ? rows.filter(test).length : waitingCount(); - return h("button", {type: "button", class: "chip preset", "data-filter": id, "aria-pressed": String(inbox ? id === "operator" : id === taskView.filter), title: `${label}: ${total}`, on: {click: () => chooseTaskFilter(id)}}, - icon(name), label, counter(total)); + return h("label", {class: "check task-filter", "data-filter": id, title: `${label}: ${total}`}, + h("input", {type: "radio", name: "task-filter", value: id, checked: inbox ? id === "operator" : id === taskView.filter, on: {change: () => chooseTaskFilter(id)}}), + icon(name), h("span", {class: "task-filter-word"}, label), counter(total)); }); } + /** + * @param dom - taskView.dom. + * @returns {HTMLElement[]} the one removable chip naming the active filter (the status tab, and on the board Running + * and Stale), whose x resets to All with every card shown; [] while All shows everything. + */ + function taskFilterChip(dom) { + const [id, label, name] = TASK_FILTERS.find(([key]) => key === (dom.inbox ? "operator" : taskView.filter)); + const board = !dom.inbox && dom.view === "board"; + const words = [id === "all" ? "" : label, board && kanban.running ? "Running" : "", board && kanban.stale ? "Stale" : ""].filter(Boolean).join(" · "); + if (!words) { + return []; + } + return [h("span", {class: "chip task-filter-chip", id: "task-filter-chip", "data-key": "task-filter-chip", "data-filter": id, role: "group", "aria-label": `Filter: ${words}`, title: `Filter: ${words}`}, + icon(id === "all" ? "bi-funnel" : name), h("span", {class: "task-chip-word"}, words), + h("button", {type: "button", class: "x", ...named("Reset filter", `Reset filter: back to All${board ? ", every card shown" : ""}`), on: {click: resetTaskFilter}}, icon("bi-x-lg")))]; + } + + /** + * @param id - the menu's element id. + * @param label - the summary's name. + * @param hint - the summary's tooltip. + * @param name - the summary's icon. + * @param end - whether the box opens to the left, for a menu near the right edge. + * @param parts - the box's sections. + * @returns {HTMLElement} a details.menu of the Tasks toolbar. + */ + function taskMenu(id, label, hint, name, end, parts) { + return h("details", {class: "menu task-menu", id}, h("summary", named(label, hint), icon(name), h("span", {class: "tool-word"}, label), caret()), + h("div", {class: end ? "menu-box end" : "menu-box"}, parts)); + } + + const taskSection = (title, ...nodes) => h("section", {class: "task-menu-section"}, h("h3", {}, title), ...nodes); + + /** + * @param dom - taskView.dom of the board. + * Moves the groups of kanban.bar to their places: the status pills into the toolbar, the board filters into the + * Filter menu, the board actions into the Actions menu; an empty board leaves a note in both menus. + */ + function placeBoardTools(dom) { + const group = (key) => (kanban.bar ? kanban.bar.querySelector(`[data-tools="${key}"]`) : null); + const none = () => h("p", {class: "muted"}, "No card matches the filter."); + const status = group("status"); + const active = document.activeElement; + const kept = active && active.id && (dom.boardFilters.contains(active) || dom.boardActions.contains(active)) ? active.id : ""; + fadeSwap(dom.status, status ? [...status.children] : []); + dom.boardFilters.replaceChildren(group("filters") || none()); + dom.boardActions.replaceChildren(group("actions") || none()); + const again = kept ? document.getElementById(kept) : null; + if (again) { + again.focus({preventScroll: true}); + } + } + function taskViewSwitch(inbox) { return h("div", {class: "segmented", role: "group", "aria-label": "View"}, Nav.TASK_VIEWS.map(([id, name]) => h("button", { type: "button", class: "icon-only", ...named(name), "aria-pressed": String(!inbox && ui.views.tasks === id), on: {click: () => go("tasks", id)}, @@ -159,21 +225,32 @@ function tasksScreen() { const inbox = ui.screen === "inbox"; const view = ui.views.tasks; - const chips = h("div", {class: "chips", role: "group", "aria-label": "Task filters"}); - const count = h("span", {class: "muted"}); + const board = !inbox && view === "board"; + const chips = h("div", {class: "task-filters", role: "radiogroup", "aria-label": "Task filters"}); + const count = h("span", {class: "muted task-count"}); const search = inbox ? null : h("input", {type: "search", class: "field", placeholder: "Filter by task, title, worker, branch …", value: taskView.q, "aria-label": "Filter tasks", on: {input: (event) => { taskView.q = event.target.value; drawTasks(); }}}); const stage = !inbox && view === "3d" ? h("div", {class: "stage"}) : null; const body = inbox ? inboxScreen() : stage ? h("div", {class: "card stage-card tasks-body", "data-panel": "tasks/3d"}, layoutTools("tasks"), stage) : h("div", {class: "tasks-body", "data-panel": `tasks/${view}`}); - const slot = h("span", {class: "box-slot"}); - taskView.dom = {chips, count, body, inbox, view, stage, slot}; + const chip = h("span", {class: "task-chip"}); + const status = h("span", {class: "task-status", role: "group", "aria-label": "Board status"}); + const tools = () => h("div", {class: "task-menu-tools"}); + const [boardFilters, boardActions, undo] = [tools(), tools(), h("div", {class: "task-menu-tools task-undo", "aria-live": "polite"})]; + taskView.dom = {chips, count, body, inbox, view, stage, chip, status, boardFilters, boardActions}; taskView.sig = ""; taskView.plan = null; taskView.bulk = null; - const bar = boxHead("Tasks", "task-toolbar", taskViewSwitch(inbox), search, count, inbox ? null : planTools(view), slot, choiceMenu()); - return h("div", {class: "graph tasks"}, bar, chips, body); + const plan = inbox ? null : planTools(view); + const filter = taskMenu("task-filter", "Filter", "Filter: the status tabs with their counts, the board toggles and the options of this view", "bi-funnel", false, [ + taskSection("Status", chips), board ? taskSection("Board", boardFilters) : null, plan ? taskSection("View", h("div", {class: "task-menu-tools"}, plan.view)) : null]); + const actions = taskMenu("task-actions", "Actions", "Actions: prune stale tasks, apply or discard staged moves, request estimates or choices, undo a signature", "bi-lightning", true, [ + board ? taskSection("Board", boardActions) : null, plan ? taskSection("Plan", h("div", {class: "task-menu-tools"}, plan.actions)) : null, taskSection("Undo", undo), choiceMenu()]); + const bar = boxHead("Tasks", "task-toolbar task-bar", taskViewSwitch(inbox), search, filter, chip, status, actions, count); + undoView.box = undo; + drawUndo(); + return h("div", {class: "graph tasks"}, bar, body); } const operatorItems = () => state.inbox.filter((item) => item.kind === "operator" && !item.settled); @@ -210,7 +287,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), state.beats, state.runner, 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]), openInbox().filter((item) => !item.until).map((item) => item.agent), 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; } @@ -223,7 +300,13 @@ } } syncPlan(); + const focused = dom.chips.contains(document.activeElement); dom.chips.replaceChildren(...taskChips(rows, dom.inbox)); + const checked = dom.chips.querySelector("input:checked"); + if (focused && checked) { + checked.focus({preventScroll: true}); + } + fadeSwap(dom.chip, taskFilterChip(dom)); if (dom.inbox) { dom.count.textContent = `${rows.length} tasks in the register`; return; @@ -243,7 +326,10 @@ gantt: ganttChart, burn: (found) => burnChart(rows, found), }; - dom.body.replaceChildren(shown.length || dom.view === "burn" ? views[dom.view](shown) : emptyState("No task", "No entry matches this filter."), ...(dom.view === "list" || dom.view === "board" ? [operatorSection()].filter(Boolean) : [])); - const bar = dom.body.querySelector(".kanban-bar"); - dom.slot.replaceChildren(...(bar ? [bar] : [])); + kanban.bar = null; + const nodes = [shown.length || dom.view === "burn" ? views[dom.view](shown) : emptyState("No task", "No entry matches this filter."), ...(dom.view === "list" || dom.view === "board" ? [operatorSection()].filter(Boolean) : [])]; + if (dom.view === "board") { + placeBoardTools(dom); + } + fadeSwap(dom.body, nodes); } diff --git a/orchestrator/templates/page-timers.js b/orchestrator/templates/page-timers.js index 8b31bae..e567305 100644 --- a/orchestrator/templates/page-timers.js +++ b/orchestrator/templates/page-timers.js @@ -5,6 +5,7 @@ document.addEventListener("visibilitychange", () => document.hidden || [moving, syncRadio].forEach((task) => task())); window.setInterval(poll, 10000); window.setInterval(follow, 3000); + window.setInterval(whileShown(watchClosed), CLOSED_POLL); window.setInterval(whileShown(moving), RELAYOUT); window.setInterval(whileShown(liveSky), 30000); window.setInterval(syncRadio, 20000); diff --git a/orchestrator/templates/prune.js b/orchestrator/templates/prune.js index 587b7fc..9774029 100644 --- a/orchestrator/templates/prune.js +++ b/orchestrator/templates/prune.js @@ -8,6 +8,7 @@ const Prune = (() => { const MINUTE = 60; const MINUTES = {value: 10, min: 1, max: 60, page: 5}; const DAYS = {min: 1, max: 999}; + const OTHER = "other"; /** * @param rows - the hub's task rows. @@ -49,14 +50,6 @@ const Prune = (() => { 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. @@ -66,7 +59,56 @@ const Prune = (() => { return value >= DAYS.min && value <= DAYS.max ? value : null; } - return {KIND, MINUTE, MINUTES, DAYS, STALE_DAYS, stale, items, pending, clock, daysOf}; + /** + * @param task - a register task slug. + * @returns the text before its first "/", OTHER for a slug without one. + */ + function prefixOf(task) { + const cut = task.indexOf("/"); + return cut > 0 ? task.slice(0, cut) : OTHER; + } + + /** + * @param rows - the stale rows of stale(). + * @returns one {prefix, rows} per prefixOf() among the rows, the prefixes in alphabetical order with OTHER last, + * each group's rows in the order given. + */ + function groups(rows) { + const found = new Map(); + for (const row of rows) { + const prefix = prefixOf(row.task); + if (!found.has(prefix)) { + found.set(prefix, []); + } + found.get(prefix).push(row); + } + const order = [...found.keys()].sort((a, b) => (a === OTHER) - (b === OTHER) || a.localeCompare(b)); + return order.map((prefix) => ({prefix, rows: found.get(prefix)})); + } + + /** + * @param row - a hub task row. + * @returns its owner as the board shows it: the worker, else the first R holder, else "-". + */ + function owner(row) { + if (row.worker && row.worker !== "-") { + return row.worker; + } + const first = String(row.responsible || "-").split(", ")[0]; + return first || "-"; + } + + /** + * @param row - a hub task row. + * @param text - what the operator typed in the filter field. + * @returns whether the row's slug, title or owner holds the trimmed text, ignoring case; true for an empty text. + */ + function matches(row, text) { + const needle = text.trim().toLowerCase(); + return !needle || [row.task, row.title, owner(row)].some((value) => String(value || "").toLowerCase().includes(needle)); + } + + return {KIND, MINUTE, MINUTES, DAYS, STALE_DAYS, OTHER, stale, items, pending, daysOf, prefixOf, groups, owner, matches}; })(); if (typeof module === "object" && module.exports) { module.exports = Prune; diff --git a/orchestrator/templates/resources.js b/orchestrator/templates/resources.js index 006ac3f..dc42dfb 100644 --- a/orchestrator/templates/resources.js +++ b/orchestrator/templates/resources.js @@ -172,7 +172,19 @@ const Resources = (() => { } const asleep = (samples) => gpuSpans(samples, (gpu) => gpu.asleep === true); - const unknown = (samples) => gpuSpans(samples, (gpu) => gpu.asleep !== true && !finite(gpu.util) && !finite(gpu.vram_used)); + const unread = (gpu) => gpu.asleep !== true && !finite(gpu.util) && !finite(gpu.vram_used); + + /** + * @param samples - sampler rows. + * @returns gpuSpans() of every awake GPU without a reading, each span with causes: the distinct nvidia-smi error + * lines (gpu.error) its rows recorded, in order; empty when none did. + */ + function unknown(samples) { + const rows = timed(samples); + return gpuSpans(samples, unread).map(({name, spans: found}) => ({name, spans: found.map((span) => ({...span, causes: [...new Set(rows + .filter((row) => row.t >= span.from && row.t < span.to) + .flatMap((row) => listOf(row, "gpus").filter((gpu) => String(gpu.name) === name && unread(gpu) && typeof gpu.error === "string" && gpu.error !== "").map((gpu) => gpu.error)))]}))})); + } function stack(tokens) { const totals = new Map(); diff --git a/orchestrator/templates/style-bubbles.css b/orchestrator/templates/style-bubbles.css index 964d185..aebe3eb 100644 --- a/orchestrator/templates/style-bubbles.css +++ b/orchestrator/templates/style-bubbles.css @@ -9,11 +9,16 @@ .speech-bubble[data-state="speaking"]:not(.leaving) { z-index: 1; } .bubble-words { display: block; max-height: calc(6 * 1.35em); overflow: hidden; overflow-wrap: anywhere; scroll-behavior: smooth; } .speech-bubble[data-state="waiting"] .bubble-words { letter-spacing: .12em; } -.bubble-who { display: none; color: var(--muted); font: 650 var(--fs-xs)/1.2 var(--sans); } +.bubble-head { display: none; } +.bubble-who { color: var(--muted); font: 650 var(--fs-xs)/1.2 var(--sans); } +.bubble-skip { pointer-events: auto; } +.speech-bubble.leaving .bubble-skip, .speech-bubble[data-vanishing] .bubble-skip { pointer-events: none; } .bubble-bar { position: absolute; right: 0; bottom: calc(var(--sp-4) + env(safe-area-inset-bottom, 0px)); left: 0; display: flex; flex-wrap: wrap-reverse; justify-content: center; align-items: flex-end; gap: var(--sp-3) var(--sp-4); padding: 0 var(--sp-3); } .bubble-bar .speech-bubble { position: relative; transform: scale(var(--scale)); } .bubble-bar .speech-bubble::before, .bubble-bar .speech-bubble::after { display: none; } -.bubble-bar .bubble-who { display: block; } +.bubble-bar .bubble-head { display: flex; align-items: center; gap: 6px; } +.bubble-bar .bubble-head .avatar { width: 22px; height: 22px; } +.bubble-bar .bubble-skip { min-width: 0; margin-left: auto; padding: 2px 4px; font-size: var(--fs-xs); } @media (prefers-reduced-motion: reduce) { .speech-bubble { transition: opacity .4s var(--ease); } .bubble-words { scroll-behavior: auto; } diff --git a/orchestrator/templates/style-inbox.css b/orchestrator/templates/style-inbox.css index 6b4e944..1aa25bf 100644 --- a/orchestrator/templates/style-inbox.css +++ b/orchestrator/templates/style-inbox.css @@ -19,3 +19,12 @@ .rule-request p { margin: 0; } .rule-request .meta { margin: 0; } .dry-run-count strong { color: var(--text); font-variant-numeric: tabular-nums; } +.triage-bar { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2) var(--sp-3); min-width: 0; margin-bottom: var(--sp-2); } +.triage-bar > .chips { min-width: 0; margin-bottom: 0; } +.triage-pick { display: inline-flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); min-width: 0; } +.stale-footer { margin-top: var(--sp-2); padding: 8px 12px; } +.stale-footer > summary { cursor: pointer; color: var(--muted); font-size: var(--fs-sm); font-weight: 600; overflow-wrap: anywhere; } +.stale-footer[open] > summary { margin-bottom: var(--sp-2); } +.stale-list { display: grid; gap: var(--sp-2); margin: var(--sp-2) 0 0; padding: 0; list-style: none; } +.stale-list > li { display: grid; gap: var(--sp-1); min-width: 0; padding-top: var(--sp-2); border-top: 1px solid var(--line); } +.stale-title { margin: 0; overflow-wrap: anywhere; white-space: pre-wrap; } diff --git a/orchestrator/templates/style-kanban.css b/orchestrator/templates/style-kanban.css index 4392618..0dc7042 100644 --- a/orchestrator/templates/style-kanban.css +++ b/orchestrator/templates/style-kanban.css @@ -1,6 +1,8 @@ .kanban-box { display: grid; gap: 8px; min-width: 0; } .kanban-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } .kanban-bar .pill { display: inline-flex; align-items: center; gap: 4px; } +.kanban-bar > .kanban-tools { display: contents; } +.kanban-bar .tool-word { display: none; } .kanban { position: relative; display: grid; gap: 6px; min-width: 0; } .kanban-head, .kanban-cells { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; } .kanban-head .task-column { display: flex; align-items: center; gap: 6px; margin: 0; padding: 2px 6px; } @@ -9,23 +11,21 @@ .lane-toggle:hover { background: var(--hover); } .kanban-cells[hidden] { display: none; } .kanban-cell { align-content: start; min-height: 40px; min-width: 0; padding: 4px; border-radius: 8px; background: color-mix(in srgb, var(--sunken) 55%, transparent); } -.kanban-card { cursor: pointer; } +.kanban-card { grid-template-columns: auto minmax(0, 1fr); column-gap: 8px; padding: 7px 9px; border: 2px var(--card-line, solid) var(--card-state, var(--line-strong)); box-shadow: 0 0 9px 1px color-mix(in srgb, var(--card-state, var(--line-strong)) 45%, transparent); cursor: pointer; } +.kanban-card > * { grid-column: 1 / -1; } +.kanban-card > .kanban-owner { grid-column: 1; grid-row: 1 / span 2; align-self: start; display: inline-flex; } +.kanban-card > :is(.head-row, .kanban-title) { grid-column: 2; } .kanban-card .head-row { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; margin: 0; } .kanban-card .task-id { flex: 1 1 100%; } -.kanban-card.pending { border-style: dashed; border-color: var(--accent); } +.kanban-card.pending { outline: 1px dashed var(--accent); outline-offset: 2px; } .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-nobody { color: var(--faint); } +.kanban-nobody .bi { width: 18px; height: 18px; } +.kanban-swatch { flex: none; width: 14px; height: 10px; border: 2px var(--card-line) var(--card-state); border-radius: 3px; box-shadow: 0 0 5px color-mix(in srgb, var(--card-state) 55%, transparent); } .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; } @@ -62,11 +62,25 @@ 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 { gap: var(--sp-3); } +.prune-tools { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2) var(--sp-4); } .prune-dialog .prune-days { display: inline-flex; align-items: center; gap: var(--sp-2); } -.prune-dialog .prune-days .field { width: 6ch; } +.prune-stepper { display: inline-flex; align-items: center; gap: var(--sp-1); } +.prune-stepper .field { width: 7ch; text-align: center; font-variant-numeric: tabular-nums; } +.prune-tools > .prune-filter, .prune-tools > .mic-frame { flex: 1 1 14rem; min-width: 0; } .prune-list { display: grid; gap: var(--sp-1); max-height: 40vh; margin: 0; padding: 0; overflow-y: auto; list-style: none; } +.prune-list[hidden], .prune-list li[hidden], .prune-group[hidden], .prune-none[hidden] { display: 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-list .task-id { flex: 1 1 auto; min-width: 0; overflow-wrap: anywhere; } +.prune-list .prune-age { flex: none; font-variant-numeric: tabular-nums; } +.prune-owner { display: inline-flex; flex: none; } +.prune-groups { display: grid; gap: var(--sp-2); min-width: 0; } +.prune-group { display: grid; gap: var(--sp-1); min-width: 0; } +.prune-group .prune-list { max-height: none; padding-left: var(--sp-5); overflow: visible; } +.prune-group-head { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; } +.prune-group-toggle { display: inline-flex; flex: 1 1 auto; align-items: center; gap: var(--sp-2); min-width: 0; padding: var(--sp-1) 0; border: 0; background: none; color: inherit; font: inherit; font-weight: 600; text-align: left; cursor: pointer; } +.prune-prefix { overflow-wrap: anywhere; } +.prune-foot { position: sticky; bottom: 0; z-index: 1; display: grid; gap: var(--sp-2); padding-block: var(--sp-2); border-top: 1px solid var(--line); background: var(--panel); } +.prune-foot .actions { margin-top: 0; } .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; } diff --git a/orchestrator/templates/style-match.css b/orchestrator/templates/style-match.css index 0b03ab1..083f0bf 100644 --- a/orchestrator/templates/style-match.css +++ b/orchestrator/templates/style-match.css @@ -1,7 +1,7 @@ .graph.tasks.match { container: match-area / inline-size; } .graph.tasks.match > .match-stack { flex: 1; } -.match-home { display: grid; height: 100%; min-height: 0; } -.match-home > .graph.match { min-height: 0; } +.match-home { display: grid; grid-template-rows: minmax(0, 1fr); height: 100%; min-height: 0; } +.match-home > .graph.match { grid-template-rows: minmax(0, 1fr); min-height: 0; } .match-stack { display: grid; grid-template-rows: auto minmax(0, 1fr) auto; gap: var(--sp-2); min-height: 0; width: min(100%, 960px); margin: 0 auto; } .match-stack[data-wide="true"] { width: 100%; } .match-widen { position: absolute; top: 12px; right: 12px; z-index: 1; } @@ -9,7 +9,7 @@ .match-widen { display: none; } } .match-stack:has(> .match-deck) { grid-template-rows: minmax(0, 1fr) auto auto; } -.match-peeks { display: flex; flex-wrap: wrap; gap: var(--sp-1); min-width: 0; } +.match-peeks { display: flex; flex-wrap: nowrap; gap: var(--sp-1); min-width: 0; overflow: hidden; } .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] > :not(.match-stamp) { filter: grayscale(1); opacity: 0.62; } @@ -18,9 +18,12 @@ .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-stamp[data-stamp="claude"] { color: var(--info); 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; } +.match-deck:has(> .match-empty) { padding-top: 0; place-items: center; } +.match-deck > .empty.match-empty { padding: 0; border: 0; border-radius: 0; background: none; box-shadow: none; } .match-card.front, .match-layer { --bar: linear-gradient(90deg, hsl(var(--card-hue, 210) 75% 58%), hsl(var(--card-hue-2, 280) 75% 58%)); } .match-layer { position: absolute; inset: 24px 0 0; z-index: 0; border: 1px solid var(--line); border-top-width: 0; border-radius: 22px; background: var(--bar) top / 100% 6px no-repeat, var(--glass-card); filter: brightness(0.86) saturate(0.8); transform-origin: top center; pointer-events: none; } .match-layer[data-depth="1"] { transform: translateY(-8px) scale(0.98) rotate(-1.5deg); } @@ -88,29 +91,33 @@ table.diff tr.match-mark td, table.diff tr.match-comment td { padding: 4px 10px; .match-comment-box { display: grid; gap: 6px; } .match-comment-box .actions { display: flex; justify-content: flex-end; gap: 6px; } .match-actions { display: flex; justify-content: space-between; align-items: end; padding: 0 var(--sp-2) var(--sp-1); } -.match-act { display: grid; justify-items: center; gap: 8px; padding: 0; border: 0; background: none; color: inherit; font: inherit; font-size: var(--fs-sm); font-weight: 700; cursor: pointer; } +.match-act { display: grid; justify-items: center; gap: 8px; width: 96px; padding: 0; border: 0; background: none; color: inherit; font: inherit; font-size: var(--fs-sm); font-weight: 700; cursor: pointer; } .match-act-face { display: grid; place-items: center; width: 76px; height: 76px; border-radius: 50%; background: var(--tone); color: #fff; font-size: 2rem; box-shadow: 0 6px 0 color-mix(in srgb, var(--tone) 55%, #000), 0 14px 26px -12px var(--tone); transition: transform 0.12s ease, box-shadow 0.12s ease; } -.match-reject { --tone: var(--bad); } -.match-accept { --tone: var(--ok); } -.match-later { --tone: var(--muted); } -.match-later .match-act-face { width: 60px; height: 60px; font-size: 1.5rem; } +.match-reject, .match-drop { --tone: var(--bad); } +.match-accept, .match-release { --tone: var(--ok); } +.match-later, .match-skip { --tone: var(--muted); } +:is(.match-later, .match-skip) .match-act-face { width: 60px; height: 60px; font-size: 1.5rem; } .match-act:hover:not(:disabled) .match-act-face { transform: translateY(-2px) scale(1.06); } .match-act:active:not(:disabled) .match-act-face { transform: translateY(5px); box-shadow: 0 1px 0 color-mix(in srgb, var(--tone) 55%, #000), 0 4px 10px -6px var(--tone); } .match-act:focus-visible { outline: none; } .match-act:focus-visible .match-act-face { outline: 3px solid var(--accent); outline-offset: 4px; } -.match-act:disabled { opacity: 0.4; cursor: not-allowed; } +.match-act:disabled, .match-act[aria-disabled="true"] { opacity: 0.4; cursor: not-allowed; } .match-head { touch-action: pan-y; cursor: grab; } .match-card.front[data-leaning] { transition: none; } .match-card.front[data-leaning="accept"] { box-shadow: inset 0 0 0 3px var(--ok); } .match-card.front[data-leaning="reject"] { box-shadow: inset 0 0 0 3px var(--bad); } .match-done { position: relative; display: grid; place-items: center; min-height: 0; overflow: hidden; } -.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)); } } +.confetti-rain { position: fixed; top: var(--top, 0px); right: 0; bottom: 0; left: 0; z-index: 45; overflow: hidden; pointer-events: none; animation: confetti-fade 2s ease-in 5.5s forwards; } +.confetti-rain i { position: absolute; top: 0; left: calc((100% - 9px) * var(--x)); width: 9px; height: 14px; border-radius: 2px; background: hsl(var(--c) 85% 60%); animation: confetti-fall var(--t) cubic-bezier(.4, .05, .75, .9) var(--d) both; } +@keyframes confetti-fall { from { transform: translateY(0) rotate(0deg); } to { transform: translateY(calc(var(--fall) - 14px)) rotate(var(--r)); } } +@keyframes confetti-fade { to { opacity: 0; } } .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; } +/* Without --match-refresh the sand's animation shorthand turns invalid and drops its name; the inherited duration then animates nothing. */ +.undo-glass { --match-refresh: 1s; display: inline-grid; place-items: center; flex: none; width: 18px; height: 24px; color: var(--warn); } +.undo-glass .match-glass-face { animation: none; animation-duration: inherit; } +.undo-glass .match-glass-top, .undo-glass .match-glass-bottom { animation-duration: inherit; } .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%; } @@ -126,22 +133,25 @@ table.diff tr.match-mark td, table.diff tr.match-comment td { padding: 4px 10px; .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-card.front, .match-card.front .match-who .avatar { animation: none !important; } + .confetti-rain { display: none; } .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; } +.match-hidden { display: inline-flex; align-items: center; gap: 4px; } +.match-hidden[hidden] { display: none; } +.match-hidden-mark { display: grid; place-items: center; width: 40px; height: 40px; border-radius: 50%; background: var(--accent-soft); color: var(--accent); font-size: 20px; } +.match-all-hidden .match-show-all { margin-top: var(--sp-2); } .match-tally { min-width: 18px; padding: 0 5px; border-radius: 999px; background: var(--accent); color: var(--on-accent); font-size: var(--fs-xs); text-align: center; } .match-feedback { width: 100%; font-family: var(--mono); resize: vertical; } .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); } +.match-card.front.match-release-card[data-leaning="reject"]::after { content: "SKIP"; color: var(--muted); } .match-accept-risk { display: inline-flex; align-items: center; gap: 4px; border-color: var(--bad); color: var(--bad); } .match-accept-risk[aria-pressed="true"] { border-color: var(--warn); background: color-mix(in srgb, var(--warn) 16%, transparent); color: var(--warn); } .match-decision[data-held="true"] { border-style: dashed; border-color: var(--bad); } @@ -161,7 +171,8 @@ table.diff tr.match-mark td, table.diff tr.match-comment td { padding: 4px 10px; .match-head { padding: var(--sp-2); } .match-who .avatar.big { width: 56px; height: 56px; } .match-body { padding: var(--sp-1) var(--sp-2) var(--sp-2); } + .match-act { width: 80px; } .match-act-face { width: 64px; height: 64px; font-size: 1.7rem; } - .match-later .match-act-face { width: 52px; height: 52px; font-size: 1.3rem; } + :is(.match-later, .match-skip) .match-act-face { width: 52px; height: 52px; font-size: 1.3rem; } .match-card.front[data-leaning]::after, .match-stamp { font-size: 1.4rem; } } diff --git a/orchestrator/templates/style-resources.css b/orchestrator/templates/style-resources.css index 1b3ca71..fc5ff2f 100644 --- a/orchestrator/templates/style-resources.css +++ b/orchestrator/templates/style-resources.css @@ -71,22 +71,42 @@ svg .res-bar { fill: var(--c); } svg .res-bar.faint { opacity: 0.35; } .res-panel.res-hardware { min-height: min-content; } .res-panel.res-hardware > .res-plot { min-height: 48px; } -.res-limits { display: flex; flex-wrap: nowrap; align-items: center; gap: 8px; min-width: 0; overflow-x: auto; scrollbar-width: none; font-size: var(--fs-xs); } +.res-legend[hidden] { display: none; } +.res-view-menu, .res-limits-menu { position: relative; } +.res-view-menu > summary, .res-limits-menu > summary { padding: 4px 10px; } +.res-view-menu .menu-box, .res-limits-menu .menu-box { gap: 2px; min-width: 11rem; padding: 6px; } +@media (max-width: 640px) { .res-view-menu > summary > span { display: none; } } +.res-limits-menu .menu-box h3 { padding: 6px 6px 2px; } +.res-limits-menu .limit-profiles { margin: 2px 6px 6px; } +.res-limits-menu .limit-matrix { justify-self: start; margin: 2px 6px; } +.res-panel.res-hardware { overflow: visible; } +.res-limits { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; min-width: 0; font-size: var(--fs-xs); } .res-limits > * { flex: none; } .res-limits .segmented button { padding: 2px 8px; font-size: var(--fs-xs); } -.res-limits > .limit-note { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.res-limits > .limit-note { flex: 1 1 0; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.limit-stage { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; min-width: 0; } +.limit-stage[hidden] { display: none; } +.limit-stage-note { min-width: 0; overflow-wrap: anywhere; } .limit-error { margin: 0; color: var(--bad); } +.limit-swatch { display: inline-block; width: 16px; border-top: 2px solid var(--c); } +.limit-swatch.target { border-top-style: dotted; } +.limit-swatch.lower, svg .res-limit.lower { --c: var(--ok); } +.limit-swatch.upper, svg .res-limit.upper { --c: var(--warn); } +.limit-swatch.stop, svg .res-limit.stop { --c: var(--bad); } +.limit-swatch.mayday, svg .res-limit.mayday { --c: var(--violet); } +.limit-swatch.target { --c: var(--text); } .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); } +.limits-table th[title] { cursor: help; } +.limits-table .limit-cell { width: 4.5rem; font-variant-numeric: tabular-nums; } +.limits-table .limit-cell.moved { border-color: var(--accent); border-style: dashed; } +svg .res-limit { cursor: ns-resize; outline: none; touch-action: none; } +svg .res-limit-hit { stroke: transparent; stroke-width: 14; } +svg .res-limit-mark { stroke: var(--c); stroke-width: 1.4; } +svg .res-limit.moved .res-limit-mark { stroke-width: 2; stroke-dasharray: 6 3; } +svg .res-limit-was { stroke: var(--c); stroke-width: 1; stroke-dasharray: 1 3; opacity: 0.6; pointer-events: none; } +svg .res-limit:hover .res-limit-mark, svg .res-limit:focus-visible .res-limit-mark, svg .res-limit[data-dragging] .res-limit-mark { stroke-width: 2.6; } +svg .res-limit text { fill: var(--c); font-size: var(--fs-2xs); pointer-events: none; } 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); } diff --git a/orchestrator/templates/style-tasks.css b/orchestrator/templates/style-tasks.css index cbd6380..f41d2a3 100644 --- a/orchestrator/templates/style-tasks.css +++ b/orchestrator/templates/style-tasks.css @@ -5,8 +5,40 @@ .task-toolbar input[type="search"] { flex: 1 1 120px; min-width: min(120px, 100%); } .task-toolbar .segmented button.icon-only { min-width: 30px; padding: 4px 8px; } .task-toolbar input[type="number"] { width: 4.5rem; } -.task-toolbar > .choice-request { margin-left: auto; } -.tasks > .chips { margin-bottom: 0; } +.task-bar > :is(input[type="search"], .mic-line) { flex: 1 1 10rem; min-width: 6rem; } +.task-bar > .task-count { white-space: nowrap; } +.task-bar > :is(.task-chip, .task-status) { display: inline-flex; align-items: center; gap: 6px; min-width: 0; } +.task-bar > :is(.task-chip, .task-status):empty { display: none; } +.task-status .pill { display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; } +.task-filter-chip { max-width: 16rem; padding-inline: 10px 4px; border-color: transparent; background: var(--accent-soft); color: var(--accent); cursor: default; } +.task-filter-chip .task-chip-word { min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.task-filter-chip .x { display: inline-flex; align-items: center; padding: 4px; border-radius: 999px; } +.task-filter-chip .x:hover { background: var(--panel); } +.task-menu > .menu-box { min-width: min(16rem, calc(100vw - 32px)); max-height: min(70vh, 36rem); overflow-y: auto; overscroll-behavior: contain; } +.task-menu-section { display: grid; gap: 6px; min-width: 0; } +.task-menu-section:has(> .task-menu-tools):not(:has(> .task-menu-tools > :not([hidden]))) { display: none; } +.task-menu-tools { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; min-width: 0; } +.task-menu-tools > .kanban-tools { display: contents; } +.task-menu-tools .btn { display: inline-flex; align-items: center; gap: 6px; } +.task-undo .undo-label { max-width: 14rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.task-undo .undo-left, .task-menu .prune-left { font-variant-numeric: tabular-nums; } +.task-filters { display: grid; gap: 2px; } +.task-filter { padding: 4px 8px; border-radius: 8px; color: var(--text); } +.task-filter:hover { background: var(--hover); } +.task-filter:has(input:checked) { background: var(--accent-soft); color: var(--accent); } +.task-filter-word { flex: 1 1 auto; } +.task-filter .count { margin-left: auto; } +.task-menu .choice-request > .menu-box { position: static; width: auto; max-width: none; margin-top: 6px; padding: var(--sp-2) 0 0; border: 0; border-top: 1px solid var(--line); border-radius: 0; background: none; box-shadow: none; -webkit-backdrop-filter: none; backdrop-filter: none; } +@media (max-width: 640px) { + .task-bar > .segmented { order: 0; } + .task-bar .segmented button.icon-only { min-width: 28px; padding: 4px 6px; } + .task-bar > .task-menu { order: 1; } + .task-bar > .task-menu > summary { padding-inline: 8px; } + .task-bar > .task-menu > summary :is(.tool-word, .caret) { display: none; } + .task-bar > :is(input[type="search"], .mic-line) { order: 2; flex: 1 1 5rem; min-width: 4rem; } + .task-bar > :is(.task-chip, .task-status, .task-count) { order: 3; } + .task-filter-chip { max-width: 6.5rem; } +} body.fit .graph.tasks > .tasks-body, body.fit .graph.tasks > .inbox { flex: 1; min-height: 0; overflow: auto; } .inbox { overflow-anchor: none; } .choice-agents { display: grid; gap: 6px; max-height: 30vh; overflow: auto; } diff --git a/orchestrator/templates/style-ui.css b/orchestrator/templates/style-ui.css index c6c909d..4eb78ba 100644 --- a/orchestrator/templates/style-ui.css +++ b/orchestrator/templates/style-ui.css @@ -12,7 +12,7 @@ .dial-tick.long { stroke: var(--text); stroke-width: 2; } .dial-hand { stroke: var(--accent); stroke-width: 3; stroke-linecap: round; } .dial-pin { fill: var(--accent); } -.dial-readout { font-variant-numeric: tabular-nums; font-weight: 700; } +.dial-readout { fill: var(--text); font-size: 15px; font-variant-numeric: tabular-nums; font-weight: 700; text-anchor: middle; dominant-baseline: central; } .rule-form [hidden] { display: none; } .rule-form > label.check { display: inline-flex; min-height: 34px; } .speaker-face { position: relative; display: inline-grid; flex: none; border-radius: 50%; } @@ -127,6 +127,15 @@ body.fit .spot-host { flex: none; } .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; } } +.agent-foot { gap: 4px; } +.agent-foot > .to-one { flex: none; padding: 2px; } +.to-one > label { position: relative; display: inline-flex; align-items: center; justify-content: center; padding: 2px 10px; border-radius: 8px; color: var(--muted); font-size: var(--fs-sm); font-weight: 580; cursor: pointer; } +.to-one > label:hover { color: var(--text); } +.to-one > label:has(> input:checked) { background: var(--panel); color: var(--text); box-shadow: var(--shadow); } +.to-one > label:has(> input:focus-visible) { outline: 2px solid var(--accent); outline-offset: -2px; } +.to-one > label > input { position: absolute; inset: 0; width: 100%; height: 100%; margin: 0; opacity: 0; cursor: pointer; } +.agent-foot > .agent-send { flex: none; } +@media (max-width: 640px) { .to-one > label, .agent-foot > .agent-send { min-width: 44px; min-height: 44px; } } .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; max-height: none; resize: none; } @@ -341,6 +350,8 @@ body.fit .spot-host { flex: none; } .ctx-rule { height: 1px; margin: 2px 6px; background: var(--line); } .ctx-item { display: flex; align-items: center; gap: 8px; min-width: 0; padding: 5px 10px; border: 0; border-radius: 8px; background: none; color: inherit; font: inherit; text-align: start; cursor: pointer; } .ctx-item:is(:hover, :focus) { background: var(--accent-soft); color: var(--accent); outline: none; } +.ctx-item .ctx-check { flex: 0 0 auto; width: 1em; } +.ctx-item[aria-checked="false"] .ctx-check { visibility: hidden; } .ctx-item .ctx-label { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .ctx-item .muted { flex: 0 1 auto; max-width: 45%; overflow: hidden; font-size: var(--fs-xs); text-overflow: ellipsis; white-space: nowrap; } .box-head > .toolbar { justify-content: flex-end; margin-inline-start: auto; } @@ -367,3 +378,21 @@ body.fit .spot-host { flex: none; } :is(.box-head, .home-head) .mic-line > :is(input, .btn):not(.menu-box *) { block-size: 100%; } :is(.box-head, .home-head) .segmented { align-items: stretch; } :is(.box-head, .home-head) .chips { margin-bottom: 0; } +.palette.closing[hidden], .sheet.closing[hidden] { display: grid; pointer-events: none; animation: shade-out .18s ease-in forwards; } +.ctx-menu.closing[hidden] { display: grid; pointer-events: none; } +@keyframes shade-out { to { background-color: transparent; } } +.is-working { --beat: var(--ok); animation: lub-dub 1.2s ease-in-out infinite; } +.kanban-card.is-working { --beat: var(--card-state, var(--ok)); } +.queue-job.is-working { --beat: var(--accent); } +.presence.is-working, .console-status.is-working { --beat: var(--info); } +@keyframes lub-dub { + 0%, 42%, 100% { transform: scale(1); box-shadow: 0 0 0 0 transparent; } + 10% { transform: scale(1.025); box-shadow: 0 0 10px 2px var(--beat); } + 20% { transform: scale(1); box-shadow: 0 0 4px 0 var(--beat); } + 30% { transform: scale(1.018); box-shadow: 0 0 12px 3px var(--beat); } +} +@keyframes lub-dub-glow { + 0%, 42%, 100% { box-shadow: 0 0 4px 0 var(--beat); } + 10%, 30% { box-shadow: 0 0 12px 3px var(--beat); } +} +@media (prefers-reduced-motion: reduce) { .is-working { animation-name: lub-dub-glow; } } diff --git a/tests/e2e/hub_e2e_inbox.py b/tests/e2e/hub_e2e_inbox.py index 7cdc3bd..11586e7 100644 --- a/tests/e2e/hub_e2e_inbox.py +++ b/tests/e2e/hub_e2e_inbox.py @@ -174,16 +174,16 @@ CHOICE_VIEW = """(async () => {@HELPERS@@LABELS@ return {error: text(document.getElementById("main"))}; } const box = document.getElementById("choice-request"); - const chip = document.querySelector('#main [aria-label="Task filters"] button[data-filter="operator"]'); + const chip = document.querySelector('#main [aria-label="Task filters"] [data-filter="operator"]'); const closed = all("button[data-channel]", box).filter((button) => button.checkVisibility()).length; return { kinds: [...new Set(all("#main .inbox-list > li").map((li) => text(li.querySelector(".pill"))))].sort(), - filter: [text(chip).replace(/[0-9]+$/, ""), chip.getAttribute("aria-pressed")], + filter: [text(chip).replace(/[0-9]+$/, ""), String(chip.querySelector("input").checked)], channels: all("button[data-channel]", box).map((button) => [button.dataset.channel, name(button), button.disabled]), fields: all("textarea, input:not([type=checkbox])", box).length, agents: all('input[type="checkbox"]', box).map((input) => input.value), multi: [name(box.querySelector("summary")), box.open, closed, text(box.querySelector(".menu-box h3 .count")), all('input[type="checkbox"]', box).filter((input) => input.checked).length], - bar: [box.parentElement.getAttribute("aria-label"), toolbarRows(), taskLayout()], + bar: [box.closest('[role="toolbar"]').getAttribute("aria-label"), toolbarRows(), taskLayout()], cards: all("#main .inbox-list > li").filter((li) => li.querySelector(".options")).map((li) => [text(li.querySelector(".pill")), all(".option strong", li).map(text)]), choices: all("#main [data-column], #main .group-title, #main h2, #main h3").filter((node) => node.dataset.column === "choices" || text(node) === "Choices").length, unlabelled: unlabelled(document), @@ -192,6 +192,7 @@ CHOICE_VIEW = """(async () => {@HELPERS@@LABELS@ }; })()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) CHOICE_SEND = """(async () => {@HELPERS@@WATCH@ + await openTaskMenu("task-actions"); const menu = bar(); menu.querySelector("summary").click(); await sleep(200); diff --git a/tests/e2e/hub_e2e_kit.py b/tests/e2e/hub_e2e_kit.py index 5a5ecc0..12f141f 100644 --- a/tests/e2e/hub_e2e_kit.py +++ b/tests/e2e/hub_e2e_kit.py @@ -83,6 +83,28 @@ HELPERS = """ await sleep(200); }; const taskLayout = () => all("#main .graph.tasks > *").map((node) => (node.matches('[role="toolbar"]') ? "toolbar" : node.matches('[aria-label="Task filters"]') ? "chips" : "body")); + const openTaskMenu = async (id) => { + const menu = await until(() => document.getElementById(id), 8000); + if (menu && !menu.open) { + menu.querySelector(":scope > summary").click(); + await sleep(150); + } + return menu; + }; + const withMenusOpen = (node, read) => { + const opened = []; + for (let menu = node ? node.closest("details") : null; menu; menu = menu.parentElement ? menu.parentElement.closest("details") : null) { + if (!menu.open) { + menu.open = true; + opened.push(menu); + } + } + const found = read(); + opened.forEach((menu) => { + menu.open = false; + }); + return found; + }; const screenShown = async (ms) => { const shown = await until(() => { if (typeof Nav !== "object") { diff --git a/tests/e2e/hub_e2e_plan.py b/tests/e2e/hub_e2e_plan.py index 68fd43f..c9ecfb8 100644 --- a/tests/e2e/hub_e2e_plan.py +++ b/tests/e2e/hub_e2e_plan.py @@ -7,7 +7,7 @@ PLAN_HELPERS = """ const modes = () => all('#main [aria-label="Estimation"] button').map((button) => [button.dataset.estimation, button.getAttribute("aria-pressed")]); const requestShown = () => { const button = document.getElementById("request-estimates"); - return button ? !button.hidden && button.getClientRects().length > 0 : null; + return button ? withMenusOpen(button, () => !button.hidden && button.getClientRects().length > 0) : null; }; const choose = async (select, value) => { select.value = value; @@ -57,6 +57,7 @@ BURN = """(async () => {@HELPERS@@PLAN_HELPERS@ })()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS) POINTS_ON = """(async () => {@HELPERS@@PLAN_HELPERS@ const before = {modes: modes(), request: requestShown()}; + await openTaskMenu("task-filter"); all('#main [aria-label="Estimation"] button').find((button) => button.dataset.estimation === "points").click(); const shown = await until(() => requestShown(), 8000); return {before, modes: modes(), request: Boolean(shown), ...fits()}; @@ -68,6 +69,7 @@ REQUEST = """(async () => {@HELPERS@@PLAN_HELPERS@ } const series = all("#main svg.burn path.burn-line").map((path) => [path.dataset.series, Number(path.dataset.last)]); const shown = new Set(all("#toasts .toast")); + await openTaskMenu("task-actions"); document.getElementById("request-estimates").click(); const toast = await fresh(shown, "Request estimates"); return {modes: modes(), series, toast, ...fits()}; @@ -93,6 +95,7 @@ BULK = """(async () => {@HELPERS@@PLAN_HELPERS@ return send(path, init); }; const rows = () => all("#main .task-row").map((row) => row.dataset.task); + await openTaskMenu("task-filter"); const sort = document.querySelector('#main select[aria-label="Sort"]'); const direction = document.querySelector("#main button[data-direction]"); const found = {sorts: all("option", sort).map((option) => option.value), prio: rows()}; @@ -107,6 +110,7 @@ BULK = """(async () => {@HELPERS@@PLAN_HELPERS@ for (const task of ["work/next", "work/child"]) { all("#main .task-row").find((row) => row.dataset.task === task).querySelector("input.task-pick").click(); } + await openTaskMenu("task-actions"); const button = document.getElementById("bulk-value"); found.armed = [button.disabled, text(button.querySelector(".count"))]; await choose(document.querySelector('#main select[aria-label="Business value of the selection"]'), "@VALUE@"); @@ -154,7 +158,7 @@ TREND_READ = """ const note = document.querySelector("#main .burn-forecast"); const marker = document.querySelector("#main svg.burn .forecast-line"); return { - value: select.value, options: all("option", select).map((option) => [option.value, text(option)]), days: [Number(days.value), days.getClientRects().length > 0], + value: select.value, options: all("option", select).map((option) => [option.value, text(option)]), days: [Number(days.value), withMenusOpen(days, () => days.getClientRects().length > 0)], note: note ? [note.dataset.forecast === "" ? null : Number(note.dataset.forecast), text(note)] : null, marker: marker ? Number(marker.dataset.forecast) : null, lines: all("#main svg.burn path.burn-trend").map((path) => [path.dataset.series, Number(path.dataset.from), Number(path.dataset.to)]), points: all('#main svg.burn circle.burn-point[data-series="remaining"]').map((circle) => [Number(circle.dataset.t), Number(circle.dataset.value)]), diff --git a/tests/e2e/hub_e2e_views.py b/tests/e2e/hub_e2e_views.py index 304c591..be70553 100644 --- a/tests/e2e/hub_e2e_views.py +++ b/tests/e2e/hub_e2e_views.py @@ -48,7 +48,7 @@ PROBE = """(async () => {@HELPERS@ org: all("#main .org-chart .org-row[data-office]").map((row) => [row.dataset.office, text(row.querySelector(".org-holder"))]), toggles: all("#main .org-toggle").map((button) => [name(button), button.getAttribute("aria-expanded")]), order: all("#main .agent-order li").map((item) => item.dataset.name), - taskFilters: all('#main [aria-label="Task filters"] button').map((button) => [button.dataset.filter, button.getAttribute("aria-pressed"), text(button.querySelector(".count"))]), + taskFilters: all('#main [aria-label="Task filters"] [data-filter]').map((label) => [label.dataset.filter, String(label.querySelector("input").checked), text(label.querySelector(".count"))]), taskRows: all("#main .task-row").map((row) => [row.dataset.task, row.classList.contains("open-work")]), columns: all("#main .task-column").map((column) => [column.dataset.column, all(`#main .kanban-cell[data-column="${column.dataset.column}"] .task-card`).map((card) => card.dataset.task)]), matrix: [all("#main table.matrix thead th").length, all("#main table.matrix tbody tr").length, all("#main table.matrix td .letter").map(text).join("")], @@ -62,10 +62,12 @@ PROBE = """(async () => {@HELPERS@ }; })()""".replace("@HELPERS@", HELPERS) INBOX_CHIP = """(async () => {@HELPERS@ - const chip = (id) => document.querySelector(`#main [aria-label="Task filters"] button[data-filter="${id}"]`); + const chip = (id) => document.querySelector(`#main [aria-label="Task filters"] [data-filter="${id}"]`); + await openTaskMenu("task-filter"); chip("operator").click(); await until(() => location.hash === "#tasks/operator" && document.querySelector("#main .inbox-list"), 4000); - const inbox = {hash: location.hash, items: all("#main .inbox-list > li").length, counted: Number(text(chip("operator").querySelector(".count"))), pressed: chip("operator").getAttribute("aria-pressed"), current: all("#tabs button[aria-current=page]").map(name)}; + const inbox = {hash: location.hash, items: all("#main .inbox-list > li").length, counted: Number(text(chip("operator").querySelector(".count"))), pressed: String(chip("operator").querySelector("input").checked), current: all("#tabs button[aria-current=page]").map(name)}; + await openTaskMenu("task-filter"); chip("grant").click(); await until(() => location.hash.startsWith("#tasks/"), 4000); await sleep(300); diff --git a/tests/e2e/test_agent_message_box_e2e.py b/tests/e2e/test_agent_message_box_e2e.py new file mode 100644 index 0000000..c15faab --- /dev/null +++ b/tests/e2e/test_agent_message_box_e2e.py @@ -0,0 +1,169 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import test_field_attachments_e2e as attached +from kvb_orchestrator import skill_scripts + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-095-shots")) +SIZES = ((1366, 768), (390, 844)) +TOUCH = 640 +CELLS = ["switch", "spacer", "attach", "mic", "send"] +SEND = ["Send", "Send: your passkey signs the message, verifiable with operator_message"] +HINTS = [["post", "Post", "Post arrives at the end of the turn."], ["call", "Call", "Call arrives at once, with a read receipt."]] +HEADS = {"post": ["post", "--to"], "call": ["send", "call", "--to"]} +KIT = """ + const shown = (node) => Boolean(node) && node.getClientRects().length > 0; + const box = () => document.querySelector("#popup form.popup-form"); + const addressee = (form) => form.querySelector("textarea").getAttribute("aria-label").replace(/^Message to /, ""); + const cell = (node) => (node.matches(".to-one") ? "switch" : node.matches(".spacer") ? "spacer" : node.matches(".mic-attach") ? "attach" : node.matches("button.mic") ? "mic" : node.matches(".agent-send") ? "send" : node.className || node.tagName); + const openAgentBox = async () => { + location.hash = "#stream"; + await streamShowsAll(); + const links = await until(() => { + const found = all("#main button.agent-link").filter(shown); + return found.length ? found : null; + }, 10000); + if (!links) { + return null; + } + (links.find((node) => text(node) === "Stage") || links[0]).click(); + return until(() => document.getElementById("popup").open && box(), 4000); + }; +""" +LAYOUT = """(async () => {@HELPERS@@FIELD@@KIT@ + await screenShown(8000); + const form = await openAgentBox(); + if (!form) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(300); + const frame = form.querySelector(":scope > .mic-frame"); + const foot = frame ? frame.querySelector(":scope > .mic-foot") : null; + if (!foot) { + return {error: "no framed footer", form: form.outerHTML.slice(0, 300)}; + } + const rect = (node) => node.getBoundingClientRect(); + const send = foot.querySelector(":scope > .agent-send"); + const controls = [...all(".to-one > label", foot), foot.querySelector(":scope > .mic-attach"), foot.querySelector(":scope > button.mic"), send]; + if (controls.some((node) => !node)) { + return {error: "footer control missing", foot: foot.outerHTML.slice(0, 400)}; + } + const [outer, strip, boxes] = [rect(frame), rect(foot), controls.map(rect)]; + const within = (b, edge) => b.left >= edge.left - 0.5 && b.right <= edge.right + 0.5 && b.top >= edge.top - 0.5 && b.bottom <= edge.bottom + 0.5; + return { + to: addressee(form), + files: all("input[type=file]", form).map((input) => [input.className, input.hidden, shown(input)]), + paragraphs: all("p", form).length, + children: [...form.children].map((node) => node.className), + cells: [...foot.children].filter(shown).map(cell), + inside: boxes.every((b) => within(b, outer)), + footed: boxes.every((b) => within(b, strip)), + row: Math.max(...boxes.map((b) => b.top)) < Math.min(...boxes.map((b) => b.bottom)), + sizes: boxes.map((b) => [Math.round(b.width), Math.round(b.height)]), + send: [name(send), send.title], + classes: all(".to-one > label", foot).map((label) => [label.querySelector("input").value, text(label), label.title]), + wide: wide(), + }; +})()""" +DELIVER = """(async () => {@HELPERS@@FIELD@@KIT@ + const form = box(); + if (!form) { + return {error: "agent box closed"}; + } + const field = form.querySelector("textarea"); + const send = form.querySelector(".agent-send"); + const runs = []; + for (const cls of ["post", "call"]) { + form.querySelector(`.to-one input[value="${cls}"]`).closest("label").click(); + field.value = `agent box @WIDTH@ ${cls}`; + field.focus(); + field.setSelectionRange(field.value.length, field.value.length); + field.dispatchEvent(new Event("input", {bubbles: true})); + let path = null; + if (cls === "post") { + field.dispatchEvent(new ClipboardEvent("paste", {clipboardData: carry([await pngFile("image.png")]), bubbles: true, cancelable: true})); + path = await until(() => lineOf(field, /^📎 \\/.*\\/paste-\\d{8}-\\d{6}\\.png$/), 8000); + } + const chips = form.querySelectorAll(".mic-chip").length; + const checked = form.querySelector(".to-one input:checked").value; + const before = new Set(all("#toasts .toast")); + send.click(); + const toast = await until(() => all("#toasts .toast").filter((node) => !before.has(node)).map(text).find((entry) => entry.includes(" to ")), 20000); + await until(() => !send.disabled, 20000); + runs.push({cls, checked, path, chips, toast, left: field.value}); + } + document.getElementById("toasts").replaceChildren(); + return {to: addressee(form), runs}; +})()""" + + +def probe(template: str, width: int) -> str: + return template.replace("@HELPERS@", base.HELPERS).replace("@FIELD@", attached.FIELD).replace("@KIT@", KIT).replace("@WIDTH@", str(width)) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestAgentMessageBox(base.OrchestratorE2ECase): + stored = attached.TestFieldAttachments.stored + + def check_layout(self, width: int, layout: dict) -> None: + self.assertNotIn("error", layout, layout) + self.assertEqual(layout["files"], [["mic-attach-file", True, False]], layout) + self.assertEqual((layout["paragraphs"], layout["children"]), (0, ["mic-frame mic-area"]), layout) + self.assertEqual(layout["cells"], CELLS, layout) + self.assertEqual((layout["inside"], layout["footed"], layout["row"]), (True, True, True), layout) + self.assertEqual((layout["send"], layout["classes"]), (SEND, HINTS), layout) + self.assertFalse(layout["wide"], layout) + if width < TOUCH: + self.assertTrue(all(side >= 44 for size in layout["sizes"] for side in size), layout["sizes"]) + + def check_delivery(self, delivered: dict) -> None: + self.assertNotIn("error", delivered, delivered) + post, call = delivered["runs"] + self.assertEqual([(run["cls"], run["checked"], run["left"]) for run in delivered["runs"]], [("post", "post", ""), ("call", "call", "")], delivered) + self.assertEqual(self.stored(post["path"]).read_bytes()[:8], b"\x89PNG\r\n\x1a\n") + self.assertEqual((post["chips"], call["path"], call["chips"]), (1, None, 0), delivered) + for run, label in ((post, "Post"), (call, "Call")): + self.assertTrue((run["toast"] or "").startswith(f"{label} to {delivered['to']}: sent"), run) + + def test_chromium_sends_post_with_a_pasted_screenshot_and_call_from_one_framed_field_at_two_widths(self): + local = f"http://localhost:{self.port}/" + steps = [] + for width, height in SIZES: + shot = OUT / f"chromium-{width}" + steps += [ + {"width": width, "height": height, "url": f"{local}?{width}-agent#stream", "wait": 1200, "probe": probe(LAYOUT, width), "shot": f"{shot}-agent-box.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(DELIVER, width), "shot": f"{shot}-agent-box-sent.png"}, + ] + data = self.drive(steps, self.authenticator()) + (OUT / "chromium-agent-box.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + results = iter(data["results"]) + sends = [] + for width, _ in SIZES: + layout, delivered = next(results), next(results) + with self.subTest(width=width, part="layout"): + self.check_layout(width, layout) + with self.subTest(width=width, part="delivery"): + self.check_delivery(delivered) + sends += [(width, delivered["to"], run["cls"], run["path"]) for run in delivered["runs"]] + radio = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO] + self.assertEqual([args[:-1] for args in radio], [[*HEADS[cls], to, "--session", "Operator"] for _, to, cls, _ in sends]) + for args, (width, _, cls, path) in zip(radio, sends, strict=True): + with self.subTest(width=width, cls=cls): + self.assertIn(f"agent box {width} {cls}", args[-1]) + if path: + self.assertIn(path, args[-1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_board_running_e2e.py b/tests/e2e/test_board_running_e2e.py index bcda4f1..0d2d6d5 100644 --- a/tests/e2e/test_board_running_e2e.py +++ b/tests/e2e/test_board_running_e2e.py @@ -1,4 +1,4 @@ -"""Exercise requirement 074 in Chromium: the board's running marks, their border and glow, the Running chip, at three widths.""" +"""Exercise requirement 074 in Chromium: the board's running marks, the Running chip, at three widths; the border and glow follow 090's state colour.""" from __future__ import annotations @@ -23,12 +23,12 @@ CALM = [{"name": "prefers-reduced-motion", "value": "reduce"}] MARKED = ["queue/q-1", "work/alpha", "work/bravo", "work/delta"] UNMARKED = ["work/charlie", "work/echo"] CHIPS = { - "work/alpha": [["queue", "accent", "#bi-cpu", r"test · \d+ min", "Queue job running"]], - "queue/q-1": [["queue", "accent", "#bi-cpu", r"test · \d+ min", "Queue job running"]], - "work/bravo": [["agent", "ok", "#bi-person-workspace", r"Docs · [234] min", "Agent working"]], - "work/delta": [["agent", "ok", "#bi-person-workspace", r"Skills · \d+ (s|min)", "Agent working"], ["hub", "info", "#bi-terminal", r"make deploy-hub", "Hub job running"]], + "work/alpha": [["queue", "neutral", "#bi-cpu", r"test · \d+ min", "Queue job running"]], + "queue/q-1": [["queue", "neutral", "#bi-cpu", r"test · \d+ min", "Queue job running"]], + "work/bravo": [["agent", "neutral", "#bi-person-workspace", r"Docs · [234] min", "Agent working"]], + "work/delta": [["agent", "neutral", "#bi-person-workspace", r"Skills · \d+ (s|min)", "Agent working"], ["hub", "neutral", "#bi-terminal", r"make deploy-hub", "Hub job running"]], } -BORDERS = {"work/alpha": "accent", "queue/q-1": "accent", "work/bravo": "ok", "work/delta": "ok"} +BORDERS = {**dict.fromkeys(MARKED, "ok"), **dict.fromkeys(UNMARKED, "info")} READ = """ const card = (task) => all("#main .kanban-card").find((node) => node.dataset.task === task) || null; const toggle = () => document.getElementById("kanban-running"); @@ -40,16 +40,6 @@ READ = """ probe.remove(); return found; }; - const keyframes = (wanted) => { - for (const sheet of document.styleSheets) { - for (const rule of sheet.cssRules) { - if (rule.type === CSSRule.KEYFRAMES_RULE && rule.name === wanted) { - return [...rule.cssRules].map((frame) => [frame.keyText, [...frame.style].sort()]); - } - } - } - return null; - }; const spills = (node) => { const own = node.getBoundingClientRect(); const host = node.closest(".kanban-card").getBoundingClientRect(); @@ -63,12 +53,8 @@ READ = """ marks: Object.fromEntries(cards.map((node) => [node.dataset.task, [node.dataset.mark || null, node.dataset.marks || null, all(".kanban-mark", node).map((chip) => [chip.dataset.mark, chip.dataset.tone, chip.querySelector("use").getAttribute("href"), text(chip), name(chip), chip.getAttribute("title") || ""])]])), borders: Object.fromEntries(cards.map((node) => [node.dataset.task, [getComputedStyle(node).borderTopWidth, getComputedStyle(node).borderTopColor]])), - glow: Object.fromEntries(cards.filter((node) => node.dataset.mark).map((node) => { - const after = getComputedStyle(node, "::after"); - return [node.dataset.task, [after.animationName, after.animationDuration, after.animationIterationCount]]; - })), - tones: {accent: color("--accent"), ok: color("--ok"), info: color("--info")}, - frames: keyframes("kanban-glow"), + glow: Object.fromEntries(cards.map((node) => [node.dataset.task, [getComputedStyle(node).animationName, getComputedStyle(node, "::after").animationName]])), + tones: {ok: color("--ok"), info: color("--info")}, toggle: button ? [name(button), button.getAttribute("aria-pressed"), text(button.querySelector(".count")), button.getAttribute("title") || ""] : null, spill: all("#main .kanban-mark").filter(spills).length, unlabelled: all("#main .kanban-box svg.bi").map((svg) => svg.parentElement).filter((owner) => !text(owner) && !(owner.getAttribute("title") && owner.getAttribute("aria-label"))).length, @@ -85,12 +71,14 @@ BOARD = """(async () => {@HELPERS@@READ@ return read(); })()""" FILTER = """(async () => {@HELPERS@@READ@ + await openTaskMenu("task-filter"); toggle().click(); if (!(await until(() => toggle().getAttribute("aria-pressed") === "true" && all("#main .kanban-card").length === @MARKED@, 4000))) { return {error: `still ${all("#main .kanban-card").length} cards`}; } await sleep(2500); const only = read(); + await openTaskMenu("task-filter"); toggle().click(); await until(() => toggle().getAttribute("aria-pressed") === "false" && all("#main .kanban-card").length > @MARKED@, 4000); return {only, back: read()}; @@ -155,9 +143,9 @@ class TestBoardRunning(HubCase): for task in shown: with self.subTest(task=task): first, keys, chips = read["marks"][task] + self.assertEqual(read["borders"][task], ["2px", read["tones"][BORDERS[task]]]) if task not in CHIPS: self.assertEqual((first, keys, chips), (None, None, [])) - self.assertEqual(read["borders"][task][0], "1px") continue wanted = CHIPS[task] self.assertEqual((first, keys), (wanted[0][0], " ".join(chip[0] for chip in wanted))) @@ -166,20 +154,18 @@ class TestBoardRunning(HubCase): self.assertRegex(shown_text, f"^{pattern}") self.assertEqual(label, f"{word}: {shown_text}") self.assertRegex(title, rf"(?s)^{re.escape(task)}: .+, since ") - self.assertEqual(read["borders"][task], ["2px", read["tones"][BORDERS[task]]]) def check_board(self, read: dict, moving: bool) -> None: self.assertNotIn("error", read, read) self.assertEqual(read["cards"], sorted(MARKED + UNMARKED)) self.check_marks(read, MARKED + UNMARKED) - self.assertEqual(read["frames"], [["0%, 100%", ["opacity"]], ["50%", ["opacity"]]]) - glow = ["kanban-glow", "3s", "infinite"] if moving else ["none", "0s", "1"] - self.assertEqual(read["glow"], {task: glow for task in MARKED}) + beat = "lub-dub" if moving else "lub-dub-glow" + self.assertEqual(read["glow"], {**{task: [beat, "none"] for task in MARKED}, **{task: ["none", "none"] for task in UNMARKED}}) self.assertEqual(read["toggle"][:3], ["Running", "false", str(len(MARKED))], read["toggle"]) self.assertIn("every card shown", read["toggle"][3]) self.assertEqual((read["spill"], read["unlabelled"], read["wide"]), (0, 0, False), read) - def test_chromium_marks_running_cards_glows_by_opacity_only_and_filters_them_at_three_widths(self): + def test_chromium_marks_running_cards_beats_their_state_border_and_filters_them_at_three_widths(self): data = self.drive(self.steps(), None) (OUT / "chromium-board-running.json").write_text(json.dumps(data, indent=1), encoding="utf-8") self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) diff --git a/tests/e2e/test_bubble_dock_e2e.py b/tests/e2e/test_bubble_dock_e2e.py new file mode 100644 index 0000000..a44e188 --- /dev/null +++ b/tests/e2e/test_bubble_dock_e2e.py @@ -0,0 +1,154 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import time +import unittest +from collections.abc import Callable +from pathlib import Path +from unittest import mock + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +from hub_case import HubCase +from hub_support import iso + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-bubble-dock-shots")) +WIDTH, HEIGHT = 1366, 768 +CUE = "e2e-dock" +SPEAKERS = ("Stage", "Docs") +SAID = " ".join(["the build host is almost full so rotate the logs and retry the gate before the next push"] * 4) +SILENT = """() => { + try { + localStorage.setItem("kvb-orchestrator.radio", JSON.stringify({mode: "silence", classes: ["mayday", "security"], muted: []})); + } catch (error) { + return; + } +}""" +PROBE = """(async () => {@HELPERS@ + const layer = document.getElementById("bubbles"); + const toggle = document.getElementById("bubbles-toggle"); + const live = () => all(".speech-bubble:not(.leaving):not([data-vanishing])", layer); + const of = (who) => live().find((node) => node.dataset.who === who) || null; + const where = (node) => (node.parentElement.classList.contains("bubble-bar") ? "bar" : "layer"); + const seen = (node) => Boolean(node) && node.getClientRects().length > 0; + const parts = (node) => { + const face = node.querySelector(".bubble-head .avatar[data-face]"); + const who = node.querySelector(".bubble-who"); + const skip = node.querySelector("button.bubble-skip"); + return { + where: where(node), face: seen(face) ? face.dataset.face : null, skip: seen(skip), faceLeft: seen(face) && seen(who) ? face.getBoundingClientRect().right <= who.getBoundingClientRect().left + 1 : null, + label: skip ? skip.getAttribute("aria-label") : null, title: skip ? skip.getAttribute("title") : null, type: skip ? skip.getAttribute("type") : null, tab: skip ? skip.tabIndex : null, + }; + }; + const pin = (key) => { + const node = document.createElement("span"); + node.dataset.e2ePin = key; + node.dataset.face = key; + Object.assign(node.style, {position: "fixed", left: `${Math.round(innerWidth / 2)}px`, top: `${Math.round(innerHeight / 2)}px`, width: "26px", height: "26px", borderRadius: "50%", background: "#9aa4b1"}); + document.body.prepend(node); + }; + const poll = () => window.dispatchEvent(new Event("focus")); + if (toggle.getAttribute("aria-pressed") !== "true") { + toggle.click(); + } + if (!(await until(() => toggle.getAttribute("aria-pressed") === "true" && !layer.hidden, 8000))) { + return {error: "bubbles stay off"}; + } + await sleep(1500); + poll(); + await sleep(1500); + await fetch("/api/tts", {method: "POST", headers: {"X-Kvb-Orchestrator": "1", "Content-Type": "application/json"}, body: JSON.stringify({text: "@CUE@", voice: ""}), cache: "no-store"}); + poll(); + if (!(await until(() => live().length >= 2, 20000))) { + return {error: "no bubbles", shown: live().map((node) => [node.dataset.who, node.dataset.state])}; + } + const docked = live().find((node) => where(node) === "bar"); + if (!docked) { + return {error: "no docked bubble", shown: live().map((node) => [node.dataset.who, where(node)])}; + } + const [dockedWho, anchoredWho] = [docked.dataset.who, live().find((node) => node !== docked).dataset.who]; + pin(anchoredWho); + await until(() => of(anchoredWho) && where(of(anchoredWho)) === "layer", 4000); + await sleep(800); + const anchored = parts(of(anchoredWho)); + const dock = parts(of(dockedWho)); + const states = live().map((node) => [node.dataset.who, node.dataset.state]); + const skip = of(dockedWho).querySelector("button.bubble-skip"); + const box = skip.getBoundingClientRect(); + const hit = document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2); + const takesPointer = Boolean(hit && hit.closest("button.bubble-skip") === skip); + skip.focus(); + const focused = document.activeElement === skip; + (hit && hit.closest("button.bubble-skip") ? hit : skip).click(); + const gone = Boolean(await until(() => !layer.querySelector(`.speech-bubble[data-who="${CSS.escape(dockedWho)}"]`), 3000)); + poll(); + await sleep(2500); + poll(); + await sleep(1500); + const back = Boolean(of(dockedWho)); + const kept = Boolean(of(anchoredWho)); + all("[data-e2e-pin]").forEach((node) => node.remove()); + return {dockedWho, anchoredWho, anchored, dock, states, takesPointer, focused, gone, back, kept}; +})()""" + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestDockedBubble(HubCase): + drive = base.OrchestratorE2ECase.drive + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + now = time.time() + self.claim("s1", "Skills session") + self.write_council({ + "work/s2/claim.json": {"office": "work/s2", "session": "s2", "runtime": "claude", "name": "Stage", "since": iso(now - 7200), "beat": now - 60, "work": "x"}, + "work/s3/claim.json": {"office": "work/s3", "session": "s3", "runtime": "claude", "name": "Docs", "since": iso(now - 7200), "beat": now - 60, "work": "x"}, + }) + hub = self.httpd.hub + hub.settings.put({**hub.settings.get(), "bubbles": True}, hub.settings.get()) + + def synthesize(body: bytes, admit: Callable[[str], None]) -> bytes: + if json.loads(body)["text"] == CUE: + stamp = time.time() + rows = [{"ts": stamp - index / 1000, "from": name, "to": [], "text": f"{name}: {SAID}", "class": "broadcast", "v": 2} for index, name in enumerate(SPEAKERS)] + with (self.council / "news.jsonl").open("a", encoding="utf-8") as handle: + handle.write(self.jsonl(rows)) + return base.tone(1, 8000) + + patch = mock.patch.object(hub.speech, "synthesize", synthesize) + patch.start() + self.addCleanup(patch.stop) + self.base = f"http://{self.host}/" + + def steps(self) -> list[dict]: + probe = PROBE.replace("@HELPERS@", base.HELPERS).replace("@CUE@", CUE) + return [{"width": WIDTH, "height": HEIGHT, "url": f"{self.base}?dock#stream", "wait": 1200, "probe": probe, "shot": str(OUT / f"chromium-{WIDTH}-bubble-dock.png")}] + + def check(self, found: dict) -> None: + self.assertNotIn("error", found, found) + self.assertNotEqual(found["dockedWho"], found["anchoredWho"], found) + self.assertEqual({state for _, state in found["states"]}, {"quiet"}, found) + dock, anchored = found["dock"], found["anchored"] + self.assertEqual((dock["where"], dock["face"], dock["skip"], dock["faceLeft"]), ("bar", found["dockedWho"], True, True), found) + self.assertEqual((dock["type"], dock["tab"]), ("button", 0), found) + self.assertTrue(dock["label"] and dock["title"], found) + self.assertEqual((anchored["where"], anchored["face"], anchored["skip"]), ("layer", None, False), found) + self.assertEqual((found["takesPointer"], found["focused"]), (True, True), found) + self.assertEqual((found["gone"], found["back"], found["kept"]), (True, False, True), found) + + def test_chromium_docks_a_bubble_with_face_and_close_and_the_close_skips_the_silent_bubble(self): + data = self.drive(self.steps(), None, init=SILENT) + (OUT / "chromium-bubble-dock.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + self.assertEqual(len(data["results"]), 1, data) + self.check(data["results"][0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_clock_readout_e2e.py b/tests/e2e/test_clock_readout_e2e.py new file mode 100644 index 0000000..f6447cc --- /dev/null +++ b/tests/e2e/test_clock_readout_e2e.py @@ -0,0 +1,174 @@ +"""Exercise requirement 087: the match clock, the undo dial and the prune dial print their time inside the face below the pivot, update it and keep the hand moving.""" + +from __future__ import annotations + +import datetime +import itertools +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +from hub_case import HubCase + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-087-clock-shots")) +KIT = r"""@HELPERS@ + const frame = () => new Promise((resolve) => window.requestAnimationFrame(() => resolve())); + const angle = (dial) => { + const found = /rotate\(([-0-9.]+) /.exec(dial.querySelector(".dial-hand").getAttribute("transform") || ""); + return found ? Number(found[1]) : null; + }; + const readout = (dial) => text(dial.querySelector(".dial-face .dial-readout")); + const placed = (dial) => { + const words = dial.querySelector(".dial-face .dial-readout"); + const pin = dial.querySelector(".dial-face .dial-pin"); + if (!words || !pin) { + return null; + } + const [box, pivot, face] = [words.getBoundingClientRect(), pin.getBoundingClientRect(), dial.querySelector(".dial-face").getBoundingClientRect()]; + return {centred: Math.abs(box.left + box.right - pivot.left - pivot.right) / 2 < 2, below: box.top >= pivot.bottom - 1 && box.bottom <= face.bottom, inside: box.left >= face.left && box.right <= face.right}; + }; + const sweep = async (dial) => { + await frame(); + const first = angle(dial); + await sleep(100); + return [first, angle(dial)]; + }; + const turned = async (dial) => { + const before = {now: dial.getAttribute("aria-valuenow"), readout: readout(dial)}; + dial.focus(); + dial.dispatchEvent(new KeyboardEvent("keydown", {key: "ArrowRight", bubbles: true, cancelable: true})); + const after = {now: dial.getAttribute("aria-valuenow"), readout: readout(dial)}; + const frames = await sweep(dial); + await sleep(300); + return {placed: placed(dial), before, after, frames, rest: angle(dial), max: dial.getAttribute("aria-valuemax")}; + };""" +MATCH = """(async () => {@KIT@ + const glass = await until(() => document.querySelector("#main .match-glass.large"), 8000); + if (!glass) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + const box = glass.getBoundingClientRect(); + glass.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, button: 2, clientX: box.left + 4, clientY: box.top + 4})); + const dial = await until(() => document.querySelector("#sheet .match-refresh-dial"), 3000); + return dial ? await turned(dial) : {error: "no match clock"}; +})()""" +UNDO = """(async () => {@KIT@ + await screenShown(8000); + document.getElementById("settings-open").click(); + const dial = await until(() => document.querySelector(".sheet-box form.settings .undo-dial"), 8000); + if (!dial) { + return {error: "no undo dial"}; + } + dial.scrollIntoView({block: "center"}); + await sleep(300); + return await turned(dial); +})()""" +PRUNE = """(async () => {@KIT@ + await screenShown(8000); + await openTaskMenu("task-actions"); + (await until(() => document.getElementById("kanban-prune-open"), 8000)).click(); + if (!(await until(() => document.getElementById("prune-sign"), 4000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + const setup = document.querySelector(".sheet-box .prune-dial"); + const opened = {placed: placed(setup), readout: readout(setup)}; + document.getElementById("prune-sign").click(); + const dial = await until(() => document.querySelector('.sheet-box .prune-dial[aria-readonly="true"]'), 20000); + if (!dial) { + return {opened, error: text(document.querySelector(".sheet-box") || document.getElementById("main")).slice(0, 300)}; + } + const running = placed(dial); + const seen = []; + const end = performance.now() + 3600; + while (performance.now() < end) { + const words = readout(dial); + if (!seen.length || seen[seen.length - 1].text !== words) { + seen.push({text: words, at: Math.round(performance.now())}); + } + await sleep(50); + } + const frames = await sweep(dial); + document.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await until(() => !dial.isConnected, 4000); + await sleep(100); + const gone = angle(dial); + await sleep(300); + return {opened, placed: running, seen, frames, stopped: {connected: dial.isConnected, still: gone === angle(dial)}}; +})()""" + + +def stamp(days: float) -> str: + return (datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=days)).isoformat(timespec="seconds") + + +def seconds(readout: str) -> int: + minutes, rest = readout.split(":") + return int(minutes) * 60 + int(rest) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestClockReadout(HubCase): + drive = base.OrchestratorE2ECase.drive + authenticator = base.OrchestratorE2ECase.authenticator + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.council.mkdir(exist_ok=True) + row = {"roles": {"Docs": "RA"}, "status": "queued", "updated": stamp(12), "title": "fixture task", "worker": "-"} + (self.council / "rasci.json").write_text(json.dumps({"work/old-a": row}), encoding="utf-8") + + def step(self, width: int, height: int, screen: str, probe: str, shot: str) -> dict: + return {"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}-{shot}#{screen}", "wait": 1500, + "probe": probe.replace("@KIT@", KIT).replace("@HELPERS@", base.HELPERS), "shot": str(OUT / f"chromium-{width}-{shot}.png")} + + def assert_turned(self, found: dict) -> None: + self.assertNotIn("error", found, found) + self.assertEqual(found["placed"], {"centred": True, "below": True, "inside": True}, found) + for moment in ("before", "after"): + now = int(found[moment]["now"]) + self.assertEqual(found[moment]["readout"], f"{now // 60}:{now % 60:02d}", found) + self.assertEqual(int(found["after"]["now"]), int(found["before"]["now"]) + 1, found) + first, later = found["frames"] + self.assertNotEqual(first, later, found) + self.assertAlmostEqual(found["rest"], int(found["after"]["now"]) * 360 / int(found["max"]), delta=0.01, msg=found) + + def test_the_match_clock_and_the_undo_dial_print_their_time_below_the_pivot_and_sweep_to_each_new_value(self): + steps = [step for width, height in base.WIDTHS for step in (self.step(width, height, "tasks/match", MATCH, "match-clock"), self.step(width, height, "stream", UNDO, "undo-clock"))] + data = self.drive(steps, None) + (OUT / "chromium-clocks.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], []) + self.assertEqual(len(data["results"]), 2 * len(base.WIDTHS), data) + for index, (width, _) in enumerate(base.WIDTHS): + for found in data["results"][2 * index : 2 * index + 2]: + with self.subTest(width=width): + self.assert_turned(found) + + def test_the_prune_dialog_clock_reads_m_ss_drops_one_second_each_second_and_stops_once_closed(self): + width, height = base.WIDTHS[1] + data = self.drive([self.step(width, height, "tasks/board", PRUNE, "prune-clock")], self.authenticator()) + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + found = data["results"][0] + self.assertNotIn("error", found, found) + self.assertEqual(found["opened"], {"placed": {"centred": True, "below": True, "inside": True}, "readout": "10:00"}, found) + self.assertEqual(found["placed"], {"centred": True, "below": True, "inside": True}, found) + texts = [seconds(seen["text"]) for seen in found["seen"]] + self.assertGreaterEqual(len(texts), 3, found) + self.assertEqual([earlier - later for earlier, later in itertools.pairwise(texts)], [1] * (len(texts) - 1), found) + gaps = [later["at"] - earlier["at"] for earlier, later in itertools.pairwise(found["seen"][1:])] + for gap in gaps: + self.assertAlmostEqual(gap, 1000, delta=250, msg=found) + first, later = found["frames"] + self.assertLess(later, first, found) + self.assertEqual(found["stopped"], {"connected": False, "still": True}, found) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_dialog_bound_cards_e2e.py b/tests/e2e/test_dialog_bound_cards_e2e.py new file mode 100644 index 0000000..d0944af --- /dev/null +++ b/tests/e2e/test_dialog_bound_cards_e2e.py @@ -0,0 +1,162 @@ +"""Exercise requirement 094 in Chromium: Claude's answer closes a card within 5 s, and a card whose hook stopped waiting reads open in Claude.""" + +from __future__ import annotations + +import json +import os +import re +import shutil +import sys +import time +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +from hub_case import HubCase +from hub_support import ASK, signing +from kvb_orchestrator.asking import ENDED, TERMINAL + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-094-dialog-shots")) +AGO = 690 +CLOSE_MS = 5000 +TIP = re.compile(r"^open in Claude since \d{2}:\d{2}, 1[2-4] minutes ago$") +QUESTION = "Push the branch?" +ANSWER = "Later" +OPTIONS = [{"label": "Now", "description": ""}, {"label": ANSWER, "description": ""}] +QUESTIONS = {"questions": [{"question": QUESTION, "options": [{"label": "Now"}, {"label": ANSWER}]}]} +ASKED = signing.call_key("AskUserQuestion", QUESTIONS) +CLOSER = "a" * 43 +REPORT = """ + const report = (body) => fetch("/api/asks/ran", {method: "POST", headers: {"Content-Type": "application/json", "X-Kvb-Orchestrator": "1"}, body: JSON.stringify(body)}).then((response) => response.status); + const timed = async (body, check) => { + const start = Date.now(); + const status = await report(body); + const done = await until(check, @CLOSE_MS@ + 1000); + return {status, ms: done ? Date.now() - start : null}; + }; +""" +BINDING = """(async () => {@HELPERS@@REPORT@ + const count = () => all("#main .muted").map(text).find((words) => /^[0-9]+ cards? waits?$/.test(words)) || ""; + if (!(await until(() => count() === "5 cards wait", 8000))) { + return {error: `deck shows ${count() || text(document.getElementById("main"))}`}; + } + await sleep(2500); + const found = {}; + found.ran = await timed({event: "PostToolUse", call_key: "@KEY@", session: "s1", closer: "@CLOSER@"}, () => count() === "4 cards wait"); + found.answered = await timed({event: "PostToolUse", call_key: "@ASKED@", session: "s4", answers: {"@QUESTION@": "@ANSWER@"}, closer: "@CLOSER@"}, () => count() === "3 cards wait"); + found.stop = await timed({event: "Stop", session: "s2", closer: "@CLOSER@"}, () => count() === "2 cards wait"); + found.ended = await timed({event: "SessionEnd", session: "s3", closer: "@CLOSER@"}, () => count() === "1 card waits"); + found.front = document.querySelector("#main .match-card.front") ? document.querySelector("#main .match-card.front").dataset.card : null; + return found; +})()""" +STAMP = """(async () => {@HELPERS@ + const card = await until(() => document.querySelector("#main .match-card.front"), 8000); + if (!card) { + return {error: text(document.getElementById("main"))}; + } + const stamp = card.querySelector(".match-stamp"); + if (stamp) { + stamp.dispatchEvent(new MouseEvent("mouseenter")); + } + return { + id: card.dataset.card, stamp: stamp ? text(stamp) : null, kind: stamp ? stamp.dataset.stamp : null, tip: stamp ? stamp.title : null, + blocked: text(card.querySelector(".match-blocked")), words: text(card), stale: card.dataset.stale, + accept: document.querySelector("#main .match-accept").disabled, reject: document.querySelector("#main .match-reject").disabled, + wide: document.documentElement.scrollWidth > window.innerWidth + 1, + }; +})()""" +STREAM = """(async () => {@HELPERS@ + await streamShowsAll(); + const entry = (words) => all("#main .feed > li").find((row) => text(row).includes(words)); + const decision = await until(() => entry("@QUESTION@"), 8000); + const ask = await until(() => entry("make deploy"), 8000); + const pills = (row) => (row ? all(".msg-meta .pill", row).map(text) : null); + return {decision: pills(decision), ask: pills(ask), blocked: ask ? ask.getAttribute("title") : null}; +})()""" +INBOX = """(async () => {@HELPERS@@REPORT@ + const row = () => document.querySelector('#main .inbox-list > li[data-ref="ask:@LAPSED@"]'); + if (!(await until(row, 8000))) { + return {error: text(document.getElementById("main"))}; + } + const pills = all(".msg-meta .pill", row()).map(text); + const actions = all(".item-actions .btn, .code-box .btn.primary", row()).map(text).filter((words) => /^(Grant|Deny|Allow)/.test(words)); + await sleep(2500); + const closed = await timed({event: "UserPromptSubmit", session: "s1", closer: "@CLOSER@"}, () => !row()); + return {pills, actions, closed}; +})()""" + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestDialogBoundCards(HubCase): + drive = base.OrchestratorE2ECase.drive + + def setUp(self): + super().setUp() + for session, name in (("s1", "Skills session"), ("s2", "Store session"), ("s3", "Main session"), ("s4", "Stage session")): + self.claim(session, name) + saved = self.httpd.hub.settings.get() + self.httpd.hub.settings.put({**saved, "match": {"refresh": 60}}, saved) + self.key = signing.call_key("Bash", {"command": "make build"}) + self.lapsed = self.create_ask({**ASK, "call_key": signing.call_key("Bash", {"command": ASK["command"]}), "bound": True, "closer": CLOSER}) + self.httpd.hub.asks.change(self.lapsed, {"expires": time.time() - AGO}) + self.ran = self.create_ask({**ASK, "command": "make build", "call_key": self.key, "bound": True, "closer": CLOSER, "timeout": 600}) + self.stopped = self.create_ask({**ASK, "command": "make lint", "session": "s2", "bound": True, "closer": CLOSER, "timeout": 600}) + self.ended = self.create_ask({**ASK, "command": "make docs", "session": "s3", "bound": True, "closer": CLOSER, "timeout": 600}) + status, _, body = self.post_json("/api/decisions", {"question": QUESTION, "options": OPTIONS, "session": "s4", "timeout": 600, "multi": False, "call_key": ASKED, "bound": True, "closer": CLOSER}, self.local()) + self.assertEqual(status, 201, body) + self.answered = json.loads(body)["id"] + + def step(self, name: str, width: int, height: int, screen: str, probe: str) -> dict: + flow = probe.replace("@HELPERS@", base.HELPERS).replace("@REPORT@", REPORT).replace("@CLOSE_MS@", str(CLOSE_MS)) + for marker, value in (("@KEY@", self.key), ("@ASKED@", ASKED), ("@QUESTION@", QUESTION), ("@ANSWER@", ANSWER), ("@LAPSED@", self.lapsed), ("@CLOSER@", CLOSER)): + flow = flow.replace(marker, value) + return {"width": width, "height": height, "url": f"http://localhost:{self.port}/?{name}-{width}#{screen}", "wait": 1500, "probe": flow, "shot": str(OUT / f"chromium-{name}-{width}.png")} + + def test_chromium_drops_cards_claude_answered_within_5_s_and_shows_the_timed_out_one_open_in_claude(self): + OUT.mkdir(parents=True, exist_ok=True) + steps = [self.step("binding", 1366, 768, "tasks/match", BINDING)] + steps += [self.step("open-in-claude", width, height, "tasks/match", STAMP) for width, height in base.WIDTHS] + steps += [self.step("stream", 1366, 768, "stream", STREAM), self.step("inbox", 1366, 768, "tasks/operator", INBOX)] + data = self.drive(steps, None) + (OUT / "chromium-dialog-bound.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], []) + self.assertEqual(len(data["results"]), len(steps), data) + binding, *stamps, stream, inbox = data["results"] + self.assertNotIn("error", binding, binding) + for name in ("ran", "answered", "stop", "ended"): + with self.subTest(event=name): + self.assertEqual(binding[name]["status"], 200, binding) + self.assertIsNotNone(binding[name]["ms"], binding) + self.assertLess(binding[name]["ms"], CLOSE_MS, binding) + self.assertEqual(binding["front"], f"ask:{self.lapsed}", binding) + for found in stamps: + with self.subTest(width=found.get("id")): + self.assertNotIn("error", found, found) + self.assertEqual((found["id"], found["stamp"], found["kind"], found["stale"]), (f"ask:{self.lapsed}", "IN CLAUDE", "claude", "false"), found) + self.assertRegex(found["tip"], TIP) + self.assertTrue(found["blocked"].startswith("Open in Claude: answer it there"), found) + self.assertNotIn("EXPIRED", found["words"]) + self.assertNotIn("STALE", found["words"]) + self.assertEqual((found["accept"], found["reject"], found["wide"]), (True, False, False), found) + self.assertIn("answered in Claude", stream["decision"], stream) + self.assertIn(ANSWER, stream["decision"], stream) + self.assertIn("open in Claude", stream["ask"], stream) + self.assertNotIn("expired", stream["ask"], stream) + self.assertEqual(stream["blocked"], "Open in Claude: answer it there", stream) + self.assertNotIn("error", inbox, inbox) + self.assertIn("open in Claude", inbox["pills"], inbox) + self.assertEqual(inbox["actions"], [], inbox) + self.assertEqual(inbox["closed"]["status"], 200, inbox) + self.assertIsNotNone(inbox["closed"]["ms"], inbox) + self.assertLess(inbox["closed"]["ms"], CLOSE_MS, inbox) + statuses = {ident: self.httpd.hub.asks.get(ident)["status"] for ident in (self.lapsed, self.ran, self.stopped, self.ended)} + self.assertEqual(statuses, {self.lapsed: TERMINAL, self.ran: TERMINAL, self.stopped: TERMINAL, self.ended: ENDED}) + decision = self.httpd.hub.decisions.get(self.answered) + self.assertEqual((decision["status"], decision["choice"]), (TERMINAL, ANSWER)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_hub_inbox_e2e.py b/tests/e2e/test_hub_inbox_e2e.py index 938c611..330f4ee 100644 --- a/tests/e2e/test_hub_inbox_e2e.py +++ b/tests/e2e/test_hub_inbox_e2e.py @@ -242,15 +242,16 @@ class TestHubInbox(base.OrchestratorE2ECase): self.assertEqual(view["filter"], ["Waits on Operator", "true"]) self.assertEqual(view["channels"], [[channel, label, channel in ("post", "call")] for channel, label in zip(CHOICE_CHANNELS, ["Post", "Call", "Newsletter", "Broadcast", "Pan-Pan", "Sécurité", "Mayday"], strict=True)]) self.assertEqual((view["fields"], view["choices"], view["multi"], view["unlabelled"], view["tall"], view["wide"]), (0, 0, ["Request choices", False, 0, "0", 0], [], False, False)) - self.assertEqual(view["bar"], ["Tasks", view["bar"][1], ["toolbar", "chips", "body"]]) - self.assertEqual(view["bar"][1] == 1, width != 390, view["bar"]) + self.assertEqual(view["bar"], ["Tasks", view["bar"][1], ["toolbar", "body"]]) + self.assertIn(view["bar"][1], (1, 2) if width == 390 else (1,), view["bar"]) self.assertGreaterEqual(len(view["agents"]), 2, view) self.assertIn(["Choice", ["Merge now", "Wait"]], view["cards"]) self.requested(sent, signs) self.answered(answer, signs) for fit, name in zip(fitted, TASK_VIEWS, strict=True): self.assertEqual((fit["hash"], fit["bar"], fit["choices"], fit["tall"], fit["wide"]), (f"#tasks/{name}", CHOICE_CHANNELS, 0, False, False), fit) - self.assertEqual((fit["rows"] == 1, fit["layout"]), (width != 390, ["toolbar", "chips", "body"]), fit) + self.assertIn(fit["rows"], (1, 2) if width == 390 else (1,), fit) + self.assertEqual(fit["layout"], ["toolbar", "body"], fit) if name == "board": self.assertEqual(fit["columns"], ["queued", "running", "done"]) hub = self.httpd.hub diff --git a/tests/e2e/test_hub_motion_e2e.py b/tests/e2e/test_hub_motion_e2e.py new file mode 100644 index 0000000..5e3d4f2 --- /dev/null +++ b/tests/e2e/test_hub_motion_e2e.py @@ -0,0 +1,252 @@ +"""Exercise requirement 086 in Chromium: toasts and cards fade out, running tasks beat, confetti lands and fades, reduced motion removes at once.""" + +from __future__ import annotations + +import json +import os +import shutil +import sys +import time +import unittest +from pathlib import Path +from unittest import mock + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import test_board_running_e2e as running +import test_match_release_card_e2e as deck +from hub_case import HubCase +from kvb_orchestrator import batches + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-086-shots")) +CALM = [{"name": "prefers-reduced-motion", "value": "reduce"}] +WORKING = ["work/alpha", "work/bravo", "work/delta"] +STILL = ["work/charlie", "work/echo"] +FADE_MIN_MS = 100 +CONFETTI_MAX_MS = 10000 +WATCH = """ + const fading = (node, start, limit) => new Promise((resolve) => { + const began = performance.now(); + const between = []; + const step = () => { + const at = performance.now() - began; + if (!node.isConnected || at > limit) { + resolve({gone: node.isConnected ? null : Math.round(at), span: between.length ? Math.round(between[between.length - 1] - between[0]) : 0, frames: between.length}); + return; + } + const seen = Number(getComputedStyle(node).opacity); + if (seen > 0 && seen < 1) { + between.push(at); + } + requestAnimationFrame(step); + }; + start(); + step(); + }); + const refusedToast = async () => { + for (let tries = 0; tries < 8 && card() && card().dataset.stale !== "true"; tries += 1) { + const id = card().dataset.card; + key("ArrowUp"); + await until(() => card() && card().dataset.card !== id, 4000); + await sleep(300); + } + if (!card() || card().dataset.stale !== "true") { + return null; + } + key("ArrowRight"); + return until(() => all("#toasts .toast").find((node) => text(node.querySelector("strong")) === "Accept: refused"), 4000); + }; + const rain = () => document.querySelector(".confetti-rain"); + const bits = () => all(".confetti-rain i").map((node) => node.getBoundingClientRect()); +""" +MOTION = """(async () => {@HELPERS@@CARD@@STEPS@@WATCH@ + await screenShown(8000); + if (!(await until(card, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(400); + const box = await refusedToast(); + if (!box) { + return {error: "no refused toast"}; + } + await sleep(300); + const toast = await fading(box, () => box.click(), 3000); + if (!(await decideAll())) { + return {toast, error: text(document.getElementById("main")).slice(0, 300)}; + } + const appeared = performance.now(); + const layer = await until(rain, 2000); + if (!layer) { + return {toast, error: "no confetti"}; + } + const bar = document.getElementById("head").getBoundingClientRect().bottom; + const first = bits(); + const confetti = { + pieces: first.length, below: Math.min(...first.map((rect) => rect.top)) - bar, layerTop: Math.round(layer.getBoundingClientRect().top - bar), + spread: (Math.max(...first.map((rect) => rect.right)) - Math.min(...first.map((rect) => rect.left))) / innerWidth, + }; + await sleep(Math.max(0, 4500 - (performance.now() - appeared))); + confetti.landed = bits().map((rect) => Math.round(rect.bottom - innerHeight)); + confetti.resting = Number(getComputedStyle(layer).opacity); + await until(() => !rain(), CONFETTI_MAX); + confetti.gone = rain() ? null : Math.round(performance.now() - appeared); + confetti.left = all(".confetti-rain, .confetti-rain i").length; + const risk = document.querySelector('#main .match-decision[data-card="@RED@"] .match-accept-risk'); + if (risk) { + risk.click(); + await sleep(800); + } + const release = card(); + if (!release || !releasing()) { + return {toast, confetti, error: "no release card"}; + } + const released = await fading(release, () => key("d"), 20000); + return {toast, confetti, released}; +})()""" +CALMED = """(async () => {@HELPERS@@CARD@@STEPS@@WATCH@ + await screenShown(8000); + if (!(await until(card, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(400); + const box = await refusedToast(); + if (!box) { + return {error: "no refused toast"}; + } + const toast = await fading(box, () => box.click(), 3000); + if (!(await decideAll())) { + return {toast, error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(1000); + const confetti = all(".confetti-rain, .confetti-rain i").length; + const front = card(); + const back = await fading(front, () => key("ArrowLeft"), 4000); + return {toast, confetti, back}; +})()""" +BEAT = """(async () => {@HELPERS@ + const card = (task) => all("#main .kanban-card").find((node) => node.dataset.task === task) || null; + if (!(await until(() => card("work/delta") && card("work/delta").querySelector(".kanban-mark"), 10000))) { + return {error: text(document.getElementById("main"))}; + } + await sleep(400); + const keyframes = (wanted) => { + for (const sheet of document.styleSheets) { + for (const rule of sheet.cssRules) { + if (rule.type === CSSRule.KEYFRAMES_RULE && rule.name === wanted) { + return [...new Set([...rule.cssRules].flatMap((frame) => [...frame.style]))].sort(); + } + } + } + return null; + }; + const sample = async (node) => { + const seen = {transform: new Set(), shadow: new Set()}; + for (let at = 0; at < 26; at += 1) { + const look = getComputedStyle(node); + seen.transform.add(look.transform); + seen.shadow.add(look.boxShadow); + await sleep(50); + } + return {transforms: [...seen.transform].filter((value) => value !== "none").length, shadows: seen.shadow.size}; + }; + const tasks = [...@WORKING@, ...@STILL@]; + const marked = Object.fromEntries(tasks.map((task) => [task, card(task) ? card(task).classList.contains("is-working") : null])); + const animation = Object.fromEntries(tasks.map((task) => [task, card(task) ? getComputedStyle(card(task)).animationName : null])); + return {marked, animation, beat: await sample(card("work/delta")), still: await sample(card("work/echo")), frames: {beat: keyframes("lub-dub"), glow: keyframes("lub-dub-glow")}}; +})()""" + + +def probe(template: str, **names: str) -> str: + """Args: + template: a probe with @WATCH@, @WORKING@, @STILL@, CONFETTI_MAX and + the placeholders deck.probe() fills. + names: further @NAME@ placeholders and their values. + + Returns: + The probe with every placeholder filled. + """ + filled = template.replace("@WATCH@", WATCH).replace("@WORKING@", json.dumps(WORKING)).replace("@STILL@", json.dumps(STILL)).replace("CONFETTI_MAX", str(CONFETTI_MAX_MS)) + return deck.probe(filled, **names) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestHubMotion(deck.ReleaseDeck): + def run_deck(self, name: str, template: str, media: list[dict] | None) -> dict: + step = {"width": 1366, "height": 768, "url": f"{self.base}?{name}#tasks/match", "wait": 1500, "shot": str(OUT / f"chromium-{name}.png"), + "probe": probe(template, red=f"review:{self.red}"), "media": media or []} + with mock.patch.object(batches, "UNDO", 0.3): + data = self.drive([step], self.authenticator(), init=deck.INIT) + (OUT / f"chromium-{name}.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + found = data["results"][0] + self.assertNotIn("error", found, found) + return found + + def test_chromium_a_dismissed_toast_and_a_released_card_fade_and_confetti_lands_and_fades(self): + found = self.run_deck("motion", MOTION, None) + for part in ("toast", "released"): + with self.subTest(part=part): + self.assertIsNotNone(found[part]["gone"], found) + self.assertGreaterEqual(found[part]["span"], FADE_MIN_MS, found) + confetti = found["confetti"] + self.assertEqual(confetti["pieces"], 28, confetti) + self.assertGreaterEqual(confetti["below"], -1, confetti) + self.assertGreaterEqual(confetti["layerTop"], -1, confetti) + self.assertGreaterEqual(confetti["spread"], 0.9, confetti) + self.assertTrue(all(abs(gap) <= 2 for gap in confetti["landed"]), confetti) + self.assertEqual(confetti["resting"], 1, confetti) + self.assertIsNotNone(confetti["gone"], confetti) + self.assertLessEqual(confetti["gone"], CONFETTI_MAX_MS, confetti) + self.assertEqual(confetti["left"], 0, confetti) + + def test_chromium_under_reduced_motion_a_toast_and_a_card_leave_at_once_and_no_confetti_falls(self): + found = self.run_deck("calm", CALMED, CALM) + for part in ("toast", "back"): + with self.subTest(part=part): + self.assertIsNotNone(found[part]["gone"], found) + self.assertEqual(found[part]["frames"], 0, found) + self.assertEqual(found["confetti"], 0, found) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestHubHeartbeat(HubCase): + drive = base.OrchestratorE2ECase.drive + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + now = time.time() + self.write_council(running.board_council(now)) + sessions = { + "s-docs": {"name": "Docs session", "status": "busy", "statusUpdatedAt": int((now - 120) * 1000), "running": True}, + "s-late": {"name": "Late session", "status": "busy", "statusUpdatedAt": int((now - 600) * 1000), "running": True}, + } + self.httpd.hub.agent_sessions.write_text(json.dumps({"written": now, "sessions": sessions}), encoding="utf-8") + job = self.httpd.hub.jobs.add({"task": "work/delta", "command": "make deploy-hub", "directory": "/", "sha256": "", "status": "running", "proof": None, "head": "", + "code": None, "output": "", "created_ts": now, "started": now - 45, "finished": None, "dismissed": False}) + self.httpd.hub.runner_marker.write_text(json.dumps({"pid": os.getpid(), "job": job["id"], "task": "work/delta", "started": now - 45}), encoding="utf-8") + + def test_chromium_running_tasks_beat_with_scale_and_glow_and_keep_only_the_glow_under_reduced_motion(self): + local = f"http://localhost:{self.port}/" + steps = [{"width": 1366, "height": 768, "url": f"{local}?{name}#tasks/board", "wait": 1500, "probe": probe(BEAT), "shot": str(OUT / f"chromium-beat-{name}.png"), "media": media} + for name, media in (("motion", []), ("calm", CALM))] + data = self.drive(steps, None) + (OUT / "chromium-beat.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + moving, calm = data["results"] + for found, name in ((moving, "lub-dub"), (calm, "lub-dub-glow")): + with self.subTest(animation=name): + self.assertNotIn("error", found, found) + self.assertEqual(found["marked"], {**dict.fromkeys(WORKING, True), **dict.fromkeys(STILL, False)}, found) + self.assertEqual(found["animation"], {**dict.fromkeys(WORKING, name), **dict.fromkeys(STILL, "none")}, found) + self.assertGreater(found["beat"]["shadows"], 1, found) + self.assertEqual(found["still"], {"transforms": 0, "shadows": 1}, found) + self.assertGreater(moving["beat"]["transforms"], 0, moving) + self.assertEqual(calm["beat"]["transforms"], 0, calm) + self.assertEqual(moving["frames"], {"beat": ["box-shadow", "transform"], "glow": ["box-shadow"]}, moving) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_hub_plan_e2e.py b/tests/e2e/test_hub_plan_e2e.py index 5c5b865..cea81be 100644 --- a/tests/e2e/test_hub_plan_e2e.py +++ b/tests/e2e/test_hub_plan_e2e.py @@ -116,8 +116,8 @@ class TestHubPlan(base.OrchestratorE2ECase): with self.subTest(browser=browser, width=width): for probe in (gantt, burn, points_on, request, gantt_points, bulk): self.assertNotIn("error", probe) - self.assertEqual((probe["tall"], probe["wide"], probe["layout"]), (False, False, ["toolbar", "chips", "body"]), probe) - self.assertEqual(probe["rows"] == 1, width != 390, probe) + self.assertEqual((probe["tall"], probe["wide"], probe["layout"]), (False, False, ["toolbar", "body"]), probe) + self.assertIn(probe["rows"], (1, 2) if width == 390 else (1,), probe) self.planned(gantt, points=False) self.planned(gantt_points, points=True) self.assertEqual((burn["modes"], burn["request"]), ([["none", "true"], ["points", "false"]], False)) @@ -276,8 +276,8 @@ class TestHubPlan(base.OrchestratorE2ECase): with self.subTest(browser=browser, width=width): for probe in (eta, regression, reloaded, velocity, again, tips, shown): self.assertNotIn("error", probe) - self.assertEqual((probe["tall"], probe["wide"], probe["layout"]), (False, False, ["toolbar", "chips", "body"]), probe) - self.assertEqual(probe["rows"] == 1, width != 390, probe["rows"]) + self.assertEqual((probe["tall"], probe["wide"], probe["layout"]), (False, False, ["toolbar", "body"]), probe) + self.assertIn(probe["rows"], (1, 2) if width == 390 else (1,), probe["rows"]) for mode in ("none", "points", "back"): self.eta_checked(eta[mode], "points" if mode == "points" else "none", rows, edges, (begun - 1, ended + 1)) self.assertEqual(eta["modes"], [["none", "true"], ["points", "false"]]) diff --git a/tests/e2e/test_match_empty_state_e2e.py b/tests/e2e/test_match_empty_state_e2e.py new file mode 100644 index 0000000..14a2fc7 --- /dev/null +++ b/tests/e2e/test_match_empty_state_e2e.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import test_home_dashboard_e2e as dash +from hub_case import HubCase + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-085-empty-shots")) +EMPTY = """(async () => {@HELPERS@@HOME@ + if (@WIDGET@) { + await ViewStore.update("home.pins", () => [{kind: "panel", id: "tasks/match", w: 12, h: 8}]); + await go("#home"); + } else { + await screenShown(8000); + } + const empty = await until(() => document.querySelector("#main .match-deck > .match-empty"), 8000); + if (!empty) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(300); + const deck = empty.closest(".match-deck").getBoundingClientRect(); + const box = empty.getBoundingClientRect(); + const look = getComputedStyle(empty); + return { + headed: all("#main .box-head .match-glass, #main .home-head .match-glass").length, + glass: Boolean(empty.querySelector("button.match-glass.large .match-glass-face")), + words: [text(empty.querySelector("h2")), text(empty.querySelector("p"))], + frame: [look.borderTopStyle, look.borderTopWidth, look.backgroundImage, look.backgroundColor], + dx: box.left + box.width / 2 - (deck.left + deck.width / 2), + dy: box.top + box.height / 2 - (deck.top + deck.height / 2), + fits: deck.height > box.height && deck.width >= box.width, + wide: document.documentElement.scrollWidth > innerWidth + 1, + }; +})()""" +VIEWS = (*(("page", width, height) for width, height in base.WIDTHS), ("widget", 390, 844)) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestMatchEmptyState(HubCase): + drive = base.OrchestratorE2ECase.drive + + def steps(self) -> list[dict]: + OUT.mkdir(parents=True, exist_ok=True) + steps = [] + for view, width, height in VIEWS: + route = "stream" if view == "widget" else "tasks/match" + probe = EMPTY.replace("@HELPERS@", base.HELPERS).replace("@HOME@", dash.HOME).replace("@WIDGET@", "true" if view == "widget" else "false") + steps.append({"width": width, "height": height, "url": f"http://localhost:{self.port}/?{view}-{width}-empty#{route}", "wait": 1500, "probe": probe, "shot": str(OUT / f"chromium-{view}-{width}-empty.png")}) + return steps + + def test_chromium_shows_no_header_hourglass_and_a_bare_empty_state_in_the_middle_of_the_deck(self): + data = self.drive(self.steps(), None) + (OUT / "chromium-empty.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], []) + self.assertEqual(len(data["results"]), len(VIEWS), data) + for (view, width, _), found in zip(VIEWS, data["results"], strict=True): + with self.subTest(view=view, width=width): + self.assertNotIn("error", found, found) + self.assertEqual((found["headed"], found["glass"]), (0, True), found) + self.assertEqual(found["words"], ["No card waits", "Nothing waits on the operator."], found) + self.assertEqual(found["frame"], ["none", "0px", "none", "rgba(0, 0, 0, 0)"], found) + self.assertLessEqual(abs(found["dx"]), 4, found) + self.assertLessEqual(abs(found["dy"]), 4, found) + self.assertTrue(found["fits"], found) + self.assertFalse(found["wide"], found) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_match_expired_e2e.py b/tests/e2e/test_match_expired_e2e.py index 8421900..4be2a37 100644 --- a/tests/e2e/test_match_expired_e2e.py +++ b/tests/e2e/test_match_expired_e2e.py @@ -17,21 +17,25 @@ import hub_e2e_kit as base from hub_case import HubCase from hub_support import ASK, signing from kvb_orchestrator import batches, skill_scripts -from kvb_orchestrator.denying import LAPSED -OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-080-expired-shots")) -FEEDBACK = "run it again after the gate" +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-096-expired-shots")) AGO = 690 +GONE_MS = 300 TIP = re.compile(r"^expired \d{2}:\d{2}, 12 minutes ago$") FLOW = """(async () => {@HELPERS@ const posted = []; const send = window.fetch.bind(window); window.fetch = async (path, init) => { - if (["/api/sign", "/api/inbox/approve"].includes(String(path))) { - posted.push([String(path), JSON.parse(init.body).items.map((item) => [item.kind, item.id, item.verb, item.channel || null, item.reason || null, item.to || null])]); + if (["/api/sign", "/api/inbox/approve", "/api/requests/dismiss"].includes(String(path))) { + posted.push([String(path), JSON.parse(init.body).items.map((item) => [item.kind, item.target || null, item.id, item.verb || null, item.scope || null, item.channel || null])]); } return send(path, init); }; + const sheet = document.getElementById("sheet"); + let opened = false; + new MutationObserver(() => { + opened = opened || !sheet.hidden; + }).observe(sheet, {attributes: true, attributeFilter: ["hidden"]}); const card = () => document.querySelector("#main .match-card.front"); const front = () => (card() ? card().dataset.card : null); if (!(await until(card, 8000))) { @@ -47,29 +51,39 @@ FLOW = """(async () => {@HELPERS@ const style = getComputedStyle(stamp); const found = {id, stamp: text(stamp), kind: stamp.dataset.stamp, tip: stamp.title, color: style.color, opacity: style.opacity, pointer: style.pointerEvents, accept: document.querySelector("#main .match-accept").disabled, reject: document.querySelector("#main .match-reject").disabled}; - key("ArrowRight"); - await sleep(500); - const head = card().querySelector(".match-head"); - const box = head.getBoundingClientRect(); - const at = (x) => ({bubbles: true, cancelable: true, pointerId: 9, pointerType: "touch", isPrimary: true, button: 0, clientX: x, clientY: box.top + 20}); - head.dispatchEvent(new PointerEvent("pointerdown", at(box.left + box.width / 2))); - window.dispatchEvent(new PointerEvent("pointermove", at(box.left + box.width * 0.8))); - found.leaned = card().dataset.leaning || ""; - window.dispatchEvent(new PointerEvent("pointerup", at(box.left + box.width * 0.95))); + const swipe = async (share) => { + const head = card().querySelector(".match-head"); + const box = head.getBoundingClientRect(); + const at = (x) => ({bubbles: true, cancelable: true, pointerId: 9, pointerType: "touch", isPrimary: true, button: 0, clientX: x, clientY: box.top + 20}); + head.dispatchEvent(new PointerEvent("pointerdown", at(box.left + box.width / 2))); + window.dispatchEvent(new PointerEvent("pointermove", at(box.left + box.width * (0.5 + share / 2)))); + const leaned = card().dataset.leaning || ""; + const start = performance.now(); + window.dispatchEvent(new PointerEvent("pointerup", at(box.left + box.width * (0.5 + share)))); + return {leaned, start}; + }; + const right = await swipe(0.45); await sleep(500); + found.leaned = right.leaned; found.kept = front() === id; found.tally = text(document.querySelector("#main .match-tally")); found.wide = document.documentElement.scrollWidth > window.innerWidth + 1; if (@RELEASE@) { - key("ArrowLeft"); - const feedback = await until(() => document.querySelector(".sheet-box .match-feedback"), 3000); - if (!feedback) { - return {...found, error: "no feedback sheet"}; + const left = await swipe(-0.45); + found.leftLeaned = left.leaned; + while (front() === id && performance.now() - left.start < 2000) { + await sleep(10); } - feedback.value = "@FEEDBACK@"; - document.querySelector(".sheet-box .match-feedback-reject").click(); + found.goneMs = performance.now() - left.start; + await sleep(400); + found.sheetAfterSwipe = opened; + found.dropRows = all("#main .match-decision").map((row) => [row.dataset.card, row.dataset.verdict, text(row.querySelector(".match-verdict")), Boolean(row.querySelector(".match-decision-feedback"))]); + key("s"); + found.undone = Boolean(await until(() => front() === id, 3000)); + key("ArrowLeft"); const overview = await until(() => document.querySelector("#main .match-overview"), 4000); - found.rows = overview ? all("#main .match-decision").map((row) => [row.dataset.card, row.dataset.verdict]) : []; + found.sheetAfterKey = opened; + found.rows = overview ? all("#main .match-decision").map((row) => [row.dataset.card, row.dataset.verdict, text(row.querySelector(".match-verdict")), Boolean(row.querySelector(".match-decision-feedback"))]) : []; const shown = new Set(all("#toasts .toast")); document.querySelector("#main .match-release").click(); found.toast = await until(() => all("#toasts .toast").filter((node) => !shown.has(node)).map(text).find((entry) => entry.startsWith("Release")), 15000); @@ -78,6 +92,13 @@ FLOW = """(async () => {@HELPERS@ } return found; })()""" +AGAIN = """(async () => {@HELPERS@ + await until(() => document.querySelector("#main .match-stack .empty, #main .match-card.front"), 8000); + const response = await fetch("/api/match", {cache: "no-store"}); + const cards = (await response.json()).cards.map((card) => card.id); + const front = document.querySelector("#main .match-card.front"); + return {again: true, cards, front: front ? front.dataset.card : null, empty: Boolean(document.querySelector("#main .match-stack .empty"))}; +})()""" @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") @@ -95,23 +116,28 @@ class TestMatchExpired(HubCase): return [args for script, args in self.scripts.calls if script == skill_scripts.RADIO] def step(self, width: int, height: int, release: bool) -> dict: - flow = FLOW.replace("@HELPERS@", base.HELPERS).replace("@FEEDBACK@", FEEDBACK).replace("@RELEASE@", "true" if release else "false") + flow = FLOW.replace("@HELPERS@", base.HELPERS).replace("@RELEASE@", "true" if release else "false") shot = OUT / f"chromium-{width}-{'released' if release else 'expired'}.png" return {"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}-{release}#tasks/match", "wait": 1500, "probe": flow, "shot": str(shot)} - def test_chromium_stamps_an_expired_ask_offers_only_deny_and_releases_the_deny_by_radio(self): + def again(self) -> dict: + return {"width": 1366, "height": 768, "url": f"http://localhost:{self.port}/?again#tasks/match", "wait": 1500, "probe": AGAIN.replace("@HELPERS@", base.HELPERS), "shot": str(OUT / "chromium-1366-again.png")} + + def test_chromium_drops_an_expired_ask_silently_and_the_release_dismisses_it_for_every_page(self): OUT.mkdir(parents=True, exist_ok=True) steps = [self.step(width, height, False) for width, height in base.WIDTHS] + [self.step(1366, 768, True)] with mock.patch.object(batches, "UNDO", 0.3): data = self.drive(steps, self.authenticator()) - self.settle(lambda: self.httpd.hub.asks.get(self.ask)["status"] == "denied") - (OUT / "chromium-expired.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.settle(lambda: self.httpd.hub.dismissals.listed() != []) + again = self.drive([self.again()], None) + (OUT / "chromium-expired.json").write_text(json.dumps({"release": data, "again": again}, indent=1), encoding="utf-8") self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], []) self.assertEqual(len(data["results"]), len(steps), data) + card = f"ask:{self.ask}" for found in data["results"]: with self.subTest(step=found.get("toast") is not None): self.assertNotIn("error", found, found) - self.assertEqual((found["id"], found["stamp"], found["kind"]), (f"ask:{self.ask}", "EXPIRED", "expired"), found) + self.assertEqual((found["id"], found["stamp"], found["kind"]), (card, "EXPIRED", "expired"), found) self.assertRegex(found["tip"], TIP) self.assertEqual((found["opacity"], found["pointer"]), ("1", "auto"), found) channels = [int(part) for part in found["color"].removeprefix("rgb(").removesuffix(")").split(",")[:3]] @@ -120,17 +146,26 @@ class TestMatchExpired(HubCase): self.assertEqual((found["leaned"], found["kept"], found["tally"]), ("", True, "0"), found) self.assertFalse(found["wide"], found) released = data["results"][-1] - self.assertEqual(released["rows"], [[f"ask:{self.ask}", "reject"]], released) + self.assertEqual(released["leftLeaned"], "reject", released) + self.assertLess(released["goneMs"], GONE_MS, released) + self.assertFalse(released["sheetAfterSwipe"], released) + self.assertEqual(released["dropRows"], [[card, "drop", "Drop (expired)", False]], released) + self.assertTrue(released["undone"], released) + self.assertFalse(released["sheetAfterKey"], released) + self.assertEqual(released["rows"], [[card, "drop", "Drop (expired)", False]], released) self.assertNotIn("not possible", released["toast"], released) self.assertTrue(released["emptied"], released) self.assertEqual([path for path, _ in released["posted"]], ["/api/sign", "/api/inbox/approve"], released) - self.assertEqual(released["posted"][1][1], [["ask", self.ask, "reject", "call", FEEDBACK, "Skills"]], released) - self.settle(lambda: self.radio() != []) - self.assertEqual(self.radio()[-1][:4], ["send", "call", "--to", "Skills session"]) - self.assertTrue(self.radio()[-1][-1].endswith(f"Denied by the operator: ask Bash: make deploy, {LAPSED} (from Skills). Reason: {FEEDBACK}"), self.radio()[-1]) + self.assertEqual(released["posted"][1][1], [["dismiss", "ask", self.ask, None, "expired", None]], released) + self.assertEqual(len(again["results"]), 1, again) + shown = again["results"][0] + self.assertNotIn(card, shown["cards"], shown) + self.assertEqual((shown["front"], shown["empty"]), (None, True), shown) + self.assertEqual(self.httpd.hub.asks.get(self.ask)["status"], "pending") + self.assertEqual(self.radio(), []) status, _, body = self.get("/api/match") self.assertEqual(status, 200, body) - self.assertNotIn(f"ask:{self.ask}", [card["id"] for card in json.loads(body)["cards"]]) + self.assertNotIn(card, [entry["id"] for entry in json.loads(body)["cards"]]) if __name__ == "__main__": diff --git a/tests/e2e/test_match_hourglass_e2e.py b/tests/e2e/test_match_hourglass_e2e.py index ae7a80b..3d542da 100644 --- a/tests/e2e/test_match_hourglass_e2e.py +++ b/tests/e2e/test_match_hourglass_e2e.py @@ -27,7 +27,7 @@ SPY = """() => { }; }""" KIT = """@HELPERS@ - const small = () => document.querySelector(".match-glass.small"); + const headed = () => all("#main .box-head .match-glass").length; const large = () => document.querySelector("#main .match-glass.large"); const fetches = () => window.matchFetches.length; const gaps = (times) => times.slice(1).map((at, index) => Math.round(at - times[index])); @@ -39,8 +39,8 @@ KIT = """@HELPERS@ } }; const setDial = async (key, times) => { - const box = small().getBoundingClientRect(); - const prevented = !small().dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, button: 2, clientX: box.left + 4, clientY: box.top + 4})); + const box = large().getBoundingClientRect(); + const prevented = !large().dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, button: 2, clientX: box.left + 4, clientY: box.top + 4})); const dial = await until(() => document.querySelector("#sheet .match-refresh-dial"), 3000); if (!dial) { return {prevented, error: "no dial"}; @@ -53,51 +53,51 @@ KIT = """@HELPERS@ return {prevented, from, to, closed: Boolean(closed)}; };""" FIRST = """(async () => {@KIT@ - if (!(await until(() => small() && large() && fetches() >= 2, 8000))) { + if (!(await until(() => large() && fetches() >= 2, 8000))) { return {error: text(document.getElementById("main"))}; } const start = fetches(); await until(() => fetches() >= start + 3, 9000); const rate = gaps(window.matchFetches.slice(start - 1, start + 3)); await sleep(300); - const turn = Number(small().dataset.turn); + const turn = Number(large().dataset.turn); const fetched = await until(() => (fetches() > start + 3 ? window.matchFetches[window.matchFetches.length - 1] : null), 4000); - await until(() => Number(small().dataset.turn) > turn, 1000); - const running = flips(small()); + await until(() => Number(large().dataset.turn) > turn, 1000); + const running = flips(large()); await sleep(Math.max(0, fetched + 1000 - performance.now())); - const flip = {turned: Number(small().dataset.turn) > turn, ran: running.length, finished: running.every((animation) => animation.playState === "finished"), - sand: getComputedStyle(small().querySelector(".match-glass-top")).animationDuration, grains: small().querySelectorAll(".match-grain").length}; + const flip = {turned: Number(large().dataset.turn) > turn, ran: running.length, finished: running.every((animation) => animation.playState === "finished"), + sand: getComputedStyle(large().querySelector(".match-glass-top")).animationDuration, grains: large().querySelectorAll(".match-grain").length}; await sleep(700); const before = fetches(); const clickedAt = performance.now(); - small().click(); + large().click(); await until(() => fetches() > before, 1000); const click = {at: Math.round(window.matchFetches[before] - clickedAt)}; await until(() => fetches() > before + 1, 4000); click.next = Math.round(window.matchFetches[before + 1] - window.matchFetches[before]); - const sizes = {small: small().getBoundingClientRect().height, large: large().getBoundingClientRect().height}; + const sizes = {headed: headed(), large: large().getBoundingClientRect().height}; const dial = await setDial("ArrowRight", 8); return {rate, flip, click, sizes, dial, wide: document.documentElement.scrollWidth > window.innerWidth + 1}; })()""" RELOADED = """(async () => {@KIT@ - if (!(await until(() => small() && fetches() >= 1, 8000))) { + if (!(await until(() => large() && fetches() >= 1, 8000))) { return {error: text(document.getElementById("main"))}; } const first = fetches(); await sleep(3500); - const kept = {quiet: fetches() === first, sand: small().style.getPropertyValue("--match-refresh"), title: small().title}; + const kept = {quiet: fetches() === first, sand: large().style.getPropertyValue("--match-refresh"), title: large().title}; const dial = await setDial("ArrowLeft", 8); return {kept, dial}; })()""" STILL = """(async () => {@KIT@ - if (!(await until(() => small() && large() && fetches() >= 1, 8000))) { + if (!(await until(() => large() && fetches() >= 1, 8000))) { return {error: text(document.getElementById("main"))}; } - const turn = Number(small().dataset.turn); - await until(() => Number(small().dataset.turn) > turn, 4000); + const turn = Number(large().dataset.turn); + await until(() => Number(large().dataset.turn) > turn, 4000); await sleep(200); - const glasses = [small(), large()]; - return {turned: Number(small().dataset.turn) > turn, running: glasses.map((glass) => glass.getAnimations({subtree: true}).length), face: glasses.map((glass) => getComputedStyle(glass.querySelector(".match-glass-face")).animationName)}; + const glasses = [large()]; + return {turned: Number(large().dataset.turn) > turn, running: glasses.map((glass) => glass.getAnimations({subtree: true}).length), face: glasses.map((glass) => getComputedStyle(glass.querySelector(".match-glass-face")).animationName)}; })()""" @@ -134,14 +134,15 @@ class TestMatchHourglass(HubCase): self.assertEqual(first["flip"], {"turned": True, "ran": 1, "finished": True, "sand": "2s", "grains": 3}, first) self.assertLess(first["click"]["at"], 300, first) self.assertAlmostEqual(first["click"]["next"], 2000, delta=300, msg=first) - self.assertGreater(first["sizes"]["large"], 2 * first["sizes"]["small"], first) + self.assertEqual(first["sizes"]["headed"], 0, first) + self.assertGreater(first["sizes"]["large"], 80, first) self.assertEqual(first["dial"], {"prevented": True, "from": 2, "to": 10, "closed": True}, first) self.assertFalse(first["wide"], first) self.assertEqual(reloaded["kept"]["quiet"], True, reloaded) self.assertEqual(reloaded["kept"]["sand"], "10s", reloaded) self.assertIn("every 10 s", reloaded["kept"]["title"], reloaded) self.assertEqual(reloaded["dial"], {"prevented": True, "from": 10, "to": 2, "closed": True}, reloaded) - self.assertEqual(still, {"turned": True, "running": [0, 0], "face": ["none", "none"]}, still) + self.assertEqual(still, {"turned": True, "running": [0], "face": ["none"]}, still) if __name__ == "__main__": diff --git a/tests/e2e/test_match_release_card_e2e.py b/tests/e2e/test_match_release_card_e2e.py index a0cc92f..d9273f8 100644 --- a/tests/e2e/test_match_release_card_e2e.py +++ b/tests/e2e/test_match_release_card_e2e.py @@ -12,6 +12,7 @@ HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] import hub_e2e_kit as base +import test_home_dashboard_e2e as dash import test_match_review_e2e as matched from hub_case import HubCase from kvb_orchestrator import batches @@ -48,11 +49,11 @@ STEPS = """ } return releasing(); }; - const swipeRight = async () => { + const swipe = async (sign) => { const head = card().querySelector(".match-head"); const box = head.getBoundingClientRect(); const [x, y] = [box.left + box.width / 2, box.top + 20]; - const dx = card().getBoundingClientRect().width * 0.4; + const dx = sign * card().getBoundingClientRect().width * 0.4; const at = (cx) => ({bubbles: true, cancelable: true, pointerId: 12, pointerType: "touch", isPrimary: true, button: 0, clientX: cx, clientY: y}); head.dispatchEvent(new PointerEvent("pointerdown", at(x))); window.dispatchEvent(new PointerEvent("pointermove", at(x + dx / 2))); @@ -60,6 +61,8 @@ STEPS = """ window.dispatchEvent(new PointerEvent("pointerup", at(x + dx))); return leaning; }; + const swipeRight = () => swipe(1); + const unreleased = () => !releasing() && card() && card().dataset.card; """ CARD040 = """(async () => {@HELPERS@@CARD@@STEPS@ await screenShown(8000); @@ -70,14 +73,25 @@ CARD040 = """(async () => {@HELPERS@@CARD@@STEPS@ const found = {ready: await decideAll()}; const front = card(); found.release = Boolean(front && front.closest(".match-deck") && front.querySelector(".match-release")); - found.held = text(document.querySelector("#main .match-release-held")); + found.labelled = all("button", front).map(name).filter((words) => /^Release \\d+ decisions?$/.test(words || "")); + const acts = all("#main .match-stack > .match-actions .match-act"); + found.row = acts.map((node) => [node.classList[1], text(node.querySelector(".match-act-label")), node.disabled]); + found.sides = acts.map((node) => Math.round(node.getBoundingClientRect().left)); + found.held = document.querySelector("#main .match-release") ? document.querySelector("#main .match-release").title : null; found.verdicts = all("#main .match-decision").filter((node) => node.querySelector(".match-verdict")).map((node) => node.dataset.card); found.layers = all("#main .match-layer").map((node) => node.dataset.card); found.block = Boolean(document.querySelector("#main .match-release-block")); found.risk = all("#main .match-accept-risk").map((node) => [node.closest(".match-decision").dataset.card, node.getAttribute("aria-pressed")]); found.label = text(document.querySelector("#main .match-release")); key("ArrowLeft"); - found.back = await until(() => !releasing() && card() && card().dataset.card, 4000); + found.back = await until(unreleased, 4000); + key("s"); + found.undone = Boolean(await until(releasing, 4000)); + key("a"); + found.skipped = await until(unreleased, 4000); + key("s"); + await until(releasing, 4000); + found.swiped = [await swipe(-1), await until(unreleased, 4000)]; document.querySelector("#main .match-open-overview").click(); found.again = Boolean(await until(releasing, 4000)); const cards = await served(); @@ -105,14 +119,73 @@ RELEASE = """(async () => {@HELPERS@@CARD@@STEPS@ pressed.push(risk().getAttribute("aria-pressed")); } const label = text(document.querySelector("#main .match-release")); + const disabled = document.querySelector("#main .match-release").disabled; window.e2eSubmits.length = 0; - const leaning = @SWIPE@ ? await swipeRight() : (key("ArrowRight"), ""); + const corner = []; + const watch = new MutationObserver(() => { + const box = document.querySelector("#toasts .toast.wait"); + if (!box || corner.length) { + return; + } + const mark = box.querySelector(".undo-row > .undo-glass:last-child"); + const undo = box.querySelector(".undo-row > .btn"); + if (!mark || !mark.querySelector(".match-glass-face") || !undo) { + corner.push({glass: false}); + return; + } + const [outer, glass, button] = [box, mark, undo].map((node) => node.getBoundingClientRect()); + corner.push({glass: true, right: Math.round(outer.right - glass.right), bottom: Math.round(outer.bottom - glass.bottom), after: glass.left >= button.right}); + }); + watch.observe(document.getElementById("toasts"), {childList: true}); + const leaning = @SWIPE@ ? await swipeRight() : (key("@KEY@"), ""); await until(() => window.e2eSubmits.length >= @SUBMITS@, 20000); await sleep(1500); + watch.disconnect(); if (@SUBMITS@) { await until(() => card() && !releasing(), 8000); } - return {pressed, label, leaning, submits: window.e2eSubmits, front: card() ? card().dataset.card : null, peeks: all("#main .match-peek").map((node) => node.dataset.card)}; + return {pressed, label, disabled, leaning, corner, submits: window.e2eSubmits, front: card() ? card().dataset.card : null, peeks: all("#main .match-peek").map((node) => node.dataset.card)}; +})()""" +HEIGHTS = """(async () => {@HELPERS@@HOME_KIT@@CARD@@STEPS@ + if (@WIDGET@) { + await ViewStore.update("home.pins", () => [{kind: "panel", id: "tasks/match", w: 12, h: 8}]); + await go("#home"); + } else { + await screenShown(8000); + } + if (!(await until(card, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(700); + const box = (node) => { + const rect = node.getBoundingClientRect(); + return [rect.left, rect.top, rect.width, rect.height]; + }; + const row = (selector) => all(`:scope > .match-actions ${selector}`, card().closest(".match-stack")); + const measure = () => { + const front = card(); + const inner = front.querySelector(".match-body"); + return {id: front.dataset.card, card: box(front), deck: box(front.closest(".match-deck")), scrolls: inner.scrollHeight > inner.clientHeight + 1, + acts: row(".match-act").map((node) => [node.classList[1], ...box(node)])}; + }; + const seen = []; + for (const id of @IDS@) { + if (card().dataset.card !== id) { + await pick(id); + await sleep(700); + } + seen.push(measure()); + } + for (let tries = 0; tries < 10 && card() && !releasing(); tries += 1) { + const id = card().dataset.card; + const greyed = card().dataset.stale === "true" || card().hasAttribute("data-blocked"); + row(greyed ? ".match-later" : ".match-accept")[0].click(); + await until(() => !card() || card().dataset.card !== id, 4000); + await sleep(200); + } + await sleep(700); + seen.push(releasing() ? measure() : {id: null}); + return {seen, wide: document.documentElement.scrollWidth > innerWidth + 1}; })()""" @@ -144,9 +217,9 @@ class ReleaseDeck(HubCase): @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestMatchReleaseCard(ReleaseDeck): - def release(self, name: str, clicks: int, swipe: bool, submits: int) -> dict: + def release(self, name: str, clicks: int, swipe: bool, submits: int, key: str = "ArrowRight") -> dict: step = {"width": 1920, "height": 1080, "url": f"{self.base}?{name}#tasks/match", "wait": 1500, "shot": str(OUT / f"chromium-{name}.png"), - "probe": probe(RELEASE, red=f"review:{self.red}", clicks=str(clicks), swipe="true" if swipe else "false", submits=str(submits))} + "probe": probe(RELEASE, red=f"review:{self.red}", clicks=str(clicks), swipe="true" if swipe else "false", submits=str(submits), key=key)} with mock.patch.object(batches, "UNDO", 0.3): data = self.drive([step], self.authenticator(), init=INIT) (OUT / f"chromium-{name}.json").write_text(json.dumps(data, indent=1), encoding="utf-8") @@ -171,23 +244,65 @@ class TestMatchReleaseCard(ReleaseDeck): self.assertIn(f"review:{self.stale}", found["layers"], found) self.assertEqual(found["risk"], [[f"review:{self.red}", "false"]], found) self.assertNotIn(f"review:{self.red}", found["verdicts"], found) - self.assertEqual((found["label"], found["held"]), (None, "One red-gate commit waits for your risk accept or its way back to the stack."), found) + self.assertEqual(found["labelled"], [], found) + self.assertEqual(found["row"], [["match-drop", "Cancel", True], ["match-skip", "Skip", False], ["match-release", "Release", True]], found) + self.assertEqual(found["sides"], sorted(found["sides"]), found) + self.assertEqual(found["label"], "Release", found) + self.assertIn("one red-gate commit waits for your risk accept or its way back to the stack.", found["held"], found) + self.assertIn("feat: red gate", found["held"], found) self.assertEqual(found["back"], f"review:{self.stale}", found) + self.assertEqual((found["undone"], found["skipped"], found["swiped"]), (True, f"review:{self.stale}", ["reject", f"review:{self.stale}"]), found) self.assertEqual((found["again"], found["arrived"], found["stays"]), (True, True, True), found) - def test_chromium_an_open_risk_hides_the_release_and_the_arrow_releases_nothing(self): + def test_chromium_every_card_keeps_the_deck_height_and_its_three_buttons_in_place(self): + ids = [f"review:{self.commit}", "operator:operator/issue", f"review:{self.stale}", f"review:{self.red}"] + sizes = (("page", 1366, 768, "tasks/match"), ("widget", 390, 900, "stream")) + steps = [{"width": width, "height": height, "url": f"{self.base}?{view}-{width}-heights#{route}", "wait": 1500, "shot": str(OUT / f"chromium-{view}-{width}-heights.png"), + "probe": probe(HEIGHTS, ids=json.dumps(ids), widget="true" if view == "widget" else "false", home_kit=dash.HOME)} for view, width, height, route in sizes] + data = self.drive(steps, None, init=INIT) + (OUT / "chromium-heights.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + for (view, width, _, _), found in zip(sizes, data["results"], strict=True): + with self.subTest(view=view, width=width): + self.assertNotIn("error", found, found) + seen = found["seen"] + self.assertEqual([one["id"] for one in seen], [*ids, "release"], found) + first = seen[0] + self.assertTrue(first["scrolls"], first) + self.assertEqual([act[0] for act in first["acts"]], ["match-reject", "match-later", "match-accept"], first) + for one in seen[1:]: + self.assertAlmostEqual(one["card"][3], first["card"][3], delta=1, msg=one) + self.assertAlmostEqual(one["card"][3], one["deck"][3] - (one["card"][1] - one["deck"][1]), delta=1, msg=one) + self.assertEqual(len(one["acts"]), 3, one) + for act, kept in zip(one["acts"], first["acts"], strict=True): + for at, was in zip(act[1:], kept[1:], strict=True): + self.assertAlmostEqual(at, was, delta=1, msg=(one, first)) + self.assertEqual([act[0] for act in seen[-1]["acts"]], ["match-drop", "match-skip", "match-release"], found) + self.assertFalse(found["wide"], found) + + def test_chromium_an_open_risk_greys_the_release_and_the_arrow_releases_nothing(self): found = self.release("no-risk", 0, False, 0) - self.assertEqual((found["submits"], found["label"], found["front"]), ([], None, "release"), found) + self.assertEqual((found["submits"], found["label"], found["disabled"], found["front"], found["corner"]), ([], "Release", True, "release", []), found) def test_chromium_release_by_swipe_signs_a_risk_accepted_red_gate_commit_on_its_own_first(self): found = self.release("risk", 1, True, 2) - self.assertEqual((found["pressed"], found["leaning"], found["label"]), (["true"], "accept", "Release 3 decisions"), found) + self.assertEqual((found["pressed"], found["leaning"], found["label"], found["disabled"]), (["true"], "accept", "Release", False), found) self.assertEqual(self.sorted_submits(found), [[["review", self.red, "approve"]], sorted([["review", self.commit, "approve"], ["operator", "operator/issue", "approve"]])], found) self.settle(lambda: self.status(self.red) == "approved" and self.status(self.commit) == "approved") - def test_chromium_a_withdrawn_risk_hides_the_release_again(self): + def test_chromium_d_releases_and_the_undo_countdown_shows_the_hourglass_bottom_right(self): + found = self.release("risk-d", 1, False, 2, "d") + self.assertEqual((found["pressed"], found["disabled"]), (["true"], False), found) + self.assertEqual(len(found["submits"]), 2, found) + self.assertEqual(len(found["corner"]), 1, found) + corner = found["corner"][0] + self.assertEqual((corner["glass"], corner["after"]), (True, True), found) + self.assertTrue(0 <= corner["right"] <= 40 and 0 <= corner["bottom"] <= 40, found) + self.settle(lambda: self.status(self.red) == "approved" and self.status(self.commit) == "approved") + + def test_chromium_a_withdrawn_risk_greys_the_release_again(self): found = self.release("withdrawn", 2, False, 0) - self.assertEqual((found["pressed"], found["label"], found["submits"], found["front"]), (["true", "false"], None, [], "release"), found) + self.assertEqual((found["pressed"], found["label"], found["disabled"], found["submits"], found["front"]), (["true", "false"], "Release", True, [], "release"), found) if __name__ == "__main__": diff --git a/tests/e2e/test_match_release_e2e.py b/tests/e2e/test_match_release_e2e.py index 9d0a348..9d56639 100644 --- a/tests/e2e/test_match_release_e2e.py +++ b/tests/e2e/test_match_release_e2e.py @@ -187,7 +187,7 @@ class TestMatchRelease(HubCase): self.assertEqual((found["prefill"], found["leaned"], found["short"], found["stayed"]), (reason, "accept", "accept", True), found) expected = [[self.cards[0], "reject", f"{reason}\nalso add a test"], [self.cards[1], "accept", None], [self.cards[2], "accept", None]] self.assertEqual(sorted(found["rows"]), sorted(expected), found) - self.assertEqual((found["label"], found["disabled"], found["wide"]), ("Release 3 decisions", False, False), found) + self.assertEqual((found["label"], found["disabled"], found["wide"]), ("Release", False, False), found) def run_flow(self, browser: str, driver: str, binary: str, signs: bool) -> dict: with mock.patch.object(batches, "UNDO", 0.3): diff --git a/tests/e2e/test_match_show_filter_e2e.py b/tests/e2e/test_match_show_filter_e2e.py new file mode 100644 index 0000000..6861e5e --- /dev/null +++ b/tests/e2e/test_match_show_filter_e2e.py @@ -0,0 +1,151 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import test_match_release_card_e2e as deck +from hub_support import ASK + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-097-show-shots")) +KEY = "kvb-orchestrator.match-show" +MENU = """ + const shownMenu = () => document.querySelector(".ctx-menu:not([hidden])"); + const showItems = () => all('[data-scope="match-show"] .ctx-item', shownMenu() || document.createElement("div")); + const showRead = () => showItems().map((node) => [text(node.querySelector(".ctx-label")), text(node.querySelector(".muted")), node.getAttribute("role"), node.getAttribute("aria-checked")]); + const showItem = (label) => showItems().find((node) => text(node.querySelector(".ctx-label")) === label); + const rightClick = (node) => { + const box = node.getBoundingClientRect(); + return !node.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, button: 2, clientX: box.left + 8, clientY: box.top + 4})); + }; + const closeMenu = async () => { + if (shownMenu()) { + shownMenu().dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true, cancelable: true})); + } + await until(() => !shownMenu(), 3000); + }; + const deckIds = () => all("#main .match-stack [data-card]").map((node) => node.dataset.card); + const hiddenHead = () => { + const button = document.querySelector("#main .match-hidden"); + return button ? [button.hidden, text(button)] : null; + }; +""" +FIRST = """(async () => {@HELPERS@@CARD@@STEPS@@MENU@ + await screenShown(8000); + if (!(await until(card, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(400); + const found = {head: hiddenHead(), asks: deckIds().filter((id) => id.startsWith("ask:")).length}; + found.prevented = rightClick(card().querySelector(".match-title")); + await until(shownMenu, 3000); + found.menu = showRead(); + showItem("Ask").click(); + await sleep(400); + found.open = Boolean(shownMenu()); + found.ask = showItem("Ask") ? showItem("Ask").getAttribute("aria-checked") : null; + await closeMenu(); + await until(() => !deckIds().some((id) => id.startsWith("ask:")), 4000); + await sleep(400); + found.after = {asks: deckIds().filter((id) => id.startsWith("ask:")).length, head: hiddenHead(), stored: localStorage.getItem("@KEY@")}; + for (let tries = 0; tries < 6 && !card().querySelector(".match-file tr[data-line]"); tries += 1) { + const id = card().dataset.card; + key("w"); + await until(() => card() && card().dataset.card !== id, 3000); + await sleep(250); + } + const row = card().querySelector(".match-file tr[data-line]"); + if (row) { + rightClick(row); + found.comment = {field: Boolean(await until(() => card().querySelector(".match-comment textarea"), 3000)), menu: Boolean(shownMenu())}; + card().querySelector(".match-comment .btn.ghost").click(); + await sleep(300); + } + return found; +})()""" +SECOND = """(async () => {@HELPERS@@CARD@@STEPS@@MENU@ + await screenShown(8000); + if (!(await until(card, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(400); + const found = {reloaded: {asks: deckIds().filter((id) => id.startsWith("ask:")).length, head: hiddenHead(), stored: localStorage.getItem("@KEY@")}}; + const decidedId = card().dataset.card; + key("d"); + await until(() => !card() || card().dataset.card !== decidedId, 4000); + await sleep(300); + document.querySelector("#main .match-hidden").click(); + found.opened = Boolean(await until(shownMenu, 3000)); + for (const label of ["Commit", "Command"]) { + showItem(label).click(); + await sleep(300); + } + await closeMenu(); + await until(releasing, 4000); + await sleep(400); + found.release = {front: releasing(), listed: all("#main .match-decision").map((node) => node.dataset.card), decided: decidedId, head: hiddenHead()}; + key("s"); + const empty = await until(() => document.querySelector("#main .match-deck > .match-all-hidden"), 4000); + await sleep(300); + found.empty = empty ? {words: text(empty.querySelector("h2")), glass: Boolean(empty.querySelector(".match-glass")), button: text(empty.querySelector(".match-show-all")), head: hiddenHead()} : null; + if (empty) { + empty.querySelector(".match-show-all").click(); + } + await until(card, 4000); + await sleep(400); + found.restored = {cards: deckIds().filter((id) => id !== "release").length, asks: deckIds().filter((id) => id.startsWith("ask:")).length, head: hiddenHead(), stored: localStorage.getItem("@KEY@")}; + found.wide = document.documentElement.scrollWidth > innerWidth + 1; + return found; +})()""" + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestMatchShowFilter(deck.ReleaseDeck): + def setUp(self): + super().setUp() + self.ask = self.create_ask({**ASK, "command": "make show", "timeout": 3600}) + + def step(self, name: str, template: str) -> dict: + probe = deck.probe(template.replace("@MENU@", MENU), key=KEY) + return {"width": 1366, "height": 900, "url": f"{self.base}?{name}#tasks/match", "wait": 1500, "probe": probe, "shot": str(OUT / f"chromium-{name}.png")} + + def test_chromium_hides_a_kind_remembers_it_across_a_reload_names_all_hidden_and_show_all_restores_the_deck(self): + OUT.mkdir(parents=True, exist_ok=True) + data = self.drive([self.step("show-first", FIRST), self.step("show-reload", SECOND)], None, init=deck.INIT) + (OUT / "chromium-show.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + first, second = data["results"] + self.assertNotIn("error", first, first) + self.assertNotIn("error", second, second) + self.assertEqual((first["head"], first["asks"], first["prevented"]), ([True, "0 hidden"], 1, True), first) + menu = first["menu"] + self.assertEqual([row[0] for row in menu], ["Commit", "Command", "Ask", "Decision", "Rule", "Expired", "Stale", "Greyed", "Show all"], first) + self.assertEqual([row[2] for row in menu], ["menuitemcheckbox"] * 8 + ["menuitem"], first) + self.assertEqual([row[3] for row in menu[:8]], ["true"] * 8, first) + counts = {row[0]: row[1] for row in menu[:8]} + self.assertEqual({label: counts[label] for label in ("Commit", "Command", "Ask", "Decision", "Rule", "Stale")}, {"Commit": "3", "Command": "1", "Ask": "1", "Decision": "0", "Rule": "0", "Stale": "1"}, first) + self.assertTrue(all(counts[label].isdigit() for label in ("Expired", "Greyed")), first) + self.assertEqual((first["open"], first["ask"]), (True, "false"), first) + self.assertEqual(first["after"], {"asks": 0, "head": [False, "1 hidden"], "stored": '["ask"]'}, first) + self.assertEqual(first["comment"], {"field": True, "menu": False}, first) + self.assertEqual(second["reloaded"], {"asks": 0, "head": [False, "1 hidden"], "stored": '["ask"]'}, second) + self.assertTrue(second["opened"], second) + release = second["release"] + self.assertTrue(release["front"], second) + self.assertIn(release["decided"], release["listed"], second) + self.assertEqual(release["head"], [False, "4 hidden"], second) + self.assertEqual(second["empty"], {"words": "All 5 cards hidden by the Show filter", "glass": False, "button": "Show all", "head": [False, "5 hidden"]}, second) + self.assertEqual(second["restored"]["asks"], 1, second) + self.assertEqual((second["restored"]["head"], second["restored"]["stored"]), ([True, "0 hidden"], "[]"), second) + self.assertGreaterEqual(second["restored"]["cards"], 5, second) + self.assertFalse(second["wide"], second) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_queue_overlay_e2e.py b/tests/e2e/test_queue_overlay_e2e.py index 728e7f1..4f924c0 100644 --- a/tests/e2e/test_queue_overlay_e2e.py +++ b/tests/e2e/test_queue_overlay_e2e.py @@ -95,6 +95,7 @@ LAYERS = """(async () => {@HELPERS@@READ@ await sleep(300); const back = document.activeElement; const closed = [document.getElementById("popup").open, back && back.closest(".kanban-card") ? [back.closest(".kanban-card").dataset.task, back.dataset.job] : null]; + await openTaskMenu("task-filter"); chip("jobs").click(); await until(() => !document.querySelector("#main .queue-job"), 4000); chip("line").click(); @@ -108,6 +109,7 @@ KEPT = """(async () => {@HELPERS@@READ@ } await sleep(400); const kept = read(); + await openTaskMenu("task-filter"); chip("jobs").click(); await until(() => document.querySelector("#main .queue-job"), 4000); chip("line").click(); diff --git a/tests/e2e/test_resource_limits_e2e.py b/tests/e2e/test_resource_limits_e2e.py index 66db67d..107504a 100644 --- a/tests/e2e/test_resource_limits_e2e.py +++ b/tests/e2e/test_resource_limits_e2e.py @@ -1,4 +1,4 @@ -"""Exercise requirement 084: limit lines and the target on the Hardware chart, the dial, the profile switch, the Limits sheet and the passkey to loosen.""" +"""Exercise requirements 084 and 091: limit lines dragged on the Hardware chart, staged changes with one Save and the passkey to loosen, the Limits and View menus, the right-click matrix, the tooltips and the GPU cause.""" from __future__ import annotations @@ -18,14 +18,25 @@ import test_workbench_w4_e2e as w4 from hub_case import HubCase from kvb_orchestrator import limiting -OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-084-shots")) +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-091-shots")) LEVELS = ("lower", "upper", "stop", "mayday") +NAMES = ("lower", "upper", "STOP", "MAYDAY") PROFILES = {name: {metric: dict(zip(LEVELS, values, strict=True)) for metric, values in table.items()} for name, table in limiting.PROFILE_TABLE.items()} TARGET = {"cpu": 84.0, "ram": 80.5, "psi": 0.2, "stepped": 1, "samples": []} +MISMATCH = "Failed to initialize NVML: Driver/library version mismatch" +BLOCKED = (200, 215) +HUNG = (230, 240) +ORDER = "breaks lower < upper < STOP < MAYDAY" +UPPER = "upper: the queue starts no job whose footprint would lift the load above it" READ = """ + const FRAME = 6; const chart = () => document.querySelector('#main svg.res-chart[data-chart="hardware"]'); - const lines = () => all("g.res-limit", chart() || document).map((node) => [node.dataset.metric, node.dataset.level, Number(node.dataset.value), text(node.querySelector("text")), text(node.querySelector("title"))]); - const target = () => all("g.res-target", chart() || document).map((node) => [node.dataset.metric, Number(node.dataset.value), text(node.querySelector("text"))]); + const lines = () => all("g.res-limit", chart() || document).map((node) => ({ + metric: node.dataset.metric, level: node.dataset.level, value: Number(node.dataset.value), label: text(node.querySelector("text")), title: text(node.querySelector("title")), + moved: node.classList.contains("moved"), was: Boolean(node.querySelector(".res-limit-was")), dash: getComputedStyle(node.querySelector(".res-limit-mark")).strokeDasharray, + role: node.getAttribute("role"), now: node.getAttribute("aria-valuenow"), + })); + const target = () => all("g.res-target", chart() || document).map((node) => [node.dataset.metric, Number(node.dataset.value), text(node.querySelector("text")), text(node.querySelector("title"))]); const line = (level) => (chart() ? chart().querySelector(`g.res-limit.${level}`) : null); const pressed = (group) => all(`#main [aria-label="${group}"] button[aria-pressed="true"]`).map(text); const button = (group, label) => all(`#main [aria-label="${group}"] button`).find((node) => text(node) === label); @@ -33,11 +44,40 @@ READ = """ const box = document.querySelector("#sheet:not([hidden]) .sheet-box"); return box ? box.getAttribute("aria-label") : null; }; - const dialRoot = () => document.querySelector("#sheet .limit-dial"); - const key = (name) => dialRoot().dispatchEvent(new KeyboardEvent("keydown", {key: name, bubbles: true, cancelable: true})); + const stage = (root) => { + const bar = (root || document.querySelector("#main .res-limits")).querySelector(".limit-stage"); + const error = bar.querySelector(".limit-error"); + return {shown: !bar.hidden, save: text(bar.querySelector(".limit-save")), disabled: bar.querySelector(".limit-save").disabled, error: error.hidden ? null : text(error), note: text(bar.querySelector(".limit-stage-note"))}; + }; + const yOf = (value) => { + const svg = chart(); + const box = svg.getBoundingClientRect(); + const height = svg.viewBox.baseVal.height; + return box.top + Limits.pixelOf(value, FRAME, height - FRAME) * box.height / height; + }; + const drag = async (level, value) => { + const node = line(level); + const box = node.ownerSVGElement.getBoundingClientRect(); + const at = (y, buttons) => ({clientX: box.left + box.width / 2, clientY: y, pointerId: 7, pointerType: "touch", isPrimary: true, button: 0, buttons, bubbles: true, cancelable: true}); + node.dispatchEvent(new PointerEvent("pointerdown", at(yOf(Number(node.dataset.value)), 1))); + node.dispatchEvent(new PointerEvent("pointermove", at(yOf(value), 1))); + const during = {label: text(node.querySelector("text")), moved: node.classList.contains("moved"), same: line(level) === node}; + node.dispatchEvent(new PointerEvent("pointerup", at(yOf(value), 0))); + await until(() => line(level) && line(level) !== node, 4000); + return during; + }; + const press = async (level, key, times) => { + for (let round = 0; round < times; round += 1) { + const node = line(level); + node.focus(); + node.dispatchEvent(new KeyboardEvent("keydown", {key, bubbles: true, cancelable: true})); + await until(() => line(level) !== node, 2000); + } + }; const toasts = () => all("#toasts .toast").map(text); const stored = async () => (await (await fetch("/api/limits", {cache: "no-store"})).json()).limits; const posts = []; + const asked = []; const send = window.fetch.bind(window); window.fetch = (path, init) => { if (String(path).startsWith("/api/limits") && init && init.method === "POST") { @@ -45,83 +85,220 @@ READ = """ } return send(path, init); }; + const credentials = navigator.credentials.get.bind(navigator.credentials); + navigator.credentials.get = (options) => { + asked.push(1); + return credentials(options); + }; const ready = () => until(() => lines().length === 4, 15000); const page = () => ({wide: document.documentElement.scrollWidth > innerWidth + 1, plot: Math.round(document.querySelector("#main .res-hardware .res-plot").getBoundingClientRect().height)}); + const menu = (selector) => { + const details = document.querySelector(selector); + if (!details.open) { + details.querySelector("summary").click(); + } + return details; + }; + const tick = async (selector, on) => { + const box = document.querySelector(selector); + if (box.checked !== on) { + box.click(); + } + await sleep(150); + return box.checked; + }; """ LINES = """(async () => {@HELPERS@@READ@ if (!(await ready())) { return {error: text(document.getElementById("main"))}; } - const cpu = {lines: lines(), target: target(), profile: pressed("Profile"), metric: pressed("Limit lines")}; + const cpu = {lines: lines(), target: target(), metric: pressed("Limit lines")}; button("Limit lines", "RAM").click(); - await until(() => lines().every(([metric]) => metric === "ram"), 4000); - const ram = {lines: lines(), target: target(), metric: pressed("Limit lines")}; + await until(() => lines().every(({metric}) => metric === "ram"), 4000); + const ram = {lines: lines(), target: target()}; button("Limit lines", "PSI").click(); - await until(() => lines().every(([metric]) => metric === "psi"), 4000); + await until(() => lines().every(({metric}) => metric === "psi"), 4000); const psi = {lines: lines(), target: target()}; button("Limit lines", "CPU").click(); - await until(() => lines().every(([metric]) => metric === "cpu"), 4000); - return {cpu, ram, psi, page: page(), violations: window.e2eViolations || null}; + await until(() => lines().every(({metric}) => metric === "cpu"), 4000); + await press("upper", "ArrowDown", 5); + const staged = {line: lines().find(({level}) => level === "upper"), stage: stage(), focused: document.activeElement === line("upper")}; + const unknown = all("#main rect.res-mark.unknown").map((rect) => text(rect.querySelector("title"))); + return {cpu, ram, psi, staged, unknown, page: page(), violations: window.e2eViolations || null}; })()""" -DIAL = """(async () => {@HELPERS@@READ@ +COORDS = """(async () => {@HELPERS@@READ@ if (!(await ready())) { return {error: text(document.getElementById("main"))}; } - navigator.credentials.get = () => Promise.reject(new DOMException("No passkey for a tighter value.", "NotAllowedError")); - line("upper").dispatchEvent(new MouseEvent("click", {bubbles: true})); - const opened = await until(() => sheet() === "CPU upper" && dialRoot(), 4000); - const before = dialRoot().getAttribute("aria-valuenow"); - ["ArrowDown", "ArrowDown", "ArrowDown", "ArrowDown", "ArrowDown"].forEach(key); - const turned = dialRoot().getAttribute("aria-valuenow"); - document.querySelector("#sheet .limit-save").click(); - const closed = Boolean(await until(() => sheet() === null, 6000)); - await until(() => lines().some(([, level, value]) => level === "upper" && value === 85), 4000); - const tighter = {opened: Boolean(opened), before, turned, closed, posts: [...posts], stored: (await stored()).cpu, lines: lines()}; - posts.length = 0; - line("lower").dispatchEvent(new MouseEvent("click", {bubbles: true})); - await until(() => sheet() === "CPU lower" && dialRoot(), 4000); - key("End"); - document.querySelector("#sheet .limit-save").click(); - const error = await until(() => { - const node = document.querySelector("#sheet .limit-error:not([hidden])"); - return node ? text(node) : null; - }, 4000); - const broken = {error, open: sheet(), posts: [...posts], stored: (await stored()).cpu}; - document.querySelector("#sheet .limit-cancel").click(); - return {tighter, broken, closed: sheet() === null}; + const svg = chart(); + const box = svg.getBoundingClientRect(); + const height = svg.viewBox.baseVal.height; + const band = (value) => { + const found = []; + for (let y = Math.floor(box.top); y <= Math.ceil(box.bottom); y += 1) { + if (Limits.valueAt((y - box.top) * height / box.height, FRAME, height - FRAME) === value) { + found.push(y); + } + } + return found.length ? found[Math.floor(found.length / 2)] : Math.round(yOf(value)); + }; + return {x: Math.round(box.left + box.width / 2), from: band(90), to: band(85)}; +})()""" +MOUSE = """(async () => {@HELPERS@@READ@ + if (!(await ready())) { + return {error: text(document.getElementById("main"))}; + } + const dragged = {line: lines().find(({level}) => level === "upper"), others: lines().filter(({level}) => level !== "upper").map(({moved}) => moved), stage: stage()}; + document.querySelector("#main .res-limits .limit-save").click(); + const saved = Boolean(await until(() => posts.length === 2 && !stage().shown, 8000)); + return {dragged, saved, posts: [...posts], asked: asked.length, stored: (await stored()).cpu, after: lines().find(({level}) => level === "upper")}; +})()""" +STAGE = """(async () => {@HELPERS@@READ@ + if (!(await ready())) { + return {error: text(document.getElementById("main"))}; + } + const during = await drag("upper", 85); + const moved = {during, line: lines().find(({level}) => level === "upper"), stage: stage()}; + document.querySelector("#main .res-limits .limit-discard").click(); + await until(() => !stage().shown, 4000); + const discarded = {line: lines().find(({level}) => level === "upper"), stage: stage()}; + await drag("upper", 96); + const broken = {line: lines().find(({level}) => level === "upper"), stage: stage()}; + document.querySelector("#main .res-limits .limit-save").click(); + await sleep(500); + broken.posts = [...posts]; + await press("upper", "Escape", 1); + const escaped = {line: lines().find(({level}) => level === "upper"), stage: stage()}; + await press("upper", "ArrowDown", 5); + const keyed = {line: lines().find(({level}) => level === "upper"), stage: stage(), focused: document.activeElement === line("upper")}; + document.querySelector("#main .res-limits .limit-save").click(); + const saved = Boolean(await until(() => posts.length === 2 && !stage().shown, 8000)); + return {moved, discarded, broken, escaped, keyed, saved, posts: [...posts], asked: asked.length, stored: (await stored()).cpu, after: lines().find(({level}) => level === "upper")}; +})()""" +LOOSER = """(async () => {@HELPERS@@READ@ + if (!(await ready())) { + return {error: text(document.getElementById("main"))}; + } + await press("upper", "ArrowUp", 2); + button("Limit lines", "RAM").click(); + await until(() => lines().every(({metric}) => metric === "ram"), 4000); + await press("upper", "ArrowDown", 5); + const staged = stage(); + document.querySelector("#main .res-limits .limit-save").click(); + const saved = Boolean(await until(() => posts.length === 2 && !stage().shown, 15000)); + await sleep(300); + return {staged, saved, posts: [...posts], asked: asked.length, stored: await stored(), toasts: toasts()}; })()""" CANCEL = """(async () => {@HELPERS@@READ@ if (!(await ready())) { return {error: text(document.getElementById("main"))}; } - navigator.credentials.get = () => Promise.reject(new DOMException("The operator canceled.", "NotAllowedError")); - button("Profile", "Max").click(); + navigator.credentials.get = () => { + asked.push(1); + return Promise.reject(new DOMException("The operator canceled.", "NotAllowedError")); + }; + await press("upper", "ArrowUp", 2); + document.querySelector("#main .res-limits .limit-save").click(); const toast = await until(() => toasts().find((words) => words.includes("not signed")), 6000); await sleep(500); - return {toast, posts: [...posts], stored: await stored(), profile: pressed("Profile"), lines: lines()}; + return {toast, posts: [...posts], asked: asked.length, stored: await stored(), line: lines().find(({level}) => level === "upper"), stage: stage()}; })()""" -SIGN = """(async () => {@HELPERS@@READ@ +PROFILE = """(async () => {@HELPERS@@READ@ if (!(await ready())) { return {error: text(document.getElementById("main"))}; } + menu("#main .res-limits-menu"); button("Profile", "Max").click(); - const moved = await until(() => pressed("Profile").join() === "Max" && lines().some(([, level, value]) => level === "upper" && value === 95), 15000); - return {moved: Boolean(moved), posts: [...posts], stored: await stored(), profile: pressed("Profile"), lines: lines()}; + const moved = await until(() => pressed("Profile").join() === "Max" && lines().some(({level, value}) => level === "upper" && value === 95), 15000); + return {moved: Boolean(moved), posts: [...posts], asked: asked.length, stored: await stored(), profile: pressed("Profile"), lines: lines()}; })()""" -SHEET = """(async () => {@HELPERS@@READ@ +MENUS = """(async () => {@HELPERS@@READ@ + if (!(await until(() => lines().length >= 3, 15000))) { + return {error: text(document.getElementById("main"))}; + } + const limits = menu("#main .res-limits-menu"); + await tick('#main .res-limits-menu input[data-level="mayday"]', true); + await until(() => lines().length === 4, 4000); + const entries = all("label.limit-level", limits).map((label) => [text(label), label.getAttribute("title"), label.querySelector("input").checked]); + const off = {upper: await tick('#main .res-limits-menu input[data-level="upper"]', false), target: await tick('#main .res-limits-menu input[data-level="target"]', false)}; + const hidden = {levels: lines().map(({level}) => level), target: target().length, open: limits.open}; + await tick('#main .res-limits-menu input[data-level="upper"]', true); + await tick('#main .res-limits-menu input[data-level="target"]', true); + const back = {levels: lines().map(({level}) => level), target: target().length}; + await tick('#main .res-limits-menu input[data-level="mayday"]', false); + document.getElementById("limits-open").click(); + const opened = Boolean(await until(() => sheet() === "Limits", 4000)); + const closedMenu = !limits.open; + const heads = all('#sheet table[aria-label="Limits"] thead th').map((node) => [text(node), node.getAttribute("title")]); + const cells = all('#sheet table[aria-label="Limits"] tbody tr').map((row) => [row.dataset.metric, ...all("input.limit-cell", row).map((input) => Number(input.value))]); + const dials = all("#sheet .limit-dial, #sheet [role=slider]").length; + const cell = document.querySelector('#sheet input.limit-cell[data-metric="disk"][data-level="stop"]'); + cell.value = "94"; + cell.dispatchEvent(new Event("input", {bubbles: true})); + await sleep(200); + const sheetStage = stage(document.querySelector("#sheet")); + const chartStage = stage(); + const cellMoved = cell.classList.contains("moved"); + document.querySelector("#sheet .limit-discard").click(); + await sleep(200); + const discarded = {value: cell.value, stage: stage(document.querySelector("#sheet")), moved: cell.classList.contains("moved")}; + document.querySelector('#sheet [aria-label="Close"]').click(); + await until(() => sheet() === null, 4000); + const right = new MouseEvent("contextmenu", {bubbles: true, cancelable: true, button: 2, clientX: chart().getBoundingClientRect().left + 40, clientY: chart().getBoundingClientRect().top + 20}); + chart().dispatchEvent(right); + const context = {prevented: right.defaultPrevented, opened: Boolean(await until(() => sheet() === "Limits", 4000))}; + document.querySelector('#sheet [aria-label="Close"]').click(); + await until(() => sheet() === null, 4000); + return {entries, off, hidden, back, opened, closedMenu, heads, cells, dials, sheetStage, chartStage, cellMoved, discarded, context, levels: lines().map(({level}) => level), posts: [...posts], wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" +KEPT = """(async () => {@HELPERS@@READ@ + if (!(await until(() => chart() && document.querySelector("#main .res-limits-menu"), 15000))) { + return {error: text(document.getElementById("main"))}; + } + await until(() => lines().length === 3, 6000); + const levels = lines().map(({level}) => level); + const box = document.querySelector('#main .res-limits-menu input[data-level="mayday"]').checked; + await tick('#main .res-limits-menu input[data-level="mayday"]', true); + await until(() => lines().length === 4, 4000); + return {levels, box, after: lines().map(({level}) => level)}; +})()""" +VIEW = """(async () => {@HELPERS@@READ@ if (!(await ready())) { return {error: text(document.getElementById("main"))}; } - document.getElementById("limits-open").click(); - await until(() => sheet() === "Limits", 4000); - const table = all('#sheet table[aria-label="Limits"] tbody tr').map((row) => [row.dataset.metric, ...all("button.limit-cell", row).map(text)]); - const head = all('#sheet table[aria-label="Limits"] thead th').map(text); - document.querySelector('#sheet button.limit-cell[data-metric="disk"][data-level="stop"]').click(); - const dialed = await until(() => sheet() === "Disk STOP" && dialRoot(), 4000); - const value = dialed ? dialRoot().getAttribute("aria-valuenow") : null; - document.querySelector("#sheet .limit-cancel").click(); - const back = await until(() => sheet() === "Limits", 4000); - return {table, head, dialed: Boolean(dialed), value, back: Boolean(back), wide: document.documentElement.scrollWidth > innerWidth + 1}; + const count = () => ({ + legend: !document.querySelector("#main .res-hardware .res-legend").hidden, chips: all("#main .res-hardware .legend-chip").length, wait: all("#main svg.res-chart[data-chart=hardware] rect.res-mark.wait").length, + queue: all("#main svg.res-chart[data-chart=hardware] rect.res-mark.blocked, #main svg.res-chart[data-chart=hardware] rect.res-mark.hung").length, + limits: lines().length, target: target().length, unknown: all("#main svg.res-chart[data-chart=hardware] rect.res-mark.unknown").length, + }); + const before = count(); + const view = menu("#main .res-view-menu"); + const entries = all("label.res-pick", view).map((label) => [text(label), label.getAttribute("title")]); + const chip = document.querySelector('#main .res-hardware .legend-chip[data-chip="host:CPU"]'); + chip.click(); + await sleep(400); + const chipped = all('#main svg.res-chart[data-chart=hardware] path.res-line[data-series="CPU"]').length; + document.querySelector('#main .res-hardware .legend-chip[data-chip="host:CPU"]').click(); + await sleep(400); + for (const key of ["legend", "queue", "waits", "limits"]) { + await tick(`#main .res-view-menu input[data-show="${key}"]`, false); + } + await sleep(300); + return {before, entries, chipped, after: count(), open: view.open}; +})()""" +VIEW_KEPT = """(async () => {@HELPERS@@READ@ + if (!(await until(() => chart() && document.querySelector("#main .res-view-menu"), 15000))) { + return {error: text(document.getElementById("main"))}; + } + await sleep(1500); + const count = () => ({legend: !document.querySelector("#main .res-hardware .res-legend").hidden, wait: all("#main rect.res-mark.wait").length, queue: all("#main rect.res-mark.blocked, #main rect.res-mark.hung").length, limits: lines().length}); + const kept = {view: count(), boxes: all("#main .res-view-menu input[data-show]").map((box) => [box.dataset.show, box.checked])}; + menu("#main .res-view-menu"); + for (const key of ["legend", "queue", "waits", "limits"]) { + await tick(`#main .res-view-menu input[data-show="${key}"]`, true); + } + await until(() => lines().length === 4, 4000); + return {kept, back: count()}; })()""" @@ -133,7 +310,17 @@ def probe(source: str) -> str: class TestResourceLimits(HubCase): drive = base.OrchestratorE2ECase.drive authenticator = base.OrchestratorE2ECase.authenticator - sample = w4.TestWorkbenchResources.sample + + def sample(self, index: int) -> dict: + row = w4.TestWorkbenchResources.sample(self, index) + gpu = row["gpus"][0] + if gpu.get("asleep") is not True and gpu["util"] is None: + gpu["error"] = MISMATCH + if BLOCKED[0] <= index < BLOCKED[1]: + row["queue"]["head"] = {"id": "quality-high-1002", "kind": "quality-high", "waited_s": 900, "reason": "RAM 56 % used + 37 % still to come reach the limit 85 %"} + if HUNG[0] <= index < HUNG[1]: + row["queue"]["hung"] = ["test-1001"] + return row def setUp(self): super().setUp() @@ -153,65 +340,148 @@ class TestResourceLimits(HubCase): def step(self, width: int, height: int, name: str, source: str) -> dict: return {"width": width, "height": height, "url": f"{self.page_url}?{width}-{name}#resources", "wait": 1200, "probe": probe(source), "shot": str(OUT / f"chromium-{width}-{name}.png")} - def test_every_width_draws_four_labelled_lines_and_the_target_per_metric(self): + def test_every_width_draws_four_draggable_lines_and_the_target_and_a_staged_line_turns_dashed(self): data = self.drive([self.step(width, height, "lines", LINES) for width, height in base.WIDTHS], None, init=w4.GUARD) balanced = PROFILES["balanced"] for (width, _), found in zip(base.WIDTHS, data["results"], strict=True): with self.subTest(width=width): self.assertNotIn("error", found, found) - cpu = found["cpu"] - self.assertEqual([entry[:3] for entry in cpu["lines"]], [["cpu", level, balanced["cpu"][level]] for level in LEVELS]) - self.assertEqual([entry[3] for entry in cpu["lines"]], [f"{name} {balanced['cpu'][level]}" for name, level in zip(("lower", "upper", "STOP", "MAYDAY"), LEVELS, strict=True)]) - self.assertTrue(all(entry[4].startswith(f"CPU {entry[3]} %") for entry in cpu["lines"]), cpu["lines"]) - self.assertEqual(cpu["target"], [["cpu", 84, "target 84"]]) - self.assertEqual((cpu["profile"], cpu["metric"]), (["Balanced"], ["CPU"])) - self.assertEqual([entry[2] for entry in found["ram"]["lines"]], [balanced["ram"][level] for level in LEVELS]) - self.assertEqual(found["ram"]["target"], [["ram", 80.5, "target 81"]]) - self.assertEqual(found["ram"]["metric"], ["RAM"]) - self.assertEqual(([entry[2] for entry in found["psi"]["lines"]], found["psi"]["target"]), ([balanced["psi"][level] for level in LEVELS], [])) + cpu = found["cpu"]["lines"] + self.assertEqual([(entry["metric"], entry["level"], entry["value"]) for entry in cpu], [("cpu", level, balanced["cpu"][level]) for level in LEVELS]) + self.assertEqual([entry["label"] for entry in cpu], [f"{name} {balanced['cpu'][level]}" for name, level in zip(NAMES, LEVELS, strict=True)]) + self.assertEqual({(entry["role"], entry["moved"], entry["was"], entry["dash"]) for entry in cpu}, {("slider", False, False, "none")}) + self.assertTrue(all(entry["title"].startswith(f"CPU {entry['label']} %: {name}: ") for entry, name in zip(cpu, NAMES, strict=True)), cpu) + self.assertIn(UPPER, cpu[1]["title"]) + self.assertEqual([entry[:3] for entry in found["cpu"]["target"]], [["cpu", 84, "target 84"]]) + self.assertIn("target: the live AIMD target", found["cpu"]["target"][0][3]) + self.assertEqual(found["cpu"]["metric"], ["CPU"]) + self.assertEqual([entry["value"] for entry in found["ram"]["lines"]], [balanced["ram"][level] for level in LEVELS]) + self.assertEqual([entry[:3] for entry in found["ram"]["target"]], [["ram", 80.5, "target 81"]]) + self.assertEqual(([entry["value"] for entry in found["psi"]["lines"]], found["psi"]["target"]), ([balanced["psi"][level] for level in LEVELS], [])) + staged = found["staged"] + self.assertEqual((staged["line"]["value"], staged["line"]["moved"], staged["line"]["was"], staged["line"]["label"], staged["line"]["now"]), (85, True, True, "upper 85 (was 90)", "85")) + self.assertNotEqual(staged["line"]["dash"], "none") + self.assertTrue(staged["focused"]) + self.assertEqual((staged["stage"]["shown"], staged["stage"]["save"], staged["stage"]["disabled"], staged["stage"]["note"]), (True, "Save 1 change", False, "CPU upper 90 → 85 %")) + self.assertTrue(found["unknown"]) + self.assertTrue(all(words == f"{w4.GPU} unknown: {MISMATCH}" for words in found["unknown"]), found["unknown"]) self.assertFalse(found["page"]["wide"]) self.assertGreater(found["page"]["plot"], 40) self.assertEqual(w4.quiet(found["violations"]), []) + self.assertEqual(self.stored(), balanced) - def test_a_tighter_dial_value_saves_without_the_passkey_and_a_broken_order_does_not_save(self): - found = self.drive([self.step(1366, 768, "dial", DIAL)], None, init=w4.GUARD)["results"][0] + def test_a_mouse_drag_of_cpu_upper_from_90_to_85_stages_a_dashed_line_that_saves_without_the_passkey(self): + coords = self.drive([self.step(1366, 768, "coords", COORDS)], None, init=w4.GUARD)["results"][0] + self.assertNotIn("error", coords, coords) + step = {**self.step(1366, 768, "mouse", MOUSE), "wait": 3000, "drag": [[coords["x"], coords["from"]], [coords["x"], coords["to"]]]} + found = self.drive([step], None, init=w4.GUARD)["results"][0] self.assertNotIn("error", found, found) - tighter = found["tighter"] - self.assertEqual((tighter["opened"], tighter["before"], tighter["turned"], tighter["closed"]), (True, "90", "85", True)) - self.assertEqual(tighter["posts"], [["/api/limits/sign", "sign"], ["/api/limits", "unsigned"]]) - self.assertEqual(tighter["stored"], {**PROFILES["balanced"]["cpu"], "upper": 85}) - broken = found["broken"] - self.assertIn("breaks lower < upper < STOP < MAYDAY", broken["error"]) - self.assertEqual((broken["open"], broken["posts"], broken["stored"]), ("CPU lower", [], {**PROFILES["balanced"]["cpu"], "upper": 85})) - self.assertTrue(found["closed"]) + dragged = found["dragged"] + self.assertEqual((dragged["line"]["value"], dragged["line"]["moved"], dragged["line"]["label"]), (85, True, "upper 85 (was 90)"), dragged) + self.assertNotEqual(dragged["line"]["dash"], "none") + self.assertEqual(dragged["others"], [False, False, False]) + self.assertEqual((dragged["stage"]["save"], dragged["stage"]["disabled"]), ("Save 1 change", False)) + self.assertTrue(found["saved"], found) + self.assertEqual((found["posts"], found["asked"]), ([["/api/limits/sign", "sign"], ["/api/limits", "unsigned"]], 0)) + self.assertEqual(found["stored"], {**PROFILES["balanced"]["cpu"], "upper": 85}) + self.assertEqual((found["after"]["value"], found["after"]["moved"]), (85, False)) self.assertEqual(self.stored()["cpu"]["upper"], 85) - def test_a_canceled_passkey_keeps_the_old_limits_and_a_signed_one_switches_the_profile(self): + def test_touch_drag_stages_discard_restores_an_order_break_blocks_save_and_keys_stage_a_tighter_value(self): + found = self.drive([self.step(1366, 768, "stage", STAGE)], None, init=w4.GUARD)["results"][0] + self.assertNotIn("error", found, found) + moved = found["moved"] + self.assertEqual(moved["during"], {"label": "upper 85 (was 90)", "moved": True, "same": True}) + self.assertEqual((moved["line"]["value"], moved["line"]["moved"]), (85, True)) + self.assertEqual((moved["stage"]["save"], moved["stage"]["disabled"], moved["stage"]["note"]), ("Save 1 change", False, "CPU upper 90 → 85 %")) + discarded = found["discarded"] + self.assertEqual((discarded["line"]["value"], discarded["line"]["moved"], discarded["line"]["dash"], discarded["stage"]["shown"]), (90, False, "none", False)) + broken = found["broken"] + self.assertEqual((broken["line"]["value"], broken["stage"]["disabled"], broken["posts"]), (96, True, [])) + self.assertEqual(broken["stage"]["error"], f"CPU upper 96 % {ORDER}: it must stay below STOP 95 %") + self.assertEqual((found["escaped"]["line"]["value"], found["escaped"]["stage"]["shown"]), (90, False)) + keyed = found["keyed"] + self.assertEqual((keyed["line"]["value"], keyed["line"]["moved"], keyed["stage"]["save"], keyed["focused"]), (85, True, "Save 1 change", True)) + self.assertTrue(found["saved"], found) + self.assertEqual((found["posts"], found["asked"]), ([["/api/limits/sign", "sign"], ["/api/limits", "unsigned"]], 0)) + self.assertEqual(found["stored"], {**PROFILES["balanced"]["cpu"], "upper": 85}) + self.assertEqual(self.stored(), {**PROFILES["balanced"], "cpu": {**PROFILES["balanced"]["cpu"], "upper": 85}}) + + def test_a_looser_batch_asks_one_passkey_signature_for_every_staged_value_and_a_cancel_keeps_them_staged(self): self.pin() canceled = self.drive([self.step(1366, 768, "cancel", CANCEL)], None, init=w4.GUARD)["results"][0] self.assertNotIn("error", canceled, canceled) - self.assertTrue(canceled["toast"].startswith("Profile Max"), canceled["toast"]) - self.assertEqual((canceled["posts"], canceled["stored"], canceled["profile"]), ([["/api/limits/sign", "sign"]], PROFILES["balanced"], ["Balanced"])) + self.assertIn("not signed", canceled["toast"]) + self.assertEqual((canceled["posts"], canceled["asked"], canceled["stored"]), ([["/api/limits/sign", "sign"]], 1, PROFILES["balanced"])) + self.assertEqual((canceled["line"]["value"], canceled["line"]["moved"], canceled["stage"]["shown"]), (92, True, True)) self.assertEqual(self.stored(), PROFILES["balanced"]) - steps = [self.step(width, height, "max", SIGN) for width, height in base.WIDTHS[:1]] - signed = self.drive(steps, self.authenticator(), init=w4.GUARD)["results"][0] - self.assertNotIn("error", signed, signed) - self.assertTrue(signed["moved"], signed) - self.assertEqual((signed["posts"], signed["profile"]), ([["/api/limits/sign", "sign"], ["/api/limits", "signed"]], ["Max"])) - self.assertEqual(signed["stored"], PROFILES["max"]) - self.assertEqual([entry[2] for entry in signed["lines"]], [PROFILES["max"]["cpu"][level] for level in LEVELS]) + found = self.drive([self.step(1366, 768, "looser", LOOSER)], self.authenticator(), init=w4.GUARD)["results"][0] + self.assertNotIn("error", found, found) + self.assertEqual((found["staged"]["save"], found["staged"]["disabled"]), ("Save 2 changes", False)) + self.assertEqual(found["staged"]["note"], "CPU upper 90 → 92 %, RAM upper 90 → 85 % · passkey") + self.assertTrue(found["saved"], found) + self.assertEqual((found["posts"], found["asked"]), ([["/api/limits/sign", "sign"], ["/api/limits", "signed"]], 1)) + balanced = PROFILES["balanced"] + expected = {**balanced, "cpu": {**balanced["cpu"], "upper": 92}, "ram": {**balanced["ram"], "upper": 85}} + self.assertEqual((found["stored"], self.stored()), (expected, expected)) + + def test_a_signed_profile_from_the_limits_menu_moves_every_line(self): + found = self.drive([self.step(1920, 1080, "max", PROFILE)], self.authenticator(), init=w4.GUARD)["results"][0] + self.assertNotIn("error", found, found) + self.assertTrue(found["moved"], found) + self.assertEqual((found["posts"], found["asked"], found["profile"]), ([["/api/limits/sign", "sign"], ["/api/limits", "signed"]], 1, ["Max"])) + self.assertEqual([entry["value"] for entry in found["lines"]], [PROFILES["max"]["cpu"][level] for level in LEVELS]) self.assertEqual(self.stored(), PROFILES["max"]) - def test_the_limits_sheet_lists_every_value_each_with_its_dial_at_every_width(self): - data = self.drive([self.step(width, height, "sheet", SHEET) for width, height in base.WIDTHS], None, init=w4.GUARD) + def test_the_limits_menu_hides_levels_and_opens_the_matrix_and_a_right_click_opens_it_too(self): + steps = [self.step(width, height, "menus", MENUS) for width, height in base.WIDTHS] + steps.append({**self.step(1366, 768, "kept", KEPT), "shot": None}) + data = self.drive(steps, None, init=w4.GUARD)["results"] balanced = PROFILES["balanced"] - for (width, _), found in zip(base.WIDTHS, data["results"], strict=True): + for (width, _), found in zip(base.WIDTHS, data, strict=True): with self.subTest(width=width): self.assertNotIn("error", found, found) - self.assertEqual(found["head"], ["Metric", "lower", "upper", "STOP", "MAYDAY"]) - self.assertEqual(found["table"], [[metric, *(f"{balanced[metric][level]} %" for level in LEVELS)] for metric in balanced]) - self.assertEqual((found["dialed"], found["value"], found["back"]), (True, str(balanced["disk"]["stop"]), True)) + self.assertEqual([entry[0] for entry in found["entries"]], ["lower", "upper", "STOP", "MAYDAY", "target"]) + self.assertTrue(all(title.startswith(f"{name}: ") for name, title, _ in found["entries"]), found["entries"]) + self.assertEqual(found["entries"][1][1], f"{UPPER}; for RAM, swap, PSI and disk the watch warns above it, and a load above it drops the live target") + self.assertEqual(found["off"], {"upper": False, "target": False}) + self.assertEqual(found["hidden"], {"levels": ["lower", "stop", "mayday"], "target": 0, "open": True}) + self.assertEqual(found["back"], {"levels": list(LEVELS), "target": 1}) + self.assertTrue(found["opened"]) + self.assertTrue(found["closedMenu"]) + self.assertEqual([head for head, _ in found["heads"]], ["Metric", *NAMES]) + self.assertTrue(all(title.startswith(f"{name}: ") for (name, title) in found["heads"][1:]), found["heads"]) + self.assertEqual(found["cells"], [[metric, *(balanced[metric][level] for level in LEVELS)] for metric in balanced]) + self.assertEqual(found["dials"], 0) + self.assertEqual((found["sheetStage"]["save"], found["sheetStage"]["note"], found["cellMoved"]), ("Save 1 change", "Disk STOP 95 → 94 %", True)) + self.assertEqual(found["chartStage"]["save"], "Save 1 change") + self.assertEqual((found["discarded"]["value"], found["discarded"]["stage"]["shown"], found["discarded"]["moved"]), ("95", False, False)) + self.assertEqual(found["context"], {"prevented": True, "opened": True}) + self.assertEqual(found["levels"], ["lower", "upper", "stop"]) + self.assertEqual(found["posts"], []) self.assertFalse(found["wide"]) + kept = data[-1] + self.assertNotIn("error", kept, kept) + self.assertEqual((kept["levels"], kept["box"], kept["after"]), (["lower", "upper", "stop"], False, list(LEVELS))) + self.assertEqual(self.stored(), balanced) + + def test_the_view_menu_hides_legend_markers_bands_and_lines_and_the_choice_survives_a_reload(self): + steps = [self.step(1366, 768, "view", VIEW), {**self.step(1366, 768, "view-kept", VIEW_KEPT), "wait": 1500}] + first, second = self.drive(steps, None, init=w4.GUARD)["results"] + self.assertNotIn("error", first, first) + before = first["before"] + self.assertTrue(before["legend"] and before["chips"] and before["wait"] and before["queue"] and before["unknown"], before) + self.assertEqual((before["limits"], before["target"]), (4, 1)) + self.assertEqual([label for label, _ in first["entries"]], ["Legend", "Queue markers", "Wait bands", "Limit lines"]) + self.assertTrue(all(title.startswith(f"{label}: ") for label, title in first["entries"]), first["entries"]) + self.assertEqual(first["chipped"], 0) + self.assertEqual(first["after"], {"legend": False, "chips": before["chips"], "wait": 0, "queue": 0, "limits": 0, "target": 0, "unknown": before["unknown"]}) + self.assertTrue(first["open"]) + self.assertNotIn("error", second, second) + self.assertEqual(second["kept"]["view"], {"legend": False, "wait": 0, "queue": 0, "limits": 0}) + self.assertEqual(second["kept"]["boxes"], [["legend", False], ["queue", False], ["waits", False], ["limits", False]]) + self.assertTrue(second["back"]["legend"] and second["back"]["wait"] and second["back"]["queue"], second["back"]) + self.assertEqual(second["back"]["limits"], 4) if __name__ == "__main__": diff --git a/tests/e2e/test_stale_prune_e2e.py b/tests/e2e/test_stale_prune_e2e.py index e89a369..be804a9 100644 --- a/tests/e2e/test_stale_prune_e2e.py +++ b/tests/e2e/test_stale_prune_e2e.py @@ -1,4 +1,4 @@ -"""Exercise requirement 075: the prune dialog lists the stale tasks for N days, sets the deadline on the shared dial, signs once and the board counts down.""" +"""Exercise requirements 075 and 088: the prune dialog lists the stale tasks for N days grouped by prefix with a filter, a stepper and a sticky footer, sets the deadline on the shared dial, signs 258 tasks once and the board counts down.""" from __future__ import annotations @@ -23,6 +23,7 @@ OPEN = """(async () => {@HELPERS@ if (!open) { return {error: text(document.getElementById("main")).slice(0, 300)}; } + await openTaskMenu("task-actions"); open.click(); const list = () => all(".sheet-box .prune-list li[data-task]").map((node) => node.dataset.task); await until(() => list().length, 4000); @@ -52,6 +53,7 @@ OPEN = """(async () => {@HELPERS@ })()""" SIGN = """(async () => {@HELPERS@ await screenShown(8000); + await openTaskMenu("task-actions"); (await until(() => document.getElementById("kanban-prune-open"), 8000)).click(); if (!(await until(() => document.getElementById("prune-sign"), 4000))) { return {error: text(document.getElementById("main")).slice(0, 300)}; @@ -78,7 +80,7 @@ SIGN = """(async () => {@HELPERS@ const before = left(); await sleep(2300); return {signs, started, before, after: left(), chip: {label: name(document.getElementById("kanban-prune")), title: document.getElementById("kanban-prune").title, role: document.getElementById("kanban-prune").getAttribute("role")}, - countdown: {now: waiting.getAttribute("aria-valuenow"), text: waiting.getAttribute("aria-valuetext"), unit: text(waiting.querySelector(".dial-readout")), listed: all(".sheet-box .prune-list li[data-task]").map((node) => node.dataset.task)}, + countdown: {now: waiting.getAttribute("aria-valuenow"), text: waiting.getAttribute("aria-valuetext"), readout: text(waiting.querySelector(".dial-face .dial-readout")), listed: all(".sheet-box .prune-list li[data-task]").map((node) => node.dataset.task)}, wide: document.documentElement.scrollWidth > innerWidth + 1}; })()""" WAIT = """(async () => {@HELPERS@ @@ -87,11 +89,100 @@ WAIT = """(async () => {@HELPERS@ if (!chip) { return {error: text(document.getElementById("main")).slice(0, 300)}; } + await openTaskMenu("task-actions"); document.getElementById("kanban-prune-open").click(); const waiting = await until(() => document.querySelector('.sheet-box .prune-dial[aria-readonly="true"]'), 4000); const box = chip.getBoundingClientRect(); return {chip: box.width > 0 && box.right <= innerWidth + 1, waiting: Boolean(waiting), wide: document.documentElement.scrollWidth > innerWidth + 1}; })()""" +GROUPS = """(async () => {@HELPERS@ + await screenShown(8000); + await openTaskMenu("task-actions"); + (await until(() => document.getElementById("kanban-prune-open"), 8000)).click(); + const rows = () => all(".sheet-box .prune-list li[data-task]"); + if (!(await until(() => rows().length >= @COUNT@, 8000))) { + return {error: text(document.querySelector(".sheet-box") || document.getElementById("main")).slice(0, 300)}; + } + const count = () => text(document.querySelector("#prune-sign .count")); + const group = (prefix) => document.querySelector(`.sheet-box .prune-group[data-group="${prefix}"]`); + const check = (prefix) => group(prefix).querySelector(".prune-group-check"); + const tri = (prefix) => ({checked: check(prefix).checked, mixed: check(prefix).indeterminate, count: count()}); + const row = (task) => document.querySelector(`.sheet-box li[data-task="${task}"]`); + const groups = all(".sheet-box .prune-group").map((node) => [node.dataset.group, text(node.querySelector(".prune-group-head .count")), all("li[data-task]", node).length]); + const days = document.getElementById("prune-days"); + const stepper = {type: days.type, mic: days.dataset.mic || null, framed: Boolean(days.closest(".mic-frame")), mics: all('button.mic[aria-controls="prune-days"]').length, buttons: all(".sheet-box .prune-stepper button").map(name)}; + const shown = row("work/t002"); + const look = {avatar: Boolean(shown.querySelector(".prune-owner .avatar")), owner: shown.querySelector(".prune-owner").title, age: text(shown.querySelector(".prune-age"))}; + const full = tri("work"); + shown.querySelector("input[type=checkbox]").click(); + await sleep(100); + const partial = tri("work"); + shown.querySelector("input[type=checkbox]").click(); + await sleep(100); + const back = tri("work"); + check("ci").click(); + await sleep(100); + const off = {...tri("ci"), ticked: all("li[data-task] input:checked", group("ci")).length}; + check("ci").click(); + await sleep(100); + const toggle = group("fix").querySelector(".prune-group-toggle"); + toggle.click(); + await sleep(100); + const folded = {expanded: toggle.getAttribute("aria-expanded"), hidden: group("fix").querySelector(".prune-list").hidden, count: count()}; + toggle.click(); + await sleep(100); + const filter = document.getElementById("prune-filter"); + const typed = async (value) => { + filter.value = value; + filter.dispatchEvent(new Event("input", {bubbles: true})); + await sleep(150); + return {shown: rows().filter((node) => !node.hidden).length, groups: all(".sheet-box .prune-group").filter((node) => !node.hidden).map((node) => node.dataset.group), count: count(), none: !document.querySelector(".sheet-box .prune-none").hidden}; + }; + const narrowed = await typed("t01"); + const nothing = await typed("zzz"); + const cleared = await typed(""); + const sheet = document.getElementById("sheet"); + const foot = document.querySelector(".sheet-box .prune-foot"); + const go = document.getElementById("prune-sign"); + const visible = () => { + const box = foot.getBoundingClientRect(); + const button = go.getBoundingClientRect(); + const hit = document.elementFromPoint(button.left + button.width / 2, button.top + button.height / 2); + return box.top >= 0 && box.bottom <= innerHeight + 1 && Boolean(hit && hit.closest("#prune-sign")) && Boolean(foot.querySelector(".dial-readout")); + }; + const scrolls = sheet.scrollHeight > sheet.clientHeight + 1; + const atTop = visible(); + sheet.scrollTop = Math.floor((sheet.scrollHeight - sheet.clientHeight) / 2); + await sleep(150); + const midway = visible(); + rows()[rows().length - 1].scrollIntoView({block: "end"}); + sheet.scrollTop = sheet.scrollHeight; + await sleep(150); + const atEnd = {visible: visible(), last: rows()[rows().length - 1].getBoundingClientRect().bottom <= foot.getBoundingClientRect().top + 1}; + return {rows: rows().length, count: count(), groups, stepper, look, full, partial, back, off, folded, narrowed, nothing, cleared, scrolls, atTop, midway, atEnd, wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" +SIGN_ALL = """(async () => {@HELPERS@ + await screenShown(8000); + await openTaskMenu("task-actions"); + (await until(() => document.getElementById("kanban-prune-open"), 8000)).click(); + if (!(await until(() => all(".sheet-box .prune-list li[data-task]").length >= @COUNT@, 8000))) { + return {error: text(document.querySelector(".sheet-box") || document.getElementById("main")).slice(0, 300)}; + } + const signs = []; + const send = window.fetch.bind(window); + window.fetch = (path, init) => { + if (String(path) === "/api/sign") { + signs.push(JSON.parse(init.body).items); + } + return send(path, init); + }; + const count = text(document.querySelector("#prune-sign .count")); + document.getElementById("prune-sign").click(); + const waiting = await until(() => document.querySelector('.sheet-box .prune-dial[aria-readonly="true"]'), 20000); + return {signs, count, waiting: Boolean(waiting), listed: all(".sheet-box .prune-list li[data-task]").length, wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" +MANY = 258 +PREFIXES = ("ci", "cluster", "work", "fix") def stamp(days: float) -> str: @@ -102,6 +193,14 @@ def fixture_row(status: str, days: float) -> dict: return {"roles": {"Docs": "RA"}, "status": status, "updated": stamp(days), "title": "fixture task", "worker": "-"} +def many_tasks() -> list[str]: + return [f"{PREFIXES[index % len(PREFIXES)]}/t{index:03d}" if index % 25 else f"solo-{index:03d}" for index in range(MANY)] + + +def prefix_of(task: str) -> str: + return task.split("/")[0] if "/" in task else "other" + + @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestStalePrune(HubCase): drive = base.OrchestratorE2ECase.drive @@ -127,7 +226,7 @@ class TestStalePrune(HubCase): self.assertEqual(found["first"], {"tasks": ["work/old-a", "work/old-b"], "ticked": 2, "days": "3", "sign": "Prune"}) self.assertEqual((found["ten"]["tasks"], found["one"]["tasks"]), (["work/old-a"], ["work/old-a", "work/old-b", "work/fresh"])) self.assertEqual((found["bad"], found["back"]), ({"tasks": ["work/old-a", "work/old-b", "work/fresh"], "invalid": "true"}, {"tasks": ["work/old-a", "work/old-b"], "invalid": "false"})) - self.assertEqual(found["opened"], {"attrs": ["slider", "1", "60", "10", "10 minutes for the agents to keep a task", None], "readout": "10 min", "ticks": 60, "long": 12}) + self.assertEqual(found["opened"], {"attrs": ["slider", "1", "60", "10", "10 minutes for the agents to keep a task", None], "readout": "10:00", "ticks": 60, "long": 12}) self.assertEqual(found["keys"], [["PageDown", "5"], ["Home", "1"], ["ArrowLeft", "1"], ["End", "60"], ["ArrowRight", "60"], ["PageDown", "55"], ["Home", "1"], ["PageUp", "6"]]) self.assertEqual((found["inside"], found["wide"]), (True, False)) @@ -148,7 +247,8 @@ class TestStalePrune(HubCase): self.assertTrue(signed["chip"]["title"].endswith(": work/old-a, work/old-b"), signed["chip"]) self.assertRegex(signed["before"], r"^[45]:[0-5][0-9]$") self.assertNotEqual(signed["before"], signed["after"]) - self.assertEqual((signed["countdown"]["now"], signed["countdown"]["unit"], signed["countdown"]["listed"]), ("5", "5 min", ["work/old-a", "work/old-b"])) + self.assertEqual((signed["countdown"]["now"], signed["countdown"]["listed"]), ("5", ["work/old-a", "work/old-b"])) + self.assertRegex(signed["countdown"]["readout"], r"^4:[0-5][0-9]$") self.assertFalse(signed["wide"]) jobs = sorted(self.httpd.hub.jobs.listed(), key=lambda job: job["argv"][0]) self.assertEqual([(job["kind"], job["status"], job.get("not_before")) for job in jobs], [("prune", "queued", None), ("prune", "queued", since + 300)]) @@ -156,6 +256,51 @@ class TestStalePrune(HubCase): with self.subTest(width=other): self.assertEqual(found, {"chip": True, "waiting": True, "wide": False}) + def many(self) -> list[str]: + tasks = many_tasks() + rows = {task: fixture_row("queued", 4 + index % 20) for index, task in enumerate(tasks)} + (self.council / "rasci.json").write_text(json.dumps(rows), encoding="utf-8") + return tasks + + def many_step(self, width: int, height: int, probe: str, shot: str) -> dict: + return self.step(width, height, probe.replace("@COUNT@", str(MANY)), shot) + + def test_258_tasks_group_by_prefix_with_tri_state_filter_stepper_and_a_sticky_footer(self): + tasks = self.many() + order = sorted({prefix_of(task) for task in tasks}, key=lambda prefix: (prefix == "other", prefix)) + groups = [[prefix, str(sum(prefix_of(task) == prefix for task in tasks)), sum(prefix_of(task) == prefix for task in tasks)] for prefix in order] + ci = sum(prefix_of(task) == "ci" for task in tasks) + narrowed = [task for task in tasks if "t01" in task] + data = self.drive([self.many_step(width, height, GROUPS, "groups") for width, height in base.WIDTHS], None) + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + for (width, _), found in zip(base.WIDTHS, data["results"], strict=True): + with self.subTest(width=width): + self.assertNotIn("error", found, found) + self.assertEqual((found["rows"], found["count"], found["groups"]), (MANY, str(MANY), groups)) + self.assertEqual(found["stepper"], {"type": "number", "mic": None, "framed": False, "mics": 0, "buttons": ["One day less", "One day more"]}) + self.assertEqual(found["look"], {"avatar": True, "owner": "Docs", "age": "6 d"}) + self.assertEqual((found["full"], found["partial"], found["back"]), ({"checked": True, "mixed": False, "count": str(MANY)}, {"checked": False, "mixed": True, "count": str(MANY - 1)}, {"checked": True, "mixed": False, "count": str(MANY)})) + self.assertEqual(found["off"], {"checked": False, "mixed": False, "count": str(MANY - ci), "ticked": 0}) + self.assertEqual(found["folded"], {"expanded": "false", "hidden": True, "count": str(MANY)}) + self.assertEqual(found["narrowed"], {"shown": len(narrowed), "groups": sorted({prefix_of(task) for task in narrowed}), "count": str(len(narrowed)), "none": False}) + self.assertEqual(found["nothing"], {"shown": 0, "groups": [], "count": "0", "none": True}) + self.assertEqual(found["cleared"], {"shown": MANY, "groups": order, "count": str(MANY), "none": False}) + self.assertEqual((found["scrolls"], found["atTop"], found["midway"], found["atEnd"]), (True, True, True, {"visible": True, "last": True})) + self.assertFalse(found["wide"]) + + def test_258_stale_tasks_are_pruned_under_one_signature(self): + tasks = self.many() + width, height = base.WIDTHS[0] + data = self.drive([self.many_step(width, height, SIGN_ALL, "many-signed")], self.authenticator()) + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + found = data["results"][0] + self.assertNotIn("error", found, found) + self.assertEqual((found["count"], len(found["signs"]), found["waiting"], found["listed"], found["wide"]), (str(MANY), 1, True, MANY, False)) + announce, apply = found["signs"][0] + self.assertEqual((sorted(announce["argv"][5:]), sorted(apply["argv"][3:])), (sorted(tasks), sorted(tasks))) + jobs = sorted(self.httpd.hub.jobs.listed(), key=lambda job: job["argv"][0]) + self.assertEqual([(job["kind"], job["status"], len(job["argv"])) for job in jobs], [("prune", "queued", 5 + MANY), ("prune", "queued", 3 + MANY)]) + if __name__ == "__main__": unittest.main() diff --git a/tests/e2e/test_stale_requests_e2e.py b/tests/e2e/test_stale_requests_e2e.py new file mode 100644 index 0000000..0e7abf1 --- /dev/null +++ b/tests/e2e/test_stale_requests_e2e.py @@ -0,0 +1,168 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import time +import unittest +from pathlib import Path +from unittest import mock + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +from hub_case import HubCase +from hub_support import ASK, signing +from kvb_orchestrator import batches, skill_scripts + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-093-stale-shots")) +LONG = "\n".join(f"echo line {number}" for number in range(1, 41)) +UNDO = 4 +FLOW = """(async () => {@HELPERS@ + const posted = []; + const send = window.fetch.bind(window); + window.fetch = async (path, init) => { + if (["/api/sign", "/api/requests/dismiss"].includes(String(path))) { + posted.push([String(path), JSON.parse(init.body).items.map((item) => [item.kind, item.target, item.id, item.scope])]); + } + return send(path, init); + }; + const enabled = (selector) => until(() => { + const node = document.querySelector(selector); + return node && !node.disabled ? node : null; + }, 4000); + const undoToast = () => until(() => all("#toasts .toast.wait").find((node) => text(node).startsWith("Delete")), 15000); + const phase = "@PHASE@"; + if (phase === "stream") { + await streamShowsAll(); + const foot = () => document.querySelector("#main details.stale-footer"); + if (!(await until(foot, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + const body = await until(() => document.querySelector('#main .feed > li[data-ref="@LONG@"] .code-body'), 8000); + if (!body) { + return {error: "no code box for the long ask"}; + } + const code = body.querySelector(".command code"); + const scrolls = [body.scrollHeight > body.clientHeight + 1, getComputedStyle(body).overflowY]; + body.scrollTop = body.scrollHeight; + await sleep(150); + const entry = body.closest("li"); + const actions = body.closest(".code-box").querySelector(".code-foot").getBoundingClientRect(); + const long = {scrolls, bottom: body.scrollTop + body.clientHeight >= body.scrollHeight - 1, lines: code.textContent.split("\\n").length, last: code.textContent.endsWith("echo line 40"), + clipped: entry.scrollHeight > entry.clientHeight + 1 && getComputedStyle(entry).overflowY !== "visible", foot: actions.height > 0}; + const feed = all("#main .feed > li").map((li) => li.dataset.item || ""); + const summary = text(foot().querySelector("summary")); + const closed = !foot().open; + foot().querySelector("summary").click(); + await until(() => foot().open && all(".stale-list > li", foot()).length, 3000); + const rows = all(".stale-list > li", foot()).map((li) => [li.dataset.ref, li.dataset.request]).sort(); + foot().querySelector(".triage-all").click(); + const button = await enabled("#main details.stale-footer .triage-delete"); + const label = text(button); + button.click(); + const toast = await undoToast(); + const hidden = Boolean(await until(() => !foot(), 8000)); + if (toast) { + toast.querySelector('button[aria-label="Undo"]').click(); + } + const back = await until(() => foot() && text(foot().querySelector("summary")) === summary, 10000); + return {long, feed, summary, closed, rows, label, toast: Boolean(toast), hidden, back: Boolean(back), posted, wide: document.documentElement.scrollWidth > innerWidth + 1}; + } + const chip = (id) => document.querySelector(`#main .triage-bar .chip[data-request="${id}"]`); + if (!(await until(() => chip("all"), 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + const counts = () => Object.fromEntries(all("#main .triage-bar .chip").map((node) => [node.dataset.request, text(node.querySelector(".count"))])); + const before = counts(); + if (phase === "again") { + return {before}; + } + const lists = {}; + for (const id of ["open", "expired", "stale", "failed", "all"]) { + chip(id).click(); + await until(() => chip(id).getAttribute("aria-pressed") === "true", 3000); + await sleep(200); + lists[id] = all("#main .inbox-list > li").map((li) => li.dataset.ref).sort(); + } + chip("expired").click(); + await until(() => chip("expired").getAttribute("aria-pressed") === "true", 3000); + document.querySelector("#main .triage-bar .triage-all").click(); + const button = await enabled("#main .triage-bar .triage-delete"); + const label = text(button); + button.click(); + const toast = await undoToast(); + const gone = Boolean(await until(() => !document.querySelector('#main .inbox-list > li[data-ref="@EXPIRED@"]'), 8000)); + const settled = Boolean(await until(() => !all("#toasts .toast.wait").length, 20000)); + await sleep(1500); + return {before, lists, label, toast: Boolean(toast), gone, settled, after: counts(), posted, wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestStaleRequests(HubCase): + drive = base.OrchestratorE2ECase.drive + authenticator = base.OrchestratorE2ECase.authenticator + + def setUp(self): + super().setUp() + self.claim("s1", "Skills session") + self.expired = self.create_ask({**ASK, "call_key": signing.call_key("Bash", {"command": ASK["command"]})}) + self.httpd.hub.asks.change(self.expired, {"expires": time.time() - 600}) + self.long = self.create_ask({**ASK, "command": LONG, "timeout": 3600}) + self.review = self.request("feat: stale", "") + status, _, body = self.post_json("/api/match/stale", {"id": self.review, "tree": "f" * 40}, self.local()) + self.assertEqual(status, 200, body) + greet = {"title": "echo greet", "workdir": str(self.outside), "description": "greets", "check": "manual", "status": "queued", "roles": {"Operator": "R", "Skills session": "A"}} + self.write_council({"rasci.json": {"operator/greet": greet}}) + now = time.time() + fields = {"task": "operator/greet", "command": "echo greet", "directory": str(self.outside), "sha256": "", "status": "failed", "proof": None} + job = self.httpd.hub.jobs.add({**fields, "code": 2, "output": "boom\n", "created_ts": now - 20, "started": now - 19, "finished": now - 10, "dismissed": False}) + self.run_line = self.httpd.hub.log.add({"kind": "run", "title": "failed: echo greet", "text": "boom", "ref": {"job": job["id"], "task": "operator/greet", "code": 2, "status": "failed"}})["id"] + + def step(self, phase: str, width: int, height: int) -> dict: + flow = FLOW.replace("@HELPERS@", base.HELPERS).replace("@PHASE@", phase).replace("@LONG@", f"ask:{self.long}").replace("@EXPIRED@", f"ask:{self.expired}") + screen = "stream" if phase == "stream" else "tasks/operator" + return {"width": width, "height": height, "url": f"http://localhost:{self.port}/?{phase}-{width}#{screen}", "wait": 1500, "probe": flow, "shot": str(OUT / f"chromium-{width}-{phase}.png")} + + def test_chromium_hides_stale_requests_behind_the_footer_and_deletes_them_by_chip_with_undo(self): + OUT.mkdir(parents=True, exist_ok=True) + steps = [self.step("stream", 1366, 768), self.step("tasks", 1366, 768), self.step("again", 390, 844)] + with mock.patch.object(batches, "UNDO", UNDO): + data = self.drive(steps, self.authenticator()) + (OUT / "chromium-stale-requests.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], []) + self.assertEqual(len(data["results"]), len(steps), data) + stream, tasks, again = data["results"] + for found in data["results"]: + self.assertNotIn("error", found, found) + expired, long, review, row = f"ask:{self.expired}", f"ask:{self.long}", f"review:{self.review}", "operator:operator/greet" + + self.assertEqual(stream["long"], {"scrolls": [True, "auto"], "bottom": True, "lines": 40, "last": True, "clipped": False, "foot": True}, stream) + self.assertEqual([item for item in stream["feed"] if item.endswith((f"/{expired}", f"/{review}"))], [], stream) + self.assertEqual(len([item for item in stream["feed"] if item.endswith(f"/{row}")]), 1, stream) + self.assertEqual([item for item in stream["feed"] if item.endswith(f"/{self.run_line}")], [], stream) + self.assertEqual((stream["summary"], stream["closed"]), ("2 stale requests · 1 expired · 1 stale", True), stream) + self.assertEqual(stream["rows"], sorted([[expired, "expired"], [review, "stale"]]), stream) + self.assertEqual((stream["label"], stream["toast"], stream["hidden"], stream["back"], stream["wide"]), ("Delete 2", True, True, True, False), stream) + self.assertEqual([path for path, _ in stream["posted"]], ["/api/sign", "/api/requests/dismiss"], stream) + self.assertEqual(sorted(stream["posted"][1][1]), sorted([["dismiss", "ask", self.expired, "expired"], ["dismiss", "review", self.review, "stale"]]), stream) + + self.assertEqual(tasks["before"], {"open": "1", "expired": "1", "stale": "1", "failed": "1", "all": "4"}, tasks) + self.assertEqual(tasks["lists"], {"open": [long], "expired": [expired], "stale": [review], "failed": [row], "all": sorted([long, expired, review, row])}, tasks) + self.assertEqual((tasks["label"], tasks["toast"], tasks["gone"], tasks["settled"], tasks["wide"]), ("Delete 1", True, True, True, False), tasks) + self.assertEqual(tasks["after"], {"open": "1", "expired": "0", "stale": "1", "failed": "1", "all": "3"}, tasks) + self.assertEqual(tasks["posted"][1], ["/api/requests/dismiss", [["dismiss", "ask", self.expired, "expired"]]], tasks) + + self.assertEqual(again["before"], {"open": "1", "expired": "0", "stale": "1", "failed": "1", "all": "3"}, again) + snapshot = self.snapshot() + self.assertNotIn(self.expired, [item["id"] for item in snapshot["lapsed"]]) + self.assertIn(self.long, [item["id"] for item in snapshot["inbox"]]) + self.assertEqual(self.httpd.hub.asks.get(self.expired)["status"], "pending") + self.assertEqual([args for script, args in self.scripts.calls if script == skill_scripts.RADIO], []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_task_card_identity_e2e.py b/tests/e2e/test_task_card_identity_e2e.py new file mode 100644 index 0000000..25bd21e --- /dev/null +++ b/tests/e2e/test_task_card_identity_e2e.py @@ -0,0 +1,202 @@ +"""Exercise requirement 090 in Chromium: one card per state with its border colour, glow and owner avatar, the colour legend, light and dark, at three widths.""" + +from __future__ import annotations + +import json +import os +import shutil +import sys +import time +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +from hub_case import HubCase +from hub_support import iso + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/task-card-identity-shots")) +DAY = 86400 +TONES = {"running": "ok", "operator": "warn", "queued": "info", "blocked": "bad", "stale": "faint", "ended": "line-strong"} +STATES = { + "work/run": "running", "queue/q-1": "running", "work/ask": "operator", "work/wait": "queued", "queue/q-2": "queued", + "work/stuck": "blocked", "queue/q-3": "blocked", "work/old": "stale", "work/done": "ended", "work/stop": "ended", +} +OWNERS = { + "work/run": "Stage", "queue/q-1": "Stage", "work/ask": "Skills", "work/wait": "Docs", "queue/q-2": "Main", + "work/stuck": "Main", "queue/q-3": "Docs", "work/old": "", "work/done": "Stage", "work/stop": "Docs", +} +WORKING = ["work/run", "queue/q-1"] +STATE_TONES = {"ok", "warn", "info", "bad"} +READ = """ + const card = (task) => all("#main .kanban-card").find((node) => node.dataset.task === task) || null; + const color = (variable) => { + const probe = document.createElement("span"); + probe.style.color = `var(${variable})`; + document.body.append(probe); + const found = getComputedStyle(probe).color; + probe.remove(); + return found; + }; + const avatarOf = (art) => (!art ? null : art.classList.contains("kanban-nobody") ? "nobody" : art.querySelector("svg.face-art") ? "face" : "other"); + const cardRead = (node) => { + const look = getComputedStyle(node); + const face = node.querySelector(":scope > .kanban-owner"); + const art = face ? face.querySelector(".avatar") : null; + const box = node.getBoundingClientRect(); + const at = art ? art.getBoundingClientRect() : null; + return { + state: node.dataset.cardState || null, + border: [look.borderTopWidth, look.borderTopStyle, look.borderTopColor], + sides: new Set([look.borderTopColor, look.borderRightColor, look.borderBottomColor, look.borderLeftColor]).size, + shadow: look.boxShadow, animation: look.animationName, working: node.classList.contains("is-working"), + owner: face ? face.dataset.owner : null, avatar: avatarOf(art), first: face !== null && face === node.firstElementChild, + corner: at ? [Math.round(at.left - box.left), Math.round(at.top - box.top), Math.round(at.width)] : null, + tones: all(".pill:not(.queue-chip)", node).map((pill) => pill.dataset.tone || ""), + title: node.getAttribute("title") || "", + }; + }; + const sample = async (node) => { + const seen = new Set(); + for (let at = 0; at < 26; at += 1) { + seen.add(getComputedStyle(node).boxShadow); + await sleep(50); + } + return [...seen]; + }; + const read = async () => { + const toggle = document.querySelector("#main .kanban-legend .legend-toggle"); + return { + cards: Object.fromEntries(all("#main .kanban-card").map((node) => [node.dataset.task, cardRead(node)])), + tones: Object.fromEntries(@TONES@.map((tone) => [tone, color(`--${tone}`)])), + legend: all("#main .kanban-legend .kanban-key").map((key) => { + const look = getComputedStyle(key.querySelector(".kanban-swatch")); + return [key.dataset.cardState, text(key), look.borderTopStyle, look.borderTopColor]; + }), + toggle: toggle ? [name(toggle), toggle.getAttribute("aria-pressed")] : null, + beat: await sample(card("work/run")), + mode: document.documentElement.dataset.mode || "", + wide: document.documentElement.scrollWidth > window.innerWidth + 1, + }; + }; +""" +BOARD = """(async () => {@HELPERS@@READ@ + const ready = () => @TASKS@.every((task) => card(task)) && document.querySelector("#main .kanban-legend .legend-toggle") && card("work/run").classList.contains("is-working"); + if (!(await until(ready, 12000))) { + return {error: text(document.getElementById("main")).slice(0, 400), cards: all("#main .kanban-card").map((node) => node.dataset.task)}; + } + await sleep(400); + document.querySelector("#main .kanban-legend").scrollIntoView({block: "start"}); + return read(); +})()""" + + +def probe() -> str: + return (BOARD.replace("@HELPERS@", base.HELPERS).replace("@READ@", READ).replace("@TASKS@", json.dumps(sorted(STATES))) + .replace("@TONES@", json.dumps(sorted(set(TONES.values()))))) + + +def identity_council(now: float) -> dict: + """Returns: + A register with one card per state: work/run running with an active + queue job (queue/q-1), work/ask queued under Skills, who has an open + decision, work/wait queued with only an R holder and a waiting queue + job (queue/q-2), work/stuck blocked, queue/q-3 a queue job that ended + with exit 2, work/old untouched for four days without an owner, and + work/done and work/stop ended ten minutes ago. + """ + return { + "rasci.json": { + "work/run": {"title": "Run", "status": "running", "worker": "Stage", "prio": 1}, + "work/ask": {"title": "Ask", "status": "queued", "worker": "Skills", "prio": 1}, + "work/wait": {"title": "Wait", "status": "queued", "worker": "-", "roles": {"Docs": "R"}, "prio": 2}, + "work/stuck": {"title": "Stuck", "status": "blocked", "worker": "Main", "prio": 2}, + "work/old": {"title": "Old", "status": "queued", "updated": iso(now - 4 * DAY)}, + "work/done": {"title": "Done", "status": "done", "worker": "Stage", "end": iso(now - 600)}, + "work/stop": {"title": "Stop", "status": "stopped", "worker": "Docs", "end": iso(now - 600)}, + }, + "queue.json": {"seq": 3, "entries": [ + {"id": "q-1", "seq": 1, "cmd": "make test", "kind": "test", "task": "work/run", "name": "Stage", "hotfix": None, "status": "active", "enqueued": now - 200, "granted": now - 100}, + {"id": "q-2", "seq": 2, "cmd": "make gate", "kind": "gate", "task": "work/wait", "name": "Main", "hotfix": None, "status": "waiting", "enqueued": now - 50}, + {"id": "q-3", "seq": 3, "cmd": "make deploy", "kind": "deploy", "task": "work/done", "name": "Docs", "hotfix": None, "status": "active", "enqueued": now - 900, "granted": now - 880}, + ]}, + "queue-history.jsonl": json.dumps({"id": "q-3-1794500000000000000", "kind": "deploy", "start": now - 880, "end": now - 300, "exit": 2, "workdir": "/"}) + "\n", + } + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestTaskCardIdentity(HubCase): + drive = base.OrchestratorE2ECase.drive + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.write_council(identity_council(time.time())) + self.decision("") + + def run_theme(self, theme: str) -> list[dict]: + hub = self.httpd.hub + hub.settings.put({**hub.settings.get(), "theme": theme}, hub.settings.get()) + local = f"http://localhost:{self.port}/" + steps = [{"width": width, "height": height, "url": f"{local}?{theme}-{width}#tasks/board", "wait": 1500, "probe": probe(), "shot": str(OUT / f"chromium-{theme}-{width}-card-identity.png")} + for width, height in base.WIDTHS] + data = self.drive(steps, None) + (OUT / f"chromium-{theme}-card-identity.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + return data["results"] + + def check_cards(self, read: dict) -> None: + cards = read["cards"] + self.assertEqual(sorted(cards), sorted(STATES)) + for task, wanted in STATES.items(): + with self.subTest(task=task): + found = cards[task] + line = "dashed" if wanted == "stale" else "solid" + self.assertEqual((found["state"], found["border"], found["sides"]), (wanted, ["2px", line, read["tones"][TONES[wanted]]], 1), found) + self.assertNotEqual(found["shadow"], "none", found) + self.assertEqual((found["owner"], found["avatar"], found["first"]), (OWNERS[task], "face" if OWNERS[task] else "nobody", True), found) + left, top, size = found["corner"] + self.assertTrue(0 <= left <= 16 and 0 <= top <= 16 and size >= 20, found) + self.assertEqual(set(found["tones"]) & STATE_TONES, set(), found) + self.assertTrue(found["title"].startswith(f"{task}: "), found) + self.assertEqual((found["working"], found["animation"]), (True, "lub-dub") if task in WORKING else (False, "none"), found) + + def check_colours(self, read: dict) -> None: + cards = read["cards"] + colours = {state: cards[task]["border"][2] for task, state in STATES.items()} + self.assertEqual(len(set(colours.values())), len(TONES), colours) + still = {task: cards[task]["shadow"] for task in STATES if task not in WORKING} + for state in set(TONES) - {"running"}: + with self.subTest(glow=state): + self.assertEqual(len({glow for task, glow in still.items() if STATES[task] == state}), 1, still) + self.assertEqual(len(set(still.values())), len(TONES) - 1, still) + self.assertGreater(len(read["beat"]), 1, read["beat"]) + self.assertNotEqual(cards["work/run"]["border"], cards["work/old"]["border"]) + + def check_legend(self, read: dict) -> None: + self.assertEqual([key for key, *_ in read["legend"]], list(TONES)) + for key, words, line, colour in read["legend"]: + with self.subTest(legend=key): + self.assertTrue(words, read["legend"]) + self.assertEqual((line, colour), ("dashed" if key == "stale" else "solid", read["tones"][TONES[key]])) + self.assertEqual(read["toggle"], ["Legend", "true"], read["toggle"]) + + def test_chromium_each_state_has_its_own_border_glow_and_owner_avatar_in_light_and_dark_at_three_widths(self): + seen = {} + for theme in ("light", "dark"): + for (width, _), read in zip(base.WIDTHS, self.run_theme(theme), strict=True): + with self.subTest(theme=theme, width=width): + self.assertNotIn("error", read, read) + self.assertEqual(read["mode"], theme) + self.check_cards(read) + self.check_colours(read) + self.check_legend(read) + self.assertFalse(read["wide"], read) + seen[theme] = read["tones"] + self.assertNotEqual(seen["light"], seen["dark"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_task_toolbar_e2e.py b/tests/e2e/test_task_toolbar_e2e.py new file mode 100644 index 0000000..4435432 --- /dev/null +++ b/tests/e2e/test_task_toolbar_e2e.py @@ -0,0 +1,367 @@ +"""Exercise requirement 089 in Chromium: the Tasks toolbar in one row with a Filter and an Actions menu, every control of the old two rows within two clicks, the filter chip and its reset, at three widths.""" + +from __future__ import annotations + +import datetime +import json +import os +import shutil +import sys +import unittest +from pathlib import Path +from typing import NamedTuple + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/task-toolbar-shots")) +SCREENS = ("list", "rasci", "gantt", "burn", "board", "operator") +TASKS = SCREENS[:-1] +FILTER = ("task-filter",) +ACTIONS = ("task-actions",) +CHOICES = ("task-actions", "choice-request") + + +class Control(NamedTuple): + """Args: + control: the control's name. + today: where the two-row toolbar held it. + place: where the one-row toolbar holds it. + screens: the Tasks screens that show it. + path: the menus to open, one click each, before it shows. + selector: finds it in the page. + condition: "" when it always shows, "points" when it shows under + Story points only, "optional" when only some state shows it. + """ + + control: str + today: str + place: str + screens: tuple[str, ...] + path: tuple[str, ...] + selector: str + condition: str = "" + + +VIEWS = ["List", "Board", "RASCI", "Gantt", "Burndown and burnup", "3D", "Match"] +CHANNELS = {"post": "Post", "call": "Call", "newsletter": "Newsletter", "broadcast": "Broadcast", "pan-pan": "Pan-Pan", "security": "Sécurité", "mayday": "Mayday"} +STATUS_TABS = {"all": "All", "open": "Open", "work": "Open work", "operator": "Waits on Operator", "grant": "Waiting for a grant", "ended": "Ended"} +INVENTORY = ( + *(Control(f"View switcher: {view}", "row 1", "toolbar row", SCREENS, (), f'#main .task-bar [aria-label="View"] button[aria-label="{view}"]') for view in VIEWS), + Control("Filter search", "row 1", "toolbar row", TASKS, (), '#main .task-bar input[aria-label="Filter tasks"]'), + Control("Search mic", "row 1", "toolbar row, inside the search frame", TASKS, (), "#main .task-bar .mic-line > button.mic"), + Control("Task count", "row 1", "toolbar row, last", SCREENS, (), "#main .task-bar > .task-count"), + Control("Estimation: No estimate (info button)", "row 1", "Filter > View", TASKS, FILTER, '#main [aria-label="Estimation"] button[data-estimation="none"]'), + Control("Estimation: Story points (diamond button)", "row 1", "Filter > View", TASKS, FILTER, '#main [aria-label="Estimation"] button[data-estimation="points"]'), + Control("Request estimates", "row 1, under Story points", "Actions > Plan", TASKS, ACTIONS, "#request-estimates", "points"), + Control("Sort", "row 1, list", "Filter > View", ("list",), FILTER, '#main select[aria-label="Sort"]'), + Control("Sort direction", "row 1, list", "Filter > View", ("list",), FILTER, "#main button[data-direction]"), + Control("Business value of the selection", "row 1, list", "Actions > Plan", ("list",), ACTIONS, '#main select[aria-label="Business value of the selection"]'), + Control("Set business value", "row 1, list", "Actions > Plan", ("list",), ACTIONS, "#bulk-value"), + Control("Forecast", "row 1, gantt", "Filter > View", ("gantt",), FILTER, '#main select[aria-label="Forecast"]'), + Control("Scope", "row 1, burn", "Filter > View", ("burn",), FILTER, '#main select[aria-label="Scope"]'), + Control("Trend", "row 1, burn", "Filter > View", ("burn",), FILTER, '#main select[aria-label="Trend"]'), + Control("Request choices", "row 1", "Actions > Request choices", SCREENS, ACTIONS, "#choice-request > summary"), + Control("Request choices: agents", "row 1, Request choices", "Actions > Request choices", SCREENS, CHOICES, "#choice-request .choice-agents"), + *(Control(f"Request choices: {label}", "row 1, Request choices", "Actions > Request choices", SCREENS, CHOICES, f'#choice-request button[data-channel="{channel}"]') for channel, label in CHANNELS.items()), + Control("Apply staged moves (green done counter)", "row 2, board", "Actions > Board", ("board",), ACTIONS, "#kanban-apply"), + Control("Discard staged moves (cancel)", "row 2, board", "Actions > Board", ("board",), ACTIONS, "#kanban-discard"), + Control("Older Done (hidden counter)", "row 2, board", "Filter > Board", ("board",), FILTER, "#kanban-old"), + Control("Running", "row 2, board", "Filter > Board", ("board",), FILTER, "#kanban-running"), + Control("Stale filter", "new", "Filter > Board", ("board",), FILTER, "#kanban-stale-only"), + Control("Stale count (hourglass counter)", "row 2, board", "toolbar row, compact chip while a card is stale", ("board",), (), "#main .task-bar #kanban-stale"), + Control("Prune stale", "row 2, board", "Actions > Board", ("board",), ACTIONS, "#kanban-prune-open"), + Control("Prune countdown", "row 2, board, while a signed prune waits", "toolbar row chip, and the readout inside Prune stale", ("board",), (), "#main .task-bar #kanban-prune", "optional"), + Control("Queue line", "row 2, board", "Filter > Board", ("board",), FILTER, '#main .legend-chip[data-path="kanban.hidden"][data-chip="line"]'), + Control("Queue jobs", "row 2, board", "Filter > Board", ("board",), FILTER, '#main .legend-chip[data-path="kanban.hidden"][data-chip="jobs"]'), + Control("Queue order only", "row 2, board, while queue.py lists no JSON", "Filter > Board", ("board",), FILTER, "#kanban-queue-order", "optional"), + *(Control(f"Status: {label}", "status tabs", "Filter > Status, one radio group with counts", SCREENS, FILTER, f'#main [aria-label="Task filters"] [data-filter="{tab}"] input[type="radio"]') for tab, label in STATUS_TABS.items()), + Control("Filter chip reset", "new", "toolbar row, next to Filter", ("operator",), (), "#main .task-bar #task-filter-chip button.x"), + Control("Undo", "undo toast", "Actions > Undo, one entry per running undo window", SCREENS, ACTIONS, "#main .task-undo"), +) +CLOSE = """ + const closeAll = async () => { + document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await sleep(150); + }; +""" +REACH = """(async () => {@HELPERS@@CLOSE@ + const entries = @ENTRIES@; + const ready = () => document.getElementById("task-actions") && document.querySelector("#main .tasks-body > *, #main .inbox-list"); + if (!(await screenShown(8000)) || !(await until(ready, 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(500); + const estimate = async (mode) => { + await openTaskMenu("task-filter"); + const button = () => document.querySelector(`#main [aria-label="Estimation"] button[data-estimation="${mode}"]`); + if (button().getAttribute("aria-pressed") !== "true") { + button().click(); + await until(() => button().getAttribute("aria-pressed") === "true", 8000); + } + await closeAll(); + }; + const reach = async ([control, , , , path, selector, condition]) => { + await closeAll(); + let clicks = 0; + for (const id of path) { + const menu = document.getElementById(id); + if (!menu) { + return [control, [clicks, `no menu ${id}`]]; + } + menu.querySelector(":scope > summary").click(); + clicks += 1; + await sleep(150); + } + const node = document.querySelector(selector); + if (!node) { + return [control, [clicks, condition === "optional" ? "absent" : "missing"]]; + } + const box = node.getBoundingClientRect(); + const seen = node.checkVisibility() && box.width > 0 && box.height > 0 && box.left >= -1 && box.right <= innerWidth + 1; + return [control, [clicks, seen ? "reachable" : "hidden"]]; + }; + await closeAll(); + const rows = toolbarRows(); + const wide = document.documentElement.scrollWidth > innerWidth + 1; + const reached = []; + for (const entry of entries.filter((item) => item[6] !== "points")) { + reached.push(await reach(entry)); + } + const points = entries.filter((item) => item[6] === "points"); + if (points.length) { + await estimate("points"); + for (const entry of points) { + reached.push(await reach(entry)); + } + await estimate("none"); + } + await closeAll(); + return {rows, wide, layout: taskLayout(), reached: Object.fromEntries(reached)}; +})()""" +SECTIONS = """ + const sections = (menu) => all(":scope > .menu-box > .task-menu-section", menu).filter((node) => node.checkVisibility()).map((node) => text(node.querySelector("h3"))); + const inside = (menu) => { + const box = menu.querySelector(":scope > .menu-box").getBoundingClientRect(); + return box.left >= -1 && box.right <= innerWidth + 1; + }; +""" +FILTER_OPEN = """(async () => {@HELPERS@@SECTIONS@ + if (!(await screenShown(8000)) || !(await until(() => document.getElementById("kanban-running"), 8000))) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + await sleep(400); + const menu = await openTaskMenu("task-filter"); + await sleep(200); + return { + open: menu.open, sections: sections(menu), inside: inside(menu), rows: toolbarRows(), + radios: all('[aria-label="Task filters"] input[type="radio"]', menu).map((input) => [input.value, input.checked, text(input.closest("label").querySelector(".count"))]), + wide: document.documentElement.scrollWidth > innerWidth + 1, + }; +})()""" +ACTIONS_OPEN = """(async () => {@HELPERS@@SECTIONS@ + const menu = await openTaskMenu("task-actions"); + const choices = document.getElementById("choice-request"); + choices.querySelector(":scope > summary").click(); + await sleep(250); + return { + open: [menu.open, choices.open, document.getElementById("task-filter").open], sections: sections(menu), inside: inside(menu), + channels: all("button[data-channel]", choices).filter((button) => button.checkVisibility()).map((button) => button.dataset.channel), + undo: text(menu.querySelector(".task-undo")), wide: document.documentElement.scrollWidth > innerWidth + 1, + }; +})()""" +CHIP = """(async () => {@HELPERS@@CLOSE@ + const chip = () => document.getElementById("task-filter-chip"); + const radio = (id) => document.querySelector(`#main [aria-label="Task filters"] [data-filter="${id}"] input`); + const cards = () => all("#main .kanban-card").length; + await closeAll(); + const before = {chip: Boolean(chip()), all: radio("all").checked, cards: cards()}; + await openTaskMenu("task-filter"); + radio("open").click(); + if (!(await until(() => chip() && text(chip()).includes("Open"), 4000))) { + return {error: "no chip after Open", before}; + } + const kept = document.getElementById("task-filter").open; + document.getElementById("kanban-running").click(); + if (!(await until(() => chip() && text(chip()).includes("Running"), 4000))) { + return {error: "no Running in the chip", before}; + } + await closeAll(); + await sleep(300); + const host = chip().parentElement; + const shown = { + words: text(chip().querySelector(".task-chip-word")), label: chip().getAttribute("aria-label"), reset: name(chip().querySelector("button.x")), + beside: host.previousElementSibling ? host.previousElementSibling.id : null, rows: toolbarRows(), kept, wide: document.documentElement.scrollWidth > innerWidth + 1, + }; + chip().querySelector("button.x").click(); + await until(() => !chip() && radio("all").checked, 4000); + await sleep(400); + const after = {chip: Boolean(chip()), all: radio("all").checked, running: document.getElementById("kanban-running").getAttribute("aria-pressed"), cards: cards()}; + await openTaskMenu("task-filter"); + radio("open").click(); + await until(() => chip(), 4000); + await closeAll(); + await sleep(300); + return {before, shown, after, again: [text(chip().querySelector(".task-chip-word")), toolbarRows()]}; +})()""" +KEYS = """(async () => {@HELPERS@ + const menu = await openTaskMenu("task-actions"); + const opened = menu.open; + document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await sleep(150); + const closed = !document.getElementById("task-actions").open; + await pressKey(String(Nav.TABS.findIndex(([id]) => id === "stream") + 1)); + const moved = Boolean(await until(() => location.hash.startsWith("#stream"), 4000)); + return {opened, closed, moved}; +})()""" +UNDO = """(async () => {@HELPERS@@LABELS@ + if (!(await screenShown(8000))) { + return {error: "no screen"}; + } + const row = await until(() => askOf("make deploy"), 8000); + if (!row) { + return {error: text(document.getElementById("main")).slice(0, 300)}; + } + press(row, "Grant"); + const waiting = await until(() => all("#toasts .toast.wait").find((box) => box.textContent.includes("Grant")), 15000); + await openTaskMenu("task-actions"); + const item = await until(() => document.querySelector('#main .task-undo button[data-key^="undo:"]'), 4000); + if (!waiting || !item) { + return {error: "no undo entry", toast: Boolean(waiting), undo: text(document.querySelector("#main .task-undo"))}; + } + const first = text(item.querySelector(".undo-left")); + await sleep(1300); + const second = item.isConnected ? text(item.querySelector(".undo-left")) : null; + return {visible: item.checkVisibility(), label: name(item), first, second, open: document.getElementById("task-actions").open}; +})()""" + + +def stamp(days: float) -> str: + """Args: + days: how long ago. + + Returns: + That moment as an ISO 8601 UTC stamp. + """ + return (datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=days)).isoformat(timespec="seconds") + + +def probe(template: str, **fills: str) -> str: + """Args: + template: a probe with @NAME@ placeholders. + fills: extra placeholders by lower-case name. + + Returns: + The probe with the kit's helpers and every fill put in. + """ + for key, value in {"@HELPERS@": base.HELPERS, "@LABELS@": base.LABELS, "@CLOSE@": CLOSE, "@SECTIONS@": SECTIONS, **{f"@{key.upper()}@": value for key, value in fills.items()}}.items(): + template = template.replace(key, value) + return template + + +def shown_on(screen: str) -> list[Control]: + """Args: + screen: one of SCREENS. + + Returns: + The inventory the screen shows. + """ + return [entry for entry in INVENTORY if screen in entry.screens] + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestTaskToolbar(base.OrchestratorE2ECase): + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + path = self.council / "rasci.json" + tasks = json.loads(path.read_text(encoding="utf-8")) + tasks.update({ + "work/stale-a": {"title": "Stale A", "status": "queued", "worker": "Docs", "roles": {"Docs": "RA"}, "updated": stamp(12)}, + "work/stale-b": {"title": "Stale B", "status": "blocked", "worker": "Docs", "roles": {"Docs": "RA"}, "updated": stamp(6)}, + }) + path.write_text(json.dumps(tasks), encoding="utf-8") + payload = {**self.snapshot()["settings"], "undo": 20, "proof": None} + self.assertEqual(self.post_json("/api/settings", payload, self.guard(self.host))[0], 200) + self.local = f"http://localhost:{self.port}/" + + def steps(self) -> list[dict]: + steps = [] + for width, height in base.WIDTHS: + at = {"width": width, "height": height} + entries = {screen: json.dumps([list(entry) for entry in shown_on(screen)], ensure_ascii=False) for screen in SCREENS} + steps += [{**at, "url": f"{self.local}?{width}-{screen}#tasks/{screen}", "wait": 1500, "probe": probe(REACH, entries=entries[screen]), "shot": str(OUT / f"chromium-{width}-{screen}.png")} for screen in SCREENS] + steps += [ + {**at, "url": f"{self.local}?{width}-menus#tasks/board", "wait": 1500, "probe": probe(FILTER_OPEN), "shot": str(OUT / f"chromium-{width}-board-filter-menu.png")}, + {**at, "url": None, "wait": 0, "probe": probe(ACTIONS_OPEN), "shot": str(OUT / f"chromium-{width}-board-actions-menu.png")}, + {**at, "url": None, "wait": 0, "probe": probe(CHIP), "shot": str(OUT / f"chromium-{width}-board-filter-chip.png")}, + {**at, "url": None, "wait": 0, "probe": probe(KEYS), "shot": None}, + ] + steps.append({"width": 1366, "height": 768, "url": f"{self.local}?undo#tasks/operator", "wait": 1500, "probe": probe(UNDO), "shot": str(OUT / "chromium-1366-operator-undo.png")}) + return steps + + def check_rows(self, rows: int, width: int, found: dict) -> None: + self.assertIn(rows, (1, 2) if width == 390 else (1,), found) + + def check_reach(self, found: dict, screen: str, width: int) -> None: + self.assertNotIn("error", found, found) + self.assertEqual((found["wide"], found["layout"]), (False, ["toolbar", "body"]), found) + self.check_rows(found["rows"], width, found) + entries = shown_on(screen) + self.assertEqual(sorted(found["reached"]), sorted(entry.control for entry in entries), found) + for entry in entries: + with self.subTest(control=entry.control): + clicks, state = found["reached"][entry.control] + self.assertLessEqual(clicks, 2) + self.assertEqual(clicks, len(entry.path), (entry, found["reached"][entry.control])) + self.assertIn(state, ("reachable", "absent") if entry.condition == "optional" else ("reachable",), (entry, state)) + + def check_menus(self, filtered: dict, actions: dict, width: int) -> None: + self.assertNotIn("error", filtered, filtered) + self.assertEqual((filtered["open"], filtered["sections"], filtered["inside"], filtered["wide"]), (True, ["Status", "Board", "View"], True, False), filtered) + self.assertEqual([[value, checked] for value, checked, _ in filtered["radios"]], [[tab, tab == "all"] for tab in STATUS_TABS]) + self.assertTrue(all(count.isdigit() for _, _, count in filtered["radios"]), filtered) + self.check_rows(filtered["rows"], width, filtered) + self.assertEqual((actions["open"], actions["sections"], actions["inside"], actions["wide"]), ([True, True, False], ["Board", "Undo"], True, False), actions) + self.assertEqual((actions["channels"], actions["undo"]), (list(CHANNELS), "Nothing to undo"), actions) + + def check_chip(self, chip: dict, keys: dict, width: int) -> None: + self.assertNotIn("error", chip, chip) + self.assertEqual(chip["before"]["chip"], False, chip) + self.assertTrue(chip["before"]["all"], chip) + shown = chip["shown"] + self.assertEqual((shown["words"], shown["label"], shown["reset"], shown["beside"], shown["kept"], shown["wide"]), ("Open · Running", "Filter: Open · Running", "Reset filter", "task-filter", True, False), shown) + self.check_rows(shown["rows"], width, shown) + self.assertEqual(chip["after"], {"chip": False, "all": True, "running": "false", "cards": chip["before"]["cards"]}, chip) + self.assertEqual(chip["again"][0], "Open", chip) + self.check_rows(chip["again"][1], width, chip) + self.assertEqual(keys, {"opened": True, "closed": True, "moved": True}, keys) + + def test_chromium_reaches_every_control_of_the_old_two_rows_from_one_row_at_three_widths(self): + data = self.drive(self.steps(), self.authenticator()) + (OUT / "chromium-task-toolbar.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error and "(style-src-elem)" not in error], []) + results = iter(data["results"]) + for width, _ in base.WIDTHS: + reached = {screen: next(results) for screen in SCREENS} + filtered, actions, chip, keys = next(results), next(results), next(results), next(results) + for screen, found in reached.items(): + with self.subTest(width=width, screen=screen): + self.check_reach(found, screen, width) + with self.subTest(width=width, step="menus"): + self.check_menus(filtered, actions, width) + with self.subTest(width=width, step="chip"): + self.check_chip(chip, keys, width) + undo = next(results) + self.assertNotIn("error", undo, undo) + self.assertEqual((undo["visible"], undo["open"]), (True, True), undo) + self.assertTrue(undo["label"].startswith("Undo: Grant"), undo) + self.assertRegex(undo["first"], r"^\d+ s$") + self.assertRegex(undo["second"], r"^\d+ s$") + self.assertLess(int(undo["second"].split()[0]), int(undo["first"].split()[0]), undo) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_undo_dial_e2e.py b/tests/e2e/test_undo_dial_e2e.py index 949b022..ba77cea 100644 --- a/tests/e2e/test_undo_dial_e2e.py +++ b/tests/e2e/test_undo_dial_e2e.py @@ -77,9 +77,9 @@ class TestUndoDial(deck.ReleaseDeck): for found in (texts, released): self.assertNotIn("error", found, found) self.assertIn(f"then {WORDS}.", texts["deny"], texts) - self.assertEqual(texts["opened"], {"attrs": ["slider", "0", "60", "10", "10 seconds to undo"], "label": "Undo window in seconds", "readout": "10 s", "ticks": 60, "long": 12}, texts) + self.assertEqual(texts["opened"], {"attrs": ["slider", "0", "60", "10", "10 seconds to undo"], "label": "Undo window in seconds", "readout": "0:10", "ticks": 60, "long": 12}, texts) self.assertEqual(texts["keys"], [["ArrowRight", "11"], ["PageUp", "16"], ["End", "60"], ["ArrowRight", "60"], ["PageDown", "55"], ["Home", "0"], ["ArrowLeft", "0"]], texts) - self.assertEqual(texts["zero"], {"text": "0 seconds: takes effect at once", "readout": "0 s"}, texts) + self.assertEqual(texts["zero"], {"text": "0 seconds: takes effect at once", "readout": "0:00"}, texts) self.assertEqual((texts["focused"], texts["inside"], texts["wide"]), (True, True, False), texts) self.assertTrue(released["title"].endswith(f"after each signature {WORDS}."), released) diff --git a/tests/e2e/test_workbench_w2_e2e.py b/tests/e2e/test_workbench_w2_e2e.py index d3b646f..1ae18d8 100644 --- a/tests/e2e/test_workbench_w2_e2e.py +++ b/tests/e2e/test_workbench_w2_e2e.py @@ -102,9 +102,11 @@ BOARD = """(async () => {@HELPERS@@BOARD_HELPERS@ card("work/stale").querySelector(".kanban-stop").click(); await sleep(400); const staged = read(); + await openTaskMenu("task-filter"); document.getElementById("kanban-old").click(); await sleep(300); const older = read().lanes.find(([lane]) => lane === "unpinned"); + await openTaskMenu("task-filter"); document.getElementById("kanban-old").click(); await sleep(300); document.querySelector('#main .kanban-lane[data-lane="p4"] .lane-toggle').click(); @@ -120,6 +122,7 @@ BOARD = """(async () => {@HELPERS@@BOARD_HELPERS@ (document.activeElement || document.body).dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); await sleep(300); const shown = new Set(all("#toasts .toast")); + await openTaskMenu("task-actions"); document.getElementById("kanban-apply").click(); const toast = await fresh(shown, "Apply 6 changes"); await sleep(600); @@ -257,7 +260,7 @@ class TestWorkbenchKanban(HubCase): "work/d": "set work/d --prio 4", "work/stale": "set work/stale --status stopped", }) - self.assertEqual((staged["apply"], staged["stale"], staged["labels"]["work/stale"]), ([False, "Apply 6 changes", "6"], "0", ["stopped"])) + self.assertEqual((staged["apply"], staged["stale"], staged["labels"]["work/stale"]), ([False, "Apply 6 changes", "6"], None, ["stopped"])) self.assertEqual(result["older"], ["unpinned", "true", {**EMPTY, "queued": ["queue/gate-2"], "running": ["queue/gate-1"], "done": ["work/done", "work/old", "work/stale", "work/stopped"]}]) listed = [[task, f"rasci.py {argv}"] for task, argv in STAGED] self.assertEqual((staged["listed"], result["folded"], result["popped"]), (listed, ["false", True, listed], [True, "work/b"])) diff --git a/tests/test_hub_board_running.py b/tests/test_hub_board_running.py index 665e6cb..6b35ec5 100644 --- a/tests/test_hub_board_running.py +++ b/tests/test_hub_board_running.py @@ -52,8 +52,8 @@ console.log(JSON.stringify({ def mark(key: str, text: str, hint: str, at: float) -> dict: - icon, tone = {"queue": ("bi-cpu", "accent"), "agent": ("bi-person-workspace", "ok"), "hub": ("bi-terminal", "info")}[key] - return {"key": key, "icon": icon, "tone": tone, "text": text, "hint": hint, "at": at} + icon = {"queue": "bi-cpu", "agent": "bi-person-workspace", "hub": "bi-terminal"}[key] + return {"key": key, "icon": icon, "text": text, "hint": hint, "at": at} class TestMarks(unittest.TestCase): @@ -62,8 +62,8 @@ class TestMarks(unittest.TestCase): done = subprocess.run(["node", "-e", MARKS_PROBE, str(KANBAN), str(NOW), LONG], capture_output=True, text=True, timeout=60, check=True) cls.data = json.loads(done.stdout) - def test_the_three_marks_come_in_queue_agent_hub_order_with_their_icon_and_tone(self): - self.assertEqual(self.data["order"], [["queue", "bi-cpu", "accent"], ["agent", "bi-person-workspace", "ok"], ["hub", "bi-terminal", "info"]]) + def test_the_three_marks_come_in_queue_agent_hub_order_with_their_icon(self): + self.assertEqual(self.data["order"], [["queue", "bi-cpu"], ["agent", "bi-person-workspace"], ["hub", "bi-terminal"]]) self.assertEqual(self.data["marks"]["work/all"], [ mark("queue", "test · 2 min", "work/all: queue job queue/q-1 runs test for 2 min", NOW - 125), mark("agent", "Main · 30 s", "work/all: Main works on it, last beat 30 s ago", NOW - 30), diff --git a/tests/test_hub_bubble_dock.py b/tests/test_hub_bubble_dock.py new file mode 100644 index 0000000..8576a39 --- /dev/null +++ b/tests/test_hub_bubble_dock.py @@ -0,0 +1,198 @@ +"""Exercise requirement 098: a docked speech bubble shows its speaker's face and a close button that skips the message.""" + +from __future__ import annotations + +import json +import subprocess +import unittest + +from hub_support import HUB +from test_hub_bubble_front import rules +from test_hub_bubbles import PAGE_HEAD + +BUBBLES = HUB / "templates" / "bubbles.js" +SPEECH = HUB / "templates" / "page-speech.js" +LAYER = HUB / "templates" / "page-bubbles.js" +PROBE = PAGE_HEAD + """ +const settle = async () => { + for (let round = 0; round < 8; round += 1) { + await new Promise((resolve) => setImmediate(resolve)); + } +}; +const part = () => ({gain: {value: 0, setValueAtTime: () => {}, exponentialRampToValueAtTime: () => {}}, frequency: {}, Q: {}, connect: (next) => next}); +function page() { + const layer = new Node({class: "bubbles"}); + layer.append(new Node({class: "bubble-bar"})); + const out = {stops: 0, cleared: [], vanished: [], selectors: [], made: []}; + const timers = new Map(); + const audio = { + sampleRate: 8000, currentTime: 0, destination: {}, + createBuffer: (channels, frames) => ({getChannelData: () => new Float32Array(frames)}), createBiquadFilter: part, createGain: part, + createBufferSource: () => { + const source = {...part(), ended: null, start: () => {}}; + source.addEventListener = (name, run) => { + source.ended = run; + }; + source.stop = (when) => { + if (when === undefined) { + out.stops += 1; + setImmediate(() => source.ended && source.ended()); + } + }; + return source; + }, + }; + const context = { + Bubbles, out, settings: {bubbles: true}, radioSet: {}, SPEECH_QUEUE: 9, SPEECH_QUIET: 0, SOUND_SLACK: 2, Date, + speech: {pending: [], busy: false, current: null, loading: null, item: null, source: null, timer: 0, warned: 0}, + document: {getElementById: () => layer, querySelectorAll: (selector) => out.selectors.push(selector) && [], fonts: {add: () => null}}, + window: { + innerWidth: 1366, innerHeight: 768, requestAnimationFrame: () => 1, cancelAnimationFrame: () => null, + setTimeout: (run) => { + timers.set(timers.size + 1, run); + return timers.size; + }, + clearTimeout: (id) => out.cleared.push(id), + }, + performance: {now: () => 1000}, CSS: {escape: (value) => value}, g3: {tab: "stream"}, anchor3d: () => () => null, + h: (tag, attrs, ...children) => { + const node = new Node(attrs); + node.append(...children); + if (node.classes.has("speech-bubble")) { + out.made.push(node); + } + return node; + }, + face: (who) => new Node({class: "avatar", "data-face": who}), + iconBtn: (name, label, cls, run, hint) => Object.assign(new Node({class: cls}), {icon: name, label, hint, run}), + vanish: (node) => { + if (node) { + out.vanished.push(node.dataset.who); + node.remove(); + } + }, + nameOf: (key) => `Agent ${key}`, fixed: (value) => value.toFixed(1), FontFace: class {}, toast: () => null, context: () => audio, duck: () => null, drawSpeaker: () => null, + Voice: {enqueue: (pending, next) => [...pending, next], loudness: () => 1}, + RadioSet: {KEYED: ["morse", "gibberlink"], FALLBACKS: ["gibberlink", "morse", "burst"], burst: (gain) => ({gain, seconds: 0.6, frequency: 1800, q: 0.9})}, + }; + vm.createContext(context); + vm.runInContext(code, context); + const run = (script) => vm.runInContext(script, context); + const shown = (who) => out.made.filter((node) => node.dataset.who === who && node.parentElement); + const skip = (who) => shown(who)[0].querySelector(".bubble-skip").run(); + const state = () => ({ + current: context.speech.current ? context.speech.current.who : null, pending: context.speech.pending.map((item) => item.who), busy: context.speech.busy, + quiet: run("bubbles.quiet.map((item) => item.who)"), shown: run("[...bubbles.shown.keys()].map((item) => item.who)"), stops: out.stops, vanished: [...out.vanished], + }); + return {context, out, run, shown, skip, state}; +} +const sounded = (who) => ({who, line: `${who} disk almost full`, words: [who, "disk", "almost", "full"], steps: [{kind: "burst"}], tone: "direct"}); +const silent = (who) => ({who, line: `${who} gate green`, words: [who, "gate", "green"], silent: true}); +(async () => { + const found = {}; + { + const at = page(); + at.context.say(sounded("A"), sounded("B")); + await settle(); + const node = at.shown("A")[0]; + const [head] = node.children; + const button = node.querySelector(".bubble-skip"); + found.node = { + head: head.children.map((child) => [...child.classes].join(" ")), face: head.children[0].dataset.face, icon: button.icon, label: button.label, hint: button.hint, wordsHidden: node.children[1].attrs["aria-hidden"], selectors: [...new Set(at.out.selectors)], + }; + found.before = at.state(); + at.skip("A"); + await settle(); + found.current = {...at.state(), madeA: at.out.made.filter((made) => made.dataset.who === "A").length}; + } + { + const at = page(); + at.context.say(sounded("A"), sounded("B"), sounded("C")); + await settle(); + at.skip("B"); + await settle(); + found.queued = at.state(); + } + { + const at = page(); + at.context.say(silent("A"), silent("B")); + await settle(); + const timer = at.context.speech.timer; + at.skip("A"); + await settle(); + found.silent = {...at.state(), clearedOwnTimer: at.out.cleared.includes(timer), timer: at.context.speech.timer !== timer && at.context.speech.timer > 0}; + } + { + const at = page(); + at.run('quietBubbles([{who: "Q", line: "Q docs green", words: ["Q", "docs", "green"], quiet: true}]); drawBubbles();'); + const timer = at.run("bubbles.quiet[0].timer"); + const before = at.state(); + at.skip("Q"); + at.run("quietBubbles([]); drawBubbles(); drawBubbles();"); + found.quiet = {before, after: at.state(), clearedOwnTimer: at.out.cleared.includes(timer), madeQ: at.out.made.filter((made) => made.dataset.who === "Q").length}; + } + console.log(JSON.stringify(found)); +})(); +""" + + +class TestDockedBubbleSkip(unittest.TestCase): + @classmethod + def setUpClass(cls): + done = subprocess.run(["node", "-e", PROBE, str(BUBBLES), str(SPEECH), str(LAYER)], capture_output=True, text=True, timeout=60, check=False) + if done.returncode != 0: + raise AssertionError(done.stderr[-4000:]) + cls.data = json.loads(done.stdout) + + def test_a_bubble_carries_the_speakers_face_left_of_the_name_and_a_labelled_close_button(self): + node = self.data["node"] + self.assertEqual(node["head"], ["avatar", "bubble-who", "bubble-skip"]) + self.assertEqual((node["face"], node["icon"]), ("A", "bi-x-lg")) + self.assertEqual(node["label"], "Skip message from Agent A") + self.assertIn("Agent A", node["hint"]) + self.assertEqual(node["wordsHidden"], "true") + + def test_the_face_inside_a_bubble_is_never_an_anchor(self): + self.assertEqual(self.data["node"]["selectors"], ['[data-face="A"]:not(#bubbles *)', '[data-face="B"]:not(#bubbles *)']) + + def test_closing_the_message_read_aloud_stops_its_audio_and_the_next_one_starts(self): + self.assertEqual((self.data["before"]["current"], self.data["before"]["pending"]), ("A", ["B"])) + current = self.data["current"] + self.assertEqual((current["stops"], current["current"], current["pending"], current["busy"]), (1, "B", [], True), current) + self.assertEqual((current["vanished"], current["shown"], current["madeA"]), (["A"], ["B"], 1), current) + + def test_closing_a_queued_message_takes_it_off_the_queue_and_leaves_the_voice_playing(self): + queued = self.data["queued"] + self.assertEqual((queued["stops"], queued["current"], queued["pending"], queued["vanished"]), (0, "A", ["C"], ["B"]), queued) + self.assertNotIn("B", queued["shown"]) + + def test_closing_a_silent_reading_ends_it_and_the_next_one_reads(self): + silent = self.data["silent"] + self.assertEqual((silent["current"], silent["pending"], silent["vanished"], silent["stops"]), ("B", [], ["A"], 0), silent) + self.assertEqual((silent["clearedOwnTimer"], silent["timer"]), (True, True), silent) + + def test_closing_a_quiet_bubble_drops_it_and_the_next_poll_does_not_bring_it_back(self): + quiet = self.data["quiet"] + self.assertEqual((quiet["before"]["quiet"], quiet["before"]["shown"]), (["Q"], ["Q"]), quiet) + self.assertEqual((quiet["after"]["quiet"], quiet["after"]["shown"], quiet["after"]["vanished"]), ([], [], ["Q"]), quiet) + self.assertEqual((quiet["clearedOwnTimer"], quiet["madeQ"]), (True, 1), quiet) + + +class TestDockedBubbleStyle(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.rules = rules() + + def test_face_name_and_close_show_only_in_the_bar_with_the_face_first(self): + self.assertEqual(self.rules[".bubble-head"]["display"], "none") + self.assertEqual(self.rules[".bubble-bar .bubble-head"]["display"], "flex") + self.assertNotIn("display", self.rules[".bubble-who"]) + + def test_the_close_button_takes_clicks_through_the_layer_that_ignores_the_pointer(self): + self.assertEqual(self.rules[".bubbles"]["pointer-events"], "none") + self.assertEqual(self.rules[".bubble-skip"]["pointer-events"], "auto") + self.assertEqual(self.rules[".speech-bubble.leaving .bubble-skip"]["pointer-events"], "none") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hub_bubble_front.py b/tests/test_hub_bubble_front.py index feb56cc..a9f1ca5 100644 --- a/tests/test_hub_bubble_front.py +++ b/tests/test_hub_bubble_front.py @@ -59,6 +59,7 @@ const [a, b, c] = ["A", "B", "C"].map(item); const speech = {current: null, loading: null, pending: []}; const context = { Bubbles, speech, document, h, settings: {bubbles: true}, g3: {tab: "stream"}, CSS: {escape: (value) => value}, nameOf: (key) => key, fixed: (value) => value.toFixed(1), + face: () => element("span", {}), iconBtn: () => element("button", {}), performance: {now: () => 5000}, window: {innerWidth: 1366, innerHeight: 768, setTimeout: () => 0, requestAnimationFrame: () => 1, cancelAnimationFrame: () => {}}, }; vm.createContext(context); diff --git a/tests/test_hub_bubbles.py b/tests/test_hub_bubbles.py index eb5230a..4188ed2 100644 --- a/tests/test_hub_bubbles.py +++ b/tests/test_hub_bubbles.py @@ -334,7 +334,7 @@ async function transmitted(steps, cut, row = ROW, broken = "") { } return node; }, - nameOf: (key) => key, fixed: (value) => value.toFixed(1), FontFace: class {}, toast: () => null, context: () => audio, + nameOf: (key) => key, fixed: (value) => value.toFixed(1), FontFace: class {}, toast: () => null, context: () => audio, face: () => new Node({}), iconBtn: () => new Node({}), duck: () => { if (broken === "duck") { throw new Error("no gain node"); @@ -418,7 +418,7 @@ function run(scenario) { node.append(...children); return node; }, - nameOf: (key) => key, fixed: (value) => value.toFixed(1), fetch: async () => ({ok: false, status: 404}), FontFace: class {}, + nameOf: (key) => key, fixed: (value) => value.toFixed(1), fetch: async () => ({ok: false, status: 404}), FontFace: class {}, face: () => new Node({}), iconBtn: () => new Node({}), drawSpeaker: () => null, toast: () => null, saveSettings: () => null, context: () => null, Voice: {enqueue: (pending, next) => [...pending, next]}, SPEECH_QUEUE: 9, SPEECH_QUIET: 0, }; vm.runInNewContext(`${code} @@ -699,7 +699,7 @@ class TestHubBubbles(HubCase): with self.subTest(part=part): self.assertIn(part, toggle) self.assertIn('