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:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-25 01:22:03 +00:00
1 parent 7d1926e3de
commit 2722cda1b5
120 files changed
+5372 -486

No files matched your search

+1 -1
View File
@@ -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
View File
@@ -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);
+6 -5
View File
@@ -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();
+5 -4
View File
@@ -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);
+1 -1
View File
@@ -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();
+1 -1
View File
@@ -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;
+191
View File
@@ -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()
+1 -1
View File
@@ -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)
+141
View File
@@ -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()
+8 -8
View File
@@ -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"]
+8 -4
View File
@@ -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)
+1 -1
View File
@@ -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):
+14 -14
View File
@@ -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)
+173
View File
@@ -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">&minus;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()
+124
View File
@@ -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()
+1 -1
View File
@@ -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)
+128
View File
@@ -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()
+1 -1
View File
@@ -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"]])
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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")], [])
+156
View File
@@ -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()
+24 -8
View File
@@ -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)
+147
View File
@@ -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()
+147
View File
@@ -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()
+164
View File
@@ -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()
+47 -28
View File
@@ -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], [])
+2 -2
View File
@@ -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"]), [])
+125
View File
@@ -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()
+214
View File
@@ -0,0 +1,214 @@
from __future__ import annotations
import copy
import importlib.util
import json
import os
import stat
import subprocess
import sys
import tempfile
import time
import unittest
from pathlib import Path
import hub_support
from hub_case import HubCase
from kvb_orchestrator import accounts
from kvb_orchestrator.errors import ToolError
from kvb_orchestrator.viewstore import VIEW, upgraded, valid_view
HUB = hub_support.HUB
REPO = hub_support.REPO_ROOT
HOOK = REPO / "skills" / "kvb-org-organize" / "scripts" / "account.py"
SAMPLER = HUB / "client" / "resources.py"
MODULE = HUB / "templates" / "resources.js"
ACCOUNT = {
"provider": "Anthropic", "email": "one@example.org", "renewal": {"day": 1, "time": "09:00"}, "reset": {"day": 4, "time": "18:30"},
"resubscribe": "2026-12-01", "autorenew": True, "limit": 1000, "note": "team seat",
}
MOMENTS = r"""
const R = require(process.argv[1]);
const at = (text) => new Date(text).getTime();
const iso = (ms) => new Date(ms).toISOString();
const reset = {day: 0, time: "03:30"};
const entry = {total: 900, hours: [[at("2026-10-24T22:00:00Z") / 1000, 100], [at("2026-10-25T03:00:00Z") / 1000, 200], [at("2026-10-26T08:00:00Z") / 1000, 300]]};
console.log(JSON.stringify({
before: iso(R.lastMoment(reset, at("2026-10-25T01:00:00Z"))),
after: iso(R.lastMoment(reset, at("2026-10-25T04:00:00Z"))),
next: iso(R.nextMoment(reset, at("2026-10-25T04:00:00Z"))),
exact: iso(R.lastMoment(reset, at("2026-10-25T02:30:00Z"))),
used: R.accountUsage(entry, reset, at("2026-10-26T09:00:00Z")),
unassigned: R.accountUsage(entry, null, at("2026-10-26T09:00:00Z")),
}));
"""
def load(path: Path, name: str):
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class TestValidation(unittest.TestCase):
def test_a_full_account_passes_and_every_bad_field_is_refused(self):
self.assertEqual(accounts.valid_account(copy.deepcopy(ACCOUNT)), ACCOUNT)
self.assertEqual(accounts.valid_account({**ACCOUNT, "limit": None, "resubscribe": ""})["limit"], None)
bad = {
"email": "not-an-address", "renewal": {"day": 7, "time": "09:00"}, "reset": {"day": 1, "time": "24:00"},
"resubscribe": "2026-02-30", "autorenew": "yes", "limit": -1, "provider": "", "note": "x" * 201,
}
for key, value in bad.items():
with self.subTest(key=key), self.assertRaises(ToolError):
accounts.valid_account({**ACCOUNT, key: value})
with self.assertRaises(ToolError):
accounts.valid_account({**ACCOUNT, "extra": 1})
def test_usage_sums_per_account_with_recent_hours_and_unmapped_rows_under_the_empty_key(self):
now = 1_000_000.0
rows = [
{"t": now - 7200, "agent": "A", "model": "m", "input": 10, "output": 5, "cache_read": 0, "cache_write": 0, "account": "one@example.org"},
{"t": now - 3600, "agent": "B", "model": "m", "input": 1, "output": 1, "cache_read": 1, "cache_write": 1, "account": "two@example.org"},
{"t": now - 3600, "agent": "A", "model": "m", "input": 20, "output": 0, "cache_read": 0, "cache_write": 0, "account": "one@example.org"},
{"t": now - 30 * 86400, "agent": "A", "model": "m", "input": 100, "output": 0, "cache_read": 0, "cache_write": 0, "account": "one@example.org", "width": 86400},
{"t": now - 3600, "agent": "C", "model": "m", "input": 7, "output": 0, "cache_read": 0, "cache_write": 0},
]
self.assertEqual(accounts.usage(rows, now), {
"one@example.org": {"total": 135, "hours": [(int(now - 7200), 15), (int(now - 3600), 20)]},
"two@example.org": {"total": 4, "hours": [(int(now - 3600), 4)]},
"": {"total": 7, "hours": [(int(now - 3600), 7)]},
})
class TestResetMath(unittest.TestCase):
def test_the_weekly_reset_keeps_its_wall_clock_across_the_october_dst_change(self):
done = subprocess.run(["node", "-e", MOMENTS, str(MODULE)], capture_output=True, text=True, timeout=60, check=False, env={**os.environ, "TZ": "Europe/Berlin"})
self.assertEqual(done.returncode, 0, done.stderr)
found = json.loads(done.stdout)
self.assertEqual(found["before"], "2026-10-18T01:30:00.000Z")
self.assertEqual(found["after"], "2026-10-25T02:30:00.000Z")
self.assertEqual(found["exact"], "2026-10-25T02:30:00.000Z")
self.assertEqual(found["next"], "2026-11-01T02:30:00.000Z")
self.assertEqual(found["used"], {"since": 500, "today": 300, "total": 900})
self.assertEqual(found["unassigned"], {"since": None, "today": 300, "total": 900})
class TestHook(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.root = Path(folder.name)
self.home, self.council = self.root / "home", self.root / "council"
self.home.mkdir()
profile = {"oauthAccount": {"emailAddress": "one@example.org", "accountUuid": "u-1", "organizationName": "Org"}, "projects": {"/x": {"history": ["secret"]}}}
(self.home / ".claude.json").write_text(json.dumps(profile), encoding="utf-8")
def hook(self, payload: dict) -> subprocess.CompletedProcess:
env = {"PATH": os.environ["PATH"], "HOME": str(self.home), "AGENTS_COUNCIL_ROOT": str(self.council)}
return subprocess.run([sys.executable, str(HOOK), "hook"], input=json.dumps(payload), capture_output=True, text=True, timeout=60, check=False, env=env)
def test_the_hook_writes_one_line_of_session_and_email_only_mode_0600_and_no_repeat(self):
for payload in ({"session_id": "s1"}, {"session_id": "s1"}, {"session_id": "s2", "agent_id": "sub"}, {}):
self.assertEqual(self.hook(payload).returncode, 0)
path = self.council / accounts.SESSION_ACCOUNTS
self.assertEqual(path.read_text(encoding="utf-8").splitlines(), ['{"session": "s1", "email": "one@example.org"}'])
self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600)
self.assertEqual(accounts.mapping(path), {"s1": "one@example.org"})
self.assertEqual(accounts.active(path), "one@example.org")
def test_a_profile_without_the_field_writes_nothing(self):
(self.home / ".claude.json").write_text(json.dumps({"oauthAccount": {}}), encoding="utf-8")
self.assertEqual(self.hook({"session_id": "s1"}).returncode, 0)
self.assertFalse((self.council / accounts.SESSION_ACCOUNTS).exists())
class TestSampler(unittest.TestCase):
def test_token_rows_carry_the_account_of_their_session_and_merge_per_account(self):
sampler = load(SAMPLER, "kvb_resources_sampler")
sums: dict = {}
sampler.add(sums, (3600, "A", "m", 3600, "one@example.org"), (1, 2, 0, 0))
sampler.add(sums, (3600, "A", "m", 3600, ""), (5, 0, 0, 0))
rows = sampler.token_rows(sums)
self.assertEqual([(row["input"], row.get("account")) for row in rows], [(5, None), (1, "one@example.org")])
merged = sampler.compact(rows + rows, 7200)
self.assertEqual([(row["input"], row.get("account")) for row in merged], [(10, None), (2, "one@example.org")])
with tempfile.TemporaryDirectory() as folder:
council = Path(folder)
(council / sampler.SESSION_ACCOUNTS).write_text('{"session": "s1", "email": "a@example.org"}\n{"session": "s1", "email": "b@example.org"}\nnot json\n', encoding="utf-8")
self.assertEqual(sampler.session_accounts(council), {"s1": "b@example.org"})
def test_an_agent_written_mapping_that_is_a_link_a_fifo_too_big_or_too_long_maps_nothing(self):
sampler = load(SAMPLER, "kvb_resources_sampler")
line = '{"session": "s1", "email": "a@example.org"}\n'
with tempfile.TemporaryDirectory() as folder:
council = Path(folder)
path = council / sampler.SESSION_ACCOUNTS
target = council / "target.jsonl"
target.write_text(line, encoding="utf-8")
path.symlink_to(target)
self.assertEqual(sampler.session_accounts(council), {})
path.unlink()
os.mkfifo(path)
self.assertEqual(sampler.session_accounts(council), {})
path.unlink()
path.write_text(line + " " * sampler.JSON_BYTES, encoding="utf-8")
self.assertEqual(sampler.session_accounts(council), {})
path.write_text(line + json.dumps({"session": "s2", "email": "x" * (sampler.EMAIL_CHARS + 1)}) + "\n", encoding="utf-8")
self.assertEqual(sampler.session_accounts(council), {"s1": "a@example.org"})
class TestView(unittest.TestCase):
def test_the_panels_list_replaces_the_combined_flag_of_older_documents(self):
for combined, panels in ((True, ["combined", "accounts"]), (False, ["hardware", "tokens", "accounts"])):
with self.subTest(combined=combined):
old = copy.deepcopy(VIEW)
old["resources"] = {key: value for key, value in old["resources"].items() if key != "panels"} | {"combined": combined}
self.assertEqual(valid_view(upgraded(old))["resources"]["panels"], panels)
class TestAccountsApi(HubCase):
def post(self, path: str, payload: object) -> tuple[int, bytes]:
status, _, body = self.post_json(path, payload, self.guard(self.host))
return status, body
def test_add_edit_and_remove_keep_the_file_0600_outside_the_repo_and_refuse_bad_input(self):
status, body = self.post("/api/accounts", {"id": "", "account": ACCOUNT})
self.assertEqual(status, 200, body)
added = json.loads(body)
file = self.state / accounts.ACCOUNTS
self.assertEqual(stat.S_IMODE(file.stat().st_mode), 0o600)
status, body = self.post("/api/accounts", {"id": added["id"], "account": {**ACCOUNT, "limit": None}})
self.assertEqual((status, json.loads(body)["limit"]), (200, None))
for payload in ({"id": "", "account": {**ACCOUNT, "email": "x"}}, {"id": "", "account": {**ACCOUNT, "limit": -5}}, {"id": "zz", "account": ACCOUNT}, {"account": ACCOUNT}):
with self.subTest(payload=str(payload)[:60]):
self.assertEqual(self.post("/api/accounts", payload)[0], 400)
self.assertEqual(self.post("/api/accounts", {"id": "0" * 16, "account": ACCOUNT})[0], 404)
status, _, body = self.get("/api/accounts")
self.assertEqual(status, 200, body)
view = json.loads(body)
self.assertEqual(([row["email"] for row in view["accounts"]], view["active"], view["usage"]), (["one@example.org"], None, {}))
self.assertEqual(self.post(f"/api/accounts/{added['id']}/delete", {})[0], 200)
self.assertEqual(self.post(f"/api/accounts/{added['id']}/delete", {})[0], 404)
view_file = self.state / "view.json"
self.assertNotIn("example.org", view_file.read_text(encoding="utf-8") if view_file.exists() else "")
self.assertFalse(str(file).startswith(str(REPO)))
def test_the_view_maps_usage_and_the_active_account_from_the_hook_and_the_sampler_rows(self):
self.post("/api/accounts", {"id": "", "account": ACCOUNT})
self.council.mkdir(parents=True, exist_ok=True)
(self.council / accounts.SESSION_ACCOUNTS).write_text('{"session": "s1", "email": "one@example.org"}\n', encoding="utf-8")
folder = self.kept / "resources"
folder.mkdir(parents=True, exist_ok=True)
hour = int(time.time() // 3600 * 3600)
rows = [{"t": hour, "agent": "A", "model": "m", "input": 40, "output": 2, "cache_read": 0, "cache_write": 0, "account": "one@example.org"}, {"t": hour, "agent": "B", "model": "m", "input": 3, "output": 0, "cache_read": 0, "cache_write": 0}]
(folder / "tokens.jsonl").write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")
status, _, body = self.get("/api/accounts")
self.assertEqual(status, 200, body)
view = json.loads(body)
self.assertEqual(view["active"], "one@example.org")
self.assertEqual(view["usage"], {"one@example.org": {"total": 42, "hours": [[hour, 42]]}, "": {"total": 3, "hours": [[hour, 3]]}})
if __name__ == "__main__":
unittest.main()
+54
View File
@@ -0,0 +1,54 @@
from __future__ import annotations
import json
import subprocess
import unittest
import hub_support
from kvb_orchestrator.jobs import UNRUNNABLE, row_blocked
MODULE = hub_support.HUB / "templates" / "answers.js"
CLASSIFY = r"""
const A = require(process.argv[1]);
const option = (label) => ({label, description: ""});
const items = {
ask: {kind: "ask"},
yesNo: {kind: "decision", options: [option("Yes"), option("No")], multi: false},
row: {kind: "operator", check: "decision", options: [option(" no "), option("YES")], multi: false},
named: {kind: "decision", options: [option("Commit B11"), option("Don't commit")], multi: false},
multi: {kind: "decision", options: [option("Yes"), option("No")], multi: true},
three: {kind: "decision", options: [option("Yes"), option("No"), option("Later")], multi: false},
command: {kind: "operator", check: "done", options: []},
};
console.log(JSON.stringify({
boolean: Object.fromEntries(Object.entries(items).map(([name, item]) => [name, A.boolean(item)])),
pair: A.pair(items.yesNo),
declined: [A.declined("No", "", 1000), A.declined("No", " rebase first,\n then merge ", 1000), A.declined("No", "x".repeat(20), 10), A.declined("No", "Yes", 1000)],
}));
"""
class TestAnswers(unittest.TestCase):
def test_asks_and_yes_no_choices_are_boolean_while_named_multi_and_longer_choices_keep_their_form(self):
done = subprocess.run(["node", "-e", CLASSIFY, str(MODULE)], capture_output=True, text=True, timeout=60, check=False)
self.assertEqual(done.returncode, 0, done.stderr)
found = json.loads(done.stdout)
self.assertEqual(found["boolean"], {"ask": True, "yesNo": True, "row": True, "named": False, "multi": False, "three": False, "command": False})
self.assertEqual(found["pair"], {"yes": "Yes", "no": "No"})
self.assertEqual(found["declined"], ["No", "No: rebase first, then merge", "No: xxxxxx", "No: Yes"])
class TestRowBlocked(unittest.TestCase):
def test_a_queued_or_running_job_names_its_reason_a_free_row_none_and_a_decision_row_is_never_unrunnable(self):
row = {"task": "operator/x", "command": "true", "directory": "/repo", "check": "done"}
reasons = {"operator/q": "Queued in the hub runner for 3 min", "operator/r": "The hub runner runs it for 9 min"}
self.assertEqual(row_blocked(row, reasons), "")
self.assertEqual(row_blocked({**row, "task": "operator/q"}, reasons), reasons["operator/q"])
self.assertEqual(row_blocked({**row, "task": "operator/r", "directory": "relative"}, reasons), reasons["operator/r"])
self.assertEqual(row_blocked({**row, "directory": "relative"}, reasons), UNRUNNABLE)
self.assertEqual(row_blocked({**row, "command": "-"}, reasons), UNRUNNABLE)
self.assertEqual(row_blocked({**row, "check": "decision", "directory": "-"}, reasons), "")
if __name__ == "__main__":
unittest.main()
+95
View File
@@ -0,0 +1,95 @@
from __future__ import annotations
import json
import re
import subprocess
import unittest
from hub_support import HUB
TEMPLATES = HUB / "templates"
MODULES = ["page-constants.js", "page-reveal.js", "page-dom.js"]
VIEWS = {
"page-match.js": "Match",
"page-tasks.js": "Tasks",
"page-resources.js": "Resources",
"page-artifacts.js": "Artifacts",
"page-graph-charts.js": "Agents",
"page-firewall.js": "Controls",
}
PROBE = r"""
const fs = require("fs");
const vm = require("vm");
const [dir, names] = [process.argv[1], JSON.parse(process.argv[2])];
class El {
constructor(tag) { Object.assign(this, {tag, children: [], attrs: {}, dataset: {}, style: {}}); }
setAttribute(key, value) { this.attrs[key] = String(value); }
getAttribute(key) { return Object.hasOwn(this.attrs, key) ? this.attrs[key] : null; }
append(...nodes) { this.children.push(...nodes); }
addEventListener() {}
}
const document = {
currentScript: null, body: new El("body"),
getElementById: () => Object.assign(new El("div"), {textContent: "[]"}),
createElement: (tag) => new El(tag), createElementNS: (ns, tag) => new El(tag),
};
const context = {
console, document, JSON, Math, Date, Intl, Promise, Set, Map, Number, String, Array, Object, RegExp, Boolean, Error,
Node: El, Element: El, HTMLElement: El,
window: {location: {hash: ""}, setTimeout: () => 0, matchMedia: () => ({matches: false})},
state: {inbox: [], radio: []}, ui: {}, settings: {},
};
const source = names.map((name) => fs.readFileSync(`${dir}/${name}`, "utf8")).join("\n");
const probe = `
const title = h("strong", {class: "box-title"}, "Match");
const count = h("span", {}, "2 cards wait");
const button = h("button", {type: "button"}, "Tasks");
const band = boxHead("Match", "task-toolbar", title, count, null, button);
const plain = boxHead("Resources", "", button);
const holding = boxHead("Agents", "", h("div", {role: "toolbar", "aria-label": "Agents tools"}, button));
JSON.stringify({
band: {tag: band.tag, attrs: band.attrs, order: band.children.map((child) => child.tag + ":" + (child.children[0] || ""))},
plain: plain.attrs.class, holding: holding.attrs.role,
});
`;
console.log(vm.runInNewContext(`${source}\n${probe}`, context));
"""
class TestBoxHeads(unittest.TestCase):
def test_the_band_helper_renders_its_label_classes_and_children_in_order_and_never_nests_a_toolbar(self):
done = subprocess.run(["node", "-e", PROBE, str(TEMPLATES), json.dumps(MODULES)], capture_output=True, text=True, timeout=60, check=False)
self.assertEqual(done.returncode, 0, done.stderr)
out = json.loads(done.stdout)
self.assertEqual(out["band"]["tag"], "div")
self.assertEqual(out["band"]["attrs"], {"class": "box-head task-toolbar", "role": "toolbar", "aria-label": "Match"})
self.assertEqual(out["band"]["order"], ["strong:Match", "span:2 cards wait", "button:Tasks"])
self.assertEqual((out["plain"], out["holding"]), ("box-head", "group"))
def test_every_view_builds_its_controls_with_the_one_band_helper(self):
helpers = [name for name in sorted(path.name for path in TEMPLATES.glob("*.js")) if re.search(r"\bconst boxHead\b|\bfunction boxHead\b", (TEMPLATES / name).read_text(encoding="utf-8"))]
self.assertEqual(helpers, ["page-dom.js"])
for name, label in VIEWS.items():
with self.subTest(view=name):
self.assertIn(f'boxHead("{label}"', (TEMPLATES / name).read_text(encoding="utf-8"))
def test_no_template_keeps_a_separate_controls_card(self):
for path in sorted(TEMPLATES.glob("*.js")):
with self.subTest(file=path.name):
self.assertNotIn("card controls", path.read_text(encoding="utf-8"))
def test_the_band_sits_on_the_box_edge_through_the_main_padding_variables(self):
page = (TEMPLATES / "index.html.j2").read_text(encoding="utf-8")
self.assertRegex(page, r"main \{ --main-pad: var\(--sp-5\); --main-top: var\(--main-pad\);[^}]*padding: var\(--main-top\) var\(--main-pad\)")
self.assertRegex(page, r"\.box-head \{[^}]*margin: calc\(-1 \* var\(--main-top\)\) calc\(-1 \* var\(--main-pad\)\) 0;")
self.assertIn("--main-top: var(--sp-3)", (TEMPLATES / "style-ui.css").read_text(encoding="utf-8"))
def test_the_match_card_bar_is_its_own_background_on_the_outer_edge(self):
css = (TEMPLATES / "style-match.css").read_text(encoding="utf-8")
self.assertNotIn(".match-card.front::before", css)
self.assertRegex(css, r"\.match-card\.front \{[^}]*border-top-width: 0;[^}]*background: var\(--bar\) top / 100% 6px no-repeat")
self.assertIn("mask-image: linear-gradient(180deg, transparent 6px, #000 6px", css)
if __name__ == "__main__":
unittest.main()
+18 -6
View File
@@ -27,7 +27,11 @@ class Element {
}
getAttribute(name) { return Object.hasOwn(this.attrs, name) ? this.attrs[name] : null; }
hasAttribute(name) { return Object.hasOwn(this.attrs, name); }
matches(selector) { return selector.split(",").map((part) => part.trim()).some((part) => (part.startsWith("[") ? this.hasAttribute(part.slice(1, -1)) : this.tagName === part.toUpperCase())); }
matches(selector) {
return selector.split(",").map((part) => /^([\w-]*)(?:\[([\w-]+)\])?$/.exec(part.trim())).some((found) => Boolean(found) && (!found[1] || this.tagName === found[1].toUpperCase()) && (!found[2] || this.hasAttribute(found[2])));
}
get dataset() { return Object.fromEntries(Object.entries(this.attrs).filter(([name]) => name.startsWith("data-")).map(([name, value]) => [name.slice(5), value])); }
get classList() { return {contains: (name) => String(this.attrs.class || "").split(" ").includes(name)}; }
closest(selector) { return this.matches(selector) ? this : this.parentElement && this.parentElement.closest(selector); }
contains(node) { return Boolean(node) && (node === this || this.contains(node.parentElement)); }
getBoundingClientRect() { return this.rect; }
@@ -45,7 +49,7 @@ const context = {
h: (tag, attrs, ...children) => ({tag, attrs, children}), face: () => null, revealed: (text) => text,
agentNames: () => ["Docs", "Stage"], agentKey: (who) => KEYS_OF[who] || who, nameOf: (key) => NAMES[key] || key, labelOf: (key) => NAMES[key] || key, keyOf: (item) => `${item.kind}:${item.id}`,
go: () => {}, useView: () => {}, useSaved: () => {}, openAgent: () => {}, openRadio: () => {}, confirmAct: () => {}, openAgentOrder: () => {}, settingsSheet: () => {},
toggleMusic: () => {}, skyLook: () => {}, toggleLeitstand: () => {}, askNotify: () => {}, helpSheet: () => {}, micButton: () => null,
toggleMusic: () => {}, skyLook: () => {}, toggleLeitstand: () => {}, askNotify: () => {}, helpSheet: () => {}, micFrame: (field) => field,
taskSheet: (id) => calls.tasks.push(id), artSelect: () => {}, select: () => {}, openItem: () => {}, openSheet: () => {}, glossarySections: () => [], toast: () => {},
homePins: () => [], homePress: (kind, id) => calls.pins.push(`${kind}:${id}`), HOME_OPENERS: {task: (id) => calls.tasks.push(`home ${id}`)},
closeMenus: () => { calls.closed += 1; }, calls,
@@ -53,7 +57,7 @@ const context = {
const probe = `
ctxShow = (sections, at) => calls.shown.push({at, sections: labels(sections)});
selectionFeedback = () => null;
feedbackSheet = (picked) => calls.feedback.push(picked.path);
markLines = (picked) => calls.feedback.push(picked.path + ":" + picked.from + "-" + picked.until);
const labels = (sections) => sections.map((section) => [section.scope, section.title, section.items.map((item) => item.label)]);
const out = {};
const panel = new Element("div", {"data-panel": "tasks/list"});
@@ -94,6 +98,12 @@ const entry = new Element("li", {"data-ref": "review:r1", "data-to": "Skills"});
const file = new Element("section", {"data-path": "src/app.py"}, entry);
const cell = new Element("td", {}, file);
out.unselected = labels(ctxSections(cell))[0];
const row = new Element("tr", {"data-line": "7"}, file);
const code = new Element("td", {}, row);
out.row = fire(code, {});
ctxSections(code)[0].items[0].run();
const note = new Element("tr", {"data-line": "7", class: "match-mark"}, file);
out.note = fire(new Element("td", {}, note), {}).sections[0][2];
selectionFeedback = () => ({ref: "review:r1", to: "Skills", path: "src/app.py", from: 2, until: 3, quote: "new"});
out.selected = fire(cell, {});
ctxSections(cell)[0].items[0].run();
@@ -159,12 +169,14 @@ class TestHubContextMenu(unittest.TestCase):
with self.subTest(case=case):
self.assertEqual(keys[case], {"prevented": False, "at": None, "element": None})
def test_a_selection_in_a_diff_makes_feedback_the_first_item_of_the_menu(self):
def test_a_selection_or_a_right_clicked_code_row_in_a_diff_makes_comment_the_first_item_of_the_menu(self):
self.assertEqual(self.data["unselected"], ["element", "src/app.py", ["Copy path", "Open entry", "Copy id"]])
self.assertEqual(self.data["row"]["sections"][0], ["element", "src/app.py", ["Comment", "Copy path", "Open entry", "Copy id"]])
self.assertEqual(self.data["note"], ["Copy path", "Open entry", "Copy id"])
selected = self.data["selected"]
self.assertTrue(selected["prevented"])
self.assertEqual(selected["sections"][0], ["element", "src/app.py", ["Feedback", "Copy path", "Open entry", "Copy id"]])
self.assertEqual(self.data["feedback"], ["src/app.py"])
self.assertEqual(selected["sections"][0], ["element", "src/app.py", ["Comment", "Copy path", "Open entry", "Copy id"]])
self.assertEqual(self.data["feedback"], ["src/app.py:7-7", "src/app.py:2-3"])
def test_the_shortcuts_sheet_names_the_context_menu_keys(self):
keys = self.data["keysHelp"]
+5 -16
View File
@@ -8,7 +8,7 @@ from hub_case import HubCase
from hub_support import HUB
TEMPLATES = HUB / "templates"
MODULES = ["page-constants.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-inbox.js", "page-grant.js"]
MODULES = ["page-constants.js", "answers.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-inbox.js", "page-grant.js"]
PROBE = r"""
const fs = require("fs");
const vm = require("vm");
@@ -118,17 +118,9 @@ const results = {};
results.keys = {submits: submits.splice(0), stopped, focused: document.activeElement === null ? "" : document.activeElement.tag};
press("4");
results.keys.other = document.activeElement.tag;
const denials = [];
denyNow = (item, channel, reason) => { denials.push([item.id, channel, reason]); };
const asking = inboxItem(items.ask, 6);
results.ask = {options: shape(asking).options, other: shape(asking).other};
await optionNamed(asking, "No").fire("click");
const tell = classed(asking, "other")[0];
all(tell).find((el) => el.tag === "input").value = " Yes ";
await tell.fire("submit");
await optionNamed(asking, "Yes").fire("click");
results.ask.denials = denials.splice(0);
results.ask.grants = submits.splice(0).map((label) => label.split(":")[0]);
const buttons = all(asking).filter((el) => el.tag === "button").map((el) => el.getAttribute("aria-label"));
results.ask = {options: shape(asking).options, other: shape(asking).other, choice: shape(asking).choice, grant: buttons.includes("Grant"), deny: all(asking).some((el) => el.tag === "deny")};
const look = (item) => {
const node = inboxItem(item, 0);
return [waitOf(item), (node.attrs.class || "").split(" ").includes("pending"), classed(node, "wait-spin").length, node.attrs.title || ""];
@@ -211,11 +203,8 @@ class TestDecisionRows(unittest.TestCase):
self.assertEqual((keys["submits"], keys["stopped"], keys["focused"]), (["Choice: B"], 1, ""))
self.assertEqual(keys["other"], "input")
def test_a_permission_ask_offers_yes_and_no_and_typed_text_always_denies_with_it_as_the_reason(self):
ask = self.data["ask"]
self.assertEqual((ask["options"], ask["other"]), ([["Yes", False], ["No", False]], 1))
self.assertEqual(ask["denials"], [["a-1", "post", ""], ["a-1", "post", "Yes"]])
self.assertEqual(ask["grants"], ["Grant"])
def test_a_permission_ask_shows_no_numbered_form_and_its_grant_and_deny_buttons_answer_it(self):
self.assertEqual(self.data["ask"], {"options": [], "other": 0, "choice": 0, "grant": True, "deny": True})
class TestDecisionFeed(HubCase):
+1 -1
View File
@@ -7,7 +7,7 @@ import unittest
from hub_support import HUB
TEMPLATES = HUB / "templates"
MODULES = ["page-constants.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-inbox.js", "page-grant.js"]
MODULES = ["page-constants.js", "answers.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-inbox.js", "page-grant.js"]
PROBE = r"""
const fs = require("fs");
const vm = require("vm");
+4 -2
View File
@@ -643,7 +643,9 @@ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
def node(probe: str, *args: str) -> dict:
done = subprocess.run(["node", "-e", probe, *args], capture_output=True, text=True, timeout=60, check=True)
done = subprocess.run(["node", "-e", probe, *args], capture_output=True, text=True, timeout=60, check=False)
if done.returncode != 0:
raise AssertionError(done.stderr[-2000:])
return json.loads(done.stdout)
@@ -765,7 +767,7 @@ class TestHomePage(unittest.TestCase):
marked = set(re.findall(r"\['[^']+', \"([^\"]+)\"\]", home))
captured = set(re.findall(r'Panels\.capture\("([^"]+)"', home))
made = set(re.findall(r'\{kind: "(\w+)", id, view[,}]', sources))
self.assertEqual((len(literal), marked), (12, {"radio-log"}))
self.assertEqual((len(literal), marked), (13, {"radio-log"}))
literal |= marked
self.assertEqual(len(dynamic), 13)
self.assertEqual(sorted(literal | dynamic), sorted(registered))
+1 -1
View File
@@ -147,7 +147,7 @@ class TestLocalPlan(HubCase):
def test_the_tree_timer_writes_the_local_dry_run_after_the_tree(self):
starts = [line.split("=", 1)[1] for line in TREE_UNIT.read_text(encoding="utf-8").splitlines() if line.startswith("ExecStart=")]
self.assertEqual(len(starts), 2)
self.assertEqual(len(starts), 3)
self.assertIn("pkgmgr branch tree --format json --output %h/.local/state/pkgmgr/tree/branch-tree.json", starts[0])
self.assertEqual(starts[1], "/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/local_plan.py --tree %h/.local/state/pkgmgr/tree/branch-tree.json --pkgmgr %h/.local/share/kvb-orchestrator/pkgmgr/bin/pkgmgr --budget 240")
self.assertIn("TimeoutStartSec=600", TREE_UNIT.read_text(encoding="utf-8").splitlines())
+73 -1
View File
@@ -13,9 +13,20 @@ from pathlib import Path
from unittest import mock
from hub_case import HubCase
from hub_support import APPROVAL, ASK, GIT_ENV, HUB, OPTIONS, REPO_ROOT, key, signing
from hub_support import (
APPROVAL,
ASK,
GIT_ENV,
HUB,
OPERATOR,
OPTIONS,
REPO_ROOT,
key,
signing,
)
from kvb_orchestrator import batches, ledger, payloads, scores, skill_scripts
from kvb_orchestrator.errors import Conflict
from kvb_orchestrator.jobs import UNRUNNABLE, blocked_reasons
MATCH = REPO_ROOT / "skills" / "kvb-match" / "scripts" / "match.py"
CLIENT = HUB / "client"
@@ -391,6 +402,67 @@ class TestCommandCards(MatchCase):
self.assertFalse(fresh["stale"], fresh)
self.assertIn("swapped", next(entry["content"] for entry in fresh["files"] if entry["path"].endswith("body.md")))
def test_a_row_with_an_open_job_or_no_absolute_directory_stays_a_greyed_card_with_its_reason(self):
row = {"title": "true", "workdir": str(self.work), "description": "ship the release notes", "check": "done", "roles": {"Skills": "A", "Operator": "R"}}
register = {f"operator/{slug}": row for slug in ("free", "waits", "runs")}
self.write_council({"rasci.json": {**register, "operator/loose": {**row, "workdir": "relative/dir"}}})
now = time.time()
base = {"command": "true", "directory": str(self.work), "sha256": "0" * 64, "proof": None, "output": "", "finished": None, "dismissed": False, "code": None}
self.httpd.hub.jobs.add({**base, "task": "operator/runs", "status": "running", "created_ts": now - 1800, "started": now - 1800})
self.httpd.hub.jobs.add({**base, "task": "operator/waits", "status": "queued", "created_ts": now - 600, "started": None})
cards = {card["id"].removeprefix("operator:"): card for card in self.cards() if card["kind"] == "command"}
self.assertEqual(sorted(cards), ["operator/free", "operator/loose", "operator/runs", "operator/waits"])
self.assertEqual(cards["operator/free"]["blocked"], "")
self.assertEqual(cards["operator/runs"]["blocked"], "The hub runner runs it for 30 min; its result comes in Waits on Operator.")
self.assertEqual(cards["operator/waits"]["blocked"], "Queued in the hub runner for 10 min behind operator/runs, which runs for 30 min; the runner runs one job at a time.")
self.assertEqual(cards["operator/loose"]["blocked"], UNRUNNABLE)
def test_every_open_row_operator_py_lists_shows_in_match_the_inbox_and_the_stream_with_its_reason(self):
row = {"title": "true", "workdir": str(self.work), "description": "ship the release notes", "check": "done", "roles": {"Skills": "A", "Operator": "R"}}
options = [{"label": "Commit B11", "description": ""}, {"label": "Don't commit", "description": ""}]
register = {f"operator/{slug}": row for slug in ("free", "waits", "runs")}
register |= {"operator/loose": {**row, "workdir": "relative/dir"}, "operator/pick": {**row, "title": "Commit B11?", "check": "decision", "options": options}}
self.write_council({"rasci.json": register})
now = time.time()
base = {"command": "true", "directory": str(self.work), "sha256": "0" * 64, "proof": None, "output": "", "finished": None, "dismissed": False, "code": None}
self.httpd.hub.jobs.add({**base, "task": "operator/runs", "status": "running", "created_ts": now - 1800, "started": now - 1800})
self.httpd.hub.jobs.add({**base, "task": "operator/waits", "status": "queued", "created_ts": now - 600, "started": None})
env = {"PATH": os.environ["PATH"], "HOME": str(self.outside), "AGENTS_COUNCIL_ROOT": str(self.council)}
done = subprocess.run([sys.executable, str(OPERATOR), "list", "--json"], capture_output=True, text=True, timeout=60, check=False, env=env)
self.assertEqual(done.returncode, 0, done.stderr)
listed = {entry["task"] for entry in json.loads(done.stdout)}
self.assertEqual(listed, set(register))
cards = {card["ref"]: card for card in self.cards() if card["kind"] in ("command", "decision")}
status, _, body = self.get("/api/state")
self.assertEqual(status, 200, body)
inbox = {item["id"]: item for item in json.loads(body)["inbox"] if item["kind"] == "operator"}
data = self.events("")
stream = {entry["ref"]["task"]: entry for entry in data["events"] + data.get("entries", []) if entry["kind"] == "operator"}
for area, found in (("match", cards), ("inbox", inbox), ("stream", stream)):
with self.subTest(area=area):
self.assertEqual(set(found), listed)
self.assertTrue(all(entry["waiting"] for entry in stream.values()), stream)
runs, waits = "The hub runner runs it for 30 min; its result comes in Waits on Operator.", "Queued in the hub runner for 10 min behind operator/runs, which runs for 30 min; the runner runs one job at a time."
expected = {"operator/free": "", "operator/pick": "", "operator/runs": runs, "operator/waits": waits, "operator/loose": UNRUNNABLE}
self.assertEqual({task: inbox[task]["blocked"] for task in listed}, expected)
self.assertEqual({task: stream[task]["ref"]["blocked"] for task in listed}, expected)
self.assertEqual({task: cards[task].get("blocked", "") for task in listed}, expected)
self.assertEqual((inbox["operator/runs"]["runnable"], inbox["operator/runs"]["deniable"]), (False, False))
self.assertEqual(json.loads(body)["badges"]["tasks"], 2)
def test_the_blocked_reason_names_the_last_started_running_job_and_none_without_jobs(self):
now = 10_000.0
jobs = [
{"task": "operator/old", "status": "running", "created_ts": 0.0, "started": 60.0},
{"task": "operator/new", "status": "running", "created_ts": 9_000.0, "started": 9_100.0},
{"task": "operator/next", "status": "queued", "created_ts": 9_940.0, "started": None},
{"task": "operator/gone", "status": "done", "created_ts": 0.0, "started": 0.0},
]
reasons = blocked_reasons(jobs, now)
self.assertEqual(sorted(reasons), ["operator/new", "operator/next", "operator/old"])
self.assertEqual(reasons["operator/next"], "Queued in the hub runner for 1 min behind operator/new, which runs for 15 min; the runner runs one job at a time.")
self.assertEqual(blocked_reasons([], now), {})
def test_a_command_card_shows_the_scores_its_command_carries_with_their_emoji_only(self):
self.operator_row("operator/commit", SCORED, str(self.work))
chips = [(chip["id"], chip["value"]) for chip in self.card("operator:operator/commit")["metrics"]]
+111
View File
@@ -0,0 +1,111 @@
from __future__ import annotations
import json
import re
import time
import unittest
from unittest import mock
from hub_support import ASK, HUB, REPO_ROOT
from kvb_orchestrator import scores
from test_hub_match import MatchCase, git, merge_repo, move_head
ORDER = ["fix", "break", "tokens", "velocity", "security", "legal", "architecture", "score"]
FULL = "🎯 Fix: 95 % · 💥 Break: 3 % · 💸 Tokens: 100 % · ⏱️ Velocity: 100 % · 🛡️ Security: 99 · ⚖️ Legal: 98 · 🏛️ Architecture: 97 · 🏆 Score: 96"
OLD = "🎯 Fix: 95 % · 💥 Break: 3 % · 💸 Tokens: 100 % · ⏱️ Velocity: 100 % · 🛡️ Security: 99 · 🏆 Score: 96"
BUSY = ("operator/one", "operator/two", "operator/three")
class TestMergeDiff(MatchCase):
def staged_merge(self) -> tuple[str, str]:
repo, target = merge_repo(self.work)
git(repo, "merge", "--no-commit", "--no-ff", "-q", target)
tree = git(repo, "write-tree").strip()
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": tree}
result = self.tool("review_request", arguments)
self.assertFalse(result["isError"], result)
self.repo = repo
return result["structuredContent"]["id"], tree
def test_a_merge_review_without_a_diff_shows_the_merge_onto_its_first_parent(self):
review, tree = self.staged_merge()
before = self.card(f"review:{review}")
self.assertFalse(before["files"], before)
status, _, body = self.call("GET", "/api/runner/previews", None, self.client())
self.assertEqual(status, 200, body)
self.assertEqual([(row["id"], row["worktree"], row["tree"], row["head"]) for row in json.loads(body)["reviews"]], [(review, str(self.repo), tree, None)])
self.run_runner(register=False)
card = self.card(f"review:{review}")
self.assertEqual([(entry["path"], entry["status"], entry["additions"]) for entry in card["files"]], [("app.py", "M", 1)])
self.assertIn("+added = 2", card["files"][0]["patch"])
self.assertEqual((card["stale"], card["diff_error"]), (False, None))
def test_the_merge_card_turns_stale_once_head_moves(self):
review, _ = self.staged_merge()
self.run_runner(register=False)
taken = self.httpd.hub.merge_previews.get(f"review:{review}")["taken"]
self.run_runner(register=False)
self.assertEqual(self.httpd.hub.merge_previews.get(f"review:{review}")["taken"], taken)
move_head(self.repo)
self.run_runner(register=False)
card = self.card(f"review:{review}")
self.assertEqual((card["stale"], card["stale_reason"]), (True, "HEAD moved since it was added"))
self.assertEqual([entry["path"] for entry in card["files"]], ["app.py"])
def test_a_review_whose_tree_is_missing_shows_the_read_error(self):
repo, _ = merge_repo(self.work)
arguments = {**self.arguments("Merge gone", "", self.page("gone.html", "<!doctype html><title>g</title>")), "repo": str(repo / ".git"), "worktree": str(repo), "branch": "main", "tree": "0" * 40}
review = self.tool("review_request", arguments)["structuredContent"]["id"]
self.run_runner(register=False)
card = self.card(f"review:{review}")
self.assertIsNone(card["files"], card)
self.assertTrue(card["diff_error"], card)
def test_only_the_runner_posts_a_review_preview_and_only_for_a_pending_review(self):
review, _ = self.staged_merge()
shown = {"id": review, "head": "a" * 40, "diff": []}
self.assertEqual(self.post_json("/api/runner/previews", shown, self.guard(self.host))[0], 403)
for bad, code in (({**shown, "id": "f" * 16}, 404), ({**shown, "id": "../x"}, 400), ({**shown, "head": "HEAD"}, 400), ({**shown, "diff": "x"}, 400), ({**shown, "extra": 1}, 400)):
with self.subTest(bad=bad):
self.assertEqual(self.post_json("/api/runner/previews", bad, self.client())[0], code)
self.assertEqual(self.post_json("/api/runner/previews", shown, self.client())[0], 200)
class TestChips(unittest.TestCase):
def labels(self) -> dict:
return scores.score_labels(REPO_ROOT / "skills")
def test_legal_and_architecture_sit_between_security_and_score(self):
self.assertEqual([chip["id"] for chip in scores.metric_chips(FULL, self.labels(), True)], ORDER)
self.assertEqual([(chip["emoji"], chip["value"]) for chip in scores.metric_chips(FULL, self.labels(), True)][5:7], [("⚖️", "98"), ("🏛️", "97")])
def test_a_score_without_them_shows_no_empty_legal_or_architecture_chip(self):
self.assertEqual([chip["id"] for chip in scores.metric_chips(OLD, self.labels(), True)], [key for key in ORDER if key not in ("legal", "architecture")])
class TestStrayText(unittest.TestCase):
def test_no_native_dom_call_of_the_match_view_takes_a_value_that_can_be_null(self):
source = (HUB / "templates" / "page-match.js").read_text(encoding="utf-8")
self.assertEqual(re.findall(r"\.replaceChildren\([^;]*\bpeeks\)", source), [])
self.assertIn('card.reason && card.reason !== "-" ? h("p", {class: "match-reason"}', source)
class TestCount(MatchCase):
def test_the_tasks_badge_counts_exactly_the_open_match_cards(self):
self.claim("s1", "Skills session")
self.write_council({"rasci.json": {task: {"title": f"make {task[9:]}", "workdir": "/repo", "check": "done", "roles": {"Operator": "R"}} for task in BUSY}})
ask = self.create_ask(ASK)
hub = type(self.httpd.hub)
with mock.patch.object(hub, "open_jobs", return_value=set(BUSY)), mock.patch.object(hub, "blocked_rows", return_value=dict.fromkeys(BUSY, "Queued in the hub runner")):
cards = self.cards()
self.assertEqual([card["id"] for card in cards if not card.get("blocked")], [f"ask:{ask}"])
self.assertEqual(sorted(card["id"] for card in cards if card.get("blocked")), sorted(f"operator:{task}" for task in BUSY))
self.assertEqual(self.snapshot()["badges"]["tasks"], 1)
self.assertIn("<title>(1) Agent Orchestrator</title>", self.index())
self.httpd.hub.asks.change(ask, {"expires": time.time() - 1})
self.assertEqual(([card["id"] for card in self.cards() if not card.get("blocked")], self.snapshot()["badges"]["tasks"]), ([], 0))
self.assertIn("<title>Agent Orchestrator</title>", self.index())
if __name__ == "__main__":
unittest.main()
+39 -20
View File
@@ -24,12 +24,13 @@ hub_limits = importlib.import_module("hub_limits")
approval = importlib.import_module("approval")
TEMPLATES = HUB / "templates"
DIFFS = TEMPLATES / "diffs.js"
PAGE_MODULES = ["page-constants.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-diff.js", "page-inbox.js", "page-grant.js", "page-stream.js", "page-screens.js", "page-keyboard.js"]
PAGE_MODULES = ["page-constants.js", "answers.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-diff.js", "page-inbox.js", "page-grant.js", "page-stream.js", "page-screens.js", "page-keyboard.js"]
SECRET = 'api_key = "plain-example-words"'
ARMOURED = "before\n-----BEGIN EXAMPLE-----\nplain words only\n-----END EXAMPLE-----\nafter\n"
WITHHELD = "content withheld"
MASKED = "masked"
MASK = "••••"
LINE_NOTES_GO = "Your line comments go to the requesting agent with Deny as a call, or after Grant as a post."
APP_CLEAR = f"@@ -1,2 +1,4 @@\n keep = 1\n-old = 2\n+new = 3\n+{SECRET}\n+print(1)"
APP_SHOWN = f"@@ -1,2 +1,4 @@\n keep = 1\n-old = 2\n+new = 3\n+{MASK}\n+print(1)"
ALLOW = {"behavior": "allow"}
@@ -56,8 +57,6 @@ console.log(JSON.stringify({
collapsed: [[400, 0], [200, 201], [0, 401]].map(([additions, deletions]) => D.collapsed({additions, deletions})),
span: [D.span([7, 3, 5]), D.span([]), D.span([0, 2])],
lineSpan: [D.lineSpan("make\\n deploy\\n now", "deploy\\n now"), D.lineSpan("one line", "nope"), D.lineSpan("a\\nb", "")],
feedback: D.feedback("review:0123456789abcdef", "src/app.py", 4, 5, " -old\\n+new ", " use the helper "),
quoted: [D.quoted("x".repeat(D.QUOTE_LIMIT + 5)).length, D.QUOTE_LIMIT],
picked: D.feedbackOf([{text: "Feedback on review:abc a:1-1: \\"q\\" t"}, {text: "Feedback on review:abcd a:1-1"}, {text: "hello"}], "review:abc").length,
}));
"""
@@ -101,7 +100,7 @@ const document = {
};
document.activeElement = document.body;
document.getElementById("emoji-bases").textContent = "[]";
const all =(node) => (typeof node === "string" ? [] : [node, ...node.children.flatMap(all)]);
const all =(node) => (node === null || typeof node === "string" ? [] : [node, ...node.children.flatMap(all)]);
const classes = (node) => String(node.className || node.attrs.class || "").split(" ").filter(Boolean);
const labels = (node) => all(node).filter((el) => el.tag === "button").map((el) => el.getAttribute("aria-label") || el.textContent);
const calls = {proofs: [], posts: [], sheets: [], radio: [], signs: []};
@@ -129,6 +128,7 @@ const context = {
load: async () => {}, toast: () => {}, fail: () => [], undoToast: () => {},
jobOpen: () => false, dismissJob: () => {}, consoleOf: () => null, settleConsoles: () => {}, repaintConsoles: () => {},
withoutOutput: (item) => item, ruleRequestBody: () => null, acceptRule: () => null, reviewSheet: () => {}, openAgent: () => {}, confirmAct: () => {}, measure: () => {},
presetChips: () => null, savedComments: () => [], rememberComment: () => {}, repaintReview: () => {},
openSheet: (title, body) => calls.sheets.push({title, body}), closeSheet: () => {}, emptyState: () => new El("div"), onLocalhost: () => true, localLink: () => null,
focusSub: () => {}, openPalette: () => {}, closePalette: () => {}, skyLook: () => {}, popupDialog: () => ({open: false}), closePopup: () => {}, closeMenus: () => {}, helpSheet: () => {},
space: {look: false}, stream: {events: [], entries: [], dom: null}, filter: {}, inboxDom: null, inboxSig: "", reviewDom: null, graphDom: null, tree: {}, taskView: {}, g3: {},
@@ -189,13 +189,27 @@ const sheet = calls.sheets.pop();
const confirm = all({children: sheet.body}).filter((el) => el.tag === "button").pop();
results.bulk = {label: confirm.textContent, shown: all({children: sheet.body}).filter((el) => el.tag === "li").length};
confirm.click();
feedbackSheet({ref: "review:0123456789abcdef", to: "Skills", path: "src/app.py", from: 2, until: 4, quote: "-old\\n+new"});
const form = calls.sheets.pop();
const area = all({children: form.body}).find((el) => el.tag === "textarea");
area.value = " call the helper instead ";
const send = all({children: form.body}).filter((el) => el.tag === "button").pop();
results.feedback = {title: form.title, send: [send.getAttribute("aria-label"), send.getAttribute("title")]};
send.click();
const comment = (from, until, words) => {
markLines({ref: "review:0123456789abcdef", to: "Skills", path: "src/app.py", from, until, anchor: null, inline: false});
const form = calls.sheets.pop();
all({children: form.body}).find((el) => el.tag === "textarea").value = words;
const save = all({children: form.body}).filter((el) => el.tag === "button").pop();
save.click();
return {title: form.title, save: [save.getAttribute("aria-label"), save.getAttribute("title")]};
};
setTimeout(() => {
results.feedback = comment(2, 3, " call the helper instead ");
comment(1, 1, " ");
comment(3, 3, "rename it");
results.notes = lineNotes("review:0123456789abcdef");
const marked = inboxItem(review, 1);
results.marked = {
rows: all(marked).filter((el) => el.tag === "tr" && /mark/.test(classes(el).join(" "))).map((row) => [classes(row).join(" "), row.dataset.line]),
notes: all(marked).filter((el) => classes(el).includes("match-mark")).map((el) => el.textContent),
list: all(marked).filter((el) => classes(el).includes("line-mark")).map((el) => el.textContent),
};
approveOne(review);
}, 0);
let prevented = false;
feedbackKey = () => true;
keyboard({key: "f", target: document.body, altKey: false, ctrlKey: false, metaKey: false, isComposing: false, preventDefault: () => { prevented = true; }});
@@ -204,6 +218,7 @@ setTimeout(() => {
results.proofs = calls.proofs.map((call) => call.entries.map((entry) => [entry.kind, entry.verb, entry.label]));
results.posts = calls.posts.map((call) => [call.path, call.body.items.length, call.body.proof !== null]);
results.radio = calls.radio;
results.cleared = lineNotes("review:0123456789abcdef");
drawInbox = () => {};
drawStream = () => {};
const secret = {...review, id: "3123456789abcdef", diff: 2};
@@ -304,9 +319,7 @@ class TestDiffsModule(unittest.TestCase):
self.assertEqual(self.data["span"], [[3, 7], None, [2, 2]])
self.assertEqual(self.data["lineSpan"], [[2, 3], [1, 1], [1, 2]])
def test_the_feedback_text_follows_the_contract(self):
self.assertEqual(self.data["feedback"], 'Feedback on review:0123456789abcdef src/app.py:4-5: "-old\n+new" use the helper')
self.assertEqual(self.data["quoted"], [2001, 2000])
def test_earlier_feedback_posts_are_found_by_their_card(self):
self.assertEqual(self.data["picked"], 1)
@@ -372,13 +385,19 @@ class TestOperatorPage(unittest.TestCase):
def test_the_bulk_bar_counts_and_grants_asks_reviews_operator_commands_and_choices_with_one_signature(self):
self.assertEqual(self.data["bulk"], {"label": "Grant 4", "shown": 4})
self.assertEqual(self.data["proofs"], [[["operator", "approve", ""], ["review", "approve", ""], ["ask", "approve", ""], ["decision", "approve", "Now"]]])
self.assertEqual(self.data["posts"], [["/api/inbox/approve", 4, True]])
self.assertEqual(self.data["proofs"], [[["operator", "approve", ""], ["review", "approve", ""], ["ask", "approve", ""], ["decision", "approve", "Now"]], [["review", "approve", ""]]])
self.assertEqual(self.data["posts"], [["/api/inbox/approve", 4, True], ["/api/inbox/approve", 1, True]])
def test_feedback_is_one_signed_post_to_the_requesting_agent_in_the_contract_format_and_the_key_f_opens_it(self):
self.assertEqual(self.data["feedback"]["title"], "Feedback")
self.assertEqual(self.data["feedback"]["send"], ["Send feedback", "Send feedback: a post to Skills"])
self.assertEqual(self.data["radio"], [{"to": "Skills", "text": 'Feedback on review:0123456789abcdef src/app.py:2-4: "-old\n+new" call the helper instead', "upload": "", "cls": "post", "voice": ""}])
def test_line_comments_collect_on_their_card_and_go_as_one_post_after_its_grant(self):
self.assertEqual(self.data["feedback"], {"title": "Comment", "save": ["Save comment", LINE_NOTES_GO]})
self.assertEqual(self.data["notes"], "src/app.py:2-3: call the helper instead;\nsrc/app.py:3: rename it")
self.assertEqual(self.data["marked"], {
"rows": [["del marked", "2"], ["add marked", "2"], ["add marked", "3"], ["match-mark", "3"], ["match-mark", "3"]],
"notes": ["call the helper instead", "rename it"],
"list": ["src/app.py:2-3call the helper instead", "src/app.py:3rename it"],
})
self.assertEqual(self.data["radio"], [{"to": "Skills", "text": f"Granted: feat: x. Notes:\n{self.data['notes']}", "upload": "", "cls": "post", "voice": ""}])
self.assertEqual(self.data["cleared"], "")
self.assertTrue(self.data["key"])
+42 -17
View File
@@ -91,8 +91,8 @@ const fs = require("fs");
const vm = require("vm");
const Resources = require(process.argv[1]);
const Plan = require(process.argv[2]);
const code = [process.argv[3], process.argv[4], process.argv[5]].map((path) => fs.readFileSync(path, "utf8")).join("\\n");
const T = Number(process.argv[6]);
const code = [process.argv[3], process.argv[4], process.argv[5], process.argv[6]].map((path) => fs.readFileSync(path, "utf8")).join("\\n");
const T = Number(process.argv[7]);
@FIXTURE@
const make = (tag, attrs, children) => {
const node = {tag, attrs: {}, children: [], textContent: "", isConnected: true, listeners: {},
@@ -115,7 +115,7 @@ const make = (tag, attrs, children) => {
};
const h = (tag, attrs, ...children) => make(tag, attrs, children);
const icon = (name) => make("svg", {class: "bi", "data-icon": name}, []);
const view = {resources: {hidden: [], tokens: "interval", combined: false, combinedHidden: []}, burn: {overlays: []}, home: {pins: []}};
const view = {resources: {hidden: [], tokens: "interval", panels: ["hardware", "tokens", "accounts"], combinedHidden: []}, burn: {overlays: []}, home: {pins: []}};
const served = JSON.parse(JSON.stringify(view));
const fetched = [];
const sheets = [];
@@ -129,7 +129,8 @@ const context = {
Resources, Plan, h, s: h, icon, DAY: 86400, ui: {preset: 86400, from: null, to: null, asOf: null, offline: false},
state: {tasks, now: T + 6000}, settings: {estimation: "none"}, setTimeout, clearTimeout,
named: (label, hint) => ({title: hint || label, "aria-label": label}),
iconBtn: (name, label, cls, run, hint) => make("button", {title: hint, "aria-label": label}, [icon(name)]),
iconBtn: (name, label, cls, run, hint) => make("button", {title: hint, "aria-label": label}, [icon(name)]), caret: () => icon("bi-caret-down-fill"),
boxHead: (label, cls, ...children) => make("div", {class: "box-head", "aria-label": label}, children),
fixed: (value) => value.toFixed(1), dash: (value) => (value === null ? "–" : value), absolute: {format: () => "d"}, clock: {format: () => "c"}, stampOf: (t) => new Date(t * 1000),
revealed: (text) => String(text), counter: (value) => make("span", {class: "count"}, [String(value)]), openSheet: (title, body, wide) => sheets.push({title, body, wide}),
window: {setTimeout: (run) => run(), setInterval: () => 1, addEventListener: () => null},
@@ -139,6 +140,10 @@ const context = {
},
windowQuery: () => "from=1", nowSeconds: () => 0,
fetch: async (url, options) => {
if (url === "/api/accounts") {
fetched.push(url);
return {ok: true, json: async () => ({accounts: [], active: null, usage: {}})};
}
if (url !== "/api/view") {
fetched.push(url);
return {ok: true, json: async () => ({since: T - 600, until: T + 6000, samples, tokens})};
@@ -192,10 +197,17 @@ const read = () => {
right: all.filter((node) => node.attrs["data-axis"] === "right").map((node) => node.children.join("")),
chips: all.filter((node) => has(node, "legend-chip")).map((node) => [node.attrs["data-chip"], node.attrs["data-path"], node.attrs["aria-pressed"], node.textContent]),
switches: all.filter((node) => has(node, "res-switch")).map((node) => [node.attrs["data-switch"], node.attrs["aria-pressed"]]),
picks: all.filter((node) => node.attrs["data-pick"]).map((node) => [node.attrs["data-pick"], Boolean(node.checked), Boolean(node.disabled)]),
accounts: textOf(all.find((node) => has(node, "acc-body"))),
titles: all.filter((node) => has(node, "res-title")).map((node) => [node.attrs.title, node.attrs["aria-label"], node.children[0].attrs["data-icon"]]),
};
};
const press = (selector) => walk(context.screen, []).find(selector).listeners.click();
const pick = (kind, on) => {
const box = walk(context.screen, []).find((node) => node.attrs["data-pick"] === kind);
box.checked = on;
box.listeners.change();
};
const textOf = (node) => node.children.map((child) => (typeof child === "object" ? textOf(child) : String(child))).join("");
const sheetOf = ({title, body, wide}) => {
const nodes = body.flatMap((node) => walk(node, []));
@@ -218,14 +230,18 @@ const sheetOf = ({title, body, wide}) => {
const hidden = read();
press((node) => node.attrs["data-switch"] === "tokens");
const accumulated = read();
press((node) => node.attrs["data-switch"] === "combined");
pick("combined", true);
pick("hardware", false);
pick("tokens", false);
const combined = read();
press((node) => node.attrs["data-chip"] === "burn:scope" && node.attrs["data-path"] === "resources.combinedHidden");
press((node) => node.attrs["data-chip"] === "util:0000_3a_01_3a_00.0" && node.attrs["data-path"] === "resources.combinedHidden");
const deselected = read();
pick("accounts", false);
const last = read();
await new Promise((resolve) => setTimeout(resolve, 400));
await settle();
console.log(JSON.stringify({fetched, normal, hidden, accumulated, combined, deselected, stored: context.store.get("resources")}));
console.log(JSON.stringify({fetched, normal, hidden, accumulated, combined, deselected, last, stored: context.store.get("resources")}));
})();
""".replace("@FIXTURE@", FIXTURE)
@@ -327,14 +343,18 @@ def chips(entries: list[list[str]], path: str, hidden: set[str]) -> list[list[st
class TestResourcesPage(unittest.TestCase):
@classmethod
def setUpClass(cls):
sources = [str(HUB / "templates" / name) for name in ("view-store.js", "legend-chips.js", "page-resources.js")]
done = subprocess.run(["node", "-e", PAGE_PROBE, str(MODULE), str(PLAN), *sources, str(T)], capture_output=True, text=True, timeout=60, check=True)
sources = [str(HUB / "templates" / name) for name in ("view-store.js", "legend-chips.js", "page-resources.js", "page-accounts.js")]
done = subprocess.run(["node", "-e", PAGE_PROBE, str(MODULE), str(PLAN), *sources, str(T)], capture_output=True, text=True, timeout=60, check=False)
if done.returncode != 0:
raise AssertionError(done.stderr[-2000:])
cls.found = json.loads(done.stdout)
def test_normal_mode_draws_exactly_a_hardware_and_a_tokens_chart_on_one_time_axis(self):
found = self.found["normal"]
self.assertEqual(found["count"], "8")
self.assertEqual(found["panels"], [["resources-hardware", False], ["resources-tokens", False], ["resources-combined", True]])
self.assertEqual(found["panels"], [["resources-hardware", False], ["resources-tokens", False], ["resources-combined", True], ["resources-accounts", False]])
self.assertEqual(found["picks"], [["hardware", True, False], ["tokens", True, False], ["combined", False, False], ["accounts", True, False]])
self.assertIn("No account yet", found["accounts"])
axis = [str(T - 600), str(T + 6000)]
self.assertEqual(found["charts"], [["hardware", *axis], ["tokens", *axis]])
self.assertEqual(found["bands"], [["idle", "saturated"], []])
@@ -344,8 +364,8 @@ class TestResourcesPage(unittest.TestCase):
self.assertEqual((found["unknown"], found["words"]), ([[T + 300, T + 360]], ["0000:01:00.0 unknown: no reading"]))
self.assertEqual(found["bars"], [["Stage", T, False], ["Skills", T, False], ["Stage", T + 3600, False]])
self.assertEqual(found["chips"], chips(HARDWARE_CHIPS + AGENT_CHIPS, "resources.hidden", set()))
self.assertEqual(found["switches"], [["tokens", "false"], ["combined", "false"]])
names = [("Hardware: disks, CPU, RAM, swap, GPU and VRAM", "bi-cpu"), ("Tokens per agent", "bi-coin"), ("Hardware, tokens and burnup", "bi-layers")]
self.assertEqual(found["switches"], [["tokens", "false"]])
names = [("Hardware: disks, CPU, RAM, swap, GPU and VRAM", "bi-cpu"), ("Tokens per agent", "bi-coin"), ("Hardware, tokens and burnup", "bi-layers"), ("Accounts", "bi-person-badge")]
self.assertEqual(found["titles"], [[name, name, icon] for name, icon in names])
def test_blocked_and_hung_marks_sit_in_lanes_of_their_own_and_name_head_wait_reason_and_ids(self):
@@ -376,11 +396,11 @@ class TestResourcesPage(unittest.TestCase):
def test_the_accumulated_switch_draws_running_sums_of_the_shown_agents_instead_of_bars(self):
found = self.found["accumulated"]
self.assertEqual((found["bars"], found["sums"]), ([], [["Skills", [0, 375]]]))
self.assertEqual(found["switches"], [["tokens", "true"], ["combined", "false"]])
self.assertEqual(found["switches"], [["tokens", "true"]])
def test_the_combined_switch_replaces_both_charts_with_one_holding_every_series_switched_on(self):
def test_the_panels_menu_shows_the_combined_chart_with_every_series_switched_on_instead_of_both(self):
found = self.found["combined"]
self.assertEqual(found["panels"], [["resources-hardware", True], ["resources-tokens", True], ["resources-combined", False]])
self.assertEqual(found["panels"], [["resources-hardware", True], ["resources-tokens", True], ["resources-combined", False], ["resources-accounts", False]])
self.assertEqual(found["charts"], [["combined", str(T - 600), str(T + 6000)]])
self.assertEqual(found["lines"], LINES)
self.assertEqual(found["sums"], [["Stage", [0, 10, 510]], ["Skills", [0, 375, 375]]])
@@ -390,16 +410,21 @@ class TestResourcesPage(unittest.TestCase):
self.assertAlmostEqual(done_last, 200 / 3)
burn = [["burn:done", "Done 67 %"], ["burn:scope", "Scope 100 %"]]
self.assertEqual(found["chips"], chips(HARDWARE_CHIPS + AGENT_CHIPS + burn, "resources.combinedHidden", set()))
self.assertEqual(found["switches"], [["tokens", "true"], ["combined", "true"]])
self.assertEqual(found["picks"], [["hardware", False, False], ["tokens", False, False], ["combined", True, False], ["accounts", True, False]])
def test_the_last_checked_panel_cannot_be_switched_off(self):
found = self.found["last"]
self.assertEqual(found["panels"], [["resources-hardware", True], ["resources-tokens", True], ["resources-combined", False], ["resources-accounts", True]])
self.assertEqual(found["picks"], [["hardware", False, False], ["tokens", False, False], ["combined", True, True], ["accounts", False, False]])
def test_each_combined_series_is_deselectable_and_every_switch_is_stored_in_one_patch(self):
found = self.found["deselected"]
self.assertEqual([series for series, _, _ in found["burn"]], ["done"])
self.assertEqual(found["lines"], [line for line in LINES if line != "0000:01:00.0|util"])
stored = {"hidden": ["host:CPU", "agent:Stage"], "tokens": "accumulated", "combined": True, "combinedHidden": ["burn:scope", f"util:{GPU_ID}"]}
stored = {"hidden": ["host:CPU", "agent:Stage"], "tokens": "accumulated", "panels": ["combined"], "combinedHidden": ["burn:scope", f"util:{GPU_ID}"]}
self.assertEqual(self.found["stored"], stored)
changes = {f"resources.{key}": value for key, value in stored.items()}
self.assertEqual(self.found["fetched"], ["/api/resources?from=1", ["PATCH", "/api/view", changes]])
self.assertEqual(self.found["fetched"], ["/api/resources?from=1", "/api/accounts", ["PATCH", "/api/view", changes]])
AXIS_PROBE = """
+40
View File
@@ -0,0 +1,40 @@
from __future__ import annotations
import json
import subprocess
import unittest
import hub_support
MODULE = hub_support.HUB / "templates" / "settings-files.js"
LISTED = r"""
const S = require(process.argv[1]);
const files = JSON.parse(process.argv[2]);
const paths = (result) => ({shown: result.shown.map((file) => file.path), missing: result.missing});
console.log(JSON.stringify({folded: paths(S.listed(files, false)), open: paths(S.listed(files, true))}));
"""
def files() -> list[dict]:
present = [{"path": f"/p/{index:02d}/.claude/settings.json", "folder": True, "error": ""} for index in range(10)]
present[7]["error"] = "unreadable: ValueError"
present[3]["error"] = "a link or no directory on the path: Not a directory"
absent = [{"path": f"/a/{index:02d}/.claude/settings.json", "folder": False, "error": "no directory: create it first"} for index in range(30)]
older = {"path": "/o/.claude/settings.json", "error": ""}
return [*absent[15:], present[5], *present[:5], *absent[:15], older, *present[6:]]
class TestSettingsFiles(unittest.TestCase):
def test_files_without_their_folder_fold_away_and_error_rows_lead_then_paths_in_order(self):
done = subprocess.run(["node", "-e", LISTED, str(MODULE), json.dumps(files())], capture_output=True, text=True, timeout=60, check=False)
self.assertEqual(done.returncode, 0, done.stderr)
found = json.loads(done.stdout)
errors = ["/p/03/.claude/settings.json", "/p/07/.claude/settings.json"]
rest = [f"/p/{index:02d}/.claude/settings.json" for index in range(10) if index not in (3, 7)]
self.assertEqual(found["folded"], {"shown": [*errors, "/o/.claude/settings.json", *rest], "missing": 30})
self.assertEqual(found["open"]["shown"], [*errors, "/o/.claude/settings.json", *rest, *[f"/a/{index:02d}/.claude/settings.json" for index in range(30)]])
self.assertEqual(found["open"]["missing"], 30)
if __name__ == "__main__":
unittest.main()
+145
View File
@@ -0,0 +1,145 @@
from __future__ import annotations
import json
import re
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
import hub_support
import skills_index
from hub_case import HubCase
from kvb_orchestrator.skillindex import SKILLS_INDEX, served
HUB = hub_support.HUB
TEMPLATES = HUB / "templates"
SCRIPT = HUB / "client" / "skills_index.py"
TREE_UNIT = HUB / "systemd" / "kvb-orchestrator-tree.service"
FIELDS = {
"page-composer.js": r'h\("textarea", \{"aria-label": "Message", [^}]*"data-skills": ""',
"page-agent.js": r'h\("textarea", \{"aria-label": `Message to \$\{name\}`, placeholder: `Message to \$\{name\} …`, "data-skills": ""',
"page-match.js": r'"aria-label": "Comment", [^}]*"data-skills": card\.repo \|\| ""',
"page-dialog.js": r'"aria-label": `Other answer to \$\{item\.id\}`[^}]*"data-skills": item\.repo \|\| ""',
"page-deny.js": r'placeholder: "e\.g\. make the gate green first", "data-skills": item\.repo \|\| ""',
"page-inbox.js": r'placeholder: "e\.g\. make the gate green first", "data-skills": ""',
"page-diff.js": r'"aria-label": "Feedback", title: "Feedback", "data-skills": ""',
}
FEEDBACK = r'class: "field match-feedback", [^}]*"data-skills": card\.repo \|\| ""'
RANK = r"""
const fs = require("fs");
const vm = require("vm");
const context = {JSON, Math, Number, String, Array, Object, RegExp, Set, Map, Boolean, WeakSet, console};
const source = fs.readFileSync(process.argv[1], "utf8");
const skills = [
{name: "kvb-org-robot", description: "", source: "~/.claude/skills"},
{name: "kvb-org-radio", description: "", source: "~/.claude/skills"},
{name: "kvb-org-radio", description: "", source: "~/.agents/skills"},
{name: "kvb-org-rasci", description: "", source: "~/.claude/skills"},
{name: "i8-alpha", description: "", source: "~/.claude/skills"},
{name: "i8-zeta", description: "", source: "/repo"},
{name: "make-kvb-org-r", description: "", source: "~/.claude/skills"},
];
const probe = `JSON.stringify({
radio: slashRank(${JSON.stringify(skills)}, "kvb-org-r", "").map((skill) => skill.name),
core: slashRank(${JSON.stringify(skills)}, "i8-", "/repo").map((skill) => skill.name),
plain: slashRank(${JSON.stringify(skills)}, "i8-", "").map((skill) => skill.name),
tokens: [slashToken("/kvb", 4), slashToken("say /kvb-org", 12), slashToken("a/b", 3), slashToken("path/to", 7), slashToken("x /", 3)],
inserted: slashInsert("ask /kvb-org-r now", {start: 4, prefix: "kvb-org-r"}, 14, "kvb-org-radio"),
})`;
console.log(vm.runInNewContext(`${source}\n${probe}`, context));
"""
def skill(root: Path, folder: str, text: str | None) -> None:
path = root / folder
path.mkdir(parents=True)
if text is not None:
(path / "SKILL.md").write_text(text, encoding="utf-8")
class TestIndex(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.root = Path(folder.name)
self.home, self.repo = self.root / "home", self.root / "repo"
skill(self.home / ".claude/skills", "kvb-org-radio", "---\nname: kvb-org-radio\ndescription: Default channel to other agents.\n---\nbody\n")
skill(self.home / ".agents/skills", "kvb-org-radio", "---\nname: kvb-org-radio\ndescription: \"Agents copy\"\n---\n")
skill(self.home / ".agents/skills", "folded", "---\nname: folded\ndescription: >\n Two lines\n joined.\n---\n")
skill(self.home / ".claude/skills", "no-file", None)
skill(self.home / ".claude/skills", "bare", "---\nname: bare\n---\n")
skill(self.repo / ".claude/skills", "i8-commit", "---\nname: i8-commit\ndescription: Commit the staged changes.\n---\n")
skill(self.repo / ".claude/skills", "open", "---\nname: open\ndescription: never closed\n")
self.tree = self.root / "branch-tree.json"
self.tree.write_text(json.dumps({"repos": [{"path": str(self.repo)}, {"path": "relative"}]}), encoding="utf-8")
def test_the_index_lists_every_source_once_per_name_and_source_without_paths_or_bodies(self):
output = self.root / SKILLS_INDEX
done = subprocess.run([sys.executable, str(SCRIPT), "--home", str(self.home), "--tree", str(self.tree), "--output", str(output)], capture_output=True, text=True, timeout=60, check=False)
self.assertEqual(done.returncode, 0, done.stderr)
rows = json.loads(output.read_text(encoding="utf-8"))["skills"]
self.assertEqual([(row["name"], row["source"], row["description"]) for row in rows], [
("bare", "~/.claude/skills", ""),
("folded", "~/.agents/skills", "Two lines joined."),
("i8-commit", str(self.repo), "Commit the staged changes."),
("kvb-org-radio", "~/.agents/skills", "Agents copy"),
("kvb-org-radio", "~/.claude/skills", "Default channel to other agents."),
("open", str(self.repo), ""),
])
self.assertEqual({key for row in rows for key in row}, {"name", "description", "source"})
def test_the_front_matter_parser_needs_an_opening_and_a_closing_rule(self):
self.assertEqual(skills_index.front_matter("name: x\n"), {})
self.assertEqual(skills_index.front_matter("---\nname: x\n"), {})
self.assertEqual(skills_index.front_matter("---\nname: x\ndescription: 'quoted'\n---\n"), {"name": "x", "description": "quoted"})
def test_the_tree_timer_writes_the_index_next_to_the_tree(self):
starts = [line.split("=", 1)[1] for line in TREE_UNIT.read_text(encoding="utf-8").splitlines() if line.startswith("ExecStart=")]
self.assertEqual(starts[2], "/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/skills_index.py --home %h --tree %h/.local/state/pkgmgr/tree/branch-tree.json --output %h/.local/state/pkgmgr/tree/skills-index.json")
class TestServed(unittest.TestCase):
def test_the_hub_keeps_valid_rows_only_sorted_and_without_extra_keys(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
file = Path(folder.name) / SKILLS_INDEX
self.assertEqual(served(file), {"skills": []})
rows = [{"name": "zeta", "description": "z", "source": "~/.claude/skills", "path": "/home/x/SKILL.md"}, {"name": "has space", "description": "", "source": "x"}, {"name": "alpha", "description": 3, "source": "x"}, {"name": "alpha", "description": "a", "source": "~/.claude/skills"}, "row"]
file.write_text(json.dumps({"skills": rows}), encoding="utf-8")
self.assertEqual(served(file), {"skills": [{"name": "alpha", "description": "a", "source": "~/.claude/skills"}, {"name": "zeta", "description": "z", "source": "~/.claude/skills"}]})
class TestSuggestions(unittest.TestCase):
def test_rank_token_and_insert(self):
done = subprocess.run(["node", "-e", RANK, str(TEMPLATES / "page-slash.js")], capture_output=True, text=True, timeout=60, check=False)
self.assertEqual(done.returncode, 0, done.stderr)
out = json.loads(done.stdout)
self.assertEqual(out["radio"], ["kvb-org-radio", "kvb-org-rasci", "kvb-org-robot", "make-kvb-org-r"])
self.assertEqual((out["core"], out["plain"]), (["i8-zeta", "i8-alpha"], ["i8-alpha", "i8-zeta"]))
self.assertEqual(out["tokens"], [{"start": 0, "prefix": "kvb"}, {"start": 4, "prefix": "kvb-org"}, None, None, {"start": 2, "prefix": ""}])
self.assertEqual(out["inserted"], {"value": "ask /kvb-org-radio now", "caret": 19})
def test_every_field_whose_text_reaches_an_agent_carries_the_marker(self):
for name, pattern in FIELDS.items():
with self.subTest(file=name):
self.assertRegex((TEMPLATES / name).read_text(encoding="utf-8"), pattern)
self.assertRegex((TEMPLATES / "page-match.js").read_text(encoding="utf-8"), FEEDBACK)
self.assertIn('const SLASH_FIELDS = "textarea[data-skills], input[data-skills]";', (TEMPLATES / "page-slash.js").read_text(encoding="utf-8"))
self.assertIn("slashWatch();", (TEMPLATES / "page-boot.js").read_text(encoding="utf-8"))
self.assertEqual(re.findall(r'\{% include "page-(?:mic|slash)\.js" %\}', (TEMPLATES / "index.html.j2").read_text(encoding="utf-8")), ['{% include "page-mic.js" %}', '{% include "page-slash.js" %}'])
class TestSkillsRoute(HubCase):
def test_api_skills_serves_the_index_and_follows_the_next_timer_run(self):
index = self.tree_file.with_name(SKILLS_INDEX)
self.assertEqual(json.loads(self.get("/api/skills")[2]), {"skills": []})
index.write_text(json.dumps({"written": 1, "skills": [{"name": "kvb-org-radio", "description": "Radio", "source": "~/.claude/skills"}]}), encoding="utf-8")
self.assertEqual(json.loads(self.get("/api/skills")[2])["skills"], [{"name": "kvb-org-radio", "description": "Radio", "source": "~/.claude/skills"}])
index.write_text(json.dumps({"written": 2, "skills": [{"name": "new-skill", "description": "", "source": "~/.agents/skills"}, {"name": "kvb-org-radio", "description": "Radio", "source": "~/.claude/skills"}]}), encoding="utf-8")
self.assertEqual([row["name"] for row in json.loads(self.get("/api/skills")[2])["skills"]], ["kvb-org-radio", "new-skill"])
if __name__ == "__main__":
unittest.main()
+84
View File
@@ -0,0 +1,84 @@
from __future__ import annotations
import json
import re
import subprocess
import unittest
from hub_support import HUB
TEMPLATES = HUB / "templates"
MODULES = ["page-constants.js", "page-reveal.js", "page-dom.js", "page-board.js", "page-composer.js"]
PROBE = r"""
const fs = require("fs");
const vm = require("vm");
const [dir, names] = [process.argv[1], JSON.parse(process.argv[2])];
class El {
constructor(tag) { Object.assign(this, {tag, children: [], attrs: {}, dataset: {}, style: {}}); }
setAttribute(key, value) { this.attrs[key] = String(value); }
getAttribute(key) { return Object.hasOwn(this.attrs, key) ? this.attrs[key] : null; }
append(...nodes) { this.children.push(...nodes); }
replaceChildren(...nodes) { this.children = nodes; }
addEventListener() {}
}
const document = {
currentScript: null, body: new El("body"),
getElementById: () => Object.assign(new El("div"), {textContent: "[]"}),
createElement: (tag) => new El(tag), createElementNS: (ns, tag) => new El(tag),
};
const context = {
console, document, JSON, Math, Date, Intl, Promise, Set, Map, Number, String, Array, Object, RegExp, Boolean, Error,
El, Node: El, Element: El, HTMLElement: El,
window: {location: {hash: ""}, setTimeout: () => 0, matchMedia: () => ({matches: false})},
state: {inbox: [], radio: [], silence: null}, ui: {}, settings: {},
};
const source = names.map((name) => fs.readFileSync(`${dir}/${name}`, "utf8")).join("\n");
const probe = `
const toggle = new El("button");
state.silence = null;
drawMayday(toggle);
const idle = [toggle.attrs["aria-pressed"], toggle.children[1], toggle.title];
state.silence = {since: 1, by: "Docs", text: "disk full"};
drawMayday(toggle);
const active = [toggle.attrs["aria-pressed"], toggle.children[1], toggle.title];
JSON.stringify({idle, active, channels: CHANNELS.map(([id]) => id), titled: CHANNELS.every(([id]) => typeof CHANNEL_HINTS[id] === "string" && CHANNEL_HINTS[id].length > 0)});
`;
console.log(vm.runInNewContext(`${source}\n${probe}`, context));
"""
class TestSpeakCard(unittest.TestCase):
def probe(self) -> dict:
done = subprocess.run(["node", "-e", PROBE, str(TEMPLATES), json.dumps(MODULES)], capture_output=True, text=True, timeout=60, check=False)
self.assertEqual(done.returncode, 0, done.stderr)
return json.loads(done.stdout)
def test_the_toggle_reads_mayday_until_one_holds_the_radio_silent_then_cancel_mayday(self):
out = self.probe()
self.assertEqual(out["idle"][:2], ["false", "MAYDAY"])
self.assertTrue(out["idle"][2].startswith("MAYDAY: "), out)
self.assertEqual(out["active"], ["true", "Cancel mayday", "Cancel mayday: lift the radio silence so the agents write again; your passkey signs it"])
def test_the_channel_select_holds_no_mayday_and_every_option_has_a_title(self):
out = self.probe()
self.assertEqual(out["channels"], ["post", "call", "newsletter", "broadcast", "pan-pan", "security"])
self.assertTrue(out["titled"], out)
def test_the_card_has_no_hint_sentence_and_no_browser_confirm(self):
composer = (TEMPLATES / "page-composer.js").read_text(encoding="utf-8")
self.assertNotIn("window.confirm", composer)
self.assertNotIn("Your passkey signs every message", composer)
self.assertNotIn("composer-hint", composer)
self.assertRegex(composer, r"status, h\(\"div\", \{class: \"ptt-split\".*\), mayday\)\);")
def test_the_card_is_one_rounded_surface(self):
css = (TEMPLATES / "style-ui.css").read_text(encoding="utf-8")
self.assertRegex(css, r"\.radio-card\.radio-speak \{ border-radius: 14px; \}")
self.assertRegex(css, r"\.composer-grid \{[^}]*border-radius: 10px;")
self.assertRegex(css, r"\.composer textarea \{[^}]*border-radius: 10px;")
self.assertNotIn(".radio-cancel", css)
self.assertIsNone(re.search(r'class: "[^"]*\bcard\b', (TEMPLATES / "page-composer.js").read_text(encoding="utf-8")))
if __name__ == "__main__":
unittest.main()
+2 -3
View File
@@ -26,11 +26,10 @@ class TestHubSurface(HubCase):
def test_badges_count_waiting_operator_tasks_on_tasks_active_agents_and_open_runner_jobs(self):
now = 1000.0
inbox = [{"until": None, "settled": False}, {"until": None, "settled": False}, {"until": now + 60, "settled": False}, {"until": None, "settled": True}]
claims = [{"agent": "A", "beat": now - 10}, {"agent": "A", "beat": now - 20}, {"agent": "B", "beat": now - 900}, {"agent": "C", "beat": now - 901}, {"agent": "D", "beat": None}]
jobs = [{"status": "queued"}, {"status": "running"}, {"status": "done"}, {"status": "failed"}]
self.assertEqual(view.badges(inbox, claims, jobs, now), {"tasks": 2, "agents": 2, "artifacts": 2})
self.assertEqual(view.badges([], [], [], now), {"tasks": 0, "agents": 0, "artifacts": 0})
self.assertEqual(view.badges(2, claims, jobs, now), {"tasks": 2, "agents": 2, "artifacts": 2})
self.assertEqual(view.badges(0, [], [], now), {"tasks": 0, "agents": 0, "artifacts": 0})
self.claim("s1", "Skills session")
self.create_ask(ASK)
self.assertEqual(self.snapshot()["badges"], {"tasks": 1, "agents": 1, "artifacts": 0})
+18 -15
View File
@@ -30,9 +30,9 @@ DIGESTS = "const P = require(process.argv[1]); console.log(JSON.stringify(proces
CHIPS = HUB / "templates" / "legend-chips.js"
CHIPS_STYLE = HUB / "templates" / "style-legend-chips.css"
FULL = {
"resources": {"hidden": ["host:CPU", "agent:Stage", "disk:/mnt_20_data"], "tokens": "accumulated", "combined": True, "combinedHidden": ["burn:scope"]},
"resources": {"hidden": ["host:CPU", "agent:Stage", "disk:/mnt_20_data"], "tokens": "accumulated", "panels": ["combined", "accounts"], "combinedHidden": ["burn:scope"]},
"burn": {"overlays": ["fix", "score"]},
"home": {"pins": [{"kind": "panel", "id": "resources-hardware", "w": 12, "h": 4}, {"kind": "task", "id": "work/feature", "w": 1, "h": 12}]},
"home": {"pins": [{"kind": "panel", "id": "resources-hardware", "w": 12, "h": 4}, {"kind": "task", "id": "work/feature", "w": 1, "h": 12}], "zoom": {"panel:resources-hardware": 130}},
"kanban": {"hidden": ["line"]},
"legend": {"views": {"resources-tokens": False, "tasks/burn": True}, "tiles": {"panel:resources-hardware": False}},
"approval": {"mode": "select"},
@@ -122,7 +122,7 @@ const caught = (run) => {
const stored = await Promise.all([first, second]);
server.home.pins = [@PIN@];
server.burn.overlays = ["fix"];
const combined = await V.set("resources.combined", true);
const combined = await V.set("approval.mode", "select");
const adopted = [V.get("home.pins"), V.get("burn.overlays"), V.get("resources.hidden"), heard.filter(([name]) => name === "pins").at(-1)];
server.resources.hidden = ["host:CPU", "host:RAM"];
const rebased = await V.update("resources.hidden", (list) => [...list, "disk:/"]);
@@ -159,11 +159,11 @@ const caught = (run) => {
const landed = await Promise.all([flying, leaving]);
await wait(400);
const left = clone(server);
server.resources.combined = false;
server.approval.mode = "direct";
await hooks["pageshow:run"]({persisted: false});
const notRestored = [gets, V.get("resources.combined")];
const notRestored = [gets, V.get("approval.mode")];
await hooks["pageshow:run"]({persisted: true});
const restored = [gets, V.get("resources.combined"), hooks.pageshow];
const restored = [gets, V.get("approval.mode"), hooks.pageshow];
const long = "x".repeat(300);
console.log(JSON.stringify({
unknown, wide, listSet, local, stored, combined, adopted, rebased, merged, churned, gaveUp, refused, during, kept, beforeLeave, atLeave, landed, sent, server: left, hooks: hooks.pagehide, error: V.error(), notRestored, restored,
@@ -292,7 +292,7 @@ class TestViewDocument(unittest.TestCase):
def test_the_defaults_and_a_full_document_pass_unchanged(self):
self.assertEqual(valid_view(copy.deepcopy(VIEW)), VIEW)
self.assertEqual(valid_view(copy.deepcopy(FULL)), FULL)
self.assertEqual(VIEW, {"resources": {"hidden": [], "tokens": "interval", "combined": False, "combinedHidden": []}, "burn": {"overlays": []}, "home": {"pins": []}, "kanban": {"hidden": []}, "legend": {"views": {}, "tiles": {}}, "approval": {"mode": "direct"}})
self.assertEqual(VIEW, {"resources": {"hidden": [], "tokens": "interval", "panels": ["hardware", "tokens", "accounts"], "combinedHidden": []}, "burn": {"overlays": []}, "home": {"pins": [], "zoom": {}}, "kanban": {"hidden": []}, "legend": {"views": {}, "tiles": {}}, "approval": {"mode": "direct"}})
def test_unknown_or_missing_keys_and_malformed_values_are_refused(self):
def changed(section: str | None, key: str | None, value: object) -> dict:
@@ -315,7 +315,10 @@ class TestViewDocument(unittest.TestCase):
"missing key": changed("resources", "combinedHidden", KeyError),
"section not an object": changed("burn", None, ["fix"]),
"tokens mode": changed("resources", "tokens", "sum"),
"combined not a flag": changed("resources", "combined", 1),
"panels not a list": changed("resources", "panels", "accounts"),
"no panel": changed("resources", "panels", []),
"unknown panel": changed("resources", "panels", ["radio"]),
"repeated panel": changed("resources", "panels", ["tokens", "tokens"]),
"hidden not a list": changed("resources", "hidden", "host:CPU"),
"id with a space": changed("resources", "hidden", ["host CPU"]),
"empty id": changed("resources", "combinedHidden", [""]),
@@ -441,7 +444,7 @@ class TestViewDocument(unittest.TestCase):
store = self.store()
store.patch(change({"home.pins": [PIN], "burn.overlays": ["fix"]}, {"home.pins": [], "burn.overlays": []}))
found = store.patch(change({"resources.hidden": ["host:CPU"]}, {"resources.hidden": []}))
expected = {**VIEW, "resources": {**VIEW["resources"], "hidden": ["host:CPU"]}, "burn": {"overlays": ["fix"]}, "home": {"pins": [PIN]}}
expected = {**VIEW, "resources": {**VIEW["resources"], "hidden": ["host:CPU"]}, "burn": {"overlays": ["fix"]}, "home": {"pins": [PIN], "zoom": {}}}
self.assertEqual((found, ViewStore(store.file).get()), (expected, expected))
def test_a_stale_tab_on_the_same_path_gets_a_conflict_and_its_retry_keeps_both_changes(self):
@@ -479,7 +482,7 @@ class TestViewClient(unittest.TestCase):
self.assertEqual((first["url"], first["method"], first["headers"], first["keepalive"]), ("/api/view", "PATCH", {"X-Kvb-Orchestrator": "1", "Content-Type": "application/json"}, False))
self.assertEqual(self.bodies()[:2], [
{"set": {"resources.hidden": ["host:CPU"], "resources.tokens": "accumulated"}, "expect": {"resources.hidden": [], "resources.tokens": "interval"}},
{"set": {"resources.combined": True}, "expect": {"resources.combined": False}},
{"set": {"approval.mode": "select"}, "expect": {"approval.mode": "direct"}},
])
def test_an_older_tab_adopts_what_another_browser_stored_on_other_paths(self):
@@ -518,8 +521,8 @@ class TestViewClient(unittest.TestCase):
self.assertEqual(self.data["local"][0], ["host:CPU"])
def test_a_page_restored_from_the_back_forward_cache_refetches_the_stored_view(self):
self.assertEqual(self.data["notRestored"], [0, True])
self.assertEqual(self.data["restored"], [1, False, 1])
self.assertEqual(self.data["notRestored"], [0, "select"])
self.assertEqual(self.data["restored"], [1, "direct", 1])
def test_ids_follow_the_view_grammar_and_stay_distinct(self):
ids = self.data["ids"]
@@ -594,7 +597,7 @@ class TestHubView(HubCase):
def test_two_tabs_changing_other_paths_keep_both_changes(self):
self.assertEqual(self.patch(change({"home.pins": [PIN], "burn.overlays": ["fix"]}, {"home.pins": [], "burn.overlays": []}), self.guard(self.host))[0], 200)
status, body = self.patch(change({"resources.hidden": ["host:CPU"]}, {"resources.hidden": []}), self.guard(self.host))
expected = {**VIEW, "resources": {**VIEW["resources"], "hidden": ["host:CPU"]}, "burn": {"overlays": ["fix"]}, "home": {"pins": [PIN]}}
expected = {**VIEW, "resources": {**VIEW["resources"], "hidden": ["host:CPU"]}, "burn": {"overlays": ["fix"]}, "home": {"pins": [PIN], "zoom": {}}}
self.assertEqual((status, json.loads(body), self.view()), (200, expected, expected))
def test_a_stale_expect_answers_409_with_the_stored_view_and_stores_nothing(self):
@@ -635,7 +638,7 @@ class TestHubView(HubCase):
"not utf-8": b"\xff\xfe{}",
"a list": b"[]",
"no expect": json.dumps({"set": {"resources.tokens": "interval"}}).encode(),
"expect other paths": change({"resources.tokens": "interval"}, {"resources.combined": True}),
"expect other paths": change({"resources.tokens": "interval"}, {"resources.panels": ["combined", "accounts"]}),
"set and more": json.dumps({"set": {"resources.tokens": "interval"}, "expect": {"resources.tokens": "accumulated"}, "theme": "dark"}).encode(),
"empty set": change({}, {}),
"set a list": json.dumps({"set": [["resources.tokens", "interval"]], "expect": {}}).encode(),
@@ -643,7 +646,7 @@ class TestHubView(HubCase):
"unknown key": change({"resources.extra": 1}, {"resources.extra": 0}),
"too deep": change({"home.pins.0": PIN}, {"home.pins.0": PIN}),
"a section missing a key": change({"resources": {"hidden": []}}, {"resources": FULL["resources"]}),
"malformed value": change({"resources.combined": "yes"}, {"resources.combined": True}),
"malformed value": change({"resources.panels": "yes"}, {"resources.panels": ["combined", "accounts"]}),
"null overlay": change({"burn.overlays": [None]}, {"burn.overlays": ["fix", "score"]}),
"one bad of two": change({"resources.tokens": "interval", "home.pins": [{**PIN, "w": 13}]}, {"resources.tokens": "accumulated", "home.pins": FULL["home"]["pins"]}),
"the change limit and one byte": padded + b" " * (CHANGE_LIMIT + 1 - len(padded)),
+95
View File
@@ -0,0 +1,95 @@
from __future__ import annotations
import copy
import json
import subprocess
import tempfile
import unittest
from pathlib import Path
from hub_case import HubCase
from hub_support import HUB
from kvb_orchestrator.errors import ToolError
from kvb_orchestrator.viewstore import VIEW, ViewStore, upgraded, valid_view
TEMPLATES = HUB / "templates"
KEY = "panel:tasks/board"
PIN = {"kind": "panel", "id": "tasks/board", "w": 6, "h": 4}
STEPS = """
const P = require(process.argv[1]);
const run = (zooms, steps) => steps.reduce((now, step) => P.zoomBy(now, "panel:tasks/board", step), zooms);
console.log(JSON.stringify({
three: run({}, [1, 1, 1]), reset: run({"panel:tasks/board": 130}, [0]), floor: run({}, Array(8).fill(-1)), ceiling: run({}, Array(14).fill(1)),
other: run({"panel:x": 70}, [1]), back: run({}, [1, -1]), zoom: P.ZOOM,
}));
"""
def change(values: dict, expected: dict) -> bytes:
return json.dumps({"set": values, "expect": expected}).encode()
def viewed(zoom: dict) -> dict:
doc = copy.deepcopy(VIEW)
doc["home"] = {"pins": [PIN], "zoom": zoom}
return doc
class TestZoomSteps(unittest.TestCase):
def test_keys_step_ten_percent_inside_50_to_200_and_reset_leaves_the_base_out(self):
done = subprocess.run(["node", "-e", STEPS, str(TEMPLATES / "panels.js")], capture_output=True, text=True, timeout=60, check=False)
self.assertEqual(done.returncode, 0, done.stderr)
out = json.loads(done.stdout)
self.assertEqual(out["zoom"], {"min": 50, "max": 200, "step": 10, "base": 100})
self.assertEqual((out["three"], out["reset"], out["floor"], out["ceiling"]), ({KEY: 130}, {}, {KEY: 50}, {KEY: 200}))
self.assertEqual((out["other"], out["back"]), ({"panel:x": 70, KEY: 110}, {}))
def test_the_tile_keys_the_wheel_and_the_menu_reach_the_same_step(self):
home = (TEMPLATES / "page-home.js").read_text(encoding="utf-8")
self.assertIn('const ZOOM_KEYS = {"+": 1, "=": 1, "-": -1, "0": 0};', home)
self.assertIn("event.ctrlKey || !event.deltaY", home)
self.assertIn('body.addEventListener("wheel", (event) => homeWheel(event, key), {passive: false});', home)
context = (TEMPLATES / "page-context.js").read_text(encoding="utf-8")
for label, step in (('"Zoom in"', "1"), ('"Zoom out"', "-1"), ("`Reset zoom (${homeZoom(key)} %)`", "0")):
with self.subTest(label=label):
self.assertIn(f"label: {label}, hint: ", context)
self.assertIn(f"homeZoomBy(key, {step})", context)
self.assertIn("Ctrl+wheel", (TEMPLATES / "page-constants.js").read_text(encoding="utf-8"))
self.assertIn(".home-body > * { zoom: var(--zoom, 1); }", (TEMPLATES / "style-home.css").read_text(encoding="utf-8"))
class TestZoomStore(unittest.TestCase):
def test_a_pinned_tile_keeps_its_zoom_and_an_unpinned_one_loses_it(self):
self.assertEqual(valid_view(viewed({KEY: 130}))["home"]["zoom"], {KEY: 130})
self.assertEqual(valid_view(viewed({KEY: 130, "panel:gone": 70}))["home"]["zoom"], {KEY: 130})
def test_values_off_the_grid_or_outside_50_to_200_are_refused(self):
for bad in ({KEY: 40}, {KEY: 210}, {KEY: 105}, {KEY: True}, {KEY: "130"}, {KEY: 130.0}, {"no key": 130}, []):
with self.subTest(bad=bad), self.assertRaises(ToolError):
valid_view(viewed(bad))
def test_an_older_document_without_zoom_reads_with_none(self):
old = copy.deepcopy(VIEW)
old["home"] = {"pins": [PIN]}
self.assertEqual(valid_view(upgraded(old))["home"], {"pins": [PIN], "zoom": {}})
def test_the_zoom_survives_a_restart(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
file = Path(folder.name) / "view.json"
ViewStore(file).patch(change({"home.pins": [PIN], "home.zoom": {KEY: 130}}, {"home.pins": [], "home.zoom": {}}))
self.assertEqual(ViewStore(file).get()["home"], {"pins": [PIN], "zoom": {KEY: 130}})
class TestZoomOverHttp(HubCase):
def patch(self, body: bytes) -> int:
return self.call("PATCH", "/api/view", body, {**self.guard(self.host), "Content-Type": "application/json"})[0]
def test_the_hub_refuses_an_off_grid_zoom_with_400_and_keeps_a_valid_one(self):
self.assertEqual(self.patch(change({"home.pins": [PIN], "home.zoom": {KEY: 135}}, {"home.pins": [], "home.zoom": {}})), 400)
self.assertEqual(self.patch(change({"home.pins": [PIN], "home.zoom": {KEY: 130}}, {"home.pins": [], "home.zoom": {}})), 200)
self.assertEqual(json.loads(self.get("/api/view")[2])["home"]["zoom"], {KEY: 130})
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -10,7 +10,7 @@ from pathlib import Path
from hub_support import signing
TEMPLATES = Path(__file__).resolve().parent.parent / "orchestrator" / "templates"
MODULES = ["page-constants.js", "glossary.js", "ancestry.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-diff.js", "page-rule-request.js", "page-inbox.js", "page-grant.js", "page-firewall.js", "page-review.js", "page-cleanup.js", "page-offices.js", "page-ancestry.js", "page-tasks-prio.js"]
MODULES = ["page-constants.js", "glossary.js", "answers.js", "ancestry.js", "page-reveal.js", "page-dom.js", "page-dialog.js", "page-diff.js", "page-rule-request.js", "page-inbox.js", "page-grant.js", "page-firewall.js", "page-review.js", "page-cleanup.js", "page-offices.js", "page-ancestry.js", "page-tasks-prio.js"]
RLO, ZWSP, LRI, SEPARATOR, CARRIAGE = chr(0x202E), chr(0x200B), chr(0x2066), chr(0x2028), chr(0x0D)
FILLER, NBSP, CGJ, VS15, VS16 = chr(0x3164), chr(0xA0), chr(0x34F), chr(0xFE0E), chr(0xFE0F)
HIDDEN = (RLO, ZWSP, LRI, SEPARATOR, CARRIAGE, FILLER, NBSP, CGJ, VS16)
+3 -2
View File
@@ -535,11 +535,12 @@ class TestSettingsWriter(unittest.TestCase):
def test_a_missing_directory_shows_in_the_view_as_the_writer_handles_it(self):
self.project_settings.parent.rmdir()
shown = self.writer.view()["files"][1]
self.assertEqual((shown["exists"], shown["error"]), (False, host.MISSING_DIRECTORY))
self.assertEqual((shown["exists"], shown["folder"], shown["error"]), (False, False, host.MISSING_DIRECTORY))
self.assertTrue(self.writer.view()["files"][0]["folder"])
result = self.signed({"file": str(self.project_settings), "base": "", "changes": [ADD_LINT]})
self.assertEqual((result["status"], self.project_settings.parent.exists()), ("refused", False), result)
self.project_settings.parent.mkdir()
self.assertEqual(self.writer.view()["files"][1]["error"], "")
self.assertEqual((self.writer.view()["files"][1]["error"], self.writer.view()["files"][1]["folder"]), ("", True))
self.assertEqual(self.signed({"file": str(self.project_settings), "base": "", "changes": [ADD_LINT]})["status"], "done")
def test_the_unit_runs_once_outside_any_agent_and_refuses_inside_one(self):