feat: hub and skills requirements 032 to 063

Hub: send in the field (032), coherent speak box (033), stream head band (034), Match at full width with its pile (035, 036), Home without the outer box (037), badge to Match (038), rejects that survive a changed or withdrawn card (039), the release card (040), code marks in the review diff (041), why Deny is off (042), the undo window clock (043), widgets without inner boxes (044), the Artifacts head on one line (045), accepting a red gate's risk (046), one code box (047), done rows greyed and folded (048), one control height (049), menus that stay open (050), radio settings in the Device card (051), bubbles beside the modes (052), agent settings on every face and name (053), pin only by menu (054), WASD in Match (055), the flowing card edge (056), Schedules in Controls (057) and the hub poll cost (059).

Skills: the coach leaves for its own repository kevinveenbirkenbach/coach (058; test_install pins its four skills in skills-lock.json and stays red until that repository is published and pinned), hooks and timers start fewer processes (060), council files on hot paths stay bounded and mirror by marker instead of mtime (061), scripts and hooks hand agents less output (062), and block.py builds the commit table and message block in one run (063). Requirement documents 032 to 063 with their implementation amendments.

MEDUSA false positives accepted after kvb-think-criticize (36 lines): MM-SCAN-058 (pla inside replace or plan), JB-SCAN-616/641 (the local clip helper), CODEGEN-SCAN-001 (drop-in paths), CGS-SCAN-029 (systemctl argv from constants), CGS-SCAN-040 (runner poll loop), FLA-SCAN-055 (feedback), WM-SCAN-354, AI-BACKDOOR-006, GENAI-SCAN-1270, B604 (runner shell path for passkey-verified commands), TC004, EXA002, EXA006, EXA010 and WEB-SSRF.

🎯 Fix: 92 %
💥 Break: 8 %
💸 Tokens: 89 %
⏱️ Velocity: –
🛡️ Security: ~100 %
🏆 Score: 95
🚦 Gate: ⛔ break 8 % > 5

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-26 08:44:15 +00:00
1 parent e5fd70e183
commit 0fad1bfae3
265 files changed
+10434 -2242

No files matched your search

+1 -1
View File
@@ -10,7 +10,7 @@ import {join} from "node:path";
const [binary, planFile] = process.argv.slice(2);
const plan = JSON.parse(readFileSync(planFile, "utf8"));
const profile = mkdtempSync(join(tmpdir(), "bidi-"));
writeFileSync(join(profile, "user.js"), ['user_pref("media.navigator.streams.fake", true);', 'user_pref("media.navigator.permission.disabled", true);', ""].join("\n"));
writeFileSync(join(profile, "user.js"), ['user_pref("media.navigator.streams.fake", true);', 'user_pref("media.navigator.permission.disabled", true);', 'user_pref("media.volume_scale", "0.0");', ""].join("\n"));
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const KEYS = {Enter: "", Tab: "", ArrowLeft: "", ArrowRight: ""};
const port = await new Promise((resolve) => {
+1 -1
View File
@@ -15,7 +15,7 @@ const profile = mkdtempSync(join(tmpdir(), "cdp-"));
// --no-sandbox: the agent sandbox already forbids the user namespaces Chromium's own sandbox needs.
// --enable-unsafe-swiftshader: without a GPU, headless Chromium gives WebGL only through SwiftShader, which it no longer enables by itself.
// --ignore-certificate-errors: the https station fixtures use a throwaway self-signed certificate.
const flags = ["--headless", "--no-sandbox", "--disable-gpu", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--ignore-certificate-errors", "--use-fake-device-for-media-stream", "--use-fake-ui-for-media-stream", "--no-first-run", "--no-default-browser-check", "--hide-scrollbars", `--user-data-dir=${profile}`, "--remote-debugging-port=0", "about:blank"];
const flags = ["--headless", "--no-sandbox", "--disable-gpu", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--ignore-certificate-errors", "--use-fake-device-for-media-stream", "--use-fake-ui-for-media-stream", "--mute-audio", "--no-first-run", "--no-default-browser-check", "--hide-scrollbars", `--user-data-dir=${profile}`, "--remote-debugging-port=0", "about:blank"];
const browser = spawn(binary, flags, {stdio: ["ignore", "ignore", "pipe"]});
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const KEYS = {Enter: [13, "\r"], Tab: [9, ""], ArrowLeft: [37, ""], ArrowRight: [39, ""]};
+9 -9
View File
@@ -25,7 +25,7 @@ RUN_DONE = """(async () => {@HELPERS@@LABELS@
await until(() => document.querySelector("#main .console").dataset.status === "done", 20000);
await sleep(500);
const lines = out().textContent.trim().split("\\n");
return {done: line(), last: lines[lines.length - 1], lines: lines.length, followed: atEnd(), actions: all(".item-actions button", out().closest("li")).map(name)};
return {done: line(), last: lines[lines.length - 1], lines: lines.length, followed: atEnd(), actions: all(":is(.item-actions, .code-foot) button", out().closest("li")).map(name)};
})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS)
INBOX_PICK = """(async () => {@HELPERS@
navigator.credentials.get = @SIGNS@ ? navigator.credentials.get.bind(navigator.credentials) : () => Promise.reject(new DOMException("The operator canceled.", "NotAllowedError"));
@@ -50,14 +50,15 @@ INBOX_PICK = """(async () => {@HELPERS@
last.scrollIntoView({block: "center"});
await sleep(300);
const title = text(last.querySelector(".command code"));
const ref = last.dataset.ref;
await cursorTo(ref);
await sleep(300);
const before = scroller.scrollTop;
last.querySelector("input").click();
await pressKey("x");
await sleep(300);
const after = scroller.scrollTop;
const holder = document.activeElement && document.activeElement.closest("li");
const focused = Boolean(holder && text(holder.querySelector(".command code")) === title && document.activeElement.checked);
all("#main .inbox-list > li").find((li) => li.textContent.includes("pick a name")).querySelector("input").click();
await sleep(300);
const focused = Boolean(document.querySelector(`#main .inbox-list > li.cursor[data-ref="${ref}"]`));
await selectRow(all("#main .inbox-list > li").find((li) => li.textContent.includes("pick a name")).dataset.ref);
const buttons = all("#grant-bar .grant-split button").map(name);
document.querySelector("#grant-bar details.grant-menu > summary").click();
await until(() => document.querySelector("#grant-bar details.grant-menu[open]"), 2000);
@@ -78,7 +79,8 @@ LAYOUT = """(async () => {@HELPERS@@LABELS@
await until(() => document.querySelector("#main .console") && rowOf("Rule request"), 8000);
const rule = rowOf("Rule request");
return {
kinds: all("#main .inbox-list > li").map((li) => text(li.querySelector(".pill"))),
kinds: all("#main .inbox-list > li").map((li) => all(".msg-meta .pill", li).map(text).find((label) => label !== "done")),
done: all("#main .inbox-list > li[data-done]").length,
splits: all("#main .deny-split").map((group) => all("button", group).map(name)),
console: line(),
followed: atEnd(),
@@ -210,8 +212,6 @@ CHOICE_SEND = """(async () => {@HELPERS@@WATCH@
return {picked, counted, opened, runs, fields: all("textarea, input:not([type=checkbox])", bar()).length, ...fits()};
})()""".replace("@HELPERS@", HELPERS).replace("@WATCH@", WATCH)
CHOICE_ANSWER = """(async () => {@HELPERS@@WATCH@
bar().querySelector("summary").click();
await sleep(200);
const closed = [bar().open, all("button[data-channel]", bar()).filter((button) => button.checkVisibility()).length];
const card = await until(() => all("#main .inbox-list > li").find((li) => li.textContent.includes("@QUESTION@")), 8000);
if (!card) {
+24
View File
@@ -44,6 +44,13 @@ HELPERS = """
const all = (selector, root) => [...(root || document).querySelectorAll(selector)];
const text = (node) => (node ? node.textContent.trim() : null);
const name = (node) => (node ? node.getAttribute("aria-label") || text(node) : null);
const streamShowsAll = async () => {
const chip = await until(() => all("#main .chip").find((node) => text(node) === "only waiting"), 8000);
if (chip && chip.getAttribute("aria-pressed") === "true") {
chip.click();
await sleep(1500);
}
};
const toolbarRows = () => {
const bar = document.querySelector('#main [role="toolbar"][aria-label="Tasks"]');
const boxes = bar ? [...bar.children].filter((node) => node.getClientRects().length).map((node) => node.getBoundingClientRect()).sort((a, b) => a.top - b.top) : [];
@@ -58,6 +65,23 @@ HELPERS = """
}
return rows;
};
const pressKey = async (key) => {
document.body.dispatchEvent(new KeyboardEvent("keydown", {key, bubbles: true, cancelable: true}));
await sleep(60);
};
const cursorTo = async (ref) => {
const row = () => document.querySelector(`#main .inbox-list > li[data-ref="${ref}"]`);
const cursor = () => document.querySelector("#main .inbox-list > li.cursor");
for (let steps = 0; steps < 50 && row() && cursor() !== row(); steps += 1) {
await pressKey(Number(row().dataset.index) > Number(cursor() ? cursor().dataset.index : -1) ? "j" : "k");
}
return Boolean(row() && cursor() === row());
};
const selectRow = async (ref) => {
await cursorTo(ref);
await pressKey("x");
await sleep(200);
};
const taskLayout = () => all("#main .graph.tasks > *").map((node) => (node.matches('[role="toolbar"]') ? "toolbar" : node.matches('[aria-label="Task filters"]') ? "chips" : "body"));
const screenShown = async (ms) => {
const shown = await until(() => {
+4 -3
View File
@@ -6,7 +6,8 @@ PROBE = """(async () => {@HELPERS@
await screenShown(8000);
await until(() => !(text(document.querySelector("#main .space-note")) || "").startsWith("Loading") && !all("#main .empty h2").some((title) => text(title).endsWith("…")), 8000);
const badge = (button) => {
const found = button.querySelector(".badge");
const next = button.nextElementSibling;
const found = button.querySelector(".badge") || (next && next.matches("a.badge") ? next : null);
return found && !found.hidden ? text(found) : null;
};
const icons = all("svg.bi").filter((svg) => !svg.closest(".sprite"));
@@ -95,7 +96,7 @@ ACTIONS = """(async () => {@HELPERS@
await sleep(500);
found.popup = all("#popup input[type=radio]").map((input) => [input.value, input.checked]);
found.popupUnlabelled = all("#popup svg.bi").map((svg) => svg.parentElement).filter((owner) => !text(owner) && !(owner.getAttribute("title") && owner.getAttribute("aria-label"))).length;
found.centred = [document.getElementById("popup").open, document.querySelector("#popup .leader line").getAttribute("display")];
found.leader = [document.getElementById("popup").open, document.querySelector("#popup .leader line").getAttribute("display")];
return found;
})()""".replace("@HELPERS@", HELPERS)
POPUPS = """
@@ -140,7 +141,7 @@ POPUP_ORBIT = """(async () => {@HELPERS@@POPUPS@
await sleep(400);
const art = box.querySelector(".popup-head .avatar.big");
const face = art ? {key: art.dataset.face, svg: Boolean(art.querySelector("svg.face-art .mouth")), text: art.textContent} : null;
const shown = {...opened(), ...look(pick()), sections: all("h3", box).map((head) => head.firstChild.textContent), composer: Boolean(box.querySelector("form textarea")), offices: text(box.querySelector(".popup-body p")), face};
const shown = {...opened(), ...look(pick()), sections: all("h3", box).map((head) => head.firstChild.textContent), composer: Boolean(box.querySelector("form textarea")), offices: text(box.querySelector(".popup-body > div:not(.agent-settings) > p")), face};
const gone = await away(pick);
click(pick());
await sleep(300);
+2 -1
View File
@@ -47,7 +47,8 @@ POP = """(async () => {@HELPERS@@PROBES@
[top, bottom] = [Math.max(top, box(node).top), Math.min(bottom, box(node).bottom)];
}
}
const room = {above: Math.floor(box(fold).top - top), below: Math.floor(bottom - box(fold).bottom), need: Math.floor(Math.min(layer.scrollHeight + layer.offsetHeight - layer.clientHeight, cap))};
const frame = box(layer.offsetParent || fold);
const room = {above: Math.floor(frame.top - top), below: Math.floor(bottom - frame.bottom), need: Math.floor(Math.min(layer.scrollHeight + layer.offsetHeight - layer.clientHeight, cap))};
const opened = {open: fold.open, side: fold.dataset.side, height: Math.round(box(layer).height), cap: Math.ceil(cap), ...room, outside: outside(layer), whole};
layer.querySelector(".station button").focus();
document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));
+14 -1
View File
@@ -70,7 +70,20 @@ PROBES = """
node.click();
};
const box = (node) => node.getBoundingClientRect();
const ownStar = (owner) => all(".star", owner).find((node) => node.closest("[data-panel], [data-item]") === owner) || null;
const pinByMenu = async (owner) => {
const edge = box(owner);
owner.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, button: 2, clientX: Math.round(edge.left + 4), clientY: Math.round(edge.top + 4)}));
const menu = await until(() => document.querySelector(".ctx-menu:not([hidden])"), 3000);
const item = menu ? all('[role="group"][data-scope="element"] [role="menuitem"]', menu).find((node) => text(node.querySelector(".ctx-label")) === "Pin to Home") : null;
if (item) {
item.click();
} else if (menu) {
menu.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true, cancelable: true}));
}
await sleep(250);
const target = Panels.targetOf(owner);
return String((ViewStore.get("home.pins") || []).some((pin) => pin.kind === target.kind && pin.id === target.id));
};
const openSpot = async () => {
await until(() => typeof Nav === "object" && document.getElementById("radio-spot"), 8000);
const toggle = document.getElementById("radio-open");
+4 -12
View File
@@ -39,9 +39,6 @@ LAYOUT = """(async () => {@HELPERS@@PROBES@
});
const [device, speak, history] = ["radio-device", "radio-speak", "radio-log"].map((id) => box(spot.querySelector(`[data-panel="${id}"]`)));
const owners = [spot, ...all("[data-panel]", spot)];
const controls = all('button, input, select, textarea, summary, [role="tab"]', spot).filter((node) => shown(node) && !node.classList.contains("star"));
const overlap = (a, b) => Math.max(0, Math.min(a.right, b.right) - Math.max(a.left, b.left)) * Math.max(0, Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top));
const covered = owners.map(ownStar).filter(Boolean).flatMap((star) => controls.filter((node) => !node.contains(star) && overlap(box(star), box(node)) > 1).map((node) => `${star.title} over ${node.getAttribute("aria-label") || text(node)}`));
const knobs = all(".radio-knobs .knob-row", spot).map((row) => Math.round(box(row.querySelector(".knob-label")).left));
return {
page: [document.documentElement.scrollWidth, innerWidth], tall: [document.documentElement.scrollHeight, innerHeight, Math.round(box(spot).height)],
@@ -57,7 +54,7 @@ LAYOUT = """(async () => {@HELPERS@@PROBES@
sliver: Math.min(...avatars.map((row) => row.sliver)),
order: {stacked: device.bottom <= speak.top + 1 && speak.bottom <= history.top + 1 && Math.abs(device.left - speak.left) < 2, beside: device.right <= speak.left && speak.bottom <= history.top + 1 && Math.abs(speak.left - history.left) < 2},
labels: [...new Set(knobs)].length,
stars: owners.map((owner) => [owner.dataset.panel, Boolean(ownStar(owner))]), covered,
pinnable: owners.map((owner) => [owner.dataset.panel, Boolean(Panels.targetOf(owner))]), stars: all(".star, .star-row", spot).length,
stations: [Boolean(spot.querySelector("details.radio-station")), spot.querySelector("details.radio-station").open],
};
})()"""
@@ -124,12 +121,7 @@ HOME = """(async () => {@HELPERS@@PROBES@
const owners = Object.fromEntries(@PARTS@.map((id) => [id, id === "radio" ? spot : spot.querySelector(`[data-panel="${id}"]`)]));
const pressed = {};
for (const [id, owner] of Object.entries(owners)) {
const star = ownStar(owner);
if (star.getAttribute("aria-pressed") !== "true") {
star.click();
await sleep(250);
}
pressed[id] = star.getAttribute("aria-pressed");
pressed[id] = await pinByMenu(owner);
}
await until(() => (ViewStore.get("home.pins") || []).length === 4, 5000);
const stored = (ViewStore.get("home.pins") || []).map((pin) => [`${pin.kind}:${pin.id}`, pin.w, pin.h]);
@@ -169,7 +161,7 @@ HOME = """(async () => {@HELPERS@@PROBES@
speak: [Boolean(tile("radio-speak").querySelector("form.composer textarea")), tile("radio-speak").querySelectorAll("form.composer select option").length > 0],
log: [tile("radio-log").querySelectorAll(".radio-row").length, tile("radio").querySelectorAll(".radio-row").length, document.querySelectorAll("#radio-spot .radio-row").length],
gone: all("#main .home-tile.gone").length,
stars: all("#main .home-tile .home-body .star").length,
stars: all("#main .star, #main .star-row").length,
ids: all("#main .home-tile .home-body [id]").map((node) => node.id).filter((id) => !id.startsWith("mic-field-")),
};
const count = (id) => tile(id).querySelectorAll(".radio-row").length;
@@ -332,7 +324,7 @@ SPOT = """(async () => {@HELPERS@@PROBES@@SPEAKING@
const found = await cue("@CUE@");
await sleep(300);
states.speech = {...measure(), who: found && !found.error ? found.who : found};
const stop = display.querySelector("button");
const stop = display.querySelector('button[aria-label="Stop speaking"]');
if (stop) {
stop.click();
}
+19 -8
View File
@@ -193,15 +193,26 @@ LOG = """(async () => {@HELPERS@@RADIO@
all(".radio-filters button", spot).find((button) => name(button) === "Clear filters").click();
await sleep(150);
const clearedChips = [chips(), search().value, rows().length];
const muteOf = () => spot.querySelector(".radio-row .radio-mute");
const sender = name(muteOf());
muteOf().click();
const faceOf = () => spot.querySelector(".radio-row .radio-sender");
const sender = name(faceOf());
faceOf().click();
const switches = await until(() => document.getElementById("popup").open && document.querySelector("#popup .agent-settings"), 4000);
const key = switches ? switches.dataset.agent : "";
const stored = async () => ((await (await fetch("/api/state", {cache: "no-store"})).json()).settings.agents || {})[key] || null;
const flip = async (what, want) => {
switches.querySelector(`[data-switch="${what}"]`).click();
await until(() => switches.querySelector(`[data-switch="${what}"]`).getAttribute("aria-pressed") === want, 4000);
};
await flip("sound", "false");
await flip("aloud", "false");
await until(() => faceOf().dataset.quiet === "true", 4000);
const muted = [sender, faceOf().dataset.quiet, await stored(), Boolean(switches)];
await flip("sound", "true");
await flip("aloud", "true");
await until(() => faceOf().dataset.quiet === "false", 4000);
const unmuted = [faceOf().dataset.quiet, await stored()];
all("#popup .popup-head button").find((button) => name(button) === "Close").click();
await sleep(150);
const stored = () => JSON.parse(localStorage.getItem("kvb-orchestrator.radio") || "{}").muted || [];
const muted = [sender, muteOf().getAttribute("aria-pressed"), stored().length, document.getElementById("popup").open];
muteOf().click();
await sleep(150);
const unmuted = [muteOf().getAttribute("aria-pressed"), stored().length];
spot.querySelector(".radio-row .radio-pick").click();
const full = await until(() => document.getElementById("popup").open && document.querySelector("#popup .radio-full"), 4000);
const opened = [document.getElementById("popup").open, text(full)];
+1 -1
View File
@@ -83,7 +83,7 @@ SWEEP = """(async () => {@HELPERS@
}
return top < -1 || bottom > innerHeight + 1 || left < -1 || right > innerWidth + 1 ? "outside the window" : null;
};
const nodes = all("#main *").filter((node) => !node.ownerSVGElement && !node.closest("canvas") && shown(node));
const nodes = all("#main *").filter((node) => !node.ownerSVGElement && !node.closest("canvas, [inert]") && shown(node));
const cut = nodes.map((node) => [path(node), clipped(node)]).filter(([, why]) => why);
const owner = (node) => {
for (let up = node.parentElement; up && up !== main; up = up.parentElement) {
+202
View File
@@ -0,0 +1,202 @@
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_radio_receipts_e2e as rr
from kvb_orchestrator import settings
from kvb_orchestrator.presence import SNAPSHOT
OUT = Path(os.environ.get("E2E_OUT", "/tmp/agent-settings-shots"))
WIDTH, HEIGHT = 1366, 900
SILENT = """() => {
try {
localStorage.setItem("kvb-orchestrator.radio", JSON.stringify({mode: "silence", classes: ["mayday", "security"]}));
} catch (error) {
return;
}
}"""
KIT = """
const SKIP = ".match-peek, .popup-head, .ctx-menu, .palette, #popup, .chip-check";
const OPENERS = "button.agent-link, button.agent-face, button.reader, button.radio-sender, button.org-holder";
const fresh = async () => (await (await fetch("/api/state", {cache: "no-store"})).json());
const audit = async (root) => {
const keys = (await fresh()).people || {};
const faces = all(".avatar[data-face]", root).filter((node) => node.getClientRects().length && keys[node.dataset.face] && !node.closest(SKIP));
return {count: faces.length, loose: faces.filter((node) => !node.closest(OPENERS)).map((node) => `${node.dataset.face} in ${node.parentElement.className}`)};
};
const closePopup = async () => {
const close = all("#popup .popup-head button").find((node) => node.getAttribute("aria-label") === "Close");
if (close) {
close.click();
}
await until(() => !document.getElementById("popup").open, 4000);
};
const opens = async (button) => {
if (!button) {
return null;
}
button.click();
const group = await until(() => document.getElementById("popup").open && document.querySelector("#popup .agent-settings[data-agent]"), 4000);
const found = group ? {agent: group.dataset.agent, switches: all("[data-switch]", group).map((node) => [node.dataset.switch, node.getAttribute("aria-pressed"), text(node)])} : null;
await closePopup();
return found;
};
const shown = (selector) => all(selector).find((node) => node.getClientRects().length) || null;
"""
STREAM = """(async () => {@HELPERS@@KIT@
await screenShown(8000);
location.hash = "#stream";
await streamShowsAll();
await until(() => shown("#main .entry button.agent-link") && shown("#main .entry button.reader"), 10000);
await sleep(400);
const found = {
audit: await audit(document.getElementById("main")),
entry: await opens(shown("#main .entry button.agent-link")),
reader: await opens(shown("#main .entry button.reader")),
};
location.hash = "#stream/inbox";
await until(() => shown("#main .inbox-list button.agent-link"), 10000);
return {...found, waiting: await opens(shown("#main .inbox-list button.agent-link"))};
})()"""
TASKS = """(async () => {@HELPERS@@KIT@
location.hash = "#tasks";
await until(() => shown("#main .who button.agent-link"), 10000);
await sleep(400);
return {audit: await audit(document.getElementById("main")), worker: await opens(shown("#main .who button.agent-link"))};
})()"""
RADIO = """(async () => {@HELPERS@@KIT@
location.hash = "#stream/radio";
const spot = await until(() => document.getElementById("radio-spot") && shown("#radio-spot .radio-row .radio-sender") && document.getElementById("radio-spot"), 10000);
await sleep(400);
return {audit: spot ? await audit(spot.querySelector(".radio-log")) : null, sender: await opens(shown("#radio-spot .radio-row .radio-sender"))};
})()"""
BUBBLES = """(async () => {@HELPERS@@KIT@
const everything = document.querySelector('#radio-spot .radio-tabs [data-tab="all"]');
if (everything && everything.getAttribute("aria-selected") !== "true") {
everything.click();
await sleep(400);
}
const row = await until(() => all("#radio-spot .radio-row").find((node) => node.querySelector(".radio-sender") && node.querySelector(".radio-route") && text(node.querySelector(".radio-route")).startsWith("Stage ")), 10000);
if (!row) {
return {error: "no radio row from Stage"};
}
row.querySelector(".radio-sender").click();
const group = await until(() => document.getElementById("popup").open && document.querySelector("#popup .agent-settings[data-agent]"), 4000);
if (!group) {
return {error: "no agent settings for Stage"};
}
const agent = group.dataset.agent;
const toggle = () => group.querySelector('[data-switch="bubbles"]');
toggle().click();
const pressed = Boolean(await until(() => toggle().getAttribute("aria-pressed") === "false", 6000));
const end = Date.now() + 6000;
let stored = null;
while (Date.now() < end) {
stored = ((await fresh()).settings.agents || {})[agent] || null;
if (stored && stored.bubbles === false) {
break;
}
await sleep(200);
}
await closePopup();
const other = await until(() => document.querySelector('.speech-bubble:not([data-who="' + agent + '"])'), 15000);
const seen = new Set();
const watchUntil = Date.now() + 3000;
while (Date.now() < watchUntil) {
all(".speech-bubble").forEach((node) => seen.add(node.dataset.who));
await sleep(100);
}
const quiet = await until(() => all("#radio-spot .radio-row").find((node) => text(node.querySelector(".radio-route") || node).startsWith("Stage ") && node.querySelector(".radio-sender")), 4000);
quiet.querySelector(".radio-sender").click();
const again = await until(() => document.getElementById("popup").open && document.querySelector("#popup .agent-settings[data-agent]"), 4000);
again.querySelector('[data-switch="bubbles"]').click();
await until(() => again.querySelector('[data-switch="bubbles"]').getAttribute("aria-pressed") === "true", 6000);
await sleep(600);
const back = ((await fresh()).settings.agents || {})[agent] || null;
await closePopup();
return {agent, pressed, stored, other: other ? other.dataset.who : null, seen: [...seen], back};
})()"""
def fill(probe: str) -> str:
return probe.replace("@HELPERS@", base.HELPERS).replace("@KIT@", KIT)
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestAgentSettings(base.OrchestratorE2ECase):
mark = rr.TestRadioReceipts.mark
sight = rr.TestRadioReceipts.sight
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
file =self.state / "settings.json"
file.write_text(json.dumps({**settings.SETTINGS, "bubbles": True}), encoding="utf-8")
held = self.httpd.hub.settings
with held.lock:
held.current = settings.Settings(file).get()
self.sent = False
self.present()
self.mark("s2", time.time())
self.sight()
self.beside(self.live_rows)
def present(self) -> None:
payload = {"written": time.time(), "sessions": {"s1": {"name": "Skills session", "running": True}, "s2": {"name": "Stage", "running": True}}}
written = self.state / f".{SNAPSHOT}.e2e"
written.write_text(json.dumps(payload), encoding="utf-8")
os.replace(written, self.state / SNAPSHOT)
def live_rows(self) -> None:
self.present()
if self.sent or self.httpd.hub.settings.get()["agents"].get("s2", {}).get("bubbles") is not False:
return
self.sent = True
now = time.time()
rows = [
{"ts": now, "from": "Stage", "to": [], "text": "stage rotates the keys quietly", "class": "security", "v": 2},
{"ts": now + 0.001, "from": "Skills session", "to": [], "text": "skills rotates the keys aloud", "class": "security", "v": 2},
]
with (self.council / "news.jsonl").open("a", encoding="utf-8") as handle:
handle.write(self.jsonl(rows))
def test_chromium_opens_every_agent_from_its_face_or_name_and_switches_its_own_bubbles(self):
steps = [
{"width": WIDTH, "height": HEIGHT, "url": f"{self.base}?agents#stream", "wait": 1200, "probe": fill(STREAM), "shot": str(OUT / "chromium-stream.png")},
{"width": WIDTH, "height": HEIGHT, "url": None, "wait": 0, "probe": fill(TASKS), "shot": str(OUT / "chromium-tasks.png")},
{"width": WIDTH, "height": HEIGHT, "url": None, "wait": 0, "probe": fill(RADIO), "shot": str(OUT / "chromium-radio.png")},
{"width": WIDTH, "height": HEIGHT, "url": None, "wait": 0, "probe": fill(BUBBLES), "shot": str(OUT / "chromium-bubbles.png")},
]
data = self.drive(steps, self.authenticator(), init=SILENT)
(OUT / "chromium-agent-settings.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual(data["errors"], [])
stream, tasks, radio, bubbles = data["results"]
switches = [["sound", "true", "Sound"], ["aloud", "true", "Read aloud"], ["bubbles", "true", "Bubbles"]]
for name, found in (("stream", stream), ("tasks", tasks), ("radio", radio)):
with self.subTest(screen=name):
self.assertNotIn("error", found, found)
self.assertGreater(found["audit"]["count"], 0, found)
self.assertEqual(found["audit"]["loose"], [], found)
for found in (stream["entry"], stream["waiting"], stream["reader"], tasks["worker"], radio["sender"]):
self.assertIsNotNone(found, data["results"])
self.assertEqual(found["switches"], switches, found)
self.assertNotIn("error", bubbles, bubbles)
self.assertEqual((bubbles["agent"], bubbles["pressed"], bubbles["stored"]), ("s2", True, {"sound": True, "aloud": True, "bubbles": False}), bubbles)
self.assertEqual(bubbles["other"], "s1", bubbles)
self.assertNotIn("s2", bubbles["seen"], bubbles)
self.assertIsNone(bubbles["back"], bubbles)
self.assertEqual(self.httpd.hub.settings.get()["agents"], {})
if __name__ == "__main__":
unittest.main()
+87
View File
@@ -0,0 +1,87 @@
from __future__ import annotations
import json
import os
import shutil
import sys
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
from hub_case import HubCase
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-045-shots"))
WIDTHS = ((1920, 1080), (1366, 768), (390, 844))
HEAD = """(async () => {@HELPERS@
const head = await until(() => {
const found = document.querySelector("#main .art-head");
return found && found.querySelector(".art-count").textContent && found.querySelector(".delete-blocked") ? found : null;
}, 10000);
if (!head) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
await sleep(300);
const items = (node) => (getComputedStyle(node).display === "contents" ? [...node.children].flatMap(items) : [node]);
const shown = [...head.children].flatMap(items).filter((child) => child.getClientRects().length);
const boxes = shown.map((child) => child.getBoundingClientRect()).sort((a, b) => a.top - b.top);
let [lines, bottom] = [0, -Infinity];
for (const box of boxes) {
if (box.top >= bottom - 1) {
lines += 1;
bottom = box.bottom;
} else {
bottom = Math.max(bottom, box.bottom);
}
}
const look = getComputedStyle(head);
const inner = head.clientHeight - parseFloat(look.paddingTop) - parseFloat(look.paddingBottom);
const row = Math.max(...shown.map((child) => child.getBoundingClientRect().height));
const count = head.querySelector(".art-count");
const chip = head.querySelector(".delete-blocked");
const every = head.querySelector('button[aria-label="Delete all merged"]');
return {
lines, inner: Math.round(inner), row: Math.round(row), overflow: head.scrollWidth > head.clientWidth + 1,
count: {text: text(count), title: count.title, ellipsis: getComputedStyle(count).textOverflow, nowrap: getComputedStyle(count).whiteSpace},
chip: {title: chip.title, beside: chip.parentElement === every.closest(".why-off").parentElement},
every: {disabled: every.disabled, wrapper: every.closest(".why-off").title},
wide: document.documentElement.scrollWidth > innerWidth + 1,
};
})()"""
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestArtifactsHead(HubCase):
drive = base.OrchestratorE2ECase.drive
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
self.write_fixture("branch-tree-tokenless.json")
data = json.loads(self.tree_file.read_text(encoding="utf-8"))
data["repos"] = [repo for repo in data["repos"] if repo["forge"] != "none"]
self.tree_file.write_text(json.dumps(data), encoding="utf-8")
def test_chromium_keeps_the_artifacts_head_on_one_line_from_1024_px_and_moves_delete_blocked_into_a_chip(self):
steps = [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}#artifacts/tree", "wait": 1500, "probe": HEAD.replace("@HELPERS@", base.HELPERS), "shot": str(OUT / f"chromium-{width}-artifacts-head.png")} for width, height in WIDTHS]
data = self.drive(steps, None)
(OUT / "chromium-artifacts-head.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], [])
reason = "no GitHub token in the Secret Service"
for (width, _), found in zip(WIDTHS, data["results"], strict=True):
with self.subTest(width=width):
self.assertNotIn("error", found, found)
self.assertEqual((found["overflow"], found["wide"]), (False, False), found)
self.assertLessEqual(found["lines"], 1 if width >= 1024 else 2, found)
if width >= 1024:
self.assertLessEqual(abs(found["inner"] - found["row"]), 2, found)
self.assertRegex(found["count"]["text"], r"^\d+ repositories · as of \d\d:\d\d$")
self.assertEqual((found["count"]["title"], found["count"]["ellipsis"], found["count"]["nowrap"]), (found["count"]["text"], "ellipsis", "nowrap"), found)
self.assertEqual(found["chip"], {"title": f"Delete blocked: {reason}", "beside": True}, found)
self.assertEqual(found["every"], {"disabled": True, "wrapper": f"Delete all merged blocked: {reason}"}, found)
if __name__ == "__main__":
unittest.main()
+103
View File
@@ -0,0 +1,103 @@
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
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-038-shots"))
WIDTHS = tuple(size for size in base.WIDTHS if size[0] in (1366, 390))
BADGE = """
const tasks = () => document.getElementById("tab-tasks");
const badge = () => {
const next = tasks().nextElementSibling;
return next && next.matches("a.badge") && !next.hidden ? next : null;
};
"""
CLICK = """(async () => {@HELPERS@@BADGE@
await screenShown(8000);
const count = await until(badge, 8000);
if (!count) {
return {error: "no count"};
}
const [icon, edge, own] = [tasks().querySelector("svg").getBoundingClientRect(), count.getBoundingClientRect(), tasks().getBoundingClientRect()];
const pad = parseFloat(getComputedStyle(tasks()).paddingLeft);
const gap = parseFloat(getComputedStyle(tasks()).columnGap);
const found = {
text: text(count), label: count.getAttribute("aria-label"), nested: Boolean(tasks().querySelector(".badge")),
icon: Math.round((icon.left - own.left - pad) * 10) / 10, count: Math.round((edge.left - icon.right - gap) * 10) / 10,
};
count.click();
found.hash = await until(() => location.hash === "#tasks/match" && location.hash, 4000);
location.hash = "stream";
await screenShown(8000);
tasks().click();
await sleep(400);
found.icon_hash = location.hash;
return found;
})()"""
FOCUS = """(async () => {@HELPERS@@BADGE@
await screenShown(8000);
const count = await until(badge, 8000);
count.focus();
return {focused: document.activeElement === count};
})()"""
READ = """(async () => {@HELPERS@
await sleep(400);
return {hash: location.hash};
})()"""
def probe(template: str) -> str:
return template.replace("@HELPERS@", base.HELPERS).replace("@BADGE@", BADGE)
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestBadgeToMatch(HubCase):
drive = base.OrchestratorE2ECase.drive
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
self.claim("s1", "Skills")
decided = self.tool("decision_request", {"question": "Open the Match view?", "options": hub_support.OPTIONS, "agent": "Skills", "recommended": ""})
self.assertFalse(decided["isError"], decided)
self.snapshot()
self.page_url = f"http://localhost:{self.port}/"
def test_chromium_opens_match_from_the_count_by_click_and_enter_and_tasks_from_the_icon(self):
steps = []
for width, height in WIDTHS:
at = {"width": width, "height": height}
steps += [
{**at, "url": f"{self.page_url}?{width}-click#stream", "wait": 1200, "probe": probe(CLICK), "shot": str(OUT / f"chromium-{width}-badge-match.png")},
{**at, "url": f"{self.page_url}?{width}-key#stream", "wait": 1200, "probe": probe(FOCUS), "shot": None},
{**at, "url": None, "wait": 0, "keys": ["Enter"], "probe": probe(READ), "shot": None},
]
data = self.drive(steps, None)
(OUT / "chromium-badge-match.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual(data["errors"], [])
results = iter(data["results"])
for width, _ in WIDTHS:
click, focus, read = next(results), next(results), next(results)
with self.subTest(width=width):
self.assertNotIn("error", click, click)
self.assertEqual((click["text"], click["label"], click["nested"]), ("1", "1 open operator task: open Match", False), click)
self.assertLessEqual(abs(click["icon"]), 1, click)
self.assertLessEqual(abs(click["count"]), 1, click)
self.assertEqual(click["hash"], "#tasks/match", click)
self.assertTrue(click["icon_hash"].startswith("#tasks") and not click["icon_hash"].startswith("#tasks/match"), click)
self.assertEqual((focus["focused"], read["hash"]), (True, "#tasks/match"), (focus, read))
if __name__ == "__main__":
unittest.main()
+23 -5
View File
@@ -19,6 +19,7 @@ from hub_case import HubCase
OUT = Path(os.environ.get("E2E_OUT", "/tmp/box-heads-shots"))
VIEWS = {
"stream": "Stream",
"tasks/match": "Match",
"tasks/list": "Tasks",
"tasks/board": "Tasks",
@@ -52,10 +53,19 @@ BAND = """(async () => {@HELPERS@@BUTTON@
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));
const shown = [...head.querySelectorAll(":scope > *, :scope > .box-slot > *")].filter((node) => node.getClientRects().length);
const tops = shown.map((node) => Math.round(node.getBoundingClientRect().top));
const control = ':is(.btn, .field, select, input[type="search"], input[type="text"], .segmented, .chip, .menu > summary, .mic-line)';
const controls = all(control, head).filter((node) => node.getClientRects().length && !node.closest(".menu-box") && !node.parentElement.closest(".mic-line, .segmented"))
.map((node) => [node.getAttribute("aria-label") || node.className || node.tagName, Math.round(node.getBoundingClientRect().height * 10) / 10]);
const centers = shown.map((node) => {
const box = node.getBoundingClientRect();
return Math.round((box.top + box.height / 2) * 10) / 10;
});
return {
controls, centers, token: getComputedStyle(document.documentElement).getPropertyValue("--control-h").trim(),
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),
edges: [box.top - outer.top - parseFloat(style.borderTopWidth), box.left - outer.left - parseFloat(style.borderLeftWidth), outer.left + main.clientLeft + main.clientWidth - 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,
};
@@ -92,9 +102,11 @@ EDGE = """(async () => {@HELPERS@
card.dataset.pattern = pattern;
await sleep(60);
const shown = getComputedStyle(card);
const edge = getComputedStyle(card, "::before");
const after = getComputedStyle(head, "::before");
found[pattern] = {
border: shown.borderTopWidth, bar: shown.backgroundImage.startsWith("linear-gradient"), size: shown.backgroundSize.split(",")[0].trim(),
border: shown.borderTopWidth, bar: edge.backgroundImage.startsWith("linear-gradient"), size: edge.height, scroll: shown.overflowY,
fade: (edge.maskImage || edge.webkitMaskImage || "").replace(/\\s+/g, " "),
flush: Math.round(head.getBoundingClientRect().top - card.getBoundingClientRect().top), top: after.top,
mask: (after.maskImage || after.webkitMaskImage || "").replace(/\\s+/g, " "), hatch: after.backgroundImage !== "none",
};
@@ -146,6 +158,11 @@ class TestBoxHeads(HubCase):
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)
self.assertEqual(row["token"], "36px", row)
self.assertTrue(row["controls"], row)
self.assertEqual([control for control in row["controls"] if abs(control[1] - 36) > 1], [], row)
if view == "stream" and row["rows"] == 1:
self.assertLessEqual(max(row["centers"]) - min(row["centers"]), 2, 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"]))
@@ -172,8 +189,9 @@ class TestBoxHeads(HubCase):
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))
self.assertEqual((found["border"], found["bar"], found["size"], found["scroll"], found["flush"], found["top"], found["hatch"]), ("0px", True, "22px", "hidden", 0, "0px", True), (pattern, found))
self.assertTrue(found["fade"].startswith("linear-gradient(rgb(0, 0, 0) 0px"), (pattern, found))
self.assertTrue(found["mask"].startswith("linear-gradient(rgba(0, 0, 0, 0) 0px"), (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)
+96
View File
@@ -0,0 +1,96 @@
from __future__ import annotations
import json
import os
import shutil
import sys
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
from hub_case import HubCase
from hub_support import ASK
OUT = Path(os.environ.get("E2E_OUT", "/tmp/bubbles-mode-row-shots"))
PROBE = """(async () => {@HELPERS@
await screenShown(8000);
location.hash = "#stream/radio";
const toggle = await until(() => document.querySelector("#radio-spot:not([hidden]) .radio-bubbles"), 8000);
if (!toggle) {
return {error: "no bubbles toggle in the mode row"};
}
const header = document.getElementById("bubbles-toggle");
const row = toggle.closest(".radio-mode-row");
const modes = row.querySelector(".radio-modes");
const stored = async () => (await (await fetch("/api/state", {cache: "no-store"})).json()).settings.bubbles;
const mode = () => all("#radio-spot .radio-modes button[aria-pressed='true']").map((button) => button.dataset.mode);
const look = async () => ({radio: toggle.getAttribute("aria-pressed"), header: header.getAttribute("aria-pressed"), stored: await stored(), mode: mode()});
const flip = async (button, want) => {
button.click();
await until(() => toggle.getAttribute("aria-pressed") === want && header.getAttribute("aria-pressed") === want, 8000);
const end = Date.now() + 8000;
while (Date.now() < end && String(await stored()) !== want) {
await sleep(200);
}
return look();
};
const divider = row.querySelector(".mode-divider");
const [lane, bar, switcher] = [modes, divider, toggle].map((node) => node.getBoundingClientRect());
const layout = {
order: [...row.children].map((node) => node.className),
divider: [Math.round(bar.width), bar.height > 0, getComputedStyle(divider).backgroundColor !== "rgba(0, 0, 0, 0)"],
sameLine: switcher.top < lane.bottom && switcher.bottom > lane.top,
after: bar.left >= lane.right - 1 || bar.top >= lane.bottom - 1,
named: [toggle.getAttribute("aria-label"), Boolean(toggle.title), toggle.getAttribute("aria-controls")],
inModes: Boolean(modes.querySelector(".radio-bubbles")),
};
const before = await look();
const want = before.radio === "true" ? "false" : "true";
const flipped = await flip(toggle, want);
const back = await flip(header, before.radio);
return {layout, before, flipped, back, wide: document.documentElement.scrollWidth > innerWidth + 1};
})()"""
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestBubblesModeRow(HubCase):
drive = base.OrchestratorE2ECase.drive
authenticator = base.OrchestratorE2ECase.authenticator
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
self.claim("s1", "Skills session")
self.create_ask({**ASK, "timeout": 3600})
def test_chromium_switches_bubbles_from_the_mode_row_and_the_header_toggle_follows_at_three_widths(self):
authenticator = self.authenticator()
for width, height in base.WIDTHS:
with self.subTest(width=width):
probe = PROBE.replace("@HELPERS@", base.HELPERS)
data = self.drive([{"width": width, "height": height, "url": f"http://{self.host}/?{width}#stream", "wait": 1200, "probe": probe, "shot": str(OUT / f"chromium-{width}-bubbles-row.png")}], authenticator)
(OUT / f"chromium-{width}-bubbles-row.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual(data["errors"], [])
found = data["results"][0]
self.assertNotIn("error", found, found)
layout = found["layout"]
self.assertEqual(layout["order"][1:], ["mode-divider", "btn small ghost icon-only radio-bubbles"])
self.assertIn("radio-modes", layout["order"][0])
self.assertEqual((layout["divider"], layout["after"], layout["inModes"]), ([1, True, True], True, False), layout)
self.assertEqual(layout["named"], ["Speech bubbles", True, "bubbles"])
if width >= 1024:
self.assertTrue(layout["sameLine"], layout)
before, flipped, back = found["before"], found["flipped"], found["back"]
self.assertEqual((before["radio"], before["stored"]), (before["header"], before["radio"] == "true"), before)
self.assertEqual((flipped["radio"], flipped["header"], flipped["stored"]), (str(not before["stored"]).lower(), str(not before["stored"]).lower(), not before["stored"]), flipped)
self.assertEqual((back["radio"], back["header"], back["stored"]), (before["radio"], before["radio"], before["stored"]), back)
self.assertEqual((flipped["mode"], back["mode"]), (before["mode"], before["mode"]))
self.assertEqual(len(before["mode"]), 1)
self.assertFalse(found["wide"])
if __name__ == "__main__":
unittest.main()
+3 -3
View File
@@ -33,7 +33,7 @@ COMMON = """
await until(() => menu().open, 2000);
await sleep(100);
};
const grantOf = (ref) => row(ref) && (row(ref).querySelector(".item-actions button.primary") || all(".options.dialog > button.option", row(ref)).find((button) => text(button.querySelector("strong")) === "Yes"));
const grantOf = (ref) => row(ref) && (row(ref).querySelector(":is(.item-actions, .code-foot) button.primary") || all(".options.dialog > button.option", row(ref)).find((button) => text(button.querySelector("strong")) === "Yes"));
const wide = () => document.documentElement.scrollWidth > innerWidth + 1;
const switchState = () => [name(main()), count(), document.querySelector("#grant-bar #grant-direct") ? "select" : "direct"];
const storedMode = async (mode) => {
@@ -248,9 +248,9 @@ class TestBulkGrant(base.OrchestratorE2ECase):
self.assertEqual((mode["before"], mode["kept"], mode["after"]), (["Select", "0 selected", "direct"], True, selecting), mode)
self.assertNotIn("error", collect, collect)
self.assertEqual(collect["restored"], selecting, collect)
self.assertEqual(collect["pale"], [True, True], collect)
self.assertEqual(collect["pale"], [False, 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", True], ["true", True]], []), collect)
self.assertEqual((collect["pressed"], collect["posted"]), ([["true", False], ["true", False], ["true", False]], []), 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)
+1 -4
View File
@@ -46,10 +46,7 @@ INBOX = """(async () => {@HELPERS@@COMMON@
}
const single = await pick(1, sheet().querySelector(".deny-reason textarea"));
const menu = () => document.querySelector("#grant-bar details.grant-menu");
const checkbox = row("@ASK@").querySelector('input[type="checkbox"]');
if (checkbox && !checkbox.checked) {
checkbox.click();
}
await selectRow(row("@ASK@").dataset.ref);
if (!(await until(() => menu(), 3000))) {
return {single, error: "no selection menu"};
}
+88
View File
@@ -0,0 +1,88 @@
from __future__ import annotations
import json
import os
import shutil
import sys
import time
import unittest
from pathlib import Path
from unittest import mock
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
from hub_support import ASK
from kvb_orchestrator import batches
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-048-shots"))
DONE = """(async () => {@HELPERS@
const row = (ref) => document.querySelector(`#main .inbox-list > li[data-ref="${ref}"]`);
if (!(await until(() => row("@OPEN@") && document.querySelector("#main details.inbox-done"), 8000))) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
const fold = document.querySelector("#main details.inbox-done");
const done = all(".inbox-list > li", fold).map((li) => ({ref: li.dataset.ref, done: li.hasAttribute("data-done"), pill: all(".msg-meta .pill", li).map(text).includes("done"), opacity: Number(getComputedStyle(li).opacity)}));
const shown = {open: fold.open, summary: text(fold.querySelector("summary")), last: fold === document.querySelector("#main .inbox").lastElementChild, done,
boxes: all('#main .inbox-list .item input[type="checkbox"]').length};
await ViewStore.set("approval.mode", "select");
await until(() => row("@OPEN@") && row("@OPEN@").hasAttribute("aria-selected"), 10000);
const check = () => row("@OPEN@").querySelector("[aria-pressed]");
const state = () => [row("@OPEN@").getAttribute("aria-selected"), check() ? check().getAttribute("aria-pressed") : null];
const before = state();
check().click();
await until(() => state()[0] === "true", 3000);
const picked = state();
check().click();
await until(() => state()[0] === "false", 3000);
const cleared = state();
await cursorTo("@OPEN@");
await pressKey("x");
await until(() => state()[0] === "true", 3000);
const keyed = state();
await pressKey("x");
await until(() => state()[0] === "false", 3000);
await ViewStore.set("approval.mode", "direct");
fold.scrollIntoView({block: "center"});
return {...shown, before, picked, cleared, keyed, wide: document.documentElement.scrollWidth > innerWidth + 1};
})()"""
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestDoneRows(base.OrchestratorE2ECase):
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
now = time.time()
greet = {"title": "echo greet", "workdir": str(self.outside), "description": "greets", "check": "manual", "status": "queued", "roles": {"Operator": "R", "Skills session": "A"}}
self.write_council({"rasci.json": {"operator/greet": greet}})
fields = {"task": "operator/greet", "command": "echo greet", "directory": str(self.outside), "sha256": "", "status": "done", "proof": None}
self.httpd.hub.jobs.add({**fields, "code": 0, "output": "greet\n", "created_ts": now - 20, "started": now - 19, "finished": now - 10, "dismissed": False})
self.open = f"ask:{self.create_ask({**ASK, 'command': 'make open', 'timeout': 3600})}"
held = self.create_ask({**ASK, "command": "make held", "timeout": 3600})
self.held = f"ask:{held}"
entries = [self.entry("ask", held, "", "")]
with mock.patch.object(batches, "UNDO", 120):
self.assertEqual(self.approve(entries, self.signed(entries, self.pin()))[0], 202)
self.base = f"http://{self.host}/"
def test_chromium_folds_held_and_ended_rows_under_done_and_selects_by_the_green_check_without_a_checkbox_at_1920_and_390(self):
probe = DONE.replace("@HELPERS@", base.HELPERS).replace("@OPEN@", self.open)
steps = [{"width": width, "height": height, "url": f"{self.base}?{width}#tasks/operator", "wait": 1500, "probe": probe, "shot": str(OUT / f"chromium-{width}-done-rows.png")} for width, height in ((1920, 1080), (390, 844))]
data = self.drive(steps, None)
(OUT / "chromium-done-rows.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
for (width, _), found in zip(((1920, 1080), (390, 844)), data["results"], strict=True):
with self.subTest(width=width):
self.assertNotIn("error", found, found)
self.assertEqual((found["open"], found["summary"], found["last"], found["boxes"], found["wide"]), (False, "Done (2)", True, 0, False), found)
self.assertEqual(sorted(row["ref"] for row in found["done"]), sorted([self.held, "operator:operator/greet"]), found)
for row in found["done"]:
self.assertTrue(row["done"] and row["pill"], row)
self.assertLessEqual(row["opacity"], 0.5, row)
self.assertEqual((found["before"], found["picked"], found["cleared"], found["keyed"]), (["false", "false"], ["true", "true"], ["false", "false"], ["true", "true"]), found)
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -30,7 +30,7 @@ SHOW = """(async () => {@HELPERS@
if (!ready) {
return {error: text(document.getElementById("main"))};
}
const owned = (svg) => svg.closest("button, a, [title]");
const owned = (svg) => svg.closest("button, a, label, [title]");
const rows = () => all("#main table.fw-table tr[data-filter]");
const chip = (id) => document.querySelector(`#main [aria-label="Show rules"] button[data-filter="${id}"]`);
const sources = all("#main tbody[data-source]").map((node) => node.dataset.source);
@@ -290,7 +290,7 @@ class TestFirewallE2E(HubCase):
with self.subTest(width=width):
self.assertNotIn("error", shown, shown)
self.assertEqual((shown["title"], shown["subs"]), ("Controls", base.SUBS))
self.assertEqual(shown["tabs"], {"first": [["tools", "true", False], ["rules", "false", True], ["groups", "false", True]], "picked": [["tools", "false", True], ["rules", "true", False], ["groups", "false", True]]})
self.assertEqual(shown["tabs"], {"first": [["tools", "true", False], ["rules", "false", True], ["groups", "false", True], ["schedules", "false", True]], "picked": [["tools", "false", True], ["rules", "true", False], ["groups", "false", True], ["schedules", "false", True]]})
self.assertEqual(shown["sources"], ["hub", str(self.settings)])
self.assertEqual(shown["folded"], {"expanded": ["false"] * 2, "rows": 0})
self.assertEqual(shown["opened"], ["true"] * 2)
+22 -33
View File
@@ -40,7 +40,7 @@ LONG_NAME = "/".join(Path(LONG_REPO).parts[-3:])
LONG_ROWS = ("repo", "worktree", "core", "leaf")
READ = res.READ.replace("const stored = async", "const storedResources = async").replace("await stored()", "await storedResources()")
KIT = """
const stars = (selector) => all(selector).map((owner) => Boolean(ownStar(owner)));
const pinnable = (selector) => all(selector).map((owner) => Boolean(Panels.targetOf(owner)));
const panel = (kind) => `#main [data-panel="resources-${kind}"]`;
const lineIds = (root) => [...new Set(all("path.res-line", root).map((path) => path.dataset.id))];
const tileOf = (kind) => all("#main .home-tile").find((node) => node.dataset.pin.startsWith(`metric:${kind}/`)) || null;
@@ -73,21 +73,20 @@ LOADED = """(async () => {@HELPERS@@READ@
FOUND = """(async () => {@HELPERS@@HOME@@KIT@
const found = {};
await go("resources");
found.charts = stars('#main section.res-panel[data-panel^="resources-"]');
found.chips = all("#main .legend-chip .star").length;
found.inHead = all("#main .res-panel .star").every((star) => star.parentElement.classList.contains("res-head"));
found.charts = pinnable('#main section.res-panel[data-panel^="resources-"]');
found.stars = all(".star, .star-row").length;
await go("artifacts/tree");
await until(() => kept(), 8000);
found.tree = stars('#main [data-panel="artifacts/tree"]');
found.rows = Object.fromEntries(["repo", "branch", "wt"].map((kind) => [kind, stars(`#main [data-item^="artifact:${kind}:"]`)]));
found.tree = pinnable('#main [data-panel="artifacts/tree"]');
found.rows = Object.fromEntries(["repo", "branch", "wt"].map((kind) => [kind, pinnable(`#main [data-item^="artifact:${kind}:"]`)]));
await until(() => Object.values(longRows).every((find) => find()), 8000);
found.long = Object.fromEntries(Object.entries(longRows).map(([key, find]) => [key, find() ? find().dataset.item.length : null]));
found.disabled = all('#main [data-item^="artifact:"]').filter((node) => !ownStar(node) || ownStar(node).disabled).map((node) => node.dataset.item.slice(0, 80));
found.disabled = all('#main [data-item^="artifact:"]').filter((node) => !Panels.targetOf(node) || Panels.targetOf(node).refused).map((node) => node.dataset.item.slice(0, 80));
found.deletes = all('#main button[aria-label="Delete"]').length;
await go("agents/hierarchy");
found.order = stars('#main [data-panel="agents/order"]');
found.order = pinnable('#main [data-panel="agents/order"]');
await go("tasks/operator");
found.operator = stars('#main [data-panel="tasks/operator"]');
found.operator = pinnable('#main [data-panel="tasks/operator"]');
return found;
})()"""
METRIC = """(async () => {@HELPERS@@HOME@@READ@@KIT@
@@ -103,7 +102,7 @@ METRIC = """(async () => {@HELPERS@@HOME@@READ@@KIT@
}
const cpuOnly = Boolean(await until(() => lineIds(document.querySelector(panel("hardware"))).join() === "@CPU@", 5000));
const hardware = await press(panel("hardware"));
const cpuTitle = starOf(panel("hardware")).getAttribute("title");
const cpuTitle = (await pinState(panel("hardware")))[1];
const tokens = await press(panel("tokens"));
for (const id of others) {
chip(id).click();
@@ -111,7 +110,7 @@ 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")];
const allState = await pinState(panel("hardware"));
await pickPanel("combined", true);
await pickPanel("hardware", false);
await pickPanel("tokens", false);
@@ -127,7 +126,7 @@ COMBINED_OFF = """(async () => {@HELPERS@@HOME@@READ@@KIT@
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")]};
return {off, hardware: await pinState(panel("hardware"))};
})()"""
HOME_METRICS = """(async () => {@HELPERS@@HOME@@KIT@
await go("home");
@@ -166,12 +165,7 @@ PM = """(async () => {@HELPERS@@HOME@@KIT@
const row = await until(() => kept(), 8000);
row.closest("details").open = true;
const tree = await press('#main [data-panel="artifacts/tree"]');
const rowStar = row ? ownStar(row) : null;
if (rowStar) {
rowStar.click();
await sleep(200);
}
const branch = rowStar ? (ownStar(kept()) || rowStar).getAttribute("aria-pressed") : null;
const branch = row ? await pinOwner(kept() || row) : null;
await go("agents/hierarchy");
const order = await press('#main [data-panel="agents/order"]');
await go("tasks/operator");
@@ -210,14 +204,9 @@ LONG = """(async () => {@HELPERS@@HOME@@KIT@
const pressed = {};
const keys = {};
for (const [key, find] of Object.entries(longRows)) {
const star = ownStar(find());
keys[key] = pinKey(find());
pressed[key] = star ? [star.disabled, star.title.startsWith("Pin to Home: Artifact ")] : null;
if (star && !star.disabled) {
star.click();
await sleep(200);
}
pressed[key].push(ownStar(longRows[key]()).getAttribute("aria-pressed"));
const before = await menuPinOf(find());
pressed[key] = before ? [before[1].startsWith("Pin to Home: Artifact "), await pinOwner(find())] : null;
}
await go("home");
await settled();
@@ -365,10 +354,10 @@ class TestHomeBookmarks(HubCase):
{"width": width, "height": height, "url": f"{page}-clear#stream", "wait": 600, "probe": CLEAR, "shot": None},
{"width": width, "height": height, "url": f"{page}-loaded#resources", "wait": 1200, "probe": probe(LOADED), "shot": None},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(FOUND), "shot": None},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(dash.STARS), "shot": None},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(METRIC), "shot": f"{shot}-combined-star.png"},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(dash.STARS, ["resources"]), "shot": None},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(COMBINED_OFF), "shot": f"{shot}-metric-star.png"},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(dash.OWNERS), "shot": None},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(METRIC), "shot": f"{shot}-combined-pin.png"},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(dash.OWNERS, ["resources"]), "shot": None},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(COMBINED_OFF), "shot": f"{shot}-metric-pin.png"},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(HOME_METRICS), "shot": f"{shot}-home-metrics.png"},
{"width": width, "height": height, "url": f"{page}-reloaded#home", "wait": 1500, "probe": probe(RELOADED), "shot": None},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(PM), "shot": f"{shot}-home-bookmarks.png"},
@@ -388,7 +377,7 @@ class TestHomeBookmarks(HubCase):
loaded = next(results)
self.assertTrue(loaded["drawn"], loaded)
found = next(results)
self.assertEqual((found["charts"], found["chips"], found["inHead"]), ([True] * 4, 0, True), found)
self.assertEqual((found["charts"], found["stars"]), ([True] * 4, 0), 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)
@@ -399,7 +388,7 @@ class TestHomeBookmarks(HubCase):
self.assertEqual(found["disabled"], [], found)
self.assertGreaterEqual(found["deletes"], 1, found)
walked = next(results)
self.assertEqual((walked["missing"], walked["covered"]), ([], []), walked)
self.assertEqual((walked["missing"], walked["stars"]), ([], []), walked)
metric = next(results)
self.assertNotIn("error", metric, metric)
self.assertEqual((metric["cpuOnly"], metric["hardware"], metric["tokens"], metric["back"], metric["combinedOn"], metric["combined"]), (True, "true", "true", True, True, "true"), metric)
@@ -415,7 +404,7 @@ class TestHomeBookmarks(HubCase):
self.assertRegex(metric["stored"][0][1], r"^hardware/[0-9a-f]{16}$")
self.assertEqual([key for _, key, _ in metric["stored"][1:]], ["tokens/interval/all", "combined/interval/all"])
combined_walk = next(results)
self.assertEqual((combined_walk["missing"], combined_walk["covered"]), ([], []), combined_walk)
self.assertEqual((combined_walk["missing"], combined_walk["stars"]), ([], []), combined_walk)
self.assertEqual(next(results), {"off": True, "hardware": ["false", "Pin to Home: Hardware: all series"]})
home = next(results)
self.assertEqual(home["errors"], [], home)
@@ -453,7 +442,7 @@ class TestHomeBookmarks(HubCase):
def check_long(self, long: dict) -> None:
self.assertEqual(long["errors"], [], long)
self.assertEqual(long["pressed"], {key: [False, True, "true"] for key in LONG_ROWS}, long)
self.assertEqual(long["pressed"], {key: [True, "true"] for key in LONG_ROWS}, long)
self.assertEqual([key for key in long["stored"] if key in long["keys"].values()], list(long["keys"].values()), long)
for key in ("core", "leaf"):
self.assertRegex(long["keys"][key], r"^artifact:(wt|artefact)_23_[0-9a-f]{16}$", long)
+62 -62
View File
@@ -20,6 +20,7 @@ from hub_support import HUB, iso
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-008-shots"))
REAL_STORE = (HUB / "templates" / "view-store.js").exists()
CUE = "e2e-home-change"
PIN_LABELS = ("Pin to Home", "Unpin from Home")
SCREENS = [
"stream", "agents/orbit", "agents/chord", "agents/swimlane", "agents/3d", "agents/tree", "agents/hierarchy",
"artifacts/orbit", "artifacts/chord", "artifacts/swimlane", "artifacts/tree", "artifacts/3d",
@@ -52,19 +53,48 @@ HOME = """
await screenShown(8000);
await sleep(500);
};
const ownStar = (owner) => [...owner.querySelectorAll(".star")].find((node) => node.closest("[data-panel], [data-item]") === owner) || null;
const starOf = (selector) => {
const owner = document.querySelector(selector);
return owner ? ownStar(owner) : null;
const PIN_LABELS = ["Pin to Home", "Unpin from Home"];
const shownMenu = () => document.querySelector(".ctx-menu:not([hidden])");
const menuLabel = (node) => text(node.querySelector(".ctx-label"));
const closeMenu = async () => {
const menu = shownMenu();
if (menu) {
menu.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true, cancelable: true}));
await sleep(100);
}
};
const press = async (selector) => {
const button = await until(() => starOf(selector), 8000);
if (!button) {
const pinItem = async (owner) => {
await closeMenu();
owner.scrollIntoView({block: "center"});
const box = owner.getBoundingClientRect();
owner.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, button: 2, clientX: Math.round(box.left + 4), clientY: Math.round(box.top + 4)}));
const menu = await until(shownMenu, 3000);
return menu ? all('[role="group"][data-scope="element"] [role="menuitem"]', menu).find((node) => PIN_LABELS.includes(menuLabel(node))) || null : null;
};
const menuPinOf = async (owner) => {
const item = await pinItem(owner);
const state = item ? [String(menuLabel(item) === PIN_LABELS[1]), `${menuLabel(item)}: ${item.title}`] : null;
await closeMenu();
return state;
};
const pinState = async (selector) => {
const owner = await until(() => document.querySelector(selector), 8000);
return owner ? menuPinOf(owner) : null;
};
const pinOwner = async (owner) => {
const target = Panels.targetOf(owner);
const item = await pinItem(owner);
if (!item) {
await closeMenu();
return null;
}
button.click();
item.click();
await sleep(200);
return button.getAttribute("aria-pressed");
return String((ViewStore.get("home.pins") || []).some((pin) => pin.kind === target.kind && pin.id === target.id));
};
const press = async (selector) => {
const owner = await until(() => document.querySelector(selector), 8000);
return owner ? pinOwner(owner) : null;
};
const tiles = () => all("#main .home-tile").map((tile) => tile.dataset.pin);
const tile = (key) => document.querySelector(`#main .home-tile[data-pin="${key}"]`);
@@ -103,71 +133,41 @@ START_EMPTY = """(async () => {@HELPERS@
await screenShown(8000);
return {hash: location.hash, screen: document.getElementById("main").getAttribute("aria-labelledby"), first: name(document.querySelector("#tabs > .tab-group > button"))};
})()"""
STARS = """(async () => {@HELPERS@@HOME@
OWNERS = """(async () => {@HELPERS@@HOME@
const seen = [];
const missing = [];
const covered = [];
const CONTROLS = 'button, a[href], input, select, textarea, summary, [role="button"], [role="tab"], [tabindex]:not([tabindex="-1"])';
const shown = (node) => node.getClientRects().length > 0 && getComputedStyle(node).visibility !== "hidden" && !node.closest("details:not([open]) > :not(summary)");
const overlap = (a, b) => Math.max(0, Math.min(a.right, b.right) - Math.max(a.left, b.left)) * Math.max(0, Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top));
const stars = [];
const menus = [];
const XHTML = "http://www.w3.org/1999/xhtml";
const clipped = (node) => {
const box = node.getBoundingClientRect();
const drawn = {left: box.left, top: box.top, right: box.right, bottom: box.bottom};
let position = getComputedStyle(node).position;
for (let at = node.parentElement; at && at !== document.body && position !== "fixed"; at = at.parentElement) {
const look = getComputedStyle(at);
if (at.namespaceURI !== XHTML || ["inline", "contents"].includes(look.display) || (position === "absolute" && look.position === "static")) {
continue;
}
position = look.position;
const edge = at.getBoundingClientRect();
const left = edge.left + at.clientLeft;
const top = edge.top + at.clientTop;
if (look.overflowX !== "visible") {
drawn.left = Math.max(drawn.left, left);
drawn.right = Math.min(drawn.right, left + at.clientWidth);
}
if (look.overflowY !== "visible") {
drawn.top = Math.max(drawn.top, top);
drawn.bottom = Math.min(drawn.bottom, top + at.clientHeight);
}
}
return drawn;
};
const layer = (node) => node.closest("dialog[open]");
const count = (where) => {
const shown = (node) => node.getClientRects().length > 0 && getComputedStyle(node).visibility !== "hidden" && !node.closest("details:not([open]) > :not(summary)");
const count = async (where) => {
const owners = all("[data-panel], [data-item]").filter((node) => node.namespaceURI === XHTML);
seen.push([where, owners.length]);
missing.push(...owners.filter((node) => !ownStar(node)).map((node) => `${where}: ${node.outerHTML.slice(0, 120)}`));
const controls = all(CONTROLS).filter(shown);
for (const star of all(".star").filter(shown)) {
const box = clipped(star);
for (const other of controls) {
if (other !== star && !other.contains(star) && !star.contains(other) && layer(other) === layer(star) && overlap(box, clipped(other)) > 1) {
covered.push(`${where}: ${star.title} over ${other.outerHTML.slice(0, 100)}`);
}
}
}
missing.push(...owners.filter((node) => !Panels.targetOf(node)).map((node) => `${where}: ${node.outerHTML.slice(0, 120)}`));
stars.push(...all(".star, .star-row").map((node) => `${where}: ${node.outerHTML.slice(0, 120)}`));
const first = owners.filter(shown).find((node) => node.closest("dialog[open]")) || owners.find(shown) || owners[0];
const item = first ? await pinItem(first) : null;
menus.push([where, item ? menuLabel(item) : null]);
await closeMenu();
};
for (const hash of @SCREENS@) {
await go(hash);
await sleep(hash.endsWith("3d") || hash.startsWith("artifacts") ? 1500 : 300);
count(hash);
await count(hash);
}
await go("agents/orbit");
const agent = document.querySelector('#main svg .node.k-session[data-pick]');
if (agent) {
agent.dispatchEvent(new MouseEvent("click", {bubbles: true}));
await until(() => document.querySelector('#popup[open] [data-item^="agent:"]'), 5000);
count("agent card");
await count("agent card");
document.getElementById("popup").close();
}
document.getElementById("radio-open").click();
await until(() => document.querySelector('[data-panel="radio-log"]'), 5000);
count("radio spot");
await count("radio spot");
document.getElementById("radio-open").click();
return {seen, missing, covered, total: seen.reduce((sum, [, size]) => sum + size, 0)};
return {seen, missing, stars, menus, total: seen.reduce((sum, [, size]) => sum + size, 0)};
})()"""
PIN = """(async () => {@HELPERS@@HOME@
await go("tasks/gantt");
@@ -322,7 +322,7 @@ class TestHomeDashboard(HubCase):
steps += [
{"width": width, "height": height, "url": f"{page}-clear#stream", "wait": 600, "probe": CLEAR, "shot": None},
{"width": width, "height": height, "url": f"{page}-empty", "wait": 1500, "probe": probe(START_EMPTY), "shot": f"{shot}-start-empty.png"},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(STARS), "shot": f"{shot}-stars.png"},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(OWNERS), "shot": f"{shot}-owners.png"},
{"width": width, "height": height, "url": f"{page}-pin#stream", "wait": 1200, "probe": probe(PIN), "shot": f"{shot}-pinned.png"},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(RESIZE), "shot": f"{shot}-resized.png"},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(REORDER), "shot": f"{shot}-reordered.png"},
@@ -347,10 +347,10 @@ class TestHomeDashboard(HubCase):
next(results)
empty = next(results)
self.assertEqual((empty["hash"], empty["screen"], empty["first"]), ("", "tab-stream", "Home"), empty)
stars = next(results)
self.assertEqual(stars["missing"], [], stars)
self.assertEqual(stars["covered"], [], stars)
self.assertGreater(stars["total"], 20, stars)
owners = next(results)
self.assertEqual((owners["missing"], owners["stars"]), ([], []), owners)
self.assertEqual([where for where, label in owners["menus"] if label not in PIN_LABELS], [where for where, size in owners["seen"] if not size], owners)
self.assertGreater(owners["total"], 20, owners)
pinned = next(results)
self.assertEqual((pinned["gantt"], pinned["feature"], pinned["docs"], pinned["streamed"], pinned["chart"], pinned["off"], pinned["again"]), ("true", "true", "true", "true", True, "false", "true"), pinned)
self.assertEqual(pinned["pinned"], ["panel:tasks/gantt", "task:work/feature", "task:work/docs", "panel:stream"])
@@ -397,14 +397,14 @@ class TestHomeDashboard(HubCase):
def init(self) -> str | None:
return None if REAL_STORE else STUB
def test_chromium_stars_pins_resizes_reorders_and_marks_gone_tiles_at_three_widths(self):
def test_chromium_pins_by_menu_resizes_reorders_and_marks_gone_tiles_at_three_widths(self):
data = self.drive(self.steps("chromium"), None, init=self.init())
(OUT / "chromium-home.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual(data["errors"], [])
self.check(data)
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
def test_firefox_stars_pins_resizes_reorders_and_marks_gone_tiles_at_three_widths(self):
def test_firefox_pins_by_menu_resizes_reorders_and_marks_gone_tiles_at_three_widths(self):
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=self.init())
(OUT / "firefox-home.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], [])
@@ -412,7 +412,7 @@ class TestHomeDashboard(HubCase):
@unittest.skipUnless(REAL_STORE, "waits on 007: view-store.js and /api/view are not on this branch yet")
def test_a_second_browser_shows_the_same_layout(self):
first = self.drive([step for step in self.steps("chromium")[:6] if step["probe"] != probe(STARS)], None)
first = self.drive([step for step in self.steps("chromium")[:6] if step["probe"] != probe(OWNERS)], None)
second = self.drive([{"width": 1366, "height": 768, "url": f"{self.base}?second", "wait": 2000, "probe": probe(RELOADED), "shot": str(OUT / "chromium-second.png")}], None)
self.assertEqual(second["results"][0]["tiles"], first["results"][-1]["down"])
self.assertEqual((second["results"][0]["hash"], second["results"][0]["screen"]), ("#home", "tab-home"))
+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_home_bookmarks_e2e as bm
import test_home_tile_open_e2e as opened
import test_workbench_w4_e2e as w4
from hub_case import HubCase
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-044-shots"))
PANELS = [
"stream", "radio-log", "radio", "radio-device", "radio-speak", "agents/orbit", "agents/chord", "agents/swimlane", "agents/3d", "agents/tree", "agents/hierarchy",
"artifacts/orbit", "artifacts/chord", "artifacts/swimlane", "artifacts/3d", "artifacts/tree", "tasks/list", "tasks/board", "tasks/rasci", "tasks/gantt", "tasks/burn",
"tasks/3d", "tasks/operator", "tasks/match", "agents/order", "resources-accounts",
]
NAMED = {"panel:radio-log": "radio-card", "panel:radio-device": "radio-card", "panel:radio-speak": "radio-card", "panel:tasks/gantt": "gantt-scroll"}
FLAT = """(async () => {@HELPERS@@HOME@@KIT@
await go("home");
await until(() => !all("#main .home-tile .empty h2").some((title) => text(title).endsWith("…")), 8000);
await sleep(1200);
const boxed = (node) => {
const look = getComputedStyle(node);
return parseFloat(look.borderTopWidth) > 0 || look.backgroundColor !== "rgba(0, 0, 0, 0)" || look.backgroundImage !== "none";
};
const area = (node) => node.offsetWidth * node.offsetHeight;
const left = (body) => {
for (let node = body.firstElementChild; node;) {
if (node.classList.contains("home-flat")) {
return null;
}
if (boxed(node)) {
return node.className;
}
const biggest = [...node.children].reduce((best, child) => (!best || area(child) > area(best) ? child : best), null);
node = biggest && area(biggest) >= 0.75 * area(node) ? biggest : null;
}
return null;
};
const found = all("#main .home-tile").map((node) => {
const body = node.querySelector(".home-body");
const flat = body.querySelector(".home-flat");
const look = flat ? getComputedStyle(flat) : null;
const pad = parseFloat(getComputedStyle(body).paddingBottom);
const tail = [];
for (let node = flat; node; node = node.nextElementSibling) {
tail.push(node.getBoundingClientRect().bottom);
}
const gap = flat ? body.getBoundingClientRect().top + body.clientTop + body.clientHeight - pad - Math.max(...tail) : null;
const heading = flat ? flat.querySelector(":scope > .radio-card-head > .group-title") : null;
return {
key: node.dataset.pin, flat: flat ? [...flat.classList].filter((name) => name !== "home-flat") : null, boxLeft: left(body),
border: look ? look.borderTopWidth : null, background: look ? look.backgroundColor : null, gap: gap === null ? null : Math.round(gap * 10) / 10,
heading: heading ? heading.getClientRects().length > 0 : null,
};
});
return {tiles: found, wide: document.documentElement.scrollWidth > innerWidth + 1};
})()"""
FULL = """(async () => {@HELPERS@@HOME@
await go("tasks/gantt");
const gantt = await until(() => document.querySelector("#main .gantt-scroll"), 8000);
const ganttBorder = gantt ? getComputedStyle(gantt).borderTopWidth : null;
document.getElementById("radio-open").click();
const log = await until(() => document.querySelector('#radio-spot:not([hidden]) [data-panel="radio-log"]'), 8000);
const device = document.querySelector('#radio-spot:not([hidden]) [data-panel="radio-device"]');
const out = {gantt: ganttBorder, log: log ? getComputedStyle(log).borderTopWidth : null, device: device ? getComputedStyle(device).borderTopWidth : null};
document.getElementById("radio-open").click();
return out;
})()"""
SHOW = """(async () => {@HELPERS@@HOME@
await go("home");
const found = await until(() => tile("@KEY@"), 8000);
found.scrollIntoView({block: "center"});
await sleep(400);
return {key: found.dataset.pin};
})()"""
def probe(template: str, **names: str) -> str:
return opened.probe(template.replace("@PANELS@", json.dumps(PANELS)), **names)
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestHomeFlatWidgets(HubCase):
seed = base.OrchestratorE2ECase.seed
subagents = base.OrchestratorE2ECase.subagents
drive = base.OrchestratorE2ECase.drive
sample = w4.TestWorkbenchResources.sample
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
self.seed()
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")
def steps(self) -> list[dict]:
steps = []
for width, height in ((1920, 1080), (390, 844)):
page = f"{self.base}?{width}"
steps += [
{"width": width, "height": height, "url": f"{page}-clear#stream", "wait": 600, "probe": bm.CLEAR, "shot": None},
{"width": width, "height": height, "url": f"{page}-seed#stream", "wait": 1200, "probe": probe(opened.SEED), "shot": None},
{"width": width, "height": height, "url": f"{page}-flat#home", "wait": 1500, "probe": probe(FLAT), "shot": str(OUT / f"chromium-{width}-home.png")},
{"width": width, "height": height, "url": f"{page}-full#stream", "wait": 1200, "probe": probe(FULL), "shot": None},
]
steps += [{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(SHOW, key=key), "shot": str(OUT / f"chromium-{width}-{key.split(':')[1].replace('/', '-')}.png")} for key in NAMED]
return steps
def test_chromium_flattens_every_widget_whose_content_is_a_box_and_keeps_the_box_in_full_view_at_1920_and_390(self):
data = self.drive(self.steps(), None)
(OUT / "chromium-flat.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], [])
per_width = len(data["results"]) // 2
for index, width in enumerate((1920, 390)):
flat, full = data["results"][index * per_width + 2], data["results"][index * per_width + 3]
self.assertFalse(flat["wide"], flat)
tiles = {tile["key"]: tile for tile in flat["tiles"]}
self.assertEqual(len(tiles), len(PANELS) + 7, sorted(tiles))
for key, tile in tiles.items():
with self.subTest(width=width, key=key):
self.assertIsNone(tile["boxLeft"], tile)
if tile["flat"] is not None:
self.assertEqual((tile["border"], tile["background"]), ("0px", "rgba(0, 0, 0, 0)"), tile)
self.assertLessEqual(abs(tile["gap"]), 2, tile)
for key, box in NAMED.items():
with self.subTest(width=width, named=key):
self.assertIn(box, tiles[key]["flat"] or [], tiles[key])
for key in ("panel:radio-log", "panel:radio-device"):
self.assertFalse(tiles[key]["heading"], tiles[key])
self.assertEqual(full, {"gantt": "1px", "log": "1px", "device": "1px"}, full)
if __name__ == "__main__":
unittest.main()
+95
View File
@@ -0,0 +1,95 @@
from __future__ import annotations
import json
import os
import shutil
import sys
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
from hub_case import HubCase
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-037-shots"))
FRAME = """
const frame = () => {
const look = getComputedStyle(document.getElementById("main"));
return {background: look.backgroundColor, image: look.backgroundImage, border: look.borderLeftWidth, shadow: look.boxShadow};
};
"""
PINS = """(async () => {@HELPERS@@FRAME@
await ViewStore.update("home.pins", () => [{kind: "panel", id: "stream", w: 6, h: 4}, {kind: "panel", id: "radio-log", w: 6, h: 4}]);
location.hash = "home";
await screenShown(8000);
const tile = await until(() => document.querySelector("#main .home-tile"), 8000);
await sleep(600);
const nav = document.querySelector(".navbar");
const edge = nav.getBoundingClientRect().left + parseFloat(getComputedStyle(nav).paddingLeft);
return {frame: frame(), offset: Math.round((tile.getBoundingClientRect().left - edge) * 10) / 10, wide: document.documentElement.scrollWidth > innerWidth + 1};
})()"""
EMPTY = """(async () => {@HELPERS@@FRAME@
await ViewStore.update("home.pins", () => []);
location.hash = "home";
await screenShown(8000);
const empty = await until(() => document.querySelector("#main .home > .empty:not([hidden])"), 8000);
await sleep(300);
const look = empty ? getComputedStyle(empty) : null;
return {frame: frame(), card: look ? [look.backgroundColor !== "rgba(0, 0, 0, 0)", look.borderTopStyle, text(empty.querySelector("h2"))] : null};
})()"""
STREAM = """(async () => {@HELPERS@@FRAME@
location.hash = "stream";
await screenShown(8000);
await sleep(300);
return {frame: frame()};
})()"""
CLEAR = "rgba(0, 0, 0, 0)"
def probe(template: str) -> str:
return template.replace("@HELPERS@", base.HELPERS).replace("@FRAME@", FRAME)
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestHomeFrame(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 test_chromium_draws_home_without_a_box_and_keeps_the_box_on_the_stream(self):
steps = []
for width, height in base.WIDTHS:
shot = OUT / f"chromium-{width}"
steps += [
{"width": width, "height": height, "url": f"{self.page_url}?{width}-pins#home", "wait": 1200, "probe": probe(PINS), "shot": f"{shot}-home-pins.png"},
{"width": width, "height": height, "url": f"{self.page_url}?{width}-empty#home", "wait": 1200, "probe": probe(EMPTY), "shot": f"{shot}-home-empty.png"},
{"width": width, "height": height, "url": f"{self.page_url}?{width}-stream#stream", "wait": 1200, "probe": probe(STREAM), "shot": None},
]
data = self.drive(steps, None)
(OUT / "chromium-home-frame.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual(data["errors"], [])
results = iter(data["results"])
for width, _ in base.WIDTHS:
pins, empty, stream = next(results), next(results), next(results)
with self.subTest(width=width):
for found in (pins, empty, stream):
self.assertNotIn("error", found, found)
for bare in (pins["frame"], empty["frame"]):
self.assertEqual(bare, {"background": CLEAR, "image": "none", "border": "0px", "shadow": "none"}, bare)
self.assertLessEqual(abs(pins["offset"]), 2, pins)
self.assertFalse(pins["wide"])
self.assertEqual(empty["card"], [True, "dashed", "Nothing pinned yet"], empty)
self.assertNotEqual(stream["frame"]["background"], CLEAR, stream)
self.assertEqual(stream["frame"]["border"], "1px", stream)
self.assertNotEqual(stream["frame"]["shadow"], "none", stream)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -103,7 +103,7 @@ class TestHubBoard(base.OrchestratorE2ECase):
self.assertNotIn("error", found)
self.assertEqual((found["badge"], found["start"], found["wide"]), (["Day", "1 alone"], everyone, False))
self.assertEqual((found["one"], found["kept"], found["none"], found["all"]), ([one, [True] * 3], one, [nobody, [False] * 3], [everyone, [True] * 3]))
self.assertEqual(found["popup"], {"badge": ["Draining"], "buttons": ["Mute Stage", "Drain", "Suspend", "Resume"]})
self.assertEqual(found["popup"], {"badge": ["Draining"], "buttons": ["Drain", "Suspend", "Resume"]})
self.assertEqual([question.split(":")[0] for question in found["questions"]], ["Drain Stage", "Suspend Stage"])
sent = [["/api/board/sign", ["action", "agents"], "drain", ["s2"]], ["/api/board/drain", ["proof", "agents"], None, ["s2"]], ["/api/board/sign", ["action", "agents"], "suspend", ["s2"]], ["/api/board/suspend", ["proof", "agents"], None, ["s2"]]]
self.assertEqual(found["posted"], sent if signs else sent[::2])
+1 -1
View File
@@ -49,7 +49,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.assertEqual((sorted(probe["kinds"]), probe["done"]), (["Ask", "Operator", "Operator", "Review", "Rule request"], 1))
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.")
+1 -1
View File
@@ -310,7 +310,7 @@ class TestHubRadio(base.OrchestratorE2ECase):
self.assertEqual(saved["tones"], ["MAYDAY / PAN-PAN", "Reviews, asks, decisions", "Post and calls to you", "All radio", "Squelch", "speak while CPU < 50 %"])
self.assertEqual(saved["bells"], ["MAYDAY / PAN-PAN tone", "Reviews, asks, decisions tone", "Post and calls to you tone", "All radio tone"])
self.assertEqual((saved["kept"], saved["after"]), ([float(squelch), radio_bell != "off", post == "speak"], [radio_bell, post]))
self.assertEqual(saved["general"], {"sections": ["Ambience", "Location", "Appearance", "Music", "Notifications", "Passkey"], "radio": 0})
self.assertEqual(saved["general"], {"sections": ["Ambience", "Location", "Appearance", "Music", "Undo window", "Passkey"], "radio": 0})
self.assertEqual((saved["tall"], saved["wide"]), (width == 390, False))
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"]}
+2 -2
View File
@@ -30,7 +30,7 @@ EXPECTED = {
"resources": ["resources-hardware", "resources-tokens"],
}
READ = """
const PARTS = ".legend > :not(.star, .legend-toggle), .res-legend, .home-metric > .legend-chips";
const PARTS = ".legend > :not(.legend-toggle), .res-legend, .home-metric > .legend-chips";
const owners = () => [...all("#main [data-panel]").filter((host) => !host.closest(".home-tile")), ...all(".home-tile[data-pin]")];
const keyOf = (owner) => owner.dataset.pin || owner.dataset.panel;
const ownerOf = (key) => owners().find((node) => keyOf(node) === key) || null;
@@ -63,7 +63,7 @@ SCAN = """(async () => {@HELPERS@@READ@
const flip = async (key) => {
const path = ownerOf(key).dataset.pin ? "tiles" : "views";
const button = () => toggleOf(ownerOf(key));
const placed = path === "tiles" ? button().nextElementSibling.classList.contains("home-open") : button().previousElementSibling.classList.contains("star");
const placed = path === "tiles" ? button().nextElementSibling.classList.contains("home-open") : button().parentElement.matches("[data-legend-slot], .legend-row") && button().parentElement.lastElementChild === button();
const before = shownParts(ownerOf(key));
button().click();
const hidden = Boolean(await until(() => ownerOf(key) && ownerOf(key).dataset.legend === "hidden" && shownParts(ownerOf(key)) === 0 && button().getAttribute("aria-pressed") === "false", 4000));
+2 -2
View File
@@ -91,7 +91,7 @@ OVERLAY = """(async () => {@HELPERS@@UNLABELLED@@CAPTURE@
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();
row().querySelector(":is(.item-actions, .code-foot) 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};
@@ -140,7 +140,7 @@ class TestLineComments(base.OrchestratorE2ECase):
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["item"], overlay["inline"]), (None, {"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", "", ""]]
+167
View File
@@ -0,0 +1,167 @@
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
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-035-036-shots"))
DECK = """
const widen = () => card() && card().querySelector(".match-widen");
const shown = (node) => Boolean(node && node.getClientRects().length);
const area = () => {
const box = document.querySelector("#main .graph.match");
const look = getComputedStyle(box);
return box.clientWidth - parseFloat(look.paddingLeft) - parseFloat(look.paddingRight);
};
const width = () => card().offsetWidth;
const later = async () => {
const before = card().dataset.card;
document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "ArrowUp", bubbles: true}));
return Boolean(await until(() => card() && card().dataset.card !== before, 4000));
};
const flip = async (wide) => {
widen().click();
await until(() => document.querySelector("#main .match-stack").dataset.wide === String(wide), 4000);
await sleep(200);
};
"""
WIDE = """(async () => {@HELPERS@@CARD@@DECK@
await screenShown(8000);
if (!(await until(card, 8000))) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
await sleep(300);
if (document.querySelector("#main .match-stack").dataset.wide === "true") {
await flip(false);
}
const before = {button: shown(widen()), width: width(), area: Math.round(area())};
if (!before.button) {
return {before};
}
await flip(true);
const wide = {width: width(), area: Math.round(area()), label: widen().getAttribute("aria-label"), keys: await later()};
wide.after = width();
return {before, wide};
})()"""
KEPT = """(async () => {@HELPERS@@CARD@@DECK@
await screenShown(8000);
if (!(await until(card, 8000))) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
await sleep(300);
const kept = {wide: document.querySelector("#main .match-stack").dataset.wide, width: width(), area: Math.round(area())};
await flip(false);
const narrow = {width: width(), label: widen().getAttribute("aria-label"), keys: await later()};
narrow.after = width();
return {kept, narrow};
})()"""
PILE = """(async () => {@HELPERS@@CARD@@DECK@
await screenShown(8000);
if (!(await until(card, 8000))) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
await sleep(300);
const open = () => Number((text(document.querySelector("#main .task-toolbar .muted")) || "").split(" ")[0]);
const pile = () => {
const front = card();
const edge = front.getBoundingClientRect();
return {open: open(), release: front.classList.contains("match-release-card"), layers: all("#main .match-layer").map((layer) => ({
size: Math.abs(layer.offsetWidth - front.offsetWidth) <= 2 && Math.abs(layer.offsetHeight - front.offsetHeight) <= 2,
above: layer.getBoundingClientRect().top < edge.top - 1,
lower: Number(getComputedStyle(layer).zIndex) < Number(getComputedStyle(front).zIndex),
inert: getComputedStyle(layer).pointerEvents === "none" && layer.getAttribute("aria-hidden") === "true",
}))};
};
const seen = [pile()];
for (let tries = 0; open() > 1 && tries < 8; tries += 1) {
const count = open();
document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "ArrowLeft", bubbles: true}));
const confirm = await until(() => document.querySelector(".match-feedback-reject"), 2000);
if (!confirm) {
await later();
continue;
}
confirm.click();
if (await until(() => open() === count - 1 && card(), 4000)) {
await sleep(500);
seen.push(pile());
}
}
return {seen};
})()"""
def probe(template: str) -> str:
return template.replace("@HELPERS@", base.HELPERS).replace("@CARD@", matched.CARD).replace("@DECK@", DECK)
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestMatchPile(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()
def steps(self) -> list[dict]:
steps = []
for width, height in base.WIDTHS:
at = {"width": width, "height": height}
shot = OUT / f"chromium-{width}"
steps.append({**at, "url": f"{self.base}?{width}-wide#tasks/match", "wait": 1500, "probe": probe(WIDE), "shot": f"{shot}-match-wide.png"})
if width > 640:
steps.append({**at, "url": f"{self.base}?{width}-kept#tasks/match", "wait": 1500, "probe": probe(KEPT), "shot": f"{shot}-match-narrow.png"})
steps.append({**at, "url": f"{self.base}?{width}-pile#tasks/match", "wait": 1500, "probe": probe(PILE), "shot": f"{shot}-match-pile.png"})
return steps
def test_chromium_widens_a_match_card_keeps_the_choice_and_piles_the_waiting_cards_behind_it(self):
data = self.drive(self.steps(), None, init=w4.GUARD)
(OUT / "chromium-match-pile.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
results = iter(data["results"])
for width, _ in base.WIDTHS:
wide = next(results)
kept = next(results) if width > 640 else None
pile = next(results)
with self.subTest(width=width, step="wide"):
self.assertNotIn("error", wide, wide)
self.assertEqual(wide["before"]["button"], width > 640, wide)
self.assertLessEqual(wide["before"]["width"], 960, wide)
if width > 640:
self.assertLessEqual(abs(wide["wide"]["width"] - wide["wide"]["area"]), 2, wide)
self.assertEqual((wide["wide"]["label"], wide["wide"]["keys"], wide["wide"]["after"]), ("Normal width", True, wide["wide"]["width"]), wide)
if kept:
with self.subTest(width=width, step="kept"):
self.assertNotIn("error", kept, kept)
self.assertEqual(kept["kept"]["wide"], "true", kept)
self.assertLessEqual(abs(kept["kept"]["width"] - kept["kept"]["area"]), 2, kept)
self.assertLessEqual(kept["narrow"]["width"], 960, kept)
self.assertEqual((kept["narrow"]["label"], kept["narrow"]["keys"], kept["narrow"]["after"]), ("Full width", True, kept["narrow"]["width"]), kept)
with self.subTest(width=width, step="pile"):
self.assertNotIn("error", pile, pile)
seen = pile["seen"]
self.assertGreaterEqual(seen[0]["open"], 3, seen)
self.assertEqual(seen[-1]["open"], 1, seen)
for state in seen:
self.assertEqual(len(state["layers"]), min(2, state["open"] - (0 if state["release"] else 1)), state)
for layer in state["layers"]:
self.assertEqual(layer, {"size": True, "above": True, "lower": True, "inert": True}, state)
if __name__ == "__main__":
unittest.main()
+170
View File
@@ -0,0 +1,170 @@
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
from hub_case import HubCase
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-039-shots"))
INIT = """() => {
window.e2eViolations = [];
document.addEventListener("securitypolicyviolation", (event) => window.e2eViolations.push(`${event.violatedDirective} ${event.blockedURI}`));
const real = window.fetch.bind(window);
window.e2eSent = [];
window.fetch = (input, options) => {
const url = String(input && input.url ? input.url : input);
if (url.startsWith("/api/match") && window.e2eMatch) {
return Promise.resolve(new Response(JSON.stringify({cards: window.e2eMatch}), {headers: {"Content-Type": "application/json"}}));
}
if (url === "/api/messages" && options && options.method === "POST") {
window.e2eSent.push(JSON.parse(options.body));
}
return real(input, options);
};
}"""
STEPS = """
const served = async () => (await (await fetch("/api/match", {cache: "no-store"})).json()).cards;
const key = (name) => document.body.dispatchEvent(new KeyboardEvent("keydown", {key: name, bubbles: true}));
const actionable = async () => {
for (let tries = 0; tries < 6 && card() && card().querySelector(".match-stale-note, [data-stale='true']"); tries += 1) {
key("ArrowUp");
await sleep(600);
}
return card() && card().dataset.card;
};
const reject = async (words) => {
const id = await actionable();
key("ArrowLeft");
const field = await until(() => document.querySelector(".match-feedback"), 4000);
if (!field) {
return null;
}
field.value = words;
document.querySelector(".match-feedback-reject").click();
await until(() => !card() || card().dataset.card !== id, 4000);
return id;
};
const release = async () => {
const open = document.querySelector("#main .match-open-overview");
if (open && !open.hidden) {
open.click();
}
return until(() => document.querySelector("#main .match-overview"), 8000);
};
const serve = async (cards) => {
window.e2eMatch = cards;
await sleep(2600);
window.dispatchEvent(new Event("focus"));
};
"""
CHANGED = """(async () => {@HELPERS@@CARD@@STEPS@
await screenShown(8000);
if (!(await until(card, 8000))) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
await sleep(300);
const cards = await served();
const id = await reject("fix the probe");
await serve(cards.map((one) => (one.id === id ? {...one, hash: `${one.hash}0`} : one)));
await release();
const note = await until(() => document.querySelector(`#main .match-decision[data-card="${id}"] .match-decision-note`), 8000);
const row = document.querySelector(`#main .match-decision[data-card="${id}"]`);
return {id, verdict: row && row.dataset.verdict, note: note ? text(note) : null};
})()"""
ACCEPTED = """(async () => {@HELPERS@@CARD@@STEPS@
await screenShown(8000);
if (!(await until(card, 8000))) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
await sleep(300);
const cards = await served();
const id = await actionable();
const title = (cards.find((one) => one.id === id) || {}).title;
key("ArrowRight");
await until(() => !card() || card().dataset.card !== id, 4000);
const tally = () => text(document.querySelector("#main .match-tally"));
const before = tally();
const shown = new Set(all("#toasts .toast"));
await serve(cards.map((one) => (one.id === id ? {...one, hash: `${one.hash}0`} : one)));
const toast = await until(() => all("#toasts .toast").filter((node) => !shown.has(node)).map(text).find((entry) => entry.startsWith("Accept dropped")), 8000);
return {id, title, before, after: tally(), toast: toast || null};
})()"""
WITHDRAWN = """(async () => {@HELPERS@@CARD@@STEPS@
await screenShown(8000);
if (!(await until(card, 8000))) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
await sleep(300);
const cards = await served();
const id = await reject("withdrawn probe");
const title = (cards.find((one) => one.id === id) || {}).title;
await serve(cards.filter((one) => one.id !== id));
await release();
const row = await until(() => document.querySelector(`#main .match-decision[data-card="${id}"][data-withdrawn="true"]`), 8000);
const button = document.querySelector("#main .match-release");
if (!row || !button) {
return {id, row: Boolean(row), button: Boolean(button)};
}
button.click();
await until(() => window.e2eSent.length, 15000);
return {id, title, row: true, sent: window.e2eSent.map((message) => ({cls: message.class, text: message.text}))};
})()"""
def probe(template: str) -> str:
return template.replace("@HELPERS@", base.HELPERS).replace("@CARD@", matched.CARD).replace("@STEPS@", STEPS)
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestMatchRejects(HubCase):
drive = base.OrchestratorE2ECase.drive
authenticator = base.OrchestratorE2ECase.authenticator
cards = matched.TestMatchReview.cards
review = matched.TestMatchReview.review
payload = matched.TestMatchReview.payload
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
self.cards()
self.base = f"http://localhost:{self.port}/"
def test_chromium_keeps_a_reject_across_a_changed_or_withdrawn_card_and_drops_a_changed_accept_with_a_toast(self):
at = {"width": 1366, "height": 900}
steps = [
{**at, "url": f"{self.base}?changed#tasks/match", "wait": 1500, "probe": probe(CHANGED), "shot": str(OUT / "chromium-changed.png")},
{**at, "url": f"{self.base}?accepted#tasks/match", "wait": 1500, "probe": probe(ACCEPTED), "shot": str(OUT / "chromium-accepted.png")},
{**at, "url": f"{self.base}?withdrawn#tasks/match", "wait": 1500, "probe": probe(WITHDRAWN), "shot": str(OUT / "chromium-withdrawn.png")},
]
data = self.drive(steps, self.authenticator(), init=INIT)
(OUT / "chromium-match-rejects.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], [])
changed, accepted, withdrawn = data["results"]
with self.subTest(case="changed reject"):
self.assertNotIn("error", changed, changed)
self.assertEqual(changed["verdict"], "reject", changed)
self.assertIn("changed since your reject", changed["note"], changed)
with self.subTest(case="changed accept"):
self.assertNotIn("error", accepted, accepted)
self.assertEqual((accepted["before"], accepted["after"]), ("1", "0"), accepted)
self.assertIn(accepted["title"], accepted["toast"] or "", accepted)
with self.subTest(case="withdrawn reject"):
self.assertNotIn("error", withdrawn, withdrawn)
self.assertTrue(withdrawn["row"], withdrawn)
calls = [message for message in withdrawn["sent"] if message["cls"] == "call"]
self.assertEqual(len(calls), 1, withdrawn)
self.assertIn(withdrawn["title"], calls[0]["text"], withdrawn)
self.assertIn("withdrawn probe", calls[0]["text"], withdrawn)
if __name__ == "__main__":
unittest.main()
+193
View File
@@ -0,0 +1,193 @@
from __future__ import annotations
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
import test_match_review_e2e as matched
from hub_case import HubCase
from kvb_orchestrator import batches
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-040-shots"))
INIT = """() => {
window.e2eViolations = [];
document.addEventListener("securitypolicyviolation", (event) => window.e2eViolations.push(`${event.violatedDirective} ${event.blockedURI}`));
const real = window.fetch.bind(window);
window.e2eSubmits = [];
window.e2eMatch = null;
window.fetch = (input, options) => {
const url = String(input && input.url ? input.url : input);
if (url.startsWith("/api/match") && window.e2eMatch) {
return Promise.resolve(new Response(JSON.stringify({cards: window.e2eMatch}), {headers: {"Content-Type": "application/json"}}));
}
if (url === "/api/inbox/approve" && options && typeof options.body === "string") {
window.e2eSubmits.push(JSON.parse(options.body).items.map((item) => [item.kind, item.id, item.verb]));
}
return real(input, options);
};
}"""
STEPS = """
const served = async () => (await (await fetch("/api/match", {cache: "no-store"})).json()).cards;
const key = (name) => document.body.dispatchEvent(new KeyboardEvent("keydown", {key: name, bubbles: true, cancelable: true}));
const releasing = () => Boolean(card() && card().classList.contains("match-release-card"));
const decideAll = async () => {
for (let tries = 0; tries < 10 && card() && !releasing(); tries += 1) {
const front = card();
const id = front.dataset.card;
key(front.dataset.stale === "true" || front.hasAttribute("data-blocked") ? "ArrowUp" : "ArrowRight");
await until(() => !card() || card().dataset.card !== id, 4000);
await sleep(200);
}
return releasing();
};
const swipeRight = async () => {
const head = card().querySelector(".match-head");
const box = head.getBoundingClientRect();
const [x, y] = [box.left + box.width / 2, box.top + 20];
const dx = card().getBoundingClientRect().width * 0.4;
const at = (cx) => ({bubbles: true, cancelable: true, pointerId: 12, pointerType: "touch", isPrimary: true, button: 0, clientX: cx, clientY: y});
head.dispatchEvent(new PointerEvent("pointerdown", at(x)));
window.dispatchEvent(new PointerEvent("pointermove", at(x + dx / 2)));
const leaning = card().dataset.leaning || "";
window.dispatchEvent(new PointerEvent("pointerup", at(x + dx)));
return leaning;
};
"""
CARD040 = """(async () => {@HELPERS@@CARD@@STEPS@
await screenShown(8000);
if (!(await until(card, 8000))) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
await sleep(300);
const found = {ready: await decideAll()};
const front = card();
found.release = Boolean(front && front.closest(".match-deck") && front.querySelector(".match-release"));
found.layers = all("#main .match-layer").map((node) => node.dataset.card);
found.block = Boolean(document.querySelector("#main .match-release-block"));
found.risk = all("#main .match-accept-risk").map((node) => [node.closest(".match-decision").dataset.card, node.getAttribute("aria-pressed")]);
found.label = text(document.querySelector("#main .match-release"));
key("ArrowLeft");
found.back = await until(() => !releasing() && card() && card().dataset.card, 4000);
document.querySelector("#main .match-open-overview").click();
found.again = Boolean(await until(releasing, 4000));
const cards = await served();
window.e2eMatch = [...cards, {...cards.find((one) => one.id === "@COMMIT@"), id: "review:e2e-new", ref: "e2e-new", hash: "e2e", title: "e2e: arrived meanwhile"}];
found.arrived = Boolean(await until(() => document.querySelector('#main .match-layer[data-card="review:e2e-new"]'), 10000));
found.stays = releasing();
window.e2eMatch = null;
found.wide = document.documentElement.scrollWidth > innerWidth + 1;
return found;
})()"""
RELEASE = """(async () => {@HELPERS@@CARD@@STEPS@
await screenShown(8000);
if (!(await until(card, 8000))) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
await sleep(300);
if (!(await decideAll())) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
const risk = () => document.querySelector('#main .match-decision[data-card="@RED@"] .match-accept-risk');
const pressed = [];
for (let clicks = 0; clicks < @CLICKS@; clicks += 1) {
risk().click();
await sleep(200);
pressed.push(risk().getAttribute("aria-pressed"));
}
const label = text(document.querySelector("#main .match-release"));
window.e2eSubmits.length = 0;
const leaning = @SWIPE@ ? await swipeRight() : (key("ArrowRight"), "");
await until(() => window.e2eSubmits.length >= @SUBMITS@, 20000);
await sleep(1500);
await until(() => card() && !releasing(), 8000);
return {pressed, label, leaning, submits: window.e2eSubmits, front: card() ? card().dataset.card : null, peeks: all("#main .match-peek").map((node) => node.dataset.card)};
})()"""
def probe(template: str, **names: str) -> str:
fills = {"@HELPERS@": base.HELPERS, "@CARD@": matched.CARD, "@STEPS@": STEPS, **{f"@{key.upper()}@": value for key, value in names.items()}}
for key, value in fills.items():
template = template.replace(key, value)
return template
class ReleaseDeck(HubCase):
drive = base.OrchestratorE2ECase.drive
authenticator = base.OrchestratorE2ECase.authenticator
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()
diff = [{"path": "src/red.py", "status": "M", "mode": "100644", "additions": 1, "deletions": 0, "patch": "@@ -1,1 +1,2 @@\n line 1\n+red line", "note": ""}]
arguments = {**self.arguments("feat: red gate", "", self.page("feature-red.html", "<!doctype html><title>p</title>")), "worktree": "/repo/.worktrees/feature/red", "branch": "feature/red", "agent": "Stage", "diff": diff, "gate": "fail"}
result = self.tool("review_request", arguments)
self.assertFalse(result["isError"], result)
self.red = result["structuredContent"]["id"]
self.base = f"http://localhost:{self.port}/"
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestMatchReleaseCard(ReleaseDeck):
def release(self, name: str, clicks: int, swipe: bool, submits: int) -> dict:
step = {"width": 1920, "height": 1080, "url": f"{self.base}?{name}#tasks/match", "wait": 1500, "shot": str(OUT / f"chromium-{name}.png"),
"probe": probe(RELEASE, red=f"review:{self.red}", clicks=str(clicks), swipe="true" if swipe else "false", submits=str(submits))}
with mock.patch.object(batches, "UNDO", 0.3):
data = self.drive([step], self.authenticator(), init=INIT)
(OUT / f"chromium-{name}.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
found = data["results"][0]
self.assertNotIn("error", found, found)
return found
def sorted_submits(self, found: dict) -> list[list[list[str]]]:
return [sorted(batch) for batch in found["submits"]]
def test_chromium_puts_the_release_card_in_front_of_greyed_and_new_cards_and_left_returns_to_the_stack(self):
steps = [{"width": width, "height": height, "url": f"{self.base}?{width}-card#tasks/match", "wait": 1500, "shot": str(OUT / f"chromium-{width}-release-card.png"),
"probe": probe(CARD040, commit=f"review:{self.commit}")} for width, height in ((390, 844), (1920, 1080))]
data = self.drive(steps, None, init=INIT)
(OUT / "chromium-release-card.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
for (width, _), found in zip(((390, 844), (1920, 1080)), data["results"], strict=True):
with self.subTest(width=width):
self.assertNotIn("error", found, found)
self.assertEqual((found["ready"], found["release"], found["block"], found["wide"]), (True, True, False, False), found)
self.assertIn(f"review:{self.stale}", found["layers"], found)
self.assertEqual(found["risk"], [[f"review:{self.red}", "false"]], found)
self.assertEqual(found["label"], "Release 2 decisions", found)
self.assertEqual(found["back"], f"review:{self.stale}", found)
self.assertEqual((found["again"], found["arrived"], found["stays"]), (True, True, True), found)
def test_chromium_release_by_arrow_leaves_the_red_gate_commit_in_the_stack_until_its_risk_is_accepted(self):
found = self.release("no-risk", 0, False, 1)
self.assertEqual(self.sorted_submits(found), [sorted([["review", self.commit, "approve"], ["operator", "operator/issue", "approve"]])], found)
self.assertEqual(found["label"], "Release 2 decisions", found)
self.assertIn(f"review:{self.red}", [found["front"], *found["peeks"]], found)
def test_chromium_release_by_swipe_signs_a_risk_accepted_red_gate_commit_on_its_own_first(self):
found = self.release("risk", 1, True, 2)
self.assertEqual((found["pressed"], found["leaning"], found["label"]), (["true"], "accept", "Release 3 decisions"), found)
self.assertEqual(self.sorted_submits(found), [[["review", self.red, "approve"]], sorted([["review", self.commit, "approve"], ["operator", "operator/issue", "approve"]])], found)
self.settle(lambda: self.status(self.red) == "approved" and self.status(self.commit) == "approved")
def test_chromium_a_withdrawn_risk_leaves_the_red_gate_commit_out_again(self):
found = self.release("withdrawn", 2, False, 1)
self.assertEqual((found["pressed"], found["label"]), (["true", "false"], "Release 2 decisions"), found)
self.assertEqual(self.sorted_submits(found), [sorted([["review", self.commit, "approve"], ["operator", "operator/issue", "approve"]])], found)
self.assertIn(f"review:{self.red}", [found["front"], *found["peeks"]], found)
if __name__ == "__main__":
unittest.main()
+5 -2
View File
@@ -84,8 +84,11 @@ FLOW = """(async () => {@HELPERS@
const leaned = await swipe(width * 0.4, 0);
await until(() => front() !== order[2], 3000);
order.push(front());
key("w");
await until(() => front() !== order[3], 3000);
order.push(front());
const short = await swipe(width * 0.1, 0);
const stayed = front() === order[3];
const stayed = front() === order[4];
await swipe(width * 0.4, 4);
const overview = await until(() => document.querySelector("#main .match-overview"), 3000);
const rows = overview ? all("#main .match-decision").map((item) => [item.dataset.card, item.dataset.verdict, text(item.querySelector(".match-decision-feedback"))]) : [];
@@ -175,7 +178,7 @@ class TestMatchRelease(HubCase):
def check_flow(self, found: dict) -> None:
reason = f"{FIRST}:3: rename it"
self.assertNotIn("error", found, found)
self.assertEqual(found["order"], [self.cards[0], self.cards[1], self.cards[2], self.cards[1]], found)
self.assertEqual(found["order"], [self.cards[0], self.cards[1], self.cards[2], "release", self.cards[1]], found)
self.assertEqual((found["prefill"], found["leaned"], found["short"], found["stayed"]), (reason, "accept", "accept", True), found)
expected = [[self.cards[0], "reject", f"{reason}\nalso add a test"], [self.cards[1], "accept", None], [self.cards[2], "accept", None]]
self.assertEqual(sorted(found["rows"]), sorted(expected), found)
+3 -6
View File
@@ -32,6 +32,7 @@ CARD = """
};
const head = () => ({
card: card().dataset.card, kind: card().dataset.kind, stale: card().dataset.stale, face: Boolean(card().querySelector(".match-who .avatar svg")),
opens: Boolean(card().querySelector(".match-who .avatar").closest("button.agent-link")),
name: text(card().querySelector(".match-name")), age: text(card().querySelector(".match-age")),
metrics: all(".match-metric", card()).map((chip) => [chip.dataset.metric, text(chip.querySelector("strong"))]),
under: Boolean(card().querySelector(".match-metrics")) && card().querySelector(".match-metrics").getBoundingClientRect().top >= card().querySelector(".match-name").getBoundingClientRect().bottom - 1,
@@ -182,9 +183,9 @@ class TestMatchReview(HubCase):
order = [path for path, _ in FILES]
paints = set()
for width, _ in widths:
stack, scroll, mark, command, stale = (next(results) for _ in range(5))
with self.subTest(width=width):
stack = next(results)
self.assertEqual((stack["card"], stack["kind"], stack["stale"], stack["face"]), (f"review:{self.commit}", "commit", "false", True), stack)
self.assertEqual((stack["card"], stack["kind"], stack["stale"], stack["face"], stack["opens"]), (f"review:{self.commit}", "commit", "false", True, True), stack)
self.assertEqual((stack["name"], stack["age"]), ("Skills", "3 days"), stack)
self.assertEqual((stack["metrics"], stack["under"]), ([["fix", "95"], ["break", "3"]], True), stack)
place = [["branch", "feature/match", "Branch: feature/match (click copies)"], ["repo", "repo", "Repository: /repo (click copies)"],
@@ -197,25 +198,21 @@ class TestMatchReview(HubCase):
self.assertEqual(stack["peeks"], ["operator:operator/issue", f"review:{self.stale}"], stack)
self.assertFalse(stack["accept"], stack)
self.assertFalse(stack["wide"], stack)
scroll = next(results)
self.assertEqual(scroll["steps"][0], order[:1], scroll)
self.assertEqual(scroll["steps"][-1], order, scroll)
for step in scroll["steps"]:
self.assertEqual(step, order[: len(step)], scroll)
self.assertGreater(len({len(step) for step in scroll["steps"]}), 2, scroll)
self.assertEqual(scroll["numbered"], [[path, True] for path in order], scroll)
mark = next(results)
self.assertEqual((mark["clicked"], mark["pressed"]), (True, True), mark)
self.assertEqual(mark["marks"], [["3", "use the helper here"], ["6", "long press note"]], mark)
self.assertEqual(mark["marked"], ["3", "6"], mark)
self.assertEqual((mark["presets"], mark["preset"]), (["long press note", "use the helper here"], ["use the helper here", True]), mark)
self.assertEqual(mark["count"], "2", mark)
command = next(results)
self.assertEqual((command["kind"], command["stale"], command["command"], command["why"]), ("command", "false", self.command, "file the release issue"), command)
self.assertEqual(command["where"], str(self.work), command)
self.assertEqual(command["payload"], [["body.md", "read", 14], ["link.md", "refused", 0]], command)
self.assertEqual((command["name"], command["age"]), ("Skills", "3 days"), command)
stale = next(results)
self.assertEqual((stale["kind"], stale["stale"], stale["accept"], stale["name"], stale["age"]), ("commit", "true", True, "Stage", "9 days"), stale)
self.assertIn("changed", stale["reason"])
self.assertEqual(len(paints), 1, paints)
+1 -1
View File
@@ -22,7 +22,7 @@ SIDE = """
const front = () => (card() ? card().dataset.card : null);
const tally = () => text(document.querySelector("#main .match-tally"));
const point = () => {
const name = card().querySelector(".match-name").getBoundingClientRect();
const name = card().querySelector(".match-age").getBoundingClientRect();
return {front: front(), x: Math.round(name.left + name.width / 2), y: Math.round(name.top + name.height / 2), width: card().getBoundingClientRect().width};
};
const aim = (x, y) => {
+1 -1
View File
@@ -68,7 +68,7 @@ FLOW = """(async () => {@HELPERS@
}
return send(path, init);
};
const card = () => document.querySelector("#main .match-card.front");
const card = () => document.querySelector("#main .match-card.front:not(.match-release-card)");
if (!(await until(card, 8000))) {
return {error: text(document.getElementById("main"))};
}
+111
View File
@@ -0,0 +1,111 @@
from __future__ import annotations
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 test_match_release_card_e2e as deck
from kvb_orchestrator import batches
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-055-shots"))
WASD = """(async () => {@HELPERS@@CARD@@STEPS@
await screenShown(8000);
if (!(await until(card, 8000))) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
await sleep(300);
const front = () => (card() ? card().dataset.card : null);
const tally = () => text(document.querySelector("#main .match-tally"));
const press = async (name) => {
const was = front();
key(name);
await until(() => front() !== was, 3000);
await sleep(250);
return front();
};
const seen = [front()];
seen.push(await press("d"));
seen.push(await press("w"));
seen.push(await press("d"));
const decided = tally();
const undone = [await press("s"), await press("s"), await press("s")];
const cleared = tally();
for (let tries = 0; tries < 4 && !card().querySelector(".match-file tr[data-line]"); tries += 1) {
await press("w");
}
const row = card().querySelector(".match-file tr[data-line]");
let typed = null;
if (row) {
const spot = row.getBoundingClientRect();
row.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, clientX: spot.left + 40, clientY: spot.top + 4, button: 2}));
const field = await until(() => card().querySelector(".match-comment textarea"), 3000);
const was = front();
field.focus();
field.dispatchEvent(new KeyboardEvent("keydown", {key: "d", bubbles: true, cancelable: true}));
await sleep(500);
typed = {front: front() === was, tally: tally()};
card().querySelector(".match-comment .btn.ghost").click();
}
key("a");
const sheet = Boolean(await until(() => document.querySelector(".sheet-box .match-feedback"), 3000));
document.querySelector(".sheet-box .btn.ghost").click();
await sleep(300);
for (let tries = 0; tries < 4 && (front() === "@RED@" || card().dataset.stale === "true"); tries += 1) {
await press("w");
}
await press("d");
const lap = [front()];
for (let step = 0; step < 8; step += 1) {
lap.push(await press("w"));
}
while (front() !== "release") {
await press("w");
}
const onRelease = {a: await press("a")};
document.querySelector("#main .match-open-overview").click();
await until(releasing, 3000);
onRelease.w = await press("w");
onRelease.s = await press("s");
window.e2eSubmits.length = 0;
key("d");
await until(() => window.e2eSubmits.length, 20000);
onRelease.d = window.e2eSubmits;
return {seen, decided, undone, cleared, typed, sheet, lap, onRelease};
})()"""
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestMatchWasd(deck.ReleaseDeck):
def test_chromium_runs_the_deck_with_wasd_undoes_step_by_step_and_brings_the_release_card_once_a_lap(self):
OUT.mkdir(parents=True, exist_ok=True)
step = {"width": 1920, "height": 1080, "url": f"{self.base}?wasd#tasks/match", "wait": 1500, "shot": str(OUT / "chromium-wasd.png"), "probe": deck.probe(WASD, red=f"review:{self.red}")}
with mock.patch.object(batches, "UNDO", 0.3):
data = self.drive([step], self.authenticator(), init=deck.INIT)
(OUT / "chromium-wasd.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
found = data["results"][0]
self.assertNotIn("error", found, found)
first, second, third, _ = found["seen"]
self.assertEqual(found["decided"], "2", found)
self.assertEqual(found["undone"], [third, second, first], found)
self.assertEqual(found["cleared"], "0", found)
self.assertEqual(found["typed"], {"front": True, "tally": "0"}, found)
self.assertTrue(found["sheet"], found)
lap = found["lap"]
period = lap.index(lap[0], 1)
self.assertEqual(lap[period:], lap[: len(lap) - period], found)
self.assertEqual(lap[:period].count("release"), 1, found)
self.assertNotIn("release", [found["onRelease"]["a"], found["onRelease"]["w"]], found)
self.assertEqual(found["onRelease"]["s"], "release", found)
self.assertEqual(len(found["onRelease"]["d"]), 1, found)
if __name__ == "__main__":
unittest.main()
+82
View File
@@ -0,0 +1,82 @@
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
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-050-shots"))
MENU = """(async () => {@HELPERS@
const menu = await until(() => document.querySelector("#main .stream-head details.menu"), 8000);
if (!menu) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
const open = async () => {
if (!menu.open) {
menu.querySelector("summary").click();
}
await until(() => menu.open, 2000);
};
const chips = () => all('.menu-box [aria-label="Kinds"] .chip', menu);
const states = () => chips().map((chip) => chip.getAttribute("aria-pressed"));
const leave = () => menu.dispatchEvent(new PointerEvent("pointerleave", {pointerType: "mouse"}));
const enter = () => menu.dispatchEvent(new PointerEvent("pointerenter", {pointerType: "mouse"}));
await open();
const before = states();
for (const index of [0, 1, 2]) {
chips()[index].click();
await sleep(300);
}
const after = states();
const kept = menu.open;
leave();
await sleep(2500);
const at25 = menu.open;
await sleep(1000);
const at35 = menu.open;
await open();
leave();
await sleep(2000);
enter();
await sleep(1500);
const back = menu.open;
document.getElementById("main").click();
await sleep(50);
const outside = menu.open;
await open();
document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true, cancelable: true}));
await sleep(50);
const escaped = menu.open;
await open();
return {before, after, kept, at25, at35, back, outside, escaped};
})()"""
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestMenusStayOpen(base.OrchestratorE2ECase):
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
def test_chromium_keeps_the_stream_filter_open_through_chip_clicks_and_closes_it_3_s_after_the_pointer_left(self):
step = {"width": 1920, "height": 1080, "url": f"{self.base}?menu#stream", "wait": 1500, "probe": MENU.replace("@HELPERS@", base.HELPERS), "shot": str(OUT / "chromium-1920-filter-menu.png")}
data = self.drive([step], None)
(OUT / "chromium-menu.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
found = data["results"][0]
self.assertNotIn("error", found, found)
self.assertEqual(len(found["before"]), len(found["after"]), found)
self.assertEqual([found["before"][index] != found["after"][index] for index in range(3)], [True, True, True], found)
self.assertEqual((found["kept"], found["at25"], found["at35"], found["back"]), (True, True, False, True), found)
self.assertEqual((found["outside"], found["escaped"]), (False, False), found)
if __name__ == "__main__":
unittest.main()
+24 -8
View File
@@ -28,12 +28,16 @@ SCAN = """
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");
const tail = line ? [...frame.children].slice([...frame.children].indexOf(button) + 1) : [];
const end = line ? frame.lastElementChild.getBoundingClientRect() : null;
const spans = (box) => Math.abs(box.top - outer.top - 1) <= 1 && Math.abs(outer.bottom - 1 - box.bottom) <= 1;
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,
id: field.id, label: field.getAttribute("aria-label") || "", framed: true, line,
last: line ? field.nextElementSibling === button && tail.every((node) => node.matches("button[type=submit]")) : Boolean(foot) && button.parentElement === foot && field.nextElementSibling === foot && [...foot.children].slice([...foot.children].indexOf(button) + 1).every((node) => node.matches(".ptt-split, .mayday-toggle")),
fits: line ? spans(mic) && Math.abs(outer.right - 1 - end.right) <= 1 : mic.bottom <= outer.bottom && mic.top >= text.bottom - 1,
divider: line ? getComputedStyle(button).borderLeftWidth : getComputedStyle(foot).borderTopWidth,
clear: line ? text.right <= mic.left + 0.5 : true,
send: tail.map((node) => ({fits: spans(node.getBoundingClientRect()), divider: getComputedStyle(node).borderLeftWidth, own: getComputedStyle(node).borderTopWidth})),
};
});
const ring = (field) => {
@@ -46,7 +50,13 @@ SCAN = """
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()};
const other = await until(() => document.querySelector("#main .option.other .mic-frame"), 8000);
const extra = document.body.appendChild(document.createElement("textarea"));
await sleep(100);
extra.remove();
await sleep(100);
const sends = other.closest("form").querySelectorAll("button[type=submit]").length;
return {mics: scan(), sends, ring: ring(field), wide: wide()};
})()"""
RULES = """(async () => {@HELPERS@@SCAN@
(await until(() => document.getElementById("controls-tab-rules"), 15000)).click();
@@ -58,10 +68,11 @@ RADIO = """(async () => {@HELPERS@@SCAN@
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");
const mic = foot.querySelector(":scope > button.mic");
const idle = getComputedStyle(mic).backgroundColor;
mic.setAttribute("aria-pressed", "true");
const recording = getComputedStyle(mic).backgroundColor;
mic.setAttribute("aria-pressed", "false");
area.style.height = "260px";
await sleep(100);
const after = scan().find((entry) => entry.id === area.id);
@@ -87,6 +98,8 @@ class TestMicFrames(HubCase):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
self.claim("s1", "Skills")
decided = self.tool("decision_request", {"question": "Merge the mic frames?", "options": hub_support.OPTIONS, "agent": "Skills", "recommended": ""})
self.assertFalse(decided["isError"], decided)
self.snapshot()
self.page_url = f"http://localhost:{self.port}/"
@@ -117,6 +130,9 @@ class TestMicFrames(HubCase):
self.assertNotIn("error", found, found)
self.check_mics(found["mics"])
self.assertFalse(found["wide"])
other = [entry for entry in stream["mics"] if entry["label"].startswith("Other answer to ")]
self.assertEqual([entry["send"] for entry in other], [[{"fits": True, "divider": "1px", "own": "0px"}]], other)
self.assertEqual(stream["sends"], 1)
self.assertEqual(stream["ring"], ["solid", "none"])
self.assertEqual(radio["ring"], ["solid", "none"])
self.assertEqual(radio["record"], "Record")
+103 -33
View File
@@ -1,9 +1,11 @@
from __future__ import annotations
import datetime
import json
import os
import shutil
import sys
import time
import unittest
from pathlib import Path
@@ -24,64 +26,103 @@ LABELS = [
("channel-aloud", "Read radio aloud"),
("channel-title", "Waiting count in the tab title"),
]
SOURCES = [("resources", "Resource warnings"), ("mayday", "MAYDAY calls"), ("dream", "Dream reminder")]
ON = {"browser": True, "sounds": True, "aloud": True, "title": True}
SECTIONS = ["Ambience", "Location", "Appearance", "Music", "Undo window", "Passkey"]
KIT = """
const boxes = (group) => all("input[type=checkbox]", group).map((box) => [box.name, box.checked, words(box.closest("label"))]);
const rows = (fold) => all(".notify-source", fold).map((row) => [row.dataset.source, row.dataset.state, words(row.querySelector("label")), text(row.querySelector(".notify-state")), all("button", row).map(text)]);
const stored = async () => (await (await fetch("/api/state", {cache: "no-store"})).json()).settings;
const fold = async () => {
location.hash = "#stream/radio";
const notify = await until(() => document.querySelector("#radio-spot details.radio-notify"), 8000);
if (notify && !notify.open) {
notify.querySelector("summary").click();
await sleep(400);
}
const group = notify ? await until(() => notify.querySelector("fieldset.channels"), 8000) : null;
return {notify, group};
};
const sheet = async () => {
document.getElementById("settings-open").click();
const form = await until(() => document.querySelector(".sheet-box form.settings"), 8000);
const group = form ? form.querySelector("fieldset.channels") : null;
if (group) {
group.scrollIntoView({block: "center"});
await sleep(300);
const found = form ? {sections: all("section > h3", form).map(text), channels: all("fieldset.channels, .notify-source", form).length} : null;
if (form) {
all("button", form).find((button) => text(button) === "Cancel").click();
await until(() => !document.querySelector(".sheet-box form.settings"), 8000);
}
return {form, group};
return found;
};
const look = (form, group) => {
const box = group.getBoundingClientRect();
const look = (notify, group) => {
const layer = notify.querySelector(".station-body").getBoundingClientRect();
return {
legend: text(group.querySelector("legend")), boxes: boxes(group), sections: all("section > h3", form).map(text), clashes: clashes(form),
inside: box.left >= -1 && box.right <= innerWidth + 1, wide: document.documentElement.scrollWidth > innerWidth + 1,
legend: text(group.querySelector("legend")), boxes: boxes(group), sources: rows(notify), clashes: clashes(notify.querySelector(".station-body")),
inDevice: Boolean(notify.closest(".radio-device > .radio-settings")), stations: Boolean(notify.closest(".radio-settings").querySelector("details.radio-station")),
inside: layer.left >= -1 && layer.right <= innerWidth + 1, wide: document.documentElement.scrollWidth > innerWidth + 1,
};
};
const save = async (group, on) => {
for (const box of all("input[type=checkbox]", group)) {
const save = async (on) => {
for (const name of @NAMES@) {
const {group} = await fold();
const box = group.querySelector(`input[name="${name}"]`);
if (box.checked !== on) {
box.click();
}
const key = name.replace("channel-", "");
const end = Date.now() + 8000;
while (Date.now() < end && (await stored()).channels[key] !== on) {
await sleep(200);
}
}
const shown = boxes(group);
group.closest("form").querySelector('button[type="submit"]').click();
const closed = Boolean(await until(() => !document.querySelector(".sheet-box form.settings"), 8000));
const {group} = await fold();
const titled = Boolean(await until(() => (on ? /@TITLED@/.test(document.title) : document.title === "@PLAIN@"), 8000));
const stored = (await (await fetch("/api/state", {cache: "no-store"})).json()).settings.channels;
return {shown, closed, titled, title: document.title, stored};
return {shown: boxes(group), titled, title: document.title, stored: (await stored()).channels};
};
"""
OPENED = """(async () => {@HELPERS@@OVERLAP@@KIT@
await screenShown(8000);
await until(() => /@TITLED@/.test(document.title), 8000);
const title = document.title;
const {form, group} = await sheet();
return group ? {title, ...look(form, group)} : {error: text(document.querySelector(".sheet-box")), title};
const general = await sheet();
const {notify, group} = await fold();
return group ? {title, general, ...look(notify, group)} : {error: "no channel group in the Device card", title};
})()"""
SWITCHED = """(async () => {@HELPERS@@OVERLAP@@KIT@
const group = document.querySelector(".sheet-box fieldset.channels");
return group ? save(group, @ON@) : {error: "no channel group"};
return save(@ON@);
})()"""
SAVED_ON = """(async () => {@HELPERS@@OVERLAP@@KIT@
const group = document.querySelector(".sheet-box fieldset.channels");
if (!group) {
return {error: "no channel group"};
}
const saved = await save(group, true);
const again = await sheet();
const saved = await save(true);
document.querySelector("#radio-spot details.radio-notify").open = false;
await sleep(300);
const again = await fold();
return {...saved, reopened: again.group ? boxes(again.group) : null};
})()"""
SNOOZED = """(async () => {@HELPERS@@OVERLAP@@KIT@
await screenShown(8000);
const {notify} = await fold();
const row = (id) => notify.querySelector(`.notify-source[data-source="${id}"]`);
const button = (id, label) => all("button", row(id)).find((item) => text(item) === label);
const wait = async (id, state) => Boolean(await until(() => row(id) && row(id).dataset.state === state, 8000));
const before = rows(notify);
const titles = all(".notify-source button", notify).map((item) => item.getAttribute("title"));
button("resources", "1 h").click();
const hour = await wait("resources", "snoozed");
const snoozed = rows(notify);
row("mayday").querySelector('input[type="checkbox"]').click();
const off = await wait("mayday", "off");
button("dream", "8:00").click();
const morning = await wait("dream", "snoozed");
const after = rows(notify);
const dream = (await stored()).popups.dream;
button("dream", "Resume").click();
const resumed = await wait("dream", "on");
return {before, titles, hour, snoozed, off, morning, after, dream, resumed, last: rows(notify), popups: (await stored()).popups, toasts: all("#toasts .toast").map(text)};
})()"""
def fill(probe: str) -> str:
return probe.replace("@HELPERS@", base.HELPERS).replace("@OVERLAP@", base.OVERLAP).replace("@KIT@", KIT).replace("@TITLED@", TITLED).replace("@PLAIN@", PLAIN)
names = json.dumps([name for name, _ in LABELS])
return probe.replace("@HELPERS@", base.HELPERS).replace("@OVERLAP@", base.OVERLAP).replace("@KIT@", KIT).replace("@NAMES@", names).replace("@TITLED@", TITLED).replace("@PLAIN@", PLAIN)
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
@@ -97,7 +138,7 @@ class TestNotificationChannels(HubCase):
def legacy(self) -> None:
file = self.state / "settings.json"
older = {key: value for key, value in settings.SETTINGS.items() if key != "channels"}
older = {key: value for key, value in settings.SETTINGS.items() if key not in ("channels", "popups")}
file.write_text(json.dumps({**older, "notify": False}), encoding="utf-8")
held = self.httpd.hub.settings
with held.lock:
@@ -118,17 +159,18 @@ class TestNotificationChannels(HubCase):
self.assertNotIn("error", found, found)
self.assertEqual(data["errors"], [])
self.assertRegex(opened["title"], TITLED)
self.assertEqual(opened["general"], {"sections": SECTIONS, "channels": 0})
self.assertEqual((opened["legend"], opened["boxes"]), ("Notification channels", [[name, name != "channel-browser", label] for name, label in LABELS]))
self.assertEqual(opened["sections"], ["Ambience", "Location", "Appearance", "Music", "Notifications", "Passkey"])
self.assertEqual((opened["clashes"], opened["inside"], opened["wide"]), ({"found": [], "outside": []}, True, False), opened)
self.assertEqual((off["shown"], off["closed"], off["titled"], off["title"], off["stored"]), ([[name, False, label] for name, label in LABELS], True, True, PLAIN, dict.fromkeys(ON, False)), off)
self.assertEqual([row[:3] for row in opened["sources"]], [[source, "on", label] for source, label in SOURCES])
self.assertEqual((opened["inDevice"], opened["stations"], opened["clashes"], opened["inside"], opened["wide"]), (True, True, {"found": [], "outside": []}, True, False), opened)
self.assertEqual((off["shown"], off["titled"], off["title"], off["stored"]), ([[name, False, label] for name, label in LABELS], True, PLAIN, dict.fromkeys(ON, False)), off)
self.assertEqual((reloaded["title"], reloaded["boxes"], reloaded["clashes"]), (PLAIN, [[name, False, label] for name, label in LABELS], {"found": [], "outside": []}), reloaded)
self.assertEqual((back["closed"], back["titled"], back["stored"], back["reopened"]), (True, True, ON, [[name, True, label] for name, label in LABELS]), back)
self.assertEqual((back["titled"], back["stored"], back["reopened"]), (True, ON, [[name, True, label] for name, label in LABELS]), back)
self.assertRegex(back["title"], TITLED)
written = json.loads((self.state / "settings.json").read_text(encoding="utf-8"))
self.assertEqual((written["channels"], "notify" in written), (ON, False))
def test_chromium_migrates_the_old_notify_flag_and_switches_every_channel_off_and_on_through_a_reload_at_three_widths(self):
def test_chromium_migrates_the_old_notify_flag_and_switches_every_channel_off_and_on_in_the_device_card_through_a_reload_at_three_widths(self):
authenticator = self.authenticator()
for width, height in base.WIDTHS:
with self.subTest(width=width):
@@ -137,6 +179,34 @@ class TestNotificationChannels(HubCase):
(OUT / f"chromium-{width}-channels.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.check(data)
def test_chromium_snoozes_mutes_and_resumes_each_gnome_popup_source_and_writes_notify_json(self):
page = f"http://localhost:{self.port}/?popups"
started = time.time()
data = self.drive([{"width": 1366, "height": 900, "url": f"{page}#stream", "wait": 1200, "probe": fill(SNOOZED), "shot": str(OUT / "chromium-popups.png")}], self.authenticator())
(OUT / "chromium-popups.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual(data["errors"], [])
found = data["results"][0]
self.assertNotIn("error", found, found)
self.assertEqual([row[:3] for row in found["before"]], [[source, "on", label] for source, label in SOURCES])
self.assertEqual([row[4] for row in found["before"]], [["1 h", "8:00"]] * 3)
self.assertTrue(all(title.split(": ")[0] in dict(SOURCES).values() for title in found["titles"]), found["titles"])
self.assertEqual((found["hour"], found["off"], found["morning"], found["resumed"]), (True, True, True, True), found)
resources = found["snoozed"][0]
self.assertEqual((resources[1], resources[4]), ("snoozed", ["Resume", "1 h", "8:00"]))
self.assertRegex(resources[3], r"^snoozed until \d\d:\d\d$")
self.assertEqual(found["after"][1][1:], ["off", "MAYDAY calls", "off", []])
self.assertEqual(found["last"][2][1], "on")
popups = found["popups"]
self.assertEqual((popups["mayday"], popups["dream"]), ({"on": False, "until": 0}, {"on": True, "until": 0}))
self.assertTrue(popups["resources"]["on"])
self.assertLessEqual(abs(popups["resources"]["until"] - (started + 3600)), 120, popups)
written = json.loads((self.council / settings.NOTIFY).read_text(encoding="utf-8"))
self.assertEqual(written, popups)
morning = datetime.datetime.fromtimestamp(found["dream"]["until"])
self.assertEqual((found["dream"]["on"], morning.hour, morning.minute, morning.second), (True, 8, 0, 0), found["dream"])
self.assertLess(started, found["dream"]["until"])
self.assertLessEqual(found["dream"]["until"] - started, 33 * 3600)
if __name__ == "__main__":
unittest.main()
+157
View File
@@ -0,0 +1,157 @@
from __future__ import annotations
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
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-047-shots"))
LONG = "\n".join(f"echo line {number}" for number in range(1, 201))
SHIP = "make ship " + " ".join(f"ARG{number}=value" for number in range(40))
KIT = """
const press = async (button) => {
button.click();
await sleep(250);
return button.getAttribute("aria-expanded");
};
const look = (box) => {
const body = box.querySelector(".code-body");
const foot = box.querySelector(".code-foot");
return {
last: box.lastElementChild === foot, foot: all("button", foot).map(name), expanded: foot.querySelector(".code-eye").getAttribute("aria-expanded"),
clipped: body.scrollHeight > body.clientHeight + 1,
};
};
const toggle = async (box) => {
const eye = box.querySelector(".code-eye");
const first = {...look(box)};
const opened = await press(eye);
const full = {expanded: opened, clipped: look(box).clipped};
const closed = await press(eye);
return {first, full, closed: {expanded: closed, clipped: look(box).clipped}};
};
const loose = (selector) => all(selector).filter((node) => !node.closest(".code-box")).length;
"""
STREAM = """(async () => {@HELPERS@@KIT@
await streamShowsAll();
const rowOf = () => document.querySelector('#main .feed > li[data-ref="@ASK@"]');
const reviewOf = () => all("#main .feed > li.k-review").find((li) => !li.classList.contains("waiting") && text(li).includes("@REVIEW_TITLE@"));
await until(() => rowOf() && reviewOf(), 8000);
await sleep(1500);
const [row, review] = [rowOf(), reviewOf()];
if (!row || !review) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
const ask = await toggle(row.querySelector(".code-box"));
const box = review.querySelector(".code-box");
const before = box ? box.querySelectorAll(".diff-file").length : null;
box.querySelector(".code-eye").click();
const loaded = Boolean(await until(() => all("#main .feed > li.k-review").find((li) => text(li).includes("@REVIEW_TITLE@") && li.querySelector(".code-box .diff-file")), 8000));
return {ask, before, loaded, sheet: Boolean(document.querySelector("#sheet:not([hidden])")), loose: loose("#main .command, #main .diff-file"), wide: document.documentElement.scrollWidth > innerWidth + 1};
})()"""
OPERATOR = """(async () => {@HELPERS@@KIT@
const row = await until(() => document.querySelector('#main .inbox-list > li[data-ref="@ASK@"]'), 8000);
if (!row) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
return {ask: await toggle(row.querySelector(".code-box")), loose: loose("#main .command, #main .diff-file"), wide: document.documentElement.scrollWidth > innerWidth + 1};
})()"""
MATCH = """(async () => {@HELPERS@@KIT@
const front = () => document.querySelector("#main .match-card.front");
await until(front, 8000);
for (let tries = 0; tries < 12 && front() && front().dataset.card !== "@ASK@"; tries += 1) {
const id = front().dataset.card;
document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "w", bubbles: true, cancelable: true}));
await until(() => front() && front().dataset.card !== id, 3000);
await sleep(200);
}
const card = front();
if (!card || card.dataset.card !== "@ASK@") {
return {error: card ? card.dataset.card : "no card"};
}
const box = card.querySelector(".code-box");
const body = card.querySelector(".match-body");
return {box: look(box), place: box.dataset.place, scrolls: body.scrollHeight > body.clientHeight + 1, overflowY: getComputedStyle(body).overflowY,
page: document.documentElement.scrollHeight > innerHeight + 1, loose: loose("#main .match-command, #main .match-file")};
})()"""
TASKS = """(async () => {@HELPERS@@KIT@
const row = await until(() => document.querySelector('#main li[data-task="operator/ship"]'), 8000);
if (!row) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
const box = row.querySelector(".code-box");
const first = look(box);
box.querySelector(".code-eye").click();
const sheet = await until(() => document.querySelector('#sheet:not([hidden]) .code-box[data-place="sheet"]'), 4000);
const full = sheet ? text(sheet) : null;
document.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));
const closed = Boolean(await until(() => !document.querySelector("#sheet:not([hidden])"), 4000));
return {place: box.dataset.place, first, full, closed, loose: loose("#main .command, #main .diff-file")};
})()"""
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestOneCodeBox(base.OrchestratorE2ECase):
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
self.ask =f"ask:{self.create_ask({**ASK, 'command': LONG, 'timeout': 3600})}"
register = json.loads((self.council / "rasci.json").read_text(encoding="utf-8"))
register["operator/ship"] = {"title": SHIP, "workdir": "/repo", "status": "running", "roles": {"Operator": "R"}}
self.write_council({"rasci.json": register})
diff = [{"path": "src/box.py", "status": "M", "mode": "100644", "additions": 1, "deletions": 0, "patch": "@@ -1,1 +1,2 @@\n line 1\n+box line", "note": ""}]
self.review_title = "feat: decided box"
arguments = {**self.arguments(self.review_title, "", self.page("box.html", "<!doctype html><title>p</title>")), "worktree": "/repo/.worktrees/feature/box", "branch": "feature/box", "agent": "Stage", "diff": diff}
review = self.tool("review_request", arguments)["structuredContent"]["id"]
entries = [self.entry("review", review, "", "")]
with mock.patch.object(batches, "UNDO", 0.05):
self.assertEqual(self.approve(entries, self.signed(entries, self.pin()))[0], 202)
self.settle(lambda: self.status(review) == "approved")
def fill(self, probe: str) -> str:
return probe.replace("@HELPERS@", base.HELPERS).replace("@KIT@", KIT).replace("@ASK@", self.ask).replace("@REVIEW_TITLE@", self.review_title)
def test_chromium_puts_every_command_and_diff_in_one_code_box_whose_eye_toggles_in_place_at_1920_and_390(self):
steps = []
for width, height in ((1920, 1080), (390, 844)):
page = f"{self.base}?{width}"
steps += [
{"width": width, "height": height, "url": f"{page}-stream#stream", "wait": 1500, "probe": self.fill(STREAM), "shot": str(OUT / f"chromium-{width}-stream.png")},
{"width": width, "height": height, "url": f"{page}-operator#tasks/operator", "wait": 1500, "probe": self.fill(OPERATOR), "shot": str(OUT / f"chromium-{width}-operator.png")},
{"width": width, "height": height, "url": f"{page}-match#tasks/match", "wait": 1500, "probe": self.fill(MATCH), "shot": str(OUT / f"chromium-{width}-match.png")},
{"width": width, "height": height, "url": f"{page}-tasks#tasks/list", "wait": 1500, "probe": self.fill(TASKS), "shot": str(OUT / f"chromium-{width}-tasks.png")},
]
data = self.drive(steps, None)
(OUT / "chromium-code-box.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
for index, width in enumerate((1920, 390)):
stream, operator, match, tasks = data["results"][index * 4:index * 4 + 4]
with self.subTest(width=width):
for found in (stream, operator, match, tasks):
self.assertNotIn("error", found, found)
self.assertEqual(found["loose"], 0, found)
for found in (stream["ask"], operator["ask"]):
self.assertEqual((found["first"]["last"], found["first"]["expanded"], found["first"]["clipped"]), (True, "false", True), found)
self.assertEqual(found["first"]["foot"][:2], ["Copy", "Show all"], found)
self.assertTrue({"Grant", "Deny"} <= set(found["first"]["foot"]), found)
self.assertEqual(found["full"], {"expanded": "true", "clipped": False}, found)
self.assertEqual(found["closed"], {"expanded": "false", "clipped": True}, found)
self.assertEqual((stream["before"], stream["loaded"], stream["sheet"], stream["wide"], operator["wide"]), (0, True, False, False, False), stream)
self.assertEqual((match["place"], match["box"]["expanded"], match["box"]["last"], match["box"]["foot"]), ("open", "true", True, ["Copy", "Show less"]), match)
self.assertEqual((match["scrolls"], match["overflowY"], match["page"]), (True, "auto", False), match)
self.assertEqual((tasks["place"], tasks["first"]["expanded"], tasks["closed"]), ("closed", "false", True), tasks)
self.assertIn(SHIP, tasks["full"], tasks)
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -205,12 +205,12 @@ class TestOrchestratorE2E(base.OrchestratorE2ECase):
self.assertEqual(actions["keys"], ["#agents/chord", "#artifacts/tree", "#tasks/3d", "#home", "#stream"])
self.assertEqual(actions["ambience"], ["sky-look", "music-toggle", "leitstand", "notify"])
self.assertEqual((actions["settingsUnlabelled"], actions["popupUnlabelled"]), (0, 0))
self.assertEqual((actions["sections"], actions["radioFields"]), (["Ambience", "Location", "Appearance", "Music", "Notifications", "Passkey"], 0))
self.assertEqual((actions["sections"], actions["radioFields"]), (["Ambience", "Location", "Appearance", "Music", "Undo window", "Passkey"], 0))
for tool in ("Radio …", "Cancel mayday", "Priority …", "Drain", "Suspend", "Resume", "Controls …", "Settings …", "Look at the sky", "Toggle control room", "Enable notifications"):
with self.subTest(tool=tool):
self.assertTrue(any(tool in entry for entry in actions["palette"]), actions["palette"])
self.assertEqual(actions["popup"], [["post", True], ["call", False]])
self.assertEqual(actions["centred"], [True, "none"])
self.assertEqual(actions["leader"], [True, "inline"])
calm, chips = extra[4:]
self.assertRegex(calm["note"], r"Force · without motion \(prefers-reduced-motion\)$")
self.assertEqual({key: value for key, value in chips["inbox"].items() if key != "counted"}, {"hash": "#tasks/operator", "items": chips["inbox"]["counted"], "pressed": "true", "current": ["Tasks"]})
+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_box_heads_e2e as heads
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/pin-by-menu-shots"))
OLD = {"kind": "panel", "id": "tasks/list", "w": 6, "h": 4}
SEED = f"""(async () => {{
await ViewStore.update("home.pins", () => [{json.dumps(OLD)}]);
return true;
}})()"""
VIEW = """(async () => {@HELPERS@
await screenShown(8000);
await sleep(600);
return {owners: all("#main [data-panel], #main [data-item]").length, stars: all(".star, .star-row").length, slots: all("[data-star-slot]").length};
})()"""
MENU = """(async () => {@HELPERS@@HOME@
const read = async (hash, selector) => {
await go(hash);
const owner = await until(() => document.querySelector(selector), 8000);
if (!owner) {
return {error: hash};
}
const spotOf = (node) => [...node.children].find((child) => child.closest("[data-panel], [data-item]") === node) || node;
const label = async () => {
const live = document.querySelector(selector);
const item = live ? await pinItem(spotOf(live)) : null;
return [item ? menuLabel(item) : null, item];
};
const [before, item] = await label();
if (item) {
item.click();
await sleep(800);
}
const target = Panels.targetOf(owner);
const added = stored().includes(`${target.kind}:${target.id}`);
const [after] = await label();
await closeMenu();
return {before, added, after};
};
return {gantt: await read("tasks/gantt", '#main [data-panel="tasks/gantt"]'), stream: await read("stream", '#main [data-panel="stream"]')};
})()"""
TILES = """(async () => {@HELPERS@@HOME@
await go("home");
await until(() => tile("panel:tasks/list") && tile("panel:tasks/gantt") && tile("panel:stream"), 8000);
await sleep(400);
return {tiles: tiles(), stars: all(".star, .star-row").length, slots: all("[data-star-slot]").length};
})()"""
def probe(template: str) -> str:
return template.replace("@HELPERS@", base.HELPERS).replace("@HOME@", dash.HOME)
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestPinByMenu(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) -> list[dict]:
steps = []
for width, height in base.WIDTHS:
at = {"width": width, "height": height}
shot = OUT / f"chromium-{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": SEED, "shot": None},
]
steps += [{**at, "url": f"{self.base}?{width}-{view.replace('/', '-')}#{view}", "wait": 1500, "probe": probe(VIEW), "shot": f"{shot}-{view.replace('/', '-')}.png"} for view in heads.VIEWS]
steps += [
{**at, "url": None, "wait": 0, "probe": probe(MENU), "shot": f"{shot}-menu.png"},
{**at, "url": None, "wait": 0, "probe": probe(TILES), "shot": f"{shot}-home.png"},
]
return steps
def test_chromium_shows_no_star_and_pins_and_unpins_through_the_context_menu_keeping_an_old_pin(self):
data = self.drive(self.steps(), None, init=w4.GUARD)
(OUT / "chromium-pin-by-menu.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
results = iter(data["results"])
for width, _ in base.WIDTHS:
next(results)
next(results)
views = {view: next(results) for view in heads.VIEWS}
menu = next(results)
home = next(results)
with self.subTest(width=width, step="views"):
self.assertEqual({view: (row["stars"], row["slots"]) for view, row in views.items()}, dict.fromkeys(heads.VIEWS, (0, 0)), views)
self.assertGreater(sum(row["owners"] for row in views.values()), 0, views)
with self.subTest(width=width, step="menu"):
pinned = {"before": "Pin to Home", "added": True, "after": "Unpin from Home"}
self.assertEqual((menu["gantt"], menu["stream"]), (pinned, pinned), menu)
with self.subTest(width=width, step="home"):
self.assertEqual(home["tiles"], ["panel:tasks/list", "panel:tasks/gantt", "panel:stream"], home)
self.assertEqual((home["stars"], home["slots"]), (0, 0), home)
if __name__ == "__main__":
unittest.main()
+131
View File
@@ -0,0 +1,131 @@
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_home_bookmarks_e2e as bm
from hub_case import HubCase
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-059-shots"))
INIT = """() => {
window.e2eViolations = [];
document.addEventListener("securitypolicyviolation", (event) => window.e2eViolations.push(`${event.violatedDirective} ${event.blockedURI}`));
window.e2eHidden = false;
Object.defineProperty(Document.prototype, "hidden", {configurable: true, get: () => window.e2eHidden});
window.e2eAudio = {starts: 0, stops: 0};
const start = OscillatorNode.prototype.start;
const stop = OscillatorNode.prototype.stop;
OscillatorNode.prototype.start = function (...args) { window.e2eAudio.starts += 1; return start.apply(this, args); };
OscillatorNode.prototype.stop = function (...args) { window.e2eAudio.stops += 1; return stop.apply(this, args); };
}"""
POLLS = """(async () => {@HELPERS@
await streamShowsAll();
const list = await until(() => document.querySelector('#main [data-panel="stream"]') && document.querySelector('#main [data-panel="stream"] li.entry') ? document.querySelector('#main [data-panel="stream"]') : null, 10000);
if (!list) {
return {error: text(document.getElementById("main"))};
}
await sleep(1500);
const first = list.querySelector("li.entry");
let replaced = 0;
new MutationObserver((records) => { replaced += records.length; }).observe(list, {childList: true});
await sleep(11500);
const kept = {connected: first.isConnected, replaced, rows: list.querySelectorAll("li.entry").length};
const note = document.getElementById("sky-note");
let sky = 0;
new MutationObserver((records) => { sky += records.length; }).observe(note, {childList: true, characterData: true, subtree: true});
window.e2eHidden = true;
document.dispatchEvent(new Event("visibilitychange"));
await sleep(11500);
const hidden = sky;
window.e2eHidden = false;
document.dispatchEvent(new Event("visibilitychange"));
await sleep(3000);
return {kept, hidden, shown: sky - hidden, violations: window.e2eViolations};
})()"""
MUSIC = """(async () => {@HELPERS@
const audio = () => ({...window.e2eAudio});
const save = async (on, volume) => {
document.getElementById("settings-open").click();
const form = await until(() => document.querySelector("#sheet form.settings"), 5000);
if (!form) {
return false;
}
const box = [...form.querySelectorAll("label.check")].find((label) => label.textContent.includes("Music on")).querySelector("input");
box.checked = on;
form.querySelector('input[aria-label="Overall volume"]').value = String(volume);
form.requestSubmit();
return Boolean(await until(() => !document.querySelector("#sheet form.settings"), 8000));
};
const before = audio();
const on = await save(true, 0.5);
const started = await until(() => window.e2eAudio.starts >= before.starts + 4, 8000);
const loud = audio();
const quiet = await save(true, 0);
await sleep(3500);
const stopped = audio();
await sleep(6000);
const later = audio();
const rose = await save(true, 0.5);
const restarted = await until(() => window.e2eAudio.starts >= later.starts + 4, 8000);
const off = await save(false, 0.5);
return {saved: [on, quiet, rose, off], started: Boolean(started), restarted: Boolean(restarted), before, loud, stopped, later, violations: window.e2eViolations};
})()"""
def probe(template: str) -> str:
return template.replace("@HELPERS@", base.HELPERS)
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestPollCost(HubCase):
drive = base.OrchestratorE2ECase.drive
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
now = time.time()
self.write_council({"news.jsonl": self.jsonl([{"ts": now - 60 * n, "from": "One", "to": [], "text": f"row {n}"} for n in range(1, 6)])})
self.page_url = f"http://localhost:{self.port}/"
def test_chromium_keeps_stream_rows_across_polls_stops_the_sky_hidden_and_the_music_at_level_zero_at_three_widths(self):
steps = []
for width, height in base.WIDTHS:
at = {"width": width, "height": height}
shot = OUT / f"chromium-{width}"
steps += [
{**at, "url": f"{self.page_url}?{width}-clear#stream", "wait": 600, "probe": bm.CLEAR, "shot": None},
{**at, "url": f"{self.page_url}?{width}#stream", "wait": 1500, "probe": probe(POLLS), "shot": f"{shot}-stream.png"},
{**at, "url": None, "wait": 0, "probe": probe(MUSIC), "shot": None},
]
data = self.drive(steps, None, init=INIT)
(OUT / "chromium-poll-cost.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual(data["errors"], [])
results = iter(data["results"])
for width, _ in base.WIDTHS:
_, polls, music = next(results), next(results), next(results)
with self.subTest(width=width):
self.assertNotIn("error", polls, polls)
self.assertEqual((polls["kept"]["connected"], polls["kept"]["replaced"]), (True, 0), polls)
self.assertGreaterEqual(polls["kept"]["rows"], 5, polls)
self.assertEqual(polls["hidden"], 0, polls)
self.assertGreaterEqual(polls["shown"], 1, polls)
self.assertEqual(polls["violations"], [])
self.assertEqual(music["saved"], [True, True, True, True], music)
self.assertTrue(music["started"], music)
self.assertGreaterEqual(music["stopped"]["stops"] - music["loud"]["stops"], 4, music)
self.assertEqual(music["later"]["starts"], music["stopped"]["starts"], music)
self.assertTrue(music["restarted"], music)
self.assertEqual(music["violations"], [])
if __name__ == "__main__":
unittest.main()
+3 -4
View File
@@ -74,8 +74,7 @@ class TestRadioLayout(kit.RadioLayoutCase):
self.assertGreaterEqual(layout["sliver"], 10, layout)
self.assertTrue(layout["order"]["stacked" if width == 390 else "beside"], layout)
self.assertEqual(layout["labels"], 1, layout)
self.assertEqual(layout["stars"], [[part, True] for part in PARTS], layout)
self.assertEqual(layout["covered"], [], layout)
self.assertEqual((layout["pinnable"], layout["stars"]), ([[part, True] for part in PARTS], 0), layout)
self.assertEqual(layout["stations"], [True, False], layout)
def check_popup(self, popup: dict) -> None:
@@ -231,14 +230,14 @@ class TestRadioLayout(kit.RadioLayoutCase):
with self.subTest(browser=browser, width=width, part="fit view"):
self.check_fit(fit, (width, height))
def test_chromium_lays_the_radio_out_without_overflow_one_line_rows_popup_and_four_home_stars_at_four_widths(self):
def test_chromium_lays_the_radio_out_without_overflow_one_line_rows_popup_and_four_home_pins_at_four_widths(self):
data = self.drive(self.steps("chromium"), None)
(OUT / "chromium-radio-layout.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_lays_the_radio_out_without_overflow_one_line_rows_popup_and_four_home_stars_at_four_widths(self):
def test_firefox_lays_the_radio_out_without_overflow_one_line_rows_popup_and_four_home_pins_at_four_widths(self):
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"))
(OUT / "firefox-radio-layout.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
@@ -170,8 +170,8 @@ class TestRadioSet(HubCase):
self.assertEqual([row["line"] for row in log["narrowed"]], ["rebase done"])
self.assertEqual(log["none"][0], 0)
self.assertEqual(log["clearedChips"], [{"class": "", "from": "", "to": "", "agent": ""}, "", len(every)])
self.assertTrue(log["muted"][0].startswith("Mute "), log["muted"])
self.assertEqual((log["muted"][1:], log["unmuted"]), (["true", 1, False], ["false", 0]), log)
self.assertTrue(log["muted"][0].startswith("Open "), log["muted"])
self.assertEqual((log["muted"][1:], log["unmuted"]), (["true", {"sound": False, "aloud": False, "bubbles": True}, True], ["false", None]), log)
self.assertEqual(log["opened"][0], True)
self.assertTrue(log["opened"][1], log)
self.assertEqual(log["fits"], {"page": True, "panel": True})
+77
View File
@@ -0,0 +1,77 @@
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_line_comments_e2e as comments
MARKS = """(async () => {@HELPERS@@UNLABELLED@
const row = () => document.querySelector('#main .inbox-list > li[data-ref="@REVIEW@"]');
if (!(await until(row, 8000))) {
return {error: text(document.getElementById("main"))};
}
const to = row().dataset.to || null;
const lines = () => all("#sheet .review-file[data-path='src/app.py'] tr[data-line]");
const open = async () => {
row().querySelector(".headline").click();
return until(() => lines().length, 8000);
};
if (!(await open())) {
return {error: text(document.getElementById("sheet")), to};
}
const cell = lines()[2].querySelector("td.code");
const box = cell.getBoundingClientRect();
cell.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, clientX: box.left + 4, clientY: box.top + 4}));
const field = await until(() => document.querySelector("#sheet tr.match-comment textarea"), 4000);
if (!field) {
return {error: "no inline comment field", to, menu: Boolean(document.querySelector(".ctx-menu:not([hidden])"))};
}
field.value = "c";
all("#sheet tr.match-comment button").find((button) => name(button) === "Save comment").click();
await until(() => document.querySelector("#sheet tr.match-mark"), 4000);
const shown = all("#sheet tr.match-mark").map(text);
document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));
await until(() => document.getElementById("sheet").hidden, 4000);
await open();
const kept = all("#sheet tr.match-mark").map(text);
const via = all("#sheet .deny-split button").find((button) => name(button).startsWith("Deny via"));
if (via) {
via.click();
}
const reason = await until(() => document.querySelector(".sheet-box .deny-reason textarea"), 4000);
return {to, shown, kept, via: Boolean(via), reason: reason ? reason.value : null, wide: document.documentElement.scrollWidth > innerWidth + 1};
})()"""
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestReviewMarks(base.OrchestratorE2ECase):
def setUp(self):
super().setUp()
arguments = {**self.arguments(comments.TITLE, "", self.page("marks.html", comments.review_page())), "worktree": "/repo/.worktrees/feature/marks", "branch": "feature/marks"}
result = self.tool("review_request", arguments)
self.assertFalse(result["isError"], result)
self.review = result["structuredContent"]["id"]
def test_chromium_marks_a_line_in_the_review_modal_of_a_card_without_requester_and_keeps_it_for_the_deny_reason(self):
probe = MARKS.replace("@HELPERS@", base.HELPERS).replace("@UNLABELLED@", base.UNLABELLED).replace("@REVIEW@", f"review:{self.review}")
step = {"width": 1366, "height": 768, "url": f"http://localhost:{self.port}/?marks#stream/inbox", "wait": 1200, "probe": probe, "shot": self.shot("1366-review-marks")}
data = self.drive([step], None)
(Path(self.shot("1366-review-marks")).with_suffix(".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], [])
found = data["results"][0]
self.assertNotIn("error", found, found)
self.assertIsNone(found["to"], found)
self.assertEqual((found["shown"], found["kept"], found["via"], found["wide"]), (["c"], ["c"], True, False), found)
self.assertIn("src/app.py:3: c", found["reason"] or "", found)
if __name__ == "__main__":
unittest.main()
+117
View File
@@ -0,0 +1,117 @@
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
from hub_case import HubCase
from kvb_orchestrator import schedules
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-057-shots"))
FOREIGN = {"name": "backup.timer", "kind": "timer", "owner": "other", "unit": "backup.timer", "file": "/u/backup.timer", "schedule": "OnCalendar=daily", "next": 1_900_000_000, "last": None, "event": "", "command": "", "off": "systemctl --user disable --now backup.timer"}
HUB_UNIT = {**FOREIGN, "name": "kvb-orchestrator-tree.timer", "owner": "hub", "unit": "kvb-orchestrator-tree.timer", "off": ""}
PROBE = """(async () => {@HELPERS@@HOME@
const row = (name) => document.querySelector(`#main [data-schedule="${name}"]`);
const rows = async () => (await (await fetch("/api/state")).json()).schedules.rows;
const settle = async (check, ms) => {
const end = Date.now() + ms;
while (Date.now() < end) {
if (await check()) {
return true;
}
await sleep(200);
}
return false;
};
const owner = await until(() => document.querySelector('#main [data-panel="stream/schedules"]') && row("coach"), 8000);
if (!owner) {
return {error: text(document.getElementById("main"))};
}
const tabs = all('#main [role="tab"]').map((tab) => [tab.dataset.tab, tab.getAttribute("aria-selected")]);
const foreign = all("#main [data-schedule-foreign]").map((node) => ({name: node.dataset.scheduleForeign, switches: node.querySelectorAll('input[role="switch"]').length, copy: Boolean(node.querySelector('button[aria-label="Copy"]')), off: text(node.querySelector(".sched-off code"))}));
const flip = async (wanted) => {
row("coach").querySelector('input[role="switch"]').click();
return settle(async () => (await rows()).coach.on === wanted && row("coach") && row("coach").querySelector('input[role="switch"]').checked === wanted, 8000);
};
const on = await flip(true);
const off = await flip(false);
const times = row("dream-popup").querySelector("input.sched-times");
times.value = "21:30, 06:00";
times.dispatchEvent(new Event("change", {bubbles: true}));
const retimed = await settle(async () => JSON.stringify((await rows())["dream-popup"].at) === '["06:00","21:30"]', 8000);
const wide = document.documentElement.scrollWidth > innerWidth + 1;
const panel = document.querySelector('#main [data-panel="stream/schedules"]');
const spot = [...panel.children].find((node) => node.closest("[data-panel], [data-item]") === panel) || panel;
const item = await pinItem(spot);
const label = item ? menuLabel(item) : null;
if (item) {
item.click();
await sleep(300);
}
await closeMenu();
return {hash: location.hash, tabs, foreign, on, off, retimed, wide, label, pinned: stored().includes("panel:stream/schedules")};
})()"""
TILE = """(async () => {@HELPERS@@HOME@
await go("home");
const shown = await until(() => tile("panel:stream/schedules") && tile("panel:stream/schedules").querySelector('[data-schedule="coach"]'), 8000);
return {tile: Boolean(shown), switches: shown ? tile("panel:stream/schedules").querySelectorAll('input[role="switch"]').length : 0};
})()"""
def probe(template: str) -> str:
return template.replace("@HELPERS@", base.HELPERS).replace("@HOME@", dash.HOME)
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestSchedules(HubCase):
drive = base.OrchestratorE2ECase.drive
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
self.council.mkdir(parents=True, exist_ok=True)
(self.council / schedules.SCHEDULES_VIEW).write_text(json.dumps({"at": 1_800_000_000, "rows": [FOREIGN, HUB_UNIT]}), encoding="utf-8")
self.page_url = f"http://localhost:{self.port}/"
def test_chromium_opens_schedules_switches_coach_retimes_the_popup_shows_foreign_rows_read_only_and_pins_it_at_three_widths(self):
steps = []
for width, height in base.WIDTHS:
at = {"width": width, "height": height}
shot = OUT / f"chromium-{width}"
steps += [
{**at, "url": f"{self.page_url}?{width}-clear#stream", "wait": 600, "probe": bm.CLEAR, "shot": None},
{**at, "url": f"{self.page_url}?{width}#stream/schedules", "wait": 1500, "probe": probe(PROBE), "shot": f"{shot}-schedules.png"},
{**at, "url": None, "wait": 0, "probe": probe(TILE), "shot": f"{shot}-home.png"},
]
data = self.drive(steps, None)
(OUT / "chromium-schedules.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual(data["errors"], [])
results = iter(data["results"])
for width, _ in base.WIDTHS:
_, found, home = next(results), next(results), next(results)
with self.subTest(width=width):
self.assertNotIn("error", found, found)
self.assertEqual(found["tabs"], [["tools", "false"], ["rules", "false"], ["groups", "false"], ["schedules", "true"]])
self.assertEqual(found["hash"], "#stream/schedules")
self.assertEqual((found["on"], found["off"], found["retimed"], found["wide"]), (True, True, True, False))
self.assertEqual(found["foreign"], [
{"name": "backup.timer", "switches": 0, "copy": True, "off": "systemctl --user disable --now backup.timer"},
{"name": "kvb-orchestrator-tree.timer", "switches": 0, "copy": False, "off": None},
])
self.assertEqual((found["label"], found["pinned"]), ("Pin to Home", True))
self.assertEqual(home, {"tile": True, "switches": 5})
stored = json.loads((self.council / schedules.SCHEDULES).read_text(encoding="utf-8"))
self.assertEqual((stored["coach"], stored["dream-popup"]), ({"on": False, "every": 1}, {"on": False, "at": ["06:00", "21:30"]}))
if __name__ == "__main__":
unittest.main()
+127
View File
@@ -0,0 +1,127 @@
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-033-shots"))
COMPOSER = (hub_support.HUB / "templates" / "page-composer.js").read_text(encoding="utf-8")
HINTS = re.findall(r'^\s+"?[\w-]+"?: "([^"]+)",$', COMPOSER.split("const MAYDAY_ASK")[0], re.MULTILINE)
SHAPE = """
const hints = @HINTS@;
const role = (node) => [["channel", ".composer-grid"], ["text", "textarea"], ["foot", ".mic-foot"], ["mic", "button.mic"], ["ptt", ".ptt-split"], ["mayday", ".mayday-toggle"],
["spacer", ".spacer"], ["status", ".composer-status"], ["record", "button[aria-pressed]"]].find(([, selector]) => node.matches(selector))?.[0] || node.tagName.toLowerCase();
const edges = (node) => ["Top", "Right", "Bottom", "Left"].map((side) => getComputedStyle(node)[`border${side}Width`]);
const shape = (form) => {
const frame = form.querySelector(":scope > .mic-frame");
const foot = frame.querySelector(":scope > .mic-foot");
return {
frame: [...frame.children].map(role), foot: [...foot.children].map(role),
lines: {channel: edges(frame.querySelector(".composer-grid")), text: edges(frame.querySelector("textarea")), foot: getComputedStyle(foot).borderTopWidth},
titles: all("[title]", form).map((node) => node.title).filter((title) => hints.some((hint) => title.includes(hint))),
};
};
"""
RADIO = """(async () => {@HELPERS@@SHAPE@
const form = await until(() => document.querySelector("#radio-spot .radio-speak form.composer"), 15000);
await sleep(300);
return {shape: shape(form), wide: document.documentElement.scrollWidth > innerWidth + 1};
})()"""
HOME = """(async () => {@HELPERS@@SHAPE@
const misfits = [];
let first = null;
for (let rows = 3; rows <= 8; rows += 1) {
for (let cols = 4; cols <= 12; cols += 1) {
await ViewStore.update("home.pins", () => [{kind: "panel", id: "radio-speak", w: cols, h: rows}]);
const tile = await until(() => {
const node = document.querySelector('#main .home-tile[data-pin="panel:radio-speak"]');
return node && node.dataset.w === String(cols) && node.dataset.h === String(rows) && node.querySelector("form.composer .mayday-toggle") ? node : null;
}, 4000);
if (!tile) {
misfits.push({cols, rows, missing: true});
continue;
}
await sleep(40);
const body = tile.querySelector(".home-body").getBoundingClientRect();
const out = [".ptt-split", ".mayday-toggle"].filter((selector) => {
const edge = tile.querySelector(selector).getBoundingClientRect();
return !(edge.width > 0 && edge.left >= body.left - 0.5 && edge.right <= body.right + 0.5 && edge.top >= body.top - 0.5 && edge.bottom <= body.bottom + 0.5);
});
if (out.length) {
misfits.push({cols, rows, out});
}
if (!first) {
first = {shape: shape(tile.querySelector("form.composer")), speak: tile.querySelector(".home-body").innerText.includes("Speak")};
}
}
}
await ViewStore.update("home.pins", () => [{kind: "panel", id: "radio-speak", w: 6, h: 5}]);
await sleep(400);
return {misfits, first, wide: document.documentElement.scrollWidth > innerWidth + 1};
})()"""
FRAME = ["channel", "text", "foot"]
FOOT = ["record", "status", "spacer", "mic", "ptt", "mayday"]
LINES = {"channel": ["0px", "0px", "1px", "0px"], "text": ["0px", "0px", "0px", "0px"], "foot": "1px"}
def probe(template: str) -> str:
return template.replace("@HELPERS@", base.HELPERS).replace("@SHAPE@", SHAPE).replace("@HINTS@", json.dumps(HINTS))
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestSpeakBox(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_shape(self, shape: dict) -> None:
self.assertEqual((shape["frame"], shape["foot"]), (FRAME, FOOT), shape)
self.assertEqual((shape["lines"], shape["titles"]), (LINES, []), shape)
def test_the_hint_list_is_read_from_the_composer(self):
self.assertEqual(len(HINTS), 6, HINTS)
def test_chromium_draws_one_speak_frame_in_the_radio_view_and_keeps_ptt_and_mayday_inside_every_home_widget_size(self):
steps = []
for width, height in base.WIDTHS:
shot = OUT / f"chromium-{width}"
steps += [
{"width": width, "height": height, "url": f"{self.page_url}?{width}-radio#stream/radio", "wait": 1200, "probe": probe(RADIO), "shot": f"{shot}-radio-speak.png"},
{"width": width, "height": height, "url": f"{self.page_url}?{width}-home#home", "wait": 1200, "probe": probe(HOME), "shot": f"{shot}-home-speak.png"},
]
data = self.drive(steps, None)
(OUT / "chromium-speak-box.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual(data["errors"], [])
results = iter(data["results"])
for width, _ in base.WIDTHS:
radio, home = next(results), next(results)
with self.subTest(width=width, view="radio"):
self.assertNotIn("error", radio, radio)
self.check_shape(radio["shape"])
self.assertFalse(radio["wide"])
with self.subTest(width=width, view="home"):
self.assertNotIn("error", home, home)
self.assertEqual(home["misfits"], [], home["misfits"][:5])
self.check_shape(home["first"]["shape"])
self.assertFalse(home["first"]["speak"])
self.assertFalse(home["wide"])
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -116,8 +116,8 @@ class TestSpeakCard(base.OrchestratorE2ECase):
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.assertFalse(any(titled for _, titled in layout["channels"]), layout)
self.assertEqual(layout["radius"], ["14px", "0px", "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)
+74
View File
@@ -0,0 +1,74 @@
from __future__ import annotations
import json
import os
import shutil
import sys
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
from hub_case import HubCase
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-034-shots"))
BAND = """(async () => {@HELPERS@
if (!(await screenShown(8000))) {
return {error: "no screen"};
}
const main = document.getElementById("main");
const band = await until(() => main.querySelector(".stream-head"), 8000);
if (!band) {
return {error: text(main).slice(0, 300)};
}
await sleep(400);
const look = getComputedStyle(band);
const tile = document.body.appendChild(Object.assign(document.createElement("div"), {className: "home-tile"}));
const tint = getComputedStyle(tile).backgroundColor;
tile.remove();
const inner = () => main.getBoundingClientRect().top + parseFloat(getComputedStyle(main).borderTopWidth);
const before = band.getBoundingClientRect().top - inner();
band.parentElement.append(Object.assign(document.createElement("div"), {style: "height: 3000px"}));
main.scrollTop = 600;
await sleep(200);
const after = band.getBoundingClientRect().top - inner();
return {
first: band.parentElement.firstElementChild === band && main.firstElementChild === band.parentElement,
line: [look.borderBottomWidth, look.borderBottomStyle], lineColor: look.borderBottomColor === getComputedStyle(main.appendChild(Object.assign(document.createElement("i"), {style: "color: var(--line)"}))).color,
background: look.backgroundColor === tint, before: Math.round(before * 10) / 10, after: Math.round(after * 10) / 10, scrolled: main.scrollTop,
};
})()"""
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestStreamBand(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 test_chromium_keeps_the_stream_controls_in_a_flush_sticky_head_band(self):
steps = [
{"width": width, "height": height, "url": f"{self.page_url}?{width}#stream", "wait": 1200, "probe": BAND.replace("@HELPERS@", base.HELPERS), "shot": str(OUT / f"chromium-{width}-stream-band.png")}
for width, height in base.WIDTHS
]
data = self.drive(steps, None)
(OUT / "chromium-stream-band.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual(data["errors"], [])
for result, (width, _) in zip(data["results"], base.WIDTHS, strict=True):
with self.subTest(width=width):
self.assertNotIn("error", result, result)
self.assertEqual((result["first"], result["line"], result["lineColor"], result["background"]), (True, ["1px", "solid"], True, True), result)
self.assertLessEqual(abs(result["before"]), 1, result)
self.assertGreaterEqual(result["scrolled"], 600, result)
self.assertLessEqual(abs(result["after"] - result["before"]), 1, result)
if __name__ == "__main__":
unittest.main()
@@ -39,6 +39,7 @@ PROBE = """(async () => {@HELPERS@
field.dispatchEvent(new Event("input", {bubbles: true}));
field.setSelectionRange(6, 6);
const top = scroller.scrollTop;
all("#main .chip").find((chip) => text(chip) === "Transcripts").click();
const redrawn = await until(() => {
const [now, typed] = [askOf(), choiceOf()];
return now && typed && now.dataset.probe !== "old" && typed.dataset.probe !== "old" ? [now, typed] : null;
+83
View File
@@ -0,0 +1,83 @@
from __future__ import annotations
import json
import os
import shutil
import sys
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import test_match_release_card_e2e as deck
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-043-shots"))
WORDS = "10 s remain to undo"
TEXTS = """(async () => {@HELPERS@@CARD@@STEPS@
const row = () => document.querySelector('#main .inbox-list > li[data-ref="@RED@"]');
if (!(await until(row, 8000))) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
all(".deny-split button", row()).find((button) => name(button).startsWith("Deny via")).click();
const sheet = await until(() => document.querySelector(".sheet-box .deny-channels"), 4000);
const deny = sheet ? all(".sheet-box p.muted").map(text).find((line) => line.startsWith("The passkey signs the denial")) : null;
document.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));
await until(() => !document.querySelector(".sheet-box .deny-channels"), 4000);
document.getElementById("settings-open").click();
const dial = await until(() => document.querySelector(".sheet-box form.settings .undo-dial"), 8000);
if (!dial) {
return {deny, error: "no dial"};
}
dial.scrollIntoView({block: "center"});
await sleep(300);
const attrs = () => ["role", "aria-valuemin", "aria-valuemax", "aria-valuenow", "aria-valuetext"].map((attr) => dial.getAttribute(attr));
const dialed = {attrs: attrs(), label: dial.getAttribute("aria-label"), readout: text(dial.querySelector(".dial-readout")), ticks: all(".dial-tick", dial).length, long: all(".dial-tick.long", dial).length};
const press = (key) => {
dial.dispatchEvent(new KeyboardEvent("keydown", {key, bubbles: true, cancelable: true}));
return dial.getAttribute("aria-valuenow");
};
dial.focus();
const keys = [["ArrowRight", press("ArrowRight")], ["PageUp", press("PageUp")], ["End", press("End")], ["ArrowRight", press("ArrowRight")], ["PageDown", press("PageDown")], ["Home", press("Home")], ["ArrowLeft", press("ArrowLeft")]];
const zero = {text: dial.getAttribute("aria-valuetext"), readout: text(dial.querySelector(".dial-readout"))};
const box = dial.getBoundingClientRect();
return {deny, opened: dialed, keys, zero, focused: document.activeElement === dial, inside: box.left >= 0 && box.right <= innerWidth, wide: document.documentElement.scrollWidth > innerWidth + 1};
})()"""
RELEASED = """(async () => {@HELPERS@@CARD@@STEPS@
await screenShown(8000);
if (!(await until(card, 8000)) || !(await decideAll())) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
return {title: document.querySelector("#main .match-release").title};
})()"""
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestUndoDial(deck.ReleaseDeck):
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
payload = {**self.snapshot()["settings"], "undo": 10, "proof": None}
self.assertEqual(self.post_json("/api/settings", payload, self.guard(self.host))[0], 200)
def test_chromium_sets_the_undo_window_on_a_dial_and_every_undo_text_names_the_saved_seconds(self):
steps = [
{"width": 1366, "height": 768, "url": f"{self.base}?dial#stream/inbox", "wait": 1500, "shot": str(OUT / "chromium-1366-undo-dial.png"), "probe": deck.probe(TEXTS, red=f"review:{self.red}")},
{"width": 1920, "height": 1080, "url": f"{self.base}?dial-release#tasks/match", "wait": 1500, "shot": str(OUT / "chromium-1920-undo-release.png"), "probe": deck.probe(RELEASED)},
]
data = self.drive(steps, None, init=deck.INIT)
(OUT / "chromium-undo-dial.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], [])
texts, released = data["results"]
for found in (texts, released):
self.assertNotIn("error", found, found)
self.assertIn(f"then {WORDS}.", texts["deny"], texts)
self.assertEqual(texts["opened"], {"attrs": ["slider", "0", "60", "10", "10 seconds to undo"], "label": "Undo window in seconds", "readout": "10 s", "ticks": 60, "long": 12}, texts)
self.assertEqual(texts["keys"], [["ArrowRight", "11"], ["PageUp", "16"], ["End", "60"], ["ArrowRight", "60"], ["PageDown", "55"], ["Home", "0"], ["ArrowLeft", "0"]], texts)
self.assertEqual(texts["zero"], {"text": "0 seconds: takes effect at once", "readout": "0 s"}, texts)
self.assertEqual((texts["focused"], texts["inside"], texts["wide"]), (True, True, False), texts)
self.assertTrue(released["title"].endswith(f"after each signature {WORDS}."), released)
if __name__ == "__main__":
unittest.main()
+74
View File
@@ -0,0 +1,74 @@
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_line_comments_e2e as comments
from hub_support import iso
WHY = """(async () => {@HELPERS@@UNLABELLED@
const row = () => document.querySelector('#main .inbox-list > li[data-ref="@REVIEW@"]');
if (!(await until(row, 8000))) {
return {error: text(document.getElementById("main"))};
}
const described = (button) => {
const note = document.getElementById(button.getAttribute("aria-describedby") || "");
return note ? note.textContent : null;
};
const main = all(".deny-split button", row()).find((button) => name(button) === "Deny");
const split = {disabled: main.disabled, title: main.closest(".why-off").title, described: described(main)};
all(".deny-split button", row()).find((button) => name(button).startsWith("Deny via")).click();
const confirm = await until(() => all(".sheet-box .actions button").find((button) => text(button) === "Deny"), 4000);
const call = document.querySelector('.sheet-box .deny-channels input[value="call"]');
const look = () => ({disabled: confirm.disabled, title: confirm.closest(".why-off").title, described: described(confirm)});
const off = {checked: call.checked, ...look()};
const select = document.querySelector(".sheet-box .deny-recipient select");
select.value = "Skills";
select.dispatchEvent(new Event("change", {bubbles: true}));
await sleep(100);
return {split, off, on: look(), wide: document.documentElement.scrollWidth > innerWidth + 1};
})()"""
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestWhyDeny(base.OrchestratorE2ECase):
def setUp(self):
super().setUp()
now = time.time()
self.write_council({"work/s1/claim.json": {"office": "work/s1", "session": "s1", "runtime": "claude", "name": "Skills", "since": iso(now - 3600), "beat": now, "work": "hub"}})
arguments = {**self.arguments(comments.TITLE, "", self.page("why.html", comments.review_page())), "worktree": "/repo/.worktrees/feature/why", "branch": "feature/why"}
result = self.tool("review_request", arguments)
self.assertFalse(result["isError"], result)
self.review = result["structuredContent"]["id"]
def test_chromium_names_why_deny_is_off_on_hover_and_for_keyboard_users_until_a_recipient_is_picked(self):
probe = WHY.replace("@HELPERS@", base.HELPERS).replace("@UNLABELLED@", base.UNLABELLED).replace("@REVIEW@", f"review:{self.review}")
step = {"width": 1366, "height": 768, "url": f"http://localhost:{self.port}/?why#stream/inbox", "wait": 1200, "probe": probe, "shot": self.shot("1366-why-deny")}
data = self.drive([step], None)
Path(self.shot("1366-why-deny")).with_suffix(".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], [])
found = data["results"][0]
self.assertNotIn("error", found, found)
missing = "No agent to tell: the item names no recipient"
self.assertTrue(found["split"]["disabled"], found)
self.assertTrue(found["split"]["title"].startswith(missing) and found["split"]["described"].startswith(missing), found)
needs = "Pick the agent to tell: a post or call needs a recipient"
self.assertEqual(found["off"], {"checked": True, "disabled": True, "title": needs, "described": needs}, found)
self.assertFalse(found["on"]["disabled"], found)
self.assertNotIn("needs a recipient", found["on"]["title"], found)
self.assertEqual(found["on"]["title"], found["on"]["described"], found)
self.assertIn("Skills", found["on"]["title"], found)
self.assertFalse(found["wide"], found)
if __name__ == "__main__":
unittest.main()
+6 -4
View File
@@ -41,7 +41,7 @@ OPERATOR = """(async () => {@HELPERS@@UNLABELLED@
const mine = (words) => all("#main .inbox-list > li").find((li) => li.textContent.includes(words));
const cards = ["@TAG@ review", "@TAG@ ship", "@TAG@ commit"].map(mine);
const tasks = document.getElementById("tab-tasks");
const badge = tasks.querySelector(".badge");
const badge = tasks.nextElementSibling;
const review = cards[0];
const files = all(".diff-file", review).map((file) => ({
path: file.dataset.path, status: file.dataset.status, open: file.querySelector("details") ? file.querySelector("details").open : null,
@@ -57,7 +57,9 @@ OPERATOR = """(async () => {@HELPERS@@UNLABELLED@
operator: operator ? {command: text(operator.querySelector(".command code")), place: operator.querySelector(".command").dataset.path, text: text(operator), buttons: all("button", operator).map(name)} : null,
files, wide: document.documentElement.scrollWidth > window.innerWidth + 1,
};
["@TAG@ review", "@TAG@ ship", "@TAG@ commit"].forEach((words) => mine(words).querySelector('input[type="checkbox"]').click());
for (const words of ["@TAG@ review", "@TAG@ ship", "@TAG@ commit"]) {
await selectRow(mine(words).dataset.ref);
}
await sleep(300);
found.unlabelled = {main: unlabelled(document.getElementById("main"))};
const grant = all("#grant-bar .grant-split button").find((button) => name(button).startsWith("Grant selection"));
@@ -144,7 +146,7 @@ FEEDBACK = """(async () => {@HELPERS@@UNLABELLED@
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();
all(":is(.item-actions, .code-foot) 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);
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};
@@ -204,7 +206,7 @@ class TestWorkbenchOperatorTasks(HubCase):
self.assertNotIn("error", tasks, tasks)
self.assertEqual((tasks["hash"], tasks["tabs"], tasks["subs"], tasks["streamInbox"], tasks["current"]), ("#tasks/operator", base.TABS, ["Controls"], False, ["Tasks"]))
self.assertRegex(tasks["badge"] or "", r"^[1-9][0-9]*$")
self.assertEqual((tasks["kinds"], tasks["boxes"]), (["k-review", "k-operator", "k-ask"], [True, True, True]))
self.assertEqual((tasks["kinds"], tasks["boxes"]), (["k-review", "k-operator", "k-ask"], [False, False, False]))
operator = tasks["operator"]
self.assertEqual((operator["command"], operator["place"]), (f"make {tag} ship", "/repo"))
self.assertIn(f"{tag} ship the build", operator["text"])
+1 -1
View File
@@ -44,7 +44,7 @@ STREAM = """(async () => {@HELPERS@@READ@
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 buttons = (row) => all(":is(.line-actions, .code-foot) 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()};
})()"""