feat(orchestrator): bulk grant mode, continuous review diff and an inbox denial reason (020)
A Direct/Select switch in the header (ids grant-direct, grant-select; ViewStore approval.mode) decides whether a grant button acts at once or adds its item to a selection that a tray grants under one passkey signature; rules and red gates still act at once. The review sheet shows every file in one scrolling stack whose next file opens as the previous one ends (openOnScroll moves to page-diff.js and serves Match too). The grant bar boots before the header is measured, so --head counts it. The inbox denial sheet takes an optional reason for every requester; it shares page-inbox.js hunks with the selection code, so both land in this one commit. Fix stays below 90: the header ids and the measure order fix e2e failures of the aborted final run of 2026-11-17 that the master gate has not rerun yet. Accepted MEDUSA false positives (security.py accept after kvb-think-criticize, 2026-11-17): page-inbox.js PQC007 EXA010; page-match.js EXA010. 🎯 Fix: 85 % 💥 Break: 5 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 81 🚦 Gate: ⛔ fix 85 % < 90 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
88a2d88e47
commit
65d00c0d2c
22 files changed
+763
-65
No files matched your search
@@ -33,7 +33,7 @@ INBOX_PICK = """(async () => {@HELPERS@
|
||||
const send = window.fetch.bind(window);
|
||||
window.fetch = (path, init) => {
|
||||
if (["/api/sign", "/api/inbox/approve"].includes(String(path))) {
|
||||
posted.push([String(path), JSON.parse(init.body).items.map((item) => [item.id, item.verb, item.channel || null])]);
|
||||
posted.push([String(path), JSON.parse(init.body).items.map((item) => [item.id, item.verb, item.channel || null, item.reason])]);
|
||||
}
|
||||
return send(path, init);
|
||||
};
|
||||
@@ -62,12 +62,15 @@ INBOX_PICK = """(async () => {@HELPERS@
|
||||
all("#main .inbox-actions button").find((button) => name(button).startsWith("Deny selection")).click();
|
||||
await until(() => document.querySelector(".sheet-box .actions"), 4000);
|
||||
const listed = all(".sheet-box ul.mini > li strong").map(text);
|
||||
const reason = document.querySelector(".sheet-box .deny-reason textarea");
|
||||
const reasoned = Boolean(reason && document.activeElement === reason);
|
||||
reason.value = "rebase first";
|
||||
const confirm = all(".sheet-box .actions button").find((button) => text(button).startsWith("Deny "));
|
||||
const label = text(confirm);
|
||||
const shown = new Set(all("#toasts .toast"));
|
||||
confirm.click();
|
||||
const toast = await until(() => all("#toasts .toast").filter((node) => !shown.has(node)).map(text).find((entry) => entry.startsWith("Deny selection")), 15000);
|
||||
return {title, before, moved: Math.abs(after - before), focused, buttons, listed, label, toast, posted, wide: document.documentElement.scrollWidth > window.innerWidth + 1};
|
||||
return {title, before, moved: Math.abs(after - before), focused, buttons, listed, label, reasoned, toast, posted, wide: document.documentElement.scrollWidth > window.innerWidth + 1};
|
||||
})()""".replace("@HELPERS@", HELPERS)
|
||||
LAYOUT = """(async () => {@HELPERS@@LABELS@
|
||||
await until(() => document.querySelector("#main .console") && rowOf("Rule request"), 8000);
|
||||
|
||||
@@ -324,7 +324,7 @@ CANCELED = """() => {
|
||||
}"""
|
||||
JUMPED = {
|
||||
"hash": "#stream", "focused": True, "tabs": [[tab, True, True] for tab in ("#home", "#stream/inbox", "#agents/orbit", "#artifacts/tree", "#tasks/list", "#resources")], "closed": [True, "false"],
|
||||
"header": [["radio-open", "Radio", ""], ["bubbles-toggle", "Speech bubbles", ""], ["palette-open", "Commands", ""], ["settings-open", "Settings", ""]], "radioTab": False,
|
||||
"header": [["grant-direct", "Direct", "Direct"], ["grant-select", "Select", "Select"], ["radio-open", "Radio", ""], ["bubbles-toggle", "Speech bubbles", ""], ["palette-open", "Commands", ""], ["settings-open", "Settings", ""]], "radioTab": False,
|
||||
}
|
||||
GEAR_SAVE = """(async () => {@HELPERS@@CLASHES@
|
||||
const spot = document.getElementById("radio-spot");
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
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_e2e_kit import WIDTHS
|
||||
from hub_support import ASK
|
||||
from kvb_orchestrator import batches
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/bulk-grant-shots"))
|
||||
FILES = ("src/app.py", "src/view.js", "docs/notes.md")
|
||||
ROWS = 80
|
||||
COMMON = """
|
||||
const row = (ref) => document.querySelector(`#main .inbox-list > li[data-ref="${ref}"]`);
|
||||
const modeButton = (mode) => document.querySelector(`#grant-bar button[data-mode="${mode}"]`);
|
||||
const tray = () => document.querySelector("#grant-bar .grant-tray");
|
||||
const count = () => text(document.querySelector("#grant-bar .grant-count"));
|
||||
const grantOf = (ref) => row(ref) && row(ref).querySelector(".item-actions button.primary");
|
||||
const wide = () => document.documentElement.scrollWidth > innerWidth + 1;
|
||||
const switchState = () => [modeButton("direct").getAttribute("aria-pressed"), modeButton("select").getAttribute("aria-pressed"), tray().hidden, Boolean(document.querySelector("#main .inbox-actions"))];
|
||||
const storedMode = async (mode) => {
|
||||
const end = Date.now() + 6000;
|
||||
while (Date.now() < end) {
|
||||
const view = await (await fetch("/api/view", {cache: "no-store"})).json();
|
||||
if (view.approval.mode === mode) {
|
||||
return true;
|
||||
}
|
||||
await sleep(200);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const key = (value) => document.body.dispatchEvent(new KeyboardEvent("keydown", {key: value, bubbles: true}));
|
||||
"""
|
||||
DIFF = """(async () => {@HELPERS@@COMMON@
|
||||
if (!(await until(() => row("@REVIEW@"), 8000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
row("@REVIEW@").querySelector(".headline").click();
|
||||
const stack = await until(() => {
|
||||
const found = document.querySelector("#sheet .review-stack");
|
||||
return found && all(".review-file", found).length === 3 ? found : null;
|
||||
}, 8000);
|
||||
if (!stack) {
|
||||
return {error: text(document.getElementById("sheet"))};
|
||||
}
|
||||
const files = () => all(".review-file", stack);
|
||||
const state = () => ({opened: files().map((file) => file.open), marked: all("#sheet .file-entry[aria-current='true']").map((entry) => Number(entry.dataset.index))});
|
||||
const first = state();
|
||||
const [one, two] = files();
|
||||
stack.scrollTop = one.offsetTop + one.offsetHeight - stack.clientHeight + 4;
|
||||
await until(() => files()[1].open, 4000);
|
||||
await sleep(300);
|
||||
const ended = state();
|
||||
stack.scrollTop = two.offsetTop;
|
||||
await until(() => state().marked[0] === 1, 4000);
|
||||
await sleep(200);
|
||||
const second = state();
|
||||
document.querySelector('#sheet .file-entry[data-index="2"]').click();
|
||||
await sleep(400);
|
||||
const three = files()[2];
|
||||
const atTop = Math.abs(three.getBoundingClientRect().top - stack.getBoundingClientRect().top) <= 2 || stack.scrollTop >= stack.scrollHeight - stack.clientHeight - 1;
|
||||
return {first, ended, second, jumped: {...state(), atTop}, wide: wide()};
|
||||
})()"""
|
||||
MODE = """(async () => {@HELPERS@@COMMON@
|
||||
key("Escape");
|
||||
await until(() => document.getElementById("sheet").hidden, 4000);
|
||||
const before = switchState();
|
||||
modeButton("select").click();
|
||||
const kept = await storedMode("select");
|
||||
await until(() => !tray().hidden, 4000);
|
||||
return {before, kept, after: switchState(), wide: wide()};
|
||||
})()"""
|
||||
COLLECT = """(async () => {@HELPERS@@COMMON@
|
||||
const posted = [];
|
||||
const send = window.fetch.bind(window);
|
||||
window.fetch = (path, init) => {
|
||||
if (["/api/sign", "/api/inbox/approve"].includes(String(path))) {
|
||||
posted.push(String(path));
|
||||
}
|
||||
return send(path, init);
|
||||
};
|
||||
if (!(await until(() => row("@REVIEW@") && row("@ASK@") && row("@RUN@") && !tray().hidden, 8000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
const restored = switchState();
|
||||
const counts = [];
|
||||
const press = async (ref, expected) => {
|
||||
grantOf(ref).click();
|
||||
await until(() => count() === expected, 3000);
|
||||
counts.push(count());
|
||||
};
|
||||
await press("@REVIEW@", "1 selected");
|
||||
await press("@ASK@", "2 selected");
|
||||
await press("@REVIEW@", "1 selected");
|
||||
await press("@REVIEW@", "2 selected");
|
||||
if (document.activeElement) {
|
||||
document.activeElement.blur();
|
||||
}
|
||||
for (let step = 0; step < 40 && !row("@RUN@").classList.contains("cursor"); step += 1) {
|
||||
const cursor = document.querySelector("#main .inbox-list > li.cursor");
|
||||
key(cursor && Number(cursor.dataset.index) > Number(row("@RUN@").dataset.index) ? "k" : "j");
|
||||
await sleep(60);
|
||||
}
|
||||
key("a");
|
||||
await until(() => count() === "3 selected", 3000);
|
||||
counts.push(count());
|
||||
const pressed = ["@REVIEW@", "@ASK@", "@RUN@"].map((ref) => grantOf(ref).getAttribute("aria-pressed"));
|
||||
const labels = all("#grant-bar .grant-tray button").map(name);
|
||||
return {restored, counts, pressed, labels, posted, wide: wide()};
|
||||
})()"""
|
||||
SHEET = """(async () => {@HELPERS@@COMMON@
|
||||
all("#grant-bar .grant-tray button").find((button) => name(button) === "Grant selection (3)").click();
|
||||
await until(() => document.querySelector(".sheet-box .actions"), 4000);
|
||||
const confirm = all(".sheet-box .actions button").find((button) => text(button).startsWith("Grant "));
|
||||
return {listed: all(".sheet-box ul.mini > li strong").map(text), label: text(confirm), wide: wide()};
|
||||
})()"""
|
||||
CONFIRM = """(async () => {@HELPERS@@COMMON@
|
||||
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"].includes(String(path))) {
|
||||
posted.push([String(path), JSON.parse(init.body).items.map((item) => `${item.kind}:${item.id}:${item.verb}`).sort()]);
|
||||
}
|
||||
return send(path, init);
|
||||
};
|
||||
const shown = new Set(all("#toasts .toast"));
|
||||
all(".sheet-box .actions button").find((button) => text(button).startsWith("Grant ")).click();
|
||||
const toast = await until(() => all("#toasts .toast").filter((node) => !shown.has(node)).map(text).find((entry) => entry.startsWith("Grant selection")), 15000);
|
||||
await sleep(@SIGNS@ ? 2500 : 300);
|
||||
return {posted, toast, count: count(), wide: wide()};
|
||||
})()"""
|
||||
DIRECT = """(async () => {@HELPERS@@COMMON@
|
||||
const posted = [];
|
||||
const send = window.fetch.bind(window);
|
||||
window.fetch = (path, init) => {
|
||||
if (String(path) === "/api/sign") {
|
||||
posted.push(JSON.parse(init.body).items.map((item) => `${item.kind}:${item.id}`));
|
||||
return Promise.resolve(new Response("held by the e2e", {status: 503}));
|
||||
}
|
||||
return send(path, init);
|
||||
};
|
||||
modeButton("direct").click();
|
||||
const kept = await storedMode("direct");
|
||||
await until(() => tray().hidden && document.querySelector("#main .inbox-actions"), 4000);
|
||||
const spare = await until(() => grantOf("@SPARE@"), 4000);
|
||||
const pressed = spare.getAttribute("aria-pressed");
|
||||
spare.click();
|
||||
await until(() => posted.length, 4000);
|
||||
return {kept, after: switchState(), pressed, posted, wide: wide()};
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str, **values: str) -> str:
|
||||
found = template.replace("@HELPERS@", base.HELPERS).replace("@COMMON@", COMMON)
|
||||
for name, value in values.items():
|
||||
found = found.replace(f"@{name}@", value)
|
||||
return found
|
||||
|
||||
|
||||
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, ROWS + 1))
|
||||
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">+{ROWS}</span><span class="del">−0</span></span></summary><table class="diff"><tbody>{rows}</tbody></table></details>')
|
||||
return f'<!DOCTYPE html><html><body><section class="group" id="staged" data-files="3">{"".join(sections)}</section></body></html>'
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestBulkGrant(base.OrchestratorE2ECase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
page = self.page("three-files.html", review_page())
|
||||
rows = {}
|
||||
self.sets = {}
|
||||
for width, _ in WIDTHS:
|
||||
review = self.review(f"feat: three files {width}", f"feature/bulk-{width}", page)
|
||||
ask = self.create_ask({**ASK, "command": f"make deploy-{width}", "timeout": 3600})
|
||||
task = f"operator/bulk-{width}"
|
||||
rows[task] = {"title": f"echo bulk {width}", "workdir": "/repo", "description": "bulk", "check": "manual", "status": "queued", "roles": {"Operator": "R", "Skills session": "A"}}
|
||||
self.sets[width] = {"REVIEW": f"review:{review}", "ASK": f"ask:{ask}", "RUN": f"operator:{task}"}
|
||||
self.spare = f"review:{self.review('feat: spare', 'feature/bulk-spare', page)}"
|
||||
self.write_council({"rasci.json": rows})
|
||||
|
||||
def review(self, title: str, branch: str, page: str) -> str:
|
||||
arguments = {**self.arguments(title, "", page), "worktree": f"/repo/.worktrees/{branch}", "branch": branch, "agent": "Skills"}
|
||||
result = self.tool("review_request", arguments)
|
||||
self.assertFalse(result["isError"], result)
|
||||
return result["structuredContent"]["id"]
|
||||
|
||||
def steps(self, browser: str, signs: bool) -> list[dict]:
|
||||
local = f"http://localhost:{self.port}/"
|
||||
flag = "true" if signs else "false"
|
||||
steps = []
|
||||
for width, height in WIDTHS:
|
||||
ids = self.sets[width]
|
||||
shot = str(OUT / f"{browser}-{width}")
|
||||
steps += [
|
||||
{"width": width, "height": height, "url": f"{local}?{width}#stream/inbox", "wait": 1200, "probe": probe(DIFF, **ids), "shot": f"{shot}-continuous-diff.png"},
|
||||
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(MODE), "shot": None},
|
||||
{"width": width, "height": height, "url": f"{local}?{width}-kept#stream/inbox", "wait": 1200, "probe": probe(COLLECT, **ids), "shot": f"{shot}-select-tray.png"},
|
||||
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(SHEET), "shot": f"{shot}-grant-sheet.png"},
|
||||
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(CONFIRM, SIGNS=flag), "shot": None},
|
||||
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(DIRECT, SPARE=self.spare), "shot": f"{shot}-direct.png"},
|
||||
]
|
||||
return steps
|
||||
|
||||
def check(self, data: dict, browser: str, signs: bool) -> None:
|
||||
self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], [])
|
||||
results = iter(data["results"])
|
||||
for width, _ in WIDTHS:
|
||||
ids = self.sets[width]
|
||||
diff, mode, collect, sheet, confirm, direct = (next(results) for _ in range(6))
|
||||
with self.subTest(browser=browser, width=width):
|
||||
self.assertNotIn("error", diff, diff)
|
||||
self.assertEqual(diff["first"], {"opened": [True, False, False], "marked": [0]}, diff)
|
||||
self.assertEqual(diff["ended"]["opened"], [True, True, False], diff)
|
||||
self.assertEqual(diff["second"], {"opened": [True, True, False], "marked": [1]}, diff)
|
||||
self.assertEqual(diff["jumped"], {"opened": [True, True, True], "marked": [2], "atTop": True}, diff)
|
||||
self.assertEqual((mode["before"], mode["kept"], mode["after"]), (["true", "false", True, True], True, ["false", "true", False, False]), mode)
|
||||
self.assertNotIn("error", collect, collect)
|
||||
self.assertEqual(collect["restored"], ["false", "true", False, False], collect)
|
||||
self.assertEqual(collect["counts"], ["1 selected", "2 selected", "1 selected", "2 selected", "3 selected"], collect)
|
||||
self.assertEqual((collect["pressed"], collect["posted"]), (["true"] * 3, []), collect)
|
||||
self.assertEqual((collect["labels"][0], collect["labels"][-1]), ("Grant selection (3)", "Clear"), collect)
|
||||
self.assertEqual((sheet["label"], len(sheet["listed"])), ("Grant 3", 3), sheet)
|
||||
items = sorted(f"{ref}:approve" for ref in ids.values())
|
||||
self.assertEqual(confirm["posted"], [["/api/sign", items], *([["/api/inbox/approve", items]] if signs else [])], confirm)
|
||||
self.assertEqual(confirm["count"], "0 selected" if signs else "3 selected", confirm)
|
||||
self.assertEqual(direct["kept"], True, direct)
|
||||
self.assertEqual(direct["after"], ["true", "false", True, True], direct)
|
||||
self.assertEqual((direct["pressed"], direct["posted"]), (None, [[self.spare]]), direct)
|
||||
self.assertFalse(any(found["wide"] for found in (diff, mode, collect, sheet, confirm, direct)), width)
|
||||
|
||||
def granted(self) -> None:
|
||||
reviews = [ids["REVIEW"].split(":", 1)[1] for ids in self.sets.values()]
|
||||
asks = [ids["ASK"].split(":", 1)[1] for ids in self.sets.values()]
|
||||
self.settle(lambda: all(self.status(review) == "approved" for review in reviews))
|
||||
self.assertEqual([self.ask_status(ask, "0") for ask in asks], ["allowed"] * len(asks))
|
||||
self.assertEqual(self.status(self.spare.split(":", 1)[1]), "pending")
|
||||
|
||||
def test_chromium_continuous_diff_select_tray_one_signature_and_direct_at_three_widths(self):
|
||||
with mock.patch.object(batches, "UNDO", 0.3):
|
||||
data = self.drive(self.steps("chromium", True), self.authenticator())
|
||||
(OUT / "chromium-bulk-grant.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.check(data, "chromium", True)
|
||||
self.granted()
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
|
||||
def test_firefox_continuous_diff_select_tray_and_direct_at_three_widths_unsigned(self):
|
||||
data = self.drive(self.steps("firefox", False), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"))
|
||||
(OUT / "firefox-bulk-grant.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.check(data, "firefox", False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -50,8 +50,7 @@ class TestHubInbox(base.OrchestratorE2ECase):
|
||||
def layout(self, probe: dict) -> None:
|
||||
self.assertNotIn("error", probe)
|
||||
self.assertEqual(sorted(probe["kinds"]), ["Ask", "Operator", "Operator", "Review", "Rule request"])
|
||||
self.assertIn(["Deny", "Deny via …"], probe["splits"])
|
||||
self.assertEqual(len(probe["splits"]), 4)
|
||||
self.assertEqual(probe["splits"], [["Deny", "Deny via …"]] * 5)
|
||||
self.assertEqual(probe["fields"], ["Kind", "Tool (glob)", "Pattern (glob)", "Directory (glob)", "Expires on"])
|
||||
self.assertEqual(probe["dry"], "Dry run: the rule would have granted 1 of 1 asks from the last 7 days.")
|
||||
self.assertEqual(probe["accept"], 1)
|
||||
@@ -163,9 +162,9 @@ class TestHubInbox(base.OrchestratorE2ECase):
|
||||
self.assertGreater(found["before"], 0, found)
|
||||
self.assertEqual((found["moved"], found["focused"], found["wide"]), (0, True, False), found)
|
||||
self.assertTrue({"Grant selection (1)", "Deny selection (2)"} <= set(found["buttons"]), found["buttons"])
|
||||
self.assertEqual((sorted(found["listed"]), found["label"]), (sorted([found["title"], "pick a name"]), "Deny 2"))
|
||||
self.assertEqual((sorted(found["listed"]), found["label"], found["reasoned"]), (sorted([found["title"], "pick a name"]), "Deny 2", True))
|
||||
task = f"operator/row-{found['title'][-2:]}"
|
||||
items = sorted([[task, "reject", "post"], ["operator/name", "reject", "post"]])
|
||||
items = sorted([[task, "reject", "post", "rebase first"], ["operator/name", "reject", "post", "rebase first"]])
|
||||
self.assertEqual([[path, sorted(entries)] for path, entries in found["posted"]], [["/api/sign", items], *([["/api/inbox/approve", items]] if signs else [])])
|
||||
self.assertIn("takes effect" if signs else "not signed", found["toast"])
|
||||
denied += [task, "operator/name"]
|
||||
|
||||
@@ -139,7 +139,7 @@ class TestOrchestratorE2E(base.OrchestratorE2ECase):
|
||||
with self.subTest(url=step["url"], width=step["width"]):
|
||||
self.assertNotIn("error", probe)
|
||||
self.assertEqual((probe["title"], probe["h1"]), ("(2) Agent Orchestrator", "Agent Orchestrator"))
|
||||
self.assertEqual(probe["header"], ["radio-open", "bubbles-toggle", "palette-open", "settings-open"])
|
||||
self.assertEqual(probe["header"], ["grant-direct", "grant-select", "radio-open", "bubbles-toggle", "palette-open", "settings-open"])
|
||||
self.assertEqual((probe["tabs"], probe["subs"]), (TABS, SUBS))
|
||||
self.assertEqual(probe["badges"], {"tab-home": None, "tab-stream": None, "tab-rules": None, "tab-agents": "1", "tab-artifacts": None, "tab-tasks": "2", "tab-resources": None})
|
||||
self.assertEqual(probe["banner"], "MAYDAY · Docs: disk full")
|
||||
|
||||
@@ -10,7 +10,7 @@ import unittest
|
||||
from unittest import mock
|
||||
|
||||
from hub_case import HubCase
|
||||
from hub_support import ASK, CLIENT, Key, key, signing, verifier
|
||||
from hub_support import ASK, CLIENT, PAGE, Key, key, signing, verifier
|
||||
from kvb_orchestrator import batches, skill_scripts
|
||||
|
||||
PUSH = "git push"
|
||||
@@ -90,21 +90,22 @@ class TestHubDeny(HubCase):
|
||||
row = {"title": PUSH, "workdir": "/repo", "description": "ship", "check": "manual", "status": "queued", "roles": {"Operator": "R", "Skills session": "A"}}
|
||||
self.write_council({"rasci.json": {"operator/push": row}})
|
||||
ask_id = self.create_ask(ASK)
|
||||
review_id = self.request("feat: deny me", "")
|
||||
review_id = self.tool("review_request", {**self.arguments("feat: deny me", "", self.page("bundle.html", PAGE)), "agent": "Skills"})["structuredContent"]["id"]
|
||||
digest = hashlib.sha256(PUSH.encode()).hexdigest()
|
||||
entries = [
|
||||
self.denial("ask", ask_id, "", "post", ""),
|
||||
self.denial("operator", "operator/push", digest, "post", ""),
|
||||
{**self.entry("review", review_id, "", ""), "verb": "reject"},
|
||||
self.denial("review", review_id, "", "post", "rebase first"),
|
||||
]
|
||||
with mock.patch.object(batches, "UNDO", 0.05):
|
||||
self.assertEqual(self.approve(entries, self.signed(entries, self.pin()))[0], 202)
|
||||
self.settle(lambda: self.ask_status(ask_id, "0") == "denied")
|
||||
self.settle(lambda: (skill_scripts.RASCI, ["set", "operator/push", "--status", "stopped"]) in self.scripts.calls)
|
||||
self.settle(lambda: self.tool("review_wait", {"id": review_id, "timeout_seconds": 0})["structuredContent"]["status"] == "rejected")
|
||||
self.settle(lambda: len(self.radio()) >= 2)
|
||||
self.assertEqual(sorted(sent[:3] for sent in self.radio()), [["post", "--to", "Skills session"]] * 2)
|
||||
self.settle(lambda: len(self.radio()) >= 3)
|
||||
self.assertEqual(sorted(sent[:3] for sent in self.radio()), [["post", "--to", "Skills session"]] * 3)
|
||||
self.assertTrue(all("Denied by the operator: " in sent[-1] for sent in self.radio()), self.radio())
|
||||
self.assertIn("Denied by the operator: commit feat: deny me", next(sent[-1] for sent in self.radio() if "Reason: rebase first" in sent[-1]))
|
||||
self.assertFalse({ask_id, review_id} & {item["id"] for item in self.snapshot()["inbox"]})
|
||||
|
||||
def test_every_class_but_mayday_reaches_the_agent_or_all(self):
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import unittest
|
||||
|
||||
from hub_support import HUB
|
||||
|
||||
TEMPLATES = HUB / "templates"
|
||||
MODULES = ["page-constants.js", "page-reveal.js", "page-dom.js", "page-inbox.js", "page-grant.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: {}, handlers: {}, hidden: false, textContent: ""}); }
|
||||
setAttribute(key, value) {
|
||||
this.attrs[key] = String(value);
|
||||
if (key.startsWith("data-")) {
|
||||
this.dataset[key.slice(5).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())] = 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(name, handler) { this.handlers[name] = handler; }
|
||||
click() { this.handlers.click({stopPropagation() {}, preventDefault() {}}); }
|
||||
remove() {}
|
||||
}
|
||||
const all = (node) => [node, ...(node.children || []).filter((child) => child instanceof El).flatMap(all)];
|
||||
const text = (node) => (typeof node === "string" ? node : (node.children || []).map(text).join(""));
|
||||
const buttons = (node) => all(node).filter((el) => el.tag === "button");
|
||||
const document = {
|
||||
currentScript: null, body: new El("body"), hidden: false, activeElement: null,
|
||||
getElementById: (id) => Object.assign(new El("div"), {textContent: id === "emoji-bases" ? "[]" : ""}),
|
||||
createElement: (tag) => new El(tag), createElementNS: (ns, tag) => new El(tag),
|
||||
};
|
||||
const now = 1_800_000_000;
|
||||
const base = {agent: "Store", to: "Store", detail: "", green: false, gate: "", score: "", warnings: [], options: [], recommended: "", command: "", directory: "/repo", sha256: "s", runnable: false, deniable: false, job: null, rule: null, dry_run: null, diff: null, pinned: false, until: 0, held: false, ts: now};
|
||||
const items = {
|
||||
green: {...base, kind: "review", id: "r-green", title: "feat: green", gate: "pass", green: true},
|
||||
red: {...base, kind: "review", id: "r-red", title: "feat: red", gate: "fail"},
|
||||
ask: {...base, kind: "ask", id: "a-1", title: "git push: ask", command: "git push"},
|
||||
run: {...base, kind: "operator", id: "operator/run", title: "make install", command: "make install", runnable: true, deniable: true},
|
||||
pick: {...base, kind: "decision", id: "d-1", title: "Which?", recommended: "A", options: [{label: "A", description: ""}]},
|
||||
rule: {...base, kind: "rule", id: "1123456789abcdef", title: "Rule ask Bash make deploy"},
|
||||
};
|
||||
const mode = {value: "select"};
|
||||
const sets = [];
|
||||
const listeners = [];
|
||||
const context = {
|
||||
console, document, JSON, Math, Date, Intl, Promise, Set, Map, Number, String, Array, Object, RegExp, Boolean, Error, setTimeout,
|
||||
Node: El, Element: El, HTMLElement: El,
|
||||
window: {location: {hash: "", hostname: "localhost", port: "8737", pathname: "/"}, setTimeout: () => 0, clearTimeout: () => {}, setInterval: () => 0, clearInterval: () => {}, getSelection: () => "", matchMedia: () => ({matches: false})},
|
||||
state: {inbox: [], radio: [], messages: [], settings: {}, now},
|
||||
ui: {screen: "inbox", busy: false, selected: new Set(), cursor: 0, snoozed: false, asOf: null},
|
||||
known: {batches: new Set()},
|
||||
ViewStore: {get: (path) => (path === "approval.mode" ? mode.value : null), set: (path, value) => { sets.push([path, value]); mode.value = value; }, on: (path, callback) => listeners.push([path, callback])},
|
||||
denySplit: () => new El("deny"), jobOpen: () => false, load: async () => {}, openItem: () => {},
|
||||
items, mode, sets, listeners, all, text, buttons,
|
||||
};
|
||||
const source = names.map((name) => fs.readFileSync(`${dir}/${name}`, "utf8")).join("\n");
|
||||
const probe = `
|
||||
const proofs = [];
|
||||
const accepts = [];
|
||||
let renders = 0;
|
||||
let streams = 0;
|
||||
proofFor = async (entries) => { proofs.push(entries.map((entry) => entry.kind + ":" + entry.id)); return null; };
|
||||
acceptRule = (item) => { accepts.push(item.id); };
|
||||
render = () => { renders += 1; };
|
||||
drawStream = () => { streams += 1; };
|
||||
toast = () => ({remove() {}});
|
||||
const results = {};
|
||||
const take = () => ({selected: [...ui.selected].sort(), proofs: proofs.splice(0), accepts: accepts.splice(0), renders, streams});
|
||||
const press = (item) => {
|
||||
const first = actionsFor(item)[0];
|
||||
return {pressed: first.getAttribute("aria-pressed"), title: first.getAttribute("title")};
|
||||
};
|
||||
(async () => {
|
||||
state.inbox = Object.values(items).map((item) => ({...item}));
|
||||
const of = (key) => state.inbox.find((item) => item.id === items[key].id);
|
||||
results.unpressed = press(of("green"));
|
||||
await approveOne(of("green"));
|
||||
results.added = take();
|
||||
results.pressed = press(of("green"));
|
||||
await approveOne(of("green"));
|
||||
results.removed = take();
|
||||
for (const key of ["green", "ask", "run", "pick"]) {
|
||||
await approveOne(of(key));
|
||||
}
|
||||
results.collected = take();
|
||||
await approveOne(of("red"));
|
||||
results.red = {...take(), press: press(of("red"))};
|
||||
await approveOne(of("rule"));
|
||||
results.rule = {...take(), press: press(of("rule"))};
|
||||
grantBoot();
|
||||
const bar = grantView.tray;
|
||||
const modes = grantView.modes;
|
||||
results.tray = {hidden: bar.hidden, text: text(bar), labels: buttons(bar).map((button) => button.getAttribute("aria-label")), modes: modes.map((button) => [button.dataset.mode, button.getAttribute("aria-pressed")]), listen: listeners.map(([path]) => path)};
|
||||
buttons(bar).pop().click();
|
||||
results.cleared = take();
|
||||
modes[0].click();
|
||||
results.switched = sets.splice(0);
|
||||
drawGrant();
|
||||
results.direct_tray = {hidden: bar.hidden, children: bar.children.length, modes: modes.map((button) => button.getAttribute("aria-pressed"))};
|
||||
results.direct_press = press(of("green"));
|
||||
await approveOne(of("green"));
|
||||
results.direct = take();
|
||||
console.log(JSON.stringify(results));
|
||||
})().catch((error) => { console.error(error && error.stack || error); process.exit(1); });
|
||||
`;
|
||||
vm.runInNewContext(`${source}\n${probe}`, {...context, process});
|
||||
"""
|
||||
|
||||
|
||||
class TestGrantMode(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
done = subprocess.run(["node", "-e", PROBE, str(TEMPLATES), json.dumps(MODULES)], capture_output=True, text=True, timeout=60, check=False)
|
||||
if done.returncode != 0:
|
||||
raise AssertionError(done.stderr[-4000:])
|
||||
cls.data = json.loads(done.stdout)
|
||||
|
||||
def test_a_grant_in_select_toggles_the_selection_without_a_signature(self):
|
||||
self.assertEqual(self.data["added"]["selected"], ["review:r-green"])
|
||||
self.assertEqual(self.data["added"]["proofs"], [])
|
||||
self.assertEqual((self.data["added"]["renders"], self.data["added"]["streams"]), (1, 1))
|
||||
self.assertEqual(self.data["removed"]["selected"], [])
|
||||
self.assertEqual(self.data["removed"]["proofs"], [])
|
||||
|
||||
def test_every_selectable_kind_collects_in_select(self):
|
||||
self.assertEqual(self.data["collected"]["selected"], ["ask:a-1", "decision:d-1", "operator:operator/run", "review:r-green"])
|
||||
self.assertEqual(self.data["collected"]["proofs"], [])
|
||||
|
||||
def test_the_grant_button_shows_whether_its_item_is_selected(self):
|
||||
self.assertEqual(self.data["unpressed"]["pressed"], "false")
|
||||
self.assertTrue(self.data["unpressed"]["title"].startswith("Select: "), self.data["unpressed"])
|
||||
self.assertEqual(self.data["pressed"]["pressed"], "true")
|
||||
|
||||
def test_a_red_gate_and_a_rule_stay_direct_in_select_and_say_why(self):
|
||||
self.assertEqual(self.data["red"]["proofs"], [["review:r-red"]])
|
||||
self.assertEqual(self.data["red"]["press"]["pressed"], None)
|
||||
self.assertEqual(self.data["red"]["press"]["title"], "Grant: acts at once, a red gate is never granted in a selection")
|
||||
self.assertEqual(self.data["rule"]["accepts"], ["1123456789abcdef"])
|
||||
self.assertEqual(self.data["rule"]["proofs"], [])
|
||||
self.assertTrue(self.data["rule"]["press"]["title"].endswith(": acts at once, a rule is accepted one at a time"), self.data["rule"])
|
||||
|
||||
def test_the_tray_counts_the_selection_and_holds_its_actions(self):
|
||||
tray = self.data["tray"]
|
||||
self.assertFalse(tray["hidden"])
|
||||
self.assertTrue(tray["text"].startswith("4 selected"), tray)
|
||||
self.assertEqual(tray["labels"], ["Grant selection (4)", "Deny selection (2)", "Grant all green (1)", "Clear"])
|
||||
self.assertEqual(tray["modes"], [["direct", "false"], ["select", "true"]])
|
||||
self.assertEqual(tray["listen"], ["approval"])
|
||||
|
||||
def test_clear_empties_the_selection(self):
|
||||
self.assertEqual(self.data["cleared"]["selected"], [])
|
||||
|
||||
def test_the_switch_stores_the_mode_in_the_view_store(self):
|
||||
self.assertEqual(self.data["switched"], [["approval.mode", "direct"]])
|
||||
|
||||
def test_direct_hides_the_tray_and_grants_at_once(self):
|
||||
self.assertEqual(self.data["direct_tray"], {"hidden": True, "children": 0, "modes": ["true", "false"]})
|
||||
self.assertEqual(self.data["direct_press"]["pressed"], None)
|
||||
self.assertEqual(self.data["direct_press"]["title"], "Grant")
|
||||
self.assertEqual(self.data["direct"]["proofs"], [["review:r-green"]])
|
||||
self.assertEqual(self.data["direct"]["selected"], [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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-api.js", "page-passkey.js", "page-inbox.js", "page-console.js", "page-rule-request.js", "page-load.js"]
|
||||
MODULES = ["page-constants.js", "page-reveal.js", "page-dom.js", "page-api.js", "page-passkey.js", "page-inbox.js", "page-grant.js", "page-console.js", "page-rule-request.js", "page-load.js"]
|
||||
GONE = "operator/gui-agentbox-merge-push"
|
||||
NOTICE = "already done or removed elsewhere"
|
||||
PROBE = r"""
|
||||
@@ -95,7 +95,7 @@ const grantBoth = () => submit(state.inbox.map((item) => entryOf(item, "approve"
|
||||
(async () => {
|
||||
await scenario("run_sign_404", ["gone", "kept"], {"/api/sign": missing}, () => approveOne(state.inbox[0]));
|
||||
await scenario("run_approve_404", ["gone", "kept"], {"/api/sign": reply(200, '{"payload": null}'), "/api/inbox/approve": missing}, () => approveOne(state.inbox[0]));
|
||||
await scenario("deny_404", ["gone", "kept"], {"/api/sign": missing}, () => rejectOne(state.inbox[0]));
|
||||
await scenario("deny_404", ["gone", "kept"], {"/api/sign": missing}, () => submit([denialOf(state.inbox[0], "")], "Denial: " + short(state.inbox[0].title)));
|
||||
await scenario("dismiss_404", ["closed", "kept"], {"/api/inbox/dismiss": missing}, () => dismissJob(state.inbox[0].job));
|
||||
await scenario("rule_404", ["rule", "kept"], {["/api/rule-requests/" + items.rule.id + "/sign"]: missing}, () => acceptRule(state.inbox[0]));
|
||||
await scenario("run_409", ["gone", "kept"], {"/api/sign": reply(409, '{"id": "operator/kept", "status": "changed"}')}, () => approveOne(state.inbox[1]));
|
||||
|
||||
@@ -24,7 +24,7 @@ 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-diff.js", "page-inbox.js", "page-stream.js", "page-screens.js", "page-keyboard.js"]
|
||||
PAGE_MODULES = ["page-constants.js", "page-reveal.js", "page-dom.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"
|
||||
|
||||
@@ -35,6 +35,7 @@ FULL = {
|
||||
"home": {"pins": [{"kind": "panel", "id": "resources-hardware", "w": 12, "h": 4}, {"kind": "task", "id": "work/feature", "w": 1, "h": 12}]},
|
||||
"kanban": {"hidden": ["line"]},
|
||||
"legend": {"views": {"resources-tokens": False, "tasks/burn": True}, "tiles": {"panel:resources-hardware": False}},
|
||||
"approval": {"mode": "select"},
|
||||
}
|
||||
PIN ={"kind": "panel", "id": "resources-hardware", "w": 6, "h": 3}
|
||||
EMBEDDED = re.compile(r'<script nonce="[^"]+" id="view" type="application/json">(.*?)</script>')
|
||||
@@ -291,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": {}}})
|
||||
self.assertEqual(VIEW, {"resources": {"hidden": [], "tokens": "interval", "combined": False, "combinedHidden": []}, "burn": {"overlays": []}, "home": {"pins": []}, "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:
|
||||
@@ -342,6 +343,10 @@ class TestViewDocument(unittest.TestCase):
|
||||
"legend shown as text": changed("legend", "tiles", {"panel:resources-hardware": "false"}),
|
||||
"legend tile key without kind": changed("legend", "tiles", {"resources-hardware": False}),
|
||||
"legend tile key with a space": changed("legend", "tiles", {"panel:resources hardware": False}),
|
||||
"approval section missing": {key: value for key, value in FULL.items() if key != "approval"},
|
||||
"approval unknown key": changed("approval", "batch", True),
|
||||
"approval mode unknown": changed("approval", "mode", "auto"),
|
||||
"approval mode not text": changed("approval", "mode", True),
|
||||
}
|
||||
for name, doc in cases.items():
|
||||
with self.subTest(case=name), self.assertRaises(ToolError):
|
||||
|
||||
@@ -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-diff.js", "page-rule-request.js", "page-inbox.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", "ancestry.js", "page-reveal.js", "page-dom.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)
|
||||
|
||||
Reference in new issue
Block a user