feat(orchestrator): hub requirements 066 to 082 and 084
Radio footer, rules page, schedules editor (System timers and Claude tasks through signed runner jobs), account usage bar, usage explorer with a streamed usage.jsonl, queue Controls tab and override, running tasks on the board, stale task prune with the generic dial, greyed card stamps, commit-tree diffs from the runner preview, VS Code path links, expired asks and decisions that stay as EXPIRED cards (asks keyed by a call digest; an async PostToolUse hook closes those answered in the terminal), the Match refresh hourglass, attachments by paste, drop and paperclip in every text field (page CSP gains img-src blob: for the thumbnails) and the limits board with profiles and a passkey to loosen. Fixes: one red accept on a red-gate commit and no release while a risk is open, the send bar footer segments share one height, the mic button survives a redraw, new Match cards queue before the release card. E2E specs were still running at commit time (operator order); their failures follow as separate fixes. 🎯 Fix: 88 % 💥 Break: 8 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 81 🚦 Gate: ⛔ fix 88 % < 90, break 8 % > 5 (committed on the operator's word) Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dc0d578eca
commit
f356083a24
149 files changed
+10646
-963
No files matched your search
@@ -211,7 +211,8 @@ RULES_OVERLAP = """(async () => {@HELPERS@@CLASHES@
|
||||
open.click();
|
||||
}
|
||||
(await until(() => document.getElementById("controls-tab-rules"), 8000)).click();
|
||||
const rules = await until(() => document.querySelector("#main .rule-form"), 8000);
|
||||
(await until(() => document.querySelector("#main [data-new-rule]"), 8000)).click();
|
||||
const rules = await until(() => document.querySelector("#sheet .rule-form"), 8000);
|
||||
const kind = rules.querySelector("select");
|
||||
const found = {};
|
||||
for (const value of ["decision", "review", "ask"]) {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from test_hub_queue_controls import LEARNED
|
||||
from test_hub_queue_overlay import ROWS, board_council, fake_queue
|
||||
|
||||
FAKE_QUEUE = """import json
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
here = pathlib.Path(__file__)
|
||||
with here.with_suffix(".calls").open("a", encoding="utf-8") as calls:
|
||||
calls.write(" ".join(sys.argv[1:]) + "\\n")
|
||||
shown = {("list", "--json"): "rows.json", ("learned", "--json"): "learned.json"}.get(tuple(sys.argv[1:]))
|
||||
if shown is None:
|
||||
sys.exit(2)
|
||||
sys.stdout.write(here.with_name(shown).read_text(encoding="utf-8"))
|
||||
"""
|
||||
WAITING = "q-2"
|
||||
|
||||
|
||||
def waiting_rows() -> list[dict]:
|
||||
"""Returns:
|
||||
The queue-list fixture with no job overridden yet, q-2 and q-3
|
||||
waiting.
|
||||
"""
|
||||
return [{**row, "override": False} for row in ROWS]
|
||||
|
||||
|
||||
def started_rows() -> list[dict]:
|
||||
"""Returns:
|
||||
waiting_rows() after the override of WAITING was granted: it runs.
|
||||
"""
|
||||
return [{**row, "status": "active", "position": "run", "override": True, "reason": "granted on its last poll"} if row["id"] == WAITING else row for row in waiting_rows()]
|
||||
|
||||
|
||||
def install(case: object, now: float) -> Path:
|
||||
"""Args:
|
||||
case: a HubCase; its council gets the board fixture and its hub the
|
||||
fake queue.py.
|
||||
now: epoch seconds of the fixture.
|
||||
|
||||
Returns:
|
||||
The fake queue.py, printing rows.json for `list --json` and
|
||||
learned.json for `learned --json`.
|
||||
"""
|
||||
case.write_council(board_council(now))
|
||||
script = fake_queue(case.state.parent / "fake-skills", FAKE_QUEUE, waiting_rows())
|
||||
(script.parent / "learned.json").write_text(json.dumps(LEARNED), encoding="utf-8")
|
||||
case.httpd.hub.queue_order.script = script
|
||||
return script
|
||||
|
||||
|
||||
def queue_jobs(case: object) -> list[dict]:
|
||||
return [job for job in case.httpd.hub.jobs.listed() if job.get("kind") == "queue"]
|
||||
@@ -0,0 +1,202 @@
|
||||
"""Exercise requirement 074 in Chromium: the board's running marks, their border and glow, the Running chip, at three widths."""
|
||||
|
||||
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 iso
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/board-running-shots"))
|
||||
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"]],
|
||||
}
|
||||
BORDERS = {"work/alpha": "accent", "queue/q-1": "accent", "work/bravo": "ok", "work/delta": "ok"}
|
||||
READ = """
|
||||
const card = (task) => all("#main .kanban-card").find((node) => node.dataset.task === task) || null;
|
||||
const toggle = () => document.getElementById("kanban-running");
|
||||
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 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();
|
||||
return own.right > host.right + 1 || own.left < host.left - 1;
|
||||
};
|
||||
const read = () => {
|
||||
const cards = all("#main .kanban-card");
|
||||
const button = toggle();
|
||||
return {
|
||||
cards: cards.map((node) => node.dataset.task).sort(),
|
||||
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"),
|
||||
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,
|
||||
wide: document.documentElement.scrollWidth > window.innerWidth + 1,
|
||||
};
|
||||
};
|
||||
"""
|
||||
BOARD = """(async () => {@HELPERS@@READ@
|
||||
if (!(await until(() => card("work/delta") && card("work/delta").querySelector(".kanban-mark") && toggle(), 10000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
await sleep(400);
|
||||
card("work/delta").scrollIntoView({block: "center"});
|
||||
return read();
|
||||
})()"""
|
||||
FILTER = """(async () => {@HELPERS@@READ@
|
||||
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();
|
||||
toggle().click();
|
||||
await until(() => toggle().getAttribute("aria-pressed") === "false" && all("#main .kanban-card").length > @MARKED@, 4000);
|
||||
return {only, back: read()};
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str) -> str:
|
||||
return template.replace("@HELPERS@", base.HELPERS).replace("@READ@", READ).replace("@MARKED@", str(len(MARKED)))
|
||||
|
||||
|
||||
def board_council(now: float) -> dict:
|
||||
"""Returns:
|
||||
A register whose work/alpha holds an active queue job, work/bravo
|
||||
a worker and work/delta an R with a fresh beat, work/charlie a
|
||||
worker whose beat is 10 minutes old, and work/echo nothing.
|
||||
"""
|
||||
return {
|
||||
"rasci.json": {
|
||||
"work/alpha": {"title": "Alpha", "status": "running", "worker": "Stage", "prio": 1},
|
||||
"work/bravo": {"title": "Bravo", "status": "running", "worker": "Docs", "prio": 2},
|
||||
"work/charlie": {"title": "Charlie", "status": "queued", "worker": "Late"},
|
||||
"work/delta": {"title": "Delta", "status": "running", "worker": "Main", "roles": {"Skills": "R", "Main": "A"}},
|
||||
"work/echo": {"title": "Echo", "status": "queued", "worker": "-"},
|
||||
},
|
||||
"queue.json": {"seq": 1, "entries": [
|
||||
{"id": "q-1", "seq": 1, "cmd": "make test", "kind": "test", "task": "work/alpha", "name": "Stage", "hotfix": None, "status": "active", "enqueued": now - 200, "granted": now - 100},
|
||||
]},
|
||||
"work/delta/claim.json": {"session": "c-skills", "runtime": "claude", "name": "Skills", "since": iso(now - 600), "beat": now - 60, "work": "delta"},
|
||||
}
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestBoardRunning(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
now = time.time()
|
||||
self.write_council(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\nsecond line", "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 steps(self) -> list[dict]:
|
||||
local = f"http://localhost:{self.port}/"
|
||||
steps = []
|
||||
for width, height in base.WIDTHS:
|
||||
steps += [
|
||||
{"width": width, "height": height, "url": f"{local}?{width}#tasks/board", "wait": 1500, "probe": probe(BOARD), "shot": str(OUT / f"chromium-{width}-running-board.png")},
|
||||
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(FILTER), "shot": str(OUT / f"chromium-{width}-running-filter.png")},
|
||||
{"width": width, "height": height, "url": f"{local}?{width}-calm#tasks/board", "wait": 1500, "probe": probe(BOARD), "shot": str(OUT / f"chromium-{width}-running-reduced-motion.png"), "media": CALM},
|
||||
]
|
||||
return steps
|
||||
|
||||
def check_marks(self, read: dict, shown: list[str]) -> None:
|
||||
for task in shown:
|
||||
with self.subTest(task=task):
|
||||
first, keys, chips = read["marks"][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)))
|
||||
self.assertEqual([chip[:3] for chip in chips], [chip[:3] for chip in wanted])
|
||||
for (_, _, _, shown_text, label, title), (_, _, _, pattern, word) in zip(chips, wanted, strict=True):
|
||||
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})
|
||||
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):
|
||||
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], [])
|
||||
results = iter(data["results"])
|
||||
for width, _ in base.WIDTHS:
|
||||
with self.subTest(width=width):
|
||||
board, filtered, calm = next(results), next(results), next(results)
|
||||
self.check_board(board, True)
|
||||
self.assertNotIn("error", filtered, filtered)
|
||||
only = filtered["only"]
|
||||
self.assertEqual(only["cards"], MARKED)
|
||||
self.check_marks(only, MARKED)
|
||||
self.assertEqual(only["toggle"][:3], ["Running", "true", str(len(MARKED))])
|
||||
self.assertIn("only these shown", only["toggle"][3])
|
||||
self.assertEqual(filtered["back"]["cards"], sorted(MARKED + UNMARKED))
|
||||
self.check_board(calm, False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,138 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
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_match_review_e2e as matched
|
||||
from hub_case import HubCase
|
||||
from hub_support import iso
|
||||
from test_hub_match import git, merge_repo
|
||||
from test_hub_operator_tasks import rules_dir, staged_diff
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/commit-tree-diff-shots"))
|
||||
MISSING = "0" * 40
|
||||
SHOWN = "operator:operator/commit-tree"
|
||||
BROKEN = "operator:operator/commit-tree-missing"
|
||||
ROW = {"description": "commit the feature tree", "check": "done", "roles": {"Skills": "A", "Operator": "R"}}
|
||||
DIFF = """(async () => {@HELPERS@@CARD@
|
||||
await screenShown(8000);
|
||||
await until(card, 8000);
|
||||
const shown = await pick("@SHOWN@");
|
||||
await sleep(400);
|
||||
if (!shown) {
|
||||
return {error: text(document.getElementById("main")).slice(0, 300)};
|
||||
}
|
||||
const box = shown.querySelector(".code-box");
|
||||
const eye = box.querySelector(".code-eye");
|
||||
const state = () => ({open: box.dataset.open, expanded: eye.getAttribute("aria-expanded")});
|
||||
const first = state();
|
||||
eye.click();
|
||||
await sleep(250);
|
||||
const hidden = state();
|
||||
eye.click();
|
||||
await sleep(250);
|
||||
const line = shown.querySelector(".match-merge");
|
||||
return {
|
||||
files: all(".match-file", box).map((file) => file.dataset.path), added: all(".match-file tr", box).some((row) => text(row).includes("added = 2")),
|
||||
line: text(line), kind: line ? line.dataset.kind : null, failed: line ? line.dataset.error : null, first, hidden, again: state(),
|
||||
wide: document.documentElement.scrollWidth > innerWidth + 1,
|
||||
};
|
||||
})()"""
|
||||
ERROR = """(async () => {@HELPERS@@CARD@
|
||||
await screenShown(8000);
|
||||
await until(card, 8000);
|
||||
const shown = await pick("@BROKEN@");
|
||||
await sleep(400);
|
||||
if (!shown) {
|
||||
return {error: text(document.getElementById("main")).slice(0, 300)};
|
||||
}
|
||||
const line = shown.querySelector(".match-merge");
|
||||
return {line: text(line), failed: line ? line.dataset.error : null, files: all(".match-file", shown).length, none: text(shown.querySelector(".code-box p.muted")),
|
||||
wide: document.documentElement.scrollWidth > innerWidth + 1};
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str, **names: str) -> str:
|
||||
fills = {"@HELPERS@": base.HELPERS, "@CARD@": matched.CARD, **{f"@{key.upper()}@": value for key, value in names.items()}}
|
||||
for key, value in fills.items():
|
||||
template = template.replace(key, value)
|
||||
return template
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestCommitTreeDiff(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
work = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(work.cleanup)
|
||||
repo, target = merge_repo(Path(work.name))
|
||||
tree = git(repo, "rev-parse", f"{target}^{{tree}}").strip()
|
||||
self.parent = git(repo, "rev-parse", "main").strip()
|
||||
now = time.time()
|
||||
self.write_council({
|
||||
"work/s1/claim.json": {"office": "work/s1", "session": "s1", "runtime": "claude", "name": "Skills", "since": iso(now - 86400), "beat": now, "work": "commit-tree"},
|
||||
"rasci.json": {
|
||||
"operator/commit-tree": {**ROW, "title": f"git commit-tree {tree} -p {self.parent} -m 'feat: added'", "workdir": str(repo)},
|
||||
"operator/commit-tree-missing": {**ROW, "title": f"git commit-tree {MISSING} -p {self.parent} -m 'feat: gone'", "workdir": str(repo)},
|
||||
},
|
||||
})
|
||||
home = self.outside / "medusa-home"
|
||||
rules_dir(home / staged_diff.RULES_HOME.relative_to(Path.home()) / Path(staged_diff.RULES_TAIL.replace("*", "")).parent)
|
||||
with mock.patch.dict(os.environ, {"HOME": str(home), "XDG_CACHE_HOME": str(home / ".cache")}):
|
||||
self.run_runner(register=False)
|
||||
self.base = f"http://{self.host}/"
|
||||
|
||||
def steps(self, browser: str) -> list[dict]:
|
||||
steps = []
|
||||
for width, height in base.WIDTHS:
|
||||
at = {"width": width, "height": height}
|
||||
shot = OUT / f"{browser}-{width}"
|
||||
steps += [
|
||||
{**at, "url": f"{self.base}?{width}-diff#tasks/match", "wait": 1500, "probe": probe(DIFF, shown=SHOWN), "shot": f"{shot}-commit-tree-diff.png"},
|
||||
{**at, "url": f"{self.base}?{width}-error#tasks/match", "wait": 1500, "probe": probe(ERROR, broken=BROKEN), "shot": f"{shot}-commit-tree-error.png"},
|
||||
]
|
||||
return steps
|
||||
|
||||
def check(self, data: dict, browser: str) -> None:
|
||||
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
|
||||
results = iter(data["results"])
|
||||
for width, _ in base.WIDTHS:
|
||||
shown, broken = next(results), next(results)
|
||||
with self.subTest(browser=browser, width=width, step="diff"):
|
||||
self.assertNotIn("error", shown, shown)
|
||||
self.assertEqual((shown["files"], shown["added"], shown["kind"], shown["failed"], shown["wide"]), (["app.py"], True, "commit-tree", "false", False), shown)
|
||||
self.assertIn(f"onto parent {self.parent[:12]}", shown["line"])
|
||||
self.assertEqual((shown["first"], shown["hidden"], shown["again"]), ({"open": "true", "expanded": "true"}, {"open": "false", "expanded": "false"}, {"open": "true", "expanded": "true"}), shown)
|
||||
with self.subTest(browser=browser, width=width, step="error"):
|
||||
self.assertNotIn("error", broken, broken)
|
||||
self.assertEqual((broken["failed"], broken["files"], broken["none"], broken["wide"]), ("true", 0, "No diff to show.", False), broken)
|
||||
self.assertIn(f"No commit-tree diff: git cat-file -t {MISSING} failed: fatal: Not a valid object name {MISSING}", broken["line"])
|
||||
|
||||
def test_chromium_shows_the_commit_tree_diff_its_eye_toggle_and_the_git_error_line(self):
|
||||
data = self.drive(self.steps("chromium"), None)
|
||||
(OUT / "chromium-commit-tree-diff.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.check(data, "chromium")
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
|
||||
def test_firefox_shows_the_commit_tree_diff_its_eye_toggle_and_the_git_error_line(self):
|
||||
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"))
|
||||
(OUT / "firefox-commit-tree-diff.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.check(data, "firefox")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -23,6 +23,9 @@ BROKEN = {PRESENT[3], PRESENT[7]}
|
||||
READ = """
|
||||
const box = () => document.querySelector("#main .fw-controls");
|
||||
const tab = (id) => document.getElementById(`controls-tab-${id}`);
|
||||
const unfold = () => all("#main details[data-fold]").forEach((fold) => {
|
||||
fold.open = true;
|
||||
});
|
||||
const flush = () => {
|
||||
const head = box().querySelector(":scope > .box-head");
|
||||
const main = document.getElementById("main");
|
||||
@@ -46,6 +49,7 @@ RULES = """(async () => {@HELPERS@@READ@
|
||||
return {error: text(document.getElementById("main")), sources: sources()};
|
||||
}
|
||||
tab("rules").click();
|
||||
unfold();
|
||||
const folded = {sources: sources(), toggle: text(toggle()), pressed: toggle().getAttribute("aria-pressed")};
|
||||
toggle().click();
|
||||
await until(() => sources().length === 40, 4000);
|
||||
@@ -55,7 +59,8 @@ RULES = """(async () => {@HELPERS@@READ@
|
||||
return {folded, opened, flush: flush(), rules: width("Firewall rules"), forms: forms(), multiple: all("#main select[multiple]").length, wide: wide()};
|
||||
})()"""
|
||||
GROUPS = """(async () => {@HELPERS@@READ@
|
||||
tab("groups").click();
|
||||
tab("rules").click();
|
||||
unfold();
|
||||
const form = await until(() => width("Agent groups") && document.querySelector('#main form[aria-label="New agent group"]'), 4000);
|
||||
const chips = all('[aria-label="Members"] label.check-chip', form);
|
||||
const faces = chips.filter((chip) => chip.querySelector(".avatar svg")).length;
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
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_match_rejects_e2e as rejects
|
||||
import test_match_review_e2e as matched
|
||||
from hub_case import HubCase
|
||||
from hub_support import HOST_STATE
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-082-shots"))
|
||||
MARK = "📎 "
|
||||
INIT = """() => {
|
||||
window.e2eUploads = 0;
|
||||
const real = window.fetch.bind(window);
|
||||
window.fetch = (input, options) => {
|
||||
if (String(input && input.url ? input.url : input).startsWith("/api/uploads")) {
|
||||
window.e2eUploads += 1;
|
||||
}
|
||||
return real(input, options);
|
||||
};
|
||||
}"""
|
||||
FIELD = """
|
||||
const LIMIT = 50 * 1024 * 1024;
|
||||
const wide = () => document.documentElement.scrollWidth > innerWidth + 1;
|
||||
const pngFile = async (name) => {
|
||||
const canvas = document.createElement("canvas");
|
||||
Object.assign(canvas, {width: 24, height: 16});
|
||||
const paint = canvas.getContext("2d");
|
||||
paint.fillStyle = "#c33";
|
||||
paint.fillRect(0, 0, 24, 16);
|
||||
const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/png"));
|
||||
return new File([blob], name, {type: "image/png"});
|
||||
};
|
||||
const carry = (files, words) => {
|
||||
const transfer = new DataTransfer();
|
||||
files.forEach((file) => transfer.items.add(file));
|
||||
if (words) {
|
||||
transfer.setData("text/plain", words);
|
||||
}
|
||||
return transfer;
|
||||
};
|
||||
const lineOf = (field, pattern) => field.value.split("\\n").find((line) => pattern.test(line)) || null;
|
||||
const choose = (picker, file) => {
|
||||
picker.files = carry([file]).files;
|
||||
picker.dispatchEvent(new Event("change", {bubbles: true}));
|
||||
};
|
||||
const exercise = async (field) => {
|
||||
const frame = await until(() => field.closest(".mic-frame"), 4000);
|
||||
if (!frame) {
|
||||
return {error: "field not framed"};
|
||||
}
|
||||
field.focus();
|
||||
const before = window.e2eUploads;
|
||||
const plainValue = field.value;
|
||||
const plain = new ClipboardEvent("paste", {clipboardData: carry([], "plain words"), bubbles: true, cancelable: true});
|
||||
field.dispatchEvent(plain);
|
||||
await sleep(300);
|
||||
const textPaste = {prevented: plain.defaultPrevented, uploads: window.e2eUploads - before, same: field.value === plainValue};
|
||||
field.dispatchEvent(new ClipboardEvent("paste", {clipboardData: carry([await pngFile("image.png")]), bubbles: true, cancelable: true}));
|
||||
const placeholder = lineOf(field, /^📎 uploading paste-\\d{8}-\\d{6}\\.png…$/);
|
||||
const pasted = await until(() => lineOf(field, /^📎 \\/.*\\/paste-\\d{8}-\\d{6}\\.png$/), 8000);
|
||||
const drop = new DragEvent("drop", {dataTransfer: carry([new File(["dropped notes\\n"], "notes.txt", {type: "text/plain"})]), bubbles: true, cancelable: true});
|
||||
field.dispatchEvent(drop);
|
||||
const dropped = await until(() => lineOf(field, /^📎 \\/.*\\/notes\\.txt$/), 8000);
|
||||
const picker = frame.querySelector(".mic-attach-file");
|
||||
const button = frame.querySelector(".mic-foot > .mic-attach");
|
||||
choose(picker, new File(["# picked\\n"], "picked.md", {type: "text/markdown"}));
|
||||
const picked = await until(() => lineOf(field, /^📎 \\/.*\\/picked\\.md$/), 8000);
|
||||
await until(() => frame.querySelectorAll(".mic-chip").length === 3, 4000);
|
||||
const thumb = frame.querySelector(".mic-chip img.mic-chip-thumb");
|
||||
await until(() => thumb && thumb.complete && thumb.naturalWidth > 0, 4000);
|
||||
const chips = all(".mic-chip", frame).map((chip) => ({path: chip.dataset.path, thumb: Boolean(chip.querySelector("img.mic-chip-thumb")), icon: Boolean(chip.querySelector(":scope > svg.bi"))}));
|
||||
const row = frame.querySelector(":scope > .mic-chips");
|
||||
const layout = {aboveFoot: Boolean(row) && row.nextElementSibling === frame.querySelector(":scope > .mic-foot"), beforeMic: Boolean(button) && button.nextElementSibling && button.nextElementSibling.matches("button.mic"), icon: Boolean(button && button.querySelector('use[href="#bi-paperclip"]'))};
|
||||
const overBefore = window.e2eUploads;
|
||||
choose(picker, new File([new Uint8Array(LIMIT + 1)], "big.bin"));
|
||||
const over = await until(() => lineOf(field, /^⚠️ big\\.bin: /), 4000);
|
||||
const overUploads = window.e2eUploads - overBefore;
|
||||
const overPath = lineOf(field, /^📎 \\/.*big\\.bin$/);
|
||||
const gone = all(".mic-chip", frame).find((chip) => chip.dataset.path.endsWith("/notes.txt"));
|
||||
gone.querySelector(".mic-chip-drop").click();
|
||||
await sleep(150);
|
||||
const lines = field.value.split("\\n");
|
||||
return {
|
||||
textPaste, placeholder, pasted, dropped, picked, chips, layout, thumbLoaded: Boolean(thumb && thumb.naturalWidth > 0),
|
||||
over, overUploads, overPath,
|
||||
removed: {line: lines.includes(dropped), chips: frame.querySelectorAll(".mic-chip").length, kept: [pasted, picked].every((line) => lines.includes(line))},
|
||||
wide: wide(),
|
||||
};
|
||||
};
|
||||
"""
|
||||
REJECT = """(async () => {@HELPERS@@CARD@@STEPS@@FIELD@
|
||||
await screenShown(8000);
|
||||
if (!(await until(card, 8000))) {
|
||||
return {error: text(document.getElementById("main")).slice(0, 300)};
|
||||
}
|
||||
await sleep(300);
|
||||
await actionable();
|
||||
key("ArrowLeft");
|
||||
const field = await until(() => document.querySelector(".match-feedback"), 4000);
|
||||
if (!field) {
|
||||
return {error: "no reject feedback field"};
|
||||
}
|
||||
return exercise(field);
|
||||
})()"""
|
||||
COMPOSER = """(async () => {@HELPERS@@FIELD@
|
||||
const field = await until(() => document.querySelector("#radio-spot form.composer textarea"), 15000);
|
||||
if (!field) {
|
||||
return {error: "no composer"};
|
||||
}
|
||||
return exercise(field);
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str) -> str:
|
||||
return template.replace("@HELPERS@", base.HELPERS).replace("@CARD@", matched.CARD).replace("@STEPS@", rejects.STEPS).replace("@FIELD@", FIELD)
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestFieldAttachments(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
cards = matched.TestMatchReview.cards
|
||||
review = matched.TestMatchReview.review
|
||||
payload = matched.TestMatchReview.payload
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
self.cards()
|
||||
self.base = f"http://localhost:{self.port}/"
|
||||
|
||||
def stored(self, line: str) -> Path:
|
||||
self.assertTrue(line and line.startswith(MARK), line)
|
||||
return self.state / Path(line[len(MARK):]).relative_to(HOST_STATE)
|
||||
|
||||
def check(self, found: dict) -> None:
|
||||
self.assertNotIn("error", found, found)
|
||||
self.assertEqual(found["textPaste"], {"prevented": False, "uploads": 0, "same": True}, found)
|
||||
self.assertIsNotNone(found["placeholder"], found)
|
||||
for key in ("pasted", "dropped", "picked"):
|
||||
with self.subTest(line=key):
|
||||
self.assertTrue(self.stored(found[key]).is_file(), found[key])
|
||||
self.assertEqual(self.stored(found["pasted"]).read_bytes()[:8], b"\x89PNG\r\n\x1a\n")
|
||||
self.assertEqual(self.stored(found["dropped"]).read_text(encoding="utf-8"), "dropped notes\n")
|
||||
self.assertEqual([(chip["thumb"], chip["icon"]) for chip in found["chips"]], [(True, False), (False, True), (False, True)], found["chips"])
|
||||
self.assertTrue(found["thumbLoaded"], found)
|
||||
self.assertEqual(found["layout"], {"aboveFoot": True, "beforeMic": True, "icon": True}, found)
|
||||
self.assertEqual((found["over"], found["overUploads"], found["overPath"]), ("⚠️ big.bin: too large, at most 50 MiB", 0, None), found)
|
||||
self.assertEqual(found["removed"], {"line": False, "chips": 2, "kept": True}, found)
|
||||
self.assertFalse(found["wide"], found)
|
||||
|
||||
def test_chromium_attaches_by_paste_drop_and_picker_in_the_reject_feedback_and_the_composer_at_three_widths(self):
|
||||
steps = []
|
||||
for width, height in base.WIDTHS:
|
||||
shot = OUT / f"chromium-{width}"
|
||||
steps += [
|
||||
{"width": width, "height": height, "url": f"{self.base}?{width}-reject#tasks/match", "wait": 1500, "probe": probe(REJECT), "shot": f"{shot}-reject.png"},
|
||||
{"width": width, "height": height, "url": f"{self.base}?{width}-radio#stream/radio", "wait": 1200, "probe": probe(COMPOSER), "shot": f"{shot}-composer.png"},
|
||||
]
|
||||
data = self.drive(steps, None, init=INIT)
|
||||
(OUT / "chromium-field-attachments.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"])
|
||||
for width, _ in base.WIDTHS:
|
||||
for view in ("reject", "composer"):
|
||||
with self.subTest(width=width, view=view):
|
||||
self.check(next(results))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -26,7 +26,12 @@ SHOW = """(async () => {@HELPERS@
|
||||
const tabs = () => all('#main [role="tab"]').map((node) => [node.dataset.tab, node.getAttribute("aria-selected"), document.getElementById(node.getAttribute("aria-controls")).hidden]);
|
||||
const first = tabs();
|
||||
document.querySelector('#main [role="tab"][data-tab="rules"]').click();
|
||||
const ready = await until(() => all("#main table.fw-table tbody[data-source]").length > 1, 10000);
|
||||
const sections = ["settings", "patterns", "groups", "sets"].map((id) => document.querySelector(`#main details[data-fold="${id}"]`));
|
||||
const collapsed = sections.map((node) => Boolean(node) && !node.open);
|
||||
sections.forEach((node) => {
|
||||
node.open = true;
|
||||
});
|
||||
const ready = await until(() => all("#main table.fw-table tbody[data-source]").length > 0, 10000);
|
||||
if (!ready) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
@@ -43,10 +48,15 @@ SHOW = """(async () => {@HELPERS@
|
||||
chip("deny").click();
|
||||
const withoutDeny = {pressed: chip("deny").getAttribute("aria-pressed"), deny: rows().filter((node) => node.dataset.filter === "deny").length, rows: rows().length};
|
||||
chip("deny").click();
|
||||
document.querySelector("#main [data-new-rule]").click();
|
||||
const sheet = await until(() => document.querySelector("#sheet .rule-form"), 4000);
|
||||
const targets = sheet ? all('select[aria-label="Applies to"] option', sheet).map(text) : null;
|
||||
document.querySelector("#sheet .sheet-head button").click();
|
||||
const wrap = document.querySelector("#main .fw-table-wrap");
|
||||
wrap.scrollIntoView({block: "start"});
|
||||
await sleep(100);
|
||||
return {
|
||||
collapsed,
|
||||
title: text(document.querySelector("#main .box-head h2.box-title")),
|
||||
tabs: {first, picked: tabs()},
|
||||
subs: all("#tabs .subtabs button").map(name),
|
||||
@@ -59,7 +69,7 @@ SHOW = """(async () => {@HELPERS@
|
||||
heads: all("#main table.fw-table thead th").map(text),
|
||||
chips: all('#main [aria-label="Show rules"] button').map((node) => [node.dataset.filter, node.getAttribute("aria-pressed")]),
|
||||
patterns: all('#main [aria-label="Never granted"] li').length,
|
||||
targets: all('#main .rule-form select[aria-label="Applies to"] option').map(text),
|
||||
targets,
|
||||
unlabelled: all("#main svg.bi").map(owned).filter((owner) => !owner || (!text(owner) && !(owner.getAttribute("title") && owner.getAttribute("aria-label")))).length,
|
||||
secret: document.documentElement.innerHTML.includes("@SECRET@"),
|
||||
wide: document.documentElement.scrollWidth > innerWidth + 1,
|
||||
@@ -157,9 +167,16 @@ GROUP_RULE = """(async () => {@HELPERS@
|
||||
form.requestSubmit();
|
||||
return until(() => all('#main [aria-label="Staged changes"] li').find((node) => node.dataset.staged === `add ${entry}`), 8000);
|
||||
};
|
||||
const unfold = () => all("#main details[data-fold]").forEach((fold) => {
|
||||
fold.open = true;
|
||||
});
|
||||
const openForm = async () => {
|
||||
document.querySelector("#main [data-new-rule]").click();
|
||||
return until(() => document.querySelector("#sheet .rule-form"), 8000);
|
||||
};
|
||||
await screenShown(8000);
|
||||
await until(() => document.querySelector('#main form[aria-label="New agent group"]'), 10000);
|
||||
(await until(() => document.querySelector('#main tbody[data-source="hub"] .fw-fold'), 10000)).click();
|
||||
unfold();
|
||||
const group = document.querySelector('#main form[aria-label="New agent group"]');
|
||||
group.querySelector('input[aria-label="Group name"]').value = "builders";
|
||||
for (const box of group.querySelectorAll('[aria-label="Members"] input[type="checkbox"]')) {
|
||||
@@ -167,7 +184,7 @@ GROUP_RULE = """(async () => {@HELPERS@
|
||||
}
|
||||
group.requestSubmit();
|
||||
const row = await until(() => document.querySelector('#main [data-group="builders"]'), 8000);
|
||||
const rules = document.querySelector("#main .rule-form");
|
||||
const rules = await openForm();
|
||||
const target = rules.querySelector('select[aria-label="Applies to"]');
|
||||
const choice = await until(() => [...target.options].find((option) => option.value.startsWith("group:")), 8000);
|
||||
if (!row || !choice) {
|
||||
@@ -176,10 +193,11 @@ GROUP_RULE = """(async () => {@HELPERS@
|
||||
target.value = choice.value;
|
||||
rules.querySelector('input[placeholder="make test*"]').value = "make e2e";
|
||||
rules.requestSubmit();
|
||||
const ruleRow = () => all("#main tr[data-rule]").find((node) => all("code", node).some((code) => text(code) === "make e2e"));
|
||||
const pill = await until(() => all("#main tr[data-rule] [data-agents]").find((node) => text(node) === "group builders"), 15000);
|
||||
const hits = await until(() => ruleRow() && text(ruleRow().querySelector(".fw-hits")) !== "…" && text(ruleRow().querySelector(".fw-hits")), 8000);
|
||||
const found = {group: text(row.querySelector("strong")), members: text(row.querySelector(".muted")), pills: all("#main tr[data-rule] [data-agents]").map(text), found: Boolean(pill), hits, toasts: all("#toasts .toast").map(text)};
|
||||
const ruleRow = () => all("#main li.hub-rule").find((node) => all("code", node).some((code) => text(code) === "make e2e"));
|
||||
const pill = await until(() => all("#main li.hub-rule [data-agents]").find((node) => text(node) === "group builders"), 15000);
|
||||
unfold();
|
||||
const hits = await until(() => ruleRow() && text(ruleRow().querySelector(".hub-rule-count")), 8000);
|
||||
const found = {group: text(document.querySelector('#main [data-group="builders"] strong')), members: text(document.querySelector('#main [data-group="builders"] .muted')), pills: all("#main li.hub-rule [data-agents]").map(text), found: Boolean(pill), hits, sheet: Boolean(document.querySelector("#sheet .rule-form")), toasts: all("#toasts .toast").map(text)};
|
||||
const sets = document.querySelector('#main form[aria-label="New rule set"]');
|
||||
sets.querySelector('input[aria-label="Set name"]').value = "ci";
|
||||
for (const box of sets.querySelectorAll('[aria-label="Rules"] input[type="checkbox"]')) {
|
||||
@@ -195,8 +213,8 @@ GROUP_RULE = """(async () => {@HELPERS@
|
||||
found.kept = setState();
|
||||
setTake().click();
|
||||
found.taken = await until(() => all("#toasts .toast").map(text).find((line) => line.startsWith("ci:")), 15000);
|
||||
found.reloaded = await until(() => setRow() && setTarget().value.startsWith("group:") && document.querySelector("#main .rule-form") && setState(), 8000);
|
||||
const form = document.querySelector("#main .rule-form");
|
||||
found.reloaded = await until(() => setRow() && setTarget().value.startsWith("group:") && document.querySelector("#main .hub-rule-list") && setState(), 8000);
|
||||
const form = await openForm();
|
||||
const picker = form.querySelector('select[aria-label="Applies to"]');
|
||||
const sign = form.querySelector("[data-sign]");
|
||||
choose(picker, groupValue(picker));
|
||||
@@ -214,14 +232,14 @@ GROUP_RULE = """(async () => {@HELPERS@
|
||||
found.setGone = setState();
|
||||
setTake().click();
|
||||
await sleep(500);
|
||||
found.sent = sent.filter((url) => url.startsWith("/api/rules"));
|
||||
found.sent = sent.filter((url) => url.startsWith("/api/rules") && url !== "/api/rules/match");
|
||||
choose(picker, "all");
|
||||
found.again = {value: picker.value, valid: picker.checkValidity(), blocked: sign.disabled, options: [...picker.options].map((option) => option.value).includes("gone")};
|
||||
const toggle = (label) => ruleRow() && [...ruleRow().querySelectorAll("button")].find((button) => text(button) === label);
|
||||
toggle("Turn off").click();
|
||||
found.off = Boolean(await until(() => toggle("Turn on"), 8000));
|
||||
toggle("Turn on").click();
|
||||
found.on = Boolean(await until(() => toggle("Turn off"), 15000));
|
||||
const toggle = () => ruleRow().querySelector("input.switch");
|
||||
toggle().click();
|
||||
found.off = Boolean(await until(() => ruleRow() && ruleRow().dataset.on === "false" && !toggle().checked, 8000));
|
||||
toggle().click();
|
||||
found.on = Boolean(await until(() => ruleRow() && ruleRow().dataset.on === "true" && toggle().checked, 15000));
|
||||
found.prompts = prompts;
|
||||
return found;
|
||||
})()"""
|
||||
@@ -290,12 +308,13 @@ class TestFirewallE2E(HubCase):
|
||||
with self.subTest(width=width):
|
||||
self.assertNotIn("error", shown, shown)
|
||||
self.assertEqual((shown["title"], shown["subs"]), ("Controls", base.SUBS))
|
||||
self.assertEqual(shown["tabs"], {"first": [["tools", "true", False], ["rules", "false", True], ["groups", "false", True], ["schedules", "false", True]], "picked": [["tools", "false", True], ["rules", "true", False], ["groups", "false", True], ["schedules", "false", True]]})
|
||||
self.assertEqual(shown["sources"], ["hub", str(self.settings)])
|
||||
self.assertEqual(shown["folded"], {"expanded": ["false"] * 2, "rows": 0})
|
||||
self.assertEqual(shown["opened"], ["true"] * 2)
|
||||
self.assertEqual(shown["tabs"], {"first": [["tools", "true", False], ["rules", "false", True], ["schedules", "false", True]], "picked": [["tools", "false", True], ["rules", "true", False], ["schedules", "false", True]]})
|
||||
self.assertEqual(shown["collapsed"], [True] * 4)
|
||||
self.assertEqual(shown["sources"], [str(self.settings)])
|
||||
self.assertEqual(shown["folded"], {"expanded": ["false"], "rows": 0})
|
||||
self.assertEqual(shown["opened"], ["true"])
|
||||
self.assertEqual(shown["heads"], ["Action", "Tool", "Pattern", "Scope", "Source", "Hits (7 days)", ""])
|
||||
self.assertEqual(shown["chips"], [[chip, "true"] for chip in ("allow", "ask", "deny", "sandbox", "signed")])
|
||||
self.assertEqual(shown["chips"], [[chip, "true"] for chip in ("allow", "ask", "deny", "sandbox")])
|
||||
rows = shown["rows"]
|
||||
self.assertEqual([row[0] for row in rows], sorted((row[0] for row in rows), key=["deny", "ask", "allow", "sandbox"].index))
|
||||
for row in (
|
||||
@@ -364,7 +383,7 @@ class TestFirewallE2E(HubCase):
|
||||
self.assertEqual(data["errors"], [])
|
||||
found = data["results"][0]
|
||||
self.assertNotIn("error", found, found)
|
||||
self.assertEqual((found["group"], found["members"], found["found"], found["hits"]), ("builders", "Skills, Stage", True, "0 unused"), found)
|
||||
self.assertEqual((found["group"], found["members"], found["found"], found["hits"], found["sheet"]), ("builders", "Skills, Stage", True, "0 of the last 0 asks", False), found)
|
||||
stored = [rule for rule in self.httpd.hub.rules.listed() if rule["pattern"] == "make e2e"]
|
||||
self.assertEqual([(rule["agents"], rule["proof"]["payload"]["agents"]) for rule in stored], [(["s1", "s2"], ["s1", "s2"])] * 2)
|
||||
for rule in stored:
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
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
|
||||
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"
|
||||
AGO = 690
|
||||
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])]);
|
||||
}
|
||||
return send(path, init);
|
||||
};
|
||||
const card = () => document.querySelector("#main .match-card.front");
|
||||
const front = () => (card() ? card().dataset.card : null);
|
||||
if (!(await until(card, 8000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
const key = (name) => document.body.dispatchEvent(new KeyboardEvent("keydown", {key: name, bubbles: true, cancelable: true}));
|
||||
const id = front();
|
||||
const stamp = card().querySelector(".match-stamp");
|
||||
if (!stamp) {
|
||||
return {id, stamp: null};
|
||||
}
|
||||
stamp.dispatchEvent(new MouseEvent("mouseenter"));
|
||||
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)));
|
||||
await sleep(500);
|
||||
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"};
|
||||
}
|
||||
feedback.value = "@FEEDBACK@";
|
||||
document.querySelector(".sheet-box .match-feedback-reject").click();
|
||||
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]) : [];
|
||||
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);
|
||||
found.emptied = Boolean(await until(() => document.querySelector("#main .match-stack .empty"), 15000));
|
||||
found.posted = posted;
|
||||
}
|
||||
return found;
|
||||
})()"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestMatchExpired(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
authenticator = base.OrchestratorE2ECase.authenticator
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.claim("s1", "Skills session")
|
||||
self.ask = self.create_ask({**ASK, "call_key": signing.call_key("Bash", {"command": ASK["command"]})})
|
||||
self.httpd.hub.asks.change(self.ask, {"expires": time.time() - AGO})
|
||||
|
||||
def radio(self) -> list[list[str]]:
|
||||
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")
|
||||
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):
|
||||
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.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)
|
||||
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.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]]
|
||||
self.assertGreater(max(channels) - min(channels), 20, found)
|
||||
self.assertEqual((found["accept"], found["reject"]), (True, False), found)
|
||||
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.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])
|
||||
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"]])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,148 @@
|
||||
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
|
||||
from hub_case import HubCase
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-081-hourglass-shots"))
|
||||
REDUCED = [{"name": "prefers-reduced-motion", "value": "reduce"}]
|
||||
SPY = """() => {
|
||||
const real = window.fetch.bind(window);
|
||||
window.matchFetches = [];
|
||||
window.fetch = (input, options) => {
|
||||
const url = typeof input === "string" ? input : input.url;
|
||||
if (new URL(url, window.location.href).pathname === "/api/match") {
|
||||
window.matchFetches.push(performance.now());
|
||||
}
|
||||
return real(input, options);
|
||||
};
|
||||
}"""
|
||||
KIT = """@HELPERS@
|
||||
const small = () => document.querySelector(".match-glass.small");
|
||||
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]));
|
||||
const flips = (glass) => glass.getAnimations({subtree: true}).filter((animation) => animation.animationName === "match-flip");
|
||||
const sheetOpen = () => !document.getElementById("sheet").hidden;
|
||||
const press = (target, key, times) => {
|
||||
for (let step = 0; step < times; step += 1) {
|
||||
target.dispatchEvent(new KeyboardEvent("keydown", {key, bubbles: true, cancelable: true}));
|
||||
}
|
||||
};
|
||||
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 dial = await until(() => document.querySelector("#sheet .match-refresh-dial"), 3000);
|
||||
if (!dial) {
|
||||
return {prevented, error: "no dial"};
|
||||
}
|
||||
const from = Number(dial.getAttribute("aria-valuenow"));
|
||||
press(dial, key, times);
|
||||
const to = Number(dial.getAttribute("aria-valuenow"));
|
||||
document.querySelector("#sheet .match-refresh-save").click();
|
||||
const closed = await until(() => !sheetOpen(), 5000);
|
||||
return {prevented, from, to, closed: Boolean(closed)};
|
||||
};"""
|
||||
FIRST = """(async () => {@KIT@
|
||||
if (!(await until(() => small() && 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 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 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};
|
||||
await sleep(700);
|
||||
const before = fetches();
|
||||
const clickedAt = performance.now();
|
||||
small().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 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))) {
|
||||
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 dial = await setDial("ArrowLeft", 8);
|
||||
return {kept, dial};
|
||||
})()"""
|
||||
STILL = """(async () => {@KIT@
|
||||
if (!(await until(() => small() && large() && fetches() >= 1, 8000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
const turn = Number(small().dataset.turn);
|
||||
await until(() => Number(small().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)};
|
||||
})()"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestMatchHourglass(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
|
||||
def probe(self, flow: str) -> str:
|
||||
return flow.replace("@KIT@", KIT).replace("@HELPERS@", base.HELPERS)
|
||||
|
||||
def steps(self) -> list[dict]:
|
||||
steps = []
|
||||
for width, height in base.WIDTHS:
|
||||
url = f"http://localhost:{self.port}/?{width}#tasks/match"
|
||||
steps.append({"width": width, "height": height, "url": url, "wait": 1500, "probe": self.probe(FIRST), "shot": str(OUT / f"chromium-{width}-hourglass.png")})
|
||||
steps.append({"width": width, "height": height, "url": url, "wait": 1500, "probe": self.probe(RELOADED)})
|
||||
steps.append({"width": width, "height": height, "url": url, "wait": 1500, "probe": self.probe(STILL), "media": REDUCED, "shot": str(OUT / f"chromium-{width}-hourglass-still.png")})
|
||||
return steps
|
||||
|
||||
def test_chromium_fetches_on_the_hourglass_cycle_flips_it_and_keeps_the_dial_interval(self):
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
data = self.drive(self.steps(), None, "cdp.mjs", os.environ.get("CHROMIUM", "chromium"), init=SPY)
|
||||
(OUT / "chromium-hourglass.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"]), 3 * len(base.WIDTHS), data)
|
||||
for index, (width, _) in enumerate(base.WIDTHS):
|
||||
first, reloaded, still = data["results"][3 * index : 3 * index + 3]
|
||||
with self.subTest(width=width):
|
||||
for found in (first, reloaded, still):
|
||||
self.assertNotIn("error", found, found)
|
||||
self.assertEqual(len(first["rate"]), 3, first)
|
||||
for gap in first["rate"]:
|
||||
self.assertAlmostEqual(gap, 2000, delta=300, msg=first)
|
||||
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["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)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -70,6 +70,8 @@ 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.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")]);
|
||||
@@ -107,7 +109,9 @@ RELEASE = """(async () => {@HELPERS@@CARD@@STEPS@
|
||||
const leaning = @SWIPE@ ? await swipeRight() : (key("ArrowRight"), "");
|
||||
await until(() => window.e2eSubmits.length >= @SUBMITS@, 20000);
|
||||
await sleep(1500);
|
||||
await until(() => card() && !releasing(), 8000);
|
||||
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)};
|
||||
})()"""
|
||||
|
||||
@@ -163,18 +167,17 @@ class TestMatchReleaseCard(ReleaseDeck):
|
||||
for (width, _), found in zip(((390, 844), (1920, 1080)), data["results"], strict=True):
|
||||
with self.subTest(width=width):
|
||||
self.assertNotIn("error", found, found)
|
||||
self.assertEqual((found["ready"], found["release"], found["block"], found["wide"]), (True, True, False, False), found)
|
||||
self.assertEqual((found["ready"], found["release"], found["block"], found["wide"]), (True, False, False, False), found)
|
||||
self.assertIn(f"review:{self.stale}", found["layers"], found)
|
||||
self.assertEqual(found["risk"], [[f"review:{self.red}", "false"]], found)
|
||||
self.assertEqual(found["label"], "Release 2 decisions", 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["back"], f"review:{self.stale}", found)
|
||||
self.assertEqual((found["again"], found["arrived"], found["stays"]), (True, True, True), found)
|
||||
|
||||
def test_chromium_release_by_arrow_leaves_the_red_gate_commit_in_the_stack_until_its_risk_is_accepted(self):
|
||||
found = self.release("no-risk", 0, False, 1)
|
||||
self.assertEqual(self.sorted_submits(found), [sorted([["review", self.commit, "approve"], ["operator", "operator/issue", "approve"]])], found)
|
||||
self.assertEqual(found["label"], "Release 2 decisions", found)
|
||||
self.assertIn(f"review:{self.red}", [found["front"], *found["peeks"]], found)
|
||||
def test_chromium_an_open_risk_hides_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)
|
||||
|
||||
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)
|
||||
@@ -182,11 +185,9 @@ class TestMatchReleaseCard(ReleaseDeck):
|
||||
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_leaves_the_red_gate_commit_out_again(self):
|
||||
found = self.release("withdrawn", 2, False, 1)
|
||||
self.assertEqual((found["pressed"], found["label"]), (["true", "false"], "Release 2 decisions"), found)
|
||||
self.assertEqual(self.sorted_submits(found), [sorted([["review", self.commit, "approve"], ["operator", "operator/issue", "approve"]])], found)
|
||||
self.assertIn(f"review:{self.red}", [found["front"], *found["peeks"]], found)
|
||||
def test_chromium_a_withdrawn_risk_hides_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)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -84,11 +84,8 @@ FLOW = """(async () => {@HELPERS@
|
||||
const leaned = await swipe(width * 0.4, 0);
|
||||
await until(() => front() !== order[2], 3000);
|
||||
order.push(front());
|
||||
key("w");
|
||||
await until(() => front() !== order[3], 3000);
|
||||
order.push(front());
|
||||
const short = await swipe(width * 0.1, 0);
|
||||
const stayed = front() === order[4];
|
||||
const stayed = front() === order[3];
|
||||
await swipe(width * 0.4, 4);
|
||||
const overview = await until(() => document.querySelector("#main .match-overview"), 3000);
|
||||
const rows = overview ? all("#main .match-decision").map((item) => [item.dataset.card, item.dataset.verdict, text(item.querySelector(".match-decision-feedback"))]) : [];
|
||||
@@ -178,7 +175,7 @@ class TestMatchRelease(HubCase):
|
||||
def check_flow(self, found: dict) -> None:
|
||||
reason = f"{FIRST}:3: rename it"
|
||||
self.assertNotIn("error", found, found)
|
||||
self.assertEqual(found["order"], [self.cards[0], self.cards[1], self.cards[2], "release", self.cards[1]], found)
|
||||
self.assertEqual(found["order"], [self.cards[0], self.cards[1], self.cards[2], self.cards[1]], found)
|
||||
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)
|
||||
|
||||
@@ -188,8 +188,9 @@ class TestMatchReview(HubCase):
|
||||
self.assertEqual((stack["card"], stack["kind"], stack["stale"], stack["face"], stack["opens"]), (f"review:{self.commit}", "commit", "false", True, True), stack)
|
||||
self.assertEqual((stack["name"], stack["age"]), ("Skills", "3 days"), stack)
|
||||
self.assertEqual((stack["metrics"], stack["under"]), ([["fix", "95"], ["break", "3"]], True), stack)
|
||||
place = [["branch", "feature/match", "Branch: feature/match (click copies)"], ["repo", "repo", "Repository: /repo (click copies)"],
|
||||
["worktree", ".worktrees/feature/match", "Worktree: /repo/.worktrees/feature/match (click copies)"]]
|
||||
opens = "click opens in VS Code, right-click copies the path"
|
||||
place = [["branch", "feature/match", "Branch: feature/match (click copies)"], ["repo", "repo", f"Repository: /repo ({opens})"],
|
||||
["worktree", ".worktrees/feature/match", f"Worktree: /repo/.worktrees/feature/match ({opens})"]]
|
||||
self.assertEqual(stack["place"], place, stack)
|
||||
self.assertIn(stack["paint"][0], PATTERNS, stack)
|
||||
self.assertTrue(stack["paint"][1] and stack["paint"][2] and stack["paint"][3], stack)
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
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
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-077-stamp-shots"))
|
||||
FLOW = """(async () => {@HELPERS@
|
||||
const card = () => document.querySelector("#main .match-card.front");
|
||||
if (!(await until(card, 8000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
const looked = () => {
|
||||
const stamp = card().querySelector(".match-stamp");
|
||||
if (!stamp) {
|
||||
return {card: card().dataset.card, stamp: null};
|
||||
}
|
||||
const style = getComputedStyle(stamp);
|
||||
const body = getComputedStyle(card().querySelector(".match-body"));
|
||||
return {card: card().dataset.card, stamp: text(stamp), kind: stamp.dataset.stamp, color: style.color, opacity: style.opacity, filter: style.filter, body: body.filter};
|
||||
};
|
||||
const first = looked();
|
||||
const head = card().querySelector(".match-head");
|
||||
const box = head.getBoundingClientRect();
|
||||
const at = (x) => ({bubbles: true, cancelable: true, pointerId: 7, 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)));
|
||||
const during = card().querySelector(".match-stamp") ? text(card().querySelector(".match-stamp")) : null;
|
||||
window.dispatchEvent(new PointerEvent("pointerup", at(box.left + box.width * 0.9)));
|
||||
await sleep(300);
|
||||
const swiped = looked();
|
||||
document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "ArrowUp", bubbles: true, cancelable: true}));
|
||||
await until(() => card() && card().dataset.card !== first.card, 3000);
|
||||
return {first, during, swiped, second: looked(), wide: document.documentElement.scrollWidth > window.innerWidth + 1};
|
||||
})()"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestMatchStamp(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
work = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(work.cleanup)
|
||||
row = {"title": "true", "workdir": work.name, "description": "ship it", "check": "done", "roles": {"Skills": "A", "Operator": "R"}}
|
||||
self.write_council({"rasci.json": {"operator/runs": row, "operator/waits": row}})
|
||||
now = time.time()
|
||||
job = {"command": "true", "directory": work.name, "sha256": "0" * 64, "proof": None, "output": "", "finished": None, "dismissed": False, "code": None}
|
||||
self.httpd.hub.jobs.add({**job, "task": "operator/runs", "status": "running", "created_ts": now - 900, "started": now - 900})
|
||||
self.httpd.hub.jobs.add({**job, "task": "operator/waits", "status": "queued", "created_ts": now - 60, "started": None})
|
||||
|
||||
def test_chromium_stamps_every_greyed_card_with_its_reason_in_colour(self):
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
flow = FLOW.replace("@HELPERS@", base.HELPERS)
|
||||
steps = [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}#tasks/match", "wait": 1500, "probe": flow, "shot": str(OUT / f"chromium-{width}-stamp.png")} for width, height in base.WIDTHS]
|
||||
data = self.drive(steps, None, "cdp.mjs", os.environ.get("CHROMIUM", "chromium"))
|
||||
(OUT / "chromium-stamp.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(base.WIDTHS), data)
|
||||
for found in data["results"]:
|
||||
with self.subTest(width=found.get("first", {}).get("card")):
|
||||
self.assertNotIn("error", found, found)
|
||||
stamps = {found["first"]["card"]: found["first"]["kind"], found["second"]["card"]: found["second"]["kind"]}
|
||||
self.assertEqual(stamps, {"operator:operator/runs": "running", "operator:operator/waits": "queued"}, found)
|
||||
for looked in (found["first"], found["second"]):
|
||||
self.assertIn(looked["stamp"], ("RUNNING", "QUEUED"), found)
|
||||
self.assertEqual((looked["opacity"], looked["filter"]), ("1", "none"), found)
|
||||
self.assertNotIn("grayscale", looked["filter"], found)
|
||||
self.assertIn("grayscale", looked["body"], found)
|
||||
channels = [int(part) for part in looked["color"].removeprefix("rgb(").removesuffix(")").split(",")[:3]]
|
||||
self.assertGreater(max(channels) - min(channels), 20, found)
|
||||
self.assertEqual((found["during"], found["swiped"]["stamp"], found["swiped"]["card"]), (found["first"]["stamp"], found["first"]["stamp"], found["first"]["card"]), found)
|
||||
self.assertFalse(found["wide"], found)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -33,7 +33,7 @@ SCAN = """
|
||||
const spans = (box) => Math.abs(box.top - outer.top - 1) <= 1 && Math.abs(outer.bottom - 1 - box.bottom) <= 1;
|
||||
return {
|
||||
id: field.id, label: field.getAttribute("aria-label") || "", framed: true, line,
|
||||
last: line ? field.nextElementSibling === button && tail.every((node) => node.matches("button[type=submit]")) : Boolean(foot) && button.parentElement === foot && field.nextElementSibling === foot && [...foot.children].slice([...foot.children].indexOf(button) + 1).every((node) => node.matches(".ptt-split, .mayday-toggle")),
|
||||
last: line ? field.nextElementSibling === button && tail.every((node) => node.matches("button[type=submit]")) : Boolean(foot) && button.parentElement === foot && [field.nextElementSibling, field.nextElementSibling && field.nextElementSibling.matches(".mic-chips") ? field.nextElementSibling.nextElementSibling : null].includes(foot) && [...foot.children].slice([...foot.children].indexOf(button) + 1).every((node) => node.matches(".ptt-split, .mayday-toggle")),
|
||||
fits: line ? spans(mic) && Math.abs(outer.right - 1 - end.right) <= 1 : mic.bottom <= outer.bottom && mic.top >= text.bottom - 1,
|
||||
divider: line ? getComputedStyle(button).borderLeftWidth : getComputedStyle(foot).borderTopWidth,
|
||||
clear: line ? text.right <= mic.left + 0.5 : true,
|
||||
@@ -60,7 +60,8 @@ STREAM = """(async () => {@HELPERS@@SCAN@
|
||||
})()"""
|
||||
RULES = """(async () => {@HELPERS@@SCAN@
|
||||
(await until(() => document.getElementById("controls-tab-rules"), 15000)).click();
|
||||
await until(() => document.querySelector("#main .rule-form .mic-frame"), 4000);
|
||||
(await until(() => document.querySelector("#main [data-new-rule]"), 4000)).click();
|
||||
await until(() => document.querySelector("#sheet .rule-form .mic-frame"), 4000);
|
||||
return {mics: scan(), wide: wide()};
|
||||
})()"""
|
||||
RADIO = """(async () => {@HELPERS@@SCAN@
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
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/hub-079-shots"))
|
||||
WORKTREE = "/repo/.worktrees/feature/links"
|
||||
FILE = "src/my app#1.py"
|
||||
ACTIONS = "click opens in VS Code, right-click copies the path"
|
||||
LINKS = """(async () => {@HELPERS@
|
||||
const card = () => document.querySelector("#main .match-card.front");
|
||||
await screenShown(8000);
|
||||
await until(() => card() && card().querySelector(".match-file .diff-head"), 8000);
|
||||
await sleep(400);
|
||||
const copied = [];
|
||||
navigator.clipboard.writeText = (value) => {
|
||||
copied.push(value);
|
||||
return Promise.resolve();
|
||||
};
|
||||
const chip = (place) => card().querySelector(`.match-place .match-where[data-place="${place}"]`);
|
||||
const head = card().querySelector(".match-file .diff-head a.path-link");
|
||||
const menuShut = () => all(".ctx-menu").every((menu) => menu.hidden);
|
||||
const rightClick = (node) => {
|
||||
const box = node.getBoundingClientRect();
|
||||
return !node.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, clientX: box.left + 4, clientY: box.top + 4, button: 2}));
|
||||
};
|
||||
const leftClick = (node) => {
|
||||
document.addEventListener("click", (event) => event.preventDefault(), {capture: true, once: true});
|
||||
node.click();
|
||||
};
|
||||
const facts = {
|
||||
branch: [chip("branch").tagName, chip("branch").getAttribute("href")],
|
||||
repo: [chip("repo").tagName, chip("repo").getAttribute("href"), chip("repo").title],
|
||||
worktree: [chip("worktree").tagName, chip("worktree").getAttribute("href"), chip("worktree").title],
|
||||
head: head ? [head.getAttribute("href"), text(head.querySelector("code.path")), head.title] : null,
|
||||
};
|
||||
leftClick(chip("worktree"));
|
||||
await sleep(100);
|
||||
const clickCopied = copied.length;
|
||||
const prevented = [rightClick(chip("worktree")), rightClick(head)];
|
||||
await sleep(200);
|
||||
return {...facts, clickCopied, prevented, copied, menuShut: menuShut(), wide: document.documentElement.scrollWidth > window.innerWidth + 1};
|
||||
})()"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestPathLinks(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
now = time.time()
|
||||
self.write_council({"work/s1/claim.json": {"office": "work/s1", "session": "s1", "runtime": "claude", "name": "Skills", "since": iso(now - 86400), "beat": now, "work": "links"}})
|
||||
patch = "@@ -1,2 +1,3 @@\n first\n+added\n second"
|
||||
diff = [{"path": FILE, "status": "M", "mode": "100644", "additions": 1, "deletions": 0, "patch": patch, "note": ""}]
|
||||
arguments = {**self.arguments("feat: path links", "", self.page("links.html", "<!doctype html><title>p</title>")), "worktree": WORKTREE, "branch": "feature/links", "agent": "Skills", "diff": diff}
|
||||
result = self.tool("review_request", arguments)
|
||||
self.assertFalse(result["isError"], result)
|
||||
self.base = f"http://{self.host}/"
|
||||
|
||||
def steps(self, browser: str) -> list[dict]:
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
probe = LINKS.replace("@HELPERS@", base.HELPERS)
|
||||
return [{"width": width, "height": height, "url": f"{self.base}?{width}#tasks/match", "wait": 1500, "probe": probe, "shot": str(OUT / f"{browser}-{width}-links.png")} for width, height in base.WIDTHS]
|
||||
|
||||
def check(self, data: dict) -> None:
|
||||
for (width, _), found in zip(base.WIDTHS, data["results"], strict=True):
|
||||
with self.subTest(width=width):
|
||||
self.assertEqual(found["branch"], ["BUTTON", None], found)
|
||||
self.assertEqual(found["repo"], ["A", "vscode://file/repo", f"Repository: /repo ({ACTIONS})"], found)
|
||||
self.assertEqual(found["worktree"], ["A", f"vscode://file{WORKTREE}", f"Worktree: {WORKTREE} ({ACTIONS})"], found)
|
||||
self.assertEqual(found["head"], [f"vscode://file{WORKTREE}/src/my%20app%231.py", FILE, f"{WORKTREE}/{FILE}: {ACTIONS}"], found)
|
||||
self.assertEqual(found["clickCopied"], 0, found)
|
||||
self.assertEqual(found["prevented"], [True, True], found)
|
||||
self.assertEqual(found["copied"], [WORKTREE, f"{WORKTREE}/{FILE}"], found)
|
||||
self.assertTrue(found["menuShut"], found)
|
||||
self.assertFalse(found["wide"], found)
|
||||
|
||||
def test_chromium_links_chips_and_diff_heads_and_copies_on_right_click_at_three_widths(self):
|
||||
data = self.drive(self.steps("chromium"), None)
|
||||
(OUT / "chromium-links.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.assertEqual(data["errors"], [])
|
||||
self.check(data)
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
|
||||
def test_firefox_links_chips_and_diff_heads_and_copies_on_right_click_at_three_widths(self):
|
||||
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"))
|
||||
(OUT / "firefox-links.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.check(data)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Exercise requirement 073: Start now on a waiting queue job signs one override, and the job shows granted within one poll."""
|
||||
|
||||
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
|
||||
import queue_kit
|
||||
from hub_case import HubCase
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-073-shots"))
|
||||
PAGE = """(async () => {@HELPERS@
|
||||
await screenShown(8000);
|
||||
(await until(() => document.getElementById("controls-tab-queue"), 8000)).click();
|
||||
const start = () => document.querySelector('#main .queue-tab [data-start="@JOB@"]');
|
||||
if (!(await until(start, 8000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
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 before = {label: text(start()), disabled: start().disabled, others: all("#main .queue-tab [data-start]").map((node) => node.dataset.start)};
|
||||
start().click();
|
||||
const granted = await until(() => !start() && document.querySelector('#main .queue-tab .queue-waiting [data-job="@JOB@"]') === null, 45000);
|
||||
return {before, signs, granted: Boolean(granted), wide: document.documentElement.scrollWidth > innerWidth + 1};
|
||||
})()"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestQueueOverride(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
authenticator = base.OrchestratorE2ECase.authenticator
|
||||
beside = base.OrchestratorE2ECase.beside
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
self.script = queue_kit.install(self, time.time())
|
||||
self.page_url = f"http://localhost:{self.port}/"
|
||||
|
||||
def grant_once_signed(self) -> None:
|
||||
if queue_kit.queue_jobs(self):
|
||||
(self.script.parent / "rows.json").write_text(json.dumps(queue_kit.started_rows()), encoding="utf-8")
|
||||
|
||||
def test_start_now_signs_one_override_and_the_job_shows_granted_within_one_poll(self):
|
||||
self.beside(self.grant_once_signed)
|
||||
width, height = base.WIDTHS[0]
|
||||
probe = PAGE.replace("@HELPERS@", base.HELPERS).replace("@JOB@", queue_kit.WAITING)
|
||||
steps = [{"width": width, "height": height, "url": f"{self.page_url}?{width}#stream/rules", "wait": 1500, "probe": probe, "shot": str(OUT / f"chromium-{width}-queue-start-now.png")}]
|
||||
data = self.drive(steps, self.authenticator())
|
||||
found = data["results"][0]
|
||||
self.assertNotIn("error", found, found)
|
||||
self.assertEqual((found["before"]["label"], found["before"]["disabled"]), ("Start now", False))
|
||||
self.assertEqual(sorted(found["before"]["others"]), ["q-2", "q-3", "q-4"])
|
||||
self.assertEqual(found["signs"], [[{"kind": "queue", "argv": ["override", queue_kit.WAITING]}]])
|
||||
self.assertTrue(found["granted"], found)
|
||||
self.assertFalse(found["wide"])
|
||||
jobs = queue_kit.queue_jobs(self)
|
||||
self.assertEqual([(job["argv"], job["status"]) for job in jobs], [(["override", queue_kit.WAITING], "queued")])
|
||||
|
||||
def test_the_waiting_jobs_and_their_start_now_fit_every_width(self):
|
||||
probe = """(async () => {@HELPERS@
|
||||
await screenShown(8000);
|
||||
(await until(() => document.getElementById("controls-tab-queue"), 8000)).click();
|
||||
const buttons = await until(() => all("#main .queue-tab [data-start]").length === 3 && all("#main .queue-tab [data-start]"), 8000);
|
||||
if (!buttons) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
return {shown: buttons.map((node) => node.getClientRects().length > 0), wide: document.documentElement.scrollWidth > innerWidth + 1};
|
||||
})()""".replace("@HELPERS@", base.HELPERS)
|
||||
steps = [{"width": width, "height": height, "url": f"{self.page_url}?{width}#stream/rules", "wait": 1500, "probe": probe, "shot": str(OUT / f"chromium-{width}-queue-waiting.png")} for width, height in base.WIDTHS]
|
||||
data = self.drive(steps, None)
|
||||
for (width, _), found in zip(base.WIDTHS, data["results"], strict=True):
|
||||
with self.subTest(width=width):
|
||||
self.assertNotIn("error", found, found)
|
||||
self.assertEqual(found, {"shown": [True] * 3, "wide": False})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Exercise requirement 072: the Controls tab Queue shows the learnings and the settings, stages two changes and signs them with one passkey assertion."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
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
|
||||
import queue_kit
|
||||
from hub_case import HubCase
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-072-shots"))
|
||||
READ = """
|
||||
const panel = () => document.querySelector("#main .queue-tab");
|
||||
const field = (key) => panel().querySelector(`[data-setting="${key}"] input`);
|
||||
const table = (label) => panel().querySelector(`table[aria-label="${label}"]`);
|
||||
const rows = (label) => all("tbody tr", table(label)).map((row) => all("th, td", row).map((cell) => text(cell)));
|
||||
const wide = () => document.documentElement.scrollWidth > innerWidth + 1;
|
||||
const open = async () => {
|
||||
await screenShown(8000);
|
||||
(await until(() => document.getElementById("controls-tab-queue"), 8000)).click();
|
||||
return until(() => panel() && table("Kinds") && field("budget_percent.cpu"), 8000);
|
||||
};
|
||||
"""
|
||||
SHOW = """(async () => {@HELPERS@@READ@
|
||||
if (!(await open())) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
return {
|
||||
kinds: rows("Kinds").map((row) => row.slice(0, 5)), signatures: rows("Signatures"), last: rows("Last runs").map((row) => row.slice(1)),
|
||||
settings: ["budget_percent.ram", "budget_percent.cpu", "load_limits.cpu_percent", "load_limits.mem_percent", "load_limits.sample_seconds", "slot_limits.test", "ram_cap_percent.test"].map((key) => [key, field(key).value]),
|
||||
wide: wide(),
|
||||
};
|
||||
})()"""
|
||||
STAGE = """(async () => {@HELPERS@@READ@
|
||||
if (!(await open())) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
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 set = (key, value) => {
|
||||
field(key).value = value;
|
||||
field(key).dispatchEvent(new Event("change", {bubbles: true}));
|
||||
};
|
||||
set("budget_percent.cpu", "180");
|
||||
set("slot_limits.test", "2");
|
||||
const apply = await until(() => panel().querySelector("[data-queue-apply]"), 4000);
|
||||
const staged = all('[aria-label="Staged settings"] li', panel()).map((node) => node.dataset.staged);
|
||||
apply.click();
|
||||
await until(() => !panel().querySelector("[data-queue-apply]"), 8000);
|
||||
return {staged, signs, wide: wide()};
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(source: str) -> str:
|
||||
return source.replace("@HELPERS@", base.HELPERS).replace("@READ@", READ)
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestQueueTab(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
authenticator = base.OrchestratorE2ECase.authenticator
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
self.script = queue_kit.install(self, time.time())
|
||||
self.page_url = f"http://localhost:{self.port}/"
|
||||
|
||||
def test_the_tab_shows_the_learnings_and_the_settings_at_every_width(self):
|
||||
steps = [{"width": width, "height": height, "url": f"{self.page_url}?{width}#stream/rules", "wait": 1500, "probe": probe(SHOW), "shot": str(OUT / f"chromium-{width}-queue-tab.png")} for width, height in base.WIDTHS]
|
||||
data = self.drive(steps, None)
|
||||
for (width, _), found in zip(base.WIDTHS, data["results"], strict=True):
|
||||
with self.subTest(width=width):
|
||||
self.assertNotIn("error", found, found)
|
||||
self.assertEqual(found["kinds"], [["test", "7", "12.5", "30", "2 (learned)"]])
|
||||
self.assertEqual(found["signatures"], [["make test", "test", "7", "4", "1", "12.5", "30", "2"]])
|
||||
self.assertEqual(found["last"], [["test", "make test", "4", "0", "override"]])
|
||||
self.assertEqual(dict(found["settings"]), {"budget_percent.ram": "75", "budget_percent.cpu": "100", "load_limits.cpu_percent": "90", "load_limits.mem_percent": "85", "load_limits.sample_seconds": "5", "slot_limits.test": "", "ram_cap_percent.test": ""})
|
||||
self.assertFalse(found["wide"])
|
||||
|
||||
def test_two_staged_settings_ask_one_passkey_assertion_and_queue_one_runner_job_each(self):
|
||||
steps = [{"width": 1366, "height": 768, "url": f"{self.page_url}?1366#stream/rules", "wait": 1500, "probe": probe(STAGE), "shot": str(OUT / "chromium-1366-queue-tab-applied.png")}]
|
||||
found = self.drive(steps, self.authenticator())["results"][0]
|
||||
self.assertNotIn("error", found, found)
|
||||
self.assertEqual(found["staged"], ["budget_percent.cpu", "slot_limits.test"])
|
||||
self.assertEqual(found["signs"], [[{"kind": "queue", "argv": ["config", "set", "budget_percent.cpu", "180"]}, {"kind": "queue", "argv": ["config", "set", "slot_limits.test", "2"]}]])
|
||||
jobs = queue_kit.queue_jobs(self)
|
||||
self.assertEqual(sorted(job["argv"][2:] for job in jobs), [["budget_percent.cpu", "180"], ["slot_limits.test", "2"]])
|
||||
self.assertEqual(len({str(job["proof"]) for job in jobs}), 1)
|
||||
self.assertFalse(found["wide"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,144 @@
|
||||
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
|
||||
from hub_case import HubCase
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-066-shots"))
|
||||
GROWN = (1920, 390)
|
||||
LABELLED = 480
|
||||
GEOMETRY = """
|
||||
const px = (value) => parseFloat(value) || 0;
|
||||
const wide = () => document.documentElement.scrollWidth > innerWidth + 1;
|
||||
const footer = (form) => {
|
||||
const frame = form.querySelector(".mic-frame");
|
||||
const foot = frame.querySelector(":scope > .composer-foot");
|
||||
const cells = [foot.querySelector(":scope > button:first-child"), foot.querySelector(":scope > .mic-attach"), foot.querySelector(":scope > .mic"), foot.querySelector(".ptt"), foot.querySelector(".ptt-menu"), foot.querySelector(":scope > .mayday-toggle")];
|
||||
const boxes = cells.map((cell) => cell.getBoundingClientRect());
|
||||
const looks = cells.map((cell) => getComputedStyle(cell));
|
||||
const clickable = cells.map((cell) => getComputedStyle(cell.matches("details") ? cell.querySelector(":scope > summary") : cell));
|
||||
const frameLook = getComputedStyle(frame);
|
||||
const inner = Math.max(0, px(frameLook.borderBottomLeftRadius) - px(frameLook.borderBottomWidth));
|
||||
return {
|
||||
level: boxes.every((box) => Math.abs(box.top - boxes[0].top) <= 1 && Math.abs(box.bottom - boxes[0].bottom) <= 1),
|
||||
gaps: boxes.slice(1).map((box, index) => Math.round(Math.abs(box.left - boxes[index].right))),
|
||||
corners: [Math.abs(px(looks[0].borderBottomLeftRadius) - inner) <= 0.5, Math.abs(px(looks[looks.length - 1].borderBottomRightRadius) - inner) <= 0.5],
|
||||
dividers: looks.map((look) => look.borderLeftWidth),
|
||||
outer: looks.map((look) => [look.borderTopWidth, look.borderRightWidth, look.borderBottomWidth]).flat().filter((width) => width !== "0px"),
|
||||
moves: clickable.map((look) => look.transitionProperty.split(", ").filter((name) => /border|padding|shadow|transform|width|height/.test(name))),
|
||||
eases: clickable.every((look) => ["background-color", "color"].every((name) => look.transitionProperty.split(", ").includes(name)) && look.transitionDuration.split(", ").every((time) => time === "0.15s")),
|
||||
area: Math.round(frame.getBoundingClientRect().width),
|
||||
labels: all(".cell-label", foot).map((label) => label.getBoundingClientRect().width > 1),
|
||||
icons: all("svg.bi", foot).every((svg) => svg.getBoundingClientRect().width > 0),
|
||||
resize: getComputedStyle(frame.querySelector("textarea")).resize,
|
||||
};
|
||||
};
|
||||
const growth = async (form) => {
|
||||
const field = form.querySelector("textarea");
|
||||
const typed = async (lines) => {
|
||||
field.value = Array.from({length: lines}, (_, index) => `line ${index + 1}`).join("\\n");
|
||||
field.dispatchEvent(new Event("input", {bubbles: true}));
|
||||
await sleep(80);
|
||||
return {scrolls: field.scrollHeight > field.clientHeight + 1, height: field.getBoundingClientRect().height};
|
||||
};
|
||||
const three = await typed(3);
|
||||
const eight = await typed(8);
|
||||
const cap = px(getComputedStyle(field).maxHeight);
|
||||
field.value = "";
|
||||
field.dispatchEvent(new Event("input", {bubbles: true}));
|
||||
return {three: three.scrolls, eight: eight.scrolls, capped: Math.abs(eight.height - cap) <= 2};
|
||||
};
|
||||
"""
|
||||
SPOT = """(async () => {@HELPERS@@GEOMETRY@
|
||||
const form = await until(() => document.querySelector("#radio-spot .radio-speak form.composer"), 15000);
|
||||
await sleep(300);
|
||||
return {footer: footer(form), growth: @GROW@ ? await growth(form) : null, wide: wide()};
|
||||
})()"""
|
||||
WIDGET = """(async () => {@HELPERS@@GEOMETRY@
|
||||
await ViewStore.update("home.pins", () => [{kind: "panel", id: "radio-speak", w: 6, h: 5}]);
|
||||
const tile = await until(() => document.querySelector('#main .home-tile[data-pin="panel:radio-speak"] form.composer') && document.querySelector('#main .home-tile[data-pin="panel:radio-speak"]'), 8000);
|
||||
await sleep(300);
|
||||
const body = tile.querySelector(".home-body").getBoundingClientRect();
|
||||
const form = tile.querySelector("form.composer").getBoundingClientRect();
|
||||
return {footer: footer(tile.querySelector("form.composer")), width: Math.round(Math.abs(form.width - body.width)), wide: wide()};
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str, grow: bool) -> str:
|
||||
return template.replace("@HELPERS@", base.HELPERS).replace("@GEOMETRY@", GEOMETRY).replace("@GROW@", "true" if grow else "false")
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestRadioComposer(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
self.claim("s1", "Skills")
|
||||
self.snapshot()
|
||||
self.page_url = f"http://localhost:{self.port}/"
|
||||
|
||||
def steps(self, browser: str) -> list[dict]:
|
||||
steps = []
|
||||
for width, height in base.WIDTHS:
|
||||
shot = OUT / f"{browser}-{width}"
|
||||
steps += [
|
||||
{"width": width, "height": height, "url": f"{self.page_url}?{width}-spot#stream/radio", "wait": 1200, "probe": probe(SPOT, width in GROWN), "shot": f"{shot}-composer-spot.png"},
|
||||
{"width": width, "height": height, "url": f"{self.page_url}?{width}-home#home", "wait": 1200, "probe": probe(WIDGET, False), "shot": f"{shot}-composer-widget.png"},
|
||||
]
|
||||
return steps
|
||||
|
||||
def check_footer(self, footer: dict) -> None:
|
||||
self.assertTrue(footer["level"], footer)
|
||||
self.assertEqual(footer["gaps"], [0, 0, 0, 0, 0], footer)
|
||||
self.assertEqual(footer["corners"], [True, True], footer)
|
||||
self.assertEqual(footer["dividers"], ["0px", "1px", "1px", "1px", "1px", "1px"], footer)
|
||||
self.assertEqual(footer["outer"], [], footer)
|
||||
self.assertEqual(footer["moves"], [[], [], [], [], [], []], footer)
|
||||
self.assertTrue(footer["eases"], footer)
|
||||
self.assertTrue(footer["icons"], footer)
|
||||
self.assertEqual(footer["resize"], "none", footer)
|
||||
self.assertEqual(set(footer["labels"]), {footer["area"] > LABELLED}, footer)
|
||||
|
||||
def check(self, data: dict) -> None:
|
||||
results = iter(data["results"])
|
||||
for width, _ in base.WIDTHS:
|
||||
spot, widget = next(results), next(results)
|
||||
with self.subTest(width=width, view="spot"):
|
||||
self.assertNotIn("error", spot, spot)
|
||||
self.check_footer(spot["footer"])
|
||||
self.assertFalse(spot["wide"])
|
||||
if width in GROWN:
|
||||
self.assertEqual(spot["growth"], {"three": False, "eight": True, "capped": True}, spot)
|
||||
with self.subTest(width=width, view="widget"):
|
||||
self.assertNotIn("error", widget, widget)
|
||||
self.check_footer(widget["footer"])
|
||||
self.assertLessEqual(widget["width"], 1, widget)
|
||||
self.assertFalse(widget["wide"])
|
||||
|
||||
def test_chromium_draws_one_flush_footer_strip_in_the_spot_and_the_full_width_widget(self):
|
||||
data = self.drive(self.steps("chromium"), None)
|
||||
(OUT / "chromium-composer.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.assertEqual(data["errors"], [])
|
||||
self.check(data)
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
|
||||
def test_firefox_draws_one_flush_footer_strip_in_the_spot_and_the_full_width_widget(self):
|
||||
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"))
|
||||
(OUT / "firefox-composer.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.check(data)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,218 @@
|
||||
"""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."""
|
||||
|
||||
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
|
||||
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"))
|
||||
LEVELS = ("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": []}
|
||||
READ = """
|
||||
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 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);
|
||||
const sheet = () => {
|
||||
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 toasts = () => all("#toasts .toast").map(text);
|
||||
const stored = async () => (await (await fetch("/api/limits", {cache: "no-store"})).json()).limits;
|
||||
const posts = [];
|
||||
const send = window.fetch.bind(window);
|
||||
window.fetch = (path, init) => {
|
||||
if (String(path).startsWith("/api/limits") && init && init.method === "POST") {
|
||||
posts.push([String(path), JSON.parse(init.body).proof === undefined ? "sign" : JSON.parse(init.body).proof === null ? "unsigned" : "signed"]);
|
||||
}
|
||||
return send(path, init);
|
||||
};
|
||||
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)});
|
||||
"""
|
||||
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")};
|
||||
button("Limit lines", "RAM").click();
|
||||
await until(() => lines().every(([metric]) => metric === "ram"), 4000);
|
||||
const ram = {lines: lines(), target: target(), metric: pressed("Limit lines")};
|
||||
button("Limit lines", "PSI").click();
|
||||
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};
|
||||
})()"""
|
||||
DIAL = """(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};
|
||||
})()"""
|
||||
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();
|
||||
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()};
|
||||
})()"""
|
||||
SIGN = """(async () => {@HELPERS@@READ@
|
||||
if (!(await ready())) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
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()};
|
||||
})()"""
|
||||
SHEET = """(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};
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(source: str) -> str:
|
||||
return source.replace("@HELPERS@", base.HELPERS).replace("@READ@", READ)
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestResourceLimits(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
authenticator = base.OrchestratorE2ECase.authenticator
|
||||
sample = w4.TestWorkbenchResources.sample
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
now = int(time.time())
|
||||
self.start = now - now % 60 - w4.ROWS * 60
|
||||
folder = self.kept / "resources"
|
||||
folder.mkdir()
|
||||
(folder / "samples.jsonl").write_text(self.jsonl([self.sample(index) for index in range(w4.ROWS)]), encoding="utf-8")
|
||||
(folder / "tokens.jsonl").write_text("", encoding="utf-8")
|
||||
self.write_council({"limits.json": PROFILES["balanced"], "limits-target.json": TARGET})
|
||||
self.page_url = f"http://localhost:{self.port}/"
|
||||
|
||||
def stored(self) -> dict:
|
||||
return json.loads((self.council / "limits.json").read_text(encoding="utf-8"))
|
||||
|
||||
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):
|
||||
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], []))
|
||||
self.assertFalse(found["page"]["wide"])
|
||||
self.assertGreater(found["page"]["plot"], 40)
|
||||
self.assertEqual(w4.quiet(found["violations"]), [])
|
||||
|
||||
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]
|
||||
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"])
|
||||
self.assertEqual(self.stored()["cpu"]["upper"], 85)
|
||||
|
||||
def test_a_canceled_passkey_keeps_the_old_limits_and_a_signed_one_switches_the_profile(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.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])
|
||||
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)
|
||||
balanced = PROFILES["balanced"]
|
||||
for (width, _), found in zip(base.WIDTHS, data["results"], 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.assertFalse(found["wide"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,8 +1,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import sys
|
||||
import time
|
||||
import unittest
|
||||
@@ -15,7 +18,7 @@ import hub_e2e_kit as base
|
||||
import test_resources_view_e2e as res
|
||||
import test_workbench_w4_e2e as w4
|
||||
from hub_case import HubCase
|
||||
from kvb_orchestrator import accounts
|
||||
from kvb_orchestrator import accounts, calibration
|
||||
from kvb_orchestrator.viewstore import VIEW
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-028-shots"))
|
||||
@@ -67,10 +70,66 @@ REMOVE = """(async () => {@HELPERS@@READ@@KIT@
|
||||
const removed = Boolean(await until(() => sheet().hidden && rows().length === 1, 5000));
|
||||
return {removed, after: rows(), page: wide(), violations: window.e2eViolations || null};
|
||||
})()"""
|
||||
BAR = """
|
||||
const bar = (id) => document.querySelector(`#main .res-accounts [data-usage="${id || "@ONE@"}"]`);
|
||||
const valueOf = (node) => Number(node.getAttribute("aria-valuenow"));
|
||||
const tenth = (value) => Math.round(value * 10) / 10;
|
||||
const settled = (value) => until(() => {
|
||||
const node = bar();
|
||||
return node && !node.hasAttribute("data-pending") && valueOf(node) === value ? node : null;
|
||||
}, 6000);
|
||||
const ratio = (node) => (100 * node.querySelector(".acc-fill").getBoundingClientRect().width) / node.getBoundingClientRect().width;
|
||||
const read = (node) => ({share: valueOf(node), ratio: ratio(node), fill: node.style.getPropertyValue("--fill"), expected: UsageBar.fillColor(valueOf(node))});
|
||||
const key = (name) => bar().dispatchEvent(new KeyboardEvent("keydown", {key: name, bubbles: true, cancelable: true}));
|
||||
const pointer = (node, type, x, y) => node.dispatchEvent(new PointerEvent(type, {bubbles: true, cancelable: true, pointerId: 1, button: 0, isPrimary: true, pointerType: "mouse", clientX: x, clientY: y}));
|
||||
const toggle = () => document.querySelector("#main .res-accounts [data-forecast-toggle]");
|
||||
const marks = () => all("#main .res-accounts [data-usage]").map((node) => [node.dataset.usage, all("[data-forecast]", node).map((mark) => [mark.dataset.forecast, mark.title])]);
|
||||
const unlimited = () => !document.querySelector('#main .res-accounts tr[data-account="@THREE@"] [data-usage]');
|
||||
"""
|
||||
USAGE = """(async () => {@HELPERS@@KIT@@BAR@
|
||||
if (!(await until(() => bar() && toggle(), 15000))) {
|
||||
return {error: text(box()) || text(document.getElementById("main"))};
|
||||
}
|
||||
await sleep(300);
|
||||
const first = bar();
|
||||
const shown = {...read(first), role: first.getAttribute("role"), range: [first.getAttribute("aria-valuemin"), first.getAttribute("aria-valuemax")], unlimited: unlimited()};
|
||||
bar().focus();
|
||||
key("ArrowRight");
|
||||
const right = valueOf(bar());
|
||||
key("PageUp");
|
||||
const paged = valueOf(bar());
|
||||
const keyed = await settled(tenth(Math.min(100, shown.share + 11)));
|
||||
const kept = Boolean(keyed) && document.activeElement === keyed;
|
||||
const rect = bar().getBoundingClientRect();
|
||||
const y = rect.top + rect.height / 2;
|
||||
pointer(bar(), "pointerdown", rect.left + rect.width * 0.1, y);
|
||||
pointer(document, "pointermove", rect.left + rect.width * 0.25, y);
|
||||
pointer(document, "pointermove", rect.left + rect.width * 0.4, y);
|
||||
pointer(document, "pointerup", rect.left + rect.width * 0.4, y);
|
||||
const dragged = await settled(40);
|
||||
const stored = (await (await fetch("/api/accounts", {cache: "no-store"})).json()).calibrations;
|
||||
const before = {pressed: toggle().getAttribute("aria-pressed"), marks: marks()};
|
||||
toggle().click();
|
||||
await until(() => toggle().getAttribute("aria-pressed") === "true" && marks().every(([, found]) => found.length === 1), 6000);
|
||||
const on = {pressed: toggle().getAttribute("aria-pressed"), marks: marks()};
|
||||
bar().scrollIntoView({block: "center", inline: "center"});
|
||||
return {shown, right, paged, keyed: Boolean(keyed), kept, dragged: dragged ? read(dragged) : null, stored, before, on, page: wide(), violations: window.e2eViolations || null};
|
||||
})()"""
|
||||
RELOAD = """(async () => {@HELPERS@@KIT@@BAR@
|
||||
if (!(await until(() => bar() && toggle() && marks().every(([, found]) => found.length === 1), 15000))) {
|
||||
return {error: text(box()) || text(document.getElementById("main"))};
|
||||
}
|
||||
bar().scrollIntoView({block: "center", inline: "center"});
|
||||
const after = {...read(bar()), pressed: toggle().getAttribute("aria-pressed"), marks: marks()};
|
||||
toggle().click();
|
||||
const off = Boolean(await until(() => toggle().getAttribute("aria-pressed") === "false" && marks().every(([, found]) => found.length === 0), 6000));
|
||||
return {after, off, page: wide(), violations: window.e2eViolations || null};
|
||||
})()"""
|
||||
DAY_TIME = r"(Sun|Mon|Tue|Wed|Thu|Fri|Sat) [0-2][0-9]:[0-5][0-9]"
|
||||
|
||||
|
||||
def probe(template: str) -> str:
|
||||
names = {"@HELPERS@": base.HELPERS, "@READ@": res.READ, "@KIT@": KIT, "@EMAIL@": EMAIL}
|
||||
def probe(template: str, ids: dict[str, str] | None = None) -> str:
|
||||
names = {"@HELPERS@": base.HELPERS, "@READ@": res.READ, "@KIT@": KIT, "@BAR@": BAR, "@EMAIL@": EMAIL, **(ids or {})}
|
||||
for key, value in names.items():
|
||||
template = template.replace(key, value)
|
||||
return template
|
||||
@@ -126,9 +185,9 @@ class TestResourcesAccounts(HubCase):
|
||||
self.assertEqual(add["prefilled"], ["Anthropic", EMAIL, "1000", True])
|
||||
self.assertTrue(add["edited"], add)
|
||||
self.assertEqual(add["afterEdit"][0][1][9], "–")
|
||||
self.assertEqual(add["off"]["panels"], [*shown, ["resources-accounts", True]])
|
||||
self.assertEqual(add["off"]["picks"][-1], ["accounts", False, False])
|
||||
self.assertEqual(add["on"]["panels"], [*shown, ["resources-accounts", False]])
|
||||
self.assertEqual(add["off"]["panels"], [*shown, ["resources-accounts", True], ["resources-usage", True]])
|
||||
self.assertEqual(add["off"]["picks"][-2:], [["accounts", False, False], ["usage", False, False]])
|
||||
self.assertEqual(add["on"]["panels"], [*shown, ["resources-accounts", False], ["resources-usage", True]])
|
||||
self.assertEqual(add["page"], {"wide": False})
|
||||
self.assertEqual(w4.quiet(add["violations"]), [])
|
||||
self.assertTrue(remove["removed"], remove)
|
||||
@@ -152,5 +211,99 @@ class TestResourcesAccounts(HubCase):
|
||||
self.check(data, "firefox")
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestAccountUsageBar(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
sample = w4.TestWorkbenchResources.sample
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
now = int(time.time())
|
||||
self.start = now - now % 60 - w4.ROWS * 60
|
||||
folder = self.kept / "resources"
|
||||
folder.mkdir()
|
||||
(folder / "samples.jsonl").write_text(self.jsonl([self.sample(index) for index in range(w4.ROWS)]), encoding="utf-8")
|
||||
tokens = [
|
||||
{"t": now - 60, "agent": "Skills", "model": "claude-opus-5-5", "input": 40, "output": 2, "cache_read": 0, "cache_write": 0, "account": EMAIL},
|
||||
{"t": now - 60, "agent": "Stage", "model": "claude-opus-5-5", "input": 900, "output": 0, "cache_read": 0, "cache_write": 0, "account": "two@example.org"},
|
||||
]
|
||||
(folder / "tokens.jsonl").write_text(self.jsonl(tokens), encoding="utf-8")
|
||||
self.council.mkdir(parents=True, exist_ok=True)
|
||||
(self.council / accounts.SESSION_ACCOUNTS).write_text(json.dumps({"session": "s1", "email": EMAIL}) + "\n", encoding="utf-8")
|
||||
reset = {"day": (datetime.datetime.now().isoweekday() % 7 + 3) % 7, "time": "12:00"}
|
||||
stored = {"provider": "Anthropic", "renewal": {"day": 1, "time": "09:00"}, "reset": reset, "resubscribe": "", "autorenew": True, "note": ""}
|
||||
ledger = self.httpd.hub.accounts.ledger
|
||||
self.ids = {
|
||||
f"@{name}@": ledger.add(accounts.valid_account({**stored, "email": email, "limit": limit}))["id"]
|
||||
for name, email, limit in (("ONE", EMAIL, 1000), ("TWO", "two@example.org", 1000), ("THREE", "three@example.org", None))
|
||||
}
|
||||
self.base = f"http://{self.host}/"
|
||||
|
||||
def steps(self, browser: str) -> list[dict]:
|
||||
steps = []
|
||||
for width, height in base.WIDTHS:
|
||||
shot = OUT / f"{browser}-{width}"
|
||||
url = f"{self.base}?{width}#resources"
|
||||
steps += [
|
||||
{"width": width, "height": height, "url": url, "wait": 1200, "probe": probe(USAGE, self.ids), "shot": f"{shot}-usage.png"},
|
||||
{"width": width, "height": height, "url": f"{self.base}?{width}-reload#resources", "wait": 1200, "probe": probe(RELOAD, self.ids), "shot": f"{shot}-usage-reloaded.png"},
|
||||
]
|
||||
return steps
|
||||
|
||||
def check(self, data: dict, browser: str) -> None:
|
||||
results = iter(data["results"])
|
||||
one, two = self.ids["@ONE@"], self.ids["@TWO@"]
|
||||
for index, (width, _) in enumerate(base.WIDTHS):
|
||||
usage, reload = next(results), next(results)
|
||||
with self.subTest(browser=browser, width=width):
|
||||
self.assertNotIn("error", usage, usage)
|
||||
shown = usage["shown"]
|
||||
self.assertEqual((shown["role"], shown["range"], shown["unlimited"]), ("slider", ["0", "100"], True))
|
||||
self.assertEqual(shown["share"], 40 if index else 4.2)
|
||||
self.assertLessEqual(abs(shown["ratio"] - shown["share"]), 1, shown)
|
||||
self.assertEqual(shown["fill"], shown["expected"])
|
||||
self.assertEqual((usage["right"], usage["paged"]), (round(shown["share"] + 1, 1), round(shown["share"] + 11, 1)))
|
||||
self.assertTrue(usage["keyed"] and usage["kept"], usage)
|
||||
self.assertEqual(usage["dragged"]["share"], 40, usage)
|
||||
self.assertLessEqual(abs(usage["dragged"]["ratio"] - 40), 1, usage)
|
||||
self.assertEqual(usage["dragged"]["fill"], usage["dragged"]["expected"])
|
||||
self.assertEqual(usage["stored"][one]["share"], 40)
|
||||
self.assertEqual(usage["before"], {"pressed": "false", "marks": [[one, []], [two, []]]})
|
||||
self.assertEqual(usage["on"]["pressed"], "true")
|
||||
(first, (mine,)), (second, (full,)) = usage["on"]["marks"]
|
||||
self.assertEqual((first, mine[0], second, full[0]), (one, "reset", two, "full"))
|
||||
self.assertRegex(mine[1], rf"^[0-9]+ % expected at the reset, {DAY_TIME}$")
|
||||
self.assertRegex(full[1], rf"^100 % at {DAY_TIME}$")
|
||||
self.assertEqual(usage["page"], {"wide": False})
|
||||
self.assertEqual(w4.quiet(usage["violations"]), [])
|
||||
self.assertNotIn("error", reload, reload)
|
||||
after = reload["after"]
|
||||
self.assertEqual((after["share"], after["pressed"]), (40, "true"))
|
||||
self.assertLessEqual(abs(after["ratio"] - 40), 1, after)
|
||||
self.assertEqual([found[0][0] for _, found in after["marks"]], ["reset", "full"])
|
||||
self.assertTrue(reload["off"], reload)
|
||||
self.assertEqual(reload["page"], {"wide": False})
|
||||
self.assertEqual(w4.quiet(reload["violations"]), [])
|
||||
self.assertFalse(self.httpd.hub.settings.get()["forecast"])
|
||||
file = self.state / calibration.CALIBRATION
|
||||
self.assertEqual(stat.S_IMODE(file.stat().st_mode), 0o600)
|
||||
self.assertEqual(json.loads(file.read_text(encoding="utf-8"))[one]["share"], 40)
|
||||
self.assertIsNone(re.search(r"@[A-Z]+@", json.dumps(data["results"])))
|
||||
|
||||
def test_chromium_calibrates_the_usage_bar_by_keys_and_drag_and_switches_the_forecast_at_three_widths(self):
|
||||
data = self.drive(self.steps("chromium"), None, init=w4.GUARD)
|
||||
(OUT / "chromium-account-usage.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.assertEqual(data["errors"], [])
|
||||
self.check(data, "chromium")
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
|
||||
def test_firefox_calibrates_the_usage_bar_by_keys_and_drag_and_switches_the_forecast_at_three_widths(self):
|
||||
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=w4.GUARD)
|
||||
(OUT / "firefox-account-usage.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.check(data, "firefox")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,147 @@
|
||||
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
|
||||
import test_resources_view_e2e as res
|
||||
import test_workbench_w4_e2e as w4
|
||||
from hub_case import HubCase
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-070-shots"))
|
||||
OPUS = "claude-opus-5-5"
|
||||
KIT = """
|
||||
const box = () => document.querySelector("#main .res-usage");
|
||||
const rows = () => all("#main .res-usage tbody tr.use-row");
|
||||
const keys = () => rows().map((row) => row.dataset.key);
|
||||
const cells = (column) => rows().map((row) => text(row.querySelector(`[data-column="${column}"]`)));
|
||||
const group = () => document.querySelector("#main [data-usage-group]");
|
||||
const choose = (select, value) => {
|
||||
select.value = value;
|
||||
select.dispatchEvent(new Event("change", {bubbles: true}));
|
||||
};
|
||||
const sortBy = (key) => document.querySelector(`#main .res-usage [data-sort="${key}"]`).click();
|
||||
const sorted = () => all("#main .res-usage [data-usage-table] thead th").map((th) => th.getAttribute("aria-sort"));
|
||||
const filters = () => all("#main .res-usage [data-filter]").map((node) => node.dataset.filter);
|
||||
const split = () => Boolean(document.querySelector("#main .res-usage [data-usage-split]"));
|
||||
const context = () => all("#main .res-usage [data-usage-context] tbody tr").map((row) => all("td", row).map((cell) => text(cell)));
|
||||
const rowOf = (key) => rows().find((row) => row.dataset.key === key);
|
||||
const wide = () => ({wide: document.documentElement.scrollWidth > innerWidth + 1});
|
||||
"""
|
||||
EXPLORE = """(async () => {@HELPERS@@READ@@KIT@
|
||||
if (!(await until(() => document.querySelector("#main .res-panels-menu") && box(), 15000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
await pickPanel("usage", true);
|
||||
if (!(await until(() => rows().length === 3, 8000))) {
|
||||
return {error: text(box())};
|
||||
}
|
||||
const bySkill = {group: group().value, keys: keys(), split: split(), context: context(), panels: panelsShown()};
|
||||
sortBy("cost");
|
||||
const byCost = {keys: keys(), costs: cells("cost"), sorted: sorted()};
|
||||
rowOf("kvb-help").click();
|
||||
const drilled = Boolean(await until(() => filters().join() === "skill" && keys().join() === "kvb-help", 6000));
|
||||
choose(group(), "tool");
|
||||
const switched = Boolean(await until(() => keys().join() === "Bash,Read," && split(), 6000));
|
||||
const byTool = {group: group().value, keys: keys(), shares: cells("share"), split: split(), filters: filters()};
|
||||
box().scrollIntoView({block: "start"});
|
||||
return {bySkill, byCost, drilled, switched, byTool, page: wide(), violations: window.e2eViolations || null};
|
||||
})()"""
|
||||
RESET = """(async () => {@HELPERS@@READ@@KIT@
|
||||
document.querySelector('#main .res-usage [data-filter="skill"]').click();
|
||||
const cleared = Boolean(await until(() => !filters().length && keys().length === 4, 6000));
|
||||
const after = {keys: keys(), filters: filters()};
|
||||
await pickPanel("usage", false);
|
||||
return {cleared, after, panels: panelsShown(), page: wide(), violations: window.e2eViolations || null};
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str) -> str:
|
||||
for key, value in {"@HELPERS@": base.HELPERS, "@READ@": res.READ, "@KIT@": KIT}.items():
|
||||
template = template.replace(key, value)
|
||||
return template
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestResourcesUsage(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
sample = w4.TestWorkbenchResources.sample
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
now = int(time.time())
|
||||
self.start = now - now % 60 - w4.ROWS * 60
|
||||
hour = now - now % 3600 - 3600
|
||||
tokens = [
|
||||
{"t": hour, "agent": "Skills", "model": OPUS, "input": 1000, "output": 100, "cache_read": 3000, "cache_write": 0, "skill": "kvb-help", "tool": "Bash,Read"},
|
||||
{"t": hour, "agent": "Skills", "model": "claude-haiku-5-5", "input": 500, "output": 50, "cache_read": 0, "cache_write": 0, "skill": "kvb-help"},
|
||||
{"t": hour, "agent": "Stage", "model": OPUS, "input": 4000, "output": 1000, "cache_read": 0, "cache_write": 1000, "tool": "Edit"},
|
||||
{"t": hour, "agent": "Stage", "model": "mystery", "input": 50000, "output": 0, "cache_read": 0, "cache_write": 0, "skill": "i8-test", "tool": "Bash"},
|
||||
]
|
||||
folder = self.kept / "resources"
|
||||
folder.mkdir()
|
||||
(folder / "samples.jsonl").write_text(self.jsonl([self.sample(index) for index in range(w4.ROWS)]), encoding="utf-8")
|
||||
(folder / "tokens.jsonl").write_text(self.jsonl([{name: value for name, value in row.items() if name not in ("skill", "tool")} for row in tokens]), encoding="utf-8")
|
||||
(folder / "usage.jsonl").write_text(self.jsonl(tokens), encoding="utf-8")
|
||||
(folder / "context.jsonl").write_text(self.jsonl([{"t": hour - hour % 86400, "agent": "Skills", "turns": {"12": 1, "30": 2, "99": 1}, "compactions": 2}]), encoding="utf-8")
|
||||
self.base = f"http://{self.host}/"
|
||||
|
||||
def steps(self, browser: str) -> list[dict]:
|
||||
steps = []
|
||||
for width, height in base.WIDTHS:
|
||||
shot = OUT / f"{browser}-{width}"
|
||||
steps += [
|
||||
{"width": width, "height": height, "url": f"{self.base}?{width}#resources", "wait": 1200, "probe": probe(EXPLORE), "shot": f"{shot}-usage.png"},
|
||||
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(RESET), "shot": f"{shot}-usage-reset.png"},
|
||||
]
|
||||
return steps
|
||||
|
||||
def check(self, data: dict, browser: str) -> None:
|
||||
results = iter(data["results"])
|
||||
for width, _ in base.WIDTHS:
|
||||
explore, reset = next(results), next(results)
|
||||
with self.subTest(browser=browser, width=width):
|
||||
self.assertNotIn("error", explore, explore)
|
||||
by_skill = explore["bySkill"]
|
||||
self.assertEqual((by_skill["group"], by_skill["keys"], by_skill["split"]), ("skill", ["i8-test", "", "kvb-help"], False))
|
||||
self.assertEqual(by_skill["panels"][-1], ["resources-usage", False])
|
||||
self.assertEqual([(row[1], row[2], row[5]) for row in by_skill["context"]], [("Skills", "4", "2")])
|
||||
self.assertEqual(explore["byCost"]["keys"], ["", "kvb-help", "i8-test"])
|
||||
self.assertEqual(explore["byCost"]["costs"], ["$0.04", "$0.01", "–"])
|
||||
self.assertEqual(explore["byCost"]["sorted"], ["none"] * 7 + ["descending", "none"])
|
||||
self.assertTrue(explore["drilled"], explore)
|
||||
self.assertTrue(explore["switched"], explore)
|
||||
self.assertEqual(explore["byTool"], {"group": "tool", "keys": ["Bash", "Read", ""], "shares": ["88.2 %", "88.2 %", "11.8 %"], "split": True, "filters": ["skill"]})
|
||||
self.assertEqual(explore["page"], {"wide": False})
|
||||
self.assertEqual(w4.quiet(explore["violations"]), [])
|
||||
self.assertTrue(reset["cleared"], reset)
|
||||
self.assertEqual(reset["after"], {"keys": ["Edit", "Read", "", "Bash"], "filters": []})
|
||||
self.assertEqual(reset["panels"][-1], ["resources-usage", True])
|
||||
self.assertEqual(reset["page"], {"wide": False})
|
||||
self.assertEqual(w4.quiet(reset["violations"]), [])
|
||||
|
||||
def test_chromium_groups_drills_down_and_sorts_the_usage_by_estimated_cost_at_three_widths(self):
|
||||
data = self.drive(self.steps("chromium"), None, init=w4.GUARD)
|
||||
(OUT / "chromium-resources-usage.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.assertEqual(data["errors"], [])
|
||||
self.check(data, "chromium")
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
|
||||
def test_firefox_groups_drills_down_and_sorts_the_usage_by_estimated_cost_at_three_widths(self):
|
||||
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=w4.GUARD)
|
||||
(OUT / "firefox-resources-usage.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.check(data, "firefox")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -149,8 +149,8 @@ class TestResourcesView(HubCase):
|
||||
self.assertNotIn("error", toggle, toggle)
|
||||
before = toggle["before"]
|
||||
self.assertEqual(before["charts"], ["hardware", "tokens"])
|
||||
self.assertEqual(before["panels"], [["resources-hardware", False], ["resources-tokens", False], ["resources-combined", True], ["resources-accounts", False]])
|
||||
self.assertEqual(before["picks"], [["hardware", True, False], ["tokens", True, False], ["combined", False, False], ["accounts", True, False]])
|
||||
self.assertEqual(before["panels"], [["resources-hardware", False], ["resources-tokens", False], ["resources-combined", True], ["resources-accounts", False], ["resources-usage", True]])
|
||||
self.assertEqual(before["picks"], [["hardware", True, False], ["tokens", True, False], ["combined", False, False], ["accounts", True, False], ["usage", False, False]])
|
||||
self.assertEqual((before["lines"], before["agents"]), (hardware, ["Skills", "Stage"]))
|
||||
self.assertEqual(set(before["pressed"].values()), {"true"})
|
||||
self.assertEqual(set(before["pressed"]), {*hardware, "agent:Skills", STAGE})
|
||||
@@ -169,8 +169,8 @@ class TestResourcesView(HubCase):
|
||||
combined = combine["combined"]
|
||||
self.assertEqual((combined["charts"], combined["lines"], combined["sums"], combined["burn"]), (["combined"], hardware, ["Skills", "Stage"], ["done", "scope"]))
|
||||
self.assertEqual(combined["right"], 2)
|
||||
self.assertEqual(combined["panels"], [["resources-hardware", True], ["resources-tokens", True], ["resources-combined", False], ["resources-accounts", False]])
|
||||
self.assertEqual(combined["picks"], [["hardware", False, False], ["tokens", False, False], ["combined", True, False], ["accounts", True, False]])
|
||||
self.assertEqual(combined["panels"], [["resources-hardware", True], ["resources-tokens", True], ["resources-combined", False], ["resources-accounts", False], ["resources-usage", True]])
|
||||
self.assertEqual(combined["picks"], [["hardware", False, False], ["tokens", False, False], ["combined", True, False], ["accounts", True, False], ["usage", False, False]])
|
||||
self.assertEqual(set(combined["pressed"].values()), {"true"})
|
||||
self.assertEqual(set(combined["pressed"]), {*hardware, "agent:Skills", STAGE, "burn:done", SCOPE})
|
||||
self.assertEqual(combine["page"], {"tall": False, "wide": False, "fits": True})
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Exercise requirement 067: the rules page lists the hub rules grouped by kind with expiry chips and match counts, and drafts a new rule in a sheet with a live count."""
|
||||
|
||||
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 ASK
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-067-shots"))
|
||||
COMMANDS = (("make deploy", "s1"), ("make deploy --dry", "s1"), ("make deploy", "s2"), ("make test", "s1"), ("git status", "s1"))
|
||||
PAGE = """(async () => {@HELPERS@
|
||||
await screenShown(8000);
|
||||
(await until(() => document.getElementById("controls-tab-rules"), 8000)).click();
|
||||
if (!(await until(() => document.querySelector("#main .hub-rule-list li.hub-rule"), 8000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
window.e2eSameDocument = true;
|
||||
const fold = (id) => document.querySelector(`#main details[data-fold="${id}"]`);
|
||||
const shown = (node) => Boolean(node && node.getClientRects().length);
|
||||
const visible = (id) => all("li.hub-rule", fold(id)).filter(shown).length;
|
||||
const rowOf = (pattern) => all("#main li.hub-rule").find((node) => text(node.querySelector(".hub-rule-pattern")) === pattern);
|
||||
const chipOf = (row) => row.querySelector("[data-expiry]");
|
||||
const found = {
|
||||
firewall: ["settings", "patterns", "groups", "sets"].map((id) => Boolean(fold(id)) && !fold(id).open),
|
||||
heads: ["ask", "review", "decision"].map((id) => [text(fold(id).querySelector("summary strong")), text(fold(id).querySelector("summary .count"))]),
|
||||
};
|
||||
const deploy = rowOf("make deploy*");
|
||||
const toggle = deploy.querySelector('input.switch[role="switch"]');
|
||||
found.row = {
|
||||
on: Boolean(toggle) && toggle.checked, tool: text(deploy.querySelector(".hub-rule-tool")), scope: text(deploy.querySelector(".hub-rule-scope")), target: text(deploy.querySelector("[data-agents]")),
|
||||
tone: chipOf(deploy).dataset.tone, chip: text(chipOf(deploy)), count: text(deploy.querySelector(".hub-rule-count")), remove: Boolean(deploy.querySelector('button[aria-label="Delete rule"]')),
|
||||
};
|
||||
found.soon = [chipOf(rowOf("make test*")).dataset.tone, text(chipOf(rowOf("make test*"))), text(rowOf("make test*").querySelector(".hub-rule-count"))];
|
||||
const before = visible("ask");
|
||||
fold("ask").querySelector("summary").click();
|
||||
await sleep(150);
|
||||
found.collapsed = {open: fold("ask").open, rows: visible("ask"), review: visible("review"), decision: visible("decision")};
|
||||
fold("ask").querySelector("summary").click();
|
||||
await sleep(150);
|
||||
found.reopened = [before, visible("ask")];
|
||||
document.querySelector("#main [data-new-rule]").click();
|
||||
const form = await until(() => document.querySelector("#sheet .rule-form"), 4000);
|
||||
if (!form) {
|
||||
return {...found, error: "no sheet"};
|
||||
}
|
||||
const live = () => document.querySelector("#sheet [data-live-count]");
|
||||
const pattern = form.querySelector('input[aria-label="Pattern"]');
|
||||
const type = async (value, matched) => {
|
||||
pattern.value = value;
|
||||
pattern.dispatchEvent(new Event("input", {bubbles: true}));
|
||||
return until(() => live().dataset.matched === matched && text(live()), 4000);
|
||||
};
|
||||
found.sheet = text(document.querySelector("#sheet .sheet-head h2"));
|
||||
found.live = [await type("make deploy*", "3"), await type("make test*", "1"), await type("", "")];
|
||||
if (@CREATE@) {
|
||||
const made = "make e2e-@WIDTH@";
|
||||
await type(made, "0");
|
||||
form.requestSubmit();
|
||||
const row = await until(() => rowOf(made), 15000);
|
||||
found.created = {row: Boolean(row), closed: document.getElementById("sheet").hidden, same: window.e2eSameDocument === true, count: row ? text(row.querySelector(".hub-rule-count")) : null, head: text(fold("ask").querySelector("summary .count"))};
|
||||
} else {
|
||||
document.querySelector("#sheet .sheet-head button").click();
|
||||
}
|
||||
found.wide = document.documentElement.scrollWidth > innerWidth + 1;
|
||||
return found;
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(width: int, create: bool) -> str:
|
||||
return PAGE.replace("@HELPERS@", base.HELPERS).replace("@CREATE@", "true" if create else "false").replace("@WIDTH@", str(width))
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestRulesPage(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
authenticator = base.OrchestratorE2ECase.authenticator
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
self.claim("s1", "Skills")
|
||||
self.claim("s2", "Stage")
|
||||
self.snapshot()
|
||||
for command, session in COMMANDS:
|
||||
self.create_ask({**ASK, "command": command, "session": session})
|
||||
self.page_url = f"http://localhost:{self.port}/"
|
||||
|
||||
def stored(self, signer) -> None:
|
||||
now = time.time()
|
||||
self.signed_rule(signer, {"kind": "ask", "tool": "Bash", "pattern": "make deploy*", "scope": "/repo*", "expires": now + 30 * 86400})
|
||||
self.signed_rule(signer, {"kind": "ask", "tool": "Bash", "pattern": "make test*", "scope": "*", "expires": now + 86400 + 3600})
|
||||
self.signed_rule(signer, {"kind": "review", "tool": "", "pattern": "feature/*", "scope": "/repo/*", "expires": now + 10 * 86400})
|
||||
self.signed_rule(signer, {"kind": "decision", "tool": "", "pattern": "*", "scope": "*", "expires": now + 10 * 86400})
|
||||
|
||||
def steps(self, browser: str, create: bool) -> list[dict]:
|
||||
return [{"width": width, "height": height, "url": f"{self.page_url}?{width}#stream/rules", "wait": 1500, "probe": probe(width, create), "shot": str(OUT / f"{browser}-{width}-rules-page.png")} for width, height in base.WIDTHS]
|
||||
|
||||
def check(self, data: dict, create: bool) -> None:
|
||||
for index, ((width, _), found) in enumerate(zip(base.WIDTHS, data["results"], strict=True)):
|
||||
made = index if create else 0
|
||||
with self.subTest(width=width):
|
||||
self.assertNotIn("error", found, found)
|
||||
self.assertEqual(found["firewall"], [True] * 4)
|
||||
self.assertEqual(found["heads"], [["Ask", str(2 + made)], ["Review", "1"], ["Decision", "1"]])
|
||||
row = found["row"]
|
||||
self.assertEqual({key: row[key] for key in ("on", "tool", "scope", "target", "tone", "count", "remove")}, {"on": True, "tool": "Bash", "scope": "/repo*", "target": "all agents", "tone": "neutral", "count": "3 of the last 5 asks", "remove": True})
|
||||
self.assertRegex(row["chip"], r"^(29|30) days left$")
|
||||
self.assertEqual(found["soon"], ["bad", "1 day left", "1 of the last 5 asks"])
|
||||
self.assertEqual(found["collapsed"], {"open": False, "rows": 0, "review": 1, "decision": 1})
|
||||
self.assertEqual(found["reopened"], [2 + made, 2 + made])
|
||||
self.assertEqual(found["sheet"], "New rule")
|
||||
self.assertEqual(found["live"][:2], ["Would grant 3 of the last 5 asks", "Would grant 1 of the last 5 asks"])
|
||||
self.assertTrue(found["live"][2].startswith("Not counted: "), found["live"])
|
||||
if create:
|
||||
self.assertEqual(found["created"], {"row": True, "closed": True, "same": True, "count": "0 of the last 5 asks", "head": str(3 + made)})
|
||||
self.assertFalse(found["wide"])
|
||||
|
||||
def test_chromium_lists_the_rules_by_kind_and_creates_one_from_the_sheet_at_three_widths(self):
|
||||
authenticator = self.authenticator()
|
||||
self.stored(self.pin())
|
||||
data = self.drive(self.steps("chromium", True), authenticator)
|
||||
(OUT / "chromium-rules-page.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.assertEqual(data["errors"], [])
|
||||
self.check(data, True)
|
||||
self.assertEqual(sorted(rule["pattern"] for rule in self.httpd.hub.rules.listed() if rule["pattern"].startswith("make e2e-")), sorted(f"make e2e-{width}" for width, _ in base.WIDTHS))
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
|
||||
def test_firefox_lists_the_rules_by_kind_and_counts_the_draft_at_three_widths(self):
|
||||
self.stored(self.pin())
|
||||
data = self.drive(self.steps("firefox", False), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"))
|
||||
(OUT / "firefox-rules-page.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.check(data, False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,3 +1,5 @@
|
||||
"""Exercise requirement 068: one Schedules table of all four sources, source chips, inline edit on click and the passkey prompt for a foreign row."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
@@ -11,17 +13,20 @@ HERE = Path(__file__).resolve().parent
|
||||
sys.path[:0] = [str(HERE.parent), str(HERE)]
|
||||
|
||||
import hub_e2e_kit as base
|
||||
import test_home_bookmarks_e2e as bm
|
||||
import test_home_dashboard_e2e as dash
|
||||
from hub_case import HubCase
|
||||
from kvb_orchestrator import schedules
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-057-shots"))
|
||||
FOREIGN = {"name": "backup.timer", "kind": "timer", "owner": "other", "unit": "backup.timer", "file": "/u/backup.timer", "schedule": "OnCalendar=daily", "next": 1_900_000_000, "last": None, "event": "", "command": "", "off": "systemctl --user disable --now backup.timer"}
|
||||
HUB_UNIT = {**FOREIGN, "name": "kvb-orchestrator-tree.timer", "owner": "hub", "unit": "kvb-orchestrator-tree.timer", "off": ""}
|
||||
PROBE = """(async () => {@HELPERS@@HOME@
|
||||
const row = (name) => document.querySelector(`#main [data-schedule="${name}"]`);
|
||||
const rows = async () => (await (await fetch("/api/state")).json()).schedules.rows;
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-068-shots"))
|
||||
ROW = {"kind": "timer", "file": "", "task": "", "next": 1_900_000_000, "last": None, "on": True, "dropin": False, "error": "", "command": ""}
|
||||
SYSTEM = {**ROW, "name": "backup.timer", "source": "system", "unit": "backup.timer", "file": "/u/backup.timer", "schedule": "OnCalendar=daily", "dropin": True}
|
||||
HUB_UNIT = {**ROW, "name": "kvb-orchestrator-tree.timer", "source": "hub", "unit": "kvb-orchestrator-tree.timer", "schedule": "OnCalendar=*:0/5"}
|
||||
CLAUDE = {**ROW, "name": "repo f08cfd39", "source": "claude", "kind": "cron", "file": "/home/u/Repositories/github.com/me/repo/.claude/scheduled_tasks.json", "task": "f08cfd39",
|
||||
"schedule": "7 * * * *", "next": None, "last": 1_799_000_000, "command": "Triage the last two CI runs"}
|
||||
PROBE = """(async () => {@HELPERS@
|
||||
const panel = () => document.querySelector('#main [data-panel="stream/schedules"]');
|
||||
const row = (key) => panel().querySelector(`tr[data-schedule="${CSS.escape(key)}"]`);
|
||||
const sources = () => all("tbody tr", panel()).map((node) => node.dataset.source);
|
||||
const stored = async () => (await (await fetch("/api/state")).json()).schedules.rows;
|
||||
const settle = async (check, ms) => {
|
||||
const end = Date.now() + ms;
|
||||
while (Date.now() < end) {
|
||||
@@ -32,85 +37,72 @@ PROBE = """(async () => {@HELPERS@@HOME@
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const owner = await until(() => document.querySelector('#main [data-panel="stream/schedules"]') && row("coach"), 8000);
|
||||
if (!owner) {
|
||||
const edit = (key, value) => {
|
||||
row(key).querySelector("td[data-edit]").click();
|
||||
const field = row(key).querySelector("input.sched-input");
|
||||
field.value = value;
|
||||
field.dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", bubbles: true}));
|
||||
};
|
||||
if (!(await until(() => panel() && row("coach") && row("backup.timer"), 8000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
const tabs = all('#main [role="tab"]').map((tab) => [tab.dataset.tab, tab.getAttribute("aria-selected")]);
|
||||
const foreign = all("#main [data-schedule-foreign]").map((node) => ({name: node.dataset.scheduleForeign, switches: node.querySelectorAll('input[role="switch"]').length, copy: Boolean(node.querySelector('button[aria-label="Copy"]')), off: text(node.querySelector(".sched-off code"))}));
|
||||
const flip = async (wanted) => {
|
||||
row("coach").querySelector('input[role="switch"]').click();
|
||||
return settle(async () => (await rows()).coach.on === wanted && row("coach") && row("coach").querySelector('input[role="switch"]').checked === wanted, 8000);
|
||||
};
|
||||
const on = await flip(true);
|
||||
const off = await flip(false);
|
||||
const times = row("dream-popup").querySelector("input.sched-times");
|
||||
times.value = "21:30, 06:00";
|
||||
times.dispatchEvent(new Event("change", {bubbles: true}));
|
||||
const retimed = await settle(async () => JSON.stringify((await rows())["dream-popup"].at) === '["06:00","21:30"]', 8000);
|
||||
const wide = document.documentElement.scrollWidth > innerWidth + 1;
|
||||
const panel = document.querySelector('#main [data-panel="stream/schedules"]');
|
||||
const spot = [...panel.children].find((node) => node.closest("[data-panel], [data-item]") === panel) || panel;
|
||||
const item = await pinItem(spot);
|
||||
const label = item ? menuLabel(item) : null;
|
||||
if (item) {
|
||||
item.click();
|
||||
await sleep(300);
|
||||
}
|
||||
await closeMenu();
|
||||
return {hash: location.hash, tabs, foreign, on, off, retimed, wide, label, pinned: stored().includes("panel:stream/schedules")};
|
||||
const head = all("thead th", panel()).map((cell) => text(cell));
|
||||
const all4 = [...new Set(sources())];
|
||||
panel().querySelector('[data-source-chip="system"]').click();
|
||||
const withoutSystem = [...new Set(sources())];
|
||||
panel().querySelector('[data-source-chip="system"]').click();
|
||||
const back = [...new Set(sources())];
|
||||
edit("dream-popup", "21:30, 06:00");
|
||||
const retimed = await settle(async () => JSON.stringify((await stored())["dream-popup"].at) === '["06:00","21:30"]', 8000);
|
||||
const prompts = [];
|
||||
new MutationObserver(() => {
|
||||
const prompt = document.getElementById("passkey-prompt");
|
||||
if (prompt && !prompts.length) {
|
||||
prompts.push(text(prompt));
|
||||
}
|
||||
}).observe(document.body, {childList: true, subtree: true});
|
||||
await until(() => row("backup.timer"), 4000);
|
||||
edit("backup.timer", "08:00");
|
||||
await until(() => prompts.length, 8000);
|
||||
await sleep(1500);
|
||||
return {head, all4, withoutSystem, back, retimed, prompt: prompts[0] || null, reset: Boolean(row("backup.timer").querySelector("[data-reset]")), wide: document.documentElement.scrollWidth > innerWidth + 1};
|
||||
})()"""
|
||||
TILE = """(async () => {@HELPERS@@HOME@
|
||||
await go("home");
|
||||
const shown = await until(() => tile("panel:stream/schedules") && tile("panel:stream/schedules").querySelector('[data-schedule="coach"]'), 8000);
|
||||
return {tile: Boolean(shown), switches: shown ? tile("panel:stream/schedules").querySelectorAll('input[role="switch"]').length : 0};
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str) -> str:
|
||||
return template.replace("@HELPERS@", base.HELPERS).replace("@HOME@", dash.HOME)
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestSchedules(HubCase):
|
||||
class TestSchedulesEditor(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
authenticator = base.OrchestratorE2ECase.authenticator
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
self.council.mkdir(parents=True, exist_ok=True)
|
||||
(self.council / schedules.SCHEDULES_VIEW).write_text(json.dumps({"at": 1_800_000_000, "rows": [FOREIGN, HUB_UNIT]}), encoding="utf-8")
|
||||
(self.council / schedules.SCHEDULES_VIEW).write_text(json.dumps({"at": 1_800_000_000, "rows": [SYSTEM, HUB_UNIT, CLAUDE]}), encoding="utf-8")
|
||||
self.page_url = f"http://localhost:{self.port}/"
|
||||
|
||||
def test_chromium_opens_schedules_switches_coach_retimes_the_popup_shows_foreign_rows_read_only_and_pins_it_at_three_widths(self):
|
||||
steps = []
|
||||
for width, height in base.WIDTHS:
|
||||
at = {"width": width, "height": height}
|
||||
shot = OUT / f"chromium-{width}"
|
||||
steps += [
|
||||
{**at, "url": f"{self.page_url}?{width}-clear#stream", "wait": 600, "probe": bm.CLEAR, "shot": None},
|
||||
{**at, "url": f"{self.page_url}?{width}#stream/schedules", "wait": 1500, "probe": probe(PROBE), "shot": f"{shot}-schedules.png"},
|
||||
{**at, "url": None, "wait": 0, "probe": probe(TILE), "shot": f"{shot}-home.png"},
|
||||
]
|
||||
data = self.drive(steps, None)
|
||||
def test_chips_filter_a_click_edits_a_schedule_and_a_foreign_row_asks_the_passkey_at_three_widths(self):
|
||||
probe = PROBE.replace("@HELPERS@", base.HELPERS)
|
||||
steps = [{"width": width, "height": height, "url": f"{self.page_url}?{width}#stream/schedules", "wait": 1500, "probe": probe, "shot": str(OUT / f"chromium-{width}-schedules.png")} for width, height in base.WIDTHS]
|
||||
data = self.drive(steps, self.authenticator())
|
||||
(OUT / "chromium-schedules.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.assertEqual(data["errors"], [])
|
||||
results = iter(data["results"])
|
||||
for width, _ in base.WIDTHS:
|
||||
_, found, home = next(results), next(results), next(results)
|
||||
for (width, _), found in zip(base.WIDTHS, data["results"], strict=True):
|
||||
with self.subTest(width=width):
|
||||
self.assertNotIn("error", found, found)
|
||||
self.assertEqual(found["tabs"], [["tools", "false"], ["rules", "false"], ["groups", "false"], ["schedules", "true"]])
|
||||
self.assertEqual(found["hash"], "#stream/schedules")
|
||||
self.assertEqual((found["on"], found["off"], found["retimed"], found["wide"]), (True, True, True, False))
|
||||
self.assertEqual(found["foreign"], [
|
||||
{"name": "backup.timer", "switches": 0, "copy": True, "off": "systemctl --user disable --now backup.timer"},
|
||||
{"name": "kvb-orchestrator-tree.timer", "switches": 0, "copy": False, "off": None},
|
||||
])
|
||||
self.assertEqual((found["label"], found["pinned"]), ("Pin to Home", True))
|
||||
self.assertEqual(home, {"tile": True, "switches": 5})
|
||||
self.assertEqual(found["head"], ["Source", "Name", "Schedule", "Next", "Last", "On"])
|
||||
self.assertEqual(found["all4"], ["skills", "hub", "claude", "system"])
|
||||
self.assertEqual(found["withoutSystem"], ["skills", "hub", "claude"])
|
||||
self.assertEqual(found["back"], found["all4"])
|
||||
self.assertTrue(found["retimed"])
|
||||
self.assertIn("Retime backup.timer", found["prompt"] or "")
|
||||
self.assertTrue(found["reset"])
|
||||
self.assertFalse(found["wide"])
|
||||
stored = json.loads((self.council / schedules.SCHEDULES).read_text(encoding="utf-8"))
|
||||
self.assertEqual((stored["coach"], stored["dream-popup"]), ({"on": False, "every": 1}, {"on": False, "at": ["06:00", "21:30"]}))
|
||||
self.assertEqual(stored["dream-popup"], {"on": False, "at": ["06:00", "21:30"]})
|
||||
jobs = [job for job in self.httpd.hub.jobs.listed() if job.get("kind") == "schedule"]
|
||||
self.assertEqual({tuple(job["argv"]) for job in jobs}, {("timer", "backup.timer", "--at", "08:00")})
|
||||
self.assertEqual(len(jobs), len(base.WIDTHS))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -20,7 +20,7 @@ COMPOSER = (hub_support.HUB / "templates" / "page-composer.js").read_text(encodi
|
||||
HINTS = re.findall(r'^\s+"?[\w-]+"?: "([^"]+)",$', COMPOSER.split("const MAYDAY_ASK")[0], re.MULTILINE)
|
||||
SHAPE = """
|
||||
const hints = @HINTS@;
|
||||
const role = (node) => [["channel", ".composer-grid"], ["text", "textarea"], ["foot", ".mic-foot"], ["mic", "button.mic"], ["ptt", ".ptt-split"], ["mayday", ".mayday-toggle"],
|
||||
const role = (node) => [["channel", ".composer-grid"], ["text", "textarea"], ["chips", ".mic-chips"], ["foot", ".mic-foot"], ["file", ".mic-attach-file"], ["attach", ".mic-attach"], ["mic", "button.mic"], ["ptt", ".ptt-split"], ["mayday", ".mayday-toggle"],
|
||||
["spacer", ".spacer"], ["status", ".composer-status"], ["record", "button[aria-pressed]"]].find(([, selector]) => node.matches(selector))?.[0] || node.tagName.toLowerCase();
|
||||
const edges = (node) => ["Top", "Right", "Bottom", "Left"].map((side) => getComputedStyle(node)[`border${side}Width`]);
|
||||
const shape = (form) => {
|
||||
@@ -70,8 +70,8 @@ HOME = """(async () => {@HELPERS@@SHAPE@
|
||||
await sleep(400);
|
||||
return {misfits, first, wide: document.documentElement.scrollWidth > innerWidth + 1};
|
||||
})()"""
|
||||
FRAME = ["channel", "text", "foot"]
|
||||
FOOT = ["record", "status", "spacer", "mic", "ptt", "mayday"]
|
||||
FRAME = ["channel", "status", "text", "chips", "foot"]
|
||||
FOOT = ["record", "file", "attach", "mic", "ptt", "mayday"]
|
||||
LINES = {"channel": ["0px", "0px", "1px", "0px"], "text": ["0px", "0px", "0px", "0px"], "foot": "1px"}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
"""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."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
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-075-shots"))
|
||||
OPEN = """(async () => {@HELPERS@
|
||||
await screenShown(8000);
|
||||
const open = await until(() => document.getElementById("kanban-prune-open"), 8000);
|
||||
if (!open) {
|
||||
return {error: text(document.getElementById("main")).slice(0, 300)};
|
||||
}
|
||||
open.click();
|
||||
const list = () => all(".sheet-box .prune-list li[data-task]").map((node) => node.dataset.task);
|
||||
await until(() => list().length, 4000);
|
||||
const field = document.getElementById("prune-days");
|
||||
const first = {tasks: list(), ticked: all(".sheet-box .prune-list input:checked").length, days: field.value, sign: name(document.getElementById("prune-sign"))};
|
||||
const days = async (value) => {
|
||||
field.value = value;
|
||||
field.dispatchEvent(new Event("change", {bubbles: true}));
|
||||
await sleep(300);
|
||||
return {tasks: list(), invalid: field.getAttribute("aria-invalid")};
|
||||
};
|
||||
const ten = await days("10");
|
||||
const one = await days("1");
|
||||
const bad = await days("0");
|
||||
const back = await days("3");
|
||||
const dial = document.querySelector(".sheet-box .prune-dial");
|
||||
const attrs = () => ["role", "aria-valuemin", "aria-valuemax", "aria-valuenow", "aria-valuetext", "aria-readonly"].map((attr) => dial.getAttribute(attr));
|
||||
const opened = {attrs: attrs(), readout: text(dial.querySelector(".dial-readout")), ticks: all(".dial-tick", dial).length, long: all(".dial-tick.long", dial).length};
|
||||
const press = (key) => {
|
||||
dial.dispatchEvent(new KeyboardEvent("keydown", {key, bubbles: true, cancelable: true}));
|
||||
return dial.getAttribute("aria-valuenow");
|
||||
};
|
||||
dial.focus();
|
||||
const keys = ["PageDown", "Home", "ArrowLeft", "End", "ArrowRight", "PageDown", "Home", "PageUp"].map((key) => [key, press(key)]);
|
||||
const box = document.querySelector(".sheet-box").getBoundingClientRect();
|
||||
return {first, ten, one, bad, back, opened, keys, inside: box.left >= 0 && box.right <= innerWidth + 1, wide: document.documentElement.scrollWidth > innerWidth + 1};
|
||||
})()"""
|
||||
SIGN = """(async () => {@HELPERS@
|
||||
await screenShown(8000);
|
||||
(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 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 dial = document.querySelector(".sheet-box .prune-dial");
|
||||
dial.focus();
|
||||
dial.dispatchEvent(new KeyboardEvent("keydown", {key: "PageDown", bubbles: true, cancelable: true}));
|
||||
const started = Date.now() / 1000;
|
||||
document.getElementById("prune-sign").click();
|
||||
const chip = await until(() => document.getElementById("kanban-prune"), 20000);
|
||||
const waiting = await until(() => document.querySelector('.sheet-box .prune-dial[aria-readonly="true"]'), 8000);
|
||||
if (!chip || !waiting) {
|
||||
return {signs, error: text(document.querySelector(".sheet-box") || document.getElementById("main")).slice(0, 300)};
|
||||
}
|
||||
const left = () => text(document.querySelector("#kanban-prune .prune-left"));
|
||||
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)},
|
||||
wide: document.documentElement.scrollWidth > innerWidth + 1};
|
||||
})()"""
|
||||
WAIT = """(async () => {@HELPERS@
|
||||
await screenShown(8000);
|
||||
const chip = await until(() => document.getElementById("kanban-prune"), 8000);
|
||||
if (!chip) {
|
||||
return {error: text(document.getElementById("main")).slice(0, 300)};
|
||||
}
|
||||
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};
|
||||
})()"""
|
||||
|
||||
|
||||
def stamp(days: float) -> str:
|
||||
return (datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=days)).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def fixture_row(status: str, days: float) -> dict:
|
||||
return {"roles": {"Docs": "RA"}, "status": status, "updated": stamp(days), "title": "fixture task", "worker": "-"}
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestStalePrune(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)
|
||||
tasks = {"work/old-a": fixture_row("queued", 12), "work/old-b": fixture_row("blocked", 5), "work/fresh": fixture_row("queued", 1.5), "work/ended": fixture_row("done", 20)}
|
||||
(self.council / "rasci.json").write_text(json.dumps(tasks), encoding="utf-8")
|
||||
self.page_url = f"http://localhost:{self.port}/"
|
||||
|
||||
def step(self, width: int, height: int, probe: str, shot: str) -> dict:
|
||||
return {"width": width, "height": height, "url": f"{self.page_url}?{width}-{shot}#tasks/board", "wait": 1500, "probe": probe.replace("@HELPERS@", base.HELPERS), "shot": str(OUT / f"chromium-{width}-prune-{shot}.png")}
|
||||
|
||||
def test_the_dialog_lists_the_stale_tasks_for_n_days_and_the_deadline_sits_on_the_shared_dial(self):
|
||||
data = self.drive([self.step(width, height, OPEN, "dialog") 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["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["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))
|
||||
|
||||
def test_prune_signs_both_jobs_once_and_the_board_counts_down_to_the_deadline(self):
|
||||
width, height = base.WIDTHS[0]
|
||||
steps = [self.step(width, height, SIGN, "signed"), *(self.step(other, tall, WAIT, "countdown") for other, tall in base.WIDTHS)]
|
||||
data = self.drive(steps, self.authenticator())
|
||||
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
|
||||
signed, *waits = data["results"]
|
||||
self.assertNotIn("error", signed, signed)
|
||||
self.assertEqual(len(signed["signs"]), 1, signed)
|
||||
announce, apply = signed["signs"][0]
|
||||
since = int(apply["argv"][2])
|
||||
self.assertAlmostEqual(since, signed["started"], delta=5)
|
||||
self.assertEqual(announce, {"kind": "prune", "argv": ["announce", "--days", "3", "--deadline", str(since + 300), "work/old-a", "work/old-b"]})
|
||||
self.assertEqual(apply, {"kind": "prune", "argv": ["prune", "--since", str(since), "work/old-a", "work/old-b"], "not_before": since + 300})
|
||||
self.assertEqual(signed["chip"]["role"], "timer")
|
||||
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.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)])
|
||||
for (other, _), found in zip(base.WIDTHS, waits, strict=True):
|
||||
with self.subTest(width=other):
|
||||
self.assertEqual(found, {"chip": True, "waiting": True, "wide": False})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user