feat(hub): requirements 023 to 031 and line comments on grant-time code
023 box heads: one head band per box under its top border; in widget mode its controls join the widget title band. 024 Match card content: merge cards show their diff (the runner previews a review's tree against its worktree HEAD), every card carries legal and architecture scores, the null under command cards is gone. 025 Radio speak card: no hint text, a rounder flowing card, a MAYDAY toggle beside push to talk. 026 widget zoom: zoom a widget's content by keyboard and the context menu. 027 slash skill suggestions: every field that messages agents suggests skills after a slash, from a skills index the tree timer writes. 028 Resources accounts: an Accounts panel (provider, renewal, resets, usage and remaining, host-local, emails never in git) and panel checkboxes. 029 Controls layout: Rules and Groups pages laid out. 030 Yes/No answers as buttons, and nothing hides: rows the runner cannot run stay greyed with the reason. 031 mic in fields. Line comments (operator 2026-11-24): wherever code waits for a grant (Waits on Operator, the stream, the review overlay) selected lines or a right-clicked row take a comment that marks its lines and collects on the card; Deny opens with them as the reason and Call preselected, Grant sends them after the signed grant as one post. Requirement 003 decision 4 and its contract follow. Tests are written for every requirement and run once on this head. 🎯 Fix: 80 % 💥 Break: 20 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: ~95 % 🏆 Score: 61 🚦 Gate: ⛔ fix 80 % < 90, break 20 % > 5; security ~95 % < 100: ask the operator before the commit Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7d1926e3de
commit
2722cda1b5
120 files changed
+5372
-486
No files matched your search
+1
-1
@@ -79,7 +79,7 @@ try {
|
||||
if (plan.authenticator) {
|
||||
await page("WebAuthn.enable", {enableUI: false});
|
||||
const {authenticatorId} = await page("WebAuthn.addVirtualAuthenticator", {options: {protocol: "ctap2", transport: "internal", hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true}});
|
||||
await page("WebAuthn.addCredential", {authenticatorId, credential: {...plan.authenticator, isResidentCredential: false, signCount: 0}});
|
||||
await page("WebAuthn.addCredential", {authenticatorId, credential: {signCount: 0, ...plan.authenticator, isResidentCredential: false}});
|
||||
}
|
||||
for (const step of plan.steps) {
|
||||
await page("Emulation.setDeviceMetricsOverride", {width: step.width, height: step.height, deviceScaleFactor: 1, mobile: false});
|
||||
|
||||
+17
-13
@@ -214,11 +214,6 @@ COMPOSE_SEND = """(async () => {@HELPERS@
|
||||
})()""".replace("@HELPERS@", HELPERS)
|
||||
CLEAR_MAYDAY = """(async () => {@HELPERS@
|
||||
const questions = [];
|
||||
let accept = false;
|
||||
window.confirm = (question) => {
|
||||
questions.push(question);
|
||||
return accept;
|
||||
};
|
||||
const posted = [];
|
||||
const send = window.fetch.bind(window);
|
||||
window.fetch = (path, init) => {
|
||||
@@ -229,19 +224,28 @@ CLEAR_MAYDAY = """(async () => {@HELPERS@
|
||||
};
|
||||
await until(() => document.querySelector('#main [role="toolbar"]'), 8000);
|
||||
const toolbar = all('#main [role="toolbar"] button, #main [role="toolbar"] summary').map(name);@SPOT_OPEN@
|
||||
const button = await until(() => spot && all("form.composer .radio-cancel", spot).find((node) => name(node) === "Cancel mayday" && !node.hidden), 8000);
|
||||
const button = await until(() => spot && all("form.composer .mayday-toggle", spot).find((node) => name(node) === "Cancel mayday" && node.getAttribute("aria-pressed") === "true"), 8000);
|
||||
if (!button) {
|
||||
return {error: "no shown Cancel mayday button next to PTT", toolbar};
|
||||
return {error: "no pressed Cancel mayday toggle next to PTT", toolbar};
|
||||
}
|
||||
const [title, shownLabel, next] = [button.title, text(button), Boolean(button.previousElementSibling && button.previousElementSibling.matches(".ptt-split"))];
|
||||
const answer = async (yes) => {
|
||||
button.click();
|
||||
const box = await until(() => spot.querySelector("form.composer .mayday-confirm"), 4000);
|
||||
if (box) {
|
||||
questions.push(text(box.querySelector("p")));
|
||||
all("button", box).find((node) => text(node) === (yes ? "Cancel mayday" : "Cancel")).click();
|
||||
}
|
||||
};
|
||||
const shown = new Set(all("#toasts .toast"));
|
||||
const fresh = () => all("#toasts .toast").filter((node) => !shown.has(node)).map(text);
|
||||
button.click();
|
||||
await answer(false);
|
||||
await sleep(800);
|
||||
const declined = {question: questions.slice(), posted: posted.slice(), toasts: fresh()};
|
||||
accept = true;
|
||||
button.click();
|
||||
await answer(true);
|
||||
const done = await until(() => fresh().find((toast) => toast.startsWith("Cancel mayday")), 15000);
|
||||
return {toolbar, title: button.title, shown: text(button), declined, accepted: {question: questions.slice(declined.question.length), posted: posted.slice(declined.posted.length)}, done};
|
||||
await sleep(600);
|
||||
return {toolbar, title, shown: shownLabel, next, declined, accepted: {question: questions.slice(declined.question.length), posted: posted.slice(declined.posted.length)}, done, after: [text(button), button.getAttribute("aria-pressed")]};
|
||||
})()""".replace("@HELPERS@", HELPERS).replace("@SPOT_OPEN@", SPOT_OPEN)
|
||||
SPOT_SEND = """(async () => {@HELPERS@
|
||||
const questions = [];
|
||||
@@ -265,10 +269,10 @@ SPOT_SEND = """(async () => {@HELPERS@
|
||||
inline: [getComputedStyle(spot).position, spot.getBoundingClientRect().bottom <= main.getBoundingClientRect().top, spot.parentElement.nextElementSibling === main],
|
||||
toolbar: all('#main [role="toolbar"] > *').map((node) => name(node.tagName === "DETAILS" ? node.querySelector("summary") : node)),
|
||||
channels: all("option", channel).map((option) => option.value),
|
||||
record: all("button", form).filter((button) => button.hasAttribute("aria-pressed") && !button.classList.contains("mic")).map(text),
|
||||
record: all("button", form).filter((button) => button.hasAttribute("aria-pressed") && !button.matches(".mic, .mayday-toggle")).map(text),
|
||||
heads: all(".spot-head button", spot).length,
|
||||
send: all(".ptt-split :is(button, summary)", form).filter((node) => !node.closest(".menu-box")).map((node) => [name(node), node.title]),
|
||||
cancel: form.querySelector(".radio-cancel").hidden,
|
||||
mayday: [text(form.querySelector(".mayday-toggle")), form.querySelector(".mayday-toggle").getAttribute("aria-pressed"), form.querySelector(".mayday-toggle").previousElementSibling.matches(".ptt-split")],
|
||||
@FITS@,
|
||||
};
|
||||
await until(() => [...recipient.options].some((option) => option.value === "Stage"), 8000);
|
||||
|
||||
@@ -301,15 +301,16 @@ REPLY_HOME = """(async () => {@HELPERS@@PROBES@
|
||||
};
|
||||
const sent = await sendFrom(tile("radio"), "reply from the Home radio");
|
||||
const questions = [];
|
||||
window.confirm = (question) => {
|
||||
questions.push(question);
|
||||
return true;
|
||||
};
|
||||
const clear = all("form.composer button.radio-cancel", tile("radio")).find((button) => button.getAttribute("aria-label") === "Cancel mayday");
|
||||
const clear = all("form.composer button.mayday-toggle", tile("radio")).find((button) => text(button) === "Cancel mayday" && button.getAttribute("aria-pressed") === "true");
|
||||
const enabled = clear ? !clear.disabled : null;
|
||||
const shownBefore = new Set(all("#toasts .toast"));
|
||||
if (clear) {
|
||||
clear.click();
|
||||
const ask = await until(() => tile("radio").querySelector("form.composer .mayday-confirm"), 4000);
|
||||
if (ask) {
|
||||
questions.push(text(ask.querySelector("p")));
|
||||
all("button", ask).find((button) => text(button) === "Cancel mayday").click();
|
||||
}
|
||||
}
|
||||
const lifted = await until(() => all("#toasts .toast").filter((node) => !shownBefore.has(node)).map(text).find((entry) => entry.startsWith("Cancel mayday")), 15000);
|
||||
document.getElementById("toasts").replaceChildren();
|
||||
|
||||
@@ -154,10 +154,10 @@ HOME = """(async () => {@HELPERS@@PROBES@
|
||||
await sleep(200);
|
||||
}
|
||||
const menu = whole.querySelector(".radio-mode-menu:not([hidden])");
|
||||
const cancel = whole.querySelector("form.composer .radio-cancel");
|
||||
const cancel = whole.querySelector("form.composer .mayday-toggle");
|
||||
const tools = {
|
||||
menu: opens ? [active.getAttribute("aria-expanded"), Boolean(menu), menu ? box(menu).bottom <= box(whole).bottom + 1 : null] : null,
|
||||
cancel: cancel ? [cancel.hidden, cancel.title] : null,
|
||||
cancel: cancel ? [cancel.getAttribute("aria-pressed"), cancel.title] : null,
|
||||
};
|
||||
if (opens) {
|
||||
active.click();
|
||||
@@ -244,8 +244,9 @@ SPOT = """(async () => {@HELPERS@@PROBES@@SPEAKING@
|
||||
const edge = box(node);
|
||||
const [x, y] = [edge.left + edge.width / 2, edge.top + edge.height / 2];
|
||||
const hit = document.elementFromPoint(x, y);
|
||||
if (!(list.contains(node) && (y < box(list).top || y > box(list).bottom)) && !(hit === node || node.contains(hit) || (layer && hit && layer.contains(hit) && !layer.contains(node)))) {
|
||||
found.push(`${named(node)} <- ${hit ? `${hit.tagName}.${hit.getAttribute("class")}#${hit.id}` : "null"}`);
|
||||
if (!(list.contains(node) && (y <= box(list).top || y >= box(list).bottom)) &&!(hit === node || node.contains(hit) || (layer && hit && layer.contains(hit) && !layer.contains(node)))) {
|
||||
const under = document.elementsFromPoint(x, y).slice(0, 4).map((item) => `${item.tagName}.${item.getAttribute("class")}`).join(" > ");
|
||||
found.push(`${named(node)} <- ${hit ? `${hit.tagName}.${hit.getAttribute("class")}#${hit.id}` : "null"} at ${Math.round(x)},${Math.round(y)} list ${Math.round(box(list).top)}-${Math.round(box(list).bottom)} stack ${under}`);
|
||||
}
|
||||
}
|
||||
window.scrollTo(0, 0);
|
||||
|
||||
@@ -153,7 +153,7 @@ FACE = """(async () => {@HELPERS@@RADIO@
|
||||
await sleep(150);
|
||||
const menuFits = fits();
|
||||
await modeMenu("auto", false);
|
||||
const send = [name(spot.querySelector("form.composer .ptt-more")), spot.querySelector("form.composer .radio-cancel").hidden];
|
||||
const send = [name(spot.querySelector("form.composer .ptt-more")), spot.querySelector("form.composer .mayday-toggle").getAttribute("aria-pressed")];
|
||||
const stationsHead = text(spot.querySelector(".radio-station .group-title"));
|
||||
const ptt = spot.querySelector('form.composer button[type="submit"]');
|
||||
const pageFits = fits();
|
||||
|
||||
@@ -17,7 +17,7 @@ OUT = Path(os.environ.get("E2E_OUT", "/tmp/agents-controls-shots"))
|
||||
VIEWS = (*base.VIEWS, "hierarchy")
|
||||
READ = """
|
||||
const rect = (node) => node.getBoundingClientRect();
|
||||
const card = () => document.querySelector("#main .graph > .card.controls");
|
||||
const card = () => document.querySelector("#main .graph > .box-head");
|
||||
const bar = () => card() && card().querySelector(':scope > [role="toolbar"]');
|
||||
const menuOf = (label) => all("details.menu", bar()).find((node) => name(node.querySelector("summary")) === label);
|
||||
const wide = () => document.documentElement.scrollWidth > innerWidth + 1;
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
sys.path[:0] = [str(HERE.parent), str(HERE)]
|
||||
|
||||
import hub_e2e_kit as base
|
||||
import test_home_bookmarks_e2e as bm
|
||||
import test_home_dashboard_e2e as dash
|
||||
import test_match_review_e2e as matched
|
||||
import test_workbench_w4_e2e as w4
|
||||
from hub_case import HubCase
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/box-heads-shots"))
|
||||
VIEWS = {
|
||||
"tasks/match": "Match",
|
||||
"tasks/list": "Tasks",
|
||||
"tasks/board": "Tasks",
|
||||
"resources": "Resources",
|
||||
"agents/orbit": "Agents",
|
||||
"artifacts/orbit": "Artifacts",
|
||||
"stream/rules": "Controls",
|
||||
}
|
||||
PINNED = ["tasks/match", "tasks/list", "tasks/board", "agents/orbit", "artifacts/orbit"]
|
||||
PATTERNS = ["dots", "stripes", "waves", "grid", "rings"]
|
||||
BUTTON = """
|
||||
const buttonHeight = (root, selector) => {
|
||||
const found = all(selector, root).find((node) => node.getClientRects().length);
|
||||
return found ? Math.round(found.getBoundingClientRect().height) : null;
|
||||
};
|
||||
"""
|
||||
BAND = """(async () => {@HELPERS@@BUTTON@
|
||||
if (!(await screenShown(8000))) {
|
||||
return {error: "no screen"};
|
||||
}
|
||||
const main = document.getElementById("main");
|
||||
const head = await until(() => main.querySelector(".box-head"), 8000);
|
||||
if (!head) {
|
||||
return {error: text(main).slice(0, 300)};
|
||||
}
|
||||
await sleep(400);
|
||||
let first = true;
|
||||
for (let node = head; node !== main; node = node.parentElement) {
|
||||
first = first && node.parentElement.firstElementChild === node;
|
||||
}
|
||||
const style = getComputedStyle(main);
|
||||
const outer = main.getBoundingClientRect();
|
||||
const box = head.getBoundingClientRect();
|
||||
const tops = [...head.querySelectorAll(":scope > *, :scope > .box-slot > *")].filter((node) => node.getClientRects().length).map((node) => Math.round(node.getBoundingClientRect().top));
|
||||
return {
|
||||
label: head.getAttribute("aria-label"), count: all(".box-head", main).length, cards: all(".card.controls", main).length, first,
|
||||
edges: [box.top - outer.top - parseFloat(style.borderTopWidth), box.left - outer.left - parseFloat(style.borderLeftWidth), outer.right - parseFloat(style.borderRightWidth) - box.right].map((value) => Math.round(value * 10) / 10),
|
||||
height: Math.round(box.height), rows: new Set(tops).size, button: buttonHeight(head, "button.btn.small, button.btn"),
|
||||
wide: document.documentElement.scrollWidth > innerWidth + 1, violations: window.e2eViolations || null,
|
||||
};
|
||||
})()"""
|
||||
SEED = """(async () => {@HELPERS@
|
||||
await ViewStore.update("home.pins", () => @PINNED@.map((id) => ({kind: "panel", id, w: innerWidth > 640 ? 6 : 4, h: 5})));
|
||||
return true;
|
||||
})()"""
|
||||
TILES = """(async () => {@HELPERS@@HOME@@BUTTON@
|
||||
await go("home");
|
||||
await until(() => all("#main .home-tile").length === @COUNT@, 8000);
|
||||
await sleep(1200);
|
||||
const head = document.querySelector("#main .home-tile .home-head");
|
||||
return {
|
||||
head: head ? Math.round(head.getBoundingClientRect().height) : null, button: head ? buttonHeight(head, ".home-unpin") : null,
|
||||
tiles: all("#main .home-tile").map((tile) => ({
|
||||
key: tile.dataset.pin, heads: all(".home-body .box-head", tile).length, kanban: Boolean(tile.querySelector(".home-head .kanban-bar")),
|
||||
})),
|
||||
wide: document.documentElement.scrollWidth > innerWidth + 1, violations: window.e2eViolations || null,
|
||||
};
|
||||
})()"""
|
||||
EDGE = """(async () => {@HELPERS@
|
||||
if (!(await screenShown(8000))) {
|
||||
return {error: "no screen"};
|
||||
}
|
||||
const card = await until(() => document.querySelector("#main .match-card.front"), 8000);
|
||||
if (!card) {
|
||||
return {error: text(document.getElementById("main")).slice(0, 300)};
|
||||
}
|
||||
const head = card.querySelector(".match-head");
|
||||
const kept = card.dataset.pattern;
|
||||
const found = {};
|
||||
for (const pattern of @PATTERNS@) {
|
||||
card.dataset.pattern = pattern;
|
||||
await sleep(60);
|
||||
const shown = getComputedStyle(card);
|
||||
const after = getComputedStyle(head, "::before");
|
||||
found[pattern] = {
|
||||
border: shown.borderTopWidth, bar: shown.backgroundImage.startsWith("linear-gradient"), size: shown.backgroundSize.split(",")[0].trim(),
|
||||
flush: Math.round(head.getBoundingClientRect().top - card.getBoundingClientRect().top), top: after.top,
|
||||
mask: (after.maskImage || after.webkitMaskImage || "").replace(/\\s+/g, " "), hatch: after.backgroundImage !== "none",
|
||||
};
|
||||
}
|
||||
card.dataset.pattern = kept;
|
||||
return {found};
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str, **names: str) -> str:
|
||||
fills = {"@HELPERS@": base.HELPERS, "@HOME@": dash.HOME, "@BUTTON@": BUTTON, "@PINNED@": json.dumps(PINNED), "@COUNT@": str(len(PINNED)), "@PATTERNS@": json.dumps(PATTERNS)}
|
||||
fills.update({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 TestBoxHeads(HubCase):
|
||||
seed = base.OrchestratorE2ECase.seed
|
||||
subagents = base.OrchestratorE2ECase.subagents
|
||||
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.seed()
|
||||
self.cards()
|
||||
|
||||
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}-{view.replace('/', '-')}#{view}", "wait": 1500, "probe": probe(BAND), "shot": f"{shot}-{view.replace('/', '-')}.png"} for view in VIEWS]
|
||||
steps += [
|
||||
{**at, "url": f"{self.base}?{width}-clear#stream", "wait": 600, "probe": bm.CLEAR, "shot": None},
|
||||
{**at, "url": f"{self.base}?{width}-seed#stream", "wait": 800, "probe": probe(SEED), "shot": None},
|
||||
{**at, "url": f"{self.base}?{width}-home#home", "wait": 1500, "probe": probe(TILES), "shot": f"{shot}-home-tiles.png"},
|
||||
{**at, "url": f"{self.base}?{width}-edge#tasks/match", "wait": 1500, "probe": probe(EDGE), "shot": f"{shot}-match-edge.png"},
|
||||
]
|
||||
return steps
|
||||
|
||||
def check_band(self, row: dict, view: str, width: int, home: dict) -> None:
|
||||
self.assertNotIn("error", row, row)
|
||||
self.assertEqual((row["label"], row["count"], row["cards"], row["first"]), (VIEWS[view], 1, 0, True), row)
|
||||
self.assertEqual(row["edges"], [0, 0, 0], row)
|
||||
self.assertEqual((row["wide"], w4.quiet(row["violations"])), (False, []), row)
|
||||
if width == 1920 and row["rows"] == 1:
|
||||
self.assertLessEqual(abs(row["height"] - home["head"]), 1, (row, home["head"]))
|
||||
self.assertLessEqual(abs(row["button"] - home["button"]), 1, (row, home["button"]))
|
||||
else:
|
||||
self.assertLessEqual(row["height"], row["rows"] * (home["head"] + 6) + 1, (row, home["head"]))
|
||||
|
||||
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:
|
||||
bands = {view: next(results) for view in VIEWS}
|
||||
next(results)
|
||||
next(results)
|
||||
home = next(results)
|
||||
edge = next(results)
|
||||
with self.subTest(browser=browser, width=width, step="tiles"):
|
||||
self.assertEqual(sorted(tile["key"] for tile in home["tiles"]), sorted(f"panel:{view}" for view in PINNED), home)
|
||||
self.assertEqual([tile["key"] for tile in home["tiles"] if tile["heads"]], [], home)
|
||||
self.assertEqual([tile["key"] for tile in home["tiles"] if tile["kanban"]], ["panel:tasks/board"], home)
|
||||
self.assertEqual((home["wide"], w4.quiet(home["violations"])), (False, []), home)
|
||||
for view, row in bands.items():
|
||||
with self.subTest(browser=browser, width=width, view=view):
|
||||
self.check_band(row, view, width, home)
|
||||
with self.subTest(browser=browser, width=width, step="edge"):
|
||||
self.assertNotIn("error", edge, edge)
|
||||
for pattern, found in edge["found"].items():
|
||||
self.assertEqual((found["border"], found["bar"], found["size"], found["flush"], found["top"], found["hatch"]), ("0px", True, "100% 6px", 0, "0px", True), (pattern, found))
|
||||
self.assertTrue(found["mask"].startswith("linear-gradient(rgba(0, 0, 0, 0) 6px"), (pattern, found))
|
||||
|
||||
def test_chromium_puts_one_flush_band_on_every_box_and_keeps_the_card_bar_on_the_edge(self):
|
||||
data = self.drive(self.steps("chromium"), None, init=w4.GUARD)
|
||||
(OUT / "chromium-box-heads.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_puts_one_flush_band_on_every_box_and_keeps_the_card_bar_on_the_edge(self):
|
||||
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=w4.GUARD)
|
||||
(OUT / "firefox-box-heads.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.check(data, "firefox")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -250,7 +250,7 @@ class TestBulkGrant(base.OrchestratorE2ECase):
|
||||
self.assertEqual(collect["restored"], selecting, collect)
|
||||
self.assertEqual(collect["pale"], [True, True], collect)
|
||||
self.assertEqual(collect["counts"], ["1 selected", "2 selected", "1 selected", "2 selected", "3 selected"], collect)
|
||||
self.assertEqual((collect["pressed"], collect["posted"]), ([["true", True], ["true", False], ["true", True]], []), collect)
|
||||
self.assertEqual((collect["pressed"], collect["posted"]), ([["true", True], ["true", True], ["true", True]], []), collect)
|
||||
self.assertEqual((collect["labels"][0], collect["labels"][-1]), ("Grant selection (3)", "Direct"), collect)
|
||||
self.assertEqual(sum(label.startswith("Remove ") for label in collect["labels"]), 3, collect)
|
||||
self.assertEqual((sheet["label"], len(sheet["listed"])), ("Grant 3", 3), sheet)
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
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 hub_support
|
||||
from hub_case import HubCase
|
||||
from hub_support import verifier
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-029-shots"))
|
||||
TEMPLATES = hub_support.HUB / "templates"
|
||||
PRESENT = [f"/srv/p{index:02d}/.claude/settings.json" for index in range(10)]
|
||||
ABSENT = [f"/srv/a{index:02d}/.claude/settings.json" for index in range(30)]
|
||||
BROKEN = {PRESENT[3], PRESENT[7]}
|
||||
READ = """
|
||||
const box = () => document.querySelector("#main .fw-controls");
|
||||
const tab = (id) => document.getElementById(`controls-tab-${id}`);
|
||||
const flush = () => {
|
||||
const head = box().querySelector(":scope > .box-head");
|
||||
const main = document.getElementById("main");
|
||||
return Boolean(head && head.querySelector('[role="tablist"]')) && Math.abs(head.getBoundingClientRect().top - main.getBoundingClientRect().top - parseFloat(getComputedStyle(main).borderTopWidth)) <= 1;
|
||||
};
|
||||
const width = (label) => {
|
||||
const node = document.querySelector(`#main section[aria-label="${label}"]`);
|
||||
return node && node.getClientRects().length ? node.getBoundingClientRect().width : null;
|
||||
};
|
||||
const misaligned = (form) => {
|
||||
const boxes = all("label", form).filter((label) => label.querySelector(".field") && label.getClientRects().length).map((label) => label.getBoundingClientRect());
|
||||
return boxes.filter((one, index) => boxes.slice(index + 1).some((two) => Math.min(one.bottom, two.bottom) - Math.max(one.top, two.top) > 0 && Math.abs(one.top - two.top) > 1)).length;
|
||||
};
|
||||
const forms = () => all("#main form").filter((form) => form.getClientRects().length).map((form) => [form.getAttribute("aria-label") || form.className, misaligned(form)]);
|
||||
const sources = () => all("#main tbody[data-source]").map((body) => body.dataset.source).filter((source) => source !== "hub");
|
||||
const toggle = () => document.querySelector("#main .fw-missing");
|
||||
const wide = () => document.documentElement.scrollWidth > innerWidth + 1;
|
||||
"""
|
||||
RULES = """(async () => {@HELPERS@@READ@
|
||||
if (!(await until(() => box() && sources().length === 10 && toggle(), 15000))) {
|
||||
return {error: text(document.getElementById("main")), sources: sources()};
|
||||
}
|
||||
tab("rules").click();
|
||||
const folded = {sources: sources(), toggle: text(toggle()), pressed: toggle().getAttribute("aria-pressed")};
|
||||
toggle().click();
|
||||
await until(() => sources().length === 40, 4000);
|
||||
const opened = {count: sources().length, last: sources().slice(-1)[0], toggle: text(toggle()), pressed: toggle().getAttribute("aria-pressed")};
|
||||
toggle().click();
|
||||
await until(() => sources().length === 10, 4000);
|
||||
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();
|
||||
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;
|
||||
form.querySelector('input[aria-label="Group name"]').value = "@NAME@";
|
||||
for (const chip of chips) {
|
||||
chip.querySelector("input").checked = ["Skills", "Stage"].includes(text(chip));
|
||||
}
|
||||
const lit = chips.filter((chip) => getComputedStyle(chip).backgroundColor !== getComputedStyle(chips.find((other) => !other.querySelector("input").checked)).backgroundColor).map(text);
|
||||
form.requestSubmit();
|
||||
const row = await until(() => document.querySelector('#main [data-group="@NAME@"]'), 8000);
|
||||
return {
|
||||
flush: flush(), groups: width("Agent groups"), sets: width("Rule sets"), chips: chips.map(text), faces, lit, row: row ? text(row.querySelector(".muted")) : null,
|
||||
emptyRules: text(document.querySelector('#main form[aria-label="New rule set"] .fw-chips-field p')), forms: forms(), multiple: all("#main select[multiple]").length, wide: wide(),
|
||||
};
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str, name: str) -> str:
|
||||
for key, value in {"@HELPERS@": base.HELPERS, "@READ@": READ, "@NAME@": name}.items():
|
||||
template = template.replace(key, value)
|
||||
return template
|
||||
|
||||
|
||||
def view_files() -> list[dict]:
|
||||
present = [{"path": path, "exists": True, "folder": True, "sha256": "", "error": "unreadable: ValueError" if path in BROKEN else "", "settings": {}} for path in PRESENT]
|
||||
absent = [{"path": path, "exists": False, "folder": False, "sha256": "", "error": "no directory: create it first", "settings": {}} for path in ABSENT]
|
||||
return [*absent[:15], *reversed(present), *absent[15:]]
|
||||
|
||||
|
||||
class TestControlsSource(unittest.TestCase):
|
||||
def test_no_controls_form_uses_a_multi_select(self):
|
||||
for name in ("page-rules.js", "page-firewall.js"):
|
||||
with self.subTest(name=name):
|
||||
self.assertNotIn("multiple", (TEMPLATES / name).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestControlsLayout(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
self.claim("s1", "Skills")
|
||||
self.claim("s2", "Stage")
|
||||
self.claim("s3", "Store")
|
||||
self.snapshot()
|
||||
verifier.write_private(self.state / "firewall" / "view.json", {"written": 0, "files": view_files()})
|
||||
self.page_url = f"http://localhost:{self.port}/"
|
||||
|
||||
def test_chromium_lays_out_rules_and_groups_folds_missing_files_and_names_a_group_by_chips_at_three_widths(self):
|
||||
steps = []
|
||||
for width, height in base.WIDTHS:
|
||||
shot = OUT / f"chromium-{width}"
|
||||
steps += [
|
||||
{"width": width, "height": height, "url": f"{self.page_url}?{width}#stream/rules", "wait": 1500, "probe": probe(RULES, ""), "shot": f"{shot}-rules.png"},
|
||||
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(GROUPS, f"pair{width}"), "shot": f"{shot}-groups.png"},
|
||||
]
|
||||
data = self.drive(steps, None)
|
||||
(OUT / "chromium-controls-layout.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.assertEqual(data["errors"], [])
|
||||
results = iter(data["results"])
|
||||
errors_first = [PRESENT[3], PRESENT[7], *[path for path in PRESENT if path not in BROKEN]]
|
||||
for width, _ in base.WIDTHS:
|
||||
rules, groups = next(results), next(results)
|
||||
with self.subTest(width=width):
|
||||
self.assertNotIn("error", rules, rules)
|
||||
self.assertEqual(rules["folded"], {"sources": errors_first, "toggle": "show 30 missing", "pressed": "false"})
|
||||
self.assertEqual(rules["opened"], {"count": 40, "last": ABSENT[-1], "toggle": "hide 30 missing", "pressed": "true"})
|
||||
self.assertTrue(rules["flush"], rules)
|
||||
self.assertTrue(groups["flush"], groups)
|
||||
self.assertAlmostEqual(groups["groups"], rules["rules"], delta=1)
|
||||
self.assertAlmostEqual(groups["sets"], rules["rules"], delta=1)
|
||||
self.assertEqual([count for _, count in rules["forms"] + groups["forms"]], [0] * (len(rules["forms"]) + len(groups["forms"])), (rules["forms"], groups["forms"]))
|
||||
self.assertEqual((rules["multiple"], groups["multiple"], rules["wide"], groups["wide"]), (0, 0, False, False))
|
||||
self.assertEqual((groups["chips"], groups["faces"], sorted(groups["lit"])), (["Skills", "Stage", "Store"], 3, ["Skills", "Stage"]))
|
||||
self.assertEqual(groups["row"], "Skills, Stage")
|
||||
self.assertTrue(groups["emptyRules"].startswith("No rule yet: create one under Rules"), groups["emptyRules"])
|
||||
self.assertEqual(sorted((group["name"], group["members"]) for group in self.httpd.hub.groups.listed()), sorted((f"pair{width}", ["s1", "s2"]) for width, _ in base.WIDTHS))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -47,7 +47,7 @@ SHOW = """(async () => {@HELPERS@
|
||||
wrap.scrollIntoView({block: "start"});
|
||||
await sleep(100);
|
||||
return {
|
||||
title: text(document.querySelector("#main h2.title")),
|
||||
title: text(document.querySelector("#main .box-head h2.box-title")),
|
||||
tabs: {first, picked: tabs()},
|
||||
subs: all("#tabs .subtabs button").map(name),
|
||||
sources,
|
||||
@@ -162,8 +162,8 @@ GROUP_RULE = """(async () => {@HELPERS@
|
||||
(await until(() => document.querySelector('#main tbody[data-source="hub"] .fw-fold'), 10000)).click();
|
||||
const group = document.querySelector('#main form[aria-label="New agent group"]');
|
||||
group.querySelector('input[aria-label="Group name"]').value = "builders";
|
||||
for (const option of group.querySelector('select[aria-label="Members"]').options) {
|
||||
option.selected = true;
|
||||
for (const box of group.querySelectorAll('[aria-label="Members"] input[type="checkbox"]')) {
|
||||
box.checked = true;
|
||||
}
|
||||
group.requestSubmit();
|
||||
const row = await until(() => document.querySelector('#main [data-group="builders"]'), 8000);
|
||||
@@ -182,8 +182,8 @@ GROUP_RULE = """(async () => {@HELPERS@
|
||||
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 sets = document.querySelector('#main form[aria-label="New rule set"]');
|
||||
sets.querySelector('input[aria-label="Set name"]').value = "ci";
|
||||
for (const option of sets.querySelector('select[aria-label="Rules"]').options) {
|
||||
option.selected = option.textContent.includes("make e2e");
|
||||
for (const box of sets.querySelectorAll('[aria-label="Rules"] input[type="checkbox"]')) {
|
||||
box.checked = box.closest("label").textContent.includes("make e2e");
|
||||
}
|
||||
sets.requestSubmit();
|
||||
if (!await until(setRow, 8000)) {
|
||||
@@ -291,9 +291,9 @@ class TestFirewallE2E(HubCase):
|
||||
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]], "picked": [["tools", "false", True], ["rules", "true", False], ["groups", "false", True]]})
|
||||
self.assertEqual(shown["sources"], ["hub", str(self.settings), str(self.outside / "demo" / ".claude" / "settings.json")])
|
||||
self.assertEqual(shown["folded"], {"expanded": ["false"] * 3, "rows": 0})
|
||||
self.assertEqual(shown["opened"], ["true"] * 3)
|
||||
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["heads"], ["Action", "Tool", "Pattern", "Scope", "Source", "Hits (7 days)", ""])
|
||||
self.assertEqual(shown["chips"], [[chip, "true"] for chip in ("allow", "ask", "deny", "sandbox", "signed")])
|
||||
rows = shown["rows"]
|
||||
|
||||
@@ -62,7 +62,7 @@ KIT = """
|
||||
CLEAR = """(async () => {
|
||||
sessionStorage.clear();
|
||||
await Promise.all([ViewStore.update("home.pins", () => []), ViewStore.update("resources.hidden", () => []), ViewStore.update("resources.combinedHidden", () => []),
|
||||
ViewStore.set("resources.combined", false), ViewStore.set("resources.tokens", "interval")]);
|
||||
ViewStore.update("resources.panels", () => ["hardware", "tokens", "accounts"]), ViewStore.set("resources.tokens", "interval")]);
|
||||
return true;
|
||||
})()"""
|
||||
LOADED = """(async () => {@HELPERS@@READ@
|
||||
@@ -112,7 +112,9 @@ METRIC = """(async () => {@HELPERS@@HOME@@READ@@KIT@
|
||||
const back = Boolean(await until(() => lineIds(document.querySelector(panel("hardware"))).length === @COUNT@, 5000));
|
||||
await sleep(200);
|
||||
const allState = [starOf(panel("hardware")).getAttribute("aria-pressed"), starOf(panel("hardware")).getAttribute("title")];
|
||||
switched("combined").click();
|
||||
await pickPanel("combined", true);
|
||||
await pickPanel("hardware", false);
|
||||
await pickPanel("tokens", false);
|
||||
const combinedOn = Boolean(await until(() => charts().join() === "combined" && burn().length === 2, 5000));
|
||||
const combined = await press(panel("combined"));
|
||||
return {cpuOnly, hardware, cpuTitle, tokens, back, allState, combinedOn, combined, axisOverlaps, stored: (ViewStore.get("home.pins") || []).map((pin) => [pin.kind, pin.id, pin.view || null])};
|
||||
@@ -120,7 +122,9 @@ METRIC = """(async () => {@HELPERS@@HOME@@READ@@KIT@
|
||||
COMBINED_OFF = """(async () => {@HELPERS@@HOME@@READ@@KIT@
|
||||
await go("resources");
|
||||
await until(() => charts().join() === "combined", 8000);
|
||||
switched("combined").click();
|
||||
await pickPanel("hardware", true);
|
||||
await pickPanel("tokens", true);
|
||||
await pickPanel("combined", false);
|
||||
const off = Boolean(await until(() => charts().length === 2 && lines().length === @COUNT@, 8000));
|
||||
await sleep(300);
|
||||
return {off, hardware: [starOf(panel("hardware")).getAttribute("aria-pressed"), starOf(panel("hardware")).getAttribute("title")]};
|
||||
@@ -384,7 +388,7 @@ class TestHomeBookmarks(HubCase):
|
||||
loaded = next(results)
|
||||
self.assertTrue(loaded["drawn"], loaded)
|
||||
found = next(results)
|
||||
self.assertEqual((found["charts"], found["chips"], found["inHead"]), ([True, True, True], 0, True), found)
|
||||
self.assertEqual((found["charts"], found["chips"], found["inHead"]), ([True] * 4, 0, True), found)
|
||||
self.assertEqual(found["tree"], [True], found)
|
||||
self.assertTrue(found["rows"]["repo"] and all(found["rows"]["repo"]), found)
|
||||
self.assertTrue(found["rows"]["branch"] and all(found["rows"]["branch"]), found)
|
||||
|
||||
@@ -151,10 +151,10 @@ class TestHubInbox(base.OrchestratorE2ECase):
|
||||
stops = []
|
||||
with mock.patch.object(batches, "UNDO", 0.3):
|
||||
data = self.drive(steps, self.authenticator() if signs else None, driver, binary)
|
||||
(OUT / f"{browser}-inbox-deny-selection.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
if signs:
|
||||
self.settle(lambda: len([call for call in self.scripts.calls if call[0] == skill_scripts.RASCI]) >= 2 * len(WIDTHS))
|
||||
stops = [args for script, args in self.scripts.calls if script == skill_scripts.RASCI]
|
||||
(OUT / f"{browser}-inbox-deny-selection.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], [])
|
||||
denied = []
|
||||
for found, (width, _) in zip(data["results"], WIDTHS, strict=True):
|
||||
|
||||
@@ -46,6 +46,8 @@ from hub_e2e_radio import (
|
||||
from hub_support import HOST_STATE
|
||||
from kvb_orchestrator import skill_scripts
|
||||
|
||||
SPEAK_CHANNELS = [channel for channel in CHOICE_CHANNELS if channel != "mayday"]
|
||||
PRESSED = ["Cancel mayday", "true", True]
|
||||
SEND_GROUP = [["PTT", "PTT: push to transmit the message; your passkey signs it"], ["More send options", "More: send a test message only you hear"]]
|
||||
|
||||
|
||||
@@ -231,7 +233,7 @@ class TestHubRadio(base.OrchestratorE2ECase):
|
||||
self.assertEqual(data["errors"], [])
|
||||
composed, plain, again, sent = data["results"]
|
||||
self.assertNotIn("error", composed)
|
||||
self.assertEqual(composed["channels"], ["post", "call", "newsletter", "broadcast", "pan-pan", "security", "mayday"])
|
||||
self.assertEqual(composed["channels"], SPEAK_CHANNELS)
|
||||
self.assertIn("Stage", composed["recipients"])
|
||||
self.assertEqual(composed["recording"], "true")
|
||||
self.assertEqual(composed["text"], "hello from the mic second line", composed)
|
||||
@@ -262,7 +264,7 @@ class TestHubRadio(base.OrchestratorE2ECase):
|
||||
with self.subTest(width=width):
|
||||
self.assertNotIn("error", result)
|
||||
self.assertEqual(result["toolbar"], ["Priority", "Day/Night", "Drain", "Suspend", "Resume", "Status"])
|
||||
self.assertEqual((result["title"], result["shown"]), ("Cancel mayday: lift the radio silence so the agents write again; your passkey signs it", "Cancel mayday"))
|
||||
self.assertEqual((result["title"], result["shown"], result["next"]), ("Cancel mayday: lift the radio silence so the agents write again; your passkey signs it", "Cancel mayday", True))
|
||||
self.assertEqual(result["declined"], {"question": [question], "posted": [], "toasts": []})
|
||||
self.assertEqual(result["accepted"], {"question": [question], "posted": ["/api/board/sign", "/api/board/clear-mayday"]})
|
||||
self.assertTrue((result["done"] or "").startswith("Cancel mayday: done"), result)
|
||||
@@ -284,7 +286,6 @@ class TestHubRadio(base.OrchestratorE2ECase):
|
||||
(OUT / "chromium-radio-spot.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.assertEqual(data["errors"], [])
|
||||
labels = dict(zip(CHOICE_CHANNELS, ["Post", "Call", "Newsletter", "Broadcast", "Pan-Pan", "Sécurité", "Mayday"], strict=True))
|
||||
mayday = "Send a mayday to all? All agents pause writing steps until you cancel it."
|
||||
jumps, walked = data["results"][: len(WIDTHS)], data["results"][len(WIDTHS) :]
|
||||
for jump, (width, _) in zip(jumps, WIDTHS, strict=True):
|
||||
with self.subTest(width=width, part="radio spot on every tab"):
|
||||
@@ -297,13 +298,13 @@ class TestHubRadio(base.OrchestratorE2ECase):
|
||||
self.assertNotIn("error", probe)
|
||||
self.assertEqual((sent["closed"], sent["open"]), ([True, "false"], [False, "true", True]))
|
||||
self.assertEqual(sent["inline"], ["static", True, True])
|
||||
self.assertEqual((sent["toolbar"], sent["channels"], sent["record"]), (["Priority", "Day/Night", "Status"], CHOICE_CHANNELS, ["Record"]))
|
||||
self.assertEqual((sent["heads"], sent["send"], sent["cancel"]), (0, SEND_GROUP, False))
|
||||
self.assertEqual((sent["toolbar"], sent["channels"], sent["record"]), (["Priority", "Day/Night", "Status"], SPEAK_CHANNELS, ["Record"]))
|
||||
self.assertEqual((sent["heads"], sent["send"], sent["mayday"]), (0, SEND_GROUP, PRESSED))
|
||||
self.assertEqual((sent["tall"], sent["wide"]), (width == 390, False))
|
||||
self.assertEqual([run["cls"] for run in sent["runs"]], CHOICE_CHANNELS)
|
||||
self.assertEqual([run["cls"] for run in sent["runs"]], SPEAK_CHANNELS)
|
||||
for run in sent["runs"]:
|
||||
direct = run["cls"] in ("post", "call")
|
||||
self.assertEqual((run["direct"], run["question"], run["left"]), (direct, [mayday] if run["cls"] == "mayday" else [], ""), run)
|
||||
self.assertEqual((run["direct"], run["question"], run["left"]), (direct, [], ""), run)
|
||||
self.assertTrue((run["toast"] or "").startswith(f"{labels[run['cls']]} to {'Stage' if direct else 'all'}: sent"), run)
|
||||
self.assertEqual(saved["clashes"], [{"found": [], "outside": []}])
|
||||
self.assertEqual(saved["tones"], ["MAYDAY / PAN-PAN", "Reviews, asks, decisions", "Post and calls to you", "All radio", "Squelch", "speak while CPU < 50 %"])
|
||||
@@ -314,7 +315,7 @@ class TestHubRadio(base.OrchestratorE2ECase):
|
||||
self.assertEqual(read, {"squelch": float(squelch), "radio": radio_bell, "post": post, "tall": width == 390, "wide": False})
|
||||
heads = {"post": ["post", "--to", "Stage"], "call": ["send", "call", "--to", "Stage"], "newsletter": ["post"]}
|
||||
radio = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO]
|
||||
sends = [(width, cls) for width, _ in WIDTHS for cls in CHOICE_CHANNELS]
|
||||
sends = [(width, cls) for width, _ in WIDTHS for cls in SPEAK_CHANNELS]
|
||||
self.assertEqual([args[:-1] for args in radio], [[*heads.get(cls, ["send", cls]), "--session", "Operator"] for _, cls in sends])
|
||||
for args, (width, cls) in zip(radio, sends, strict=True):
|
||||
with self.subTest(width=width, cls=cls):
|
||||
@@ -337,7 +338,6 @@ class TestHubRadio(base.OrchestratorE2ECase):
|
||||
(OUT / "firefox-radio-spot.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], [])
|
||||
labels = dict(zip(CHOICE_CHANNELS, ["Post", "Call", "Newsletter", "Broadcast", "Pan-Pan", "Sécurité", "Mayday"], strict=True))
|
||||
mayday = "Send a mayday to all? All agents pause writing steps until you cancel it."
|
||||
question = "Lift the radio silence of the active mayday?"
|
||||
hint = "Cancel mayday: lift the radio silence so the agents write again; your passkey signs it"
|
||||
results = iter(data["results"])
|
||||
@@ -348,19 +348,19 @@ class TestHubRadio(base.OrchestratorE2ECase):
|
||||
with self.subTest(browser="firefox", width=width, part="every class unsigned"):
|
||||
self.assertNotIn("error", sent, sent)
|
||||
self.assertEqual((sent["closed"], sent["open"], sent["inline"]), ([True, "false"], [False, "true", True], ["static", True, True]))
|
||||
self.assertEqual((sent["toolbar"], sent["channels"], sent["record"]), (["Priority", "Day/Night", "Status"], CHOICE_CHANNELS, ["Record"]))
|
||||
self.assertEqual((sent["heads"], sent["send"], sent["cancel"]), (0, SEND_GROUP, False))
|
||||
self.assertEqual((sent["toolbar"], sent["channels"], sent["record"]), (["Priority", "Day/Night", "Status"], SPEAK_CHANNELS, ["Record"]))
|
||||
self.assertEqual((sent["heads"], sent["send"], sent["mayday"]), (0, SEND_GROUP, PRESSED))
|
||||
self.assertEqual((sent["tall"], sent["wide"]), (width == 390, False))
|
||||
self.assertEqual([run["cls"] for run in sent["runs"]], CHOICE_CHANNELS)
|
||||
self.assertEqual([run["cls"] for run in sent["runs"]], SPEAK_CHANNELS)
|
||||
for run in sent["runs"]:
|
||||
direct = run["cls"] in ("post", "call")
|
||||
self.assertEqual((run["direct"], run["question"], run["left"]), (direct, [mayday] if run["cls"] == "mayday" else [], f"spot {width} {run['cls']}"), run)
|
||||
self.assertEqual((run["direct"], run["question"], run["left"]), (direct, [], f"spot {width} {run['cls']}"), run)
|
||||
self.assertTrue((run["toast"] or "").startswith(f"{labels[run['cls']]} to {'Stage' if direct else 'all'}: not signed"), run)
|
||||
self.assertIn("NotAllowedError", run["toast"], run)
|
||||
with self.subTest(browser="firefox", width=width, part="cancel mayday next to PTT unsigned"):
|
||||
self.assertNotIn("error", cleared, cleared)
|
||||
self.assertEqual(cleared["toolbar"], ["Priority", "Day/Night", "Drain", "Suspend", "Resume", "Status"])
|
||||
self.assertEqual((cleared["title"], cleared["shown"]), (hint, "Cancel mayday"))
|
||||
self.assertEqual((cleared["title"], cleared["shown"], cleared["next"], cleared["after"]), (hint, "Cancel mayday", True, ["Cancel mayday", "true"]))
|
||||
self.assertEqual(cleared["declined"], {"question": [question], "posted": [], "toasts": []})
|
||||
self.assertEqual(cleared["accepted"], {"question": [question], "posted": ["/api/board/sign"]})
|
||||
self.assertTrue((cleared["done"] or "").startswith("Cancel mayday: not signed"), cleared)
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
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_support import ASK
|
||||
from kvb_orchestrator import batches, skill_scripts
|
||||
|
||||
COMMAND = "git commit -m 'line comments'"
|
||||
TITLE = "feat: overlay comments"
|
||||
DIFF = [{"path": "a.txt", "status": "M", "mode": "100644", "additions": 2, "deletions": 1, "patch": "@@ -1,2 +1,3 @@\n keep\n-old\n+new\n+more", "note": ""}]
|
||||
FILES = ("src/app.py", "src/view.js")
|
||||
CAPTURE = """
|
||||
navigator.credentials.get = @SIGNS@ ? navigator.credentials.get.bind(navigator.credentials) : () => Promise.reject(new DOMException("The operator canceled.", "NotAllowedError"));
|
||||
const posted = [];
|
||||
const send = window.fetch.bind(window);
|
||||
window.fetch = (path, init) => {
|
||||
if (["/api/sign", "/api/inbox/approve", "/api/messages/sign", "/api/messages"].includes(String(path))) {
|
||||
const body = JSON.parse(init.body);
|
||||
posted.push([String(path), body.text || null, (body.items || []).map((entry) => [entry.kind, entry.verb, entry.channel || "", entry.reason || ""])]);
|
||||
}
|
||||
return send(path, init);
|
||||
};
|
||||
const rightClick = async (cell) => {
|
||||
const box = cell.getBoundingClientRect();
|
||||
cell.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, clientX: box.left + 4, clientY: box.top + 4}));
|
||||
await sleep(200);
|
||||
const first = document.querySelector('.ctx-menu:not([hidden]) [role="menuitem"]');
|
||||
const label = first ? text(first.querySelector(".ctx-label")) : null;
|
||||
if (first) {
|
||||
first.click();
|
||||
}
|
||||
return label;
|
||||
};
|
||||
const listed = (root) => (root ? all(".feedback-list li.line-mark", root).map(text) : null);
|
||||
"""
|
||||
STREAM = """(async () => {@HELPERS@@UNLABELLED@@CAPTURE@
|
||||
const rowOf = () => all("#main .feed > li.k-ask").find((li) => li.textContent.includes(@COMMAND@) && li.querySelector("tr[data-line]"));
|
||||
if (!(await until(rowOf, 10000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
const item = await rightClick(all("tr[data-line]", rowOf())[1].querySelector("td.code"));
|
||||
const field = await until(() => document.querySelector(".sheet-box textarea"), 4000);
|
||||
if (!field) {
|
||||
return {error: "no comment sheet", item};
|
||||
}
|
||||
const sheet = {title: text(document.querySelector(".sheet-head .panel-title")), range: text(document.querySelector(".sheet-box .who code")), unlabelled: unlabelled(document.querySelector("#sheet .sheet-box"))};
|
||||
field.value = "stream note";
|
||||
all(".sheet-box button").find((button) => name(button) === "Save comment").click();
|
||||
await until(() => rowOf() && rowOf().querySelector("tr.match-mark"), 4000);
|
||||
const marked = {rows: all("tr.marked", rowOf()).map((row) => row.dataset.line), notes: all("tr.match-mark", rowOf()).map(text), list: listed(rowOf()), open: !document.getElementById("sheet").hidden};
|
||||
all(".deny-split button", rowOf()).find((button) => name(button) === "Deny").click();
|
||||
const reason = await until(() => document.querySelector(".sheet-box .deny-reason textarea"), 4000);
|
||||
const deny = {reason: reason ? reason.value : null, channel: (document.querySelector(".sheet-box .deny-channels input:checked") || {}).value || null, to: (document.querySelector(".sheet-box .deny-recipient select") || {}).value || null};
|
||||
all(".sheet-box .actions button").find((button) => text(button) === "Deny").click();
|
||||
await until(() => posted.some(([path]) => path === (@SIGNS@ ? "/api/inbox/approve" : "/api/sign")), 8000);
|
||||
await sleep(1200);
|
||||
return {item, sheet, marked, deny, posted, kept: listed(rowOf()), wide: document.documentElement.scrollWidth > innerWidth + 1};
|
||||
})()"""
|
||||
OVERLAY = """(async () => {@HELPERS@@UNLABELLED@@CAPTURE@
|
||||
const row = () => document.querySelector('#main .inbox-list > li[data-ref="@REVIEW@"]');
|
||||
if (!(await until(row, 8000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
row().querySelector(".headline").click();
|
||||
const lines = () => all("#sheet .review-file[data-path='src/app.py'] tr[data-line]");
|
||||
if (!(await until(() => lines().length, 8000))) {
|
||||
return {error: text(document.getElementById("sheet"))};
|
||||
}
|
||||
const target = lines()[2];
|
||||
const item = await rightClick(target.querySelector("td.code"));
|
||||
const field = await until(() => document.querySelector("#sheet tr.match-comment textarea"), 4000);
|
||||
if (!field) {
|
||||
return {error: "no inline comment field", item};
|
||||
}
|
||||
const inline = {after: field.closest("tr").previousElementSibling === target, unlabelled: unlabelled(field.closest("tr"))};
|
||||
field.value = "overlay note";
|
||||
all("#sheet tr.match-comment button").find((button) => name(button) === "Save comment").click();
|
||||
await until(() => document.querySelector("#sheet tr.match-mark"), 4000);
|
||||
const marked = {rows: all("#sheet tr.marked").map((tr) => tr.dataset.line), notes: all("#sheet tr.match-mark").map(text), list: all("#sheet .review-notes li.line-mark").map(text), field: Boolean(document.querySelector("#sheet tr.match-comment")), open: !document.getElementById("sheet").hidden};
|
||||
document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));
|
||||
await until(() => document.getElementById("sheet").hidden, 4000);
|
||||
const card = listed(row());
|
||||
row().querySelector(".item-actions button.primary").click();
|
||||
await until(() => posted.some(([path]) => path === (@SIGNS@ ? "/api/messages" : "/api/sign")), 10000);
|
||||
await sleep(1200);
|
||||
return {item, inline, marked, card, posted, kept: listed(row()), wide: document.documentElement.scrollWidth > innerWidth + 1};
|
||||
})()"""
|
||||
|
||||
|
||||
def review_page() -> str:
|
||||
sections = []
|
||||
for path in FILES:
|
||||
rows = "".join(f'<tr class="add"><td class="num"></td><td class="num">{line}</td><td class="sign">+</td><td class="code">{html.escape(path)} line {line}</td></tr>' for line in range(1, 6))
|
||||
sections.append(f'<details class="file" data-path="{path}"><summary><span class="badge added" title="added">A</span><span class="path">{path}</span>'
|
||||
f'<span class="stat"><span class="add">+5</span><span class="del">−0</span></span></summary><table class="diff"><tbody>{rows}</tbody></table></details>')
|
||||
return f'<!DOCTYPE html><html><body><section class="group" id="staged" data-files="2">{"".join(sections)}</section></body></html>'
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestLineComments(base.OrchestratorE2ECase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.ask = self.create_ask({**ASK, "command": COMMAND, "timeout": 3600, "diff": DIFF})
|
||||
arguments = {**self.arguments(TITLE, "", self.page("overlay.html", review_page())), "worktree": "/repo/.worktrees/feature/overlay", "branch": "feature/overlay", "agent": "Skills session"}
|
||||
result = self.tool("review_request", arguments)
|
||||
self.assertFalse(result["isError"], result)
|
||||
self.review = result["structuredContent"]["id"]
|
||||
|
||||
def probe(self, template: str, signs: bool) -> str:
|
||||
values = {"@HELPERS@": base.HELPERS, "@UNLABELLED@": base.UNLABELLED, "@CAPTURE@": CAPTURE, "@SIGNS@": "true" if signs else "false", "@COMMAND@": json.dumps(COMMAND), "@REVIEW@": f"review:{self.review}"}
|
||||
for key, value in values.items():
|
||||
template = template.replace(key, value)
|
||||
return template
|
||||
|
||||
def steps(self, browser: str, signs: bool) -> list[dict]:
|
||||
local = f"http://localhost:{self.port}/"
|
||||
return [
|
||||
{"width": 1366, "height": 768, "url": f"{local}?stream#stream", "wait": 1500, "probe": self.probe(STREAM, signs), "shot": self.shot(f"{browser}-1366-line-comments-stream")},
|
||||
{"width": 1366, "height": 768, "url": f"{local}?overlay#stream/inbox", "wait": 1200, "probe": self.probe(OVERLAY, signs), "shot": self.shot(f"{browser}-1366-line-comments-overlay")},
|
||||
]
|
||||
|
||||
def check(self, data: dict, signs: bool) -> None:
|
||||
self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], [])
|
||||
stream, overlay = data["results"]
|
||||
self.assertNotIn("error", stream, stream)
|
||||
self.assertEqual((stream["item"], stream["sheet"]), ("Comment", {"title": "Comment", "range": "a.txt:2", "unlabelled": []}))
|
||||
self.assertEqual(stream["marked"], {"rows": ["2", "2"], "notes": ["stream note"], "list": ["a.txt:2stream note"], "open": False})
|
||||
self.assertEqual(stream["deny"], {"reason": "a.txt:2: stream note", "channel": "call", "to": "Skills session"})
|
||||
denial = [["ask", "reject", "call", "a.txt:2: stream note"]]
|
||||
self.assertEqual(stream["posted"], [["/api/sign", None, denial], *([["/api/inbox/approve", None, denial]] if signs else [])])
|
||||
self.assertNotIn("error", overlay, overlay)
|
||||
self.assertEqual((overlay["item"], overlay["inline"]), ("Comment", {"after": True, "unlabelled": []}))
|
||||
self.assertEqual(overlay["marked"], {"rows": ["3"], "notes": ["overlay note"], "list": ["src/app.py:3overlay note"], "field": False, "open": True})
|
||||
self.assertEqual(overlay["card"], ["src/app.py:3overlay note"])
|
||||
grant = [["review", "approve", "", ""]]
|
||||
notes = f"Granted: {TITLE}. Notes:\nsrc/app.py:3: overlay note"
|
||||
self.assertEqual(overlay["posted"], [["/api/sign", None, grant], ["/api/inbox/approve", None, grant], ["/api/messages/sign", notes, []], ["/api/messages", notes, []]] if signs else [["/api/sign", None, grant]])
|
||||
if not signs:
|
||||
self.assertEqual((stream["kept"], overlay["kept"]), (["a.txt:2stream note"], ["src/app.py:3overlay note"]))
|
||||
self.assertFalse(stream["wide"] or overlay["wide"])
|
||||
|
||||
def test_chromium_line_comments_reach_the_requester_in_the_deny_call_and_after_the_grant_as_one_post(self):
|
||||
with mock.patch.object(batches, "UNDO", 0.3):
|
||||
data = self.drive(self.steps("chromium", True), self.authenticator())
|
||||
self.settle(lambda: self.status(self.review) == "approved" and any(ask["status"] == "denied" for ask in self.httpd.hub.asks.listed() if ask["command"] == COMMAND))
|
||||
(base.OUT / "chromium-line-comments.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.check(data, True)
|
||||
asks = [(ask["status"], ask.get("channel", ""), ask.get("reason", "")) for ask in self.httpd.hub.asks.listed() if ask["command"] == COMMAND]
|
||||
self.assertEqual(asks, [("denied", "call", "a.txt:2: stream note")])
|
||||
radio = [" ".join(args) for script, args in self.scripts.calls if script == skill_scripts.RADIO]
|
||||
self.assertEqual(len([entry for entry in radio if entry.startswith("send post --to Skills session ") and f"Granted: {TITLE}. Notes:" in entry and "src/app.py:3: overlay note" in entry]), 1, radio)
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
|
||||
def test_firefox_keeps_line_comments_when_the_deny_and_the_grant_go_unsigned(self):
|
||||
data = self.drive(self.steps("firefox", False), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"))
|
||||
(base.OUT / "firefox-line-comments.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.check(data, False)
|
||||
self.assertEqual(self.status(self.review), "pending")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,124 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
sys.path[:0] = [str(HERE.parent), str(HERE)]
|
||||
|
||||
import hub_e2e_kit as base
|
||||
import test_home_bookmarks_e2e as bm
|
||||
import test_home_dashboard_e2e as dash
|
||||
import test_match_review_e2e as matched
|
||||
import test_workbench_w4_e2e as w4
|
||||
from hub_case import HubCase
|
||||
from test_hub_match import git, merge_repo
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/match-content-shots"))
|
||||
SCAN = """
|
||||
const stray = (root) => {
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
||||
const found = [];
|
||||
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
||||
if (["null", "undefined"].includes(node.nodeValue.trim())) {
|
||||
found.push(node.parentElement ? node.parentElement.className || node.parentElement.tagName : "-");
|
||||
}
|
||||
}
|
||||
return found;
|
||||
};
|
||||
"""
|
||||
MERGE = """(async () => {@HELPERS@@CARD@@SCAN@
|
||||
await screenShown(8000);
|
||||
await until(card, 8000);
|
||||
const shown = await pick("@MERGE@");
|
||||
await sleep(400);
|
||||
const files = shown ? all(".match-file", shown).map((file) => file.dataset.path) : null;
|
||||
const added = shown ? all(".match-file tr", shown).some((row) => text(row).includes("added = 2")) : false;
|
||||
const visited = [];
|
||||
for (const tab of all("#main .match-peek")) {
|
||||
tab.click();
|
||||
await sleep(250);
|
||||
visited.push(stray(document.getElementById("main")));
|
||||
}
|
||||
return {files, added, none: text(shown && shown.querySelector(".match-body > p.muted")), stray: stray(document.getElementById("main")), visited: visited.flat(),
|
||||
reasons: all("#main .match-reason").filter((node) => ["", "-"].includes(text(node).trim())).length, wide: document.documentElement.scrollWidth > innerWidth + 1};
|
||||
})()"""
|
||||
SEED = """(async () => {@HELPERS@
|
||||
await ViewStore.update("home.pins", () => [{kind: "panel", id: "tasks/match", w: innerWidth > 640 ? 6 : 4, h: 6}]);
|
||||
return true;
|
||||
})()"""
|
||||
TILE = """(async () => {@HELPERS@@HOME@@SCAN@
|
||||
await go("home");
|
||||
const pinned = await until(() => tile("panel:tasks/match")?.querySelector(".match-card"), 8000);
|
||||
await sleep(600);
|
||||
return {found: Boolean(pinned), stray: stray(document.getElementById("main"))};
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str, **names: str) -> str:
|
||||
fills = {"@HELPERS@": base.HELPERS, "@HOME@": dash.HOME, "@CARD@": matched.CARD, "@SCAN@": SCAN}
|
||||
fills.update({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 TestMatchContent(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()
|
||||
repo, target = merge_repo(self.work)
|
||||
git(repo, "merge", "--no-commit", "--no-ff", "-q", target)
|
||||
arguments = {**self.arguments("Merge feature into main", "", self.page("merge.html", "<!doctype html><title>m</title>")), "repo": str(repo / ".git"), "worktree": str(repo), "branch": "main", "tree": git(repo, "write-tree").strip()}
|
||||
self.merge = self.tool("review_request", arguments)["structuredContent"]["id"]
|
||||
self.run_runner(register=False)
|
||||
|
||||
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}-merge#tasks/match", "wait": 1500, "probe": probe(MERGE, merge=f"review:{self.merge}"), "shot": f"{shot}-merge-diff.png"},
|
||||
{**at, "url": f"{self.base}?{width}-clear#stream", "wait": 600, "probe": bm.CLEAR, "shot": None},
|
||||
{**at, "url": f"{self.base}?{width}-seed#stream", "wait": 800, "probe": probe(SEED), "shot": None},
|
||||
{**at, "url": f"{self.base}?{width}-home#home", "wait": 1500, "probe": probe(TILE), "shot": f"{shot}-home-match.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:
|
||||
merge, _, _, tile = (next(results) for _ in range(4))
|
||||
with self.subTest(browser=browser, width=width, step="merge"):
|
||||
self.assertEqual((merge["files"], merge["added"], merge["none"]), (["app.py"], True, None), merge)
|
||||
self.assertEqual((merge["stray"], merge["visited"], merge["reasons"], merge["wide"]), ([], [], 0, False), merge)
|
||||
with self.subTest(browser=browser, width=width, step="tile"):
|
||||
self.assertEqual((tile["found"], tile["stray"]), (True, []), tile)
|
||||
|
||||
def test_chromium_shows_the_merge_diff_and_no_stray_text(self):
|
||||
data = self.drive(self.steps("chromium"), None, init=w4.GUARD)
|
||||
(OUT / "chromium-match-content.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_merge_diff_and_no_stray_text(self):
|
||||
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=w4.GUARD)
|
||||
(OUT / "firefox-match-content.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.check(data, "firefox")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -158,7 +158,7 @@ class TestMatchWaiting(HubCase):
|
||||
self.assertEqual(sorted(seen), sorted([PICK, ask, choice, rule]), found)
|
||||
self.assertEqual({card_id: entry["kind"] for card_id, entry in seen.items()}, {PICK: "decision", ask: "ask", choice: "decision", rule: "rule"})
|
||||
self.assertEqual(seen[ask]["chips"], ["fix=95 %", "break=2 %", "score=93", "value=1:4"], found)
|
||||
self.assertEqual((seen[ask]["command"], seen[ask]["options"]), (SCORED, ["Yes", "No"]), found)
|
||||
self.assertEqual((seen[ask]["command"], seen[ask]["options"]), (SCORED, []), found)
|
||||
self.assertEqual((seen[PICK]["options"], seen[PICK]["acts"]["Accept"], seen[PICK]["acts"]["Reject"]), (["Merge now", "Wait"], False, False), found)
|
||||
self.assertEqual((seen[choice]["acts"]["Accept"], seen[choice]["acts"]["Reject"], seen[choice]["refused"]), (True, True, True), found)
|
||||
self.assertEqual((seen[rule]["rule"], seen[rule]["sheet"], seen[rule]["stayed"]), (True, True, True), found)
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
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 hub_support
|
||||
from hub_case import HubCase
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-031-shots"))
|
||||
TEMPLATES = hub_support.HUB / "templates"
|
||||
SCAN = """
|
||||
const shown = (node) => Boolean(node && node.getClientRects().length);
|
||||
const scan = () => all("button.mic").filter(shown).map((button) => {
|
||||
const field = document.getElementById(button.getAttribute("aria-controls"));
|
||||
const frame = button.closest(".mic-frame");
|
||||
if (!field || !frame || field.parentElement !== frame) {
|
||||
return {id: button.getAttribute("aria-controls"), framed: false};
|
||||
}
|
||||
const line = frame.classList.contains("mic-line");
|
||||
const [outer, mic, text] = [frame.getBoundingClientRect(), button.getBoundingClientRect(), field.getBoundingClientRect()];
|
||||
const foot = line ? null : frame.querySelector(":scope > .mic-foot");
|
||||
return {
|
||||
id: field.id, framed: true, line,
|
||||
last: line ? frame.lastElementChild === button : Boolean(foot) && foot.lastElementChild === button && field.nextElementSibling === foot,
|
||||
fits: line ? Math.abs(mic.top - outer.top - 1) <= 1 && Math.abs(outer.bottom - 1 - mic.bottom) <= 1 && Math.abs(outer.right - 1 - mic.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,
|
||||
};
|
||||
});
|
||||
const ring = (field) => {
|
||||
field.focus();
|
||||
const frame = field.closest(".mic-frame");
|
||||
return [getComputedStyle(frame).outlineStyle, getComputedStyle(field).outlineStyle];
|
||||
};
|
||||
const wide = () => document.documentElement.scrollWidth > innerWidth + 1;
|
||||
"""
|
||||
STREAM = """(async () => {@HELPERS@@SCAN@
|
||||
const field = await until(() => document.querySelector('#main input[type="search"]'), 15000);
|
||||
await until(() => field.closest(".mic-frame"), 4000);
|
||||
return {mics: scan(), ring: ring(field), wide: wide()};
|
||||
})()"""
|
||||
RULES = """(async () => {@HELPERS@@SCAN@
|
||||
(await until(() => document.getElementById("controls-tab-rules"), 15000)).click();
|
||||
await until(() => document.querySelector("#main .rule-form .mic-frame"), 4000);
|
||||
return {mics: scan(), wide: wide()};
|
||||
})()"""
|
||||
RADIO = """(async () => {@HELPERS@@SCAN@
|
||||
const area = await until(() => document.querySelector("#radio-spot form.composer textarea"), 15000);
|
||||
await until(() => area.closest(".mic-frame"), 4000);
|
||||
const foot = area.closest(".mic-frame").querySelector(".mic-foot");
|
||||
const first = foot.firstElementChild;
|
||||
const idle = getComputedStyle(foot.lastElementChild).backgroundColor;
|
||||
foot.lastElementChild.setAttribute("aria-pressed", "true");
|
||||
const recording = getComputedStyle(foot.lastElementChild).backgroundColor;
|
||||
foot.lastElementChild.setAttribute("aria-pressed", "false");
|
||||
area.style.height = "260px";
|
||||
await sleep(100);
|
||||
const after = scan().find((entry) => entry.id === area.id);
|
||||
return {mics: scan(), record: first.textContent.trim() || first.getAttribute("aria-label"), looks: idle !== recording, resized: after, ring: ring(area), wide: wide()};
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str) -> str:
|
||||
return template.replace("@HELPERS@", base.HELPERS).replace("@SCAN@", SCAN)
|
||||
|
||||
|
||||
class TestMicSource(unittest.TestCase):
|
||||
def test_no_page_module_but_the_mic_helper_inserts_a_mic_button(self):
|
||||
callers = [path.name for path in TEMPLATES.glob("*.js") if path.name != "page-mic.js" and re.search(r"micButton\(", path.read_text(encoding="utf-8"))]
|
||||
self.assertEqual(callers, [])
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestMicFrames(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 check_mics(self, mics: list[dict]) -> None:
|
||||
self.assertTrue(mics)
|
||||
for entry in mics:
|
||||
with self.subTest(field=entry["id"]):
|
||||
self.assertTrue(entry["framed"], entry)
|
||||
self.assertEqual((entry["last"], entry["fits"], entry["divider"], entry["clear"]), (True, True, "1px", True), entry)
|
||||
|
||||
def test_chromium_joins_every_mic_into_its_field_frame_at_three_widths(self):
|
||||
steps = []
|
||||
for width, height in base.WIDTHS:
|
||||
shot = OUT / f"chromium-{width}"
|
||||
steps += [
|
||||
{"width": width, "height": height, "url": f"{self.page_url}?{width}#stream", "wait": 1200, "probe": probe(STREAM), "shot": f"{shot}-stream.png"},
|
||||
{"width": width, "height": height, "url": f"{self.page_url}?{width}-rules#stream/rules", "wait": 1200, "probe": probe(RULES), "shot": f"{shot}-rules.png"},
|
||||
{"width": width, "height": height, "url": f"{self.page_url}?{width}-radio#stream/radio", "wait": 1200, "probe": probe(RADIO), "shot": f"{shot}-radio.png"},
|
||||
]
|
||||
data = self.drive(steps, None)
|
||||
(OUT / "chromium-mic-frames.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.assertEqual(data["errors"], [])
|
||||
results = iter(data["results"])
|
||||
for width, _ in base.WIDTHS:
|
||||
stream, rules, radio = next(results), next(results), next(results)
|
||||
with self.subTest(width=width):
|
||||
for found in (stream, rules, radio):
|
||||
self.assertNotIn("error", found, found)
|
||||
self.check_mics(found["mics"])
|
||||
self.assertFalse(found["wide"])
|
||||
self.assertEqual(stream["ring"], ["solid", "none"])
|
||||
self.assertEqual(radio["ring"], ["solid", "none"])
|
||||
self.assertEqual(radio["record"], "Record")
|
||||
self.assertTrue(radio["looks"])
|
||||
self.assertEqual((radio["resized"]["last"], radio["resized"]["fits"]), (True, True), radio["resized"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -164,7 +164,7 @@ class TestOrchestratorE2E(base.OrchestratorE2ECase):
|
||||
self.assertRegex(by_hash[f"#{tab}/3d"]["note"], r"^\d+ nodes · \d+ edges · Force$")
|
||||
agents = by_hash["#agents/orbit"]
|
||||
self.assertEqual(agents["toolbar"], ["Priority", "Day/Night", "Status"])
|
||||
self.assertEqual(agents["spot"], {"hidden": True, "channels": CHOICE_CHANNELS})
|
||||
self.assertEqual(agents["spot"], {"hidden": True, "channels": [channel for channel in CHOICE_CHANNELS if channel != "mayday"]})
|
||||
hierarchy = by_hash["#agents/hierarchy"]
|
||||
self.assertEqual([office for office, _ in hierarchy["org"]], ["chair", "identity/oidc", "work/s1", "work/s2"])
|
||||
self.assertEqual(hierarchy["toggles"], [["Collapse: Operator", "true"], ["Collapse: Chair", "true"], ["Collapse: identity", "true"], ["Collapse: Presidents", "true"]])
|
||||
|
||||
@@ -115,7 +115,7 @@ class TestRadioLayout(kit.RadioLayoutCase):
|
||||
self.assertTrue(found["inside"], home[moment])
|
||||
self.assertTrue(found["filled"], home[moment])
|
||||
self.assertEqual(home["tools"]["menu"], ["true", True, True], home)
|
||||
self.assertEqual(home["tools"]["cancel"], [True, "Cancel mayday: lift the radio silence so the agents write again; your passkey signs it"], home)
|
||||
self.assertEqual(home["tools"]["cancel"], ["false", "MAYDAY: send the message as mayday to all; all agents pause writing steps until you cancel it"], home)
|
||||
content = home["content"]
|
||||
self.assertEqual(content["tiles"], [f"panel:{part}" for part in PARTS], home)
|
||||
self.assertEqual(content["radio"], [True, True, True], home)
|
||||
|
||||
@@ -152,7 +152,7 @@ class TestRadioSet(HubCase):
|
||||
self.assertTrue(label["whole"] or width == 390, label)
|
||||
self.assertEqual(face["bells"], [["MAYDAY / PAN-PAN tone", "speak"], ["Reviews, asks, decisions tone", "tone"], ["Post and calls to you tone", "tone"], ["All radio tone", "off"]])
|
||||
self.assertEqual((face["caret"], list(face["groups"]), face["menuFits"]), (["auto"], ["Fallback"], {"page": True, "panel": True}))
|
||||
self.assertEqual(face["send"], ["More send options", True])
|
||||
self.assertEqual(face["send"], ["More send options", "false"])
|
||||
self.assertEqual(face["stationsHead"], "Internet radio")
|
||||
self.assertEqual(face["ptt"][0], "PTT")
|
||||
self.assertEqual([section for section in face["sections"] if section in ("Internet radio", "Tones", "Read radio aloud", "Radio")], [])
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
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
|
||||
from kvb_orchestrator import accounts
|
||||
from kvb_orchestrator.viewstore import VIEW
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-028-shots"))
|
||||
EMAIL = "one@example.org"
|
||||
KIT = """
|
||||
const box = () => document.querySelector("#main .res-accounts");
|
||||
const rows = () => all("#main .res-accounts tbody tr").map((row) => [row.dataset.account === "" ? "" : "account", all("td", row).map((cell) => text(cell))]);
|
||||
const sheet = () => document.getElementById("sheet");
|
||||
const field = (label) => sheet().querySelector(`[aria-label="${label}"]`);
|
||||
const button = (root, label) => all("button", root).find((node) => name(node) === label || text(node) === label);
|
||||
const wide = () => ({wide: document.documentElement.scrollWidth > innerWidth + 1});
|
||||
"""
|
||||
ADD = """(async () => {@HELPERS@@READ@@KIT@
|
||||
if (!(await until(() => box() && rows().length === 1, 15000))) {
|
||||
return {error: text(box()) || text(document.getElementById("main"))};
|
||||
}
|
||||
const before = rows();
|
||||
button(box(), "Add account").click();
|
||||
await until(() => !sheet().hidden && field("Provider"), 4000);
|
||||
field("Provider").value = "Anthropic";
|
||||
field("Email").value = "@EMAIL@";
|
||||
field("Renewal weekday").value = "1";
|
||||
field("Renewal time").value = "09:00";
|
||||
field("Weekly reset weekday").value = "4";
|
||||
field("Weekly reset time").value = "18:30";
|
||||
field("Autorenew").checked = true;
|
||||
field("Weekly token limit").value = "1000";
|
||||
button(sheet(), "Save").click();
|
||||
const added = Boolean(await until(() => sheet().hidden && rows().length === 2, 5000));
|
||||
const afterAdd = rows();
|
||||
button(box(), "Edit @EMAIL@").click();
|
||||
await until(() => !sheet().hidden && field("Weekly token limit"), 4000);
|
||||
const prefilled = [field("Provider").value, field("Email").value, field("Weekly token limit").value, field("Autorenew").checked];
|
||||
field("Weekly token limit").value = "";
|
||||
button(sheet(), "Save").click();
|
||||
const edited = Boolean(await until(() => sheet().hidden && rows()[0] && rows()[0][1][9] === "–", 5000));
|
||||
const afterEdit = rows();
|
||||
await pickPanel("accounts", false);
|
||||
const off = {panels: panelsShown(), picks: picks()};
|
||||
await pickPanel("accounts", true);
|
||||
await until(() => rows().length === 2, 4000);
|
||||
const on = {panels: panelsShown(), picks: picks()};
|
||||
return {before, added, afterAdd, prefilled, edited, afterEdit, off, on, page: wide(), violations: window.e2eViolations || null};
|
||||
})()"""
|
||||
REMOVE = """(async () => {@HELPERS@@READ@@KIT@
|
||||
button(box(), "Edit @EMAIL@").click();
|
||||
await until(() => !sheet().hidden && button(sheet(), "Remove"), 4000);
|
||||
button(sheet(), "Remove").click();
|
||||
const removed = Boolean(await until(() => sheet().hidden && rows().length === 1, 5000));
|
||||
return {removed, after: rows(), page: wide(), violations: window.e2eViolations || null};
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str) -> str:
|
||||
names = {"@HELPERS@": base.HELPERS, "@READ@": res.READ, "@KIT@": KIT, "@EMAIL@": EMAIL}
|
||||
for key, value in names.items():
|
||||
template = template.replace(key, value)
|
||||
return template
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestResourcesAccounts(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-haiku-4-5", "input": 3, "output": 0, "cache_read": 0, "cache_write": 0},
|
||||
]
|
||||
(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")
|
||||
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(ADD), "shot": f"{shot}-accounts.png"},
|
||||
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(REMOVE), "shot": f"{shot}-accounts-removed.png"},
|
||||
]
|
||||
return steps
|
||||
|
||||
def check(self, data: dict, browser: str) -> None:
|
||||
results = iter(data["results"])
|
||||
shown = [["resources-hardware", False], ["resources-tokens", False], ["resources-combined", True]]
|
||||
for width, _ in base.WIDTHS:
|
||||
add, remove = next(results), next(results)
|
||||
with self.subTest(browser=browser, width=width):
|
||||
self.assertNotIn("error", add, add)
|
||||
self.assertEqual([(kind, cells[-3]) for kind, cells in add["before"]], [("", "45")])
|
||||
self.assertTrue(add["added"], add)
|
||||
(kind, cells), (rest, other) = add["afterAdd"]
|
||||
self.assertEqual((kind, rest), ("account", ""))
|
||||
self.assertEqual(cells[0], "Anthropic")
|
||||
self.assertTrue(cells[1].startswith(EMAIL) and cells[1].endswith("active"), cells[1])
|
||||
self.assertEqual((cells[2], cells[5], cells[6], cells[7], cells[8], cells[9]), ("Mon 09:00", "yes", "42", "42", "42", "958"))
|
||||
self.assertEqual(other[-3], "3")
|
||||
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["page"], {"wide": False})
|
||||
self.assertEqual(w4.quiet(add["violations"]), [])
|
||||
self.assertTrue(remove["removed"], remove)
|
||||
self.assertEqual([(kind, cells[-3]) for kind, cells in remove["after"]], [("", "45")])
|
||||
self.assertEqual(remove["page"], {"wide": False})
|
||||
self.assertEqual(w4.quiet(remove["violations"]), [])
|
||||
self.assertEqual(self.httpd.hub.view_store.get(), VIEW)
|
||||
self.assertEqual(self.httpd.hub.accounts.ledger.listed(), [])
|
||||
|
||||
def test_chromium_adds_edits_and_removes_an_account_and_picks_the_panel_at_three_widths(self):
|
||||
data = self.drive(self.steps("chromium"), None, init=w4.GUARD)
|
||||
(OUT / "chromium-resources-accounts.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_adds_edits_and_removes_an_account_and_picks_the_panel_at_three_widths(self):
|
||||
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=w4.GUARD)
|
||||
(OUT / "firefox-resources-accounts.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()
|
||||
@@ -44,14 +44,26 @@ READ = """
|
||||
}
|
||||
return null;
|
||||
};
|
||||
const legendFits = () => all("#main .res-panel:not([hidden])").every((panel) => panel.querySelector(".res-plot").getBoundingClientRect().height > 40);
|
||||
const legendFits = () => all("#main .res-panel:not([hidden]) .res-plot").every((plot) => plot.getBoundingClientRect().height > 40);
|
||||
const panelsShown = () => all("#main .res-panel").map((panel) => [panel.dataset.panel, panel.hidden]);
|
||||
const picks = () => all("#main input[data-pick]").map((box) => [box.dataset.pick, box.checked, box.disabled]);
|
||||
const pickPanel = async (kind, on) => {
|
||||
const menu = document.querySelector("#main .res-panels-menu");
|
||||
menu.open = true;
|
||||
const box = menu.querySelector(`input[data-pick="${kind}"]`);
|
||||
if (box.checked !== on) {
|
||||
box.click();
|
||||
}
|
||||
await sleep(200);
|
||||
menu.open = false;
|
||||
};
|
||||
const page = () => ({tall: document.documentElement.scrollHeight > innerHeight, wide: document.documentElement.scrollWidth > innerWidth + 1, fits: legendFits()});
|
||||
"""
|
||||
TOGGLE = """(async () => {@HELPERS@@READ@
|
||||
if (!(await until(() => charts().length === 2 && chip("@CPU@") && chip("@STAGE@") && agents().length === 2, 15000))) {
|
||||
return {error: text(document.getElementById("main")), charts: charts()};
|
||||
}
|
||||
const before = {charts: charts(), lines: lines(), agents: agents(), pressed: pressed(), panels: all("#main .res-panel").map((panel) => [panel.dataset.panel, panel.hidden])};
|
||||
const before = {charts: charts(), lines: lines(), agents: agents(), pressed: pressed(), panels: panelsShown(), picks: picks()};
|
||||
chip("@CPU@").click();
|
||||
await until(() => chip("@STAGE@") && !lines().includes("@CPU@"), 4000);
|
||||
chip("@STAGE@").click();
|
||||
@@ -67,9 +79,11 @@ COMBINE = """(async () => {@HELPERS@@READ@
|
||||
switched("tokens").click();
|
||||
const accumulated = Boolean(await until(() => sums().length === 1 && !agents().length, 4000));
|
||||
const sumsAt = {sums: sums(), rising: rising(), pressed: switched("tokens").getAttribute("aria-pressed")};
|
||||
switched("combined").click();
|
||||
await pickPanel("combined", true);
|
||||
await pickPanel("hardware", false);
|
||||
await pickPanel("tokens", false);
|
||||
const combinedOn = Boolean(await until(() => charts().join() === "combined" && burn().length === 2, 4000));
|
||||
const combined = {charts: charts(), lines: lines(), sums: sums(), burn: burn(), right: all('#main text[data-axis="right"]').length, pressed: pressed(), panels: all("#main .res-panel").map((panel) => [panel.dataset.panel, panel.hidden]), switch: switched("combined").getAttribute("aria-pressed")};
|
||||
const combined = {charts: charts(), lines: lines(), sums: sums(), burn: burn(), right: all('#main text[data-axis="right"]').length, pressed: pressed(), panels: panelsShown(), picks: picks()};
|
||||
return {kept, accumulated, sumsAt, combinedOn, combined, page: page(), violations: window.e2eViolations || null};
|
||||
})()"""
|
||||
DESELECT = """(async () => {@HELPERS@@READ@
|
||||
@@ -135,7 +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]])
|
||||
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["lines"], before["agents"]), (hardware, ["Skills", "Stage"]))
|
||||
self.assertEqual(set(before["pressed"].values()), {"true"})
|
||||
self.assertEqual(set(before["pressed"]), {*hardware, "agent:Skills", STAGE})
|
||||
@@ -153,15 +168,16 @@ class TestResourcesView(HubCase):
|
||||
self.assertTrue(combine["combinedOn"], combine)
|
||||
combined = combine["combined"]
|
||||
self.assertEqual((combined["charts"], combined["lines"], combined["sums"], combined["burn"]), (["combined"], hardware, ["Skills", "Stage"], ["done", "scope"]))
|
||||
self.assertEqual((combined["right"], combined["switch"]), (2, "true"))
|
||||
self.assertEqual(combined["panels"], [["resources-hardware", True], ["resources-tokens", True], ["resources-combined", False]])
|
||||
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(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})
|
||||
self.assertEqual(w4.quiet(combine["violations"]), [])
|
||||
self.assertTrue(deselect["deselected"], deselect)
|
||||
self.assertEqual((deselect["burn"], deselect["lines"]), (["done"], [line for line in hardware if line != UTIL]))
|
||||
self.assertEqual(deselect["saved"], {"hidden": [CPU, STAGE], "tokens": "accumulated", "combined": True, "combinedHidden": [SCOPE, UTIL]})
|
||||
self.assertEqual(deselect["saved"], {"hidden": [CPU, STAGE], "tokens": "accumulated", "panels": ["accounts", "combined"], "combinedHidden": [SCOPE, UTIL]})
|
||||
self.assertEqual(deselect["reset"], 200)
|
||||
self.assertEqual(w4.quiet(deselect["violations"]), [])
|
||||
self.assertEqual(self.httpd.hub.view_store.get(), VIEW)
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
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_review_e2e as matched
|
||||
import test_workbench_w4_e2e as w4
|
||||
from hub_case import HubCase
|
||||
from kvb_orchestrator.skillindex import SKILLS_INDEX
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/slash-skills-shots"))
|
||||
SKILLS = [
|
||||
{"name": "kvb-org-radio", "description": "Default channel to other agents", "source": "~/.claude/skills"},
|
||||
{"name": "kvb-org-rasci", "description": "Register of tasks", "source": "~/.claude/skills"},
|
||||
{"name": "kvb-org-robot", "description": "Work autonomously", "source": "~/.agents/skills"},
|
||||
{"name": "i8-alpha", "description": "Global one", "source": "~/.claude/skills"},
|
||||
{"name": "i8-zeta", "description": "Core one", "source": "/repo"},
|
||||
]
|
||||
KIT = """
|
||||
const shown = () => all(".slash-list .slash-option strong").map(text);
|
||||
const type = async (field, value) => {
|
||||
field.focus();
|
||||
field.value = value;
|
||||
field.setSelectionRange(value.length, value.length);
|
||||
field.dispatchEvent(new Event("input", {bubbles: true}));
|
||||
await until(() => shown().length, 2500);
|
||||
await sleep(150);
|
||||
return shown();
|
||||
};
|
||||
const key = (field, name) => field.dispatchEvent(new KeyboardEvent("keydown", {key: name, bubbles: true, cancelable: true}));
|
||||
const flow = async (field, prefix) => {
|
||||
const listed = await type(field, `/${prefix}`);
|
||||
const box = document.querySelector(".slash-list");
|
||||
const inside = box ? box.getBoundingClientRect().right <= innerWidth + 1 && box.getBoundingClientRect().left >= -1 : null;
|
||||
key(field, "Enter");
|
||||
await sleep(150);
|
||||
const picked = field.value;
|
||||
const word = await type(field, "a/b");
|
||||
const kept = await type(field, "keep /kvb");
|
||||
key(field, "Escape");
|
||||
await sleep(150);
|
||||
return {listed, inside, picked, word, kept: kept.length > 0, closed: !document.querySelector(".slash-list"), text: field.value};
|
||||
};
|
||||
"""
|
||||
COMPOSER = """(async () => {@HELPERS@@KIT@
|
||||
await screenShown(8000);
|
||||
const field = await until(() => document.querySelector("#radio-spot:not([hidden]) .radio-speak textarea[data-skills]"), 8000);
|
||||
if (!field) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
return flow(field, "kvb-org-r");
|
||||
})()"""
|
||||
FEEDBACK = """(async () => {@HELPERS@@KIT@
|
||||
await screenShown(8000);
|
||||
const reject = await until(() => document.querySelector("#main .match-actions .match-reject:not([disabled])"), 8000);
|
||||
if (!reject) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
reject.click();
|
||||
const field = await until(() => document.querySelector("#sheet:not([hidden]) textarea.match-feedback[data-skills]"), 4000);
|
||||
if (!field) {
|
||||
return {error: "no feedback field"};
|
||||
}
|
||||
const core = await type(field, "/i8-");
|
||||
const result = {repo: field.dataset.skills, core, ...(await flow(field, "kvb-org-r"))};
|
||||
key(field, "Escape");
|
||||
await until(() => document.getElementById("sheet").hidden, 3000);
|
||||
return result;
|
||||
})()"""
|
||||
INJECTED = """(async () => {@HELPERS@@KIT@
|
||||
const field = document.createElement("textarea");
|
||||
field.dataset.skills = "";
|
||||
document.getElementById("main").append(field);
|
||||
await sleep(200);
|
||||
const result = await flow(field, "kvb-org-r");
|
||||
field.remove();
|
||||
return result;
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str) -> str:
|
||||
return template.replace("@HELPERS@", base.HELPERS).replace("@KIT@", KIT)
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestSlashSkills(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.tree_file.with_name(SKILLS_INDEX).write_text(json.dumps({"written": 1, "skills": SKILLS}), encoding="utf-8")
|
||||
|
||||
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}-composer#stream/radio", "wait": 1200, "probe": probe(COMPOSER), "shot": f"{shot}-composer.png"},
|
||||
{**at, "url": f"{self.base}?{width}-feedback#tasks/match", "wait": 1500, "probe": probe(FEEDBACK), "shot": f"{shot}-feedback.png"},
|
||||
{**at, "url": None, "wait": 0, "probe": probe(INJECTED), "shot": None},
|
||||
]
|
||||
return steps
|
||||
|
||||
def check_flow(self, found: dict) -> None:
|
||||
self.assertNotIn("error", found, found)
|
||||
self.assertEqual(found["listed"][0], "/kvb-org-radio", found)
|
||||
self.assertEqual((found["inside"], found["picked"], found["word"], found["kept"], found["closed"], found["text"]), (True, "/kvb-org-radio ", [], True, True, "keep /kvb"), found)
|
||||
|
||||
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:
|
||||
for field in ("composer", "feedback", "injected"):
|
||||
found = next(results)
|
||||
with self.subTest(browser=browser, width=width, field=field):
|
||||
self.check_flow(found)
|
||||
if field == "feedback":
|
||||
self.assertEqual((found["repo"], found["core"]), ("/repo", ["/i8-zeta", "/i8-alpha"]), found)
|
||||
|
||||
def test_chromium_suggests_skills_after_a_slash_in_every_agent_field(self):
|
||||
data = self.drive(self.steps("chromium"), None, init=w4.GUARD)
|
||||
(OUT / "chromium-slash.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_suggests_skills_after_a_slash_in_every_agent_field(self):
|
||||
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=w4.GUARD)
|
||||
(OUT / "firefox-slash.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
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_workbench_w4_e2e as w4
|
||||
from kvb_orchestrator import skill_scripts
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/speak-card-shots"))
|
||||
HINTS = ("Post arrives at the end of the turn.", "Your passkey signs every message.")
|
||||
CARD = """
|
||||
const card = () => document.querySelector("#radio-spot .radio-speak");
|
||||
const form = () => card().querySelector("form.composer");
|
||||
const toggle = () => form().querySelector(".mayday-toggle");
|
||||
const answer = async (yes) => {
|
||||
toggle().click();
|
||||
const box = await until(() => form().querySelector(".mayday-confirm"), 4000);
|
||||
if (!box) {
|
||||
return null;
|
||||
}
|
||||
const question = text(box.querySelector("p"));
|
||||
all("button", box).find((node) => text(node) === (yes ? yes : "Cancel")).click();
|
||||
return question;
|
||||
};
|
||||
const posted = [];
|
||||
const send = window.fetch.bind(window);
|
||||
window.fetch = (path, init) => {
|
||||
if (/^\\/api\\/(board|messages)/.test(String(path))) {
|
||||
posted.push(String(path));
|
||||
}
|
||||
return send(path, init);
|
||||
};
|
||||
"""
|
||||
RAISE = """(async () => {@HELPERS@@CARD@
|
||||
if (!(await screenShown(8000)) || !(await until(card, 8000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
await sleep(400);
|
||||
const foot = toggle().parentElement;
|
||||
const radius = (node) => getComputedStyle(node).borderTopLeftRadius;
|
||||
const layout = {
|
||||
hints: @HINTS@.filter((line) => text(card()).includes(line)),
|
||||
channels: all("select option", form()).slice(0, 6).map((option) => [option.value, Boolean(option.title)]),
|
||||
mayday: all("select option", form()).some((option) => option.value === "mayday"),
|
||||
next: Boolean(toggle().previousElementSibling && toggle().previousElementSibling.matches(".ptt-split")),
|
||||
face: [text(toggle()), toggle().getAttribute("aria-pressed")],
|
||||
cards: all(".card", card()).length,
|
||||
radius: [radius(card()), radius(form().querySelector(".composer-grid")), radius(form().querySelector("textarea").closest(".mic-frame"))],
|
||||
fits: foot.scrollWidth <= foot.clientWidth + 1 && foot.getBoundingClientRect().right <= card().getBoundingClientRect().right + 1,
|
||||
wide: document.documentElement.scrollWidth > innerWidth + 1,
|
||||
};
|
||||
const field = form().querySelector("textarea");
|
||||
field.value = "disk full @WIDTH@";
|
||||
field.dispatchEvent(new Event("input", {bubbles: true}));
|
||||
const shown = new Set(all("#toasts .toast"));
|
||||
const declined = await answer(false);
|
||||
await sleep(600);
|
||||
const quiet = posted.slice();
|
||||
const asked = await answer("Send mayday");
|
||||
const toast = await until(() => all("#toasts .toast").filter((node) => !shown.has(node)).map(text).find((line) => line.includes(" to all")), 15000);
|
||||
return {layout, declined, quiet, asked, toast, left: field.value, violations: window.e2eViolations || null};
|
||||
})()"""
|
||||
CANCEL = """(async () => {@HELPERS@@CARD@
|
||||
if (!(await screenShown(8000)) || !(await until(() => card() && toggle().getAttribute("aria-pressed") === "true", 8000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
const face = [text(toggle()), toggle().getAttribute("aria-pressed"), toggle().title];
|
||||
const shown = new Set(all("#toasts .toast"));
|
||||
const asked = await answer("Cancel mayday");
|
||||
const toast = await until(() => all("#toasts .toast").filter((node) => !shown.has(node)).map(text).find((line) => line.startsWith("Cancel mayday")), 15000);
|
||||
return {face, asked, toast, posted};
|
||||
})()"""
|
||||
IDLE = """(async () => {@HELPERS@@CARD@
|
||||
await screenShown(8000);
|
||||
await until(card, 8000);
|
||||
return {face: [text(toggle()), toggle().getAttribute("aria-pressed")]};
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str, **names: str) -> str:
|
||||
fills = {"@HELPERS@": base.HELPERS, "@CARD@": CARD, "@HINTS@": json.dumps(HINTS)}
|
||||
fills.update({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 TestSpeakCard(base.OrchestratorE2ECase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
(self.council / "radio-silence.json").unlink()
|
||||
self.local = f"http://localhost:{self.port}/"
|
||||
|
||||
def steps(self, template: str, name: str) -> list[dict]:
|
||||
return [{"width": width, "height": height, "url": f"{self.local}?{width}-{name}#stream/radio", "wait": 1200, "probe": probe(template, width=str(width)), "shot": self.shot(f"{width}-speak-{name}")} for width, height in base.WIDTHS]
|
||||
|
||||
def test_chromium_raises_and_cancels_a_mayday_from_the_toggle_beside_ptt(self):
|
||||
raised = self.drive(self.steps(RAISE, "raise"), self.authenticator(), init=w4.GUARD)
|
||||
(OUT / "chromium-raise.json").write_text(json.dumps(raised, indent=1), encoding="utf-8")
|
||||
self.assertEqual(raised["errors"], [])
|
||||
ask = "Send a mayday to all? All agents pause writing steps until you cancel it."
|
||||
for result, (width, _) in zip(raised["results"], base.WIDTHS, strict=True):
|
||||
with self.subTest(step="raise", width=width):
|
||||
self.assertNotIn("error", result, result)
|
||||
layout = result["layout"]
|
||||
self.assertEqual((layout["hints"], layout["mayday"], layout["next"], layout["face"], layout["cards"]), ([], False, True, ["MAYDAY", "false"], 0), layout)
|
||||
self.assertEqual([value for value, _ in layout["channels"]], ["post", "call", "newsletter", "broadcast", "pan-pan", "security"], layout)
|
||||
self.assertTrue(all(titled for _, titled in layout["channels"]), layout)
|
||||
self.assertEqual(layout["radius"], ["14px", "10px", "10px"], layout)
|
||||
self.assertEqual((layout["fits"], layout["wide"]), (True, False), layout)
|
||||
self.assertEqual((result["declined"], result["quiet"], result["asked"]), (ask, [], ask), result)
|
||||
self.assertTrue((result["toast"] or "").startswith("Mayday to all: sent$ radio.py send mayday"), result)
|
||||
self.assertEqual((result["left"], w4.quiet(result["violations"])), ("", []), result)
|
||||
sent = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO]
|
||||
self.assertEqual([args[:2] for args in sent], [["send", "mayday"]] * len(base.WIDTHS))
|
||||
for args, (width, _) in zip(sent, base.WIDTHS, strict=True):
|
||||
self.assertTrue(args[-1].endswith(f"disk full {width}"), args)
|
||||
self.scripts.calls.clear()
|
||||
(self.council / "radio-silence.json").write_text(json.dumps({"since": time.time() - 30, "until": time.time() + 3600, "by": "Operator", "text": "disk full"}), encoding="utf-8")
|
||||
cancelled = self.drive(self.steps(CANCEL, "cancel"), {**self.authenticator(), "signCount": len(base.WIDTHS)}, init=w4.GUARD)
|
||||
(OUT / "chromium-cancel.json").write_text(json.dumps(cancelled, indent=1), encoding="utf-8")
|
||||
self.assertEqual(cancelled["errors"], [])
|
||||
for result, (width, _) in zip(cancelled["results"], base.WIDTHS, strict=True):
|
||||
with self.subTest(step="cancel", width=width):
|
||||
self.assertNotIn("error", result, result)
|
||||
self.assertEqual(result["face"][:2], ["Cancel mayday", "true"], result)
|
||||
self.assertEqual((result["asked"], result["posted"]), ("Lift the radio silence of the active mayday?", ["/api/board/sign", "/api/board/clear-mayday"]), result)
|
||||
self.assertTrue((result["toast"] or "").startswith("Cancel mayday: done"), result)
|
||||
self.assertEqual(self.scripts.calls, [(skill_scripts.RADIO, ["clear", "--force", "--session", "Operator"])] * len(base.WIDTHS))
|
||||
(self.council / "radio-silence.json").unlink()
|
||||
idle = self.drive(self.steps(IDLE, "idle"), None, init=w4.GUARD)
|
||||
self.assertEqual([result["face"] for result in idle["results"]], [["MAYDAY", "false"]] * len(base.WIDTHS))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,164 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
sys.path[:0] = [str(HERE.parent), str(HERE)]
|
||||
|
||||
import hub_e2e_kit as base
|
||||
import test_home_bookmarks_e2e as bm
|
||||
import test_home_dashboard_e2e as dash
|
||||
import test_workbench_w4_e2e as w4
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/widget-zoom-shots"))
|
||||
KEY = "panel:tasks/board"
|
||||
TILE = """
|
||||
const pinned = () => tile("@KEY@");
|
||||
const body = () => pinned().querySelector(".home-body");
|
||||
const zoom = () => Number(body().dataset.zoom);
|
||||
const key = async (name, times) => {
|
||||
for (let index = 0; index < times; index += 1) {
|
||||
const before = zoom();
|
||||
pinned().focus();
|
||||
pinned().dispatchEvent(new KeyboardEvent("keydown", {key: name, bubbles: true, cancelable: true}));
|
||||
await until(() => zoom() !== before, 1500);
|
||||
}
|
||||
await sleep(200);
|
||||
return zoom();
|
||||
};
|
||||
const wheel = async (ctrlKey, deltaY) => {
|
||||
const before = zoom();
|
||||
const event = new WheelEvent("wheel", {deltaY, ctrlKey, bubbles: true, cancelable: true});
|
||||
body().dispatchEvent(event);
|
||||
await until(() => zoom() !== before, 1500);
|
||||
await sleep(200);
|
||||
return {zoom: zoom(), prevented: event.defaultPrevented};
|
||||
};
|
||||
const fit = () => {
|
||||
const style = getComputedStyle(body());
|
||||
const inner = body().clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
|
||||
return Math.abs(body().firstElementChild.offsetWidth * zoom() / 100 - inner) <= 2;
|
||||
};
|
||||
"""
|
||||
SEED = """(async () => {@HELPERS@
|
||||
await ViewStore.update("home.pins", () => [{kind: "panel", id: "tasks/board", w: innerWidth > 640 ? 6 : 4, h: 5}]);
|
||||
await ViewStore.update("home.zoom", () => ({}));
|
||||
return true;
|
||||
})()"""
|
||||
KEYS = """(async () => {@HELPERS@@HOME@@TILE@
|
||||
await go("home");
|
||||
if (!(await until(() => pinned() && body().dataset.zoom, 8000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
await sleep(600);
|
||||
const head = pinned().querySelector(".home-head").getBoundingClientRect().height;
|
||||
const three = await key("+", 3);
|
||||
const kept = Math.abs(pinned().querySelector(".home-head").getBoundingClientRect().height - head) <= 0.5;
|
||||
const fits = fit();
|
||||
const scrolls = body().scrollHeight > body().clientHeight || body().scrollWidth > body().clientWidth;
|
||||
const reset = await key("0", 1);
|
||||
const floor = await key("-", 7);
|
||||
const ceiling = await key("+", 16);
|
||||
await key("0", 1);
|
||||
const up = await wheel(true, -100);
|
||||
const plain = await wheel(false, 100);
|
||||
await key("+", 2);
|
||||
const saved = await ViewStore.update("home.zoom", (zooms) => zooms);
|
||||
return {three, kept, fits, scrolls, reset, floor, ceiling, up, plain, stored: saved ? ViewStore.get("home.zoom")["@KEY@"] : null};
|
||||
})()"""
|
||||
MENU = """(async () => {@HELPERS@@HOME@@TILE@
|
||||
await until(() => pinned() && body().dataset.zoom, 8000);
|
||||
const box = pinned().querySelector(".home-title").getBoundingClientRect();
|
||||
const open = () => pinned().querySelector(".home-title").dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, button: 2, clientX: box.left + 4, clientY: box.top + 4}));
|
||||
open();
|
||||
const menu = await until(() => document.querySelector(".ctx-menu:not([hidden])"), 4000);
|
||||
const labels = menu ? all('.ctx-group[data-scope="element"] .ctx-item .ctx-label', menu).map(text) : [];
|
||||
const item = (label) => all(".ctx-item", document.querySelector(".ctx-menu:not([hidden])")).find((node) => text(node.querySelector(".ctx-label")) === label);
|
||||
const before = zoom();
|
||||
item("Zoom out").click();
|
||||
await until(() => zoom() !== before, 1500);
|
||||
const out = zoom();
|
||||
open();
|
||||
await until(() => document.querySelector(".ctx-menu:not([hidden])"), 4000);
|
||||
item("Zoom in").click();
|
||||
await until(() => zoom() !== out, 1500);
|
||||
const back = zoom();
|
||||
open();
|
||||
await until(() => document.querySelector(".ctx-menu:not([hidden])"), 4000);
|
||||
item(`Reset zoom (${back} %)`).click();
|
||||
await until(() => zoom() === 100, 1500);
|
||||
return {labels: labels.filter((label) => label.includes("oom")), out, back, reset: zoom()};
|
||||
})()"""
|
||||
KEPT = """(async () => {@HELPERS@@HOME@@TILE@
|
||||
await go("home");
|
||||
await until(() => pinned() && body().dataset.zoom, 8000);
|
||||
return {zoom: zoom()};
|
||||
})()"""
|
||||
HELP = """(async () => {@HELPERS@
|
||||
document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "?", bubbles: true}));
|
||||
const sheet = await until(() => document.querySelector("#sheet:not([hidden]) dl.keys"), 4000);
|
||||
return {keys: sheet ? all("dt", sheet).map(text) : []};
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str) -> str:
|
||||
for key, value in (("@HELPERS@", base.HELPERS), ("@HOME@", dash.HOME), ("@TILE@", TILE), ("@KEY@", KEY)):
|
||||
template = template.replace(key, value)
|
||||
return template
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestWidgetZoom(base.OrchestratorE2ECase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
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}-clear#stream", "wait": 600, "probe": bm.CLEAR, "shot": None},
|
||||
{**at, "url": f"{self.base}?{width}-seed#stream", "wait": 800, "probe": probe(SEED), "shot": None},
|
||||
{**at, "url": f"{self.base}?{width}-keys#home", "wait": 1500, "probe": probe(KEYS), "shot": f"{shot}-zoomed.png"},
|
||||
{**at, "url": f"{self.base}?{width}-kept#home", "wait": 1500, "probe": probe(KEPT), "shot": None},
|
||||
{**at, "url": None, "wait": 0, "probe": probe(MENU), "shot": f"{shot}-menu.png"},
|
||||
{**at, "url": None, "wait": 0, "probe": probe(HELP), "shot": None},
|
||||
]
|
||||
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:
|
||||
_, _, keys, kept, menu, shown = (next(results) for _ in range(6))
|
||||
with self.subTest(browser=browser, width=width):
|
||||
self.assertNotIn("error", keys, keys)
|
||||
self.assertEqual((keys["three"], keys["kept"], keys["fits"], keys["scrolls"]), (130, True, True, True), keys)
|
||||
self.assertEqual((keys["reset"], keys["floor"], keys["ceiling"]), (100, 50, 200), keys)
|
||||
self.assertEqual((keys["up"], keys["plain"]), ({"zoom": 110, "prevented": True}, {"zoom": 110, "prevented": False}), keys)
|
||||
self.assertEqual((keys["stored"], kept["zoom"]), (130, 130), (keys, kept))
|
||||
self.assertEqual(menu["labels"], ["Zoom in", "Zoom out", "Reset zoom (130 %)"], menu)
|
||||
self.assertEqual((menu["out"], menu["back"], menu["reset"]), (120, 130, 100), menu)
|
||||
self.assertIn("+ / − · 0 · Ctrl+wheel", shown["keys"], shown)
|
||||
|
||||
def test_chromium_zooms_a_tile_by_keys_wheel_and_menu_and_keeps_it(self):
|
||||
data = self.drive(self.steps("chromium"), None, init=w4.GUARD)
|
||||
(OUT / "chromium-zoom.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_zooms_a_tile_by_keys_wheel_and_menu_and_keeps_it(self):
|
||||
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=w4.GUARD)
|
||||
(OUT / "firefox-zoom.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.check(data, "firefox")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -76,6 +76,7 @@ OPERATOR = """(async () => {@HELPERS@@UNLABELLED@
|
||||
return found;
|
||||
})()"""
|
||||
FEEDBACK = """(async () => {@HELPERS@@UNLABELLED@
|
||||
const mine = (words) => all("#main .inbox-list > li").find((li) => li.textContent.includes(words));
|
||||
const card = await until(() => all("#main .inbox-list > li").find((li) => li.textContent.includes("@TAG@ second") && li.querySelector(".diff-file tr.add")), 10000);
|
||||
if (!card) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
@@ -92,8 +93,9 @@ FEEDBACK = """(async () => {@HELPERS@@UNLABELLED@
|
||||
window.e2eFeedback = [];
|
||||
const send = window.fetch.bind(window);
|
||||
window.fetch = (path, init) => {
|
||||
if (String(path).startsWith("/api/messages")) {
|
||||
window.e2eFeedback.push([String(path), JSON.parse(init.body).text]);
|
||||
if (String(path).startsWith("/api/") && init && init.method === "POST" && !String(path).startsWith("/api/inbox/undo")) {
|
||||
const body = JSON.parse(init.body);
|
||||
window.e2eFeedback.push([String(path), body.text || null, (body.items || []).map((entry) => [entry.kind, entry.verb, entry.channel || "", entry.reason || ""])]);
|
||||
}
|
||||
return send(path, init);
|
||||
};
|
||||
@@ -117,25 +119,36 @@ FEEDBACK = """(async () => {@HELPERS@@UNLABELLED@
|
||||
const title = text(document.querySelector(".sheet-head .panel-title"));
|
||||
const range = text(document.querySelector(".sheet-box .who code"));
|
||||
sheet.value = "right-click note";
|
||||
all(".sheet-box button").find((button) => name(button) === "Send feedback").click();
|
||||
await until(() => window.e2eFeedback.length >= (@SIGNS@ ? 2 : 1), 8000);
|
||||
await sleep(600);
|
||||
const fresh = () => all("#main .inbox-list > li").find((li) => li.textContent.includes("@TAG@ second"));
|
||||
const shown = @SIGNS@ ? await until(() => fresh() && all(".feedback-list li", fresh()).map(text).find((entry) => entry.includes("right-click note")), 15000) : null;
|
||||
const close = document.querySelector(".sheet-head button");
|
||||
if (close) {
|
||||
close.click();
|
||||
}
|
||||
const ask = all("#main .inbox-list > li").find((li) => li.textContent.includes("@TAG@ keyed"));
|
||||
const code = ask.querySelector(".command code");
|
||||
all(".sheet-box button").find((button) => name(button) === "Save comment").click();
|
||||
const fresh = () => mine("@TAG@ second");
|
||||
await until(() => fresh() && fresh().querySelector("tr.match-mark"), 4000);
|
||||
const marked = {
|
||||
rows: all("tr.marked", fresh()).map((row) => row.dataset.line),
|
||||
notes: all("tr.match-mark", fresh()).map(text),
|
||||
list: all(".feedback-list li.line-mark", fresh()).map(text),
|
||||
open: !document.getElementById("sheet").hidden,
|
||||
};
|
||||
const ask = () => mine("@TAG@ keyed");
|
||||
const code = ask().querySelector(".command code");
|
||||
select(code, code);
|
||||
document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "f", bubbles: true, cancelable: true}));
|
||||
const keyed = await until(() => document.querySelector(".sheet-box textarea"), 4000);
|
||||
const keyRange = text(document.querySelector(".sheet-box .who code"));
|
||||
keyed.value = "key f note";
|
||||
all(".sheet-box button").find((button) => name(button) === "Send feedback").click();
|
||||
all(".sheet-box button").find((button) => name(button) === "Save comment").click();
|
||||
const askList = await until(() => ask() && all(".feedback-list li.line-mark", ask()).map(text).join("|"), 4000);
|
||||
const before = window.e2eFeedback.length;
|
||||
all(".deny-split button", ask()).find((button) => name(button) === "Deny").click();
|
||||
const reason = await until(() => document.querySelector(".sheet-box .deny-reason textarea"), 4000);
|
||||
const deny = {reason: reason ? reason.value : null, channel: (document.querySelector(".sheet-box .deny-channels input:checked") || {}).value || null, to: (document.querySelector(".sheet-box .deny-recipient select") || {}).value || null};
|
||||
all(".sheet-box .actions button").find((button) => text(button) === "Deny").click();
|
||||
await until(() => window.e2eFeedback.length > before && (!@SIGNS@ || window.e2eFeedback.some(([path]) => path === "/api/inbox/approve")), 8000);
|
||||
await sleep(1200);
|
||||
all(".item-actions button", fresh()).find((button) => name(button) === "Grant").click();
|
||||
await until(() => window.e2eFeedback.some(([path]) => path === (@SIGNS@ ? "/api/messages" : "/api/sign")) && window.e2eFeedback.filter(([path]) => path === "/api/sign").length >= 2, 10000);
|
||||
await sleep(1500);
|
||||
return {nearby, menu, item, title, range, keyRange, labels, shown: shown || "", posted: window.e2eFeedback, wide: document.documentElement.scrollWidth > window.innerWidth + 1};
|
||||
const kept = {review: fresh() ? all(".feedback-list li.line-mark", fresh()).map(text) : null, ask: ask() ? all(".feedback-list li.line-mark", ask()).map(text) : null};
|
||||
return {nearby, menu, item, title, range, keyRange, labels, marked, askList, deny, kept, posted: window.e2eFeedback, wide: document.documentElement.scrollWidth > window.innerWidth + 1};
|
||||
})()"""
|
||||
|
||||
|
||||
@@ -205,29 +218,35 @@ class TestWorkbenchOperatorTasks(HubCase):
|
||||
self.assertEqual(tasks["posted"], [["/api/sign", kinds], *([["/api/inbox/approve", kinds]] if signs else [])])
|
||||
self.assertFalse(tasks["wide"])
|
||||
self.assertNotIn("error", feedback, feedback)
|
||||
self.assertEqual((feedback["nearby"], feedback["menu"], feedback["item"], feedback["title"]), (True, "menu", "Feedback", "Feedback"))
|
||||
self.assertEqual((feedback["range"], feedback["keyRange"]), ("src/app.py:2-2", "/repo:1-1"))
|
||||
ref = f"review:{self.reviews[(tag, 'second')]}"
|
||||
texts = [text for path, text in feedback["posted"] if path == "/api/messages/sign"]
|
||||
self.assertEqual(texts[0].split(": ", 1)[0], f"Feedback on {ref} src/app.py:2-2")
|
||||
self.assertTrue(texts[0].endswith(" right-click note"), texts)
|
||||
if signs:
|
||||
self.assertIn("right-click note", feedback["shown"])
|
||||
self.assertTrue(any(text and text.endswith(" key f note") for _, text in feedback["posted"]), feedback["posted"])
|
||||
self.assertEqual((feedback["nearby"], feedback["menu"], feedback["item"], feedback["title"]), (True, "menu", "Comment", "Comment"))
|
||||
self.assertEqual((feedback["range"], feedback["keyRange"]), ("src/app.py:2", "/repo:1"))
|
||||
self.assertEqual(feedback["marked"], {"rows": ["2", "2"], "notes": ["right-click note"], "list": ["src/app.py:2right-click note"], "open": False})
|
||||
self.assertEqual(feedback["askList"], "/repo:1key f note")
|
||||
self.assertEqual(feedback["deny"], {"reason": "/repo:1: key f note", "channel": "call", "to": "Skills"})
|
||||
denial = [["ask", "reject", "call", "/repo:1: key f note"]]
|
||||
grant = [["review", "approve", "", ""]]
|
||||
notes = f"Granted: feat: {tag} second. Notes:\nsrc/app.py:2: right-click note"
|
||||
expected = [["/api/sign", None, denial], ["/api/inbox/approve", None, denial], ["/api/sign", None, grant], ["/api/inbox/approve", None, grant], ["/api/messages/sign", notes, []], ["/api/messages", notes, []]]
|
||||
self.assertEqual(feedback["posted"], expected if signs else [["/api/sign", None, denial], ["/api/sign", None, grant]])
|
||||
if not signs:
|
||||
self.assertEqual(feedback["kept"], {"review": ["src/app.py:2right-click note"], "ask": ["/repo:1key f note"]})
|
||||
self.assertFalse(feedback["wide"])
|
||||
radio = [" ".join(args) for script, args in self.scripts.calls if script == skill_scripts.RADIO]
|
||||
reached = [entry for entry in radio if "] Feedback on review:" in entry or "] Feedback on ask:" in entry]
|
||||
self.assertEqual(len(reached), 2 * len(base.WIDTHS) if signs else 0, radio)
|
||||
granted = [entry for entry in radio if entry.startswith("send post --to Skills ") and "Granted: feat: w" in entry and "Notes:" in entry and "right-click note" in entry]
|
||||
self.assertEqual(len(granted), len(base.WIDTHS) if signs else 0, radio)
|
||||
asks = {ask["command"]: (ask["status"], ask.get("channel", ""), ask.get("reason", "")) for ask in self.httpd.hub.asks.listed() if "keyed" in ask["command"]}
|
||||
self.assertEqual(asks, {f"git commit -m 'w{width} keyed'": ("denied", "call", "/repo:1: key f note") if signs else ("pending", "", "") for width, _ in base.WIDTHS})
|
||||
|
||||
def test_chromium_shows_operator_tasks_with_a_badge_diffs_bulk_grants_and_sends_feedback_at_three_widths(self):
|
||||
def test_chromium_shows_operator_tasks_with_a_badge_diffs_bulk_grants_and_line_comments_in_the_deny_call_and_grant_post_at_three_widths(self):
|
||||
with mock.patch.object(batches, "UNDO", 0.3):
|
||||
data = self.drive(self.steps("chromium", True), self.authenticator())
|
||||
self.settle(lambda: all(ask["status"] == "denied" for ask in self.httpd.hub.asks.listed() if "keyed" in ask["command"]))
|
||||
(OUT / "chromium-operator.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, "chromium", True)
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
|
||||
def test_firefox_shows_operator_tasks_with_a_badge_diffs_and_feedback_without_signing_at_three_widths(self):
|
||||
def test_firefox_shows_operator_tasks_with_a_badge_diffs_and_keeps_line_comments_without_signing_at_three_widths(self):
|
||||
data = self.drive(self.steps("firefox", False), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"))
|
||||
(OUT / "firefox-operator.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], [])
|
||||
|
||||
@@ -20,7 +20,7 @@ ROWS = 360
|
||||
WAITED = (120, 180)
|
||||
ASLEEP = 180
|
||||
UNREAD = (300, 320)
|
||||
PANELS = {"resources-hardware": "Hardware: disks, CPU, RAM, swap, GPU and VRAM", "resources-tokens": "Tokens per agent"}
|
||||
PANELS = {"resources-hardware": "Hardware: disks, CPU, RAM, swap, GPU and VRAM", "resources-tokens": "Tokens per agent", "resources-accounts": "Accounts"}
|
||||
GUARD = """() => {
|
||||
window.e2eViolations = [];
|
||||
document.addEventListener("securitypolicyviolation", (event) => window.e2eViolations.push(`${event.violatedDirective} ${event.blockedURI}`));
|
||||
@@ -128,7 +128,7 @@ class TestWorkbenchResources(HubCase):
|
||||
self.assertEqual(found["unknown"], [[self.start + UNREAD[0] * 60, self.start + UNREAD[1] * 60]])
|
||||
self.assertEqual((found["agents"], found["bottoms"], found["stacked"]), (["Skills", "Stage"], ["Skills"], True))
|
||||
self.assertEqual(found["legend"], ["CPU 60 %", "RAM 55 %", "Swap 5 %"])
|
||||
self.assertEqual(found["labels"], {"tab": ["Resources (key 6)", "Resources"], "reload": ["Reload: read the sampler files again", "Reload"], "titles": [[name, name] for name in PANELS.values()]})
|
||||
self.assertEqual(found["labels"], {"tab": ["Resources (key 6)", "Resources"], "reload": ["Reload: read the sampler files and the accounts again", "Reload"], "titles": [[name, name] for name in PANELS.values()]})
|
||||
self.assertEqual((found["unlabelled"], found["plots"]), (0, [True] * 2))
|
||||
self.assertEqual((found["tall"], found["wide"]), (False, False), "the page scrolls")
|
||||
self.assertEqual(quiet(found["violations"]), [])
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
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 kvb_orchestrator.jobs import UNRUNNABLE
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-030-shots"))
|
||||
ROWS = ["operator/free", "operator/loose", "operator/pick", "operator/runs", "operator/waits"]
|
||||
READ = """
|
||||
const blockedTitles = (selector) => Object.fromEntries(all(selector).filter((node) => node.hasAttribute("data-blocked")).map((node) => [node.dataset.card || node.dataset.ref || node.dataset.operator, node.getAttribute("title") || ""]));
|
||||
const wide = () => document.documentElement.scrollWidth > innerWidth + 1;
|
||||
"""
|
||||
MATCH = """(async () => {@HELPERS@@READ@
|
||||
if (!(await until(() => document.querySelector("#main .match-card.front"), 15000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
const toggle = document.querySelector("#main .match-peeks-toggle");
|
||||
if (toggle && toggle.getAttribute("aria-pressed") !== "true") {
|
||||
toggle.click();
|
||||
}
|
||||
await until(() => all("#main .match-peek").length === 4, 4000);
|
||||
const front = document.querySelector("#main .match-card.front");
|
||||
const accept = document.querySelector("#main .match-accept");
|
||||
const reject = document.querySelector("#main .match-reject");
|
||||
return {
|
||||
front: front.dataset.card, forms: all(".choice", front).length, accept: [accept.disabled, accept.getAttribute("title")], reject: [reject.disabled, reject.getAttribute("title")],
|
||||
peeks: all("#main .match-peek").map((peek) => peek.dataset.card), blocked: blockedTitles("#main .match-peek"), wide: wide(),
|
||||
};
|
||||
})()"""
|
||||
STREAM = """(async () => {@HELPERS@@READ@
|
||||
const rows = () => all("#main .feed > li.k-operator");
|
||||
if (!(await until(() => rows().length === 5, 15000))) {
|
||||
return {error: text(document.getElementById("main")), rows: rows().length};
|
||||
}
|
||||
const pick = rows().find((row) => row.dataset.ref === "operator:operator/pick");
|
||||
const buttons = (row) => all(".line-actions button", row).map((button) => [name(button), button.disabled]);
|
||||
const runs = rows().find((row) => row.dataset.ref === "operator:operator/runs");
|
||||
return {refs: rows().map((row) => row.dataset.ref).sort(), blocked: blockedTitles("#main .feed > li.k-operator"), pickForms: pick ? all(".choice", pick).length : null, pickButtons: pick ? buttons(pick) : null, runsButtons: runs ? buttons(runs) : null, wide: wide()};
|
||||
})()"""
|
||||
TASKS = """(async () => {@HELPERS@@READ@
|
||||
if (!(await until(() => all("#main .operator-list > li").length === 5, 15000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
return {rows: all("#main .operator-list > li").map((row) => row.dataset.operator).sort(), blocked: Object.keys(blockedTitles("#main .operator-list > li")).length, runs: document.querySelector('#main .operator-list > li[data-operator="operator/runs"]').getAttribute("title"), wide: wide()};
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str) -> str:
|
||||
return template.replace("@HELPERS@", base.HELPERS).replace("@READ@", READ)
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestYesNoAnswers(HubCase):
|
||||
drive = base.OrchestratorE2ECase.drive
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
work = self.outside / "work"
|
||||
work.mkdir()
|
||||
row = {"title": "true", "workdir": str(work), "description": "ship the release notes", "check": "done", "roles": {"Skills": "A", "Operator": "R"}}
|
||||
yes_no = [{"label": "Yes", "description": "merge it"}, {"label": "No", "description": "leave it"}]
|
||||
register = {task: row for task in ("operator/free", "operator/runs", "operator/waits")}
|
||||
register |= {"operator/loose": {**row, "workdir": "relative/dir"}, "operator/pick": {**row, "title": "Merge the hub now?", "check": "decision", "options": yes_no}}
|
||||
self.write_council({"rasci.json": register})
|
||||
now = time.time()
|
||||
job = {"command": "true", "directory": str(work), "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 - 1800, "started": now - 1800})
|
||||
self.httpd.hub.jobs.add({**job, "task": "operator/waits", "status": "queued", "created_ts": now - 600, "started": None})
|
||||
self.page_url = f"http://localhost:{self.port}/"
|
||||
|
||||
def test_chromium_shows_every_open_row_in_match_the_stream_and_tasks_greying_the_blocked_ones_at_three_widths(self):
|
||||
steps = []
|
||||
for width, height in base.WIDTHS:
|
||||
shot = OUT / f"chromium-{width}"
|
||||
steps += [
|
||||
{"width": width, "height": height, "url": f"{self.page_url}?{width}#tasks/match", "wait": 1500, "probe": probe(MATCH), "shot": f"{shot}-match.png"},
|
||||
{"width": width, "height": height, "url": f"{self.page_url}?{width}-stream#stream", "wait": 1500, "probe": probe(STREAM), "shot": f"{shot}-stream.png"},
|
||||
{"width": width, "height": height, "url": f"{self.page_url}?{width}-tasks#tasks/list", "wait": 1500, "probe": probe(TASKS), "shot": f"{shot}-tasks.png"},
|
||||
]
|
||||
data = self.drive(steps, None)
|
||||
(OUT / "chromium-yes-no.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.assertEqual(data["errors"], [])
|
||||
results = iter(data["results"])
|
||||
blocked = {"operator/loose": UNRUNNABLE, "operator/runs": "The hub runner runs it for 30 min", "operator/waits": "Queued in the hub runner for 10 min behind operator/runs"}
|
||||
for width, _ in base.WIDTHS:
|
||||
match, stream, tasks = next(results), next(results), next(results)
|
||||
with self.subTest(width=width):
|
||||
self.assertNotIn("error", match, match)
|
||||
self.assertEqual(sorted([match["front"], *match["peeks"]]), sorted(f"operator:{task}" for task in ROWS))
|
||||
self.assertEqual(sorted(match["blocked"]), sorted(f"operator:{task}" for task in blocked))
|
||||
for task, reason in blocked.items():
|
||||
self.assertIn(reason, match["blocked"][f"operator:{task}"])
|
||||
if match["front"] == "operator:operator/pick":
|
||||
self.assertEqual(match["forms"], 0)
|
||||
self.assertEqual(match["accept"][0], False)
|
||||
self.assertTrue(match["accept"][1].startswith("Accept: Yes"), match["accept"])
|
||||
self.assertTrue(match["reject"][1].startswith("Reject: No"), match["reject"])
|
||||
self.assertNotIn("error", stream, stream)
|
||||
self.assertEqual(stream["refs"], sorted(f"operator:{task}" for task in ROWS))
|
||||
self.assertEqual(sorted(stream["blocked"]), sorted(f"operator:{task}" for task in blocked))
|
||||
for task, reason in blocked.items():
|
||||
self.assertIn(reason, stream["blocked"][f"operator:{task}"])
|
||||
self.assertEqual(stream["pickForms"], 0)
|
||||
self.assertEqual(stream["pickButtons"][:2], [["Yes", False], ["No", False]])
|
||||
self.assertIn(["Run", True], stream["runsButtons"])
|
||||
self.assertNotIn("error", tasks, tasks)
|
||||
self.assertEqual((tasks["rows"], tasks["blocked"]), (ROWS, 5))
|
||||
self.assertIn(blocked["operator/runs"], tasks["runs"])
|
||||
self.assertEqual((match["wide"], stream["wide"], tasks["wide"]), (False, False, False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user