feat(orchestrator): hub page for requirements 085 to 099
085 calm Match deck: no header hourglass, centred bare empty state, the release card as a deck card (Cancel, Skip, Release), fixed card height. 086 motion: vanish() fade everywhere with a lint test, view transitions, a lub-dub heartbeat for working objects, confetti that lands and fades. 087 time readout under the pivot of every analog clock. 088 prune dialog grouped by prefix with tri-state boxes, search, stepper and sticky footer. 089 one-row task toolbar with Filter and Actions menus and a filter chip. 090 card border by state colour with a soft glow and owner avatars. 091 draggable limit lines with staged changes and one Save, a Limits menu with the matrix, View toggles, the GPU cause in its tooltip. 093 request chips Open, Expired, Stale, Failed, All and a signed Delete. 094 closed cards leave the deck within 5 s; open in Claude stamps. 095 compact agent message box with Post/Call, attach, mic and Send in the field. 096 Reject on an expired card drops it silently as Drop (expired). 097 Show filter in Match's right-click menu. 098 docked speech bubbles carry the speaker's avatar and a skip button. 099 Match card headlines cut to 120 characters with the full title in the tooltip; the code box keeps the whole command. tests/test_hub_path_links.py: a unicode fixture without German. Full make test green through the queue (2605 tests, ruff, shellcheck, markdownlint). Gate missed on the operator's word: break 7 %, the E2E specs (13 new, 15 updated) run next. 🎯 Fix: 92 % 💥 Break: 7 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 86 🚦 Gate: ⛔ break 7 % > 5 Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8ee52644c8
commit
6323f087bc
95 files changed
+5807
-704
No files matched your search
@@ -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);
|
||||
|
||||
@@ -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") {
|
||||
|
||||
@@ -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)]),
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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()
|
||||
@@ -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], [])
|
||||
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
@@ -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"]])
|
||||
|
||||
@@ -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()
|
||||
@@ -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__":
|
||||
|
||||
@@ -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__":
|
||||
|
||||
@@ -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__":
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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()
|
||||
@@ -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();
|
||||
|
||||
@@ -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__":
|
||||
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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"]))
|
||||
|
||||
Reference in new issue
Block a user