diff --git a/docs/requirements/004-radio-set.md b/docs/requirements/004-radio-set.md index e2ce466..7db8210 100644 --- a/docs/requirements/004-radio-set.md +++ b/docs/requirements/004-radio-set.md @@ -314,9 +314,10 @@ flowchart TD each against the contract of its side of decision 11, in six states on the real code paths (idle, stations open, a recorded voice note, a real reading through the mocked synthesizer, MAYDAY banner with a - short and a long text) after the view transition settles, the station - popover's placement, whole rows, Escape and outside click in the spot and - on the Home tiles at 1366, 1280 and 390 px, and where the focus lands + short and a long text) after the view transition settles; + `tests/e2e/test_radio_focus_e2e.py` measures the station popover's + placement, whole rows, Escape and outside click in the spot and on the + Home tiles at 1366, 1280 and 390 px, and where the focus lands after mouse presses on a History tab and on blank `#main` with Day/Night or the stations open at 1366 and 390 px in both browsers, the focus on a keyboard-focused row button and tab across new rows and a forced minute diff --git a/orchestrator/templates/index.html.j2 b/orchestrator/templates/index.html.j2 index 20d8d03..507f620 100644 --- a/orchestrator/templates/index.html.j2 +++ b/orchestrator/templates/index.html.j2 @@ -650,6 +650,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi {% include "page-palette.js" %} +{% include "page-context.js" %} + {% include "page-load.js" %} {% include "page-boot.js" %} diff --git a/orchestrator/templates/page-ancestry.js b/orchestrator/templates/page-ancestry.js index 5cd9817..57b34d6 100644 --- a/orchestrator/templates/page-ancestry.js +++ b/orchestrator/templates/page-ancestry.js @@ -51,10 +51,13 @@ })); } + function glossarySections() { + return Glossary.explain().map(([heading, rows]) => h("section", {}, h("h4", {}, heading), + h("dl", {class: "glossary"}, rows.map(([term, meaning]) => h("div", {}, h("dt", {}, term), h("dd", {}, meaning)))))); + } + function gateExplain() { - return h("details", {class: "gate-explain"}, h("summary", {title: "Explain: what each mark of this branch means"}, icon("bi-question-circle"), "Explain"), - Glossary.explain().map(([heading, rows]) => h("section", {}, h("h4", {}, heading), - h("dl", {class: "glossary"}, rows.map(([term, meaning]) => h("div", {}, h("dt", {}, term), h("dd", {}, meaning))))))); + return h("details", {class: "gate-explain"}, h("summary", {title: "Explain: what each mark of this branch means"}, icon("bi-question-circle"), "Explain"), glossarySections()); } function gateApply() { diff --git a/orchestrator/templates/page-boot.js b/orchestrator/templates/page-boot.js index d199b41..924733c 100644 --- a/orchestrator/templates/page-boot.js +++ b/orchestrator/templates/page-boot.js @@ -28,7 +28,8 @@ document.addEventListener("keydown", context, {once: true}); document.addEventListener("pointerdown", unlock); document.addEventListener("keydown", keyboard); - document.addEventListener("contextmenu", feedbackMenu); + document.addEventListener("keydown", ctxKeydown); + document.addEventListener("contextmenu", ctxContextMenu); document.addEventListener("selectionchange", feedbackButton); document.addEventListener("visibilitychange", refresh); window.addEventListener("focus", refresh); diff --git a/orchestrator/templates/page-constants.js b/orchestrator/templates/page-constants.js index c18bc9e..a02820b 100644 --- a/orchestrator/templates/page-constants.js +++ b/orchestrator/templates/page-constants.js @@ -76,7 +76,7 @@ direct: [[740, 0, 0.2]], radio: [[520, 0, 0.07]], }; - const KEYS = [["Ctrl+K", "Commands, views, agents and AI command"], ["1 · 2 · 3 · 4", "Stream · Agents · Artifacts · Tasks"], ["j / k", "Waits on Operator: next / previous entry"], ["x", "Waits on Operator: select entry"], ["a", "Waits on Operator: grant entry (3 s to undo)"], ["Enter", "Waits on Operator: open entry"], ["f", "Feedback on the selected lines of a diff or a command"], ["/", "Search the stream"], ["h", "Look at the sky: drag turns the view, wheel or two fingers zoom, Esc ends"], ["Arrows · + / − · 0", "Sky (focused): turn · zoom · reset"], ["Drag · wheel", "3D: turn, right drag pans, wheel zooms"],["🎙 hold", "Voice input into the agent field or the command line, never sent automatically"], ["?", "This help"], ["Esc", "Close"]]; + const KEYS = [["Ctrl+K", "Commands, views, agents and AI command"], ["Right-click", "Context menu: the element's commands, then the tab's, then the general ones"], ["Shift+right-click", "The browser's own context menu"], ["Menu key · Shift+F10", "Context menu of the focused element: ↑ / ↓ move, Enter runs, Esc closes"], ["1 · 2 · 3 · 4", "Stream · Agents · Artifacts · Tasks"], ["j / k", "Waits on Operator: next / previous entry"], ["x", "Waits on Operator: select entry"], ["a", "Waits on Operator: grant entry (3 s to undo)"], ["Enter", "Waits on Operator: open entry"], ["f", "Feedback on the selected lines of a diff or a command"], ["/", "Search the stream"], ["h", "Look at the sky: drag turns the view, wheel or two fingers zoom, Esc ends"], ["Arrows · + / − · 0", "Sky (focused): turn · zoom · reset"], ["Drag · wheel", "3D: turn, right drag pans, wheel zooms"],["🎙 hold", "Voice input into the agent field or the command line, never sent automatically"], ["?", "This help"], ["Esc", "Close"]]; const calm = window.matchMedia("(prefers-reduced-motion: reduce)"); const relative = new Intl.RelativeTimeFormat("en", {numeric: "auto"}); const absolute = new Intl.DateTimeFormat("en-GB", {dateStyle: "medium", timeStyle: "short"}); diff --git a/orchestrator/templates/page-context.js b/orchestrator/templates/page-context.js new file mode 100644 index 0000000..1aa6e25 --- /dev/null +++ b/orchestrator/templates/page-context.js @@ -0,0 +1,250 @@ + const ctxMenu = {node: null, back: null}; + const CTX_FIELDS = ["INPUT", "TEXTAREA", "SELECT"]; + const CTX_GAP = 8; + const CTX_MODIFIERS = ["Shift", "Control", "Alt", "Meta"]; + const CTX_OPENS = {task: "Open task", message: "Open message", artifact: "Open artifact"}; + const ctxAttr = (...names) => (node) => names.map((name) => node.getAttribute(name)).find(Boolean) || null; + const ctxField = (node) => Boolean(node.isContentEditable) || CTX_FIELDS.includes(node.tagName); + const ctxInside = (node) => Boolean(ctxMenu.node) && ctxMenu.node.contains(node); + const ctxCopyItem = (label, text) => ({label, hint: text, run: () => ctxCopy(text)}); + + function ctxAgentOf(node) { + const raw = ctxAttr("data-agent", "data-face", "data-name", "data-session")(node); + return raw && raw !== HUMAN ? agentKey(raw) : null; + } + + function ctxPinOf(node) { + return node.matches(Panels.HOSTS) ? Panels.targetOf(node) : null; + } + + const ctxPinEntry = (target) => (target.id && !target.refused ? Panels.lookup(target.kind, target.id, target.view) : null); + const ctxEntryOf = (ref) => state.inbox.find((entry) => keyOf(entry) === ref) || null; + const ctxArtifactOf = (id) => (tree.model ? tree.model.byId.get(id) || null : null); + + function ctxTaskItems(node, id) { + const known = state.tasks.some((row) => row.task === id); + return [...(known ? [{label: "Open task", hint: id, run: () => taskSheet(id)}] : []), ctxCopyItem("Copy task id", id)]; + } + + function ctxAgentItems(node, key) { + return [ctxCopyItem("Copy name", nameOf(key))]; + } + + function ctxBranchItems(node, name) { + const ref = `branch:${node.getAttribute("data-repo")}\u0000${name}`; + const open = ctxArtifactOf(ref) ? [{label: "Open branch", hint: name, run: () => artSelect(ref)}] : []; + return [...open, ctxCopyItem("Copy branch name", name), {label: "Explain", hint: "what each mark of a branch means", run: () => openSheet("Explain", glossarySections(), false)}]; + } + + function ctxPathItems(node, path) { + return [...feedbackItems(), ...(path === "-" ? [] : [ctxCopyItem("Copy path", path)])]; + } + + function ctxEntryItems(node, ref) { + const item = ctxEntryOf(ref); + return item ? [{label: "Open entry", hint: item.title, run: () => openItem(item)}, ctxCopyItem("Copy id", item.id)] : []; + } + + function ctxPickItems(node, id) { + const found = ctxArtifactOf(id); + if (found) { + return [{label: "Open artifact", hint: found.label, run: () => artSelect(id)}]; + } + const sub = state.graph.nodes.find((entry) => entry.id === id && entry.kind === "subagent"); + return sub ? [{label: "Open parent agent", hint: labelOf(sub.parent), run: () => select(id)}] : []; + } + + function ctxPickTitle(id) { + const found = ctxArtifactOf(id) || state.graph.nodes.find((entry) => entry.id === id); + return found ? found.label : id; + } + + function ctxPinItems(node, target) { + const entry = ctxPinEntry(target); + if (!entry) { + return []; + } + const opens = Object.hasOwn(CTX_OPENS, target.kind) ? [{label: CTX_OPENS[target.kind], hint: entry.title, run: () => HOME_OPENERS[target.kind](Panels.raw(target.id), target.id)}] : []; + const pinned = Panels.has(homePins(), target.kind, target.id); + return [...opens, {label: pinned ? "Unpin from Home" : "Pin to Home", hint: entry.title, run: () => homePress(target.kind, target.id, entry.title, target.view)}]; + } + + const CTX_KINDS = [ + {kind: "task", id: ctxAttr("data-task"), title: (id) => `Task ${id}`, items: ctxTaskItems}, + {kind: "agent", id: ctxAgentOf, title: (key) => nameOf(key), items: ctxAgentItems}, + {kind: "branch", id: ctxAttr("data-branch"), title: (name) => `Branch ${name}`, items: ctxBranchItems}, + {kind: "path", id: ctxAttr("data-path"), title: (path) => path, items: ctxPathItems}, + {kind: "entry", id: ctxAttr("data-ref"), title: (ref) => ctxEntryOf(ref).title, items: ctxEntryItems}, + {kind: "rule", id: ctxAttr("data-rule", "data-entry"), title: (id) => `Rule ${id}`, items: (node, id) => [ctxCopyItem("Copy rule", id)]}, + {kind: "pick", id: ctxAttr("data-pick"), title: ctxPickTitle, items: ctxPickItems}, + {kind: "pin", id: ctxPinOf, title: (target) => ctxPinEntry(target).title, items: ctxPinItems}, + ]; + + /** + * @param target - the element a right-click or the menu key hit. + * @returns [{kind, id, node, entry}]: per kind of CTX_KINDS the nearest marked element from target up, nearest first. + */ + function ctxFound(target) { + const found = []; + for (let node = target; node; node = node.parentElement) { + for (const entry of CTX_KINDS.filter((kind) => !found.some((seen) => seen.kind === kind.kind))) { + const id = entry.id(node); + if (id) { + found.push({kind: entry.kind, id, node, entry}); + } + } + } + return found; + } + + function ctxOwn(found, items) { + const groups = found.map((seen) => ({seen, items: items.filter((item) => item.scope === seen.kind && item.id === seen.id)})).filter((group) => group.items.length); + const flat = groups.flatMap((group) => group.items); + return {title: groups.length ? groups[0].seen.entry.title(groups[0].seen.id) : "", items: flat.filter((item, index) => flat.findIndex((other) => other.label === item.label) === index)}; + } + + /** + * @param target - the element the menu is for. + * @returns [{scope, title, items}]: the element's own items, then the current tab's, then the general ones; empty + * sections left out. + */ + function ctxSections(target) { + const found = ctxFound(target); + const provided = found.flatMap((seen) => seen.entry.items(seen.node, seen.id).map((item) => ({...item, scope: seen.kind, id: seen.id}))); + const items = [...paletteItems(), ...provided]; + const own = ctxOwn(found, items); + const tab = Nav.TABS.find(([id]) => id === Nav.tabOf(ui.screen)); + return [ + {scope: "element", title: own.title, items: own.items}, + ...(tab ? [{scope: tab[0], title: tab[1], items: items.filter((item) => item.scope === tab[0])}] : []), + {scope: "general", title: "General", items: items.filter((item) => item.scope === "general")}, + ].filter((section) => section.items.length); + } + + async function ctxCopy(text) { + try { + await navigator.clipboard.writeText(text); + toast("Copied", [revealed(text)], true); + } catch { + toast("Not copied", ["The browser refused the clipboard."], false); + } + } + + function ctxNode() { + if (!ctxMenu.node) { + ctxMenu.node = h("div", {class: "ctx-menu", role: "menu", "aria-label": "Context menu", tabindex: -1, hidden: true, on: {keydown: ctxKeys}}); + document.body.append(ctxMenu.node); + } + return ctxMenu.node; + } + + function ctxItem(item) { + return h("button", {type: "button", role: "menuitem", tabindex: -1, class: "ctx-item", title: revealed(item.hint), on: {click: () => ctxRun(item)}}, + item.face ? face(item.face, false) : null, h("span", {class: "ctx-label"}, revealed(item.label)), h("span", {class: "muted"}, revealed(item.hint))); + } + + function ctxGroup(section, index) { + return [index ? h("div", {role: "separator", class: "ctx-rule"}) : null, + h("div", {role: "group", class: "ctx-group", "aria-label": revealed(section.title), "data-scope": section.scope}, h("div", {class: "ctx-head", "aria-hidden": "true"}, revealed(section.title)), section.items.map(ctxItem))]; + } + + function ctxPlace(node, at) { + node.style.left = "0px"; + node.style.top = "0px"; + const box = node.getBoundingClientRect(); + const below = at.y + box.height + CTX_GAP <= window.innerHeight; + node.style.left = `${Math.max(CTX_GAP, Math.min(at.x, window.innerWidth - box.width - CTX_GAP))}px`; + node.style.top = `${Math.max(CTX_GAP, Math.min(below ? at.y : at.y - box.height, window.innerHeight - box.height - CTX_GAP))}px`; + } + + /** + * @param sections - what ctxSections gives. + * @param at - {x, y}, the viewport point the menu opens at; it moves inside the viewport when it would run past it. + */ + function ctxShow(sections, at) { + const node = ctxNode(); + node.replaceChildren(...sections.flatMap(ctxGroup).filter(Boolean)); + node.hidden = false; + ctxPlace(node, at); + const first = node.querySelector('[role="menuitem"]'); + if (first) { + first.focus({preventScroll: true}); + } + } + + function ctxOpen(target, at) { + closeMenus(null); + ctxMenu.back = document.activeElement; + ctxShow(ctxSections(target), at); + } + + function ctxClose(restore) { + if (!ctxMenu.node || ctxMenu.node.hidden) { + return; + } + const back = ctxMenu.back; + ctxMenu.back = null; + ctxMenu.node.hidden = true; + ctxMenu.node.replaceChildren(); + if (restore && back && back.isConnected && typeof back.focus === "function") { + back.focus({preventScroll: true}); + } + } + + function ctxRun(item) { + ctxClose(true); + item.run(); + } + + /** + * @param keep - the menu a click landed in, as closeMenus gets it; the context menu stays open when it is that menu. + */ + function ctxDismiss(keep) { + if (ctxMenu.node && ctxMenu.node !== keep) { + ctxClose(ctxMenu.node.contains(document.activeElement)); + } + } + + function ctxKeys(event) { + const items = [...ctxMenu.node.querySelectorAll('[role="menuitem"]')]; + const at = items.indexOf(document.activeElement); + const moves = {ArrowDown: at + 1, ArrowUp: Math.max(at, 0) - 1, Home: 0, End: items.length - 1}; + if (Object.hasOwn(moves, event.key)) { + items[(moves[event.key] + items.length) % items.length].focus(); + } else if (event.key === "Enter" || event.key === " ") { + items[Math.max(at, 0)].click(); + } else if (CTX_MODIFIERS.includes(event.key)) { + return; + } else { + ctxClose(true); + } + event.preventDefault(); + event.stopPropagation(); + } + + function ctxContextMenu(event) { + const target = event.target; + if (!(target instanceof Element) || event.defaultPrevented) { + return; + } + if (ctxInside(target)) { + event.preventDefault(); + return; + } + if (event.shiftKey || ctxField(target)) { + return; + } + event.preventDefault(); + ctxOpen(target, {x: event.clientX, y: event.clientY}); + } + + function ctxKeydown(event) { + const pressed = event.key === "ContextMenu" || (event.key === "F10" && event.shiftKey); + const target = document.activeElement; + if (!pressed || event.ctrlKey || event.altKey || event.metaKey || !(target instanceof Element) || ctxField(target) || ctxInside(target)) { + return; + } + event.preventDefault(); + const box = target.getBoundingClientRect(); + ctxOpen(target, {x: box.left, y: box.bottom}); + } diff --git a/orchestrator/templates/page-diff.js b/orchestrator/templates/page-diff.js index 1441202..48a5904 100644 --- a/orchestrator/templates/page-diff.js +++ b/orchestrator/templates/page-diff.js @@ -113,9 +113,9 @@ diffView.picked = null; } - function showFeedback(picked, x, y, menu) { + function showFeedback(picked, x, y) { if (!diffView.float) { - diffView.float = h("div", {class: "feedback-float", hidden: true}, + diffView.float = h("div", {class: "feedback-float", role: "toolbar", hidden: true}, h("button", {type: "button", class: "btn small primary icon-only", ...named("Feedback", "Feedback (f): a post with the selected lines to the requesting agent"), on: { mousedown: (event) => event.preventDefault(), click: () => diffView.picked && feedbackSheet(diffView.picked), @@ -123,8 +123,6 @@ document.body.append(diffView.float); } diffView.picked = picked; - diffView.float.setAttribute("role", menu ? "menu" : "toolbar"); - diffView.float.firstChild.setAttribute("role", menu ? "menuitem" : "button"); diffView.float.style.left = `${Math.max(Math.min(x, window.innerWidth - 44), 4)}px`; diffView.float.style.top = `${Math.max(Math.min(y, window.innerHeight - 44), 4)}px`; diffView.float.hidden = false; @@ -135,21 +133,20 @@ diffView.timer = window.setTimeout(() => { const picked = selectionFeedback(); if (picked) { - showFeedback(picked, picked.rect.right + 4, picked.rect.bottom + 4, false); + showFeedback(picked, picked.rect.right + 4, picked.rect.bottom + 4); } else if (!diffView.float || !diffView.float.contains(document.activeElement)) { hideFeedback(); } }, 120); } - function feedbackMenu(event) { + /** + * @returns the context menu items of a [data-path] region, a diff file or a command: Feedback while lines of one are + * selected. + */ + function feedbackItems() { const picked = selectionFeedback(); - if (!picked || !(event.target instanceof Element) || !event.target.closest("[data-path]")) { - return; - } - event.preventDefault(); - showFeedback(picked, event.clientX, event.clientY, true); - diffView.float.firstChild.focus(); + return picked ? [{label: "Feedback", hint: "f: a post with the selected lines to the requesting agent", run: () => feedbackSheet(picked)}] : []; } function feedbackKey() { diff --git a/orchestrator/templates/page-dom.js b/orchestrator/templates/page-dom.js index 78112eb..178e6df 100644 --- a/orchestrator/templates/page-dom.js +++ b/orchestrator/templates/page-dom.js @@ -138,7 +138,7 @@ return button; } - const MENUS = "details.menu, details.radio-station"; + const MENUS = "details.menu, details.radio-station, .ctx-menu"; function closeMenus(keep) { for (const menu of document.querySelectorAll(MENUS)) { @@ -150,6 +150,7 @@ } } } + ctxDismiss(keep); } function openSheet(title, body, wide) { diff --git a/orchestrator/templates/page-palette.js b/orchestrator/templates/page-palette.js index b916511..97d6728 100644 --- a/orchestrator/templates/page-palette.js +++ b/orchestrator/templates/page-palette.js @@ -1,20 +1,24 @@ + /** + * @returns every command: {label, hint, run, scope, face, id}; scope is "general", a tab id of Nav.TABS, or an element + * kind of CTX_KINDS, which the item carries with the id of the one element it belongs to, such as an agent key. + */ function paletteItems() { return [ - ...Nav.TABS.flatMap(([id, label], index) => [{label: `View: ${label}`, hint: String(index + 1), run: () => go(id, null)}, ...(Nav.SUBS[id] || []).map(([sub, name]) => ({label: `View: ${label} › ${name}`, hint: Nav.hashOf(sub, null), run: () => go(sub, null)}))]), - ...["agents", "artifacts", "tasks"].flatMap((screen) => Nav.viewsOf(screen).map(([id, name]) => ({label: `${Nav.TABS.find(([tab]) => tab === screen)[1]}: ${name}`, hint: Nav.hashOf(screen, id), run: () => go(screen, id)}))), - ...Object.entries(state.views).map(([id, view]) => ({label: `Stream: ${view.label}`, hint: "Category", run: () => useView(id)})), - ...userViews.map((view) => ({label: `Stream: ${view.name}`, hint: "saved view", run: () => useSaved(view)})), - ...agentNames().map((name) => ({label: name, hint: "Agent", face: name, run: () => openAgent(name)})), - {label: "Radio …", hint: "Post, Call, Newsletter, Broadcast, Pan-Pan, Security, Mayday; the gear holds tones and read aloud", run: openRadio}, - ...ACTIONS.map(([id, label]) => ({label, hint: id === "clear-mayday" ? "Mayday" : "Day/Night", run: () => confirmAct(id, [])})), - {label: "Priority …", hint: "agent order in the hierarchy", run: openAgentOrder}, - {label: "Firewall …", hint: "automatic grants", run: () => go("rules", null)}, - {label: "Settings …", hint: "Ambience, location, colors, music, notifications, internet radio", run: settingsSheet}, - {label: settings.music.on ? "Music off" : "Music on", hint: "Ambience", run: toggleMusic}, - {label: space.look ? "Leave the sky" : "Look at the sky", hint: "h", run: () => skyLook(!space.look)}, - {label: "Toggle control room", hint: "Ambience", run: toggleLeitstand}, - {label: "Enable notifications", hint: "Ambience", run: askNotify}, - {label: "Keyboard shortcuts", hint: "?", run: helpSheet}, + ...Nav.TABS.flatMap(([id, label], index) => [{label: `View: ${label}`, hint: String(index + 1), scope: "general", run: () => go(id, null)}, ...(Nav.SUBS[id] || []).map(([sub, name]) => ({label: `View: ${label} › ${name}`, hint: Nav.hashOf(sub, null), scope: id, run: () => go(sub, null)}))]), + ...["agents", "artifacts", "tasks"].flatMap((screen) => Nav.viewsOf(screen).map(([id, name]) => ({label: `${Nav.TABS.find(([tab]) => tab === screen)[1]}: ${name}`, hint: Nav.hashOf(screen, id), scope: screen, run: () => go(screen, id)}))), + ...Object.entries(state.views).map(([id, view]) => ({label: `Stream: ${view.label}`, hint: "Category", scope: "stream", run: () => useView(id)})), + ...userViews.map((view) => ({label: `Stream: ${view.name}`, hint: "saved view", scope: "stream", run: () => useSaved(view)})), + ...agentNames().map((name) => ({label: name, hint: "Agent", face: name, scope: "agent", id: agentKey(name), run: () => openAgent(name)})), + {label: "Radio …", hint: "Post, Call, Newsletter, Broadcast, Pan-Pan, Security, Mayday; the gear holds tones and read aloud", scope: "general", run: openRadio}, + ...ACTIONS.map(([id, label]) => ({label, hint: id === "clear-mayday" ? "Mayday" : "Day/Night", scope: "general", run: () => confirmAct(id, [])})), + {label: "Priority …", hint: "agent order in the hierarchy", scope: "agents", run: openAgentOrder}, + {label: "Firewall …", hint: "automatic grants", scope: "stream", run: () => go("rules", null)}, + {label: "Settings …", hint: "Ambience, location, colors, music, notifications, internet radio", scope: "general", run: settingsSheet}, + {label: settings.music.on ? "Music off" : "Music on", hint: "Ambience", scope: "general", run: toggleMusic}, + {label: space.look ? "Leave the sky" : "Look at the sky", hint: "h", scope: "general", run: () => skyLook(!space.look)}, + {label: "Toggle control room", hint: "Ambience", scope: "general", run: toggleLeitstand}, + {label: "Enable notifications", hint: "Ambience", scope: "general", run: askNotify}, + {label: "Keyboard shortcuts", hint: "?", scope: "general", run: helpSheet}, ]; } diff --git a/orchestrator/templates/style-ui.css b/orchestrator/templates/style-ui.css index 9b0d185..3bfd1a7 100644 --- a/orchestrator/templates/style-ui.css +++ b/orchestrator/templates/style-ui.css @@ -240,3 +240,12 @@ body.fit .spot-host { flex: none; } .radio-spot .radio-tabs button { padding-block: 1px; } .radio-spot .radio-logbox :is(.radio-filters .field, input[type="search"]) { padding-block: 1px; } } +.ctx-menu { position: fixed; z-index: 55; display: grid; gap: 2px; width: max-content; min-width: min(220px, calc(100vw - 16px)); max-width: min(360px, calc(100vw - 16px)); max-height: calc(100dvh - 16px); padding: 4px; overflow-y: auto; overscroll-behavior: contain; background: var(--glass-card); border: 1px solid var(--line-strong); border-radius: var(--radius); box-shadow: var(--shadow-lift); -webkit-backdrop-filter: var(--blur); backdrop-filter: var(--blur); } +.ctx-menu[hidden] { display: none; } +.ctx-group { display: grid; min-width: 0; } +.ctx-head { padding: 4px 10px 2px; overflow: hidden; color: var(--muted); font-size: var(--fs-xs); font-weight: 650; letter-spacing: .04em; text-overflow: ellipsis; text-transform: uppercase; white-space: nowrap; } +.ctx-rule { height: 1px; margin: 2px 6px; background: var(--line); } +.ctx-item { display: flex; align-items: center; gap: 8px; min-width: 0; padding: 5px 10px; border: 0; border-radius: 8px; background: none; color: inherit; font: inherit; text-align: start; cursor: pointer; } +.ctx-item:is(:hover, :focus) { background: var(--accent-soft); color: var(--accent); outline: none; } +.ctx-item .ctx-label { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.ctx-item .muted { flex: 0 1 auto; max-width: 45%; overflow: hidden; font-size: var(--fs-xs); text-overflow: ellipsis; white-space: nowrap; } diff --git a/tests/e2e/hub_e2e_board.py b/tests/e2e/hub_e2e_board.py new file mode 100644 index 0000000..56bc647 --- /dev/null +++ b/tests/e2e/hub_e2e_board.py @@ -0,0 +1,237 @@ +from __future__ import annotations + +from hub_e2e_kit import HELPERS + +ORG_OPEN = """(async () => {@HELPERS@ + const row = await until(() => document.querySelector('#main .org-row[data-office="identity/oidc"]'), 8000); + if (!row) { + return {error: text(document.getElementById("main"))}; + } + const toggle = all("#main .org-toggle").find((button) => name(button) === "Collapse: identity"); + toggle.focus(); + return {focused: document.activeElement.dataset.focus, offices: all("#main .org-row[data-office]").map((entry) => entry.dataset.office)}; +})()""".replace("@HELPERS@", HELPERS) +ORG_FOLDED = """(async () => {@HELPERS@ + const toggle = document.activeElement; + const folded = {focused: toggle.dataset.focus, expanded: toggle.getAttribute("aria-expanded"), label: name(toggle), hidden: document.getElementById(toggle.getAttribute("aria-controls")).hidden, seen: all("#main .org-row[data-office]").filter((entry) => entry.offsetParent !== null).map((entry) => entry.dataset.office)}; + toggle.click(); + await sleep(200); + const before = all("#main .agent-order li").map((item) => item.dataset.name); + all("#main .agent-order li")[1].querySelector('[data-focus^="up:"]').focus(); + return {...folded, again: toggle.getAttribute("aria-expanded"), before}; +})()""".replace("@HELPERS@", HELPERS) +ORDER_MOVED = """(async () => {@HELPERS@ + const after = all("#main .agent-order li").map((item) => item.dataset.name); + const focused = document.activeElement.dataset.focus || null; + const save = all("#main .agent-order button").find((button) => text(button) === "Save order"); + const disabled = save.disabled; + save.click(); + const toast = await until(() => all("#toasts .toast").find((box) => text(box).startsWith("Priority")), 8000); + return {after, focused, disabled, toast: text(toast)}; +})()""".replace("@HELPERS@", HELPERS) +OPEN_TAKEOVER = """(async () => {@HELPERS@ + document.querySelector('#main [data-focus="takeover:identity/oidc"]').click(); + await sleep(400); + return {title: text(document.querySelector(".sheet-head .panel-title")), options: all(".sheet-box select option").map((option) => option.value), work: document.querySelector('.sheet-box input[aria-label="Work"]').value, focused: document.activeElement.tagName}; +})()""".replace("@HELPERS@", HELPERS) +CONFIRM_TAKEOVER = """(async () => {@HELPERS@ + all(".sheet-box button").find((button) => name(button) === "Hand over").click(); + const done = await until(() => document.querySelector(".sheet-box [data-result]"), 30000); + return {result: done ? done.dataset.result : null, text: text(done), toasts: all("#toasts .toast").map(text)}; +})()""".replace("@HELPERS@", HELPERS) +AFTER_TAKEOVER = """(async () => {@HELPERS@ + document.querySelector(".sheet-head button").click(); + const row = await until(() => { + const found = document.querySelector('#main .org-row[data-office="identity/oidc"] .org-holder'); + return found && !text(found).endsWith("Stage") ? found : null; + }, 15000); + return {holder: text(row)}; +})()""".replace("@HELPERS@", HELPERS) +PIN = """(async () => {@HELPERS@ + const row = await until(() => all("#main .task-row").find((item) => item.dataset.task === "work/docs"), 8000); + if (!row) { + return {error: text(document.getElementById("main"))}; + } + row.querySelector('button[aria-label="Priority"]').click(); + await sleep(400); + const field = document.querySelector('.sheet-box input[aria-label="Priority"]'); + field.value = "2"; + field.dispatchEvent(new Event("input", {bubbles: true})); + const preview = all(".sheet-box .task-edit .command code").map(text); + all(".sheet-box button").find((button) => name(button) === "Pin").click(); + const done = await until(() => document.querySelector(".sheet-box [data-jobs]"), 20000); + return {title: text(document.querySelector(".sheet-head .panel-title")), preview, jobs: done ? done.dataset.jobs : null, toasts: all("#toasts .toast").map(text)}; +})()""".replace("@HELPERS@", HELPERS) +OPEN_DELETE = """(async () => {@HELPERS@ + const card = await until(() => all("#main details.repo").find((details) => details.textContent.includes("github.com/me/demo")), 8000); + if (!card) { + return {error: text(document.getElementById("main"))}; + } + card.open = true; + await sleep(300); + const every = document.querySelector('#main button[aria-label="Delete all merged"]'); + const buttons = all('button[aria-label="Delete"]', card); + const states = all("span.state", card).map(name); + buttons.find((button) => !button.disabled).click(); + await sleep(500); + return {states, every: [every.disabled, every.title], buttons: buttons.map((button) => [button.disabled, button.title]), title: text(document.querySelector(".sheet-head .panel-title")), dry: all('.sheet-box [aria-label="Dry run"] pre').map(text)}; +})()""".replace("@HELPERS@", HELPERS) +CONFIRM = """(async () => {@HELPERS@ + all(".sheet-box button").find((button) => name(button) === "Delete").click(); + const done = await until(() => document.querySelector(".sheet-box [data-result]"), 30000); + const job = document.querySelector(".sheet-box [data-cleanup]"); + return {job: job ? job.dataset.cleanup : null, result: done ? done.dataset.result : null, text: text(done), toasts: all("#toasts .toast").map(text)}; +})()""".replace("@HELPERS@", HELPERS) +AFTER = """(async () => {@HELPERS@ + document.querySelector(".sheet-head button").click(); + const past = await until(() => all("#main details.repo").find((details) => details.textContent.includes("Recently deleted")), 15000); + return {past: past ? [past.querySelector("[data-result]").dataset.result, name(past.querySelector("span.state"))] : null, branches: all("#main details.repo").filter((details) => details !== past).flatMap((details) => all(".branch-name strong", details)).map(text)}; +})()""".replace("@HELPERS@", HELPERS) +KEPT_TREE = """(async () => {@HELPERS@ + const card = await until(() => all("#main details.repo").find((details) => details.textContent.includes("github.com/me/demo")), 8000); + if (!card) { + return {error: text(document.getElementById("main"))}; + } + card.open = true; + await sleep(300); + const row = all(".branch-row", card).find((entry) => text(entry.querySelector(".branch-name strong")) === "feature/squashed"); + const kept = row ? row.querySelector(".hint.kept") : null; + const deletes = all('button[aria-label="Delete"]', card).map((button) => text(button.closest(".branch-row").querySelector(".branch-name strong"))); + const header = all("#main .delete-all span.state").map(name); + document.querySelector('#main button[aria-label="Delete all merged"]').click(); + const sheet = await until(() => document.querySelector("#sheet:not([hidden]) li.dry-run") && document.getElementById("sheet"), 8000); + const kind = (li) => (li.dataset.token ? "token" : li.dataset.held ? "held" : li.dataset.kept ? "kept" : null); + const rows = sheet ? all("li.dry-run", sheet).map((li) => [text(li.querySelector("code")), kind(li), all("button", li).length, text(li.querySelector("pre"))]) : null; + const confirms = sheet ? all("#sheet button").filter((button) => name(button) === "Delete").length : null; + const title = text(document.querySelector(".sheet-head .panel-title")); + document.querySelector(".sheet-head button").click(); + return {kept: kept ? [kept.title, name(kept.querySelector("span.state"))] : null, rowDeletes: row ? all('button[aria-label="Delete"]', row).length : null, deletes, header, rows, confirms, title}; +})()""".replace("@HELPERS@", HELPERS) +KEPT_POPUP = """(async () => {@HELPERS@ + await screenShown(8000); + const picker = await until(() => document.querySelector('#main select[aria-label="Repository"]'), 8000); + if (picker && picker.value !== @REPO@) { + picker.value = @REPO@; + picker.dispatchEvent(new Event("change", {bubbles: true})); + } + const id = `branch:${@REPO@}\\u0000feature/squashed`; + const target = await until(() => all("#main svg [data-pick]").find((node) => node.dataset.pick === id), 8000); + if (!target) { + return {error: text(document.getElementById("main"))}; + } + target.dispatchEvent(new MouseEvent("click", {bubbles: true, cancelable: true})); + const dialog = document.getElementById("popup"); + const dry = await until(() => dialog.open && dialog.querySelector(".popup-box pre.notes"), 6000); + const kept = dialog.querySelector(".popup-box .actions .hint.kept"); + return {title: text(dialog.querySelector(".popup-box .panel-title")), heading: dry ? text(dry.previousElementSibling) : null, dry: dry ? dry.textContent : null, + deletes: all('#popup button[aria-label="Delete"]').length, kept: kept ? kept.title : null}; +})()""".replace("@HELPERS@", HELPERS) +NIGHT_MENU = """(async () => {@HELPERS@ + const questions = []; + window.confirm = (question) => { + questions.push(question); + return true; + }; + let asked = 0; + const get = navigator.credentials.get.bind(navigator.credentials); + navigator.credentials.get = (options) => { + asked += 1; + return @SIGNS@ ? get(options) : Promise.reject(new DOMException("The operator canceled.", "NotAllowedError")); + }; + const posted = []; + const send = window.fetch.bind(window); + window.fetch = (path, init) => { + if (String(path).startsWith("/api/board/")) { + const body = JSON.parse(init.body); + posted.push([String(path), Object.keys(body), body.action || null]); + } + return send(path, init); + }; + const menu = await until(() => all('#main [role="toolbar"] details.menu').find((node) => name(node.querySelector("summary")) === "Day/Night"), 8000); + if (!menu) { + return {error: text(document.getElementById("main"))}; + } + menu.open = true; + const buttons = all(".actions button", menu); + const runs = []; + for (const button of buttons) { + const label = name(button); + const [before, prompts, sent] = [asked, questions.length, posted.length]; + const shown = new Set(all("#toasts .toast")); + button.click(); + const toast = await until(() => all("#toasts .toast").filter((box) => !shown.has(box)).map(text).find((entry) => entry.startsWith(`${label}:`)), 15000); + runs.push({label, question: questions.slice(prompts), asked: asked - before, posted: posted.slice(sent), toast}); + } + return {labels: buttons.map(name), runs}; +})()""".replace("@HELPERS@", HELPERS) +NIGHT_LOOK = """(async () => {@HELPERS@ + const menu = await until(() => all('#main [role="toolbar"] details.menu').find((node) => name(node.querySelector("summary")) === "Day/Night"), 8000); + if (!menu) { + return {error: text(document.getElementById("main"))}; + } + menu.open = true; + await sleep(200); + const box = menu.querySelector(".menu-box"); + return { + children: [...box.children].map((node) => [node.tagName.toLowerCase(), node.className]), + badge: all(".pill", box).map(text), + picks: all(".night-picks label", box).map((label) => [text(label), label.querySelector("input").checked]), + buttons: all("button", box).map((button) => [name(button), button.title]), + paragraphs: all("p", box).length, + wide: document.documentElement.scrollWidth > window.innerWidth + 1, + }; +})()""".replace("@HELPERS@", HELPERS) +NIGHT_PICK = """(async () => {@HELPERS@ + const questions = []; + window.confirm = (question) => { + questions.push(question); + return true; + }; + navigator.credentials.get = @SIGNS@ ? navigator.credentials.get.bind(navigator.credentials) : () => Promise.reject(new DOMException("The operator canceled.", "NotAllowedError")); + const posted = []; + const send = window.fetch.bind(window); + window.fetch = (path, init) => { + if (String(path).startsWith("/api/board/")) { + const body = JSON.parse(init.body); + posted.push([String(path), Object.keys(body), body.action || null, body.agents || null]); + } + return send(path, init); + }; + const menu = await until(() => all('#main [role="toolbar"] details.menu').find((node) => name(node.querySelector("summary")) === "Day/Night"), 8000); + if (!menu) { + return {error: text(document.getElementById("main"))}; + } + menu.open = true; + await sleep(200); + const box = menu.querySelector(".menu-box"); + const picks = () => all(".night-picks label", box).map((label) => [text(label), label.querySelector("input").checked]); + const enabled = () => all(".actions button", box).map((button) => !button.disabled); + const tick = (label) => all(".night-picks label", box).find((node) => text(node) === label).querySelector("input").click(); + const fresh = async (label, click) => { + const shown = new Set(all("#toasts .toast")); + click(); + return until(() => all("#toasts .toast").filter((node) => !shown.has(node)).map(text).find((entry) => entry.startsWith(`${label}:`)), 15000); + }; + const found = {badge: all(".pill", box).map(text), start: picks()}; + tick("Skills"); + found.one = [picks(), enabled()]; + found.drain = await fresh("Drain", () => all(".actions button", box).find((button) => name(button) === "Drain").click()); + found.kept = picks(); + tick("Stage"); + found.none = [picks(), enabled()]; + tick("All"); + found.all = [picks(), enabled()]; + menu.open = false; + document.getElementById("palette-open").click(); + const item = await until(() => all(".palette-list li").find((li) => text(li.querySelector("span")) === "Stage"), 4000); + item.click(); + const row = await until(() => document.querySelector("#popup .agent-night"), 4000); + found.popup = {badge: all(".pill", row).map(text), buttons: all("button", row).map(name)}; + found.suspend = await fresh("Suspend", () => all("button", row).find((button) => name(button) === "Suspend").click()); + return {...found, questions, posted, wide: document.documentElement.scrollWidth > window.innerWidth + 1}; +})()""".replace("@HELPERS@", HELPERS) +NIGHT_HINTS = [ + ("Drain", "Drain: the agents finish their task and take nothing new; your passkey signs it"), + ("Suspend", "Suspend: the agents park their work, write the handover and idle; your passkey signs it"), + ("Resume", "Resume: all agents continue from their handover; your passkey signs it"), +] diff --git a/tests/e2e/hub_e2e_inbox.py b/tests/e2e/hub_e2e_inbox.py new file mode 100644 index 0000000..0e297ca --- /dev/null +++ b/tests/e2e/hub_e2e_inbox.py @@ -0,0 +1,223 @@ +from __future__ import annotations + +from hub_e2e_kit import HELPERS, LABELS + +RUN_START = """(async () => {@HELPERS@@LABELS@ + const row = await until(() => rowOf("Row"), 8000); + if (!row) { + return {error: text(document.getElementById("main"))}; + } + press(row, "Run"); + const toast = await until(() => all("#toasts .toast.wait").find((box) => box.textContent.includes("Run")), 8000); + const queued = await until(() => out() && line(), 15000); + await until(() => out().textContent.includes("Row 60"), 20000); + return {toast: text(toast), queued, running: line(), overflows: out().scrollHeight > out().clientHeight, followed: atEnd()}; +})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) +RUN_HELD = """(async () => {@HELPERS@@LABELS@ + out().scrollTop = 0; + await sleep(300); + await until(() => out().textContent.includes("Row 80"), 20000); + await sleep(300); + return {held: out().scrollTop, running: line()}; +})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) +RUN_DONE = """(async () => {@HELPERS@@LABELS@ + out().scrollTop = out().scrollHeight; + 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)}; +})()""".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")); + const posted = []; + const send = window.fetch.bind(window); + window.fetch = (path, init) => { + if (["/api/sign", "/api/inbox/approve"].includes(String(path))) { + posted.push([String(path), JSON.parse(init.body).items.map((item) => [item.id, item.verb, item.channel || null])]); + } + return send(path, init); + }; + const list = await until(() => document.querySelector("#main .inbox-list"), 8000); + if (!list) { + return {error: text(document.getElementById("main"))}; + } + let scroller = list; + while (scroller && !(scroller.scrollHeight > scroller.clientHeight + 4 && getComputedStyle(scroller).overflowY !== "visible")) { + scroller = scroller.parentElement; + } + scroller = scroller || document.scrollingElement; + const last = all("#main .inbox-list > li").filter((li) => li.textContent.includes("echo row")).pop(); + last.scrollIntoView({block: "center"}); + await sleep(300); + const title = text(last.querySelector(".command code")); + const before = scroller.scrollTop; + last.querySelector("input").click(); + 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 buttons = all("#main .inbox-actions button").map(name); + all("#main .inbox-actions button").find((button) => name(button).startsWith("Deny selection")).click(); + await until(() => document.querySelector(".sheet-box .actions"), 4000); + const listed = all(".sheet-box ul.mini > li strong").map(text); + const confirm = all(".sheet-box .actions button").find((button) => text(button).startsWith("Deny ")); + const label = text(confirm); + const shown = new Set(all("#toasts .toast")); + confirm.click(); + const toast = await until(() => all("#toasts .toast").filter((node) => !shown.has(node)).map(text).find((entry) => entry.startsWith("Deny selection")), 15000); + return {title, before, moved: Math.abs(after - before), focused, buttons, listed, label, toast, posted, wide: document.documentElement.scrollWidth > window.innerWidth + 1}; +})()""".replace("@HELPERS@", HELPERS) +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"))), + splits: all("#main .deny-split").map((group) => all("button", group).map(name)), + console: line(), + followed: atEnd(), + fits: out().getBoundingClientRect().right <= window.innerWidth, + dry: text(rule.querySelector(".dry-run-count")), + fields: all(".rule-request dt", rule).map(text), + accept: all("button", rule).filter((button) => name(button) === "Accept").length, + unlabelled: unlabelled(document), + wide: wide(), + }; +})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) +DENY_SHEET = """(async () => {@HELPERS@@LABELS@ + const row = await until(() => rowOf("git push"), 8000); + press(row, "Deny via …"); + const box = await until(() => document.querySelector(".sheet-box"), 4000); + return { + title: text(box.querySelector(".panel-title")), + channels: all(".deny-channels input[type=radio]", box).map((input) => [input.value, input.checked]), + hints: all(".deny-channel small", box).map(text), + reason: Boolean(box.querySelector("textarea")), + unlabelled: unlabelled(box), + wide: wide(), + }; +})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) +DENY = """(async () => {@HELPERS@@LABELS@ + const row = await until(() => askOf("make deploy"), 8000); + if (!row) { + return {error: text(document.getElementById("main"))}; + } + press(row, "Deny via …"); + const box = await until(() => document.querySelector(".sheet-box"), 4000); + box.querySelector('input[value="call"]').click(); + box.querySelector("textarea").value = "make the gate green first"; + press(box.querySelector(".actions"), "Deny"); + const undo = await until(() => all("#toasts .toast.wait").find((toast) => toast.textContent.includes("Denial")), 8000); + return {undo: text(undo), sheet: !document.getElementById("sheet").hidden}; +})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) +DENIED = """(async () => {@HELPERS@@LABELS@ + return {gone: Boolean(await until(() => !askOf("make deploy"), 20000))}; +})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) +ACCEPT = """(async () => {@HELPERS@@LABELS@ + press(rowOf("Rule request"), "Accept"); + const toast = await until(() => all("#toasts .toast").find((box) => box.textContent.includes("Created: Rule")), 15000); + await until(() => !rowOf("Rule request"), 8000); + return {toast: text(toast), left: Boolean(rowOf("Rule request"))}; +})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) +WATCH = """ + const questions = []; + window.confirm = (question) => { + questions.push(question); + return true; + }; + let asked = 0; + const get = navigator.credentials.get.bind(navigator.credentials); + navigator.credentials.get = (options) => { + asked += 1; + return @SIGNS@ ? get(options) : Promise.reject(new DOMException("The operator canceled.", "NotAllowedError")); + }; + const posted = []; + const send = window.fetch.bind(window); + window.fetch = (path, init) => { + if (["/api/choices/sign", "/api/choices", "/api/sign", "/api/inbox/approve"].includes(String(path))) { + const body = JSON.parse(init.body); + posted.push([String(path), Object.keys(body).sort(), body.class || null, body.to || null]); + } + return send(path, init); + }; + const bar = () => document.getElementById("choice-request"); + const fresh = async (shown, prefix) => until(() => all("#toasts .toast").filter((box) => !shown.has(box)).map(text).find((entry) => entry.startsWith(prefix)), 20000); + const fits = () => ({tall: document.documentElement.scrollHeight > window.innerHeight, wide: document.documentElement.scrollWidth > window.innerWidth + 1}); +""" +CHOICE_VIEW = """(async () => {@HELPERS@@LABELS@ + const found = await until(() => document.getElementById("choice-request") && all("#main .inbox-list > li .options").length === @CARDS@ && document.querySelector('#choice-request input[type="checkbox"]'), 8000); + if (!found) { + return {error: text(document.getElementById("main"))}; + } + const box = document.getElementById("choice-request"); + const chip = document.querySelector('#main [aria-label="Task filters"] button[data-filter="operator"]'); + const closed = all("button[data-channel]", box).filter((button) => button.checkVisibility()).length; + return { + kinds: [...new Set(all("#main .inbox-list > li").map((li) => text(li.querySelector(".pill"))))].sort(), + filter: [text(chip).replace(/[0-9]+$/, ""), chip.getAttribute("aria-pressed")], + channels: all("button[data-channel]", box).map((button) => [button.dataset.channel, name(button), button.disabled]), + fields: all("textarea, input:not([type=checkbox])", box).length, + agents: all('input[type="checkbox"]', box).map((input) => input.value), + multi: [name(box.querySelector("summary")), box.open, closed, text(box.querySelector(".menu-box h3 .count")), all('input[type="checkbox"]', box).filter((input) => input.checked).length], + bar: [box.parentElement.getAttribute("aria-label"), toolbarRows(), taskLayout()], + cards: all("#main .inbox-list > li").filter((li) => li.querySelector(".options")).map((li) => [text(li.querySelector(".pill")), all(".option strong", li).map(text)]), + choices: all("#main [data-column], #main .group-title, #main h2, #main h3").filter((node) => node.dataset.column === "choices" || text(node) === "Choices").length, + unlabelled: unlabelled(document), + tall: document.documentElement.scrollHeight > window.innerHeight, + wide: wide(), + }; +})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) +CHOICE_SEND = """(async () => {@HELPERS@@WATCH@ + const menu = bar(); + menu.querySelector("summary").click(); + await sleep(200); + const boxes = all('input[type="checkbox"]', menu).slice(0, 2); + boxes.forEach((box) => box.click()); + const counted = text(menu.querySelector(".menu-box h3 .count")); + const opened = [menu.open, all("button[data-channel]", menu).filter((button) => button.checkVisibility()).length]; + const picked = boxes.map((box) => box.value).sort((a, b) => a.localeCompare(b)); + const runs = []; + for (const button of all("button[data-channel]", bar())) { + const [before, prompts, sent] = [asked, questions.length, posted.length]; + const shown = new Set(all("#toasts .toast")); + const disabled = button.disabled; + button.click(); + const toast = await fresh(shown, "Choice request"); + runs.push({channel: button.dataset.channel, disabled, asked: asked - before, question: questions.slice(prompts), posted: posted.slice(sent), toast}); + } + 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) { + return {error: text(document.getElementById("main"))}; + } + const option = all(".option", card).find((button) => text(button.querySelector("strong")) === "Wait"); + const title = option.title; + const shown = new Set(all("#toasts .toast")); + option.click(); + const toast = await fresh(shown, "Choice: Wait"); + const gone = @SIGNS@ ? Boolean(await until(() => !all("#main .inbox-list > li").some((li) => li.textContent.includes("@QUESTION@")), 20000)) : null; + return {title, asked, posted, toast, gone, closed, ...fits()}; +})()""".replace("@HELPERS@", HELPERS).replace("@WATCH@", WATCH) +TASKS_FIT = """(async () => {@HELPERS@ + await until(() => document.getElementById("choice-request") && document.querySelector("#main .tasks-body > *"), 8000); + document.getElementById("toasts").replaceChildren(); + await sleep(300); + return { + hash: location.hash, + bar: all("#choice-request button[data-channel]").map((button) => button.dataset.channel), + rows: toolbarRows(), + layout: taskLayout(), + columns: all("#main .task-column").map((column) => column.dataset.column), + choices: all("#main [data-column], #main .group-title, #main h2, #main h3").filter((node) => node.dataset.column === "choices" || text(node) === "Choices").length, + tall: document.documentElement.scrollHeight > window.innerHeight, + wide: document.documentElement.scrollWidth > window.innerWidth + 1, + }; +})()""".replace("@HELPERS@", HELPERS) +CHOICE_REQUEST = "send me your open decisions as choices" +SLOW ="seq -f 'Row %g' 1 60; sleep 4; seq -f 'Row %g' 61 80; sleep 4; echo finished" diff --git a/tests/e2e/hub_e2e_kit.py b/tests/e2e/hub_e2e_kit.py new file mode 100644 index 0000000..1253b85 --- /dev/null +++ b/tests/e2e/hub_e2e_kit.py @@ -0,0 +1,249 @@ +from __future__ import annotations + +import array +import base64 +import json +import math +import os +import subprocess +import sys +import tempfile +import threading +import time +from collections.abc import Callable +from pathlib import Path +from unittest import mock + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent)) + +from hub_case import HubCase +from hub_engines import wav_bytes +from hub_support import ASK, iso + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/orchestrator-phase4-shots")) +WIDTHS = ((1920, 1080), (1366, 768), (390, 844)) +VIEWS = ("orbit", "chord", "swimlane", "tree", "3d") +TASK_VIEWS = ("list", "board", "rasci", "gantt", "burn", "3d") +SCREENS = ["home", "stream", "tasks/operator", "stream/rules", *(f"{tab}/{view}" for tab in ("agents", "artifacts") for view in VIEWS), "agents/hierarchy", *(f"tasks/{view}" for view in TASK_VIEWS), "resources"] +SUBS = ["Firewall"] +TABS = ["Home", "Stream", "Agents", "Artifacts", "Tasks", "Resources"] +HELPERS = """ + const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + const until = async (check, ms) => { + const end = Date.now() + ms; + while (Date.now() < end) { + const found = check(); + if (found) { + return found; + } + await sleep(200); + } + return null; + }; + 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 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) : []; + let [rows, bottom] = [0, -Infinity]; + for (const box of boxes) { + if (box.top >= bottom - 1) { + rows += 1; + bottom = box.bottom; + } else { + bottom = Math.max(bottom, box.bottom); + } + } + return rows; + }; + 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(() => { + if (typeof Nav !== "object") { + return false; + } + const route = Nav.route(location.hash); + const view = route.view ? Nav.viewsOf(route.screen).find(([id]) => id === route.view)[1] : null; + const pressed = name(document.querySelector('#main [aria-label="View"] button[aria-pressed="true"]')); + return document.getElementById("main").getAttribute("aria-labelledby") === `tab-${route.screen}` && (!view || pressed === view); + }, ms); + await sleep(0); + return Boolean(shown); + }; +""" +OVERLAP = """ + const shown = (node) => node.getClientRects().length > 0 && node.getBoundingClientRect().width > 0; + const words = (label) => [...label.childNodes].filter((node) => node.nodeType === 3).map((node) => node.textContent).join("").trim(); + const called = (node) => node.getAttribute("aria-label") || (node.closest("label") ? words(node.closest("label")) : "") || text(node) || node.type; + const clashes = (root) => { + const boxes = all("input, select, textarea, button", root).filter(shown).map((node) => ({node, box: node.getBoundingClientRect()})); + const found = []; + boxes.forEach((a, index) => boxes.slice(index + 1).forEach((b) => { + const x = Math.min(a.box.right, b.box.right) - Math.max(a.box.left, b.box.left); + const y = Math.min(a.box.bottom, b.box.bottom) - Math.max(a.box.top, b.box.top); + if (x > 0.5 && y > 0.5) { + found.push(`${called(a.node)} × ${called(b.node)}`); + } + })); + const framed = (node) => (getComputedStyle(node).display === "contents" ? framed(node.parentElement) : node); + const outside = boxes.filter(({box}) => box.right > framed(root).getBoundingClientRect().right + 0.5).map(({node}) => called(node)); + return {found, outside}; + }; +""" +SPEAKING = """ + const caption = () => { + const node = document.querySelector("#radio-spot:not([hidden]) .radio-caption"); + return node && !node.hidden ? node : null; + }; + const ring = (box) => getComputedStyle(box.querySelector(".speaker-face"), "::after").animationName; + const mouth = (art) => (art ? [art.classList.contains("speaking"), getComputedStyle(art.querySelector(".mouth")).animationName] : null); + const faces = () => ({ + speaking: mouth(document.querySelector('#radio-spot .radio-caption .avatar[data-face="s2"]')), + silent: mouth(document.querySelector('.avatar[data-face]:not([data-face="s2"])')), + keys: [...new Set(all(".avatar.speaking").map((art) => art.dataset.face))], + }); + const cue = async (word) => { + await until(() => document.querySelector("#radio-spot:not([hidden])"), 8000); + await fetch("/api/tts", {method: "POST", headers: {"X-Kvb-Orchestrator": "1", "Content-Type": "application/json"}, body: JSON.stringify({text: word, voice: ""}), cache: "no-store"}); + const found = await until(caption, 25000); + return found ? {who: text(found.querySelector("strong")), line: text(found.querySelector(".caption-line")), chip: found.querySelector(".avatar").dataset.face, ring: ring(found), faces: faces()} : {error: "no caption", toasts: all("#toasts .toast").map(text)}; + }; +""" +FITS = "tall: document.documentElement.scrollHeight > window.innerHeight, wide: document.documentElement.scrollWidth > window.innerWidth + 1" +GRAPH_HOOK = """() => { + let made = null; + Object.defineProperty(window, "ForceGraph3D", { + configurable: true, + get: () => made && ((options) => { + const graph = made(options); + window.e2eGraphs = [...(window.e2eGraphs || []), graph]; + return graph; + }), + set: (value) => { + made = value; + }, + }); +}""" + + +def tone(seconds: int, rate: int) -> bytes: + frames = array.array("h", (int(6000 * math.sin(2 * math.pi * 440 * n / rate)) for n in range(seconds * rate))) + return wav_bytes(1, 2, rate, frames.tobytes()) + + +UNLABELLED = """ + const unlabelled = (root, skip) => all("svg.bi", root).filter((svg) => !svg.closest(".sprite") && !(skip && skip.contains(svg))).map((svg) => svg.parentElement).filter((owner) => !text(owner) && !(owner.getAttribute("title") && owner.getAttribute("aria-label"))).map((owner) => owner.outerHTML.slice(0, 160)); +""" +LABELS = UNLABELLED + """ + const wide = () => document.documentElement.scrollWidth > window.innerWidth + 1; + const rowOf = (words) => all("#main .inbox-list > li").find((li) => li.textContent.includes(words)); + const askOf = (command) => all("#main .inbox-list > li.k-ask").find((li) => text(li.querySelector(".command code")) === command); + const press = (root, label) => all("button", root).find((button) => name(button) === label).click(); + const out = () => document.querySelector("#main .console .console-out"); + const atEnd = () => out().scrollTop + out().clientHeight >= out().scrollHeight - 12; + const line = () => text(document.querySelector("#main .console .console-status")); +""" +CHOICE_CHANNELS = ["post", "call", "newsletter", "broadcast", "pan-pan", "security", "mayday"] + + +def labelled(probe: dict) -> dict: + return {key: probe[key] for key in ("unlabelled", "broken")} + + +class OrchestratorE2ECase(HubCase): + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.seed() + + def seed(self) -> None: + now = time.time() + self.root = self.write_tree() + feature = f"{self.root}/worktrees/github.com/me/demo/feature" + self.claim("s1", "Skills session") + self.write_council({ + "work/s2/claim.json": {"office": "work/s2", "session": "s2", "runtime": "claude", "name": "Stage", "since": iso(now - 7200), "beat": now - 2000, "work": "x"}, + "chair/claim.json": {"office": "chair", "session": "s1", "runtime": "claude", "name": "Skills session", "since": iso(now - 7200), "beat": now, "work": "allocate"}, + "identity/oidc/claim.json": {"office": "identity/oidc", "session": "s2", "runtime": "claude", "name": "Stage", "since": iso(now - 7200), "beat": now - 2000, "work": "oidc line"}, + "rasci.json": { + "work/stage": {"title": "Stage line", "status": "running", "worker": "Stage (this session)", "roles": {"Stage (this session)": "RA"}}, + "work/feature": { + "title": "Show the merge flow in the hub", "status": "running", "worker": "Skills session", "objective": "The operator sees where a branch flows", "workdir": feature, "prio": 1, + "roles": {"Skills session": "RA", "Operator": "C", "Docs": "I"}, "key_results": [{"text": "Flow in the tree", "met": True}, {"text": "Flow in Tasks", "met": False}], + "estimates": {"Skills": {"value": 8, "complexity": 3, "at": iso(now - 600)}}, + }, + "work/docs": {"title": "Update the README", "status": "blocked", "worker": "Docs", "branch": "main", "roles": {"Docs": "R", "Maintainer": "A", "Skills": "S"}, "estimates": {"Docs": {"value": 3, "complexity": 2}}}, + "work/old": {"title": "Old line", "status": "done", "worker": "Stage", "end": iso(now - 86400), "roles": {"Stage": "RA"}}, + "operator/push": {"title": "git push", "workdir": "/repo", "status": "done", "roles": {"Operator": "R"}}, + }, + "queue.json": {"seq": 3, "entries": [{"id": "gate-3", "kind": "gate", "task": "work/feature", "workdir": feature, "session": "s1", "name": "Skills", "status": "waiting", "enqueued": now - 120, "cmd": "make test"}]}, + "radio-silence.json": {"since": now - 60, "until": now + 3600, "by": "Docs", "text": "disk full"}, + "news.jsonl": self.jsonl([ + {"ts": now - 600, "from": "Skills", "to": ["Stage"], "text": "rebase please", "class": "post", "v": 2}, + {"ts": now - 500, "from": "Stage", "to": ["Skills"], "text": "gate red", "class": "call", "v": 2}, + {"ts": now - 400, "from": "Maintainer", "to": [], "text": "main is green", "class": "newsletter", "v": 2}, + {"ts": now - 300, "from": "Maintainer", "to": [], "text": "rotate keys", "class": "security", "v": 2}, + {"ts": now - 60, "from": "Docs", "to": [], "text": "MAYDAY disk full", "class": "mayday", "v": 2}, + ]), + }) + self.subagents(now) + self.request("feat: orchestrator", "") + self.create_ask({**ASK, "timeout": 3600}) + self.base = f"http://{self.host}/" + + def subagents(self, now: float) -> None: + def line(ts: float) -> dict: + return {"type": "user", "sessionId": "s1", "timestamp": iso(ts), "message": {"role": "user", "content": "x"}} + + folder = self.projects / "-repo" / "s1" / "subagents" + folder.mkdir(parents=True) + (self.projects / "-repo" / "s1.jsonl").write_text(self.jsonl([line(now - 3600), line(now - 30)]), encoding="utf-8") + for ident, finished in (("abc", True), ("def", False)): + (folder / f"agent-{ident}.meta.json").write_text(json.dumps({"agentType": "Explore", "description": f"look {ident}", "spawnDepth": 1, "finished": finished}), encoding="utf-8") + (folder / f"agent-{ident}.jsonl").write_text(self.jsonl([line(now - 1800), line(now - 60)]), encoding="utf-8") + + def drive(self, steps: list[dict], authenticator: dict | None, driver: str = "cdp.mjs", binary: str = os.environ.get("CHROMIUM", "chromium"), init: str | None = None) -> dict: + with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as handle: + json.dump({"steps": steps, "authenticator": authenticator, "init": init}, handle) + self.addCleanup(os.unlink, handle.name) + done = subprocess.run(["node", str(HERE / driver), binary, handle.name], capture_output=True, text=True, timeout=900, check=False) + self.assertEqual(done.returncode, 0, done.stderr[-2000:]) + return json.loads(done.stdout) + + def beside(self, work: Callable[[], None]) -> None: + stop = threading.Event() + + def loop() -> None: + while not stop.wait(0.2): + work() + + thread = threading.Thread(target=loop, daemon=True) + thread.start() + self.addCleanup(thread.join, 10) + self.addCleanup(stop.set) + + def shot(self, name: str) -> str: + return str(OUT / f"chromium-{name}.png") + + def authenticator(self) -> dict: + signer = self.pin() + private = "".join(line for line in signer.pem.read_text(encoding="utf-8").splitlines() if not line.startswith("-----")) + return {"credentialId": base64.b64encode(signer.raw_id).decode(), "privateKey": private, "rpId": "localhost"} + + def speaks(self, cues: tuple[str, ...]) -> None: + hub = self.httpd.hub + spoken = tone(6, 8000) + + def synthesize(body: bytes, admit: Callable[[str], None]) -> bytes: + word = json.loads(body)["text"] + if word in cues: + row = {"ts": time.time(), "from": "Stage", "to": [], "text": f"Disk almost full ({word})\nsecond line", "class": "security", "v": 2} + with (self.council / "news.jsonl").open("a", encoding="utf-8") as handle: + handle.write(self.jsonl([row])) + return spoken + + patch = mock.patch.object(hub.speech, "synthesize", synthesize) + patch.start() + self.addCleanup(patch.stop) diff --git a/tests/e2e/hub_e2e_plan.py b/tests/e2e/hub_e2e_plan.py new file mode 100644 index 0000000..53b3c85 --- /dev/null +++ b/tests/e2e/hub_e2e_plan.py @@ -0,0 +1,256 @@ +from __future__ import annotations + +from hub_e2e_kit import HELPERS + +PLAN_HELPERS = """ + const fits = () => ({tall: document.documentElement.scrollHeight > window.innerHeight, wide: document.documentElement.scrollWidth > window.innerWidth + 1, rows: toolbarRows(), layout: taskLayout()}); + const modes = () => all('#main [aria-label="Estimation"] button').map((button) => [button.dataset.estimation, button.getAttribute("aria-pressed")]); + const requestShown = () => { + const button = document.getElementById("request-estimates"); + return button ? !button.hidden && button.getClientRects().length > 0 : null; + }; + const choose = async (select, value) => { + select.value = value; + select.dispatchEvent(new Event("change", {bubbles: true})); + await sleep(300); + }; + const fresh = async (shown, prefix) => until(() => all("#toasts .toast").filter((box) => !shown.has(box)).map(text).find((entry) => entry.startsWith(prefix)), 20000); +""" +GANTT = """(async () => {@HELPERS@@PLAN_HELPERS@ + const svg = await until(() => document.querySelector("#main svg.gantt"), 8000); + if (!svg) { + return {error: text(document.getElementById("main"))}; + } + const forecast = document.querySelector('#main select[aria-label="Forecast"]'); + const scroll = document.querySelector("#main .gantt-scroll"); + const marks = () => all("#main svg.gantt [data-forecast]").map((mark) => [mark.dataset.task, mark.dataset.forecast === "true", Number(mark.dataset.start), Number(mark.dataset.end), mark.tagName.toLowerCase()]); + const found = { + hash: location.hash, + forecast: [forecast.value, all("option", forecast).map((option) => [option.value, text(option)])], + modes: modes(), + request: requestShown(), + bars: marks(), + edges: all("#main svg.gantt path.gantt-edge").map((path) => [path.dataset.kind, path.dataset.from, path.dataset.to, path.getAttribute("marker-end")]), + hatched: all("#main svg.gantt .gantt-bar.forecast").map((bar) => getComputedStyle(bar).fill.includes("gantt-hatch")), + inner: Boolean(scroll && scroll.closest(".tasks-body")), + ...fits(), + }; + await choose(forecast, "real"); + found.real = marks().filter(([, hatched]) => hatched).length; + await choose(forecast, "points"); + found.pointsOnly = marks().filter(([, hatched]) => hatched).map(([task, , start, end, tag]) => [task, end - start, tag]); + await choose(forecast, "always"); + return found; +})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS) +BURN = """(async () => {@HELPERS@@PLAN_HELPERS@ + const svg = await until(() => document.querySelector("#main svg.burn"), 8000); + if (!svg) { + return {error: text(document.getElementById("main"))}; + } + const scope = document.querySelector('#main select[aria-label="Scope"]'); + const series = () => all("#main svg.burn path.burn-line").map((path) => [path.dataset.series, Number(path.dataset.last)]); + const found = {hash: location.hash, modes: modes(), request: requestShown(), scope: [scope.value, all("option", scope).map((option) => option.value)], series: series(), ...fits()}; + await choose(scope, "agent:Docs"); + found.agent = series(); + await choose(scope, "all"); + return found; +})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS) +POINTS_ON = """(async () => {@HELPERS@@PLAN_HELPERS@ + const before = {modes: modes(), request: requestShown()}; + all('#main [aria-label="Estimation"] button').find((button) => button.dataset.estimation === "points").click(); + const shown = await until(() => requestShown(), 8000); + return {before, modes: modes(), request: Boolean(shown), ...fits()}; +})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS) +REQUEST = """(async () => {@HELPERS@@PLAN_HELPERS@ + const svg = await until(() => document.querySelector("#main svg.burn") && requestShown(), 8000); + if (!svg) { + return {error: text(document.getElementById("main")), modes: modes()}; + } + const series = all("#main svg.burn path.burn-line").map((path) => [path.dataset.series, Number(path.dataset.last)]); + const shown = new Set(all("#toasts .toast")); + document.getElementById("request-estimates").click(); + const toast = await fresh(shown, "Request estimates"); + return {modes: modes(), series, toast, ...fits()}; +})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS) +BULK = """(async () => {@HELPERS@@PLAN_HELPERS@ + const list = await until(() => all("#main .task-row").length && document.getElementById("bulk-value"), 8000); + if (!list) { + return {error: text(document.getElementById("main"))}; + } + let asked = 0; + const get = navigator.credentials.get.bind(navigator.credentials); + navigator.credentials.get = (options) => { + asked += 1; + return @SIGNS@ ? get(options) : Promise.reject(new DOMException("The operator canceled.", "NotAllowedError")); + }; + const posted = []; + const send = window.fetch.bind(window); + window.fetch = (path, init) => { + if (["/api/sign", "/api/tasks"].includes(String(path))) { + const body = JSON.parse(init.body); + posted.push([String(path), Object.keys(body).sort(), body.items.map((item) => [item.id, item.argv.join(" ")])]); + } + return send(path, init); + }; + const rows = () => all("#main .task-row").map((row) => row.dataset.task); + const sort = document.querySelector('#main select[aria-label="Sort"]'); + const direction = document.querySelector("#main button[data-direction]"); + const found = {sorts: all("option", sort).map((option) => option.value), prio: rows()}; + await choose(sort, "status"); + found.status = rows(); + direction.click(); + await sleep(300); + found.statusDown = [rows(), name(direction)]; + direction.click(); + await choose(sort, "prio"); + found.picks = all("#main .task-row input.task-pick").map((box) => box.closest(".task-row").dataset.task); + for (const task of ["work/next", "work/child"]) { + all("#main .task-row").find((row) => row.dataset.task === task).querySelector("input.task-pick").click(); + } + const button = document.getElementById("bulk-value"); + found.armed = [button.disabled, text(button.querySelector(".count"))]; + await choose(document.querySelector('#main select[aria-label="Business value of the selection"]'), "@VALUE@"); + const shown = new Set(all("#toasts .toast")); + button.click(); + found.toast = await fresh(shown, "Business value @VALUE@ for 2 tasks"); + found.asked = asked; + found.posted = posted; + found.after = [button.disabled, all("#main .task-row input.task-pick:checked").length]; + Object.assign(found, fits()); + all('#main [aria-label="Estimation"] button').find((entry) => entry.dataset.estimation === "none").click(); + found.reset = Boolean(await until(() => requestShown() === false, 8000)); + return found; +})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS) +ETA_LIST = """(async () => {@HELPERS@@PLAN_HELPERS@ + const list = await until(() => all("#main .task-row .task-eta").length >= 8, 8000); + if (!list) { + return {error: text(document.getElementById("main"))}; + } + const number = (value) => (value === "" ? null : Number(value)); + const read = () => Object.fromEntries(all("#main .task-row").map((row) => { + const eta = row.querySelector(".task-eta"); + return [row.dataset.task, [number(eta.dataset.start), number(eta.dataset.eta), eta.dataset.forecast === "true", text(eta), eta.title]]; + })); + const toggle = async (mode) => { + const before = JSON.stringify(read()); + all('#main [aria-label="Estimation"] button').find((button) => button.dataset.estimation === mode).click(); + await until(() => JSON.stringify(read()) !== before, 8000); + await sleep(300); + return read(); + }; + const found = {none: read(), modes: modes(), ...fits()}; + found.points = await toggle("points"); + found.back = await toggle("none"); + return found; +})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS) +TREND_READ = """ + const trendOf = () => { + const select = document.querySelector('#main select[aria-label="Trend"]'); + const days = document.querySelector('#main input[aria-label="Velocity days"]'); + const note = document.querySelector("#main .burn-forecast"); + const marker = document.querySelector("#main svg.burn .forecast-line"); + return { + value: select.value, options: all("option", select).map((option) => [option.value, text(option)]), days: [Number(days.value), days.getClientRects().length > 0], + note: note ? [note.dataset.forecast === "" ? null : Number(note.dataset.forecast), text(note)] : null, marker: marker ? Number(marker.dataset.forecast) : null, + lines: all("#main svg.burn path.burn-trend").map((path) => [path.dataset.series, Number(path.dataset.from), Number(path.dataset.to)]), + points: all('#main svg.burn circle.burn-point[data-series="remaining"]').map((circle) => [Number(circle.dataset.t), Number(circle.dataset.value)]), + }; + }; + const chart = async () => until(() => document.querySelector("#main svg.burn") && document.querySelector('#main select[aria-label="Trend"]'), 8000); +""" +TREND_SET = """(async () => {@HELPERS@@PLAN_HELPERS@@TREND_READ@ + if (!(await chart())) { + return {error: text(document.getElementById("main"))}; + } + const before = trendOf(); + const shown = new Set(all("#toasts .toast")); + await choose(document.querySelector('#main select[aria-label="Trend"]'), "@MODE@"); + const toasts = [await fresh(shown, "Trend: ")]; + if ("@MODE@" === "velocity") { + const days = document.querySelector('#main input[aria-label="Velocity days"]'); + const again = new Set(all("#toasts .toast")); + days.value = "@DAYS@"; + days.dispatchEvent(new Event("change", {bubbles: true})); + toasts.push(await fresh(again, "Trend: velocity over @DAYS@ days")); + } + await sleep(400); + return {before, after: trendOf(), toasts, ...fits()}; +})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS).replace("@TREND_READ@", TREND_READ) +TREND_RELOADED = """(async () => {@HELPERS@@PLAN_HELPERS@@TREND_READ@ + if (!(await chart())) { + return {error: text(document.getElementById("main"))}; + } + await sleep(300); + return {...trendOf(), ...fits()}; +})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS).replace("@TREND_READ@", TREND_READ) +STEP_TIPS = """(async () => {@HELPERS@@PLAN_HELPERS@@TREND_READ@ + if (!(await chart())) { + return {error: text(document.getElementById("main"))}; + } + const steps = all('#main svg.burn circle.burn-point[data-series="remaining"]').map((circle) => ({ + t: Number(circle.dataset.t), started: circle.dataset.started, ended: circle.dataset.ended, joined: circle.dataset.joined, tip: text(circle.querySelector("title")), + series: all(`#main svg.burn circle.burn-point[data-step="${circle.dataset.step}"]`).map((mark) => mark.dataset.series), + })); + const shown = new Set(all("#toasts .toast")); + await choose(document.querySelector('#main select[aria-label="Trend"]'), "off"); + const reset = await fresh(shown, "Trend: off"); + await sleep(300); + return {steps, reset, note: Boolean(document.querySelector("#main .burn-forecast")), lines: all("#main svg.burn path.burn-trend").length, ...fits()}; +})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS).replace("@TREND_READ@", TREND_READ) +TASKS_3D = """(async () => {@HELPERS@@PLAN_HELPERS@ + const note = () => text(document.querySelector("#main .space-note")) || ""; + const ready = await until(() => window.e2eGraphs && document.querySelector("#main .graph3d canvas") && !note().startsWith("Loading"), 15000); + if (!ready) { + return {error: text(document.querySelector("#main .graph"))}; + } + const graph = () => window.e2eGraphs[window.e2eGraphs.length - 1]; + const id = (end) => (typeof end === "object" ? end.id : end); + const look = () => { + const data = graph().graphData(); + const color = graph().linkColor(); + return { + note: note(), layouts: all('#main [aria-label="Layout"] button').map((button) => [button.dataset.layout, button.getAttribute("aria-pressed")]), + nodes: data.nodes.map((node) => [node.id, Number.isFinite(node.fz) ? node.fz : null, Number.isFinite(node.ts) ? node.ts : null]), + links: data.links.map((link) => [id(link.source), id(link.target), link.kind, color(link)]), + label: (() => { + const shown = graph().nodeLabel()(data.nodes.find((node) => node.id === "work/t5")); + return shown instanceof Element ? shown.textContent : String(shown); + })(), + }; + }; + const layout = async (mode, word) => { + all('#main [aria-label="Layout"] button').find((button) => button.dataset.layout === mode).click(); + await until(() => note().endsWith(word), 8000); + await sleep(400); + return look(); + }; + const css = getComputedStyle(document.documentElement); + const palette = Object.fromEntries(["violet", "info", "warn"].map((role) => [role, css.getPropertyValue(`--${role}`).trim()])); + const force = look(); + const time = await layout("time", "Time"); + const field = document.querySelector('#main input[aria-label="Find a node"]'); + field.value = "work/t5"; + field.dispatchEvent(new Event("input", {bubbles: true})); + await sleep(200); + const chip = all("#main .hits .chip").find((node) => node.dataset.hit === "work/t5"); + if (!chip) { + return {error: "no search hit", force, time}; + } + chip.click(); + await sleep(600); + const dialog = document.getElementById("popup"); + const eta = dialog.querySelector(".task-eta"); + const popup = { + open: dialog.open, title: text(dialog.querySelector(".popup-box .panel-title")), id: text(dialog.querySelector(".popup-head .task-id")), picked: document.querySelector("#main .graph3d").dataset.picked || null, + eta: eta ? eta.dataset.eta : null, open_button: name(dialog.querySelector(".popup-body .actions button")), line: dialog.querySelector(".leader line").getAttribute("display") !== "none", + }; + (document.activeElement || document.body).dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await sleep(300); + popup.closed = [dialog.open, document.querySelector("#main .graph3d").dataset.picked || null]; + const back = await layout("none", "Force"); + await sleep(1200); + return {palette, force, time, popup, back: back.note, ...fits()}; +})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS) +PLAN_VALUES = {1920: "13", 1366: "21", 390: "34"} +TREND_DAYS = {1920: 7, 1366: 3, 390: 14} +STATUS_ORDER = ["queued", "awaiting", "claimed", "running", "blocked", "stale", "done", "stopped"] diff --git a/tests/e2e/hub_e2e_radio.py b/tests/e2e/hub_e2e_radio.py new file mode 100644 index 0000000..5eae592 --- /dev/null +++ b/tests/e2e/hub_e2e_radio.py @@ -0,0 +1,403 @@ +from __future__ import annotations + +import contextlib +import http.server + +from hub_e2e_kit import FITS, HELPERS, OVERLAP, SPEAKING + +CALL = """(async () => {@HELPERS@ + document.querySelector('#main [aria-label="Categories"] button[aria-label="Radio"]').click(); + const someone = await until(() => document.querySelector('#main button.linkish[title^="Open "]'), 8000); + someone.click(); + await sleep(500); + document.querySelector('#popup input[type=radio][value="call"]').click(); + const field = document.querySelector("#popup textarea"); + field.value = "E2E call ping"; + field.dispatchEvent(new Event("input", {bubbles: true})); + document.querySelector('#popup button[type="submit"]').click(); + const entry = await until(() => all("#main .entry").find((row) => row.textContent.includes("E2E call ping") && row.querySelector('.reader[data-acked="true"] .ack')), 20000); + const read = all("#main .entry .pill").filter((pill) => text(pill) === "Read").length; + return {to: text(someone), receipt: entry ? entry.querySelector('.reader[data-acked="true"]').title : null, read, sent: all("#main .entry").filter((row) => row.textContent.includes("E2E call ping")).length}; +})()""".replace("@HELPERS@", HELPERS) +MEDIA_LOG = """() => { + const keep = (entry) => { + try { + const list = JSON.parse(sessionStorage.getItem("e2e-media") || "[]"); + list.push({...entry, page: Math.round(performance.timeOrigin)}); + sessionStorage.setItem("e2e-media", JSON.stringify(list)); + } catch (error) { + return; + } + }; + const play = HTMLMediaElement.prototype.play; + window.e2eMedia = new Set(); + HTMLMediaElement.prototype.play = function () { + window.e2eAudio = this; + window.e2eMedia.add(this); + const src = this.getAttribute("src") || ""; + const result = play.call(this); + result.then(() => keep({play: "ok", src}), (error) => keep({play: error.name, src})); + return result; + }; + document.addEventListener("securitypolicyviolation", (event) => keep({csp: event.effectiveDirective, blocked: event.blockedURI})); +}""" +MEDIA = """ + const log = () => JSON.parse(sessionStorage.getItem("e2e-media") || "[]"); + const sample = () => (window.e2eAudio ? {paused: window.e2eAudio.paused, time: window.e2eAudio.currentTime, error: window.e2eAudio.error ? window.e2eAudio.error.code : null, src: window.e2eAudio.getAttribute("src")} : null); + const advancing = async () => { + const first = sample(); + await sleep(1500); + const second = sample(); + return {first, second, playing: Boolean(first && second && !second.paused && second.time - first.time > 0.5)}; + }; +""" +ADD_STATION = """(async () => {@HELPERS@ + const clock = (date) => `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`; + location.hash = "#stream/radio"; + const fold = await until(() => document.querySelector("#radio-spot details.radio-station"), 8000); + fold.open = true; + const edit = await until(() => all("#radio-spot button").find((button) => text(button) === "Edit stations" && button.getClientRects().length), 8000); + edit.click(); + const form = await until(() => document.querySelector('.sheet-box form[aria-label="Stations"]'), 8000); + all("button", form).find((button) => text(button) === "+ Station").click(); + await sleep(200); + const row = all(".stream-row", form).pop(); + const [label, address, start, end] = all("input.field", row); + const set = (input, value) => { + input.value = value; + input.dispatchEvent(new Event("input", {bubbles: true})); + }; + set(label, "@NAME@"); + set(address, "@STATION@"); + set(start, clock(new Date(Date.now() - 3600000))); + set(end, clock(new Date(Date.now() + 3600000))); + all('.days input[type="checkbox"]', row).forEach((box) => { + box.checked = true; + }); + all("button", form).find((button) => button.type === "submit").click(); + await until(() => all("#toasts .toast").map(text).find((toast) => toast.startsWith("New station")), 8000); + return {toasts: all("#toasts .toast").map(text)}; +})()""".replace("@HELPERS@", HELPERS) +STATION_NAME = "E2E tone with a very long station name that fits on no single line" +DLF_PATH = "/dlf/01/high/aac/stream.aac?aggregator=web" +DLF_NODE = "/ard/dlf/01/aac/192/stream.aac?aggregator=web" +RADIO_STATE = """(async () => {@HELPERS@@MEDIA@ + await until(() => log().some((entry) => entry.play), 8000); + return {log: log(), media: await advancing(), toasts: all("#toasts .toast").map(text)}; +})()""".replace("@HELPERS@", HELPERS).replace("@MEDIA@", MEDIA) +RADIO_VIEW = """(async () => {@HELPERS@@MEDIA@ + location.hash = "#stream/radio"; + const fold = await until(() => document.querySelector("#radio-spot details.radio-station"), 8000); + fold.open = true; + const row = await until(() => all('#radio-spot [data-station="0"]').find((item) => item.getClientRects().length), 8000); + if (!row) { + const initial = JSON.parse(document.getElementById("state").textContent); + return {error: "no station row", log: log(), wrapped: !String(HTMLMediaElement.prototype.play).includes("[native code]"), streams: initial.settings.streams, media: initial.media, now: new Date().toString()}; + } + const label = row.querySelector(".station-name"); + const style = getComputedStyle(label); + return { + state: row.dataset.state, + note: text(row.querySelector(".station-note")), + title: label.title, + line: [style.whiteSpace, style.textOverflow, label.scrollWidth > label.clientWidth, label.getBoundingClientRect().height < 2 * parseFloat(style.lineHeight)], + media: await advancing(), + log: log(), + toasts: all("#toasts .toast").map(text), + }; +})()""".replace("@HELPERS@", HELPERS).replace("@MEDIA@", MEDIA) +RADIO_CLICK = """(async () => {@HELPERS@@MEDIA@ + const row = document.querySelector('#radio-spot [data-station="0"]'); + if (!row) { + return {error: "no station row", log: log(), media: await advancing()}; + } + const play = row.querySelector('button[data-action="play"]'); + const clicked = Boolean(sample() && sample().paused && play); + if (clicked) { + play.click(); + } + await until(() => sample() && !sample().paused, 6000); + const media = await advancing(); + const now = document.querySelector('#radio-spot [data-station="0"]'); + return {clicked, state: now.dataset.state, note: text(now.querySelector(".station-note")), media, log: log()}; +})()""".replace("@HELPERS@", HELPERS).replace("@MEDIA@", MEDIA) +RADIO_STOP = """(async () => {@HELPERS@@MEDIA@ + const row = () => document.querySelector('#radio-spot [data-station="0"]'); + const stop = row() ? row().querySelector('button[data-action="stop"]') : null; + if (!stop) { + return {error: "no Stop button on the playing station", state: row() ? row().dataset.state : null, media: sample(), log: log()}; + } + const button = [stop.getAttribute("aria-label"), stop.title, text(stop), Boolean(stop.querySelector('svg.bi use[href="#bi-stop-fill"]'))]; + stop.click(); + const paused = Boolean(await until(() => sample() && sample().paused && sample().src === null, 8000)); + const media = await advancing(); + const now = row(); + const action = now ? now.querySelector("button[data-action]") : null; + const elements = [...new Set([...(window.e2eMedia || []), ...all("audio, video")])]; + return { + button, paused, media, tracked: (window.e2eMedia || new Set()).size, + state: now ? now.dataset.state : null, note: now ? text(now.querySelector(".station-note")) : null, + action: action ? [action.dataset.action, action.getAttribute("aria-label")] : null, + playing: elements.filter((element) => !element.paused).map((element) => element.getAttribute("src") || element.currentSrc || element.tagName), + }; +})()""".replace("@HELPERS@", HELPERS).replace("@MEDIA@", MEDIA) +SPEAK = """(async () => {@HELPERS@@SPEAKING@ + return cue("@CUE@"); +})()""".replace("@HELPERS@", HELPERS).replace("@SPEAKING@", SPEAKING) +SPEAK_GRAPH = """(async () => {@HELPERS@@SPEAKING@ + location.hash = "#agents/orbit"; + const node = await until(() => document.querySelector("#main svg .node.speaking"), 6000); + const silent = document.querySelector('#main svg .node[data-pick="s1"] .mouth'); + return { + node: node ? node.getAttribute("aria-label") : null, ring: node ? getComputedStyle(node.querySelector("circle")).animationName : null, + mouth: node ? getComputedStyle(node.querySelector(".mouth")).animationName : null, silent: silent ? getComputedStyle(silent).animationName : null, + }; +})()""".replace("@HELPERS@", HELPERS).replace("@SPEAKING@", SPEAKING) +SPEAK_END = """(async () => {@HELPERS@@SPEAKING@ + const ended = Boolean(await until(() => !document.querySelector("#main svg .node") || !document.querySelector("#main svg .node.speaking"), 20000)); + location.hash = "#stream/radio"; + await until(() => document.querySelector("#radio-spot:not([hidden]) .radio-caption"), 6000); + await sleep(300); + return {ended, caption: Boolean(caption()), faces: all(".avatar.speaking").length}; +})()""".replace("@HELPERS@", HELPERS).replace("@SPEAKING@", SPEAKING) +SPOT_OPEN = """ + const spotToggle = document.getElementById("radio-open"); + if (spotToggle && spotToggle.getAttribute("aria-expanded") !== "true") { + spotToggle.click(); + await sleep(300); + } + const spot = document.getElementById("radio-spot"); +""" +COMPOSE = """(async () => {@HELPERS@@SPOT_OPEN@ + const form = spot ? spot.querySelector("form.composer") : null; + if (!form) { + return {error: "no composer"}; + } + const [channel, recipient] = all("select", form); + await until(() => [...recipient.options].some((option) => option.value === "@TO@"), 8000); + channel.value = "call"; + channel.dispatchEvent(new Event("change", {bubbles: true})); + recipient.value = "@TO@"; + const record = all("button", form).find((button) => button.hasAttribute("aria-pressed")); + record.click(); + await sleep(1500); + const recording = record.getAttribute("aria-pressed"); + record.click(); + const field = form.querySelector("textarea"); + await until(() => field.value && form.querySelector('.voice-note input[type="checkbox"]'), 60000); + const replay = form.querySelector(".voice-note audio"); + const attach = form.querySelector('.voice-note input[type="checkbox"]'); + return { + channels: all("option", channel).map((option) => option.value), + recipients: all("option", recipient).map((option) => option.value), + recording, + text: field.value, + replay: replay ? replay.getAttribute("src") : null, + attach: attach ? [text(attach.closest("label")), attach.checked] : null, + status: text(form.querySelector(".composer-status")), + toasts: all("#toasts .toast").map(text), + clashes: (() => {@CLASHES@ + return clashes(form); + })(), + }; +})()""".replace("@HELPERS@", HELPERS).replace("@SPOT_OPEN@", SPOT_OPEN).replace("@CLASHES@", OVERLAP) +COMPOSE_SEND = """(async () => {@HELPERS@ + const form = document.querySelector("#radio-spot form.composer"); + const field = form.querySelector("textarea"); + field.value = `${field.value} please`; + field.dispatchEvent(new Event("input", {bubbles: true})); + form.querySelector('.voice-note input[type="checkbox"]').checked = @ATTACH@; + const before = all("#toasts .toast").length; + form.querySelector('button[type="submit"]').click(); + const sent = await until(() => all("#toasts .toast").slice(before).map(text).find((toast) => toast.startsWith("Call to")), 20000); + return {sent, left: field.value, voice: Boolean(form.querySelector(".voice-note audio"))}; +})()""".replace("@HELPERS@", HELPERS) +CLEAR_MAYDAY = """(async () => {@HELPERS@ + const questions = []; + let accept = false; + window.confirm = (question) => { + questions.push(question); + return accept; + }; + const posted = []; + const send = window.fetch.bind(window); + window.fetch = (path, init) => { + if (String(path).startsWith("/api/board/")) { + posted.push(String(path)); + } + return send(path, init); + }; + await until(() => document.querySelector('#main [role="toolbar"]'), 8000); + const toolbar = all('#main [role="toolbar"] button, #main [role="toolbar"] summary').map(name);@SPOT_OPEN@ + const button = await until(() => spot && all(".spot-head button", spot).find((node) => name(node) === "Cancel mayday" && !node.disabled), 8000); + if (!button) { + return {error: "no enabled Cancel mayday button in the radio spot", toolbar}; + } + const shown = new Set(all("#toasts .toast")); + const fresh = () => all("#toasts .toast").filter((node) => !shown.has(node)).map(text); + button.click(); + await sleep(800); + const declined = {question: questions.slice(), posted: posted.slice(), toasts: fresh()}; + accept = true; + button.click(); + const done = await until(() => fresh().find((toast) => toast.startsWith("Cancel mayday")), 15000); + return {toolbar, title: button.title, shown: text(button), declined, accepted: {question: questions.slice(declined.question.length), posted: posted.slice(declined.posted.length)}, done}; +})()""".replace("@HELPERS@", HELPERS).replace("@SPOT_OPEN@", SPOT_OPEN) +SPOT_SEND = """(async () => {@HELPERS@ + const questions = []; + window.confirm = (question) => { + questions.push(question); + return true; + }; + await until(() => document.querySelector('#main [role="toolbar"]'), 8000); + const toggle = document.getElementById("radio-open"); + const main = document.getElementById("main"); + const spot = document.getElementById("radio-spot"); + const closed = [spot.hidden, toggle.getAttribute("aria-expanded")]; + toggle.click(); + await sleep(400); + const form = spot.querySelector("form.composer"); + const [channel, recipient] = all("select", form); + const field = form.querySelector("textarea"); + const found = { + closed, + open: [spot.hidden, toggle.getAttribute("aria-expanded"), document.activeElement === field], + inline: [getComputedStyle(spot).position, spot.getBoundingClientRect().bottom <= main.getBoundingClientRect().top, spot.parentElement.nextElementSibling === main], + toolbar: all('#main [role="toolbar"] > *').map((node) => name(node.tagName === "DETAILS" ? node.querySelector("summary") : node)), + channels: all("option", channel).map((option) => option.value), + record: all("button", form).filter((button) => button.hasAttribute("aria-pressed")).map(text), + heads: all(".spot-head button", spot).map((button) => [name(button), button.title]), + @FITS@, + }; + await until(() => [...recipient.options].some((option) => option.value === "Stage"), 8000); + found.runs = []; + for (const cls of found.channels) { + channel.value = cls; + channel.dispatchEvent(new Event("change", {bubbles: true})); + const direct = !recipient.closest("label").hidden; + if (direct) { + recipient.value = "Stage"; + } + field.value = `@TEXT@ ${cls}`; + field.dispatchEvent(new Event("input", {bubbles: true})); + const shown = new Set(all("#toasts .toast")); + const prompts = questions.length; + const submit = form.querySelector('button[type="submit"]'); + submit.click(); + const toast = await until(() => all("#toasts .toast").filter((node) => !shown.has(node)).map(text).find((entry) => entry.includes(" to ")), 20000); + await until(() => !submit.disabled, 20000); + found.runs.push({cls, direct, toast, question: questions.slice(prompts), left: field.value}); + } + document.getElementById("toasts").replaceChildren(); + return found; +})()""".replace("@HELPERS@", HELPERS).replace("@FITS@", FITS) +RADIO_JUMP = """(async () => {@HELPERS@ + const spot = await until(() => location.hash === "#stream" && document.querySelector("#radio-spot:not([hidden])"), 8000); + if (!spot) { + return {error: text(document.getElementById("main"))}; + } + await sleep(200); + const focused = document.activeElement === spot.querySelector("textarea"); + const tabs = []; + for (const hash of ["#home", "#stream/inbox", "#agents/orbit", "#artifacts/tree", "#tasks/list", "#resources"]) { + location.hash = hash; + await sleep(500); + const main = document.getElementById("main"); + tabs.push([hash, !spot.hidden, spot.getBoundingClientRect().bottom <= main.getBoundingClientRect().top]); + } + const toggle = document.getElementById("radio-open"); + toggle.click(); + await sleep(200); + return { + hash: "#stream", focused, tabs, closed: [spot.hidden, toggle.getAttribute("aria-expanded")], + header: all("header.top button").map((button) => [button.id, name(button), text(button)]), radioTab: Boolean(document.getElementById("tab-radio")), + }; +})()""".replace("@HELPERS@", HELPERS) +CANCELED = """() => { + window.e2ePasskeys = 0; + if (navigator.credentials) { + navigator.credentials.get = () => { + window.e2ePasskeys += 1; + return Promise.reject(new DOMException("The operator canceled.", "NotAllowedError")); + }; + } +}""" +JUMPED = { + "hash": "#stream", "focused": True, "tabs": [[tab, True, True] for tab in ("#home", "#stream/inbox", "#agents/orbit", "#artifacts/tree", "#tasks/list", "#resources")], "closed": [True, "false"], + "header": [["radio-open", "Radio", ""], ["bubbles-toggle", "Speech bubbles", ""], ["palette-open", "Commands", ""], ["settings-open", "Settings", ""]], "radioTab": False, +} +GEAR_SAVE = """(async () => {@HELPERS@@CLASHES@ + const spot = document.getElementById("radio-spot"); + const face = spot.querySelector(".radio-face"); + const gear = all(".spot-head button", spot).find((button) => name(button) === "Read aloud"); + gear.click(); + const box = await until(() => spot.querySelector("#radio-gear .radio-read"), 4000); + if (!box) { + return {error: "no read-aloud filters behind the gear"}; + } + const chips = () => all('#radio-gear [aria-label="Classes"] button', spot); + const post = () => chips().find((chip) => text(chip) === "Post"); + const found = { + expanded: gear.getAttribute("aria-expanded"), + tones: all(".radio-knobs .knob-label", face).map(text), + classes: chips().map((chip) => [text(chip), chip.getAttribute("aria-pressed"), chip.disabled]), + clashes: [clashes(face), clashes(spot.querySelector("#radio-gear"))], + @FITS@, + }; + const squelch = face.querySelector('input[aria-label="Squelch"]'); + squelch.value = "@SQUELCH@"; + squelch.dispatchEvent(new Event("input", {bubbles: true})); + const tone = face.querySelector('button[aria-label="All radio tone"]'); + if (tone.getAttribute("aria-pressed") !== "@TONE@") { + tone.click(); + } + if (post().getAttribute("aria-pressed") !== "@POST@") { + post().click(); + } + await sleep(200); + const kept = JSON.parse(localStorage.getItem("kvb-orchestrator.radio")); + found.kept = [kept.squelch, kept.sounds.radio.on, kept.classes.includes("post")]; + gear.click(); + await sleep(200); + found.after = [gear.getAttribute("aria-expanded"), Boolean(spot.querySelector("#radio-gear .radio-read"))]; + document.getElementById("settings-open").click(); + const sheet = await until(() => document.querySelector(".sheet-box form.settings"), 4000); + found.general = {sections: all("section > h3", sheet).map(text), radio: all('[aria-label="Squelch"], [aria-label="Classes"], [aria-label="Speakers"], [aria-label="Mode"], .sound-row, .stream-row', sheet).length}; + document.querySelector(".sheet-head button").click(); + return found; +})()""".replace("@HELPERS@", HELPERS).replace("@CLASHES@", OVERLAP).replace("@FITS@", FITS) +GEAR_READ = """(async () => {@HELPERS@@SPOT_OPEN@ + const gear = spot ? all(".spot-head button", spot).find((button) => name(button) === "Read aloud") : null; + if (!gear) { + return {error: text(document.getElementById("main"))}; + } + gear.click(); + await until(() => spot.querySelector("#radio-gear .radio-read"), 4000); + const face = spot.querySelector(".radio-face"); + return { + squelch: Number(face.querySelector('input[aria-label="Squelch"]').value), + tone: face.querySelector('button[aria-label="All radio tone"]').getAttribute("aria-pressed") === "true", + post: all('#radio-gear [aria-label="Classes"] button', spot).find((chip) => text(chip) === "Post").getAttribute("aria-pressed") === "true", + @FITS@, + }; +})()""".replace("@HELPERS@", HELPERS).replace("@SPOT_OPEN@", SPOT_OPEN).replace("@FITS@", FITS) + + +class Station(http.server.BaseHTTPRequestHandler): + def do_GET(self) -> None: + if self.server.moved: + self.send_response(302) + self.send_header("Location", self.server.moved) + self.send_header("Content-Length", "0") + self.end_headers() + return + body = self.server.body + self.send_response(200) + self.send_header("Content-Type", "audio/wav") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + with contextlib.suppress(OSError): + self.wfile.write(body) + + def log_message(self, *args: object) -> None: + return diff --git a/tests/e2e/hub_e2e_views.py b/tests/e2e/hub_e2e_views.py new file mode 100644 index 0000000..61d4277 --- /dev/null +++ b/tests/e2e/hub_e2e_views.py @@ -0,0 +1,334 @@ +from __future__ import annotations + +from hub_e2e_kit import FITS, HELPERS, OVERLAP + +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"); + return found && !found.hidden ? text(found) : null; + }; + const icons = all("svg.bi").filter((svg) => !svg.closest(".sprite")); + const banner = document.getElementById("mayday"); + return { + hash: location.hash, + title: document.title, + h1: text(document.querySelector("h1")), + header: all("header.top button").map((button) => button.id), + tabs: all("#tabs > .tab-group > button").map(name), + subs: all("#tabs .subtabs button").map(name), + badges: Object.fromEntries(all("#tabs button").map((button) => [button.id, badge(button)])), + banner: banner.hidden ? null : text(banner), + rail: Boolean(document.getElementById("rail")), + views: all('#main [aria-label="View"] button').map(name), + layouts: all('#main [aria-label="Layout"] button').map(name), + chips: all('#main [aria-label="Categories"] button').map(name), + menus: all("#main details.menu > summary").map(name), + time: text(document.querySelector("#time > summary")), + replay: Boolean(document.querySelector("#time .replay input[type=range]")), + custom: Boolean(document.querySelector('#main details.menu input[type="datetime-local"]')), + toolbar: all('#main [role="toolbar"] > *').map((node) => name(node.tagName === "DETAILS" ? node.querySelector("summary") : node.querySelector("button") || node)), + spot: (() => { + const box = document.getElementById("radio-spot"); + return box ? {hidden: box.hidden, channels: [...box.querySelector("form.composer select").options].map((option) => option.value)} : null; + })(), + composers: all("form.composer").map((form) => (form.closest("#radio-spot") ? "spot" : "other")), + inbox: all("#main .inbox-list > li").length, + icons: icons.length, + unlabelled: icons.map((svg) => svg.parentElement).filter((owner) => !text(owner) && !(owner.getAttribute("title") && owner.getAttribute("aria-label"))).map((owner) => owner.outerHTML.slice(0, 160)), + broken: all("svg.bi use").filter((use) => !document.getElementById(use.getAttribute("href").slice(1))).map((use) => use.getAttribute("href")), + states: all("#main span.state").map(name), + deletes: all('#main button[aria-label="Delete"], #main button[aria-label="Delete all merged"]').map((button) => [name(button), button.disabled, button.title]), + spawn: all("#main .spawn-tree li").map((item) => [item.dataset.kind, item.dataset.running || null]), + marks: all("#main svg.chart .node").length, + note: text(document.querySelector("#main .space-note")), + canvas: Boolean(document.querySelector("#main .graph3d canvas")), + org: all("#main .org-chart .org-row[data-office]").map((row) => [row.dataset.office, text(row.querySelector(".org-holder"))]), + toggles: all("#main .org-toggle").map((button) => [name(button), button.getAttribute("aria-expanded")]), + order: all("#main .agent-order li").map((item) => item.dataset.name), + taskFilters: all('#main [aria-label="Task filters"] button').map((button) => [button.dataset.filter, button.getAttribute("aria-pressed"), text(button.querySelector(".count"))]), + taskRows: all("#main .task-row").map((row) => [row.dataset.task, row.classList.contains("open-work")]), + columns: all("#main .task-column").map((column) => [column.dataset.column, all(`#main .kanban-cell[data-column="${column.dataset.column}"] .task-card`).map((card) => card.dataset.task)]), + matrix: [all("#main table.matrix thead th").length, all("#main table.matrix tbody tr").length, all("#main table.matrix td .letter").map(text).join("")], + flows: all("#main .flow").map((flow) => flow.dataset.flow), + flowEdges: all("#main svg.chart path.flow").map((path) => path.dataset.side), + openWork: all("#main .open-work").length, + panel: all("#drawer, .drawer, #main aside, #main .panel, #main .graph-body").length, + nodeChips: all("#main .space-list, #main .chip[data-node]").length, + wide: document.documentElement.scrollWidth > window.innerWidth + 1, + tall: document.documentElement.scrollHeight > window.innerHeight, + }; +})()""".replace("@HELPERS@", HELPERS) +INBOX_CHIP = """(async () => {@HELPERS@ + const chip = (id) => document.querySelector(`#main [aria-label="Task filters"] button[data-filter="${id}"]`); + chip("operator").click(); + await until(() => location.hash === "#tasks/operator" && document.querySelector("#main .inbox-list"), 4000); + const inbox = {hash: location.hash, items: all("#main .inbox-list > li").length, counted: Number(text(chip("operator").querySelector(".count"))), pressed: chip("operator").getAttribute("aria-pressed"), current: all("#tabs button[aria-current=page]").map(name)}; + chip("grant").click(); + await until(() => location.hash.startsWith("#tasks/"), 4000); + await sleep(300); + return {inbox, back: {hash: location.hash, rows: all("#main .task-row").map((row) => [row.dataset.task, text(row.querySelector(".pill"))])}}; +})()""".replace("@HELPERS@", HELPERS) +ACTIONS = """(async () => {@HELPERS@ + const press = async (key) => { + document.dispatchEvent(new KeyboardEvent("keydown", {key, bubbles: true})); + await sleep(300); + return location.hash; + }; + const found = {keys: [await press("3"), await press("4"), await press("5"), await press("1"), await press("2")]}; + document.getElementById("settings-open").click(); + await sleep(300); + found.ambience = all(".sheet-box form > section:first-child button").map((button) => button.id); + found.sections = all(".sheet-box form.settings > section > h3").map(text); + found.radioFields = all('.sheet-box [aria-label="Squelch"], .sheet-box [aria-label="Classes"], .sheet-box [aria-label="Speakers"], .sheet-box [aria-label="Mode"], .sheet-box .sound-row, .sheet-box .stream-row').length; + found.settingsUnlabelled = all(".sheet-box svg.bi").map((svg) => svg.parentElement).filter((owner) => !text(owner) && !(owner.getAttribute("title") && owner.getAttribute("aria-label"))).length; + document.querySelector(".sheet-head button").click(); + document.getElementById("palette-open").click(); + await sleep(300); + found.palette = all(".palette-list li > span:first-child").map(text); + document.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await sleep(200); + document.querySelector('#main [aria-label="Categories"] button:nth-child(2)').click(); + await sleep(900); + document.querySelector('#main button.linkish[title^="Open "]').click(); + 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")]; + return found; +})()""".replace("@HELPERS@", HELPERS) +POPUPS = """ + const dialog = document.getElementById("popup"); + const box = dialog.querySelector(".popup-box"); + const line = dialog.querySelector(".leader line"); + const click = (target) => target.dispatchEvent(new MouseEvent("click", {bubbles: true, cancelable: true})); + const tint = document.createElement("i"); + tint.style.color = "var(--alarm)"; + document.body.append(tint); + const red = getComputedStyle(tint).color; + tint.remove(); + const tall = () => document.documentElement.scrollHeight > innerHeight; + const look = (node) => ({picked: node.classList.contains("picked"), size: Math.round(node.querySelector("circle").getBoundingClientRect().width), red: getComputedStyle(node.querySelector("circle")).fill === red}); + const opened = () => { + const rect = box.getBoundingClientRect(); + const ends = line.getAttribute("display") === "none" ? null : ["x1", "y1", "x2", "y2"].map((key) => Number(line.getAttribute(key))); + return { + open: dialog.open, fade: [dialog.classList.contains("fade"), getComputedStyle(dialog).animationName], title: text(box.querySelector(".panel-title")), opacity: Number(getComputedStyle(box).opacity), line: ends, + onBox: Boolean(ends) && (Math.abs(ends[2] - rect.left) < 1 || Math.abs(ends[2] - rect.right) < 1 || Math.abs(ends[3] - rect.top) < 1 || Math.abs(ends[3] - rect.bottom) < 1), + inside: rect.left >= 0 && rect.top >= 0 && rect.right <= innerWidth && rect.bottom <= innerHeight, + tall: tall(), wide: document.documentElement.scrollWidth > innerWidth + 1, panel: all("#drawer, .drawer, #main aside, #main .panel, #main .graph-body").length, + }; + }; + const away = async (pick) => { + const rect = box.getBoundingClientRect(); + const [, x, y] = [[rect.left, rect.left / 2, innerHeight / 2], [innerWidth - rect.right, (rect.right + innerWidth) / 2, innerHeight / 2], [rect.top, innerWidth / 2, rect.top / 2], [innerHeight - rect.bottom, innerWidth / 2, (rect.bottom + innerHeight) / 2]].sort((a, b) => b[0] - a[0])[0]; + const outside = (await until(() => document.elementFromPoint(x, y) === dialog && dialog, 3000)) || document.elementFromPoint(x, y); + click(outside); + await sleep(250); + return {...look(pick()), open: dialog.open, outside: outside === dialog}; + }; +""" +POPUP_ORBIT = """(async () => {@HELPERS@@POPUPS@ + const pick = () => document.querySelector('#main svg .node[data-pick="s2"]'); + if (!(await until(pick, 8000))) { + return {error: text(document.getElementById("main"))}; + } + const before = look(pick()); + const flat = !tall(); + click(pick()); + 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 gone = await away(pick); + click(pick()); + await sleep(300); + const again = dialog.open; + (document.activeElement || document.body).dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await sleep(250); + const escaped = {...look(pick()), open: dialog.open, again}; + click(pick()); + await sleep(500); + return {before, flat, shown, gone, escaped, last: dialog.open}; +})()""".replace("@HELPERS@", HELPERS).replace("@POPUPS@", POPUPS) +POPUP_ARTIFACT = """(async () => {@HELPERS@@POPUPS@ + const first = await until(() => document.querySelector('#main svg .node[data-pick^="branch:"]'), 8000); + if (!first) { + return {error: text(document.getElementById("main"))}; + } + const id = first.dataset.pick; + const pick = () => all("#main svg .node[data-pick]").find((node) => node.dataset.pick === id); + const before = look(pick()); + const flat = !tall(); + click(pick()); + await sleep(400); + const shown = {...opened(), ...look(pick()), label: first.getAttribute("aria-label").split(",")[0]}; + const gone = await away(pick); + click(pick()); + await sleep(400); + return {before, flat, shown, gone, last: dialog.open}; +})()""".replace("@HELPERS@", HELPERS).replace("@POPUPS@", POPUPS) +PICK_3D = """(async () => {@HELPERS@ + const field = await until(() => document.querySelector('#main input[aria-label="Find a node"]'), 8000); + const ready = await until(() => document.querySelector("#main .graph3d canvas") && !text(document.querySelector("#main .space-note")).startsWith("Loading"), 8000); + if (!field || !ready) { + return {error: text(document.querySelector("#main .graph"))}; + } + const type = async (value) => { + field.value = value; + field.dispatchEvent(new Event("input", {bubbles: true})); + await sleep(150); + return all("#main .hits .chip").map((chip) => [chip.dataset.hit, text(chip)]); + }; + const tree = await (await fetch("/api/tree", {cache: "no-store"})).json(); + const found = {empty: await type(""), twins: tree.repos.flatMap((repo) => repo.branches).filter((branch) => branch.name === "main").length, twin: await type("main"), hits: await type("@QUERY@")}; + found.flat = document.documentElement.scrollHeight <= innerHeight; + const chip = all("#main .hits .chip").find((node) => node.dataset.hit.startsWith("@PREFIX@")); + if (!chip) { + return {error: found}; + } + chip.click(); + await sleep(600); + const dialog = document.getElementById("popup"); + const line = dialog.querySelector(".leader line"); + const host = () => document.querySelector("#main .graph3d"); + found.opened = { + open: dialog.open, title: text(dialog.querySelector(".popup-box .panel-title")), label: text(chip), hit: chip.dataset.hit, picked: host().dataset.picked || null, + line: line.getAttribute("display") !== "none", lists: all("#main .space-list, #main .chip[data-node]").length, flat: document.documentElement.scrollHeight <= innerHeight, + }; + dialog.dispatchEvent(new MouseEvent("click", {bubbles: true})); + await sleep(300); + found.closed = {open: dialog.open, picked: host().dataset.picked || null}; + chip.click(); + await sleep(600); + return found; +})()""".replace("@HELPERS@", HELPERS) +RULES_OVERLAP = """(async () => {@HELPERS@@CLASHES@ + const open = document.querySelector(".sheet-head button"); + if (open) { + open.click(); + } + const rules = await until(() => document.querySelector("#main .rule-form"), 8000); + const kind = rules.querySelector("select"); + const found = {}; + for (const value of ["decision", "review", "ask"]) { + kind.value = value; + kind.dispatchEvent(new Event("change", {bubbles: true})); + await sleep(150); + found[value] = {...clashes(rules), labels: all("label", rules).filter(shown).map(words)}; + } + return found; +})()""".replace("@HELPERS@", HELPERS).replace("@CLASHES@", OVERLAP) +SETTINGS_OVERLAP = """(async () => {@HELPERS@@CLASHES@ + document.getElementById("settings-open").click(); + const settings = await until(() => document.querySelector(".sheet-box form.settings"), 8000); + const theme = all("select", settings).find((select) => [...select.options].some((option) => option.value === "custom")); + theme.value = "custom"; + theme.dispatchEvent(new Event("change", {bubbles: true})); + await sleep(250); + const place = all("section", settings).find((section) => text(section.querySelector("h3")) === "Location"); + place.scrollIntoView({block: "start"}); + return clashes(settings); +})()""".replace("@HELPERS@", HELPERS).replace("@CLASHES@", OVERLAP) +PRESENCE_HELPERS = """ + const states = () => all("#main .presence:not(label)").map((node) => node.dataset.state).sort(); + const statusMenu = () => { + const menu = all('#main [role="toolbar"] details.menu').find((node) => name(node.querySelector("summary")) === "Status"); + menu.open = true; + return menu; + }; + const looks = (menu) => all("input[data-look]", menu).map((input) => [input.dataset.look, input.checked]); + const graph3d = async (faces) => { + const box = await until(() => { + const found = document.querySelector("#main .graph3d"); + return found && found.dataset.faces !== undefined && (faces === null || found.dataset.faces === faces) ? found : null; + }, 15000); + return box ? [Number(box.dataset.faces), Number(box.dataset.badges)] : null; + }; +""" +PRESENCE_WALK = """(async () => {@HELPERS@@PRESENCE@ + const views = {}; + for (const view of ["orbit", "chord", "swimlane", "tree", "hierarchy"]) { + location.hash = `#agents/${view}`; + await screenShown(6000); + await until(() => all("#main .presence:not(label)").length, 6000); + views[view] = states(); + } + location.hash = "#agents/orbit"; + await screenShown(6000); + const node = await until(() => document.querySelector('#main svg .node[data-pick="s1"]'), 6000); + const motion = getComputedStyle(node.querySelector(".presence .glyph")).animationName; + node.dispatchEvent(new MouseEvent("click", {bubbles: true})); + const mark = await until(() => document.querySelector("#popup .presence"), 4000); + const profile = mark ? [mark.dataset.state, text(mark), mark.getAttribute("aria-label")] : null; + (document.activeElement || document.body).dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await sleep(300); + location.hash = "#agents/3d"; + const shown = await graph3d(null); + const menu = statusMenu(); + const before = looks(menu); + menu.querySelector('input[data-look="working"]').click(); + menu.querySelector('input[data-look="faces"]').click(); + const hidden = await graph3d("0"); + location.hash = "#agents/orbit"; + await screenShown(6000); + await until(() => document.querySelector('#main svg .node[data-pick="s2"]'), 6000); + return {views, motion, profile, shown, before, hidden, orbit: states(), @FITS@}; +})()""".replace("@HELPERS@", HELPERS).replace("@PRESENCE@", PRESENCE_HELPERS).replace("@FITS@", FITS) +PRESENCE_READ = """(async () => {@HELPERS@@PRESENCE@ + await until(() => document.querySelector('#main svg .node[data-pick="s2"]'), 8000); + await sleep(300); + const menu = statusMenu(); + const kept = {boxes: looks(menu), orbit: states()}; + menu.querySelector('input[data-look="working"]').click(); + menu.querySelector('input[data-look="faces"]').click(); + await sleep(300); + const back = states(); + location.hash = "#agents/3d"; + return {...kept, back, restored: await graph3d(null)}; +})()""".replace("@HELPERS@", HELPERS).replace("@PRESENCE@", PRESENCE_HELPERS) +CAMERA = """(async () => {@HELPERS@ + const ready = await until(() => window.e2eGraphs && document.querySelector("#main .graph3d canvas") && !text(document.querySelector("#main .space-note")).startsWith("Loading"), 15000); + if (!ready) { + return {error: text(document.querySelector("#main .graph"))}; + } + const graph = window.e2eGraphs[window.e2eGraphs.length - 1]; + const position = () => { + const at = graph.cameraPosition(); + return [at.x, at.y, at.z]; + }; + await sleep(5500); + let [fed, stops] = [0, 0]; + const stopped = graph.onEngineStop(); + graph.onEngineStop(() => { + stops += 1; + stopped(); + }); + const feed = graph.graphData; + graph.graphData = function (...args) { + fed += args.length; + return feed.apply(graph, args); + }; + const built = position(); + const canvas = document.querySelector("#main .graph3d canvas"); + const rect = canvas.getBoundingClientRect(); + for (let turn = 0; turn < 4; turn += 1) { + canvas.dispatchEvent(new WheelEvent("wheel", {deltaY: -120, clientX: rect.left + rect.width / 2, clientY: rect.top + rect.height / 2, bubbles: true, cancelable: true})); + await sleep(60); + } + await sleep(900); + const moved = position(); + const refreshes = []; + for (let round = 0; round < 2; round += 1) { + const [feeds, ends] = [fed, stops]; + document.dispatchEvent(new Event("visibilitychange")); + const rebuilt = Boolean(await until(() => fed > feeds, 8000)); + const settled = Boolean(await until(() => stops > ends, 10000)); + await sleep(900); + refreshes.push({rebuilt, settled, camera: position()}); + } + all("#main button").find((button) => name(button) === "Reset view").click(); + await sleep(1500); + return {hooked: typeof stopped === "function", built, moved, refreshes, reset: position()}; +})()""".replace("@HELPERS@", HELPERS) diff --git a/tests/e2e/radio_layout_focus_probes.py b/tests/e2e/radio_layout_focus_probes.py new file mode 100644 index 0000000..fc50115 --- /dev/null +++ b/tests/e2e/radio_layout_focus_probes.py @@ -0,0 +1,308 @@ +from __future__ import annotations + +POP = """(async () => {@HELPERS@@PROBES@ + await ViewStore.update("home.pins", () => @PINS@); + location.hash = "@VIEW@"; + await screenShown(8000); + if (@SPOT@) { + await openSpot(); + } else { + await closeSpot(); + } + await settle(); + await sleep(500); + const outside = (layer) => { + const edge = box(layer); + const clips = [["viewport", {top: 0, bottom: innerHeight, left: 0, right: innerWidth}]]; + for (let node = layer.parentElement; node && node !== document.documentElement; node = node.parentElement) { + const look = getComputedStyle(node); + if (look.overflowX !== "visible" || look.overflowY !== "visible") { + clips.push([`${node.tagName}.${node.getAttribute("class")}`, box(node)]); + } + } + return clips.filter(([, clip]) => edge.top < clip.top - 1 || edge.bottom > clip.bottom + 1 || edge.left < clip.left - 1 || edge.right > clip.right + 1) + .map(([name, clip]) => `${name} [${Math.round(clip.top)},${Math.round(clip.bottom)}] vs [${Math.round(edge.top)},${Math.round(edge.bottom)}]`); + }; + const out = []; + for (const selector of @ROOTS@) { + const root = document.querySelector(selector); + if (!root || !(await until(() => root.querySelectorAll(".station").length === 3, 8000))) { + out.push({selector, error: "no stations"}); + continue; + } + const fold = root.querySelector("details.radio-station"); + const summary = fold.querySelector("summary"); + const layer = fold.querySelector(".station-body"); + fold.scrollIntoView({block: "center"}); + await sleep(200); + summary.focus(); + summary.click(); + await sleep(300); + const whole = all(".station", layer).filter((row) => box(row).top >= box(layer).top - 1 && box(row).bottom <= box(layer).bottom + 1).length; + const opened = {open: fold.open, side: fold.dataset.side, height: Math.round(box(layer).height), outside: outside(layer), whole}; + layer.querySelector(".station button").focus(); + document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await sleep(200); + const escape = [fold.open, document.activeElement === summary]; + summary.click(); + await sleep(300); + const again = {open: fold.open, outside: outside(layer)}; + press(document.getElementById("main")); + await sleep(200); + out.push({selector, opened, escape, again, click: [fold.open, document.activeElement === summary, document.activeElement === document.body]}); + } + return out; +})()""" +FOCUS = """(async () => {@HELPERS@@PROBES@ + await ViewStore.update("home.pins", () => []); + location.hash = "#agents/orbit"; + await screenShown(8000); + const spot = await openSpot(); + await until(() => spot.querySelectorAll(".station").length === 3 && spot.querySelector(".radio-row"), 8000); + await settle(); + await sleep(300); + const fold = spot.querySelector("details.radio-station"); + const night = await until(() => all("details.menu").find((menu) => menu.querySelector("summary").getAttribute("aria-label") === "Day/Night"), 8000); + const label = (node) => (node ? `${node.tagName}.${node.getAttribute("class")}[${node.getAttribute("aria-label") || text(node).slice(0, 24)}]` : "null"); + const tab = () => spot.querySelector('.radio-tabs [role="tab"]:not([aria-selected="true"])'); + const cases = {}; + const run = async (key, menu, target) => { + press(menu.querySelector("summary")); + await sleep(250); + const opened = menu.open; + const node = target(); + press(node); + await sleep(400); + const active = document.activeElement; + cases[key] = {opened, closed: !menu.open, active: label(active), summary: Boolean(active && active.matches("summary")), history: Boolean(active && active.closest(".radio-logbox")), body: active === document.body}; + menu.open = false; + await sleep(150); + }; + await run("night-tab", night, tab); + await run("fold-tab", fold, tab); + await run("night-main", night, () => document.getElementById("main")); + await run("fold-main", fold, () => document.getElementById("main")); + press(fold.querySelector("summary")); + await sleep(250); + fold.querySelector(".station button").focus(); + document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await sleep(200); + cases.escape = {closed: !fold.open, toggle: document.activeElement === fold.querySelector("summary")}; + return cases; +})()""" +ROWS = """(async () => {@HELPERS@@PROBES@@LOADS@ + await ViewStore.update("home.pins", () => []); + location.hash = "#agents/orbit"; + await screenShown(8000); + const spot = await openSpot(); + await until(() => spot.querySelectorAll(".radio-row").length > 2, 8000); + await settle(); + await sleep(300); + const rows = () => spot.querySelectorAll(".radio-row").length; + const deliver = async () => { + const before = rows(); + await fetch("/api/voice/@LIVE@", {cache: "no-store"}); + window.dispatchEvent(new Event("focus")); + const done = await until(() => rows() > before, 20000); + await sleep(300); + return Boolean(done); + }; + const row = spot.querySelectorAll(".radio-row")[1]; + const button = row.querySelector(".radio-pick"); + const held = () => { + const active = document.activeElement; + const owner = active ? active.closest(".radio-row") : null; + return {same: active === button, key: owner ? owner.dataset.key : null, pick: Boolean(active && active.matches(".radio-pick")), body: active === document.body}; + }; + button.focus(); + const start = {...held(), want: row.dataset.key}; + const fresh = {...held(), delivered: await deliver()}; + const real = Date.now; + Date.now = () => real.call(Date) + 60000; + window.dispatchEvent(new Event("focus")); + const tick = {...held(), ticked: await loaded(1, 20000)}; + Date.now = real; + const tab = spot.querySelector('.radio-tabs [role="tab"][aria-selected="true"]'); + tab.focus(); + let focusins = 0; + document.addEventListener("focusin", () => { + focusins += 1; + }, true); + const delivered = [await deliver(), await deliver(), await deliver()]; + return {start, fresh, tick, tabs: {delivered, focusins, same: document.activeElement === tab, tab: document.activeElement.getAttribute("data-tab")}}; +})()""" +KEYS = """(async () => {@HELPERS@@PROBES@ + await ViewStore.update("home.pins", () => []); + location.hash = "#agents/orbit"; + await screenShown(8000); + const spot = await openSpot(); + spot.querySelector('.radio-tabs [role="tab"][data-tab="all"]').click(); + const dups = () => all(".radio-row", spot).filter((node) => text(node.querySelector(".radio-line")).startsWith("dup ")); + await until(() => dups().length === 2, 8000); + await settle(); + await sleep(300); + const rows = () => spot.querySelectorAll(".radio-row").length; + const deliver = async () => { + const before = rows(); + await fetch("/api/voice/@LIVE@", {cache: "no-store"}); + window.dispatchEvent(new Event("focus")); + const done = await until(() => rows() > before, 20000); + await sleep(300); + return Boolean(done); + }; + const line = (node) => (node && node.closest(".radio-row") ? text(node.closest(".radio-row").querySelector(".radio-line")) : null); + const out = {keys: dups().map((node) => node.dataset.key)}; + for (const word of @DUPS@) { + const button = dups().find((node) => text(node.querySelector(".radio-line")) === word).querySelector(".radio-pick"); + button.focus(); + const delivered = await deliver(); + const active = document.activeElement; + const result = {delivered, same: active === button, line: line(active), popup: null}; + if (active && active.matches(".radio-pick")) { + active.click(); + result.popup = await until(() => (popup().open && popup().querySelector(".radio-full") ? popup().querySelector(".radio-full").textContent : null), 4000); + (document.activeElement || document.body).dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await until(() => !popup().open, 2000); + } + out[word] = result; + } + const victim = all(".radio-row", spot).find((node) => node.dataset.class === "newsletter"); + victim.querySelector(".radio-pick").focus(); + const chip = spot.querySelector('.chip-select[data-chip="class"] select'); + chip.value = "call"; + chip.dispatchEvent(new Event("change", {bubbles: true})); + await sleep(500); + const near = document.activeElement; + out.filtered = {gone: !victim.isConnected, pick: Boolean(near && near.matches(".radio-pick")), class: near && near.closest(".radio-row") ? near.closest(".radio-row").dataset.class : null}; + const search = spot.querySelector('.radio-logbox input[type="search"]'); + search.value = "no radio row says this"; + search.dispatchEvent(new Event("input", {bubbles: true})); + await sleep(500); + out.emptied = {gone: !spot.querySelector(".radio-row"), list: document.activeElement === spot.querySelector("ul.radio-log")}; + search.value = ""; + search.dispatchEvent(new Event("input", {bubbles: true})); + chip.value = ""; + chip.dispatchEvent(new Event("change", {bubbles: true})); + await sleep(300); + return out; +})()""" +BANNER = """(async () => {@HELPERS@@PROBES@@LOADS@ + await ViewStore.update("home.pins", () => []); + location.hash = "#agents/orbit"; + await screenShown(8000); + const banner = document.getElementById("mayday"); + await until(() => !banner.hidden && banner.querySelector("button"), 8000); + await settle(); + await sleep(300); + const records = []; + new MutationObserver((list) => records.push(...list)).observe(banner, {childList: true, subtree: true, characterData: true, attributes: true}); + const cancel = banner.querySelector("button"); + cancel.focus(); + const polled = await loaded(2, 30000); + const steady = {polled, mutations: records.length, focus: document.activeElement === cancel, body: document.activeElement === document.body}; + records.length = 0; + await fetch("/api/voice/@SILENCE@", {cache: "no-store"}); + const again = await loaded(3, 45000); + const added = records.filter((record) => record.type === "childList" && record.addedNodes.length > 0).length; + return {steady, changed: {polled: again, text: text(banner.querySelector(".text")), added, shown: !banner.hidden, cancel: Boolean(banner.querySelector("button"))}}; +})()""" +COMPOSE_HOME = """(async () => {@HELPERS@@PROBES@ + const bodies = []; + const send = window.fetch.bind(window); + window.fetch = (path, init) => { + if (String(path) === "/api/messages") { + bodies.push(JSON.parse(init.body)); + } + return send(path, init); + }; + window.confirm = () => true; + const spot = await openSpot(); + const spotText = spot.querySelector("form.composer textarea"); + spotText.value = "draft kept in the spot"; + spotText.dispatchEvent(new Event("input", {bubbles: true})); + await ViewStore.update("home.pins", () => [{kind: "panel", id: "radio", w: 12, h: 7}, {kind: "panel", id: "radio-speak", w: 6, h: 5}, {kind: "panel", id: "radio-log", w: 6, h: 5}]); + location.hash = "#home"; + await screenShown(8000); + await until(() => tile("radio-speak") && tile("radio-log") && tile("radio") && tile("radio-log").querySelector(".radio-row"), 10000); + await sleep(400); + const homeSpeak = tile("radio-speak"); + const form = (root) => root.querySelector("form.composer"); + const area = (root) => form(root).querySelector("textarea"); + const record = (root) => all("button", form(root)).find((button) => button.hasAttribute("aria-pressed")); + const note = (root) => { + const audio = form(root).querySelector(".voice-note audio"); + return audio ? audio.getAttribute("src").replace("/api/voice/", "").replace(".wav", "") : null; + }; + const drafts = [area(spot).value, area(homeSpeak).value, area(tile("radio")).value]; + record(spot).click(); + await sleep(1200); + const first = record(spot).getAttribute("aria-pressed"); + record(homeSpeak).click(); + const handed = await until(() => (record(homeSpeak).getAttribute("aria-pressed") === "true" ? [record(spot).getAttribute("aria-pressed"), "true"] : null), 5000); + const spotHeard = await until(() => (note(spot) && area(spot).value.includes("hello from the mic") ? area(spot).value : null), 30000); + const homeBefore = area(homeSpeak).value; + await sleep(800); + record(homeSpeak).click(); + const homeHeard = await until(() => (note(homeSpeak) && area(homeSpeak).value.includes("hello from the mic") ? area(homeSpeak).value : null), 30000); + const notes = [note(spot), note(homeSpeak)]; + const sendFrom = async (root, to, words, attach) => { + const [channel, recipient] = all("select", form(root)); + channel.value = "post"; + channel.dispatchEvent(new Event("change", {bubbles: true})); + await until(() => [...recipient.options].some((option) => option.value === to), 8000); + recipient.value = to; + area(root).value = words; + area(root).dispatchEvent(new Event("input", {bubbles: true})); + const box = form(root).querySelector('.voice-note input[type="checkbox"]'); + if (box) { + box.checked = attach; + } + const shownBefore = new Set(all("#toasts .toast")); + form(root).querySelector('button[type="submit"]').click(); + return until(() => all("#toasts .toast").filter((node) => !shownBefore.has(node)).map(text).find((entry) => entry.startsWith("Post to")), 20000); + }; + const spotSent = await sendFrom(spot, "Stage", "plain text from the spot", false); + const homeAttach = Boolean(form(homeSpeak).querySelector('.voice-note input[type="checkbox"]')); + const homeSent = await sendFrom(homeSpeak, "Docs", "voice from the Home tile", true); + await closeSpot(); + document.getElementById("toasts").replaceChildren(); + return {drafts, first, handed, spotHeard, homeBefore, homeHeard, notes, spotSent, homeAttach, homeSent, bodies: bodies.map((body) => [body.to, body.text, body.voice])}; +})()""" +REPLY_HOME = """(async () => {@HELPERS@@PROBES@ + const spotOpen = () => document.getElementById("radio-open").getAttribute("aria-expanded"); + const reply = async (root) => { + const row = longRow(root); + row.scrollIntoView({block: "center"}); + await sleep(200); + await openRow(row); + all(".radio-actions button", popup()).find((button) => text(button) === "Reply").click(); + await sleep(300); + }; + await reply(tile("radio-log")); + const fromLog = {spot: spotOpen(), popup: popup().open, speak: pick(tile("radio-speak")), whole: pick(tile("radio"))}; + await reply(tile("radio")); + const fromWhole = {spot: spotOpen(), whole: pick(tile("radio"))}; + const sendFrom = async (root, words) => { + const area = root.querySelector("form.composer textarea"); + area.value = words; + area.dispatchEvent(new Event("input", {bubbles: true})); + const shownBefore = new Set(all("#toasts .toast")); + root.querySelector('form.composer button[type="submit"]').click(); + return until(() => all("#toasts .toast").filter((node) => !shownBefore.has(node)).map(text).find((entry) => entry.startsWith("Post to")), 20000); + }; + const sent = await sendFrom(tile("radio"), "reply from the Home radio"); + const questions = []; + window.confirm = (question) => { + questions.push(question); + return true; + }; + const clear = all(".spot-head button", tile("radio")).find((button) => button.getAttribute("aria-label") === "Cancel mayday"); + const enabled = clear ? !clear.disabled : null; + const shownBefore = new Set(all("#toasts .toast")); + if (clear) { + clear.click(); + } + const lifted = await until(() => all("#toasts .toast").filter((node) => !shownBefore.has(node)).map(text).find((entry) => entry.startsWith("Cancel mayday")), 15000); + document.getElementById("toasts").replaceChildren(); + return {fromLog, fromWhole, sent, enabled, questions, lifted, spot: spotOpen()}; +})()""" diff --git a/tests/e2e/radio_layout_kit.py b/tests/e2e/radio_layout_kit.py new file mode 100644 index 0000000..a0f9774 --- /dev/null +++ b/tests/e2e/radio_layout_kit.py @@ -0,0 +1,209 @@ +from __future__ import annotations + +import json +import os +import time +from pathlib import Path +from unittest import mock + +import hub_e2e_kit as base +from hub_case import HubCase +from kvb_orchestrator import receipts +from kvb_orchestrator.presence import SNAPSHOT +from kvb_orchestrator.view import RADIO_WINDOW + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/radio-layout-shots")) +LIVE = "f000000000000001" +SILENCE = "f000000000000002" +NEW_ALARM = "disk full again: the cleanup freed too little" +NAMES = ["Skills", "Stage", "Docs", "Atlas", "Beacon", "Comet", "Delta", "Echo", "Falcon", "Harbor"] +SESSIONS = {f"s{index}": name for index, name in enumerate(NAMES, start=1)} +LONG = "Disk at ninety percent on the build host: " + "the gate keeps the swarm waiting while the cache, the images and the logs keep growing; " * 4 +FILLERS = 24 +WIDTHS = (*base.WIDTHS, (960, 800)) +NARROW = (390, 960) +STAGE_SHARE = 0.12 +BANDS = ((1280, 720), (976, 744), (768, 976)) +SHORT = ((800, 600), (1024, 600), (1280, 600), (1366, 657)) +ABOVE = ((800, 976), (960, 976), (976, 744), (1024, 744), (1366, 720)) +LAPTOPS = ((1280, 720), (1366, 768), (1440, 900), (1536, 864), (1920, 1080), (1024, 768), (1680, 1050), (820, 1180), (768, 1024), *ABOVE, *SHORT) +DUPS = ("dup first", "dup second") +VIEWS = ("#stream", "#agents/orbit") +STATES = ("idle", "stations", "voice", "speech", "mayday", "mayday-long") +ALARMS = { + "mayday": "disk full", + "mayday-long": "disk full on the build host: every agent pauses its writing steps until the operator frees space under /var/lib/docker and confirms the cleanup " + "on the radio; the gate queue stays frozen, the deploy of the production worktree waits, and every held test run restarts after the clear of this mayday", +} +BANNER_MAX = 48 +FOCUS_SIZES = ((1366, 768), (390, 844)) +MAIN_SHARE = 0.54 +PLAY_MIN = {"BUTTON": (24, 24), "AUDIO": (200, 30)} +POPOVER_SIZES = ((1366, 768), (1280, 720), (390, 844)) +HOME_RADIO = [{"kind": "panel", "id": "radio-device", "w": 6, "h": 6}, {"kind": "panel", "id": "radio", "w": 12, "h": 7}] +STREAMS = [{"name": f"Station {index}", "url": f"https://radio.example/{index}.mp3", "from": "00:00", "to": "24:00", "days": list(range(7)), "on": False, "via": []} for index in (1, 2, 3)] +PARTS = ["radio", "radio-device", "radio-speak", "radio-log"] +DEFAULTS = {"radio": [12, 7], "radio-device": [6, 6], "radio-speak": [6, 5], "radio-log": [6, 5]} +SIZES = {"radio": [12, 9], "radio-device": [5, 7], "radio-speak": [7, 6], "radio-log": [8, 6]} +LISTED = {"radio-log"} +SCROLLER = {"radio": "radio-log", "radio-device": None, "radio-speak": None, "radio-log": "radio-log"} +PROBES = """ + const transitions = window.e2eTransitions || (window.e2eTransitions = []); + if (document.startViewTransition && !transitions.wrapped) { + const start = document.startViewTransition.bind(document); + document.startViewTransition = (update) => { + const run = start(update); + transitions.push(run); + return run; + }; + transitions.wrapped = true; + } + const settle = () => Promise.all(transitions.map((run) => run.finished.catch(() => null))); + const press = (node) => { + node.dispatchEvent(new MouseEvent("mousedown", {bubbles: true, cancelable: true, view: window})); + if (node.matches('button, input, select, textarea, summary, a[href], [tabindex]')) { + node.focus(); + } else if (document.activeElement) { + document.activeElement.blur(); + } + node.dispatchEvent(new MouseEvent("mouseup", {bubbles: true, cancelable: true, view: window})); + node.click(); + }; + const box = (node) => node.getBoundingClientRect(); + const ownStar = (owner) => all(".star", owner).find((node) => node.closest("[data-panel], [data-item]") === owner) || null; + const openSpot = async () => { + await until(() => typeof Nav === "object" && document.getElementById("radio-spot"), 8000); + const toggle = document.getElementById("radio-open"); + if (toggle.getAttribute("aria-expanded") !== "true") { + toggle.click(); + await sleep(300); + } + return document.getElementById("radio-spot"); + }; + const closeSpot = async () => { + const toggle = document.getElementById("radio-open"); + if (toggle.getAttribute("aria-expanded") === "true") { + toggle.click(); + await sleep(200); + } + }; + const longRow = (root) => all(".radio-row", root).find((item) => text(item.querySelector(".radio-line")).startsWith("Disk at ninety")); + const popup = () => document.getElementById("popup"); + const openRow = async (row) => { + row.querySelector(".radio-pick").click(); + return until(() => popup().open && popup().querySelector(".radio-full") ? popup() : null, 4000); + }; + const shown = (node) => node.getClientRects().length > 0; + const scrolls = (node) => { + const look = getComputedStyle(node); + return (node.scrollHeight > node.clientHeight + 1 && ["auto", "scroll"].includes(look.overflowY)) || (node.scrollWidth > node.clientWidth + 1 && ["auto", "scroll"].includes(look.overflowX)); + }; + const scrollersIn = (root) => [root, ...all("*", root)].filter((node) => node instanceof HTMLElement && node.tagName !== "SELECT" && node.tagName !== "TEXTAREA" && shown(node) && scrolls(node)).map((node) => [...node.classList].at(-1) || node.tagName); + const tile = (id) => document.querySelector(`#main .home-tile[data-pin="panel:${id}"]`); + const pick = (root) => { + const [channel, recipient] = all("select", root.querySelector("form.composer")); + return {channel: channel.value, recipient: recipient.value, toShown: !recipient.closest("label").hidden, focused: document.activeElement === root.querySelector("form.composer textarea")}; + }; +""" +LOADS = """ + const loads = {count: 0}; + const send = window.fetch.bind(window); + window.fetch = async (path, init) => { + const response = await send(path, init); + if (String(path).startsWith("/api/state")) { + const json = response.json.bind(response); + response.json = () => json().then((value) => { + loads.count += 1; + return value; + }); + } + return response; + }; + const loaded = async (more, ms) => { + const goal = loads.count + more; + const done = await until(() => loads.count >= goal, ms); + await sleep(300); + return Boolean(done); + }; +""" + + +def columns(width: int, height: int) -> bool: + return any(width >= low and height >= tall for low, tall in BANDS) + + +def probe(template: str) -> str: + return (template.replace("@HELPERS@", base.HELPERS).replace("@PROBES@", PROBES).replace("@LOADS@", LOADS).replace("@SPEAKING@", base.SPEAKING).replace("@PARTS@", json.dumps(PARTS)) + .replace("@SIZES@", json.dumps(SIZES)).replace("@LIVE@", LIVE).replace("@SILENCE@", SILENCE).replace("@DUPS@", json.dumps(DUPS)).replace("@MAIN@", str(MAIN_SHARE))) + + +class RadioLayoutCase(HubCase): + drive = base.OrchestratorE2ECase.drive + beside = base.OrchestratorE2ECase.beside + authenticator = base.OrchestratorE2ECase.authenticator + speaks = base.OrchestratorE2ECase.speaks + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + now = time.time() + self.claim("s1", "Skills session") + rows = [{"ts": now - 1200 + index * 30, "from": NAMES[index % len(NAMES)], "to": [], "text": f"status line {index}: build {index} green", "class": "newsletter", "v": 2} for index in range(FILLERS)] + self.call = now - 400 + self.long = now - 300 + rows += [ + {"ts": self.call, "from": "Skills", "to": ["Stage", "Docs"], "text": "gate red on main", "class": "call", "v": 2}, + {"ts": self.call + 5, "from": "Stage", "to": ["Skills"], "text": "gate red on main", "class": "receipt", "v": 2, "call": self.call}, + {"ts": self.long, "from": "Stage", "to": [], "text": LONG, "class": "broadcast", "v": 2}, + ] + self.write_council({"news.jsonl": self.jsonl(rows)}) + for sid in SESSIONS: + self.mark(sid, now - 100) + self.sessions() + self.beside(self.sessions) + self.httpd.hub.receipt_reads.times[("s5", self.long)] = self.long + 40 + self.sight() + self.live = 0 + hub = self.httpd.hub + heard = hub.voice_notes.get + + def get(note_id: str) -> dict: + if note_id == SILENCE: + self.silence(NEW_ALARM) + return {"id": note_id, "status": "done", "text": "", "error": "", "seconds": None, "created_ts": None} + if note_id != LIVE: + return heard(note_id) + self.live += 1 + row = {"ts": time.time(), "from": "Docs", "to": [], "text": f"live row {self.live} for Home", "class": "broadcast", "v": 2} + with (self.council / "news.jsonl").open("a", encoding="utf-8") as handle: + handle.write(self.jsonl([row])) + return {"id": note_id, "status": "done", "text": "", "error": "", "seconds": None, "created_ts": None} + + patch = mock.patch.object(hub.voice_notes, "get", get) + patch.start() + self.addCleanup(patch.stop) + + def sessions(self) -> None: + payload = {"written": time.time(), "sessions": {sid: {"name": name, "running": True} for sid, name in SESSIONS.items()}} + written = self.state / f".{SNAPSHOT}.e2e" + written.write_text(json.dumps(payload), encoding="utf-8") + os.replace(written, self.state / SNAPSHOT) + + def sight(self) -> None: + hub = self.httpd.hub + receipts.sighting_pass(hub.scripts.skills, hub.council, hub.receipt_names, hub.receipt_reads, hub.agent_sessions, RADIO_WINDOW, time.time()) + + def mark(self, sid: str, ts: float) -> None: + folder = self.council / receipts.SEEN + folder.mkdir(parents=True, exist_ok=True) + written = folder / f".{sid}.e2e" + written.write_text(json.dumps({"radio": ts}), encoding="utf-8") + os.replace(written, folder / f"{sid}.json") + + def silence(self, words: str) -> None: + now = time.time() + self.write_council({"radio-silence.json": {"since": now - 60, "until": now + 3600, "by": "Docs", "text": words}}) + + def stations(self) -> None: + hub = self.httpd.hub + hub.settings.put({**hub.settings.get(), "streams": STREAMS}, hub.settings.get()) diff --git a/tests/e2e/radio_layout_probes.py b/tests/e2e/radio_layout_probes.py new file mode 100644 index 0000000..a35957f --- /dev/null +++ b/tests/e2e/radio_layout_probes.py @@ -0,0 +1,341 @@ +from __future__ import annotations + +LAYOUT = """(async () => {@HELPERS@@PROBES@ + await ViewStore.update("home.pins", () => []); + const spot = await openSpot(); + spot.querySelector('.radio-tabs [data-tab="all"]').click(); + await until(() => all(".radio-row .reader", spot).length > 20 && longRow(spot), 20000); + await sleep(300); + window.scrollTo(0, 0); + const cardOf = (node) => (node.parentElement && node.parentElement.closest(".radio-card")) || spot; + const wider = all("*", spot).filter((node) => node.tagName !== "OPTION" && shown(node) && box(node).width > 0).filter((node) => { + const own = box(node); + const card = box(cardOf(node)); + return own.left < card.left - 1 || own.right > card.right + 1; + }).map((node) => `${node.tagName}.${node.getAttribute("class")}`); + const list = spot.querySelector(".radio-log"); + const listLook = getComputedStyle(list); + const rows = all(".radio-row", spot); + const lineHeight = parseFloat(getComputedStyle(rows[0].querySelector(".radio-line")).lineHeight); + const lines = rows.map((row) => { + const line = row.querySelector(".radio-line"); + const look = getComputedStyle(line); + return {height: Math.round(box(row).height), nowrap: look.whiteSpace === "nowrap", ellipsis: look.textOverflow === "ellipsis", flat: line.scrollHeight <= line.clientHeight + 1 && row.scrollHeight <= row.clientHeight + 1, fits: row.scrollWidth <= row.clientWidth + 1 && box(row).right <= box(list).right + 1, width: line.clientWidth}; + }); + const long = longRow(spot).querySelector(".radio-line"); + const avatars = rows.filter((row) => row.querySelector(".reader")).map((row) => { + const edge = box(row); + const line = box(row.querySelector(".radio-line")); + const faces = all(".reader .avatar", row).filter(shown).map(box); + return { + total: Number((row.querySelector(".readers").getAttribute("aria-label").match(/\\d+/) || ["0"])[0]), + count: faces.length, + more: all(".readers-more", row).filter(shown).map(text), + inside: faces.every((face) => face.left >= edge.left - 1 && face.right <= edge.right + 1 && face.top >= edge.top - 1 && face.bottom <= edge.bottom + 1), + after: faces.every((face) => face.left >= line.right - 1), + stacked: faces.slice(1).every((face, index) => face.left < faces[index].right), + sliver: faces.length ? Math.min(...faces.map((face, index) => (index + 1 < faces.length ? faces[index + 1].left : face.right) - face.left)) : null, + }; + }); + 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)], + wider, scrollers: scrollersIn(spot), + list: {overflowY: listLook.overflowY, scrollbar: [listLook.scrollbarWidth, listLook.scrollbarColor], scrolls: list.scrollHeight > list.clientHeight + 1}, + main: getComputedStyle(document.getElementById("main")).scrollbarColor, + heights: [...new Set(lines.map((line) => line.height))], lineHeight, rows: rows.length, + single: lines.every((line) => line.nowrap && line.ellipsis && line.flat && line.fits), + narrowest: Math.min(...lines.map((line) => line.width)), + long: [long.scrollWidth > long.clientWidth, getComputedStyle(long).textOverflow], + avatars: {rows: avatars.length, most: Math.max(...avatars.map((row) => row.count)), inside: avatars.every((row) => row.inside), after: avatars.every((row) => row.after), stacked: avatars.filter((row) => row.count > 1).every((row) => row.stacked)}, + folds: avatars.map((row) => [row.total, row.count, row.more]), + 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, + stations: [Boolean(spot.querySelector("details.radio-station")), spot.querySelector("details.radio-station").open], + }; +})()""" +POPUP = """(async () => {@HELPERS@@PROBES@ + const spot = document.getElementById("radio-spot"); + const copied = []; + navigator.clipboard.writeText = (value) => { + copied.push(value); + return Promise.resolve(); + }; + const row = longRow(spot); + row.scrollIntoView({block: "center"}); + await sleep(200); + const dialog = await openRow(row); + if (!dialog) { + return {error: "no popup"}; + } + const card = dialog.querySelector(".popup-box"); + const fields = Object.fromEntries(all("dl.meta > div", card).map((pair) => [text(pair.querySelector("dt")), text(pair.querySelector("dd"))])); + const readers = all(".popup-reader", card).map((item) => ({session: item.dataset.session, name: text(item.querySelector("strong")), time: text(item.querySelector(".muted")), acked: item.dataset.acked})); + const copy = card.querySelector(".radio-copy"); + const said = card.querySelector(".radio-said"); + const heard = () => [copy.getAttribute("aria-label"), said ? text(said) : null]; + const region = said ? [said.getAttribute("role"), said.getAttribute("aria-live"), card.contains(said), shown(said) && box(said).width <= 1] : null; + copy.click(); + const done = await until(() => (copy.dataset.copied === "true" ? text(copy) : null), 3000); + const success = heard(); + const buttons = all(".radio-actions button", card).map(text); + await until(() => copy.getAttribute("aria-label") === "Copy" && copy.dataset.copied === "", 4000); + const reset = heard(); + navigator.clipboard.writeText = () => Promise.reject(new DOMException("Denied", "NotAllowedError")); + copy.click(); + await until(() => copy.dataset.copied === "false", 3000); + const failure = heard(); + return { + open: dialog.open, title: text(card.querySelector(".popup-head h2")), fields, full: dialog.querySelector(".radio-full").textContent, readers, + heading: text(card.querySelector("h3")), buttons, copied, shown: done, region, success, reset, failure, + stray: [...card.childNodes].filter((node) => node.nodeType === 3).map((node) => node.textContent), + inView: (() => { + const edge = box(card); + return edge.left >= 0 && edge.top >= 0 && edge.right <= innerWidth + 1 && edge.bottom <= innerHeight + 1; + })(), + }; +})()""" +CLOSE_REPLY = """(async () => {@HELPERS@@PROBES@ + const spot = document.getElementById("radio-spot"); + (document.activeElement || document.body).dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await sleep(200); + const escaped = !popup().open; + const dialog = await openRow(longRow(spot)); + const card = box(dialog.querySelector(".popup-box")); + const x = card.left > 8 ? Math.floor(card.left / 2) : Math.ceil((card.right + document.documentElement.clientWidth) / 2); + const hit = document.elementFromPoint(x, Math.round(innerHeight / 2)); + hit.click(); + await sleep(200); + const outside = [hit === popup(), !popup().open]; + await openRow(longRow(spot)); + all(".radio-actions button", popup()).find((button) => text(button) === "Reply").click(); + await sleep(300); + return {escaped, outside, reply: {open: popup().open, ...pick(spot)}}; +})()""" +HOME = """(async () => {@HELPERS@@PROBES@ + const spot = await openSpot(); + 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"); + } + 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]); + await closeSpot(); + location.hash = "#home"; + await screenShown(8000); + await until(() => @PARTS@.every((id) => tile(id)) && tile("radio-log").querySelector(".radio-row") && tile("radio").querySelector(".radio-row"), 10000); + await sleep(400); + const measure = () => Object.fromEntries(@PARTS@.map((id) => { + const body = tile(id).querySelector(".home-body"); + const list = tile(id).querySelector(".radio-log"); + const edge = box(body); + const rows = list ? all(".radio-row", list).filter((row) => box(row).top >= box(list).top - 1 && box(row).bottom <= box(list).bottom + 1).length : null; + return [id, {scrollers: scrollersIn(tile(id)), rows, inside: list ? box(list).bottom <= edge.bottom + 1 && box(list).top >= edge.top - 1 : null, filled: Math.abs(box(tile(id).querySelector(".radio-home")).height - body.clientHeight + parseFloat(getComputedStyle(body).paddingTop) + parseFloat(getComputedStyle(body).paddingBottom)) <= 2}]; + })); + const fresh = measure(); + const whole = tile("radio"); + const bar = whole.querySelector(".spot-head"); + const gear = bar ? all("button", bar).find((button) => button.getAttribute("aria-label") === "Read aloud") : null; + const clear = bar ? all("button", bar).find((button) => button.getAttribute("aria-label") === "Cancel mayday") : null; + if (gear) { + gear.click(); + await sleep(200); + } + const filters = whole.querySelector(".radio-gear .radio-read"); + const tools = { + gear: gear ? [gear.getAttribute("aria-expanded"), Boolean(filters), filters ? box(filters).bottom <= box(whole).bottom + 1 : null] : null, + clear: clear ? [clear.disabled, clear.title] : null, + }; + if (gear) { + gear.click(); + } + const content = { + tiles: all("#main .home-tile").map((node) => node.dataset.pin), + radio: [".radio-device", ".radio-speak", ".radio-logbox"].map((selector) => Boolean(tile("radio").querySelector(selector))), + device: [text(tile("radio-device").querySelector('[data-field="mode"]')), all(".radio-knobs input[type=range]", tile("radio-device")).length], + 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, + ids: all("#main .home-tile .home-body [id]").map((node) => node.id), + }; + const count = (id) => tile(id).querySelectorAll(".radio-row").length; + const before = [count("radio-log"), count("radio")]; + await fetch("/api/voice/@LIVE@", {cache: "no-store"}); + window.dispatchEvent(new Event("focus")); + const first = (id) => text(tile(id).querySelector(".radio-row .radio-line")); + const live = await until(() => (count("radio-log") > before[0] && count("radio") > before[1] && first("radio-log").startsWith("live row") ? [first("radio-log"), first("radio")] : null), 20000); + tile("radio-device").querySelector('.radio-modes button[data-mode="quiet"]').click(); + await sleep(200); + const mode = [text(tile("radio").querySelector('[data-field="mode"]')), text(document.querySelector('#radio-spot [data-field="mode"]'))]; + tile("radio-device").querySelector('.radio-modes button[data-mode="auto"]').click(); + await sleep(200); + const sizes = @SIZES@; + await ViewStore.update("home.pins", (pins) => (pins || []).map((pin) => ({...pin, w: sizes[pin.id][0], h: sizes[pin.id][1]}))); + await until(() => @PARTS@.every((id) => tile(id).dataset.w === String(sizes[id][0]) && tile(id).dataset.h === String(sizes[id][1])), 5000); + await sleep(400); + const resized = measure(); + window.scrollTo(0, 0); + return {pressed, stored, fresh, resized, tools, content, live, mode, wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" +FIT = """(async () => {@HELPERS@@PROBES@ + await ViewStore.update("home.pins", () => []); + location.hash = "#agents/orbit"; + await screenShown(8000); + const spot = await openSpot(); + await until(() => spot.querySelector(".radio-row"), 8000); + await sleep(500); + const stage = document.querySelector("#main .stage svg"); + const list = spot.querySelector(".radio-log"); + const result = { + fit: document.body.classList.contains("fit"), tall: document.documentElement.scrollHeight > innerHeight, wide: document.documentElement.scrollWidth > innerWidth + 1, + stage: stage ? Math.round(box(stage).height) : 0, height: innerHeight, scrollers: scrollersIn(spot), + list: list.clientHeight, speak: (() => { + const card = spot.querySelector(".radio-speak"); + return card.scrollHeight <= card.clientHeight + 1; + })(), + }; + await closeSpot(); + await sleep(300); + const after = document.querySelector("#main .stage svg"); + result.closed = {boxes: spot.getClientRects().length, tall: document.documentElement.scrollHeight > innerHeight, stage: after ? Math.round(box(after).height) : 0}; + return result; +})()""" +SPOT = """(async () => {@HELPERS@@PROBES@@SPEAKING@ + await ViewStore.update("home.pins", () => []); + location.hash = "@VIEW@"; + await screenShown(8000); + const spot = await openSpot(); + await until(() => spot.querySelector(".radio-row") && spot.querySelectorAll(".radio-device .station").length === 3, 8000); + await settle(); + await sleep(500); + window.scrollTo(0, 0); + const fits = (node) => node.scrollHeight <= node.clientHeight + 1; + const list = spot.querySelector(".radio-log"); + const fold = spot.querySelector("details.radio-station"); + const form = spot.querySelector(".radio-speak form.composer"); + const note = form.querySelector(".voice-note"); + const display = spot.querySelector(".radio-caption"); + const named = (node) => node.getAttribute("aria-label") || text(node) || node.getAttribute("title") || `${node.tagName}.${node.getAttribute("class")}`; + const blocked = () => { + const layer = spot.querySelector(".radio-station[open] > .station-body"); + const marks = [spot.querySelector(".radio-lamp"), spot.querySelector('[data-field="cpu"]'), spot.querySelector(".radio-device .group-title")]; + const folded = (node) => Boolean(node.closest("details:not([open])")) && !node.closest("summary"); + const found = []; + for (const node of [...all('button, input, select, textarea, summary, audio, [role="tab"]', spot), ...marks].filter((item) => shown(item) && !folded(item) && box(item).width > 0 && box(item).height > 0)) { + window.scrollTo(0, 0); + const seen = box(node); + if (seen.bottom > innerHeight) { + window.scrollBy(0, seen.top + seen.height / 2 - innerHeight / 2); + } + const edge = box(node); + const [x, y] = [edge.left + edge.width / 2, edge.top + edge.height / 2]; + const hit = document.elementFromPoint(x, y); + if (!(list.contains(node) && (y < box(list).top || y > box(list).bottom)) && !(hit === node || node.contains(hit) || (layer && hit && layer.contains(hit) && !layer.contains(node)))) { + found.push(`${named(node)} <- ${hit ? `${hit.tagName}.${hit.getAttribute("class")}#${hit.id}` : "null"}`); + } + } + window.scrollTo(0, 0); + return found; + }; + const stack = () => { + const card = spot.querySelector(".radio-logbox"); + const head = [card.querySelector(".radio-tabs"), card.querySelector('input[type="search"]')].map(box); + const chips = all(".chip-select, .radio-filters > button", card).map(box); + return {head: Math.round(Math.max(...head.map((edge) => edge.bottom))), chips: [Math.round(Math.min(...chips.map((edge) => edge.top))), Math.round(Math.max(...chips.map((edge) => edge.bottom)))], list: Math.round(box(list).top)}; + }; + const measure = () => { + window.scrollTo(0, 0); + const [device, speak, history] = ["radio-device", "radio-speak", "radio-log"].map((id) => box(spot.querySelector(`[data-panel="${id}"]`))); + const svg = document.querySelector("#main .stage svg"); + return { + fit: document.body.classList.contains("fit"), + page: [document.documentElement.scrollWidth, document.documentElement.scrollHeight, innerWidth, innerHeight], + scrollers: scrollersIn(spot), cards: [fits(spot.querySelector(".radio-device")), fits(spot.querySelector(".radio-speak"))], + main: Math.round(box(document.getElementById("main")).height), floor: Math.round(innerHeight * @MAIN@ - box(document.getElementById("spot-host")).top), + full: Math.round(innerHeight - document.getElementById("head").offsetHeight - 16), stack: stack(), beneath: box(document.getElementById("main")).top >= box(spot).bottom - 1, + stage: svg ? Math.round(box(svg).height) : null, + list: list.clientHeight, rows: all(".radio-row", list).filter((row) => box(row).top >= box(list).top - 1 && box(row).bottom <= box(list).bottom + 1).length, + order: device.right <= speak.left && device.right <= history.left && speak.bottom <= history.top + 1 && Math.abs(speak.left - history.left) < 2, + active: {stations: fold.open ? all(".station", fold).filter(shown).length : 0, voice: !note.hidden && shown(note), speech: !display.hidden && shown(display)}, + blocked: blocked(), + banner: (() => { + const node = document.getElementById("mayday"); + if (node.hidden || !shown(node)) { + return null; + } + const words = node.querySelector(".text"); + const cancel = node.querySelector("button"); + const edge = box(cancel); + const hit = document.elementFromPoint(edge.left + edge.width / 2, edge.top + edge.height / 2); + return {height: Math.round(box(node).height), title: words.title, full: words.textContent, cut: words.scrollWidth > words.clientWidth + 1, cancel: Boolean(hit && cancel.contains(hit))}; + })(), + play: [note.querySelector(".voice-play"), note.querySelector("audio")].filter((node) => node && shown(node) && box(node).width > 0).map((node) => [node.tagName, Math.round(box(node).width), Math.round(box(node).height)]), + line: (() => { + const node = display.querySelector(".caption-line"); + return node && shown(node) ? [Math.round(node.clientWidth), text(node).length] : null; + })(), + rem: parseFloat(getComputedStyle(document.documentElement).fontSize), + }; + }; + const wanted = @STATES@; + const states = {}; + for (const name of wanted.filter((state) => state === "idle" || state.startsWith("mayday"))) { + states[name] = measure(); + } + if (wanted.includes("stations")) { + const summary = fold.querySelector("summary"); + summary.focus(); + summary.click(); + await sleep(300); + states.stations = measure(); + document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await sleep(200); + states.stations.closed = [fold.open, document.activeElement === summary]; + } + if (wanted.includes("voice")) { + const record = all("button", form).find((button) => button.hasAttribute("aria-pressed")); + record.click(); + await sleep(1300); + record.click(); + const heard = await until(() => !note.hidden && note.querySelector("audio") && form.querySelector("textarea").value, 30000); + await sleep(300); + states.voice = {...measure(), heard: Boolean(heard)}; + const toggle = note.querySelector(".voice-play"); + if (toggle && shown(toggle)) { + toggle.click(); + states.voice.played = Boolean(await until(() => !note.querySelector("audio").paused && toggle.getAttribute("aria-label") === "Pause voice message", 4000)); + toggle.click(); + states.voice.paused = Boolean(await until(() => note.querySelector("audio").paused && toggle.getAttribute("aria-label") === "Play voice message", 4000)); + } + const trash = all("button", note).find((button) => button.getAttribute("aria-label") === "Remove recording"); + if (trash) { + trash.click(); + } + await sleep(200); + } + if (wanted.includes("speech")) { + const found = await cue("@CUE@"); + await sleep(300); + states.speech = {...measure(), who: found && !found.error ? found.who : found}; + const stop = display.querySelector("button"); + if (stop) { + stop.click(); + } + await until(() => display.hidden, 8000); + } + return states; +})()""" diff --git a/tests/e2e/radio_set_kit.py b/tests/e2e/radio_set_kit.py new file mode 100644 index 0000000..f8706e5 --- /dev/null +++ b/tests/e2e/radio_set_kit.py @@ -0,0 +1,283 @@ +from __future__ import annotations + +import os +from pathlib import Path + +import hub_e2e_kit as base +from kvb_orchestrator import phrasing + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/radio-set-shots")) +WORD = phrasing.procedure("security") +CUES = {"low": "c000000000000001", "high": "c000000000000002", "hold": "c000000000000003", "free": "c000000000000004", "alarm": "a000000000000001", "call": "a000000000000002", "dark": "d000000000000001", "light": "d000000000000002"} +THRESHOLDS = {1920: 60, 1366: 70, 390: 80} +FIXTURE = [ + {"ago": 600, "from": "Operator", "to": ["Stage"], "class": "post", "text": "rebase please"}, + {"ago": 500, "from": "Stage", "to": ["Operator"], "class": "call", "text": "gate red on main"}, + {"ago": 400, "from": "Docs", "to": [], "class": "newsletter", "text": "docs are green"}, + {"ago": 350, "from": "Stage", "to": ["Skills session"], "class": "post", "text": "rebase done\nsecond line of the full message"}, + {"ago": 320, "from": "Operator", "to": [], "class": "broadcast", "text": "deploy now"}, +] +SPY = """() => { + window.e2eViolations = []; + document.addEventListener("securitypolicyviolation", (event) => window.e2eViolations.push(`${event.violatedDirective} ${event.blockedURI}`)); + const log = window.e2eAudio = {tts: [], requests: [], filters: [], starts: [], oscillators: 0, levels: [], passkeys: 0}; + const fetched = window.fetch.bind(window); + window.fetch = (input, init) => { + const url = String(input && input.url ? input.url : input); + const entry = url.includes("/api/tts") ? {body: JSON.parse(init.body), status: 0} : null; + log.requests.push(url); + if (entry) { + log.tts.push(entry); + } + return fetched(input, init).then((response) => { + if (entry) { + entry.status = response.status; + } + return response; + }); + }; + const filter = AudioContext.prototype.createBiquadFilter; + AudioContext.prototype.createBiquadFilter = function created() { + const node = filter.call(this); + log.filters.push(node); + return node; + }; + const start = AudioBufferSourceNode.prototype.start; + AudioBufferSourceNode.prototype.start = function started(...args) { + log.starts.push({seconds: this.buffer ? Math.round(this.buffer.duration * 1000) / 1000 : null, channels: this.buffer ? this.buffer.numberOfChannels : null}); + return start.apply(this, args); + }; + const tone = OscillatorNode.prototype.start; + OscillatorNode.prototype.start = function toned(...args) { + log.oscillators += 1; + return tone.apply(this, args); + }; + const level = AudioParam.prototype.setValueAtTime; + AudioParam.prototype.setValueAtTime = function levelled(value, at) { + log.levels.push(Math.round(value * 1000) / 1000); + return level.call(this, value, at); + }; + if (navigator.credentials) { + const get = navigator.credentials.get.bind(navigator.credentials); + navigator.credentials.get = (options) => { + log.passkeys += 1; + return get(options); + }; + } +}""" +RADIO = """ + const spotToggle = document.getElementById("radio-open"); + await until(() => typeof Nav === "object" && document.getElementById("radio-spot"), 8000); + if (spotToggle.getAttribute("aria-expanded") !== "true") { + spotToggle.click(); + await sleep(300); + } + const spot = document.getElementById("radio-spot"); + const audio = () => window.e2eAudio; + const cue = (name) => fetch(`/api/voice/${{@CUES@}[name]}`, {cache: "no-store"}); + const refreshNow = () => window.dispatchEvent(new Event("focus")); + const field = (name) => text(spot.querySelector(`.radio-display [data-field="${name}"]`)); + const lamp = () => spot.querySelector(".radio-lamp"); + const fits = () => ({page: document.documentElement.scrollWidth <= innerWidth + 1, panel: spot.scrollWidth <= spot.clientWidth + 1}); + const press = (mode) => spot.querySelector(`.radio-modes button[data-mode="${mode}"]`).click(); + const pressed = () => all(".radio-modes button", spot).filter((button) => button.getAttribute("aria-pressed") === "true").map((button) => button.dataset.mode); + const mark = () => ({tts: audio().tts.length, starts: audio().starts.length, filters: audio().filters.length, oscillators: audio().oscillators, levels: audio().levels.length, requests: audio().requests.length}); + const since = (at) => ({ + tts: audio().tts.slice(at.tts).map((entry) => [entry.body.text, entry.status]), + starts: audio().starts.slice(at.starts), + filters: audio().filters.slice(at.filters).map((node) => [node.type, node.frequency.value]), + oscillators: audio().oscillators - at.oscillators, + levels: audio().levels.slice(at.levels), + requests: audio().requests.slice(at.requests).filter((url) => !/\\/api\\/(state|stream|events|tts|tree|subagents|voice\\/[a-d]0)/.test(url)), + }); + const cpuShown = async (label) => { + refreshNow(); + return Boolean(await until(() => field("cpu") === label, 12000)); + }; + const transmit = async (names, count) => { + const at = mark(); + for (const name of names) { + await cue(name); + } + refreshNow(); + await until(() => audio().tts.length >= at.tts + count && audio().tts.slice(at.tts).every((entry) => entry.status), 20000); + await sleep(1500); + await until(() => lamp().dataset.lit === "false", 4000); + return since(at); + }; + const tabs = () => Object.fromEntries(all('.radio-tabs [role="tab"]', spot).map((tab) => [tab.dataset.tab, Number(text(tab.querySelector(".count")))])); + const selected = () => (spot.querySelector('.radio-tabs [aria-selected="true"]') || {dataset: {}}).dataset.tab || null; + const rows = () => all(".radio-row", spot).map((item) => ({dir: item.dataset.dir, cls: item.dataset.class, route: text(item.querySelector(".radio-route")), line: text(item.querySelector(".radio-line")), ts: Number(item.querySelector("time").dataset.ts)})); + const chip = async (name, value) => { + const select = spot.querySelector(`.chip-select[data-chip="${name}"] select`); + select.value = value; + select.dispatchEvent(new Event("change", {bubbles: true})); + await sleep(150); + }; + const chips = () => Object.fromEntries(all(".chip-select", spot).map((box) => [box.dataset.chip, box.querySelector("select").value])); + const search = () => spot.querySelector('.radio-logbox input[type="search"]'); + const tab = async (id) => { + spot.querySelector(`.radio-tabs [data-tab="${id}"]`).click(); + await sleep(150); + }; + const unlabelled = () => all(".radio-face :is(button, select, input), #radio-gear :is(button, select, input), .radio-logbox :is(button, select, input), .radio-station button", spot).filter((node) => node.getClientRects().length && !node.getAttribute("aria-label") && !text(node)).length; +""".replace("@CUES@", ", ".join(f'"{name}": "{ident}"' for name, ident in CUES.items())) +FACE = """(async () => {@HELPERS@@RADIO@ + await cpuShown("CPU 10 %"); + const display = {lamp: [text(lamp()), lamp().dataset.lit], cls: field("class"), mode: field("mode"), cpu: field("cpu"), title: spot.querySelector('[data-field="cpu"]').title}; + const modes = all(".radio-modes button", spot).map((button) => [text(button), button.getAttribute("aria-pressed"), Boolean(button.title && button.getAttribute("aria-label")), Boolean(button.querySelector("svg.bi"))]); + const knobs = all(".radio-knobs input[type=range]", spot).map((input) => [input.getAttribute("aria-label"), input.min, input.max, input.step, input.value]); + const toneToggles = all(".radio-knobs button[aria-pressed]", spot).map((button) => [button.getAttribute("aria-label"), button.getAttribute("aria-pressed")]); + const labels = all(".radio-knobs .knob-row", spot).filter((row) => row.querySelector(".knob-label")).map((row) => { + const label = row.querySelector(".knob-label"); + return {text: text(label), title: label.title, whole: label.scrollWidth <= label.clientWidth + 1, row: row.scrollWidth <= row.clientWidth + 1}; + }); + const gear = all(".spot-head button", spot).find((button) => name(button) === "Read aloud"); + gear.click(); + await sleep(200); + const groups = Object.fromEntries(all("#radio-gear .chips", spot).map((group) => [group.getAttribute("aria-label"), all(".chip", group).map((chipNode) => [text(chipNode), chipNode.getAttribute("aria-pressed"), chipNode.disabled])])); + const stationsHead = text(spot.querySelector(".radio-station .group-title")); + const ptt = spot.querySelector('form.composer button[type="submit"]'); + const pageFits = fits(); + document.getElementById("settings-open").click(); + await until(() => document.querySelector("#sheet .sheet-box"), 4000); + const sections = all("#sheet .settings h3").map(text); + all("#sheet .sheet-head button").find((button) => name(button) === "Close").click(); + await sleep(200); + all(".radio-station button", spot).find((button) => text(button) === "Edit stations").click(); + await until(() => document.querySelector("#sheet .sheet-box"), 4000); + const stations = [document.querySelector("#sheet .sheet-box").getAttribute("aria-label"), all("#sheet .settings h3").map(text)]; + all("#sheet .sheet-head button").find((button) => name(button) === "Close").click(); + await sleep(200); + return {display, modes, knobs, toneToggles, labels, groups, stationsHead, ptt: [text(ptt), ptt.title], sections, stations, fits: pageFits, unlabelled: unlabelled(), palette: getComputedStyle(document.documentElement).getPropertyValue("--panel").trim(), violations: window.e2eViolations}; +})()""" +LOG = """(async () => {@HELPERS@@RADIO@ + await until(() => rows().length, 8000); + const counts = tabs(); + await tab("sent"); + const sent = rows(); + await tab("received"); + const received = rows(); + await tab("all"); + const every = rows(); + await chip("class", "post"); + const posts = rows(); + await chip("from", "Stage"); + const fromStage = rows(); + search().value = "second"; + search().dispatchEvent(new Event("input", {bubbles: true})); + await sleep(150); + const narrowed = rows(); + search().value = "please"; + search().dispatchEvent(new Event("input", {bubbles: true})); + await sleep(150); + const none = [rows().length, text(spot.querySelector(".radio-log li.muted"))]; + all(".radio-filters button", spot).find((button) => name(button) === "Clear filters").click(); + await sleep(150); + const clearedChips = [chips(), search().value, rows().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)]; + all("#popup .popup-head button").find((button) => name(button) === "Close").click(); + await sleep(150); + await tab("received"); + await chip("agent", "Stage"); + search().value = "gate"; + search().dispatchEvent(new Event("input", {bubbles: true})); + await sleep(200); + spot.querySelector(".radio-logbox").scrollIntoView({block: "start"}); + await sleep(200); + return {counts, sent, received, every, posts, fromStage, narrowed, none, clearedChips, opened, kept: rows(), fits: fits()}; +})()""" +LOG_KEPT = """(async () => {@HELPERS@@RADIO@ + await until(() => spot.querySelector(".radio-tabs [role=tab]"), 8000); + await sleep(300); + const kept = {tab: selected(), chips: chips(), q: search().value, rows: rows()}; + all(".radio-filters button", spot).find((button) => name(button) === "Clear filters").click(); + await tab("all"); + const list = spot.querySelector(".radio-log"); + list.scrollIntoView({block: "start"}); + await sleep(300); + const top = Math.max(list.getBoundingClientRect().top, spot.getBoundingClientRect().top, document.querySelector(".head").getBoundingClientRect().bottom); + const bottom = Math.min(list.getBoundingClientRect().bottom, spot.getBoundingClientRect().bottom, innerHeight); + const shown = all(".radio-row", list).filter((item) => item.getBoundingClientRect().top >= top - 1 && item.getBoundingClientRect().bottom <= bottom + 1).length; + return {...kept, shown, total: all(".radio-row", list).length, fits: fits()}; +})()""" +SOUND = """(async () => {@HELPERS@@RADIO@ + const found = {}; + press("auto"); + await cue("free"); + await cue("low"); + found.low = await cpuShown("CPU 10 %"); + found.auto = await transmit(["alarm"], 2); + await cue("hold"); + found.held = await transmit(["alarm"], 2); + const heldCount = audio().tts.length; + await sleep(2500); + found.retries = audio().tts.length - heldCount; + await cue("free"); + press("quiet"); + found.quiet = await transmit(["alarm", "call"], 1); + press("silence"); + found.silence = await transmit(["alarm", "call"], 1); + found.pressed = pressed(); + found.mode = field("mode"); + return found; +})()""" +SOUND_KEPT = """(async () => {@HELPERS@@RADIO@ + await sleep(300); + const kept = [pressed(), field("mode")]; + press("auto"); + return {kept, pressed: pressed()}; +})()""" +BURST = """(async () => {@HELPERS@@RADIO@ + const squelch = all(".radio-knobs input[type=range]", spot).find((input) => input.getAttribute("aria-label") === "Squelch"); + squelch.value = "0.6"; + squelch.dispatchEvent(new Event("input", {bubbles: true})); + await cue("high"); + const high = await cpuShown("CPU 95 %"); + const at = mark(); + await cue("alarm"); + refreshNow(); + const lit = Boolean(await until(() => lamp().dataset.lit === "true" && audio().filters.length > at.filters, 20000)); + return {high, lit, lamp: [text(lamp()), lamp().getAttribute("aria-label")], open: spot.querySelector('[data-field="cpu"]').dataset.open, heard: since(at)}; +})()""" +BURST_DONE = """(async () => {@HELPERS@@RADIO@ + await until(() => lamp().dataset.lit === "false", 6000); + await sleep(800); + const squelch = all(".radio-knobs input[type=range]", spot).find((input) => input.getAttribute("aria-label") === "Squelch"); + squelch.value = "1"; + squelch.dispatchEvent(new Event("input", {bubbles: true})); + await cue("low"); + return {tts: audio().tts.slice(-2).map((entry) => [entry.body.text, entry.status]), low: await cpuShown("CPU 10 %")}; +})()""" +THRESHOLD = """(async () => {@HELPERS@@RADIO@ + const knob = all(".radio-knobs input[type=range]", spot).find((input) => input.getAttribute("aria-label") === "Threshold"); + const before = [knob.value, audio().passkeys]; + knob.value = "@VALUE@"; + knob.dispatchEvent(new Event("input", {bubbles: true})); + knob.dispatchEvent(new Event("change", {bubbles: true})); + await until(() => all("#toasts .toast").length, 15000); + await sleep(600); + refreshNow(); + await sleep(800); + await cue("dark"); + refreshNow(); + const light = getComputedStyle(document.documentElement).getPropertyValue("--panel").trim(); + const dark = await until(() => { + const now = getComputedStyle(document.documentElement).getPropertyValue("--panel").trim(); + return now !== light ? now : null; + }, 12000); + await sleep(400); + return {before, after: [knob.value, audio().passkeys], shown: text(knob.parentElement.querySelector(".knob-value")), title: spot.querySelector('[data-field="cpu"]').title, toasts: all("#toasts .toast strong").map(text), dark: [light, dark], fits: fits()}; +})()""" +LIGHT = """(async () => {@HELPERS@@RADIO@ + await cue("light"); + refreshNow(); + await sleep(1500); + return {violations: window.e2eViolations}; +})()""" + + +def probe(template: str) -> str: + return template.replace("@HELPERS@", base.HELPERS).replace("@RADIO@", RADIO) diff --git a/tests/e2e/test_001_gaps_e2e.py b/tests/e2e/test_001_gaps_e2e.py index fede593..e5d17d4 100644 --- a/tests/e2e/test_001_gaps_e2e.py +++ b/tests/e2e/test_001_gaps_e2e.py @@ -11,7 +11,7 @@ from pathlib import Path HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase from hub_support import ASK, iso from kvb_orchestrator import skill_scripts @@ -209,10 +209,10 @@ def probe(template: str, signs: bool = False) -> str: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestOrchestratorGaps(HubCase): - drive = base.TestOrchestratorE2E.drive - authenticator = base.TestOrchestratorE2E.authenticator - subagents = base.TestOrchestratorE2E.subagents - beside = base.TestOrchestratorE2E.beside + drive = base.OrchestratorE2ECase.drive + authenticator = base.OrchestratorE2ECase.authenticator + subagents = base.OrchestratorE2ECase.subagents + beside = base.OrchestratorE2ECase.beside def setUp(self): super().setUp() diff --git a/tests/e2e/test_firewall_e2e.py b/tests/e2e/test_firewall_e2e.py index b052049..d74fa28 100644 --- a/tests/e2e/test_firewall_e2e.py +++ b/tests/e2e/test_firewall_e2e.py @@ -12,7 +12,7 @@ from pathlib import Path HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase from hub_support import ASK, verifier from test_settings_writer import ORIGINAL @@ -199,9 +199,9 @@ def probe(template: str, values: dict[str, str]) -> str: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestFirewallE2E(HubCase): - drive = base.TestOrchestratorE2E.drive - beside = base.TestOrchestratorE2E.beside - authenticator = base.TestOrchestratorE2E.authenticator + drive = base.OrchestratorE2ECase.drive + beside = base.OrchestratorE2ECase.beside + authenticator = base.OrchestratorE2ECase.authenticator def setUp(self): super().setUp() diff --git a/tests/e2e/test_home_bookmarks_e2e.py b/tests/e2e/test_home_bookmarks_e2e.py index eb3e3cc..39fc9e6 100644 --- a/tests/e2e/test_home_bookmarks_e2e.py +++ b/tests/e2e/test_home_bookmarks_e2e.py @@ -13,8 +13,8 @@ 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_home_dashboard_e2e as dash -import test_orchestrator_e2e as base import test_resources_view_e2e as res import test_workbench_w4_e2e as w4 from hub_case import HubCase @@ -296,9 +296,9 @@ def probe(template: str, screens: list[str] | None = None) -> str: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestHomeBookmarks(HubCase): - seed = base.TestOrchestratorE2E.seed - subagents = base.TestOrchestratorE2E.subagents - drive = base.TestOrchestratorE2E.drive + seed = base.OrchestratorE2ECase.seed + subagents = base.OrchestratorE2ECase.subagents + drive = base.OrchestratorE2ECase.drive sample = w4.TestWorkbenchResources.sample def setUp(self): diff --git a/tests/e2e/test_home_dashboard_e2e.py b/tests/e2e/test_home_dashboard_e2e.py index b4abde9..98e169c 100644 --- a/tests/e2e/test_home_dashboard_e2e.py +++ b/tests/e2e/test_home_dashboard_e2e.py @@ -13,7 +13,7 @@ from unittest import mock HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase from hub_support import HUB, iso @@ -287,9 +287,9 @@ def probe(template: str) -> str: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestHomeDashboard(HubCase): - seed = base.TestOrchestratorE2E.seed - subagents = base.TestOrchestratorE2E.subagents - drive = base.TestOrchestratorE2E.drive + seed = base.OrchestratorE2ECase.seed + subagents = base.OrchestratorE2ECase.subagents + drive = base.OrchestratorE2ECase.drive def setUp(self): super().setUp() diff --git a/tests/e2e/test_home_tile_open_e2e.py b/tests/e2e/test_home_tile_open_e2e.py index 5e8d552..c5ef645 100644 --- a/tests/e2e/test_home_tile_open_e2e.py +++ b/tests/e2e/test_home_tile_open_e2e.py @@ -11,9 +11,9 @@ from pathlib import Path HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] +import hub_e2e_kit as base import test_home_bookmarks_e2e as bm import test_home_dashboard_e2e as dash -import test_orchestrator_e2e as base import test_resources_view_e2e as res import test_workbench_w4_e2e as w4 from hub_case import HubCase @@ -179,9 +179,9 @@ def landing(key: str) -> tuple[str, str]: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestHomeTileOpen(HubCase): - seed = base.TestOrchestratorE2E.seed - subagents = base.TestOrchestratorE2E.subagents - drive = base.TestOrchestratorE2E.drive + seed = base.OrchestratorE2ECase.seed + subagents = base.OrchestratorE2ECase.subagents + drive = base.OrchestratorE2ECase.drive sample = w4.TestWorkbenchResources.sample def setUp(self): diff --git a/tests/e2e/test_hub_board_e2e.py b/tests/e2e/test_hub_board_e2e.py new file mode 100644 index 0000000..dbeab48 --- /dev/null +++ b/tests/e2e/test_hub_board_e2e.py @@ -0,0 +1,272 @@ +from __future__ import annotations + +import base64 +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_e2e_board import ( + AFTER, + AFTER_TAKEOVER, + CONFIRM, + CONFIRM_TAKEOVER, + KEPT_POPUP, + KEPT_TREE, + NIGHT_HINTS, + NIGHT_LOOK, + NIGHT_MENU, + NIGHT_PICK, + OPEN_DELETE, + OPEN_TAKEOVER, + ORDER_MOVED, + ORG_FOLDED, + ORG_OPEN, + PIN, +) +from hub_e2e_kit import OUT, WIDTHS +from hub_support import verifier +from kvb_orchestrator import messaging, skill_scripts +from test_hub_cleanup import DONE_TIP, FAKE_PKGMGR, host +from test_hub_offices import COUNCIL_SCRIPT +from test_hub_offices import host as office_host + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestHubBoard(base.OrchestratorE2ECase): + def check_night_menu(self, browser: str, driver: str, binary: str, signs: bool) -> None: + """Args: + signs: cdp.mjs signs every prompt with its virtual passkey; bidi.mjs + has no virtual authenticator, so the probe answers each prompt + the way a canceled passkey dialog does. + """ + authenticator = self.authenticator() + probe = NIGHT_MENU.replace("@SIGNS@", "true" if signs else "false") + looks = [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}#agents/orbit", "wait": 1200, "probe": NIGHT_LOOK, "shot": str(OUT / f"{browser}-{width}-night-menu-tooltips.png")} for width, height in WIDTHS] + step = {"width": 1366, "height": 768, "url": f"http://localhost:{self.port}/#agents/orbit", "wait": 1200, "probe": probe, "shot": str(OUT / f"{browser}-1366-night-menu.png")} + data = self.drive([*looks, step], authenticator if signs else None, driver, binary) + (OUT / f"{browser}-night-menu.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], []) + *seen, found = data["results"] + for look, (width, _) in zip(seen, WIDTHS, strict=True): + with self.subTest(browser=browser, width=width): + self.assertNotIn("error", look) + self.assertEqual(look["children"], [["span", ""], ["div", "night-picks"], ["div", "actions"]]) + self.assertEqual((look["badge"], look["paragraphs"], look["wide"]), (["Day"], 0, False)) + self.assertEqual(look["picks"], [["All", True], ["Skills", True], ["Stage", True]]) + self.assertEqual(look["buttons"], [list(entry) for entry in NIGHT_HINTS]) + self.assertNotIn("error", found) + self.assertEqual(found["labels"], ["Drain", "Suspend", "Resume"]) + for run, action in zip(found["runs"], ("drain", "suspend", "resume"), strict=True): + with self.subTest(browser=browser, action=action): + self.assertEqual(run["asked"], 1, run) + self.assertEqual(len(run["question"]), 1, run) + self.assertIn(f"kvb-agent-{action}", run["question"][0]) + signed = [["/api/board/sign", ["action"], action]] + if signs: + self.assertEqual(run["posted"], [*signed, [f"/api/board/{action}", ["proof"], None]]) + self.assertTrue((run["toast"] or "").startswith(f"{run['label']}: done"), run) + else: + self.assertEqual(run["posted"], signed) + self.assertTrue((run["toast"] or "").startswith(f"{run['label']}: not signed"), run) + nights = [args for script, args in self.scripts.calls if script == skill_scripts.NIGHT] + self.assertEqual(nights, [[action, "--session", "Operator"] for action in ("drain", "suspend", "resume")] if signs else []) + if not signs: + self.assertEqual(self.scripts.calls, []) + + def test_chromium_runs_drain_suspend_and_resume_only_after_the_passkey_signs(self): + self.check_night_menu("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium"), signs=True) + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_asks_the_passkey_for_drain_suspend_and_resume_and_runs_nothing_unsigned(self): + self.check_night_menu("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox"), signs=False) + + def check_night_picks(self, browser: str, driver: str, binary: str, signs: bool) -> None: + """Args: + signs: as in check_night_menu. + """ + self.write_council({"night.json": {"parts": {"s2": "drain"}}}) + probe = NIGHT_PICK.replace("@SIGNS@", "true" if signs else "false") + steps = [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}#agents/orbit", "wait": 1200, "probe": probe, "shot": str(OUT / f"{browser}-{width}-night-picks.png")} for width, height in WIDTHS] + data = self.drive(steps, self.authenticator() if signs else None, driver, binary) + (OUT / f"{browser}-night-picks.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], []) + everyone, one, nobody = [["All", True], ["Skills", True], ["Stage", True]], [["All", False], ["Skills", False], ["Stage", True]], [["All", False], ["Skills", False], ["Stage", False]] + for found, (width, _) in zip(data["results"], WIDTHS, strict=True): + with self.subTest(browser=browser, width=width): + 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": ["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]) + self.assertEqual([found["drain"].split("$")[0].split()[1], found["suspend"].split("$")[0].split()[1]], ["done", "done"] if signs else ["not", "not"]) + nights = [args for script, args in self.scripts.calls if script == skill_scripts.NIGHT] + self.assertEqual(nights, [[action, "--session", "Operator", "--target=s2"] for _ in WIDTHS for action in ("drain", "suspend")] if signs else []) + calls = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO] + self.assertEqual(calls, [["send", "call", "--to", "Stage", "--session", "Operator", messaging.ALONE[action]] for _ in WIDTHS for action in ("drain", "suspend")] if signs else []) + + def test_chromium_drains_and_suspends_chosen_agents_from_the_menu_and_the_agent_panel_at_three_widths(self): + self.check_night_picks("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium"), signs=True) + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_asks_the_passkey_for_chosen_agents_and_runs_nothing_unsigned_at_three_widths(self): + self.check_night_picks("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox"), signs=False) + + def test_chromium_deletes_a_merged_branch_after_dry_run_and_signature(self): + tree = json.loads(self.tree_file.read_text(encoding="utf-8")) + tree["delete_ready"], tree["delete_reason"] = True, "" + next(item for item in tree["repos"][0]["items"] if item["branch"] == "feature/done").update(worktree=None, worktree_state=None, actions=["local-branch", "remote-branch"], compose_projects=[], images=[], merged_by="ancestor") + self.tree_file.write_text(json.dumps(tree), encoding="utf-8") + self.write_local_plan(tree, {}) + demo = f"{self.root}/repos/github.com/me/demo" + Path(demo).mkdir(parents=True) + fake = self.outside / "bin" / "pkgmgr" + fake.parent.mkdir() + fake.write_text(FAKE_PKGMGR.format(python=sys.executable), encoding="utf-8") + fake.chmod(0o755) + (fake.parent / "plan.json").write_text(json.dumps([{"branch": "feature/done", "worktree": None, "local_sha": DONE_TIP, "head": DONE_TIP, "state": "merged-clean", "merged_by": "ancestor", "skip": None, "actions": ["local-branch"]}]), encoding="utf-8") + following = json.loads(json.dumps(tree)) + following["repos"][0]["items"] = [item for item in following["repos"][0]["items"] if item["branch"] != "feature/done"] + (fake.parent / "next-tree.json").write_text(json.dumps(following), encoding="utf-8") + authenticator = self.authenticator() + trust = verifier.Trust(approvers=self.approvers, replay=self.replay / "cleanup.json", origin=self.origin) + runner = host.Cleanup(trust, self.tree_file, fake) + jobs, results = self.cleanup / "jobs", self.cleanup / "results" + self.beside(lambda: any(jobs.iterdir()) and host.cycle(jobs, results, runner)) + local = f"http://localhost:{self.port}/" + steps = [ + {"width": 1366, "height": 768, "url": f"{local}#artifacts/tree", "wait": 1200, "probe": OPEN_DELETE, "shot": self.shot("1366-delete-dry-run")}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": CONFIRM, "shot": self.shot("1366-delete-result")}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": AFTER, "shot": self.shot("1366-delete-tree-after")}, + ] + data = self.drive(steps, authenticator) + (OUT / "chromium-delete.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + opened, confirmed, after = data["results"] + self.assertNotIn("error", opened) + self.assertEqual(opened["every"], [False, "Delete all merged: 1 branches after dry run and signature"]) + self.assertEqual(opened["buttons"], [[False, "Delete: remove feature/done locally, after dry run and signature"]]) + self.assertEqual(opened["title"], "Delete feature/done") + self.assertEqual(len(opened["dry"]), 1) + self.assertTrue(opened["dry"][0].startswith("feature/done @ 5b1e6fd3a7c0: merged-clean, merged by ancestor"), opened["dry"]) + self.assertIn("stays: remote-branch (local only; the host refuses a plan that deletes it)", opened["dry"][0]) + self.assertEqual((confirmed["result"], confirmed["text"]), ("done", "feature/donedeleted"), confirmed) + self.assertEqual(confirmed["toasts"], ["Delete: donefeature/done: deleted"]) + self.assertEqual(after["past"], ["done", "deleted"]) + self.assertNotIn("feature/done", after["branches"]) + written = [json.loads(path.read_text(encoding="utf-8")) for path in results.glob("*.json")] + self.assertEqual([[(item["branch"], item["status"]) for item in result["items"]] for result in written], [[("feature/done", "done")]]) + calls = [json.loads(line)["argv"] for line in (fake.parent / "calls.jsonl").read_text(encoding="utf-8").splitlines()] + self.assertEqual(calls, [ + ["branch", "cleanup", "--local", "--json", "--branch", "feature/done"], + ["branch", "cleanup", "--apply", "--local", "--json", "--branch", "feature/done"], + ["branch", "tree", "--format", "json", "--output", str(self.tree_file)], + ]) + + def test_chromium_shows_a_branch_the_local_dry_run_keeps_without_delete_and_offers_one_whose_local_tip_it_deletes(self): + squashed_tip, cherry_tip, cherry_remote = "9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b", "8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c", "7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d" + tree = json.loads(self.tree_file.read_text(encoding="utf-8")) + tree["delete_ready"], tree["delete_reason"] = True, "" + items = tree["repos"][0]["items"] + kept = next(item for item in items if item["branch"] == "feature/kept") + kept["skip"] = None + items.append({**kept, "branch": "feature/squashed", "local_sha": squashed_tip, "upstream": "origin/feature/squashed", "ahead": 0, "behind": 0, "remotes": {"origin": squashed_tip}, + "merged_by": "pr#7", "actions": ["local-branch", "remote-branch:origin"], "reason": "merged by pr#7"}) + items.append({**kept, "branch": "feature/cherry", "local_sha": cherry_tip, "upstream": "origin/feature/cherry", "ahead": 0, "behind": 1, "remotes": {"origin": cherry_remote}, + "merged_by": "patch", "actions": ["local-branch", "remote-branch:origin"], "reason": "merged by patch"}) + self.tree_file.write_text(json.dumps(tree), encoding="utf-8") + self.write_local_plan(tree, {"feature/cherry": {"skip": None, "actions": ["local-branch"]}}) + demo = f"{self.root}/repos/github.com/me/demo" + local = f"http://localhost:{self.port}/" + steps = [ + {"width": 1366, "height": 768, "url": f"{local}#artifacts/tree", "wait": 1200, "probe": KEPT_TREE, "shot": self.shot("1366-kept-tree")}, + {"width": 1366, "height": 768, "url": f"{local}?kept#artifacts/orbit", "wait": 1200, "probe": KEPT_POPUP.replace("@REPO@", json.dumps(demo)), "shot": self.shot("1366-kept-popup")}, + ] + data = self.drive(steps, None) + (OUT / "chromium-kept.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], []) + shown, popup = data["results"] + self.assertNotIn("error", shown, shown) + self.assertNotIn("error", popup, popup) + kept_line = "pkgmgr branch cleanup --local keeps it: merged by pr#7, tip is no ancestor of refs/remotes/origin/main; use branch gc (kvb-git-gc, pkgmgr gc)" + plan = f"feature/squashed @ {squashed_tip[:12]}: merged-clean, merged by pr#7\n{kept_line}\nbranch gc would delete the local branch feature/squashed\nbranch gc would delete remote-branch:origin" + self.assertEqual((shown["kept"], shown["rowDeletes"], shown["deletes"]), ([kept_line, kept_line], 0, ["feature/kept", "feature/cherry"])) + self.assertIn("1 kept by the --local dry run: see each dry run", shown["header"]) + self.assertEqual([row[:3] for row in shown["rows"]], [["feature/kept", None, 0], ["feature/cherry", None, 0], ["feature/done", "held", 0], ["feature/squashed", "kept", 0]]) + self.assertEqual(shown["rows"][1][3], f"feature/cherry @ {cherry_tip[:12]}: merged-clean, merged by patch\ndeletes the local branch feature/cherry\nstays: remote-branch:origin (local only; the host refuses a plan that deletes it)") + self.assertEqual(shown["rows"][3][3], plan) + self.assertEqual((shown["confirms"], shown["title"]), (1, "Delete 2 merged branches")) + self.assertEqual((popup["title"], popup["heading"], popup["dry"], popup["deletes"], popup["kept"]), ("feature/squashed", "Dry run", plan, 0, kept_line)) + status, _, body = self.post_json("/api/sign", {"items": [{"kind": "cleanup", "repository": demo, "branch": "feature/squashed", "worktree": "", "tip": squashed_tip}]}, self.guard(self.host)) + self.assertEqual((status, body.decode()), (400, f"feature/squashed in {demo} is no merged-clean branch without skip reason that the --local dry run deletes at that tip\n")) + self.assertEqual(list((self.cleanup / "jobs").glob("*.json")), []) + + def test_chromium_folds_the_hierarchy_by_keyboard_reorders_agents_and_hands_an_office_over_with_a_signature(self): + signer = self.pin() + trust = verifier.Trust(approvers=self.approvers, replay=self.replay / "offices.json", origin=self.origin) + runner = office_host.Offices(trust, self.council, COUNCIL_SCRIPT, self.outside / "home") + jobs, results = self.offices / "jobs", self.offices / "results" + self.beside(lambda: any(jobs.iterdir()) and office_host.cycle(jobs, results, runner)) + private = "".join(line for line in signer.pem.read_text(encoding="utf-8").splitlines() if not line.startswith("-----")) + authenticator = {"credentialId": base64.b64encode(signer.raw_id).decode(), "privateKey": private, "rpId": "localhost"} + local = f"http://localhost:{self.port}/" + steps = [ + {"width": 1366, "height": 768, "url": f"{local}#agents/hierarchy", "wait": 1200, "probe": ORG_OPEN, "shot": self.shot("1366-hierarchy-open")}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "keys": ["Enter"], "probe": ORG_FOLDED, "shot": None}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "keys": ["Enter"], "probe": ORDER_MOVED, "shot": self.shot("1366-hierarchy-order")}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": OPEN_TAKEOVER, "shot": self.shot("1366-hierarchy-takeover")}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": CONFIRM_TAKEOVER, "shot": self.shot("1366-hierarchy-takeover-result")}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": AFTER_TAKEOVER, "shot": self.shot("1366-hierarchy-after")}, + ] + data = self.drive(steps, authenticator) + (OUT / "chromium-hierarchy.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + opened, folded, moved, sheet, confirmed, after = data["results"] + self.assertNotIn("error", opened) + self.assertEqual(opened["focused"], "toggle:dimension:identity") + self.assertEqual((folded["focused"], folded["expanded"], folded["label"], folded["hidden"], folded["again"]), ("toggle:dimension:identity", "false", "Expand: identity", True, "true")) + self.assertNotIn("identity/oidc", folded["seen"]) + before = folded["before"] + self.assertEqual(moved["after"], [before[1], before[0], *before[2:]]) + self.assertEqual((moved["focused"], moved["disabled"]), (f"down:{before[1]}", False)) + self.assertTrue(moved["toast"].startswith("Priority"), moved) + self.assertIn(("rasci.py", ["agents", "order", ",".join(moved["after"])]), [(Path(script).name, args) for script, args in self.scripts.calls]) + self.assertEqual((sheet["title"], sheet["options"], sheet["work"], sheet["focused"]), ("identity/oidc: Hand over", ["s1"], "oidc line", "SELECT")) + self.assertEqual((confirmed["result"], confirmed["text"]), ("done", "identity/oidcdone"), confirmed) + self.assertIn("Hand over: doneidentity/oidc: done", confirmed["toasts"]) + self.assertNotIn("error", after) + claim = json.loads((self.council / "identity" / "oidc" / "claim.json").read_text(encoding="utf-8")) + self.assertEqual((claim["session"], claim["work"]), ("s1", "oidc line")) + written = [json.loads(path.read_text(encoding="utf-8")) for path in results.glob("*.json")] + self.assertEqual([[(item["office"], item["action"], item["status"]) for item in result["items"]] for result in written], [[("identity/oidc", "takeover", "done")]]) + + def test_chromium_pins_a_task_priority_after_signature_and_the_runner_applies_it(self): + signer = self.pin() + private = "".join(line for line in signer.pem.read_text(encoding="utf-8").splitlines() if not line.startswith("-----")) + authenticator = {"credentialId": base64.b64encode(signer.raw_id).decode(), "privateKey": private, "rpId": "localhost"} + local = f"http://localhost:{self.port}/" + data = self.drive([{"width": 1366, "height": 768, "url": f"{local}#tasks/list", "wait": 1200, "probe": PIN, "shot": self.shot("1366-tasks-priority-signed")}], authenticator) + (OUT / "chromium-task-priority.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + pinned = data["results"][0] + self.assertNotIn("error", pinned) + self.assertEqual((pinned["title"], pinned["preview"][0]), ("work/docs", "rasci.py set work/docs --prio 2")) + self.assertEqual(pinned["toasts"], ["Priority work/docs: handed to the runnerrasci.py set work/docs --prio 2"]) + jobs = self.runner_jobs() + self.assertEqual([(job["id"], job["kind"], job["argv"]) for job in jobs], [(pinned["jobs"], "task", ["set", "work/docs", "--prio", "2"])]) + self.run_runner() + register = json.loads((self.council / "rasci.json").read_text(encoding="utf-8")) + self.assertEqual((register["work/docs"]["prio"], register["work/feature"]["prio"]), (2, 1)) + self.assertEqual([(row["task"], row["prio"]) for row in self.snapshot()["tasks"][:2]], [("work/feature", 1), ("work/docs", 2)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_hub_bubble_faces_e2e.py b/tests/e2e/test_hub_bubble_faces_e2e.py index b155793..41589a8 100644 --- a/tests/e2e/test_hub_bubble_faces_e2e.py +++ b/tests/e2e/test_hub_bubble_faces_e2e.py @@ -13,7 +13,7 @@ from unittest import mock HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase from hub_support import iso @@ -160,8 +160,8 @@ def probe(template: str) -> str: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestHubBubbleFrontAndSpawnFaces(HubCase): - drive = base.TestOrchestratorE2E.drive - subagents = base.TestOrchestratorE2E.subagents + drive = base.OrchestratorE2ECase.drive + subagents = base.OrchestratorE2ECase.subagents def setUp(self): super().setUp() diff --git a/tests/e2e/test_hub_bubbles_live_e2e.py b/tests/e2e/test_hub_bubbles_live_e2e.py index a307e6d..58050d6 100644 --- a/tests/e2e/test_hub_bubbles_live_e2e.py +++ b/tests/e2e/test_hub_bubbles_live_e2e.py @@ -13,7 +13,7 @@ from unittest import mock HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase from hub_support import iso @@ -108,8 +108,8 @@ PROBE = """(async () => {@HELPERS@ shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium" ) class TestLiveBubbles(HubCase): - drive = base.TestOrchestratorE2E.drive - beside = base.TestOrchestratorE2E.beside + drive = base.OrchestratorE2ECase.drive + beside = base.OrchestratorE2ECase.beside def setUp(self): super().setUp() diff --git a/tests/e2e/test_hub_context_menu_e2e.py b/tests/e2e/test_hub_context_menu_e2e.py new file mode 100644 index 0000000..4561732 --- /dev/null +++ b/tests/e2e/test_hub_context_menu_e2e.py @@ -0,0 +1,201 @@ +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-context-menu-shots")) +GAP = 8 +TASK = ["element", "Task work/feature", ["Open task", "Copy task id", "Pin to Home"]] +TASKS_TAB = ["tasks", "Tasks", ["Tasks: List", "Tasks: Board", "Tasks: RASCI", "Tasks: Gantt", "Tasks: Burndown and burnup", "Tasks: 3D"]] +GENERAL_HEAD = [f"View: {tab}" for tab in base.TABS] + ["Radio …", "Cancel mayday", "Drain", "Suspend", "Resume", "Settings …"] +GENERAL_TAIL = ["Look at the sky", "Toggle control room", "Enable notifications", "Keyboard shortcuts"] +MOVES = ["Copy task id", "Pin to Home", "Copy task id", "Keyboard shortcuts", "Open task", "Keyboard shortcuts"] +MENU = base.UNLABELLED + """ + const shownMenu = () => document.querySelector(".ctx-menu:not([hidden])"); + const itemLabel = (node) => (node && node.closest('[role="menuitem"]') ? text(node.closest('[role="menuitem"]').querySelector(".ctx-label")) : null); + const key = (word, extra) => (document.activeElement || document.body).dispatchEvent(new KeyboardEvent("keydown", {key: word, bubbles: true, cancelable: true, ...extra})); + const menuState = () => { + const menu = shownMenu(); + if (!menu) { + return {open: false}; + } + const box = menu.getBoundingClientRect(); + return { + open: true, role: menu.getAttribute("role"), roles: [...new Set(all("button", menu).map((node) => node.getAttribute("role")))], + groups: all('[role="group"]', menu).map((group) => [group.dataset.scope, group.getAttribute("aria-label"), all('[role="menuitem"]', group).map(itemLabel)]), + box: [box.left, box.top, box.right, box.bottom].map(Math.round), focused: itemLabel(document.activeElement), + wide: document.documentElement.scrollWidth > innerWidth + 1, unlabelled: unlabelled(menu), + }; + }; + const rowOf = () => document.querySelector('#main li.task-row[data-task="work/feature"]'); + const cardOf = () => document.querySelector('#main .kanban-card[data-task="work/feature"]'); +""" +MOUSE = """(async () => {@HELPERS@@MENU@ + await screenShown(8000); + const row = await until(rowOf, 10000); + if (!row) { + return {error: text(document.getElementById("main"))}; + } + row.scrollIntoView({block: "center"}); + await sleep(300); + const spot = row.querySelector("code.task-id"); + const box = spot.getBoundingClientRect(); + const at = {clientX: Math.round(box.left + box.width / 2), clientY: Math.round(box.top + box.height / 2)}; + const prevented = !spot.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, button: 2, ...at})); + await sleep(200); + return {prevented, at: [at.clientX, at.clientY], ...menuState()}; +})()""" +STEER = """(async () => {@HELPERS@@MENU@ + const moves = []; + for (const word of ["ArrowDown", "ArrowDown", "ArrowUp", "End", "Home", "ArrowUp"]) { + key(word); + moves.push(itemLabel(document.activeElement)); + } + key("Escape"); + await sleep(100); + const closed = !shownMenu(); + const spot = rowOf().querySelector("code.task-id"); + const box = spot.getBoundingClientRect(); + const passed = spot.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, button: 2, shiftKey: true, clientX: box.left + 2, clientY: box.top + 2})); + await sleep(100); + const shift = {passed, open: Boolean(shownMenu())}; + key("k", {ctrlKey: true}); + await sleep(200); + const palette = all("#palette:not([hidden]) .palette-list li").map((li) => text(li.querySelector("span"))); + key("Escape"); + await sleep(100); + return {moves, closed, shift, palette, paletteClosed: document.getElementById("palette").hidden}; +})()""" +KEYED = """(async () => {@HELPERS@@MENU@ + await screenShown(8000); + const card = await until(cardOf, 10000); + if (!card) { + return {error: text(document.getElementById("main"))}; + } + card.scrollIntoView({block: "center"}); + await sleep(300); + card.focus(); + const anchor = card.getBoundingClientRect(); + const prevented = !key("ContextMenu"); + await sleep(200); + return {prevented, at: [Math.round(anchor.left), Math.round(anchor.bottom)], ...menuState()}; +})()""" +RUN = """(async () => {@HELPERS@@MENU@ + const first = itemLabel(document.activeElement); + key("Enter"); + const sheet = await until(() => all('#sheet:not([hidden]) [role="dialog"]').find((node) => node.getAttribute("aria-label") === "work/feature"), 4000); + await sleep(200); + return {first, closed: !shownMenu(), sheet: Boolean(sheet)}; +})()""" +SHIFT_F10 = """(async () => {@HELPERS@@MENU@ + document.querySelector('#sheet:not([hidden]) .sheet-head button[aria-label="Close"]').click(); + await sleep(150); + const card = cardOf(); + card.focus(); + const prevented = !key("F10", {shiftKey: true}); + await sleep(150); + const opened = menuState(); + key("?"); + await sleep(100); + const help = Boolean(document.querySelector("#sheet:not([hidden])")); + return {prevented, element: opened.groups ? opened.groups[0] : null, closed: !shownMenu(), back: document.activeElement === cardOf(), help}; +})()""" + + +def probe(template: str) -> str: + return template.replace("@HELPERS@", base.HELPERS).replace("@MENU@", MENU) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestHubContextMenu(base.OrchestratorE2ECase): + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + + def steps(self, browser: str) -> list[dict]: + local = f"http://localhost:{self.port}/" + steps = [] + for width, height in base.WIDTHS: + shot = str(OUT / f"{browser}-{width}-context") + steps += [ + {"width": width, "height": height, "url": f"{local}?{width}-mouse#tasks/list", "wait": 1500, "probe": probe(MOUSE), "shot": f"{shot}-mouse.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(STEER), "shot": None}, + {"width": width, "height": height, "url": f"{local}?{width}-keyed#tasks/board", "wait": 1500, "probe": probe(KEYED), "shot": f"{shot}-key.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(RUN), "shot": f"{shot}-task-sheet.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(SHIFT_F10), "shot": None}, + ] + return steps + + def placed(self, menu: dict, at: list[int], size: tuple[int, int]) -> None: + """Args: + menu: the menuState of an open menu. + at: the viewport point the menu was opened at. + size: the viewport width and height. + """ + left, top, right, bottom = menu["box"] + width, height = size + self.assertTrue(0 <= left and right <= width and 0 <= top and bottom <= height, menu["box"]) + if at[0] + right - left <= width - GAP: + self.assertLessEqual(abs(left - at[0]), 1, (menu["box"], at)) + else: + self.assertGreaterEqual(right, width - GAP - 1, (menu["box"], at)) + if at[1] + bottom - top <= height - GAP: + self.assertLessEqual(abs(top - at[1]), 1, (menu["box"], at)) + else: + self.assertTrue(bottom <= at[1] + 1 or top <= GAP + 1, (menu["box"], at)) + + def grouped(self, menu: dict) -> None: + self.assertEqual((menu["open"], menu["role"], menu["roles"], menu["unlabelled"], menu["wide"]), (True, "menu", ["menuitem"], [], False), menu) + self.assertEqual(menu["groups"][:2], [TASK, TASKS_TAB]) + scope, title, general = menu["groups"][2] + self.assertEqual((scope, title, len(menu["groups"])), ("general", "General", 3)) + self.assertEqual(general[: len(GENERAL_HEAD)], GENERAL_HEAD) + self.assertEqual(general[-len(GENERAL_TAIL) :], GENERAL_TAIL) + self.assertIn(general[len(GENERAL_HEAD)], ("Music on", "Music off")) + self.assertEqual(menu["focused"], "Open task") + + def check(self, data: dict) -> None: + per = 5 + for index, (width, height) in enumerate(base.WIDTHS): + mouse, steer, keyed, ran, shifted = data["results"][per * index : per * (index + 1)] + with self.subTest(width=width): + for result in (mouse, steer, keyed, ran, shifted): + self.assertNotIn("error", result, result) + self.assertTrue(mouse["prevented"], mouse) + self.grouped(mouse) + self.placed(mouse, mouse["at"], (width, height)) + self.assertEqual((steer["moves"], steer["closed"]), (MOVES, True), steer) + self.assertEqual(steer["shift"], {"passed": True, "open": False}) + self.assertLessEqual({"View: Home", "Tasks: List", "Stage", "Priority …", "Keyboard shortcuts"}, set(steer["palette"]), steer["palette"]) + self.assertTrue(steer["paletteClosed"]) + self.assertTrue(keyed["prevented"], keyed) + self.grouped(keyed) + self.placed(keyed, keyed["at"], (width, height)) + self.assertEqual(ran, {"first": "Open task", "closed": True, "sheet": True}) + self.assertEqual(shifted, {"prevented": True, "element": TASK, "closed": True, "back": True, "help": False}) + + def run_browser(self, browser: str, driver: str, binary: str) -> None: + data = self.drive(self.steps(browser), None, driver, binary) + (OUT / f"{browser}-context-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], []) + self.check(data) + + def test_chromium_right_click_and_menu_key_open_the_grouped_context_menu_and_run_an_item_at_three_widths(self): + self.run_browser("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium")) + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_right_click_and_menu_key_open_the_grouped_context_menu_and_run_an_item_at_three_widths(self): + self.run_browser("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_hub_inbox_e2e.py b/tests/e2e/test_hub_inbox_e2e.py new file mode 100644 index 0000000..f0399e1 --- /dev/null +++ b/tests/e2e/test_hub_inbox_e2e.py @@ -0,0 +1,284 @@ +from __future__ import annotations + +import base64 +import json +import os +import shutil +import subprocess +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_e2e_inbox import ( + ACCEPT, + CHOICE_ANSWER, + CHOICE_REQUEST, + CHOICE_SEND, + CHOICE_VIEW, + DENIED, + DENY, + DENY_SHEET, + INBOX_PICK, + LAYOUT, + RUN_DONE, + RUN_HELD, + RUN_START, + SLOW, + TASKS_FIT, +) +from hub_e2e_kit import CHOICE_CHANNELS, OUT, TASK_VIEWS, WIDTHS +from hub_support import ASK, OPTIONS, RUNNER +from kvb_orchestrator import batches, skill_scripts + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestHubInbox(base.OrchestratorE2ECase): + def inbox_work(self) -> None: + stage = {"title": "Stage line", "status": "running", "worker": "Stage (this session)", "roles": {"Stage (this session)": "RA"}} + greet = {"title": SLOW, "workdir": str(self.outside), "description": "counts", "check": "manual", "status": "queued", "roles": {"Operator": "R", "Skills session": "A"}} + push = {"title": "git push", "workdir": "/repo", "description": "ship", "check": "manual", "status": "queued", "roles": {"Operator": "R", "Skills session": "A"}} + self.write_council({"rasci.json": {"work/stage": stage, "operator/greet": greet, "operator/push": push}}) + arguments = {"kind": "ask", "tool": "Bash", "pattern": "make deploy", "scope": "/repo*", "expires": int(time.time()) + 7 * 86400, "agent": "Skills", "why": "deploy runs after every green gate"} + self.assertFalse(self.tool("rule_request", arguments)["isError"]) + + def layout(self, probe: dict) -> None: + self.assertNotIn("error", probe) + self.assertEqual(sorted(probe["kinds"]), ["Ask", "Operator", "Operator", "Review", "Rule request"]) + self.assertIn(["Deny", "Deny via …"], probe["splits"]) + self.assertEqual(len(probe["splits"]), 4) + self.assertEqual(probe["fields"], ["Kind", "Tool (glob)", "Pattern (glob)", "Directory (glob)", "Expires on"]) + self.assertEqual(probe["dry"], "Dry run: the rule would have granted 1 of 1 asks from the last 7 days.") + self.assertEqual(probe["accept"], 1) + self.assertTrue(probe["fits"] and probe["followed"], probe) + self.assertEqual((probe["unlabelled"], probe["wide"]), ([], False)) + + def test_chromium_runs_a_command_into_its_console_denies_by_call_and_accepts_a_rule(self): + self.inbox_work() + signer = self.pin() + trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "runner.json")] + + def run_jobs() -> None: + if any(job["status"] == "queued" for job in self.httpd.hub.jobs.listed()): + subprocess.run([sys.executable, str(RUNNER), "--port", str(self.port), "--interval", "0.1", *trust, "--once"], capture_output=True, timeout=120, check=False) + + self.beside(run_jobs) + private = "".join(line for line in signer.pem.read_text(encoding="utf-8").splitlines() if not line.startswith("-----")) + authenticator = {"credentialId": base64.b64encode(signer.raw_id).decode(), "privateKey": private, "rpId": "localhost"} + inbox = f"http://localhost:{self.port}/#stream/inbox" + steps = [ + {"width": 1366, "height": 768, "url": inbox, "wait": 1200, "probe": RUN_START, "shot": self.shot("1366-inbox-console-running")}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": RUN_HELD, "shot": self.shot("1366-inbox-console-scrolled-up")}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": RUN_DONE, "shot": self.shot("1366-inbox-console-done")}, + ] + for width, height in WIDTHS: + fresh = f"http://localhost:{self.port}/?{width}#stream/inbox" + steps.append({"width": width, "height": height, "url": fresh, "wait": 1200, "probe": LAYOUT, "shot": self.shot(f"{width}-inbox-console")}) + steps.append({"width": width, "height": height, "url": None, "wait": 0, "probe": DENY_SHEET, "shot": self.shot(f"{width}-inbox-deny-sheet")}) + steps += [ + {"width": 1366, "height": 768, "url": inbox, "wait": 1200, "probe": DENY, "shot": self.shot("1366-inbox-deny-undo")}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": DENIED, "shot": None}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": ACCEPT, "shot": self.shot("1366-inbox-rule-accepted")}, + ] + data = self.drive(steps, authenticator) + (OUT / "chromium-inbox.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + started, held, done, *rest = data["results"] + self.assertNotIn("error", started) + self.assertIn("takes effect in", started["toast"]) + self.assertTrue(started["running"].startswith("running"), started) + self.assertTrue(started["overflows"] and started["followed"], started) + self.assertLess(held["held"], 50, held) + self.assertEqual((done["last"], done["lines"], done["followed"]), ("finished", 81, True)) + self.assertRegex(done["done"], r"^doneExit code 0 after \d+ s$") + self.assertIn("Close", done["actions"]) + layouts, sheets = rest[0:6:2], rest[1:6:2] + for probe, sheet, (width, _) in zip(layouts, sheets, WIDTHS, strict=True): + with self.subTest(width=width): + self.layout(probe) + self.assertTrue(probe["console"].startswith("doneExit code 0"), probe) + self.assertEqual(sheet["title"], "Deny") + self.assertEqual(sheet["channels"], [["post", True], ["call", False], ["newsletter", False], ["broadcast", False], ["pan-pan", False], ["security", False]]) + self.assertEqual(sheet["hints"][:3], ["to Skills, when its turn ends", "to Skills, at once, wakes it", "to all, when their turn ends"]) + self.assertEqual((sheet["reason"], sheet["unlabelled"], sheet["wide"]), (True, [], False)) + denied, gone, accepted = rest[6:] + self.assertNotIn("error", denied, denied) + self.assertTrue(denied["undo"].startswith("Denial (Call): Bash: make deploy"), denied) + self.assertFalse(denied["sheet"]) + self.assertTrue(gone["gone"]) + self.assertEqual((accepted["toast"], accepted["left"]), ("Created: Rule: ask Bash make deploy in /repo*", False)) + ask = self.httpd.hub.asks.listed()[0] + self.assertEqual((ask["status"], ask["reason"], ask["channel"]), ("denied", "make the gate green first", "call")) + calls = [args for script, args in self.scripts.calls if script.endswith("radio.py")] + self.assertEqual(calls[-1][:4], ["send", "call", "--to", "Skills session"]) + self.assertTrue(calls[-1][-1].endswith("Reason: make the gate green first"), calls[-1]) + self.assertEqual([(rule["kind"], rule["pattern"], rule["proof"] is not None) for rule in self.httpd.hub.rules.listed()], [("ask", "make deploy", True)]) + self.assertEqual([(job["status"], job["code"]) for job in self.httpd.hub.jobs.listed()], [("done", 0)]) + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_draws_the_inbox_console_and_the_rule_request_at_three_widths(self): + self.inbox_work() + now = time.time() + fields = {"task": "operator/greet", "command": SLOW, "directory": str(self.outside), "sha256": "", "status": "done", "proof": None} + output = "".join(f"Row {number}\n" for number in range(1, 81)) + "finished\n" + self.httpd.hub.jobs.add({**fields, "code": 0, "output": output, "created_ts": now - 20, "started": now - 19, "finished": now - 10, "dismissed": False}) + shots = [(width, height, OUT / f"firefox-{width}-inbox-console.png") for width, height in WIDTHS] + steps = [{"width": width, "height": height, "url": f"{self.base}#stream/inbox", "wait": 1200, "probe": LAYOUT, "shot": str(shot)} for width, height, shot in shots] + data = self.drive(steps, None, "bidi.mjs", os.environ.get("FIREFOX", "firefox")) + (OUT / "firefox-inbox.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], []) + for probe, (width, _, shot) in zip(data["results"], shots, strict=True): + with self.subTest(width=width): + self.layout(probe) + self.assertEqual(probe["console"], "doneExit code 0 after 9 s") + self.assertTrue(shot.is_file() and shot.stat().st_size > 1000, shot) + + def check_inbox_picks(self, browser: str, driver: str, binary: str, signs: bool) -> None: + """Args: + signs: as in check_night_menu. + """ + fill = {"description": "fill", "workdir": "/repo", "status": "queued", "roles": {"Operator": "R", "Skills session": "A"}} + rows = {f"operator/row-{n:02}": {**fill, "title": f"echo row {n:02}", "check": "manual", "seq": n} for n in range(1, 15)} + rows["operator/name"] = {**fill, "title": "pick a name", "check": "decision", "seq": 15} + self.write_council({"rasci.json": rows}) + probe = INBOX_PICK.replace("@SIGNS@", "true" if signs else "false") + steps = [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}#stream/inbox", "wait": 1200, "probe": probe, "shot": str(OUT / f"{browser}-{width}-inbox-deny-selection.png")} for width, height in WIDTHS] + stops = [] + with mock.patch.object(batches, "UNDO", 0.3): + data = self.drive(steps, self.authenticator() if signs else None, driver, binary) + if signs: + self.settle(lambda: len([call for call in self.scripts.calls if call[0] == skill_scripts.RASCI]) >= 2 * len(WIDTHS)) + stops = [args for script, args in self.scripts.calls if script == skill_scripts.RASCI] + (OUT / f"{browser}-inbox-deny-selection.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], []) + denied = [] + for found, (width, _) in zip(data["results"], WIDTHS, strict=True): + with self.subTest(browser=browser, width=width): + self.assertNotIn("error", found) + self.assertGreater(found["before"], 0, found) + self.assertEqual((found["moved"], found["focused"], found["wide"]), (0, True, False), found) + self.assertTrue({"Grant selection (1)", "Deny selection (2)"} <= set(found["buttons"]), found["buttons"]) + self.assertEqual((sorted(found["listed"]), found["label"]), (sorted([found["title"], "pick a name"]), "Deny 2")) + task = f"operator/row-{found['title'][-2:]}" + items = sorted([[task, "reject", "post"], ["operator/name", "reject", "post"]]) + self.assertEqual([[path, sorted(entries)] for path, entries in found["posted"]], [["/api/sign", items], *([["/api/inbox/approve", items]] if signs else [])]) + self.assertIn("takes effect" if signs else "not signed", found["toast"]) + denied += [task, "operator/name"] + self.assertEqual(sorted(stops), sorted([["set", task, "--status", "stopped"] for task in denied]) if signs else []) + + def test_chromium_keeps_the_inbox_scroll_on_a_tick_and_denies_a_selection_with_one_signature_at_three_widths(self): + self.check_inbox_picks("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium"), signs=True) + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_keeps_the_inbox_scroll_on_a_tick_and_denies_nothing_unsigned_at_three_widths(self): + self.check_inbox_picks("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox"), signs=False) + + def choice_steps(self, browser: str, signs: bool, questions: dict[int, str]) -> list[dict]: + flag = "true" if signs else "false" + local = f"http://localhost:{self.port}/" + steps = [] + for index, (width, height) in enumerate(WIDTHS): + cards = len(WIDTHS) - index if signs else len(WIDTHS) + steps += [ + {"width": width, "height": height, "url": f"{local}?{width}#stream/inbox", "wait": 1200, "probe": CHOICE_VIEW.replace("@CARDS@", str(cards)), "shot": str(OUT / f"{browser}-{width}-tasks-choices.png")}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": CHOICE_SEND.replace("@SIGNS@", flag), "shot": str(OUT / f"{browser}-{width}-choice-request.png")}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": CHOICE_ANSWER.replace("@SIGNS@", flag).replace("@QUESTION@", questions[width]), "shot": str(OUT / f"{browser}-{width}-choice-answer.png")}, + *({"width": width, "height": height, "url": f"{local}?{width}#tasks/{view}", "wait": 900, "probe": TASKS_FIT, "shot": str(OUT / f"{browser}-{width}-tasks-{view}-fit.png")} for view in TASK_VIEWS), + ] + return steps + + def requested(self, sent: dict, signs: bool) -> None: + """Args: + sent: the CHOICE_SEND probe: two agents ticked, then every channel + button pressed once. + """ + labels = dict(zip(CHOICE_CHANNELS, ["Post", "Call", "Newsletter", "Broadcast", "Pan-Pan", "Sécurité", "Mayday"], strict=True)) + self.assertEqual(len(sent["picked"]), 2, sent) + self.assertEqual((sent["counted"], sent["fields"], sent["tall"], sent["wide"]), ("2", 0, False, False)) + self.assertEqual(sent["opened"], [True, len(CHOICE_CHANNELS)]) + self.assertEqual([run["channel"] for run in sent["runs"]], CHOICE_CHANNELS) + for run in sent["runs"]: + with self.subTest(channel=run["channel"]): + to = sent["picked"] if run["channel"] in ("post", "call") else ["*"] + signed = [["/api/choices/sign", ["class", "to"], run["channel"], to]] + self.assertEqual((run["disabled"], run["asked"], len(run["question"])), (False, 1, int(run["channel"] == "mayday")), run) + title = f"Choice request ({labels[run['channel']]}) to {', '.join(to) if to != ['*'] else 'all'}" + self.assertEqual(run["posted"], [*signed, ["/api/choices", ["class", "proof", "to"], run["channel"], to]] if signs else signed) + self.assertTrue((run["toast"] or "").startswith(f"{title}: {'sent' if signs else 'not signed'}"), run) + + def answered(self, result: dict, signs: bool) -> None: + self.assertNotIn("error", result) + self.assertEqual((result["title"], result["asked"], result["closed"], result["tall"], result["wide"]), ("Wait: your passkey signs this answer, a post to Stage", 1, [False, 0], False, False)) + signed = [["/api/sign", ["items"], None, None]] + self.assertEqual(result["posted"], [*signed, ["/api/inbox/approve", ["items", "proof"], None, None]] if signs else signed) + self.assertTrue((result["toast"] or "").startswith("Choice: Wait" + ("" if signs else ": not signed")), result) + self.assertEqual(result["gone"], True if signs else None) + + def check_choices(self, browser: str, driver: str, binary: str, signs: bool) -> None: + """Args: + signs: cdp.mjs signs every prompt with its virtual passkey; bidi.mjs + has no virtual authenticator, so the probes answer each prompt + the way a canceled passkey dialog does. + """ + self.inbox_work() + self.create_ask({**ASK, "command": "make choices", "timeout": 3600}) + authenticator = self.authenticator() + questions = {width: f"Pick a name at {width} px?" for width, _ in WIDTHS} + decisions = {width: self.tool("decision_request", {"question": question, "options": OPTIONS, "agent": "Stage", "recommended": ""})["structuredContent"]["id"] for width, question in questions.items()} + data = self.drive(self.choice_steps(browser, signs, questions), authenticator if signs else None, driver, binary) + (OUT / f"{browser}-choices.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], []) + per = 3 + len(TASK_VIEWS) + for index, (width, _) in enumerate(WIDTHS): + view, sent, answer, *fitted = data["results"][per * index : per * (index + 1)] + with self.subTest(browser=browser, width=width): + self.assertNotIn("error", view) + self.assertEqual(view["kinds"], ["Ask", "Choice", "Operator", "Review", "Rule request"]) + self.assertEqual(view["filter"], ["Waits on Operator", "true"]) + self.assertEqual(view["channels"], [[channel, label, channel in ("post", "call")] for channel, label in zip(CHOICE_CHANNELS, ["Post", "Call", "Newsletter", "Broadcast", "Pan-Pan", "Sécurité", "Mayday"], strict=True)]) + self.assertEqual((view["fields"], view["choices"], view["multi"], view["unlabelled"], view["tall"], view["wide"]), (0, 0, ["Request choices", False, 0, "0", 0], [], False, False)) + self.assertEqual(view["bar"], ["Tasks", view["bar"][1], ["toolbar", "chips", "body"]]) + self.assertEqual(view["bar"][1] == 1, width != 390, view["bar"]) + self.assertGreaterEqual(len(view["agents"]), 2, view) + self.assertIn(["Choice", ["Merge now", "Wait"]], view["cards"]) + self.requested(sent, signs) + self.answered(answer, signs) + for fit, name in zip(fitted, TASK_VIEWS, strict=True): + self.assertEqual((fit["hash"], fit["bar"], fit["choices"], fit["tall"], fit["wide"]), (f"#tasks/{name}", CHOICE_CHANNELS, 0, False, False), fit) + self.assertEqual((fit["rows"] == 1, fit["layout"]), (width != 390, ["toolbar", "chips", "body"]), fit) + if name == "board": + self.assertEqual(fit["columns"], ["queued", "running", "done"]) + hub = self.httpd.hub + if not signs: + self.assertEqual((self.scripts.calls, hub.messages.listed()), ([], [])) + self.assertEqual([hub.decisions.get(decision)["status"] for decision in decisions.values()], ["pending"] * len(WIDTHS)) + return + requests = [record for record in hub.messages.listed() if record["text"] == CHOICE_REQUEST] + self.assertEqual((len(requests), sorted({record["class"] for record in requests})), (len(WIDTHS) * 9, sorted(CHOICE_CHANNELS))) + for record in requests: + self.assertTrue(self.tool("operator_message", {"id": record["id"], "text": CHOICE_REQUEST, "to": record["to"]})["structuredContent"]["match"], record["id"]) + radio = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO] + self.assertEqual(len(radio), len(requests) + len(WIDTHS)) + for width, decision in decisions.items(): + with self.subTest(width=width): + state = self.tool("decision_wait", {"id": decision, "timeout_seconds": 0})["structuredContent"] + self.assertEqual((state["status"], state["choice"], state["answer"]), ("decided", "Wait", f"Choice for decision {decision} ({questions[width]}): Wait")) + found = self.tool("operator_message", {"id": state["message"], "text": state["answer"], "to": "Stage"})["structuredContent"] + self.assertEqual((found["match"], found["class"], found["to"]), (True, "post", "Stage")) + self.assertIn(["post", "--to", "Stage", "--session", "Operator", f"[kvb-orchestrator msg {state['message']}] {state['answer']}"], radio) + + def test_chromium_requests_choices_on_every_channel_and_signs_a_choice_at_three_widths(self): + self.check_choices("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium"), signs=True) + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_asks_the_passkey_for_every_choice_request_and_answer_and_sends_nothing_unsigned(self): + self.check_choices("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox"), signs=False) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_hub_organigram_e2e.py b/tests/e2e/test_hub_organigram_e2e.py index 633cfd1..6538948 100644 --- a/tests/e2e/test_hub_organigram_e2e.py +++ b/tests/e2e/test_hub_organigram_e2e.py @@ -11,7 +11,7 @@ from pathlib import Path HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase from hub_support import iso @@ -88,7 +88,7 @@ DASHED = [["identity/oidc", "identity/ldap", True], ["identity/oidc", "work/s3", @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestOrganigramE2E(HubCase): - drive = base.TestOrchestratorE2E.drive + drive = base.OrchestratorE2ECase.drive def setUp(self): super().setUp() diff --git a/tests/e2e/test_hub_plan_e2e.py b/tests/e2e/test_hub_plan_e2e.py new file mode 100644 index 0000000..5c5b865 --- /dev/null +++ b/tests/e2e/test_hub_plan_e2e.py @@ -0,0 +1,339 @@ +from __future__ import annotations + +import json +import math +import os +import shutil +import sys +import time +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +from hub_e2e_kit import GRAPH_HOOK, OUT, WIDTHS +from hub_e2e_plan import ( + BULK, + BURN, + ETA_LIST, + GANTT, + PLAN_VALUES, + POINTS_ON, + REQUEST, + STATUS_ORDER, + STEP_TIPS, + TASKS_3D, + TREND_DAYS, + TREND_RELOADED, + TREND_SET, +) +from hub_e2e_views import CAMERA +from hub_support import iso +from kvb_orchestrator import skill_scripts + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestHubPlan(base.OrchestratorE2ECase): + def plan_work(self, now: float) -> None: + register = json.loads((self.council / "rasci.json").read_text(encoding="utf-8")) + register["work/feature"]["start"] = iso(now - 1800) + register["work/stage"]["start"] = iso(now - 900) + register.update({ + "work/done-a": {"title": "Done A", "status": "done", "worker": "Stage", "branch": "feature/base", "start": iso(now - 36000), "end": iso(now - 28800), "roles": {"Stage": "RA"}, "estimates": {"Stage": {"value": 5, "complexity": 2}}}, + "work/done-b": {"title": "Done B", "status": "done", "worker": "Docs", "start": iso(now - 25200), "end": iso(now - 10800), "roles": {"Docs": "RA"}, "estimates": {"Docs": {"value": 3, "complexity": 2}}}, + "work/done-c": {"title": "Done C", "status": "done", "worker": "Docs", "start": iso(now - 14400), "end": iso(now - 10800), "roles": {"Docs": "RA"}}, + "work/next": {"title": "Next step", "status": "queued", "after": ["work/feature"], "roles": {"Skills": "R", "Maintainer": "A"}, "estimates": {"Skills": {"value": 8, "complexity": 3}}}, + "work/child": {"title": "Child of the base", "status": "queued", "base": "feature/base", "roles": {"Docs": "RA"}}, + }) + queue = json.loads((self.council / "queue.json").read_text(encoding="utf-8")) + queue["entries"] += [ + {"id": "deploy-4", "seq": 4, "kind": "deploy", "task": "work/stage", "workdir": "/repo", "session": "s2", "name": "Stage", "hotfix": None, "status": "active", "enqueued": now - 400, "granted": now - 300, "cmd": "make deploy"}, + {"id": "test-5", "seq": 5, "kind": "test", "task": "work/docs", "workdir": "/repo", "session": "s2", "name": "Docs", "hotfix": None, "status": "waiting", "enqueued": now - 60, "granted": None, "cmd": "make test"}, + ] + self.write_council({"rasci.json": register, "queue.json": queue}) + + def plan_steps(self, browser: str, signs: bool) -> list[dict]: + local = f"http://localhost:{self.port}/" + flag = "true" if signs else "false" + steps = [] + for width, height in WIDTHS: + bulk = BULK.replace("@SIGNS@", flag).replace("@VALUE@", PLAN_VALUES[width]) + steps += [ + {"width": width, "height": height, "url": f"{local}?{width}#tasks/gantt", "wait": 1200, "probe": GANTT, "shot": str(OUT / f"{browser}-{width}-tasks-gantt.png")}, + {"width": width, "height": height, "url": f"{local}?{width}#tasks/burn", "wait": 900, "probe": BURN, "shot": str(OUT / f"{browser}-{width}-tasks-burn.png")}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": POINTS_ON, "shot": None}, + {"width": width, "height": height, "url": f"{local}?{width}-reloaded#tasks/burn", "wait": 1200, "probe": REQUEST, "shot": str(OUT / f"{browser}-{width}-tasks-burn-points.png")}, + {"width": width, "height": height, "url": f"{local}?{width}-points#tasks/gantt", "wait": 1200, "probe": GANTT, "shot": str(OUT / f"{browser}-{width}-tasks-gantt-points.png")}, + {"width": width, "height": height, "url": f"{local}?{width}-list#tasks/list", "wait": 1200, "probe": bulk, "shot": str(OUT / f"{browser}-{width}-tasks-business-value.png")}, + ] + return steps + + def planned(self, probe: dict, points: bool) -> None: + hour = 3600 + edges = [["after", "work/feature", "work/next"], ["base", "work/done-a", "work/child"], ["queue", "queue/deploy-4", "queue/gate-3"], ["queue", "queue/gate-3", "queue/test-5"]] + self.assertEqual(probe["forecast"], ["always", [["always", "always"], ["points", "points only"], ["real", "real only"]]]) + self.assertEqual(probe["modes"], [["none", str(not points).lower()], ["points", str(points).lower()]]) + self.assertEqual((probe["request"], probe["inner"]), (points, True)) + self.assertEqual(sorted([kind, start, end] for kind, start, end, _ in probe["edges"]), sorted(edges)) + self.assertEqual({tip for *_, tip in probe["edges"]}, {"url(#gantt-tip)"}) + bars = {task: (forecast, start, end, tag) for task, forecast, start, end, tag in probe["bars"]} + self.assertNotIn("operator/push", bars) + self.assertEqual((bars["work/old"][0], bars["work/old"][3]), (False, "circle")) + self.assertEqual([bars[task][0] for task in ("work/feature", "work/stage", "queue/deploy-4", "work/done-a")], [False] * 4) + self.assertGreaterEqual(bars["work/feature"][2] - bars["work/feature"][1], 1800) + forecasts = ("work/next", "work/docs", "work/child", "queue/gate-3", "queue/test-5") + lengths = {task: round(bars[task][2] - bars[task][1], 3) for task in forecasts} + self.assertEqual(lengths, {"work/next": (4.5 if points else 2) * hour, "work/docs": (3 if points else 2) * hour, "work/child": 2 * hour, "queue/gate-3": 2 * hour, "queue/test-5": 2 * hour}) + self.assertTrue(all(bars[task][0] for task in forecasts)) + self.assertEqual((bars["work/next"][1], bars["queue/test-5"][1]), (bars["work/feature"][2], bars["queue/gate-3"][2])) + self.assertTrue(probe["hatched"] and all(probe["hatched"]), probe["hatched"]) + self.assertEqual(probe["real"], 0) + only = {task: (round(length, 3), tag) for task, length, tag in probe["pointsOnly"]} + dot = (0, "circle") + self.assertEqual(only, {"work/next": (4.5 * hour, "rect") if points else dot, "work/docs": (3 * hour, "rect") if points else dot, "work/child": dot, "queue/gate-3": dot, "queue/test-5": dot}) + + def check_plan(self, browser: str, driver: str, binary: str, signs: bool) -> None: + """Args: + signs: cdp.mjs signs the bulk business value with its virtual + passkey; bidi.mjs has no virtual authenticator, so the probe + answers the prompt the way a canceled passkey dialog does. + """ + self.plan_work(time.time()) + authenticator = self.authenticator() + data = self.drive(self.plan_steps(browser, signs), authenticator if signs else None, driver, binary) + (OUT / f"{browser}-plan.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], []) + rows = self.snapshot()["tasks"] + ranked = list(enumerate(rows)) + status_up = [row["task"] for _, row in sorted(ranked, key=lambda pair: (STATUS_ORDER.index(pair[1]["status"]), pair[0]))] + status_down = [row["task"] for _, row in sorted(ranked, key=lambda pair: (-STATUS_ORDER.index(pair[1]["status"]), pair[0]))] + for index, (width, _) in enumerate(WIDTHS): + gantt, burn, points_on, request, gantt_points, bulk = data["results"][6 * index : 6 * (index + 1)] + value = PLAN_VALUES[width] + items = [["work/next", f"estimate work/next Operator --value {value}"], ["work/child", f"estimate work/child Operator --value {value}"]] + with self.subTest(browser=browser, width=width): + for probe in (gantt, burn, points_on, request, gantt_points, bulk): + self.assertNotIn("error", probe) + self.assertEqual((probe["tall"], probe["wide"], probe["layout"]), (False, False, ["toolbar", "chips", "body"]), probe) + self.assertEqual(probe["rows"] == 1, width != 390, probe) + self.planned(gantt, points=False) + self.planned(gantt_points, points=True) + self.assertEqual((burn["modes"], burn["request"]), ([["none", "true"], ["points", "false"]], False)) + self.assertEqual(burn["scope"][0], "all") + self.assertEqual(burn["scope"][1][:2], ["all", "filter"]) + self.assertIn("agent:Docs", burn["scope"][1]) + self.assertIn("line:identity/oidc", burn["scope"][1]) + self.assertEqual(burn["series"], [["scope", 9], ["done", 4], ["remaining", 5]]) + self.assertEqual(burn["agent"], [["scope", 5], ["done", 2], ["remaining", 3]]) + self.assertEqual(points_on["before"], {"modes": [["none", "true"], ["points", "false"]], "request": False}) + self.assertEqual((points_on["modes"], points_on["request"]), ([["none", "false"], ["points", "true"]], True)) + self.assertEqual(request["modes"], [["none", "false"], ["points", "true"]]) + self.assertEqual(request["series"], [["scope", 12], ["done", 4], ["remaining", 8], ["unestimated", 2]]) + self.assertTrue(request["toast"].startswith(f"Request estimates: {'done' if signs else 'not signed'}"), request["toast"]) + self.assertEqual(bulk["sorts"], ["prio", "wsjf", "value", "complexity", "status", "start", "end", "agent", "title"]) + self.assertEqual((bulk["prio"], bulk["status"], bulk["statusDown"]), ([row["task"] for row in rows], status_up, [status_down, "Descending"])) + self.assertEqual((bulk["picks"], bulk["armed"]), (["work/feature", "work/next", "work/docs", "work/child", "work/stage"], [False, "2"])) + self.assertTrue(bulk["toast"].startswith(f"Business value {value} for 2 tasks: {'handed to the runner' if signs else 'not signed'}"), bulk["toast"]) + signed = [["/api/sign", ["items"], items]] + self.assertEqual((bulk["asked"], bulk["posted"]), (1, [*signed, ["/api/tasks", ["items", "proof"], items]] if signs else signed)) + self.assertEqual((bulk["after"], bulk["reset"]), ([True, 0] if signs else [False, 2], True)) + self.assertEqual([args for script, args in self.scripts.calls if script == skill_scripts.ESTIMATE], [["request", "--session", "Operator"]] * (len(WIDTHS) if signs else 0)) + self.assertEqual(self.httpd.hub.settings.get()["estimation"], "none") + jobs = self.runner_jobs() + if not signs: + self.assertEqual(jobs, []) + register = json.loads((self.council / "rasci.json").read_text(encoding="utf-8")) + self.assertEqual([task for task, row in register.items() if "Operator" in row.get("estimates", {})], []) + return + self.assertEqual([job["argv"][-1] for job in jobs], [PLAN_VALUES[width] for width, _ in WIDTHS for _ in range(2)]) + self.run_runner() + register = json.loads((self.council / "rasci.json").read_text(encoding="utf-8")) + self.assertEqual({task: register[task]["estimates"]["Operator"] for task in ("work/next", "work/child")}, {"work/next": {"value": 34, "at": register["work/next"]["estimates"]["Operator"]["at"]}, "work/child": {"value": 34, "at": register["work/child"]["estimates"]["Operator"]["at"]}}) + rows = {row["task"]: row for row in self.snapshot()["tasks"]} + self.assertEqual((rows["work/next"]["wsjf"], rows["work/child"]["wsjf"], rows["work/child"]["value"]), ({"value": 34, "complexity": 3, "score": 11.33}, None, 34)) + + def test_chromium_draws_the_gantt_and_burn_switches_the_estimation_requests_estimates_and_signs_a_bulk_business_value_at_three_widths(self): + self.check_plan("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium"), signs=True) + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_draws_the_gantt_and_burn_and_asks_the_passkey_for_a_bulk_business_value_storing_nothing_unsigned(self): + self.check_plan("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox"), signs=False) + + def trend_work(self, now: float) -> None: + day = 86400 + register = { + "work/t1": {"title": "First", "status": "done", "worker": "Stage", "start": iso(now - 10 * day), "end": iso(now - 8 * day), "roles": {"Stage": "RA"}, "estimates": {"Stage": {"value": 5, "complexity": 1}}}, + "work/t2": {"title": "Second", "status": "done", "worker": "Docs", "start": iso(now - 10 * day), "end": iso(now - 6 * day), "roles": {"Docs": "RA"}, "estimates": {"Docs": {"value": 3, "complexity": 2}}}, + "work/t3": {"title": "Third", "status": "done", "worker": "Docs", "branch": "feature/t3", "start": iso(now - 10 * day), "end": iso(now - 4 * day), "roles": {"Docs": "RA"}, "estimates": {"Docs": {"value": 3, "complexity": 3}}}, + "work/t4": {"title": "Fourth", "status": "running", "worker": "Stage", "start": iso(now - day), "roles": {"Stage": "RA"}, "estimates": {"Stage": {"value": 8, "complexity": 5}}}, + "work/t5": {"title": "Fifth", "status": "queued", "after": ["work/t4"], "roles": {"Skills": "R"}, "estimates": {"Skills": {"value": 8, "complexity": 3}}}, + "work/t6": {"title": "Sixth", "status": "queued", "base": "feature/t3", "roles": {"Docs": "RA"}}, + } + queue = {"seq": 2, "entries": [ + {"id": "deploy-1", "seq": 1, "kind": "deploy", "task": "work/t4", "workdir": "/repo", "session": "s2", "name": "Stage", "hotfix": None, "status": "active", "enqueued": now - 400, "granted": now - 300, "cmd": "make deploy"}, + {"id": "test-2", "seq": 2, "kind": "test", "task": "work/t5", "workdir": "/repo", "session": "s2", "name": "Docs", "hotfix": None, "status": "waiting", "enqueued": now - 60, "granted": None, "cmd": "make test"}, + ]} + self.write_council({"rasci.json": register, "queue.json": queue}) + + def trend_steps(self, browser: str) -> list[dict]: + local = f"http://localhost:{self.port}/" + steps = [] + for width, height in WIDTHS: + days = str(TREND_DAYS[width]) + steps += [ + {"width": width, "height": height, "url": f"{local}?{width}#tasks/list", "wait": 1200, "probe": ETA_LIST, "shot": str(OUT / f"{browser}-{width}-tasks-eta.png")}, + {"width": width, "height": height, "url": f"{local}?{width}#tasks/burn", "wait": 900, "probe": TREND_SET.replace("@MODE@", "regression").replace("@DAYS@", days), "shot": str(OUT / f"{browser}-{width}-tasks-burn-regression.png")}, + {"width": width, "height": height, "url": f"{local}?{width}-regression#tasks/burn", "wait": 1200, "probe": TREND_RELOADED, "shot": None}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": TREND_SET.replace("@MODE@", "velocity").replace("@DAYS@", days), "shot": str(OUT / f"{browser}-{width}-tasks-burn-velocity.png")}, + {"width": width, "height": height, "url": f"{local}?{width}-velocity#tasks/burn", "wait": 1200, "probe": TREND_RELOADED, "shot": None}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": STEP_TIPS, "shot": str(OUT / f"{browser}-{width}-tasks-burn-steps.png")}, + {"width": width, "height": height, "url": f"{local}?{width}-3d#tasks/3d", "wait": 1200, "probe": TASKS_3D, "shot": str(OUT / f"{browser}-{width}-tasks-3d.png")}, + {"width": width, "height": height, "url": f"{local}?{width}-camera#tasks/3d", "wait": 900, "probe": CAMERA, "shot": str(OUT / f"{browser}-{width}-tasks-3d-steady-camera.png")}, + ] + return steps + + def eta_checked(self, probe: dict, mode: str, rows: dict, edges: list[dict], window: tuple[float, float]) -> None: + """Args: + probe: task -> [start, eta, forecast, text, title] as the list shows it. + mode: the estimation mode the list was drawn in. + rows: the snapshot's task rows by task. + edges: the snapshot's task edges. + window: the earliest and latest time the page can have taken as now. + """ + day = 86400 + points = {"none": {}, "points": {"work/t4": 10 * day, "work/t5": 6 * day}}[mode] + self.assertEqual(sorted(probe), sorted(rows)) + for task, (start, eta, forecast, words, title) in probe.items(): + with self.subTest(mode=mode, task=task): + row = rows[task] + self.assertTrue(words.startswith("ETA ") and words != "ETA –", words) + if row["ended"]: + self.assertEqual((eta, forecast, title), (row["end"], False, "ETA: the end of the ended task")) + continue + self.assertTrue(forecast) + self.assertAlmostEqual(eta - start, points.get(task, 4 * day), delta=0.01) + ahead = [probe[edge["from"]][1] for edge in edges if edge["to"] == task and edge["from"] in probe and edge["from"] != task] + if row["start"] is not None: + self.assertEqual(start, row["start"]) + elif ahead and max(ahead) > window[1]: + self.assertAlmostEqual(start, max(ahead), delta=0.01) + else: + self.assertTrue(window[0] <= start <= window[1], (start, window)) + + def trend_forecast(self, points: list[list[float]], mode: str, days: int) -> tuple[float, float | None]: + """Args: + points: [t, remaining] of the drawn burndown points. + + Returns: + The trend's start and the time its remaining line reaches 0 + (None when it never falls), computed here independently of plan.js. + """ + last_t, last_y = points[-1] + if mode == "regression": + mean_t = sum(t for t, _ in points) / len(points) + mean_y = sum(y for _, y in points) / len(points) + slope = sum((t - mean_t) * (y - mean_y) for t, y in points) / sum((t - mean_t) ** 2 for t, _ in points) + return points[0][0], (mean_t - mean_y / slope if slope < 0 else None) + start = max(points[0][0], last_t - days * 86400) + before = [y for t, y in points if t <= start][-1] + slope = (last_y - before) / (last_t - start) + return start, (last_t - last_y / slope if slope < 0 else None) + + def trended(self, probe: dict, mode: str, days: int) -> None: + start, forecast = self.trend_forecast(probe["points"], mode, days) + self.assertEqual(probe["value"], mode) + self.assertEqual(probe["days"], [days, mode == "velocity"]) + self.assertEqual(sorted(series for series, *_ in probe["lines"]), ["done", "remaining", "scope"]) + for _, begin, end in probe["lines"]: + self.assertAlmostEqual(begin, start, delta=0.01) + self.assertAlmostEqual(end, forecast if forecast is not None else probe["points"][-1][0], delta=0.01) + if forecast is None: + self.assertEqual((probe["note"], probe["marker"]), ([None, "∞"], None)) + return + self.assertAlmostEqual(probe["note"][0], forecast, delta=0.01) + self.assertAlmostEqual(probe["marker"], forecast, delta=0.01) + self.assertNotEqual(probe["note"][1], "∞", probe["note"]) + + def check_trend_eta_3d(self, browser: str, driver: str, binary: str) -> None: + self.trend_work(time.time()) + begun = time.time() + data = self.drive(self.trend_steps(browser), None, driver, binary, init=GRAPH_HOOK) + ended = time.time() + (OUT / f"{browser}-trend-eta-3d.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], []) + snapshot = self.snapshot() + rows = {row["task"]: row for row in snapshot["tasks"]} + edges = snapshot["task_edges"] + self.assertEqual(sorted([edge["kind"], edge["from"], edge["to"]] for edge in edges), [["after", "work/t4", "work/t5"], ["base", "work/t3", "work/t6"], ["queue", "queue/deploy-1", "queue/test-2"]]) + trends = [["off", "off"], ["regression", "linear regression"], ["velocity", "velocity"]] + per = 8 + for index, (width, _) in enumerate(WIDTHS): + eta, regression, reloaded, velocity, again, tips, shown, camera = data["results"][per * index : per * (index + 1)] + days = TREND_DAYS[width] + kept = TREND_DAYS[WIDTHS[index - 1][0]] if index else 7 + with self.subTest(browser=browser, width=width): + for probe in (eta, regression, reloaded, velocity, again, tips, shown): + self.assertNotIn("error", probe) + self.assertEqual((probe["tall"], probe["wide"], probe["layout"]), (False, False, ["toolbar", "chips", "body"]), probe) + self.assertEqual(probe["rows"] == 1, width != 390, probe["rows"]) + for mode in ("none", "points", "back"): + self.eta_checked(eta[mode], "points" if mode == "points" else "none", rows, edges, (begun - 1, ended + 1)) + self.assertEqual(eta["modes"], [["none", "true"], ["points", "false"]]) + self.assertEqual((regression["before"]["value"], regression["before"]["options"], regression["before"]["note"], regression["before"]["lines"]), ("off", trends, None, [])) + self.assertEqual(regression["before"]["days"], [kept, False]) + self.assertEqual(regression["toasts"], ["Trend: linear regression"]) + self.trended(regression["after"], "regression", kept) + self.trended(reloaded, "regression", kept) + self.assertEqual(velocity["toasts"], [f"Trend: velocity over {kept} days", f"Trend: velocity over {days} days"]) + self.trended(velocity["after"], "velocity", days) + self.trended(again, "velocity", days) + self.assertEqual([step["t"] for step in tips["steps"]], [t for t, _ in again["points"]]) + listed = [[sorted(filter(None, step[key].split(" "))) for key in ("started", "ended", "joined")] for step in tips["steps"]] + self.assertEqual(listed, [[["work/t1", "work/t2", "work/t3"], [], ["work/t5", "work/t6"]], [[], ["work/t1"], []], [[], ["work/t2"], []], [[], ["work/t3"], []], [["work/t4"], [], []], [[], [], []]]) + self.assertEqual([step["series"] for step in tips["steps"]], [["scope", "done", "remaining"]] * len(tips["steps"])) + self.assertIn("Ended: work/t1", tips["steps"][1]["tip"]) + self.assertIn("No work package started, ended or joined the scope here", tips["steps"][-1]["tip"]) + self.assertEqual((tips["reset"], tips["note"], tips["lines"]), ("Trend: off", False, 0)) + self.tasks_3d(shown, snapshot) + self.assertTrue(camera["hooked"], camera) + self.assertGreater(math.dist(camera["built"], camera["moved"]), 1, camera) + for refresh in camera["refreshes"]: + self.assertEqual((refresh["rebuilt"], refresh["settled"]), (True, True), camera) + self.assertLess(math.dist(refresh["camera"], camera["moved"]), 0.01, camera) + self.assertEqual(self.httpd.hub.settings.get()["trend"], {"mode": "off", "days": TREND_DAYS[WIDTHS[-1][0]]}) + + def tasks_3d(self, shown: dict, snapshot: dict) -> None: + tasks = sorted(row["task"] for row in snapshot["tasks"]) + colors = {"after": shown["palette"]["violet"], "base": shown["palette"]["info"], "queue": shown["palette"]["warn"]} + edges = sorted([edge["from"], edge["to"], edge["kind"], colors[edge["kind"]]] for edge in snapshot["task_edges"]) + self.assertEqual(len(set(colors.values())), 3, colors) + for layout, word in (("force", "Force"), ("time", "Time")): + drawn = shown[layout] + with self.subTest(layout=layout): + self.assertEqual(drawn["note"], f"{len(tasks)} nodes · {len(edges)} edges · {word}") + self.assertEqual(drawn["layouts"], [["none", str(layout == "force").lower()], ["time", str(layout == "time").lower()]]) + self.assertEqual(sorted(node for node, *_ in drawn["nodes"]), tasks) + self.assertEqual(sorted(drawn["links"]), edges) + self.assertEqual(drawn["label"], "work/t5 · Fifth") + self.assertEqual([fz for _, fz, _ in shown["force"]["nodes"]], [None] * len(tasks)) + timed = sorted(shown["time"]["nodes"], key=lambda node: node[2]) + self.assertTrue(all(fz is not None for _, fz, _ in timed), timed) + self.assertEqual([fz for _, fz, _ in timed], sorted(fz for _, fz, _ in timed)) + self.assertLess(timed[0][1], timed[-1][1]) + popup = shown["popup"] + self.assertEqual((popup["open"], popup["title"], popup["id"], popup["picked"], popup["open_button"], popup["line"]), (True, "Fifth", "work/t5", "work/t5", "Open task", True), popup) + self.assertTrue(popup["eta"], popup) + self.assertEqual((popup["closed"], shown["back"]), ([False, None], f"{len(tasks)} nodes · {len(edges)} edges · Force")) + + def test_chromium_draws_the_trend_forecast_point_tips_eta_and_tasks_3d_at_three_widths(self): + self.check_trend_eta_3d("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium")) + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_draws_the_trend_forecast_point_tips_eta_and_tasks_3d_at_three_widths(self): + self.check_trend_eta_3d("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_hub_radio_e2e.py b/tests/e2e/test_hub_radio_e2e.py new file mode 100644 index 0000000..3bf1d3b --- /dev/null +++ b/tests/e2e/test_hub_radio_e2e.py @@ -0,0 +1,371 @@ +from __future__ import annotations + +import http.server +import json +import os +import shutil +import ssl +import subprocess +import sys +import tempfile +import threading +import time +import unittest +from pathlib import Path +from urllib.parse import urlsplit + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +from hub_e2e_kit import CHOICE_CHANNELS, OUT, WIDTHS, tone +from hub_e2e_radio import ( + ADD_STATION, + CALL, + CANCELED, + CLEAR_MAYDAY, + COMPOSE, + COMPOSE_SEND, + DLF_NODE, + DLF_PATH, + GEAR_READ, + GEAR_SAVE, + JUMPED, + MEDIA_LOG, + RADIO_CLICK, + RADIO_JUMP, + RADIO_STOP, + RADIO_VIEW, + SPEAK, + SPEAK_END, + SPEAK_GRAPH, + SPOT_SEND, + STATION_NAME, + Station, +) +from hub_support import HOST_STATE +from kvb_orchestrator import skill_scripts + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestHubRadio(base.OrchestratorE2ECase): + def station(self, tls: ssl.SSLContext | None = None, moved: str | None = None) -> str: + """Args: + tls: serves https with this context instead of plain http. + moved: answers every request with a 302 to this URL instead of + the tone. + """ + httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Station) + httpd.body, httpd.moved = tone(30, 22050), moved + if tls: + httpd.socket = tls.wrap_socket(httpd.socket, server_side=True) + thread = threading.Thread(target=httpd.serve_forever, args=(0.05,), daemon=True) + thread.start() + self.addCleanup(httpd.server_close) + self.addCleanup(thread.join, 10) + self.addCleanup(httpd.shutdown) + return f"{'https' if tls else 'http'}://127.0.0.1:{httpd.server_address[1]}{DLF_PATH if moved else '/tone.wav'}" + + def redirected(self) -> tuple[str, list[str]]: + """Returns: + A station that replays the recorded Deutschlandfunk chain, a 302 + from st01.sslstream.dlf.de to an f111.rndfnk.com node, as a 302 to + a second https origin, and that origin as its released via. + """ + folder = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, folder) + key, cert = folder / "key.pem", folder / "cert.pem" + subprocess.run([ + "openssl", "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes", "-subj", "/CN=127.0.0.1", + "-addext", "subjectAltName=IP:127.0.0.1", "-days", "1", "-keyout", str(key), "-out", str(cert), + ], capture_output=True, timeout=60, check=True) + tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + tls.load_cert_chain(cert, key) + node = urlsplit(self.station(tls)) + origin = f"https://{node.netloc}" + return self.station(tls, f"{origin}{DLF_NODE}"), [origin] + + def check_radio(self, browser: str, driver: str, binary: str, redirected: bool = False) -> dict: + """Args: + driver: cdp.mjs saves the station through the settings form and + signs its new origin with a virtual passkey; bidi.mjs has no + virtual authenticator, so the station is saved before the page + loads. + redirected: plays the recorded Deutschlandfunk redirect chain, + saved before the page loads with its resolved via. + """ + station, via = self.redirected() if redirected else (self.station(), []) + browser = f"{browser}-dlf" if redirected else browser + signs = driver == "cdp.mjs" and not redirected + if signs: + first = {"width": 1366, "height": 768, "url": f"http://localhost:{self.port}/#stream", "wait": 900, "probe": ADD_STATION.replace("@STATION@", station).replace("@NAME@", STATION_NAME), "shot": None, "gesture": True} + else: + hub = self.httpd.hub + hub.settings.put({**hub.settings.get(), "streams": [{"name": STATION_NAME, "url": station, "from": "00:00", "to": "24:00", "days": list(range(7)), "on": True, "via": via}]}, hub.settings.get()) + first = {"width": 1366, "height": 768, "url": f"{self.base}#stream", "wait": 900, "probe": None, "shot": None} + steps = [ + first, + {"width": 390, "height": 844, "url": None, "wait": 3000, "probe": RADIO_VIEW, "shot": str(OUT / f"{browser}-390-radio-station.png")}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": RADIO_CLICK, "shot": str(OUT / f"{browser}-1366-radio-playing.png"), "gesture": True}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": RADIO_STOP, "shot": str(OUT / f"{browser}-1366-radio-stopped.png")}, + ] + data = self.drive(steps, self.authenticator() if signs else None, driver, binary, MEDIA_LOG) + (OUT / f"{browser}-radio.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + saved, view, click, stopped = data["results"] + if signs: + self.assertTrue(any(toast.startswith("New station") for toast in saved["toasts"]), saved) + self.assertNotIn("error", view) + self.assertEqual(view["title"], STATION_NAME) + self.assertEqual(view["line"], ["nowrap", "ellipsis", True, True]) + blocked = [entry for entry in view["log"] if entry.get("play") == "NotAllowedError"] + if not view["media"]["playing"]: + self.assertTrue(blocked, view) + self.assertEqual(view["state"], "blocked", view) + self.assertIn("Click", view["note"]) + self.assertTrue(any("blocked" in toast for toast in view["toasts"]), view["toasts"]) + self.assertTrue(click["clicked"], click) + self.assertNotIn("error", click) + self.assertTrue(click["media"]["playing"], click) + self.assertEqual(click["state"], "playing", click) + self.assertEqual([entry for entry in click["log"] if entry.get("csp") == "media-src"], []) + with self.subTest(browser=browser, part="station stop"): + self.assertNotIn("error", stopped, stopped) + self.assertEqual(stopped["button"], ["Stop", f"Stop: pause {STATION_NAME}", "", True]) + self.assertTrue(stopped["paused"], stopped) + self.assertFalse(stopped["media"]["playing"], stopped) + self.assertEqual((stopped["media"]["second"]["paused"], stopped["media"]["second"]["src"]), (True, None), stopped) + self.assertEqual((stopped["state"], stopped["note"], stopped["action"]), ("stopped", "stopped", ["play", "Play"]), stopped) + self.assertGreater(stopped["tracked"], 0, stopped) + self.assertEqual(stopped["playing"], [], "an audio element still plays after Stop") + return data + + def test_chromium_plays_a_saved_station(self): + self.check_radio("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium")) + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_plays_a_saved_station(self): + self.check_radio("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox")) + + def test_chromium_plays_deutschlandfunk_through_its_redirect(self): + self.check_radio("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium"), redirected=True) + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_plays_deutschlandfunk_through_its_redirect(self): + self.check_radio("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox"), redirected=True) + + def test_chromium_sends_a_call_from_the_agent_panel_and_shows_its_receipt(self): + handled = [] + + def answer() -> None: + for script, args in self.scripts.calls[len(handled) :]: + handled.append(script) + if script.endswith("radio.py") and args[:2] == ["send", "call"]: + to, text, now = args[args.index("--to") + 1], args[-1], time.time() + rows = [{"ts": now, "from": "Operator", "to": [to], "text": text, "class": "call", "v": 2}, {"ts": now + 0.5, "from": to, "to": ["Operator"], "text": text, "class": "receipt", "v": 2, "call": now}] + self.write_council({"radio-seen/e2e-callee.json": {"radio": now + 0.5}}) + (self.state / "agent-sessions.json").write_text(json.dumps({"written": now, "sessions": {"e2e-callee": {"name": to, "running": True}}}), encoding="utf-8") + with (self.council / "news.jsonl").open("a", encoding="utf-8") as handle: + handle.write(self.jsonl(rows)) + + self.beside(answer) + local = f"http://localhost:{self.port}/" + data = self.drive([{"width": 1366, "height": 768, "url": f"{local}#stream", "wait": 900, "probe": CALL, "shot": self.shot("1366-call-receipt")}], self.authenticator()) + self.assertEqual(data["errors"], []) + result = data["results"][0] + self.assertNotIn("error", result) + self.assertIsNotNone(result["receipt"], result) + self.assertTrue(" · read " in result["receipt"] and result["receipt"].endswith(" · acknowledged"), result) + self.assertEqual(result["read"], 0, result) + + def test_chromium_shows_who_speaks_while_a_message_is_read(self): + self.speaks(("e2e-cue-1", "e2e-cue-2")) + steps = [ + {"width": 1366, "height": 768, "url": f"{self.base}#stream/radio", "wait": 900, "probe": SPEAK.replace("@CUE@", "e2e-cue-1"), "shot": self.shot("1366-radio-speaking"), "gesture": True}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": SPEAK_GRAPH, "shot": self.shot("1366-agents-speaking")}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": SPEAK_END, "shot": None}, + {"width": 390, "height": 844, "url": None, "wait": 0, "probe": SPEAK.replace("@CUE@", "e2e-cue-2"), "shot": self.shot("390-radio-speaking-reduced-motion"), "gesture": True, "media": [{"name": "prefers-reduced-motion", "value": "reduce"}]}, + ] + data = self.drive(steps, None) + (OUT / "chromium-speaking.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + speaking, graph, ended, calm = data["results"] + self.talks(speaking, graph) + self.assertEqual(ended, {"ended": True, "caption": False, "faces": 0}) + self.assertEqual((calm["who"], calm["line"], calm["ring"]), ("Stage speaking", "Disk almost full (e2e-cue-2)", "none"), calm) + self.assertEqual(calm["faces"]["speaking"], [True, "none"], calm) + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_shows_who_speaks_and_moves_only_the_speakers_mouth(self): + self.speaks(("e2e-cue-1",)) + steps = [ + {"width": 1366, "height": 768, "url": f"{self.base}#stream/radio", "wait": 900, "probe": SPEAK.replace("@CUE@", "e2e-cue-1"), "shot": str(OUT / "firefox-1366-radio-speaking.png"), "gesture": True}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": SPEAK_GRAPH, "shot": str(OUT / "firefox-1366-agents-speaking.png")}, + ] + data = self.drive(steps, None, "bidi.mjs", os.environ.get("FIREFOX", "firefox")) + (OUT / "firefox-speaking.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + self.talks(*data["results"]) + + def talks(self, speaking: dict, graph: dict) -> None: + """Args: + speaking: the SPEAK probe while Stage (s2) is read aloud. + graph: the SPEAK_GRAPH probe on #agents/orbit right after it. + """ + self.assertEqual((speaking["who"], speaking["line"], speaking["chip"], speaking["ring"]), ("Stage speaking", "Disk almost full (e2e-cue-1)", "s2", "speaking"), speaking) + self.assertEqual(speaking["faces"], {"speaking": [True, "talk"], "silent": [False, "none"], "keys": ["s2"]}, speaking) + self.assertEqual((graph["node"] or "").split(",")[0], "Stage", graph) + self.assertEqual((graph["ring"], graph["mouth"], graph["silent"]), ("speaking-node", "talk", "none"), graph) + + def test_chromium_records_transcribes_and_sends_a_signed_call_with_voice(self): + local = f"http://localhost:{self.port}/" + steps = [ + {"width": 1366, "height": 768, "url": f"{local}#agents/orbit", "wait": 1200, "probe": COMPOSE.replace("@TO@", "Stage"), "shot": self.shot("1366-radio-spot-composer"), "gesture": True}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": COMPOSE_SEND.replace("@ATTACH@", "false"), "shot": None}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": COMPOSE.replace("@TO@", "Stage"), "shot": None, "gesture": True}, + {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": COMPOSE_SEND.replace("@ATTACH@", "true"), "shot": self.shot("1366-radio-spot-composer-sent")}, + ] + data = self.drive(steps, self.authenticator()) + (OUT / "chromium-composer.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + composed, plain, again, sent = data["results"] + self.assertNotIn("error", composed) + self.assertEqual(composed["channels"], ["post", "call", "newsletter", "broadcast", "pan-pan", "security", "mayday"]) + self.assertIn("Stage", composed["recipients"]) + self.assertEqual(composed["recording"], "true") + self.assertEqual(composed["text"], "hello from the mic second line", composed) + self.assertRegex(composed["replay"] or "", r"^/api/voice/[0-9a-f]{16}\.wav$") + self.assertEqual(composed["attach"], ["Attach recording", False]) + self.assertEqual(composed["clashes"], {"found": [], "outside": []}) + self.assertEqual(again["attach"], ["Attach recording", False]) + note = again["replay"].removeprefix("/api/voice/").removesuffix(".wav") + for result in (plain, sent): + self.assertEqual((result["left"], result["voice"]), ("", False), result) + self.assertTrue(result["sent"].startswith("Call to Stage: sent"), result) + calls = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO] + self.assertEqual(len(calls), 2, self.scripts.calls) + self.assertEqual([call[:4] for call in calls], [["send", "call", "--to", "Stage"]] * 2) + self.assertTrue(calls[0][-1].endswith("] hello from the mic second line please"), calls[0]) + self.assertTrue(calls[1][-1].endswith(f"] hello from the mic second line please voice: {HOST_STATE}/voice/{note}.wav"), calls[1]) + status, _, body = self.get(f"/api/voice/{note}.wav") + self.assertEqual((status, body[:4]), (200, b"RIFF")) + + def test_chromium_clears_the_mayday_from_the_radio_spot_only_after_confirmation_and_passkey_at_three_widths(self): + local = f"http://localhost:{self.port}/" + steps = [{"width": width, "height": height, "url": f"{local}?{width}#agents/orbit", "wait": 1200, "probe": CLEAR_MAYDAY, "shot": self.shot(f"{width}-radio-spot-mayday-cleared")} for width, height in WIDTHS] + data = self.drive(steps, self.authenticator()) + (OUT / "chromium-mayday.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + question = "Lift the radio silence of the active mayday?" + for result, (width, _) in zip(data["results"], WIDTHS, strict=True): + with self.subTest(width=width): + self.assertNotIn("error", result) + self.assertEqual(result["toolbar"], ["Priority", "Day/Night", "Drain", "Suspend", "Resume", "Status"]) + self.assertEqual((result["title"], result["shown"]), ("Cancel mayday: lift the radio silence so the agents write again; your passkey signs it", "")) + self.assertEqual(result["declined"], {"question": [question], "posted": [], "toasts": []}) + self.assertEqual(result["accepted"], {"question": [question], "posted": ["/api/board/sign", "/api/board/clear-mayday"]}) + self.assertTrue((result["done"] or "").startswith("Cancel mayday: done"), result) + self.assertEqual(self.scripts.calls, [(skill_scripts.RADIO, ["clear", "--force", "--session", "Operator"])] * len(WIDTHS)) + + def test_chromium_sends_every_class_from_the_radio_spot_and_keeps_its_gear_settings_through_a_reload_at_three_widths(self): + local = f"http://localhost:{self.port}/" + values = {1920: ("0.35", "false", "true"), 1366: ("0.45", "true", "false"), 390: ("0.55", "false", "true")} + steps = [{"width": width, "height": height, "url": f"{local}?{width}-jump#stream/radio", "wait": 1200, "probe": RADIO_JUMP, "shot": self.shot(f"{width}-radio-header-spot-every-tab")} for width, height in WIDTHS] + for width, height in WIDTHS: + squelch, tone, post = values[width] + gear = GEAR_SAVE.replace("@SQUELCH@", squelch).replace("@TONE@", tone).replace("@POST@", post) + steps += [ + {"width": width, "height": height, "url": f"{local}?{width}#agents/orbit", "wait": 1200, "probe": SPOT_SEND.replace("@TEXT@", f"spot {width}"), "shot": self.shot(f"{width}-radio-spot-sent")}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": gear, "shot": None}, + {"width": width, "height": height, "url": f"{local}?{width}-reloaded#agents/orbit", "wait": 1200, "probe": GEAR_READ, "shot": self.shot(f"{width}-radio-spot-gear")}, + ] + data = self.drive(steps, self.authenticator()) + (OUT / "chromium-radio-spot.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + labels = dict(zip(CHOICE_CHANNELS, ["Post", "Call", "Newsletter", "Broadcast", "Pan-Pan", "Sécurité", "Mayday"], strict=True)) + mayday = "Send a mayday to all? All agents pause writing steps until you cancel it." + jumps, walked = data["results"][: len(WIDTHS)], data["results"][len(WIDTHS) :] + for jump, (width, _) in zip(jumps, WIDTHS, strict=True): + with self.subTest(width=width, part="radio spot on every tab"): + self.assertEqual(jump, JUMPED) + for index, (width, _) in enumerate(WIDTHS): + sent, saved, read = walked[3 * index : 3 * (index + 1)] + squelch, tone, post = values[width] + with self.subTest(width=width): + for probe in (sent, saved, read): + self.assertNotIn("error", probe) + self.assertEqual((sent["closed"], sent["open"]), ([True, "false"], [False, "true", True])) + self.assertEqual(sent["inline"], ["static", True, True]) + self.assertEqual((sent["toolbar"], sent["channels"], sent["record"]), (["Priority", "Day/Night", "Status"], CHOICE_CHANNELS, ["Record"])) + self.assertEqual(sent["heads"], [["Read aloud", "Read aloud: the classes and agents the radio sounds for"], ["Cancel mayday", "Cancel mayday: lift the radio silence so the agents write again; your passkey signs it"]]) + self.assertEqual((sent["tall"], sent["wide"]), (width == 390, False)) + self.assertEqual([run["cls"] for run in sent["runs"]], CHOICE_CHANNELS) + for run in sent["runs"]: + direct = run["cls"] in ("post", "call") + self.assertEqual((run["direct"], run["question"], run["left"]), (direct, [mayday] if run["cls"] == "mayday" else [], ""), run) + self.assertTrue((run["toast"] or "").startswith(f"{labels[run['cls']]} to {'Stage' if direct else 'all'}: sent"), run) + self.assertEqual((saved["expanded"], saved["clashes"]), ("true", [{"found": [], "outside": []}] * 2)) + self.assertEqual(saved["tones"], ["MAYDAY / PAN-PAN", "Reviews, asks, decisions", "Post and calls to you", "All radio", "Squelch", "Threshold"]) + self.assertEqual([entry[0] for entry in saved["classes"]], ["Post", "Call", "Newsletter", "Broadcast", "MAYDAY", "PAN-PAN", "Sécurité"]) + self.assertEqual([entry[1:] for entry in saved["classes"] if entry[0] == "MAYDAY"], [["true", True]]) + self.assertEqual((saved["kept"], saved["after"]), ([float(squelch), tone == "true", post == "true"], ["false", False])) + self.assertEqual(saved["general"], {"sections": ["Ambience", "Location", "Appearance", "Music", "Notifications", "Passkey"], "radio": 0}) + self.assertEqual((saved["tall"], saved["wide"]), (width == 390, False)) + self.assertEqual(read, {"squelch": float(squelch), "tone": tone == "true", "post": post == "true", "tall": width == 390, "wide": False}) + heads = {"post": ["post", "--to", "Stage"], "call": ["send", "call", "--to", "Stage"], "newsletter": ["post"]} + radio = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO] + sends = [(width, cls) for width, _ in WIDTHS for cls in CHOICE_CHANNELS] + self.assertEqual([args[:-1] for args in radio], [[*heads.get(cls, ["send", cls]), "--session", "Operator"] for _, cls in sends]) + for args, (width, cls) in zip(radio, sends, strict=True): + with self.subTest(width=width, cls=cls): + self.assertTrue(args[-1].endswith(f"] spot {width} {cls}"), args) + self.assertEqual(self.httpd.hub.settings.get()["speech"], {"threshold": 50}) + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_opens_the_radio_spot_on_every_tab_and_asks_the_passkey_for_every_class_and_cancel_mayday_sending_nothing_unsigned_at_three_widths(self): + self.pin() + local = f"http://localhost:{self.port}/" + steps = [] + for width, height in WIDTHS: + shot = str(OUT / f"firefox-{width}-radio-spot") + steps += [ + {"width": width, "height": height, "url": f"{local}?{width}-jump#stream/radio", "wait": 1200, "probe": RADIO_JUMP, "shot": f"{shot}-every-tab.png"}, + {"width": width, "height": height, "url": f"{local}?{width}#agents/orbit", "wait": 1200, "probe": SPOT_SEND.replace("@TEXT@", f"spot {width}"), "shot": f"{shot}-unsigned.png"}, + {"width": width, "height": height, "url": f"{local}?{width}-mayday#agents/orbit", "wait": 1200, "probe": CLEAR_MAYDAY, "shot": f"{shot}-mayday-kept.png"}, + ] + data = self.drive(steps, None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), CANCELED) + (OUT / "firefox-radio-spot.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], []) + labels = dict(zip(CHOICE_CHANNELS, ["Post", "Call", "Newsletter", "Broadcast", "Pan-Pan", "Sécurité", "Mayday"], strict=True)) + mayday = "Send a mayday to all? All agents pause writing steps until you cancel it." + question = "Lift the radio silence of the active mayday?" + hint = "Cancel mayday: lift the radio silence so the agents write again; your passkey signs it" + results = iter(data["results"]) + for width, _ in WIDTHS: + jump, sent, cleared = next(results), next(results), next(results) + with self.subTest(browser="firefox", width=width, part="radio spot on every tab"): + self.assertEqual(jump, JUMPED) + with self.subTest(browser="firefox", width=width, part="every class unsigned"): + self.assertNotIn("error", sent, sent) + self.assertEqual((sent["closed"], sent["open"], sent["inline"]), ([True, "false"], [False, "true", True], ["static", True, True])) + self.assertEqual((sent["toolbar"], sent["channels"], sent["record"]), (["Priority", "Day/Night", "Status"], CHOICE_CHANNELS, ["Record"])) + self.assertEqual(sent["heads"], [["Read aloud", "Read aloud: the classes and agents the radio sounds for"], ["Cancel mayday", hint]]) + self.assertEqual((sent["tall"], sent["wide"]), (width == 390, False)) + self.assertEqual([run["cls"] for run in sent["runs"]], CHOICE_CHANNELS) + for run in sent["runs"]: + direct = run["cls"] in ("post", "call") + self.assertEqual((run["direct"], run["question"], run["left"]), (direct, [mayday] if run["cls"] == "mayday" else [], f"spot {width} {run['cls']}"), run) + self.assertTrue((run["toast"] or "").startswith(f"{labels[run['cls']]} to {'Stage' if direct else 'all'}: not signed"), run) + self.assertIn("NotAllowedError", run["toast"], run) + with self.subTest(browser="firefox", width=width, part="icon-only cancel mayday unsigned"): + self.assertNotIn("error", cleared, cleared) + self.assertEqual(cleared["toolbar"], ["Priority", "Day/Night", "Drain", "Suspend", "Resume", "Status"]) + self.assertEqual((cleared["title"], cleared["shown"]), (hint, "")) + self.assertEqual(cleared["declined"], {"question": [question], "posted": [], "toasts": []}) + self.assertEqual(cleared["accepted"], {"question": [question], "posted": ["/api/board/sign"]}) + self.assertTrue((cleared["done"] or "").startswith("Cancel mayday: not signed"), cleared) + self.assertEqual(self.scripts.calls, []) + self.assertTrue((self.council / "radio-silence.json").exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_inbox_gone_rows_e2e.py b/tests/e2e/test_inbox_gone_rows_e2e.py index 32f3317..d890e8d 100644 --- a/tests/e2e/test_inbox_gone_rows_e2e.py +++ b/tests/e2e/test_inbox_gone_rows_e2e.py @@ -10,7 +10,7 @@ from unittest import mock HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase OUT = Path(os.environ.get("E2E_OUT", "/tmp/inbox-gone-rows-shots")) @@ -72,7 +72,7 @@ def probe(template: str) -> str: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestInboxGoneRows(HubCase): - drive = base.TestOrchestratorE2E.drive + drive = base.OrchestratorE2ECase.drive def setUp(self): super().setUp() diff --git a/tests/e2e/test_match_review_e2e.py b/tests/e2e/test_match_review_e2e.py index 14cc423..e4457f9 100644 --- a/tests/e2e/test_match_review_e2e.py +++ b/tests/e2e/test_match_review_e2e.py @@ -12,7 +12,7 @@ from pathlib import Path HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase from hub_support import iso @@ -111,7 +111,7 @@ def patch(lines: int) -> str: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestMatchReview(HubCase): - drive = base.TestOrchestratorE2E.drive + drive = base.OrchestratorE2ECase.drive def setUp(self): super().setUp() diff --git a/tests/e2e/test_notification_channels_e2e.py b/tests/e2e/test_notification_channels_e2e.py index d5fc575..062f1e8 100644 --- a/tests/e2e/test_notification_channels_e2e.py +++ b/tests/e2e/test_notification_channels_e2e.py @@ -10,7 +10,7 @@ from pathlib import Path HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase from hub_support import ASK from kvb_orchestrator import settings @@ -86,8 +86,8 @@ def fill(probe: str) -> str: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestNotificationChannels(HubCase): - drive = base.TestOrchestratorE2E.drive - authenticator = base.TestOrchestratorE2E.authenticator + drive = base.OrchestratorE2ECase.drive + authenticator = base.OrchestratorE2ECase.authenticator def setUp(self): super().setUp() diff --git a/tests/e2e/test_orchestrator_e2e.py b/tests/e2e/test_orchestrator_e2e.py index 3186a66..0ffbd70 100644 --- a/tests/e2e/test_orchestrator_e2e.py +++ b/tests/e2e/test_orchestrator_e2e.py @@ -1,1730 +1,45 @@ from __future__ import annotations -import array -import base64 -import contextlib -import http.server import json import math import os import shutil -import ssl -import subprocess import sys -import tempfile -import threading import time import unittest -from collections.abc import Callable from pathlib import Path -from unittest import mock -from urllib.parse import urlsplit HERE = Path(__file__).resolve().parent -sys.path.insert(0, str(HERE.parent)) +sys.path[:0] = [str(HERE.parent), str(HERE)] -from hub_case import HubCase -from hub_engines import wav_bytes -from hub_support import ASK, HOST_STATE, OPTIONS, RUNNER, iso, verifier -from kvb_orchestrator import batches, messaging, skill_scripts -from test_hub_cleanup import DONE_TIP, FAKE_PKGMGR, host -from test_hub_offices import COUNCIL_SCRIPT -from test_hub_offices import host as office_host - -OUT = Path(os.environ.get("E2E_OUT", "/tmp/orchestrator-phase4-shots")) -WIDTHS = ((1920, 1080), (1366, 768), (390, 844)) -VIEWS = ("orbit", "chord", "swimlane", "tree", "3d") -TASK_VIEWS = ("list", "board", "rasci", "gantt", "burn", "3d") -SCREENS = ["home", "stream", "tasks/operator", "stream/rules", *(f"{tab}/{view}" for tab in ("agents", "artifacts") for view in VIEWS), "agents/hierarchy", *(f"tasks/{view}" for view in TASK_VIEWS), "resources"] -SUBS = ["Firewall"] -TABS = ["Home", "Stream", "Agents", "Artifacts", "Tasks", "Resources"] -HELPERS = """ - const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); - const until = async (check, ms) => { - const end = Date.now() + ms; - while (Date.now() < end) { - const found = check(); - if (found) { - return found; - } - await sleep(200); - } - return null; - }; - 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 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) : []; - let [rows, bottom] = [0, -Infinity]; - for (const box of boxes) { - if (box.top >= bottom - 1) { - rows += 1; - bottom = box.bottom; - } else { - bottom = Math.max(bottom, box.bottom); - } - } - return rows; - }; - 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(() => { - if (typeof Nav !== "object") { - return false; - } - const route = Nav.route(location.hash); - const view = route.view ? Nav.viewsOf(route.screen).find(([id]) => id === route.view)[1] : null; - const pressed = name(document.querySelector('#main [aria-label="View"] button[aria-pressed="true"]')); - return document.getElementById("main").getAttribute("aria-labelledby") === `tab-${route.screen}` && (!view || pressed === view); - }, ms); - await sleep(0); - return Boolean(shown); - }; -""" -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"); - return found && !found.hidden ? text(found) : null; - }; - const icons = all("svg.bi").filter((svg) => !svg.closest(".sprite")); - const banner = document.getElementById("mayday"); - return { - hash: location.hash, - title: document.title, - h1: text(document.querySelector("h1")), - header: all("header.top button").map((button) => button.id), - tabs: all("#tabs > .tab-group > button").map(name), - subs: all("#tabs .subtabs button").map(name), - badges: Object.fromEntries(all("#tabs button").map((button) => [button.id, badge(button)])), - banner: banner.hidden ? null : text(banner), - rail: Boolean(document.getElementById("rail")), - views: all('#main [aria-label="View"] button').map(name), - layouts: all('#main [aria-label="Layout"] button').map(name), - chips: all('#main [aria-label="Categories"] button').map(name), - menus: all("#main details.menu > summary").map(name), - time: text(document.querySelector("#time > summary")), - replay: Boolean(document.querySelector("#time .replay input[type=range]")), - custom: Boolean(document.querySelector('#main details.menu input[type="datetime-local"]')), - toolbar: all('#main [role="toolbar"] > *').map((node) => name(node.tagName === "DETAILS" ? node.querySelector("summary") : node.querySelector("button") || node)), - spot: (() => { - const box = document.getElementById("radio-spot"); - return box ? {hidden: box.hidden, channels: [...box.querySelector("form.composer select").options].map((option) => option.value)} : null; - })(), - composers: all("form.composer").map((form) => (form.closest("#radio-spot") ? "spot" : "other")), - inbox: all("#main .inbox-list > li").length, - icons: icons.length, - unlabelled: icons.map((svg) => svg.parentElement).filter((owner) => !text(owner) && !(owner.getAttribute("title") && owner.getAttribute("aria-label"))).map((owner) => owner.outerHTML.slice(0, 160)), - broken: all("svg.bi use").filter((use) => !document.getElementById(use.getAttribute("href").slice(1))).map((use) => use.getAttribute("href")), - states: all("#main span.state").map(name), - deletes: all('#main button[aria-label="Delete"], #main button[aria-label="Delete all merged"]').map((button) => [name(button), button.disabled, button.title]), - spawn: all("#main .spawn-tree li").map((item) => [item.dataset.kind, item.dataset.running || null]), - marks: all("#main svg.chart .node").length, - note: text(document.querySelector("#main .space-note")), - canvas: Boolean(document.querySelector("#main .graph3d canvas")), - org: all("#main .org-chart .org-row[data-office]").map((row) => [row.dataset.office, text(row.querySelector(".org-holder"))]), - toggles: all("#main .org-toggle").map((button) => [name(button), button.getAttribute("aria-expanded")]), - order: all("#main .agent-order li").map((item) => item.dataset.name), - taskFilters: all('#main [aria-label="Task filters"] button').map((button) => [button.dataset.filter, button.getAttribute("aria-pressed"), text(button.querySelector(".count"))]), - taskRows: all("#main .task-row").map((row) => [row.dataset.task, row.classList.contains("open-work")]), - columns: all("#main .task-column").map((column) => [column.dataset.column, all(`#main .kanban-cell[data-column="${column.dataset.column}"] .task-card`).map((card) => card.dataset.task)]), - matrix: [all("#main table.matrix thead th").length, all("#main table.matrix tbody tr").length, all("#main table.matrix td .letter").map(text).join("")], - flows: all("#main .flow").map((flow) => flow.dataset.flow), - flowEdges: all("#main svg.chart path.flow").map((path) => path.dataset.side), - openWork: all("#main .open-work").length, - panel: all("#drawer, .drawer, #main aside, #main .panel, #main .graph-body").length, - nodeChips: all("#main .space-list, #main .chip[data-node]").length, - wide: document.documentElement.scrollWidth > window.innerWidth + 1, - tall: document.documentElement.scrollHeight > window.innerHeight, - }; -})()""".replace("@HELPERS@", HELPERS) -ORG_OPEN = """(async () => {@HELPERS@ - const row = await until(() => document.querySelector('#main .org-row[data-office="identity/oidc"]'), 8000); - if (!row) { - return {error: text(document.getElementById("main"))}; - } - const toggle = all("#main .org-toggle").find((button) => name(button) === "Collapse: identity"); - toggle.focus(); - return {focused: document.activeElement.dataset.focus, offices: all("#main .org-row[data-office]").map((entry) => entry.dataset.office)}; -})()""".replace("@HELPERS@", HELPERS) -ORG_FOLDED = """(async () => {@HELPERS@ - const toggle = document.activeElement; - const folded = {focused: toggle.dataset.focus, expanded: toggle.getAttribute("aria-expanded"), label: name(toggle), hidden: document.getElementById(toggle.getAttribute("aria-controls")).hidden, seen: all("#main .org-row[data-office]").filter((entry) => entry.offsetParent !== null).map((entry) => entry.dataset.office)}; - toggle.click(); - await sleep(200); - const before = all("#main .agent-order li").map((item) => item.dataset.name); - all("#main .agent-order li")[1].querySelector('[data-focus^="up:"]').focus(); - return {...folded, again: toggle.getAttribute("aria-expanded"), before}; -})()""".replace("@HELPERS@", HELPERS) -ORDER_MOVED = """(async () => {@HELPERS@ - const after = all("#main .agent-order li").map((item) => item.dataset.name); - const focused = document.activeElement.dataset.focus || null; - const save = all("#main .agent-order button").find((button) => text(button) === "Save order"); - const disabled = save.disabled; - save.click(); - const toast = await until(() => all("#toasts .toast").find((box) => text(box).startsWith("Priority")), 8000); - return {after, focused, disabled, toast: text(toast)}; -})()""".replace("@HELPERS@", HELPERS) -OPEN_TAKEOVER = """(async () => {@HELPERS@ - document.querySelector('#main [data-focus="takeover:identity/oidc"]').click(); - await sleep(400); - return {title: text(document.querySelector(".sheet-head .panel-title")), options: all(".sheet-box select option").map((option) => option.value), work: document.querySelector('.sheet-box input[aria-label="Work"]').value, focused: document.activeElement.tagName}; -})()""".replace("@HELPERS@", HELPERS) -CONFIRM_TAKEOVER = """(async () => {@HELPERS@ - all(".sheet-box button").find((button) => name(button) === "Hand over").click(); - const done = await until(() => document.querySelector(".sheet-box [data-result]"), 30000); - return {result: done ? done.dataset.result : null, text: text(done), toasts: all("#toasts .toast").map(text)}; -})()""".replace("@HELPERS@", HELPERS) -AFTER_TAKEOVER = """(async () => {@HELPERS@ - document.querySelector(".sheet-head button").click(); - const row = await until(() => { - const found = document.querySelector('#main .org-row[data-office="identity/oidc"] .org-holder'); - return found && !text(found).endsWith("Stage") ? found : null; - }, 15000); - return {holder: text(row)}; -})()""".replace("@HELPERS@", HELPERS) -INBOX_CHIP = """(async () => {@HELPERS@ - const chip = (id) => document.querySelector(`#main [aria-label="Task filters"] button[data-filter="${id}"]`); - chip("operator").click(); - await until(() => location.hash === "#tasks/operator" && document.querySelector("#main .inbox-list"), 4000); - const inbox = {hash: location.hash, items: all("#main .inbox-list > li").length, counted: Number(text(chip("operator").querySelector(".count"))), pressed: chip("operator").getAttribute("aria-pressed"), current: all("#tabs button[aria-current=page]").map(name)}; - chip("grant").click(); - await until(() => location.hash.startsWith("#tasks/"), 4000); - await sleep(300); - return {inbox, back: {hash: location.hash, rows: all("#main .task-row").map((row) => [row.dataset.task, text(row.querySelector(".pill"))])}}; -})()""".replace("@HELPERS@", HELPERS) -PIN = """(async () => {@HELPERS@ - const row = await until(() => all("#main .task-row").find((item) => item.dataset.task === "work/docs"), 8000); - if (!row) { - return {error: text(document.getElementById("main"))}; - } - row.querySelector('button[aria-label="Priority"]').click(); - await sleep(400); - const field = document.querySelector('.sheet-box input[aria-label="Priority"]'); - field.value = "2"; - field.dispatchEvent(new Event("input", {bubbles: true})); - const preview = all(".sheet-box .task-edit .command code").map(text); - all(".sheet-box button").find((button) => name(button) === "Pin").click(); - const done = await until(() => document.querySelector(".sheet-box [data-jobs]"), 20000); - return {title: text(document.querySelector(".sheet-head .panel-title")), preview, jobs: done ? done.dataset.jobs : null, toasts: all("#toasts .toast").map(text)}; -})()""".replace("@HELPERS@", HELPERS) -ACTIONS = """(async () => {@HELPERS@ - const press = async (key) => { - document.dispatchEvent(new KeyboardEvent("keydown", {key, bubbles: true})); - await sleep(300); - return location.hash; - }; - const found = {keys: [await press("3"), await press("4"), await press("5"), await press("1"), await press("2")]}; - document.getElementById("settings-open").click(); - await sleep(300); - found.ambience = all(".sheet-box form > section:first-child button").map((button) => button.id); - found.sections = all(".sheet-box form.settings > section > h3").map(text); - found.radioFields = all('.sheet-box [aria-label="Squelch"], .sheet-box [aria-label="Classes"], .sheet-box [aria-label="Speakers"], .sheet-box [aria-label="Mode"], .sheet-box .sound-row, .sheet-box .stream-row').length; - found.settingsUnlabelled = all(".sheet-box svg.bi").map((svg) => svg.parentElement).filter((owner) => !text(owner) && !(owner.getAttribute("title") && owner.getAttribute("aria-label"))).length; - document.querySelector(".sheet-head button").click(); - document.getElementById("palette-open").click(); - await sleep(300); - found.palette = all(".palette-list li > span:first-child").map(text); - document.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); - await sleep(200); - document.querySelector('#main [aria-label="Categories"] button:nth-child(2)').click(); - await sleep(900); - document.querySelector('#main button.linkish[title^="Open "]').click(); - 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")]; - return found; -})()""".replace("@HELPERS@", HELPERS) -POPUPS = """ - const dialog = document.getElementById("popup"); - const box = dialog.querySelector(".popup-box"); - const line = dialog.querySelector(".leader line"); - const click = (target) => target.dispatchEvent(new MouseEvent("click", {bubbles: true, cancelable: true})); - const tint = document.createElement("i"); - tint.style.color = "var(--alarm)"; - document.body.append(tint); - const red = getComputedStyle(tint).color; - tint.remove(); - const tall = () => document.documentElement.scrollHeight > innerHeight; - const look = (node) => ({picked: node.classList.contains("picked"), size: Math.round(node.querySelector("circle").getBoundingClientRect().width), red: getComputedStyle(node.querySelector("circle")).fill === red}); - const opened = () => { - const rect = box.getBoundingClientRect(); - const ends = line.getAttribute("display") === "none" ? null : ["x1", "y1", "x2", "y2"].map((key) => Number(line.getAttribute(key))); - return { - open: dialog.open, fade: [dialog.classList.contains("fade"), getComputedStyle(dialog).animationName], title: text(box.querySelector(".panel-title")), opacity: Number(getComputedStyle(box).opacity), line: ends, - onBox: Boolean(ends) && (Math.abs(ends[2] - rect.left) < 1 || Math.abs(ends[2] - rect.right) < 1 || Math.abs(ends[3] - rect.top) < 1 || Math.abs(ends[3] - rect.bottom) < 1), - inside: rect.left >= 0 && rect.top >= 0 && rect.right <= innerWidth && rect.bottom <= innerHeight, - tall: tall(), wide: document.documentElement.scrollWidth > innerWidth + 1, panel: all("#drawer, .drawer, #main aside, #main .panel, #main .graph-body").length, - }; - }; - const away = async (pick) => { - const rect = box.getBoundingClientRect(); - const [, x, y] = [[rect.left, rect.left / 2, innerHeight / 2], [innerWidth - rect.right, (rect.right + innerWidth) / 2, innerHeight / 2], [rect.top, innerWidth / 2, rect.top / 2], [innerHeight - rect.bottom, innerWidth / 2, (rect.bottom + innerHeight) / 2]].sort((a, b) => b[0] - a[0])[0]; - const outside = (await until(() => document.elementFromPoint(x, y) === dialog && dialog, 3000)) || document.elementFromPoint(x, y); - click(outside); - await sleep(250); - return {...look(pick()), open: dialog.open, outside: outside === dialog}; - }; -""" -POPUP_ORBIT = """(async () => {@HELPERS@@POPUPS@ - const pick = () => document.querySelector('#main svg .node[data-pick="s2"]'); - if (!(await until(pick, 8000))) { - return {error: text(document.getElementById("main"))}; - } - const before = look(pick()); - const flat = !tall(); - click(pick()); - 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 gone = await away(pick); - click(pick()); - await sleep(300); - const again = dialog.open; - (document.activeElement || document.body).dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); - await sleep(250); - const escaped = {...look(pick()), open: dialog.open, again}; - click(pick()); - await sleep(500); - return {before, flat, shown, gone, escaped, last: dialog.open}; -})()""".replace("@HELPERS@", HELPERS).replace("@POPUPS@", POPUPS) -POPUP_ARTIFACT = """(async () => {@HELPERS@@POPUPS@ - const first = await until(() => document.querySelector('#main svg .node[data-pick^="branch:"]'), 8000); - if (!first) { - return {error: text(document.getElementById("main"))}; - } - const id = first.dataset.pick; - const pick = () => all("#main svg .node[data-pick]").find((node) => node.dataset.pick === id); - const before = look(pick()); - const flat = !tall(); - click(pick()); - await sleep(400); - const shown = {...opened(), ...look(pick()), label: first.getAttribute("aria-label").split(",")[0]}; - const gone = await away(pick); - click(pick()); - await sleep(400); - return {before, flat, shown, gone, last: dialog.open}; -})()""".replace("@HELPERS@", HELPERS).replace("@POPUPS@", POPUPS) -PICK_3D = """(async () => {@HELPERS@ - const field = await until(() => document.querySelector('#main input[aria-label="Find a node"]'), 8000); - const ready = await until(() => document.querySelector("#main .graph3d canvas") && !text(document.querySelector("#main .space-note")).startsWith("Loading"), 8000); - if (!field || !ready) { - return {error: text(document.querySelector("#main .graph"))}; - } - const type = async (value) => { - field.value = value; - field.dispatchEvent(new Event("input", {bubbles: true})); - await sleep(150); - return all("#main .hits .chip").map((chip) => [chip.dataset.hit, text(chip)]); - }; - const tree = await (await fetch("/api/tree", {cache: "no-store"})).json(); - const found = {empty: await type(""), twins: tree.repos.flatMap((repo) => repo.branches).filter((branch) => branch.name === "main").length, twin: await type("main"), hits: await type("@QUERY@")}; - found.flat = document.documentElement.scrollHeight <= innerHeight; - const chip = all("#main .hits .chip").find((node) => node.dataset.hit.startsWith("@PREFIX@")); - if (!chip) { - return {error: found}; - } - chip.click(); - await sleep(600); - const dialog = document.getElementById("popup"); - const line = dialog.querySelector(".leader line"); - const host = () => document.querySelector("#main .graph3d"); - found.opened = { - open: dialog.open, title: text(dialog.querySelector(".popup-box .panel-title")), label: text(chip), hit: chip.dataset.hit, picked: host().dataset.picked || null, - line: line.getAttribute("display") !== "none", lists: all("#main .space-list, #main .chip[data-node]").length, flat: document.documentElement.scrollHeight <= innerHeight, - }; - dialog.dispatchEvent(new MouseEvent("click", {bubbles: true})); - await sleep(300); - found.closed = {open: dialog.open, picked: host().dataset.picked || null}; - chip.click(); - await sleep(600); - return found; -})()""".replace("@HELPERS@", HELPERS) -CALL = """(async () => {@HELPERS@ - document.querySelector('#main [aria-label="Categories"] button[aria-label="Radio"]').click(); - const someone = await until(() => document.querySelector('#main button.linkish[title^="Open "]'), 8000); - someone.click(); - await sleep(500); - document.querySelector('#popup input[type=radio][value="call"]').click(); - const field = document.querySelector("#popup textarea"); - field.value = "E2E call ping"; - field.dispatchEvent(new Event("input", {bubbles: true})); - document.querySelector('#popup button[type="submit"]').click(); - const entry = await until(() => all("#main .entry").find((row) => row.textContent.includes("E2E call ping") && row.querySelector('.reader[data-acked="true"] .ack')), 20000); - const read = all("#main .entry .pill").filter((pill) => text(pill) === "Read").length; - return {to: text(someone), receipt: entry ? entry.querySelector('.reader[data-acked="true"]').title : null, read, sent: all("#main .entry").filter((row) => row.textContent.includes("E2E call ping")).length}; -})()""".replace("@HELPERS@", HELPERS) -OPEN_DELETE = """(async () => {@HELPERS@ - const card = await until(() => all("#main details.repo").find((details) => details.textContent.includes("github.com/me/demo")), 8000); - if (!card) { - return {error: text(document.getElementById("main"))}; - } - card.open = true; - await sleep(300); - const every = document.querySelector('#main button[aria-label="Delete all merged"]'); - const buttons = all('button[aria-label="Delete"]', card); - const states = all("span.state", card).map(name); - buttons.find((button) => !button.disabled).click(); - await sleep(500); - return {states, every: [every.disabled, every.title], buttons: buttons.map((button) => [button.disabled, button.title]), title: text(document.querySelector(".sheet-head .panel-title")), dry: all('.sheet-box [aria-label="Dry run"] pre').map(text)}; -})()""".replace("@HELPERS@", HELPERS) -CONFIRM = """(async () => {@HELPERS@ - all(".sheet-box button").find((button) => name(button) === "Delete").click(); - const done = await until(() => document.querySelector(".sheet-box [data-result]"), 30000); - const job = document.querySelector(".sheet-box [data-cleanup]"); - return {job: job ? job.dataset.cleanup : null, result: done ? done.dataset.result : null, text: text(done), toasts: all("#toasts .toast").map(text)}; -})()""".replace("@HELPERS@", HELPERS) -AFTER = """(async () => {@HELPERS@ - document.querySelector(".sheet-head button").click(); - const past = await until(() => all("#main details.repo").find((details) => details.textContent.includes("Recently deleted")), 15000); - return {past: past ? [past.querySelector("[data-result]").dataset.result, name(past.querySelector("span.state"))] : null, branches: all("#main details.repo").filter((details) => details !== past).flatMap((details) => all(".branch-name strong", details)).map(text)}; -})()""".replace("@HELPERS@", HELPERS) -KEPT_TREE = """(async () => {@HELPERS@ - const card = await until(() => all("#main details.repo").find((details) => details.textContent.includes("github.com/me/demo")), 8000); - if (!card) { - return {error: text(document.getElementById("main"))}; - } - card.open = true; - await sleep(300); - const row = all(".branch-row", card).find((entry) => text(entry.querySelector(".branch-name strong")) === "feature/squashed"); - const kept = row ? row.querySelector(".hint.kept") : null; - const deletes = all('button[aria-label="Delete"]', card).map((button) => text(button.closest(".branch-row").querySelector(".branch-name strong"))); - const header = all("#main .delete-all span.state").map(name); - document.querySelector('#main button[aria-label="Delete all merged"]').click(); - const sheet = await until(() => document.querySelector("#sheet:not([hidden]) li.dry-run") && document.getElementById("sheet"), 8000); - const kind = (li) => (li.dataset.token ? "token" : li.dataset.held ? "held" : li.dataset.kept ? "kept" : null); - const rows = sheet ? all("li.dry-run", sheet).map((li) => [text(li.querySelector("code")), kind(li), all("button", li).length, text(li.querySelector("pre"))]) : null; - const confirms = sheet ? all("#sheet button").filter((button) => name(button) === "Delete").length : null; - const title = text(document.querySelector(".sheet-head .panel-title")); - document.querySelector(".sheet-head button").click(); - return {kept: kept ? [kept.title, name(kept.querySelector("span.state"))] : null, rowDeletes: row ? all('button[aria-label="Delete"]', row).length : null, deletes, header, rows, confirms, title}; -})()""".replace("@HELPERS@", HELPERS) -KEPT_POPUP = """(async () => {@HELPERS@ - await screenShown(8000); - const picker = await until(() => document.querySelector('#main select[aria-label="Repository"]'), 8000); - if (picker && picker.value !== @REPO@) { - picker.value = @REPO@; - picker.dispatchEvent(new Event("change", {bubbles: true})); - } - const id = `branch:${@REPO@}\\u0000feature/squashed`; - const target = await until(() => all("#main svg [data-pick]").find((node) => node.dataset.pick === id), 8000); - if (!target) { - return {error: text(document.getElementById("main"))}; - } - target.dispatchEvent(new MouseEvent("click", {bubbles: true, cancelable: true})); - const dialog = document.getElementById("popup"); - const dry = await until(() => dialog.open && dialog.querySelector(".popup-box pre.notes"), 6000); - const kept = dialog.querySelector(".popup-box .actions .hint.kept"); - return {title: text(dialog.querySelector(".popup-box .panel-title")), heading: dry ? text(dry.previousElementSibling) : null, dry: dry ? dry.textContent : null, - deletes: all('#popup button[aria-label="Delete"]').length, kept: kept ? kept.title : null}; -})()""".replace("@HELPERS@", HELPERS) -OVERLAP = """ - const shown = (node) => node.getClientRects().length > 0 && node.getBoundingClientRect().width > 0; - const words = (label) => [...label.childNodes].filter((node) => node.nodeType === 3).map((node) => node.textContent).join("").trim(); - const called = (node) => node.getAttribute("aria-label") || (node.closest("label") ? words(node.closest("label")) : "") || text(node) || node.type; - const clashes = (root) => { - const boxes = all("input, select, textarea, button", root).filter(shown).map((node) => ({node, box: node.getBoundingClientRect()})); - const found = []; - boxes.forEach((a, index) => boxes.slice(index + 1).forEach((b) => { - const x = Math.min(a.box.right, b.box.right) - Math.max(a.box.left, b.box.left); - const y = Math.min(a.box.bottom, b.box.bottom) - Math.max(a.box.top, b.box.top); - if (x > 0.5 && y > 0.5) { - found.push(`${called(a.node)} × ${called(b.node)}`); - } - })); - const framed = (node) => (getComputedStyle(node).display === "contents" ? framed(node.parentElement) : node); - const outside = boxes.filter(({box}) => box.right > framed(root).getBoundingClientRect().right + 0.5).map(({node}) => called(node)); - return {found, outside}; - }; -""" -RULES_OVERLAP = """(async () => {@HELPERS@@CLASHES@ - const open = document.querySelector(".sheet-head button"); - if (open) { - open.click(); - } - const rules = await until(() => document.querySelector("#main .rule-form"), 8000); - const kind = rules.querySelector("select"); - const found = {}; - for (const value of ["decision", "review", "ask"]) { - kind.value = value; - kind.dispatchEvent(new Event("change", {bubbles: true})); - await sleep(150); - found[value] = {...clashes(rules), labels: all("label", rules).filter(shown).map(words)}; - } - return found; -})()""".replace("@HELPERS@", HELPERS).replace("@CLASHES@", OVERLAP) -SETTINGS_OVERLAP = """(async () => {@HELPERS@@CLASHES@ - document.getElementById("settings-open").click(); - const settings = await until(() => document.querySelector(".sheet-box form.settings"), 8000); - const theme = all("select", settings).find((select) => [...select.options].some((option) => option.value === "custom")); - theme.value = "custom"; - theme.dispatchEvent(new Event("change", {bubbles: true})); - await sleep(250); - const place = all("section", settings).find((section) => text(section.querySelector("h3")) === "Location"); - place.scrollIntoView({block: "start"}); - return clashes(settings); -})()""".replace("@HELPERS@", HELPERS).replace("@CLASHES@", OVERLAP) -MEDIA_LOG = """() => { - const keep = (entry) => { - try { - const list = JSON.parse(sessionStorage.getItem("e2e-media") || "[]"); - list.push({...entry, page: Math.round(performance.timeOrigin)}); - sessionStorage.setItem("e2e-media", JSON.stringify(list)); - } catch (error) { - return; - } - }; - const play = HTMLMediaElement.prototype.play; - window.e2eMedia = new Set(); - HTMLMediaElement.prototype.play = function () { - window.e2eAudio = this; - window.e2eMedia.add(this); - const src = this.getAttribute("src") || ""; - const result = play.call(this); - result.then(() => keep({play: "ok", src}), (error) => keep({play: error.name, src})); - return result; - }; - document.addEventListener("securitypolicyviolation", (event) => keep({csp: event.effectiveDirective, blocked: event.blockedURI})); -}""" -MEDIA = """ - const log = () => JSON.parse(sessionStorage.getItem("e2e-media") || "[]"); - const sample = () => (window.e2eAudio ? {paused: window.e2eAudio.paused, time: window.e2eAudio.currentTime, error: window.e2eAudio.error ? window.e2eAudio.error.code : null, src: window.e2eAudio.getAttribute("src")} : null); - const advancing = async () => { - const first = sample(); - await sleep(1500); - const second = sample(); - return {first, second, playing: Boolean(first && second && !second.paused && second.time - first.time > 0.5)}; - }; -""" -ADD_STATION = """(async () => {@HELPERS@ - const clock = (date) => `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`; - location.hash = "#stream/radio"; - const fold = await until(() => document.querySelector("#radio-spot details.radio-station"), 8000); - fold.open = true; - const edit = await until(() => all("#radio-spot button").find((button) => text(button) === "Edit stations" && button.getClientRects().length), 8000); - edit.click(); - const form = await until(() => document.querySelector('.sheet-box form[aria-label="Stations"]'), 8000); - all("button", form).find((button) => text(button) === "+ Station").click(); - await sleep(200); - const row = all(".stream-row", form).pop(); - const [label, address, start, end] = all("input.field", row); - const set = (input, value) => { - input.value = value; - input.dispatchEvent(new Event("input", {bubbles: true})); - }; - set(label, "@NAME@"); - set(address, "@STATION@"); - set(start, clock(new Date(Date.now() - 3600000))); - set(end, clock(new Date(Date.now() + 3600000))); - all('.days input[type="checkbox"]', row).forEach((box) => { - box.checked = true; - }); - all("button", form).find((button) => button.type === "submit").click(); - await until(() => all("#toasts .toast").map(text).find((toast) => toast.startsWith("New station")), 8000); - return {toasts: all("#toasts .toast").map(text)}; -})()""".replace("@HELPERS@", HELPERS) -STATION_NAME = "E2E tone with a very long station name that fits on no single line" -DLF_PATH = "/dlf/01/high/aac/stream.aac?aggregator=web" -DLF_NODE = "/ard/dlf/01/aac/192/stream.aac?aggregator=web" -RADIO_STATE = """(async () => {@HELPERS@@MEDIA@ - await until(() => log().some((entry) => entry.play), 8000); - return {log: log(), media: await advancing(), toasts: all("#toasts .toast").map(text)}; -})()""".replace("@HELPERS@", HELPERS).replace("@MEDIA@", MEDIA) -RADIO_VIEW = """(async () => {@HELPERS@@MEDIA@ - location.hash = "#stream/radio"; - const fold = await until(() => document.querySelector("#radio-spot details.radio-station"), 8000); - fold.open = true; - const row = await until(() => all('#radio-spot [data-station="0"]').find((item) => item.getClientRects().length), 8000); - if (!row) { - const initial = JSON.parse(document.getElementById("state").textContent); - return {error: "no station row", log: log(), wrapped: !String(HTMLMediaElement.prototype.play).includes("[native code]"), streams: initial.settings.streams, media: initial.media, now: new Date().toString()}; - } - const label = row.querySelector(".station-name"); - const style = getComputedStyle(label); - return { - state: row.dataset.state, - note: text(row.querySelector(".station-note")), - title: label.title, - line: [style.whiteSpace, style.textOverflow, label.scrollWidth > label.clientWidth, label.getBoundingClientRect().height < 2 * parseFloat(style.lineHeight)], - media: await advancing(), - log: log(), - toasts: all("#toasts .toast").map(text), - }; -})()""".replace("@HELPERS@", HELPERS).replace("@MEDIA@", MEDIA) -RADIO_CLICK = """(async () => {@HELPERS@@MEDIA@ - const row = document.querySelector('#radio-spot [data-station="0"]'); - if (!row) { - return {error: "no station row", log: log(), media: await advancing()}; - } - const play = row.querySelector('button[data-action="play"]'); - const clicked = Boolean(sample() && sample().paused && play); - if (clicked) { - play.click(); - } - await until(() => sample() && !sample().paused, 6000); - const media = await advancing(); - const now = document.querySelector('#radio-spot [data-station="0"]'); - return {clicked, state: now.dataset.state, note: text(now.querySelector(".station-note")), media, log: log()}; -})()""".replace("@HELPERS@", HELPERS).replace("@MEDIA@", MEDIA) -RADIO_STOP = """(async () => {@HELPERS@@MEDIA@ - const row = () => document.querySelector('#radio-spot [data-station="0"]'); - const stop = row() ? row().querySelector('button[data-action="stop"]') : null; - if (!stop) { - return {error: "no Stop button on the playing station", state: row() ? row().dataset.state : null, media: sample(), log: log()}; - } - const button = [stop.getAttribute("aria-label"), stop.title, text(stop), Boolean(stop.querySelector('svg.bi use[href="#bi-stop-fill"]'))]; - stop.click(); - const paused = Boolean(await until(() => sample() && sample().paused && sample().src === null, 8000)); - const media = await advancing(); - const now = row(); - const action = now ? now.querySelector("button[data-action]") : null; - const elements = [...new Set([...(window.e2eMedia || []), ...all("audio, video")])]; - return { - button, paused, media, tracked: (window.e2eMedia || new Set()).size, - state: now ? now.dataset.state : null, note: now ? text(now.querySelector(".station-note")) : null, - action: action ? [action.dataset.action, action.getAttribute("aria-label")] : null, - playing: elements.filter((element) => !element.paused).map((element) => element.getAttribute("src") || element.currentSrc || element.tagName), - }; -})()""".replace("@HELPERS@", HELPERS).replace("@MEDIA@", MEDIA) -SPEAKING = """ - const caption = () => { - const node = document.querySelector("#radio-spot:not([hidden]) .radio-caption"); - return node && !node.hidden ? node : null; - }; - const ring = (box) => getComputedStyle(box.querySelector(".speaker-face"), "::after").animationName; - const mouth = (art) => (art ? [art.classList.contains("speaking"), getComputedStyle(art.querySelector(".mouth")).animationName] : null); - const faces = () => ({ - speaking: mouth(document.querySelector('#radio-spot .radio-caption .avatar[data-face="s2"]')), - silent: mouth(document.querySelector('.avatar[data-face]:not([data-face="s2"])')), - keys: [...new Set(all(".avatar.speaking").map((art) => art.dataset.face))], - }); - const cue = async (word) => { - await until(() => document.querySelector("#radio-spot:not([hidden])"), 8000); - await fetch("/api/tts", {method: "POST", headers: {"X-Kvb-Orchestrator": "1", "Content-Type": "application/json"}, body: JSON.stringify({text: word, voice: ""}), cache: "no-store"}); - const found = await until(caption, 25000); - return found ? {who: text(found.querySelector("strong")), line: text(found.querySelector(".caption-line")), chip: found.querySelector(".avatar").dataset.face, ring: ring(found), faces: faces()} : {error: "no caption", toasts: all("#toasts .toast").map(text)}; - }; -""" -SPEAK = """(async () => {@HELPERS@@SPEAKING@ - return cue("@CUE@"); -})()""".replace("@HELPERS@", HELPERS).replace("@SPEAKING@", SPEAKING) -SPEAK_GRAPH = """(async () => {@HELPERS@@SPEAKING@ - location.hash = "#agents/orbit"; - const node = await until(() => document.querySelector("#main svg .node.speaking"), 6000); - const silent = document.querySelector('#main svg .node[data-pick="s1"] .mouth'); - return { - node: node ? node.getAttribute("aria-label") : null, ring: node ? getComputedStyle(node.querySelector("circle")).animationName : null, - mouth: node ? getComputedStyle(node.querySelector(".mouth")).animationName : null, silent: silent ? getComputedStyle(silent).animationName : null, - }; -})()""".replace("@HELPERS@", HELPERS).replace("@SPEAKING@", SPEAKING) -SPEAK_END = """(async () => {@HELPERS@@SPEAKING@ - const ended = Boolean(await until(() => !document.querySelector("#main svg .node") || !document.querySelector("#main svg .node.speaking"), 20000)); - location.hash = "#stream/radio"; - await until(() => document.querySelector("#radio-spot:not([hidden]) .radio-caption"), 6000); - await sleep(300); - return {ended, caption: Boolean(caption()), faces: all(".avatar.speaking").length}; -})()""".replace("@HELPERS@", HELPERS).replace("@SPEAKING@", SPEAKING) -SPOT_OPEN = """ - const spotToggle = document.getElementById("radio-open"); - if (spotToggle && spotToggle.getAttribute("aria-expanded") !== "true") { - spotToggle.click(); - await sleep(300); - } - const spot = document.getElementById("radio-spot"); -""" -COMPOSE = """(async () => {@HELPERS@@SPOT_OPEN@ - const form = spot ? spot.querySelector("form.composer") : null; - if (!form) { - return {error: "no composer"}; - } - const [channel, recipient] = all("select", form); - await until(() => [...recipient.options].some((option) => option.value === "@TO@"), 8000); - channel.value = "call"; - channel.dispatchEvent(new Event("change", {bubbles: true})); - recipient.value = "@TO@"; - const record = all("button", form).find((button) => button.hasAttribute("aria-pressed")); - record.click(); - await sleep(1500); - const recording = record.getAttribute("aria-pressed"); - record.click(); - const field = form.querySelector("textarea"); - await until(() => field.value && form.querySelector('.voice-note input[type="checkbox"]'), 60000); - const replay = form.querySelector(".voice-note audio"); - const attach = form.querySelector('.voice-note input[type="checkbox"]'); - return { - channels: all("option", channel).map((option) => option.value), - recipients: all("option", recipient).map((option) => option.value), - recording, - text: field.value, - replay: replay ? replay.getAttribute("src") : null, - attach: attach ? [text(attach.closest("label")), attach.checked] : null, - status: text(form.querySelector(".composer-status")), - toasts: all("#toasts .toast").map(text), - clashes: (() => {@CLASHES@ - return clashes(form); - })(), - }; -})()""".replace("@HELPERS@", HELPERS).replace("@SPOT_OPEN@", SPOT_OPEN).replace("@CLASHES@", OVERLAP) -COMPOSE_SEND = """(async () => {@HELPERS@ - const form = document.querySelector("#radio-spot form.composer"); - const field = form.querySelector("textarea"); - field.value = `${field.value} please`; - field.dispatchEvent(new Event("input", {bubbles: true})); - form.querySelector('.voice-note input[type="checkbox"]').checked = @ATTACH@; - const before = all("#toasts .toast").length; - form.querySelector('button[type="submit"]').click(); - const sent = await until(() => all("#toasts .toast").slice(before).map(text).find((toast) => toast.startsWith("Call to")), 20000); - return {sent, left: field.value, voice: Boolean(form.querySelector(".voice-note audio"))}; -})()""".replace("@HELPERS@", HELPERS) -CLEAR_MAYDAY = """(async () => {@HELPERS@ - const questions = []; - let accept = false; - window.confirm = (question) => { - questions.push(question); - return accept; - }; - const posted = []; - const send = window.fetch.bind(window); - window.fetch = (path, init) => { - if (String(path).startsWith("/api/board/")) { - posted.push(String(path)); - } - return send(path, init); - }; - await until(() => document.querySelector('#main [role="toolbar"]'), 8000); - const toolbar = all('#main [role="toolbar"] button, #main [role="toolbar"] summary').map(name);@SPOT_OPEN@ - const button = await until(() => spot && all(".spot-head button", spot).find((node) => name(node) === "Cancel mayday" && !node.disabled), 8000); - if (!button) { - return {error: "no enabled Cancel mayday button in the radio spot", toolbar}; - } - const shown = new Set(all("#toasts .toast")); - const fresh = () => all("#toasts .toast").filter((node) => !shown.has(node)).map(text); - button.click(); - await sleep(800); - const declined = {question: questions.slice(), posted: posted.slice(), toasts: fresh()}; - accept = true; - button.click(); - const done = await until(() => fresh().find((toast) => toast.startsWith("Cancel mayday")), 15000); - return {toolbar, title: button.title, shown: text(button), declined, accepted: {question: questions.slice(declined.question.length), posted: posted.slice(declined.posted.length)}, done}; -})()""".replace("@HELPERS@", HELPERS).replace("@SPOT_OPEN@", SPOT_OPEN) -NIGHT_MENU = """(async () => {@HELPERS@ - const questions = []; - window.confirm = (question) => { - questions.push(question); - return true; - }; - let asked = 0; - const get = navigator.credentials.get.bind(navigator.credentials); - navigator.credentials.get = (options) => { - asked += 1; - return @SIGNS@ ? get(options) : Promise.reject(new DOMException("The operator canceled.", "NotAllowedError")); - }; - const posted = []; - const send = window.fetch.bind(window); - window.fetch = (path, init) => { - if (String(path).startsWith("/api/board/")) { - const body = JSON.parse(init.body); - posted.push([String(path), Object.keys(body), body.action || null]); - } - return send(path, init); - }; - const menu = await until(() => all('#main [role="toolbar"] details.menu').find((node) => name(node.querySelector("summary")) === "Day/Night"), 8000); - if (!menu) { - return {error: text(document.getElementById("main"))}; - } - menu.open = true; - const buttons = all(".actions button", menu); - const runs = []; - for (const button of buttons) { - const label = name(button); - const [before, prompts, sent] = [asked, questions.length, posted.length]; - const shown = new Set(all("#toasts .toast")); - button.click(); - const toast = await until(() => all("#toasts .toast").filter((box) => !shown.has(box)).map(text).find((entry) => entry.startsWith(`${label}:`)), 15000); - runs.push({label, question: questions.slice(prompts), asked: asked - before, posted: posted.slice(sent), toast}); - } - return {labels: buttons.map(name), runs}; -})()""".replace("@HELPERS@", HELPERS) -NIGHT_LOOK = """(async () => {@HELPERS@ - const menu = await until(() => all('#main [role="toolbar"] details.menu').find((node) => name(node.querySelector("summary")) === "Day/Night"), 8000); - if (!menu) { - return {error: text(document.getElementById("main"))}; - } - menu.open = true; - await sleep(200); - const box = menu.querySelector(".menu-box"); - return { - children: [...box.children].map((node) => [node.tagName.toLowerCase(), node.className]), - badge: all(".pill", box).map(text), - picks: all(".night-picks label", box).map((label) => [text(label), label.querySelector("input").checked]), - buttons: all("button", box).map((button) => [name(button), button.title]), - paragraphs: all("p", box).length, - wide: document.documentElement.scrollWidth > window.innerWidth + 1, - }; -})()""".replace("@HELPERS@", HELPERS) -NIGHT_PICK = """(async () => {@HELPERS@ - const questions = []; - window.confirm = (question) => { - questions.push(question); - return true; - }; - navigator.credentials.get = @SIGNS@ ? navigator.credentials.get.bind(navigator.credentials) : () => Promise.reject(new DOMException("The operator canceled.", "NotAllowedError")); - const posted = []; - const send = window.fetch.bind(window); - window.fetch = (path, init) => { - if (String(path).startsWith("/api/board/")) { - const body = JSON.parse(init.body); - posted.push([String(path), Object.keys(body), body.action || null, body.agents || null]); - } - return send(path, init); - }; - const menu = await until(() => all('#main [role="toolbar"] details.menu').find((node) => name(node.querySelector("summary")) === "Day/Night"), 8000); - if (!menu) { - return {error: text(document.getElementById("main"))}; - } - menu.open = true; - await sleep(200); - const box = menu.querySelector(".menu-box"); - const picks = () => all(".night-picks label", box).map((label) => [text(label), label.querySelector("input").checked]); - const enabled = () => all(".actions button", box).map((button) => !button.disabled); - const tick = (label) => all(".night-picks label", box).find((node) => text(node) === label).querySelector("input").click(); - const fresh = async (label, click) => { - const shown = new Set(all("#toasts .toast")); - click(); - return until(() => all("#toasts .toast").filter((node) => !shown.has(node)).map(text).find((entry) => entry.startsWith(`${label}:`)), 15000); - }; - const found = {badge: all(".pill", box).map(text), start: picks()}; - tick("Skills"); - found.one = [picks(), enabled()]; - found.drain = await fresh("Drain", () => all(".actions button", box).find((button) => name(button) === "Drain").click()); - found.kept = picks(); - tick("Stage"); - found.none = [picks(), enabled()]; - tick("All"); - found.all = [picks(), enabled()]; - menu.open = false; - document.getElementById("palette-open").click(); - const item = await until(() => all(".palette-list li").find((li) => text(li.querySelector("span")) === "Stage"), 4000); - item.click(); - const row = await until(() => document.querySelector("#popup .agent-night"), 4000); - found.popup = {badge: all(".pill", row).map(text), buttons: all("button", row).map(name)}; - found.suspend = await fresh("Suspend", () => all("button", row).find((button) => name(button) === "Suspend").click()); - return {...found, questions, posted, wide: document.documentElement.scrollWidth > window.innerWidth + 1}; -})()""".replace("@HELPERS@", HELPERS) -FITS = "tall: document.documentElement.scrollHeight > window.innerHeight, wide: document.documentElement.scrollWidth > window.innerWidth + 1" -SPOT_SEND = """(async () => {@HELPERS@ - const questions = []; - window.confirm = (question) => { - questions.push(question); - return true; - }; - await until(() => document.querySelector('#main [role="toolbar"]'), 8000); - const toggle = document.getElementById("radio-open"); - const main = document.getElementById("main"); - const spot = document.getElementById("radio-spot"); - const closed = [spot.hidden, toggle.getAttribute("aria-expanded")]; - toggle.click(); - await sleep(400); - const form = spot.querySelector("form.composer"); - const [channel, recipient] = all("select", form); - const field = form.querySelector("textarea"); - const found = { - closed, - open: [spot.hidden, toggle.getAttribute("aria-expanded"), document.activeElement === field], - inline: [getComputedStyle(spot).position, spot.getBoundingClientRect().bottom <= main.getBoundingClientRect().top, spot.parentElement.nextElementSibling === main], - toolbar: all('#main [role="toolbar"] > *').map((node) => name(node.tagName === "DETAILS" ? node.querySelector("summary") : node)), - channels: all("option", channel).map((option) => option.value), - record: all("button", form).filter((button) => button.hasAttribute("aria-pressed")).map(text), - heads: all(".spot-head button", spot).map((button) => [name(button), button.title]), - @FITS@, - }; - await until(() => [...recipient.options].some((option) => option.value === "Stage"), 8000); - found.runs = []; - for (const cls of found.channels) { - channel.value = cls; - channel.dispatchEvent(new Event("change", {bubbles: true})); - const direct = !recipient.closest("label").hidden; - if (direct) { - recipient.value = "Stage"; - } - field.value = `@TEXT@ ${cls}`; - field.dispatchEvent(new Event("input", {bubbles: true})); - const shown = new Set(all("#toasts .toast")); - const prompts = questions.length; - const submit = form.querySelector('button[type="submit"]'); - submit.click(); - const toast = await until(() => all("#toasts .toast").filter((node) => !shown.has(node)).map(text).find((entry) => entry.includes(" to ")), 20000); - await until(() => !submit.disabled, 20000); - found.runs.push({cls, direct, toast, question: questions.slice(prompts), left: field.value}); - } - document.getElementById("toasts").replaceChildren(); - return found; -})()""".replace("@HELPERS@", HELPERS).replace("@FITS@", FITS) -RADIO_JUMP = """(async () => {@HELPERS@ - const spot = await until(() => location.hash === "#stream" && document.querySelector("#radio-spot:not([hidden])"), 8000); - if (!spot) { - return {error: text(document.getElementById("main"))}; - } - await sleep(200); - const focused = document.activeElement === spot.querySelector("textarea"); - const tabs = []; - for (const hash of ["#home", "#stream/inbox", "#agents/orbit", "#artifacts/tree", "#tasks/list", "#resources"]) { - location.hash = hash; - await sleep(500); - const main = document.getElementById("main"); - tabs.push([hash, !spot.hidden, spot.getBoundingClientRect().bottom <= main.getBoundingClientRect().top]); - } - const toggle = document.getElementById("radio-open"); - toggle.click(); - await sleep(200); - return { - hash: "#stream", focused, tabs, closed: [spot.hidden, toggle.getAttribute("aria-expanded")], - header: all("header.top button").map((button) => [button.id, name(button), text(button)]), radioTab: Boolean(document.getElementById("tab-radio")), - }; -})()""".replace("@HELPERS@", HELPERS) -CANCELED = """() => { - window.e2ePasskeys = 0; - if (navigator.credentials) { - navigator.credentials.get = () => { - window.e2ePasskeys += 1; - return Promise.reject(new DOMException("The operator canceled.", "NotAllowedError")); - }; - } -}""" -JUMPED = { - "hash": "#stream", "focused": True, "tabs": [[tab, True, True] for tab in ("#home", "#stream/inbox", "#agents/orbit", "#artifacts/tree", "#tasks/list", "#resources")], "closed": [True, "false"], - "header": [["radio-open", "Radio", ""], ["bubbles-toggle", "Speech bubbles", ""], ["palette-open", "Commands", ""], ["settings-open", "Settings", ""]], "radioTab": False, -} -PRESENCE_HELPERS = """ - const states = () => all("#main .presence:not(label)").map((node) => node.dataset.state).sort(); - const statusMenu = () => { - const menu = all('#main [role="toolbar"] details.menu').find((node) => name(node.querySelector("summary")) === "Status"); - menu.open = true; - return menu; - }; - const looks = (menu) => all("input[data-look]", menu).map((input) => [input.dataset.look, input.checked]); - const graph3d = async (faces) => { - const box = await until(() => { - const found = document.querySelector("#main .graph3d"); - return found && found.dataset.faces !== undefined && (faces === null || found.dataset.faces === faces) ? found : null; - }, 15000); - return box ? [Number(box.dataset.faces), Number(box.dataset.badges)] : null; - }; -""" -PRESENCE_WALK = """(async () => {@HELPERS@@PRESENCE@ - const views = {}; - for (const view of ["orbit", "chord", "swimlane", "tree", "hierarchy"]) { - location.hash = `#agents/${view}`; - await screenShown(6000); - await until(() => all("#main .presence:not(label)").length, 6000); - views[view] = states(); - } - location.hash = "#agents/orbit"; - await screenShown(6000); - const node = await until(() => document.querySelector('#main svg .node[data-pick="s1"]'), 6000); - const motion = getComputedStyle(node.querySelector(".presence .glyph")).animationName; - node.dispatchEvent(new MouseEvent("click", {bubbles: true})); - const mark = await until(() => document.querySelector("#popup .presence"), 4000); - const profile = mark ? [mark.dataset.state, text(mark), mark.getAttribute("aria-label")] : null; - (document.activeElement || document.body).dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); - await sleep(300); - location.hash = "#agents/3d"; - const shown = await graph3d(null); - const menu = statusMenu(); - const before = looks(menu); - menu.querySelector('input[data-look="working"]').click(); - menu.querySelector('input[data-look="faces"]').click(); - const hidden = await graph3d("0"); - location.hash = "#agents/orbit"; - await screenShown(6000); - await until(() => document.querySelector('#main svg .node[data-pick="s2"]'), 6000); - return {views, motion, profile, shown, before, hidden, orbit: states(), @FITS@}; -})()""".replace("@HELPERS@", HELPERS).replace("@PRESENCE@", PRESENCE_HELPERS).replace("@FITS@", FITS) -PRESENCE_READ = """(async () => {@HELPERS@@PRESENCE@ - await until(() => document.querySelector('#main svg .node[data-pick="s2"]'), 8000); - await sleep(300); - const menu = statusMenu(); - const kept = {boxes: looks(menu), orbit: states()}; - menu.querySelector('input[data-look="working"]').click(); - menu.querySelector('input[data-look="faces"]').click(); - await sleep(300); - const back = states(); - location.hash = "#agents/3d"; - return {...kept, back, restored: await graph3d(null)}; -})()""".replace("@HELPERS@", HELPERS).replace("@PRESENCE@", PRESENCE_HELPERS) -GEAR_SAVE = """(async () => {@HELPERS@@CLASHES@ - const spot = document.getElementById("radio-spot"); - const face = spot.querySelector(".radio-face"); - const gear = all(".spot-head button", spot).find((button) => name(button) === "Read aloud"); - gear.click(); - const box = await until(() => spot.querySelector("#radio-gear .radio-read"), 4000); - if (!box) { - return {error: "no read-aloud filters behind the gear"}; - } - const chips = () => all('#radio-gear [aria-label="Classes"] button', spot); - const post = () => chips().find((chip) => text(chip) === "Post"); - const found = { - expanded: gear.getAttribute("aria-expanded"), - tones: all(".radio-knobs .knob-label", face).map(text), - classes: chips().map((chip) => [text(chip), chip.getAttribute("aria-pressed"), chip.disabled]), - clashes: [clashes(face), clashes(spot.querySelector("#radio-gear"))], - @FITS@, - }; - const squelch = face.querySelector('input[aria-label="Squelch"]'); - squelch.value = "@SQUELCH@"; - squelch.dispatchEvent(new Event("input", {bubbles: true})); - const tone = face.querySelector('button[aria-label="All radio tone"]'); - if (tone.getAttribute("aria-pressed") !== "@TONE@") { - tone.click(); - } - if (post().getAttribute("aria-pressed") !== "@POST@") { - post().click(); - } - await sleep(200); - const kept = JSON.parse(localStorage.getItem("kvb-orchestrator.radio")); - found.kept = [kept.squelch, kept.sounds.radio.on, kept.classes.includes("post")]; - gear.click(); - await sleep(200); - found.after = [gear.getAttribute("aria-expanded"), Boolean(spot.querySelector("#radio-gear .radio-read"))]; - document.getElementById("settings-open").click(); - const sheet = await until(() => document.querySelector(".sheet-box form.settings"), 4000); - found.general = {sections: all("section > h3", sheet).map(text), radio: all('[aria-label="Squelch"], [aria-label="Classes"], [aria-label="Speakers"], [aria-label="Mode"], .sound-row, .stream-row', sheet).length}; - document.querySelector(".sheet-head button").click(); - return found; -})()""".replace("@HELPERS@", HELPERS).replace("@CLASHES@", OVERLAP).replace("@FITS@", FITS) -GEAR_READ = """(async () => {@HELPERS@@SPOT_OPEN@ - const gear = spot ? all(".spot-head button", spot).find((button) => name(button) === "Read aloud") : null; - if (!gear) { - return {error: text(document.getElementById("main"))}; - } - gear.click(); - await until(() => spot.querySelector("#radio-gear .radio-read"), 4000); - const face = spot.querySelector(".radio-face"); - return { - squelch: Number(face.querySelector('input[aria-label="Squelch"]').value), - tone: face.querySelector('button[aria-label="All radio tone"]').getAttribute("aria-pressed") === "true", - post: all('#radio-gear [aria-label="Classes"] button', spot).find((chip) => text(chip) === "Post").getAttribute("aria-pressed") === "true", - @FITS@, - }; -})()""".replace("@HELPERS@", HELPERS).replace("@SPOT_OPEN@", SPOT_OPEN).replace("@FITS@", FITS) -GRAPH_HOOK = """() => { - let made = null; - Object.defineProperty(window, "ForceGraph3D", { - configurable: true, - get: () => made && ((options) => { - const graph = made(options); - window.e2eGraphs = [...(window.e2eGraphs || []), graph]; - return graph; - }), - set: (value) => { - made = value; - }, - }); -}""" -CAMERA = """(async () => {@HELPERS@ - const ready = await until(() => window.e2eGraphs && document.querySelector("#main .graph3d canvas") && !text(document.querySelector("#main .space-note")).startsWith("Loading"), 15000); - if (!ready) { - return {error: text(document.querySelector("#main .graph"))}; - } - const graph = window.e2eGraphs[window.e2eGraphs.length - 1]; - const position = () => { - const at = graph.cameraPosition(); - return [at.x, at.y, at.z]; - }; - await sleep(5500); - let [fed, stops] = [0, 0]; - const stopped = graph.onEngineStop(); - graph.onEngineStop(() => { - stops += 1; - stopped(); - }); - const feed = graph.graphData; - graph.graphData = function (...args) { - fed += args.length; - return feed.apply(graph, args); - }; - const built = position(); - const canvas = document.querySelector("#main .graph3d canvas"); - const rect = canvas.getBoundingClientRect(); - for (let turn = 0; turn < 4; turn += 1) { - canvas.dispatchEvent(new WheelEvent("wheel", {deltaY: -120, clientX: rect.left + rect.width / 2, clientY: rect.top + rect.height / 2, bubbles: true, cancelable: true})); - await sleep(60); - } - await sleep(900); - const moved = position(); - const refreshes = []; - for (let round = 0; round < 2; round += 1) { - const [feeds, ends] = [fed, stops]; - document.dispatchEvent(new Event("visibilitychange")); - const rebuilt = Boolean(await until(() => fed > feeds, 8000)); - const settled = Boolean(await until(() => stops > ends, 10000)); - await sleep(900); - refreshes.push({rebuilt, settled, camera: position()}); - } - all("#main button").find((button) => name(button) === "Reset view").click(); - await sleep(1500); - return {hooked: typeof stopped === "function", built, moved, refreshes, reset: position()}; -})()""".replace("@HELPERS@", HELPERS) - - -def tone(seconds: int, rate: int) -> bytes: - frames = array.array("h", (int(6000 * math.sin(2 * math.pi * 440 * n / rate)) for n in range(seconds * rate))) - return wav_bytes(1, 2, rate, frames.tobytes()) - - -class Station(http.server.BaseHTTPRequestHandler): - def do_GET(self) -> None: - if self.server.moved: - self.send_response(302) - self.send_header("Location", self.server.moved) - self.send_header("Content-Length", "0") - self.end_headers() - return - body = self.server.body - self.send_response(200) - self.send_header("Content-Type", "audio/wav") - self.send_header("Content-Length", str(len(body))) - self.end_headers() - with contextlib.suppress(OSError): - self.wfile.write(body) - - def log_message(self, *args: object) -> None: - return - - -UNLABELLED = """ - const unlabelled = (root, skip) => all("svg.bi", root).filter((svg) => !svg.closest(".sprite") && !(skip && skip.contains(svg))).map((svg) => svg.parentElement).filter((owner) => !text(owner) && !(owner.getAttribute("title") && owner.getAttribute("aria-label"))).map((owner) => owner.outerHTML.slice(0, 160)); -""" -LABELS = UNLABELLED + """ - const wide = () => document.documentElement.scrollWidth > window.innerWidth + 1; - const rowOf = (words) => all("#main .inbox-list > li").find((li) => li.textContent.includes(words)); - const askOf = (command) => all("#main .inbox-list > li.k-ask").find((li) => text(li.querySelector(".command code")) === command); - const press = (root, label) => all("button", root).find((button) => name(button) === label).click(); - const out = () => document.querySelector("#main .console .console-out"); - const atEnd = () => out().scrollTop + out().clientHeight >= out().scrollHeight - 12; - const line = () => text(document.querySelector("#main .console .console-status")); -""" -RUN_START = """(async () => {@HELPERS@@LABELS@ - const row = await until(() => rowOf("Row"), 8000); - if (!row) { - return {error: text(document.getElementById("main"))}; - } - press(row, "Run"); - const toast = await until(() => all("#toasts .toast.wait").find((box) => box.textContent.includes("Run")), 8000); - const queued = await until(() => out() && line(), 15000); - await until(() => out().textContent.includes("Row 60"), 20000); - return {toast: text(toast), queued, running: line(), overflows: out().scrollHeight > out().clientHeight, followed: atEnd()}; -})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) -RUN_HELD = """(async () => {@HELPERS@@LABELS@ - out().scrollTop = 0; - await sleep(300); - await until(() => out().textContent.includes("Row 80"), 20000); - await sleep(300); - return {held: out().scrollTop, running: line()}; -})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) -RUN_DONE = """(async () => {@HELPERS@@LABELS@ - out().scrollTop = out().scrollHeight; - 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)}; -})()""".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")); - const posted = []; - const send = window.fetch.bind(window); - window.fetch = (path, init) => { - if (["/api/sign", "/api/inbox/approve"].includes(String(path))) { - posted.push([String(path), JSON.parse(init.body).items.map((item) => [item.id, item.verb, item.channel || null])]); - } - return send(path, init); - }; - const list = await until(() => document.querySelector("#main .inbox-list"), 8000); - if (!list) { - return {error: text(document.getElementById("main"))}; - } - let scroller = list; - while (scroller && !(scroller.scrollHeight > scroller.clientHeight + 4 && getComputedStyle(scroller).overflowY !== "visible")) { - scroller = scroller.parentElement; - } - scroller = scroller || document.scrollingElement; - const last = all("#main .inbox-list > li").filter((li) => li.textContent.includes("echo row")).pop(); - last.scrollIntoView({block: "center"}); - await sleep(300); - const title = text(last.querySelector(".command code")); - const before = scroller.scrollTop; - last.querySelector("input").click(); - 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 buttons = all("#main .inbox-actions button").map(name); - all("#main .inbox-actions button").find((button) => name(button).startsWith("Deny selection")).click(); - await until(() => document.querySelector(".sheet-box .actions"), 4000); - const listed = all(".sheet-box ul.mini > li strong").map(text); - const confirm = all(".sheet-box .actions button").find((button) => text(button).startsWith("Deny ")); - const label = text(confirm); - const shown = new Set(all("#toasts .toast")); - confirm.click(); - const toast = await until(() => all("#toasts .toast").filter((node) => !shown.has(node)).map(text).find((entry) => entry.startsWith("Deny selection")), 15000); - return {title, before, moved: Math.abs(after - before), focused, buttons, listed, label, toast, posted, wide: document.documentElement.scrollWidth > window.innerWidth + 1}; -})()""".replace("@HELPERS@", HELPERS) -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"))), - splits: all("#main .deny-split").map((group) => all("button", group).map(name)), - console: line(), - followed: atEnd(), - fits: out().getBoundingClientRect().right <= window.innerWidth, - dry: text(rule.querySelector(".dry-run-count")), - fields: all(".rule-request dt", rule).map(text), - accept: all("button", rule).filter((button) => name(button) === "Accept").length, - unlabelled: unlabelled(document), - wide: wide(), - }; -})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) -DENY_SHEET = """(async () => {@HELPERS@@LABELS@ - const row = await until(() => rowOf("git push"), 8000); - press(row, "Deny via …"); - const box = await until(() => document.querySelector(".sheet-box"), 4000); - return { - title: text(box.querySelector(".panel-title")), - channels: all(".deny-channels input[type=radio]", box).map((input) => [input.value, input.checked]), - hints: all(".deny-channel small", box).map(text), - reason: Boolean(box.querySelector("textarea")), - unlabelled: unlabelled(box), - wide: wide(), - }; -})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) -DENY = """(async () => {@HELPERS@@LABELS@ - const row = await until(() => askOf("make deploy"), 8000); - if (!row) { - return {error: text(document.getElementById("main"))}; - } - press(row, "Deny via …"); - const box = await until(() => document.querySelector(".sheet-box"), 4000); - box.querySelector('input[value="call"]').click(); - box.querySelector("textarea").value = "make the gate green first"; - press(box.querySelector(".actions"), "Deny"); - const undo = await until(() => all("#toasts .toast.wait").find((toast) => toast.textContent.includes("Denial")), 8000); - return {undo: text(undo), sheet: !document.getElementById("sheet").hidden}; -})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) -DENIED = """(async () => {@HELPERS@@LABELS@ - return {gone: Boolean(await until(() => !askOf("make deploy"), 20000))}; -})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) -ACCEPT = """(async () => {@HELPERS@@LABELS@ - press(rowOf("Rule request"), "Accept"); - const toast = await until(() => all("#toasts .toast").find((box) => box.textContent.includes("Created: Rule")), 15000); - await until(() => !rowOf("Rule request"), 8000); - return {toast: text(toast), left: Boolean(rowOf("Rule request"))}; -})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) -WATCH = """ - const questions = []; - window.confirm = (question) => { - questions.push(question); - return true; - }; - let asked = 0; - const get = navigator.credentials.get.bind(navigator.credentials); - navigator.credentials.get = (options) => { - asked += 1; - return @SIGNS@ ? get(options) : Promise.reject(new DOMException("The operator canceled.", "NotAllowedError")); - }; - const posted = []; - const send = window.fetch.bind(window); - window.fetch = (path, init) => { - if (["/api/choices/sign", "/api/choices", "/api/sign", "/api/inbox/approve"].includes(String(path))) { - const body = JSON.parse(init.body); - posted.push([String(path), Object.keys(body).sort(), body.class || null, body.to || null]); - } - return send(path, init); - }; - const bar = () => document.getElementById("choice-request"); - const fresh = async (shown, prefix) => until(() => all("#toasts .toast").filter((box) => !shown.has(box)).map(text).find((entry) => entry.startsWith(prefix)), 20000); - const fits = () => ({tall: document.documentElement.scrollHeight > window.innerHeight, wide: document.documentElement.scrollWidth > window.innerWidth + 1}); -""" -CHOICE_VIEW = """(async () => {@HELPERS@@LABELS@ - const found = await until(() => document.getElementById("choice-request") && all("#main .inbox-list > li .options").length === @CARDS@ && document.querySelector('#choice-request input[type="checkbox"]'), 8000); - if (!found) { - return {error: text(document.getElementById("main"))}; - } - const box = document.getElementById("choice-request"); - const chip = document.querySelector('#main [aria-label="Task filters"] button[data-filter="operator"]'); - const closed = all("button[data-channel]", box).filter((button) => button.checkVisibility()).length; - return { - kinds: [...new Set(all("#main .inbox-list > li").map((li) => text(li.querySelector(".pill"))))].sort(), - filter: [text(chip).replace(/[0-9]+$/, ""), chip.getAttribute("aria-pressed")], - channels: all("button[data-channel]", box).map((button) => [button.dataset.channel, name(button), button.disabled]), - fields: all("textarea, input:not([type=checkbox])", box).length, - agents: all('input[type="checkbox"]', box).map((input) => input.value), - multi: [name(box.querySelector("summary")), box.open, closed, text(box.querySelector(".menu-box h3 .count")), all('input[type="checkbox"]', box).filter((input) => input.checked).length], - bar: [box.parentElement.getAttribute("aria-label"), toolbarRows(), taskLayout()], - cards: all("#main .inbox-list > li").filter((li) => li.querySelector(".options")).map((li) => [text(li.querySelector(".pill")), all(".option strong", li).map(text)]), - choices: all("#main [data-column], #main .group-title, #main h2, #main h3").filter((node) => node.dataset.column === "choices" || text(node) === "Choices").length, - unlabelled: unlabelled(document), - tall: document.documentElement.scrollHeight > window.innerHeight, - wide: wide(), - }; -})()""".replace("@HELPERS@", HELPERS).replace("@LABELS@", LABELS) -CHOICE_SEND = """(async () => {@HELPERS@@WATCH@ - const menu = bar(); - menu.querySelector("summary").click(); - await sleep(200); - const boxes = all('input[type="checkbox"]', menu).slice(0, 2); - boxes.forEach((box) => box.click()); - const counted = text(menu.querySelector(".menu-box h3 .count")); - const opened = [menu.open, all("button[data-channel]", menu).filter((button) => button.checkVisibility()).length]; - const picked = boxes.map((box) => box.value).sort((a, b) => a.localeCompare(b)); - const runs = []; - for (const button of all("button[data-channel]", bar())) { - const [before, prompts, sent] = [asked, questions.length, posted.length]; - const shown = new Set(all("#toasts .toast")); - const disabled = button.disabled; - button.click(); - const toast = await fresh(shown, "Choice request"); - runs.push({channel: button.dataset.channel, disabled, asked: asked - before, question: questions.slice(prompts), posted: posted.slice(sent), toast}); - } - 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) { - return {error: text(document.getElementById("main"))}; - } - const option = all(".option", card).find((button) => text(button.querySelector("strong")) === "Wait"); - const title = option.title; - const shown = new Set(all("#toasts .toast")); - option.click(); - const toast = await fresh(shown, "Choice: Wait"); - const gone = @SIGNS@ ? Boolean(await until(() => !all("#main .inbox-list > li").some((li) => li.textContent.includes("@QUESTION@")), 20000)) : null; - return {title, asked, posted, toast, gone, closed, ...fits()}; -})()""".replace("@HELPERS@", HELPERS).replace("@WATCH@", WATCH) -TASKS_FIT = """(async () => {@HELPERS@ - await until(() => document.getElementById("choice-request") && document.querySelector("#main .tasks-body > *"), 8000); - document.getElementById("toasts").replaceChildren(); - await sleep(300); - return { - hash: location.hash, - bar: all("#choice-request button[data-channel]").map((button) => button.dataset.channel), - rows: toolbarRows(), - layout: taskLayout(), - columns: all("#main .task-column").map((column) => column.dataset.column), - choices: all("#main [data-column], #main .group-title, #main h2, #main h3").filter((node) => node.dataset.column === "choices" || text(node) === "Choices").length, - tall: document.documentElement.scrollHeight > window.innerHeight, - wide: document.documentElement.scrollWidth > window.innerWidth + 1, - }; -})()""".replace("@HELPERS@", HELPERS) -PLAN_HELPERS = """ - const fits = () => ({tall: document.documentElement.scrollHeight > window.innerHeight, wide: document.documentElement.scrollWidth > window.innerWidth + 1, rows: toolbarRows(), layout: taskLayout()}); - const modes = () => all('#main [aria-label="Estimation"] button').map((button) => [button.dataset.estimation, button.getAttribute("aria-pressed")]); - const requestShown = () => { - const button = document.getElementById("request-estimates"); - return button ? !button.hidden && button.getClientRects().length > 0 : null; - }; - const choose = async (select, value) => { - select.value = value; - select.dispatchEvent(new Event("change", {bubbles: true})); - await sleep(300); - }; - const fresh = async (shown, prefix) => until(() => all("#toasts .toast").filter((box) => !shown.has(box)).map(text).find((entry) => entry.startsWith(prefix)), 20000); -""" -GANTT = """(async () => {@HELPERS@@PLAN_HELPERS@ - const svg = await until(() => document.querySelector("#main svg.gantt"), 8000); - if (!svg) { - return {error: text(document.getElementById("main"))}; - } - const forecast = document.querySelector('#main select[aria-label="Forecast"]'); - const scroll = document.querySelector("#main .gantt-scroll"); - const marks = () => all("#main svg.gantt [data-forecast]").map((mark) => [mark.dataset.task, mark.dataset.forecast === "true", Number(mark.dataset.start), Number(mark.dataset.end), mark.tagName.toLowerCase()]); - const found = { - hash: location.hash, - forecast: [forecast.value, all("option", forecast).map((option) => [option.value, text(option)])], - modes: modes(), - request: requestShown(), - bars: marks(), - edges: all("#main svg.gantt path.gantt-edge").map((path) => [path.dataset.kind, path.dataset.from, path.dataset.to, path.getAttribute("marker-end")]), - hatched: all("#main svg.gantt .gantt-bar.forecast").map((bar) => getComputedStyle(bar).fill.includes("gantt-hatch")), - inner: Boolean(scroll && scroll.closest(".tasks-body")), - ...fits(), - }; - await choose(forecast, "real"); - found.real = marks().filter(([, hatched]) => hatched).length; - await choose(forecast, "points"); - found.pointsOnly = marks().filter(([, hatched]) => hatched).map(([task, , start, end, tag]) => [task, end - start, tag]); - await choose(forecast, "always"); - return found; -})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS) -BURN = """(async () => {@HELPERS@@PLAN_HELPERS@ - const svg = await until(() => document.querySelector("#main svg.burn"), 8000); - if (!svg) { - return {error: text(document.getElementById("main"))}; - } - const scope = document.querySelector('#main select[aria-label="Scope"]'); - const series = () => all("#main svg.burn path.burn-line").map((path) => [path.dataset.series, Number(path.dataset.last)]); - const found = {hash: location.hash, modes: modes(), request: requestShown(), scope: [scope.value, all("option", scope).map((option) => option.value)], series: series(), ...fits()}; - await choose(scope, "agent:Docs"); - found.agent = series(); - await choose(scope, "all"); - return found; -})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS) -POINTS_ON = """(async () => {@HELPERS@@PLAN_HELPERS@ - const before = {modes: modes(), request: requestShown()}; - all('#main [aria-label="Estimation"] button').find((button) => button.dataset.estimation === "points").click(); - const shown = await until(() => requestShown(), 8000); - return {before, modes: modes(), request: Boolean(shown), ...fits()}; -})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS) -REQUEST = """(async () => {@HELPERS@@PLAN_HELPERS@ - const svg = await until(() => document.querySelector("#main svg.burn") && requestShown(), 8000); - if (!svg) { - return {error: text(document.getElementById("main")), modes: modes()}; - } - const series = all("#main svg.burn path.burn-line").map((path) => [path.dataset.series, Number(path.dataset.last)]); - const shown = new Set(all("#toasts .toast")); - document.getElementById("request-estimates").click(); - const toast = await fresh(shown, "Request estimates"); - return {modes: modes(), series, toast, ...fits()}; -})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS) -BULK = """(async () => {@HELPERS@@PLAN_HELPERS@ - const list = await until(() => all("#main .task-row").length && document.getElementById("bulk-value"), 8000); - if (!list) { - return {error: text(document.getElementById("main"))}; - } - let asked = 0; - const get = navigator.credentials.get.bind(navigator.credentials); - navigator.credentials.get = (options) => { - asked += 1; - return @SIGNS@ ? get(options) : Promise.reject(new DOMException("The operator canceled.", "NotAllowedError")); - }; - const posted = []; - const send = window.fetch.bind(window); - window.fetch = (path, init) => { - if (["/api/sign", "/api/tasks"].includes(String(path))) { - const body = JSON.parse(init.body); - posted.push([String(path), Object.keys(body).sort(), body.items.map((item) => [item.id, item.argv.join(" ")])]); - } - return send(path, init); - }; - const rows = () => all("#main .task-row").map((row) => row.dataset.task); - const sort = document.querySelector('#main select[aria-label="Sort"]'); - const direction = document.querySelector("#main button[data-direction]"); - const found = {sorts: all("option", sort).map((option) => option.value), prio: rows()}; - await choose(sort, "status"); - found.status = rows(); - direction.click(); - await sleep(300); - found.statusDown = [rows(), name(direction)]; - direction.click(); - await choose(sort, "prio"); - found.picks = all("#main .task-row input.task-pick").map((box) => box.closest(".task-row").dataset.task); - for (const task of ["work/next", "work/child"]) { - all("#main .task-row").find((row) => row.dataset.task === task).querySelector("input.task-pick").click(); - } - const button = document.getElementById("bulk-value"); - found.armed = [button.disabled, text(button.querySelector(".count"))]; - await choose(document.querySelector('#main select[aria-label="Business value of the selection"]'), "@VALUE@"); - const shown = new Set(all("#toasts .toast")); - button.click(); - found.toast = await fresh(shown, "Business value @VALUE@ for 2 tasks"); - found.asked = asked; - found.posted = posted; - found.after = [button.disabled, all("#main .task-row input.task-pick:checked").length]; - Object.assign(found, fits()); - all('#main [aria-label="Estimation"] button').find((entry) => entry.dataset.estimation === "none").click(); - found.reset = Boolean(await until(() => requestShown() === false, 8000)); - return found; -})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS) -ETA_LIST = """(async () => {@HELPERS@@PLAN_HELPERS@ - const list = await until(() => all("#main .task-row .task-eta").length >= 8, 8000); - if (!list) { - return {error: text(document.getElementById("main"))}; - } - const number = (value) => (value === "" ? null : Number(value)); - const read = () => Object.fromEntries(all("#main .task-row").map((row) => { - const eta = row.querySelector(".task-eta"); - return [row.dataset.task, [number(eta.dataset.start), number(eta.dataset.eta), eta.dataset.forecast === "true", text(eta), eta.title]]; - })); - const toggle = async (mode) => { - const before = JSON.stringify(read()); - all('#main [aria-label="Estimation"] button').find((button) => button.dataset.estimation === mode).click(); - await until(() => JSON.stringify(read()) !== before, 8000); - await sleep(300); - return read(); - }; - const found = {none: read(), modes: modes(), ...fits()}; - found.points = await toggle("points"); - found.back = await toggle("none"); - return found; -})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS) -TREND_READ = """ - const trendOf = () => { - const select = document.querySelector('#main select[aria-label="Trend"]'); - const days = document.querySelector('#main input[aria-label="Velocity days"]'); - const note = document.querySelector("#main .burn-forecast"); - const marker = document.querySelector("#main svg.burn .forecast-line"); - return { - value: select.value, options: all("option", select).map((option) => [option.value, text(option)]), days: [Number(days.value), days.getClientRects().length > 0], - note: note ? [note.dataset.forecast === "" ? null : Number(note.dataset.forecast), text(note)] : null, marker: marker ? Number(marker.dataset.forecast) : null, - lines: all("#main svg.burn path.burn-trend").map((path) => [path.dataset.series, Number(path.dataset.from), Number(path.dataset.to)]), - points: all('#main svg.burn circle.burn-point[data-series="remaining"]').map((circle) => [Number(circle.dataset.t), Number(circle.dataset.value)]), - }; - }; - const chart = async () => until(() => document.querySelector("#main svg.burn") && document.querySelector('#main select[aria-label="Trend"]'), 8000); -""" -TREND_SET = """(async () => {@HELPERS@@PLAN_HELPERS@@TREND_READ@ - if (!(await chart())) { - return {error: text(document.getElementById("main"))}; - } - const before = trendOf(); - const shown = new Set(all("#toasts .toast")); - await choose(document.querySelector('#main select[aria-label="Trend"]'), "@MODE@"); - const toasts = [await fresh(shown, "Trend: ")]; - if ("@MODE@" === "velocity") { - const days = document.querySelector('#main input[aria-label="Velocity days"]'); - const again = new Set(all("#toasts .toast")); - days.value = "@DAYS@"; - days.dispatchEvent(new Event("change", {bubbles: true})); - toasts.push(await fresh(again, "Trend: velocity over @DAYS@ days")); - } - await sleep(400); - return {before, after: trendOf(), toasts, ...fits()}; -})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS).replace("@TREND_READ@", TREND_READ) -TREND_RELOADED = """(async () => {@HELPERS@@PLAN_HELPERS@@TREND_READ@ - if (!(await chart())) { - return {error: text(document.getElementById("main"))}; - } - await sleep(300); - return {...trendOf(), ...fits()}; -})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS).replace("@TREND_READ@", TREND_READ) -STEP_TIPS = """(async () => {@HELPERS@@PLAN_HELPERS@@TREND_READ@ - if (!(await chart())) { - return {error: text(document.getElementById("main"))}; - } - const steps = all('#main svg.burn circle.burn-point[data-series="remaining"]').map((circle) => ({ - t: Number(circle.dataset.t), started: circle.dataset.started, ended: circle.dataset.ended, joined: circle.dataset.joined, tip: text(circle.querySelector("title")), - series: all(`#main svg.burn circle.burn-point[data-step="${circle.dataset.step}"]`).map((mark) => mark.dataset.series), - })); - const shown = new Set(all("#toasts .toast")); - await choose(document.querySelector('#main select[aria-label="Trend"]'), "off"); - const reset = await fresh(shown, "Trend: off"); - await sleep(300); - return {steps, reset, note: Boolean(document.querySelector("#main .burn-forecast")), lines: all("#main svg.burn path.burn-trend").length, ...fits()}; -})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS).replace("@TREND_READ@", TREND_READ) -TASKS_3D = """(async () => {@HELPERS@@PLAN_HELPERS@ - const note = () => text(document.querySelector("#main .space-note")) || ""; - const ready = await until(() => window.e2eGraphs && document.querySelector("#main .graph3d canvas") && !note().startsWith("Loading"), 15000); - if (!ready) { - return {error: text(document.querySelector("#main .graph"))}; - } - const graph = () => window.e2eGraphs[window.e2eGraphs.length - 1]; - const id = (end) => (typeof end === "object" ? end.id : end); - const look = () => { - const data = graph().graphData(); - const color = graph().linkColor(); - return { - note: note(), layouts: all('#main [aria-label="Layout"] button').map((button) => [button.dataset.layout, button.getAttribute("aria-pressed")]), - nodes: data.nodes.map((node) => [node.id, Number.isFinite(node.fz) ? node.fz : null, Number.isFinite(node.ts) ? node.ts : null]), - links: data.links.map((link) => [id(link.source), id(link.target), link.kind, color(link)]), - label: (() => { - const shown = graph().nodeLabel()(data.nodes.find((node) => node.id === "work/t5")); - return shown instanceof Element ? shown.textContent : String(shown); - })(), - }; - }; - const layout = async (mode, word) => { - all('#main [aria-label="Layout"] button').find((button) => button.dataset.layout === mode).click(); - await until(() => note().endsWith(word), 8000); - await sleep(400); - return look(); - }; - const css = getComputedStyle(document.documentElement); - const palette = Object.fromEntries(["violet", "info", "warn"].map((role) => [role, css.getPropertyValue(`--${role}`).trim()])); - const force = look(); - const time = await layout("time", "Time"); - const field = document.querySelector('#main input[aria-label="Find a node"]'); - field.value = "work/t5"; - field.dispatchEvent(new Event("input", {bubbles: true})); - await sleep(200); - const chip = all("#main .hits .chip").find((node) => node.dataset.hit === "work/t5"); - if (!chip) { - return {error: "no search hit", force, time}; - } - chip.click(); - await sleep(600); - const dialog = document.getElementById("popup"); - const eta = dialog.querySelector(".task-eta"); - const popup = { - open: dialog.open, title: text(dialog.querySelector(".popup-box .panel-title")), id: text(dialog.querySelector(".popup-head .task-id")), picked: document.querySelector("#main .graph3d").dataset.picked || null, - eta: eta ? eta.dataset.eta : null, open_button: name(dialog.querySelector(".popup-body .actions button")), line: dialog.querySelector(".leader line").getAttribute("display") !== "none", - }; - (document.activeElement || document.body).dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); - await sleep(300); - popup.closed = [dialog.open, document.querySelector("#main .graph3d").dataset.picked || null]; - const back = await layout("none", "Force"); - await sleep(1200); - return {palette, force, time, popup, back: back.note, ...fits()}; -})()""".replace("@HELPERS@", HELPERS).replace("@PLAN_HELPERS@", PLAN_HELPERS) -PLAN_VALUES = {1920: "13", 1366: "21", 390: "34"} -TREND_DAYS = {1920: 7, 1366: 3, 390: 14} -STATUS_ORDER = ["queued", "awaiting", "claimed", "running", "blocked", "stale", "done", "stopped"] -CHOICE_REQUEST = "send me your open decisions as choices" -CHOICE_CHANNELS = ["post", "call", "newsletter", "broadcast", "pan-pan", "security", "mayday"] -NIGHT_HINTS = [ - ("Drain", "Drain: the agents finish their task and take nothing new; your passkey signs it"), - ("Suspend", "Suspend: the agents park their work, write the handover and idle; your passkey signs it"), - ("Resume", "Resume: all agents continue from their handover; your passkey signs it"), -] -SLOW ="seq -f 'Row %g' 1 60; sleep 4; seq -f 'Row %g' 61 80; sleep 4; echo finished" - - -def labelled(probe: dict) -> dict: - return {key: probe[key] for key in ("unlabelled", "broken")} +import hub_e2e_kit as base +from hub_e2e_kit import ( + CHOICE_CHANNELS, + GRAPH_HOOK, + OUT, + SCREENS, + SUBS, + TABS, + WIDTHS, + labelled, +) +from hub_e2e_views import ( + ACTIONS, + CAMERA, + INBOX_CHIP, + PICK_3D, + POPUP_ARTIFACT, + POPUP_ORBIT, + PRESENCE_READ, + PRESENCE_WALK, + PROBE, + RULES_OVERLAP, + SETTINGS_OVERLAP, +) @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") -class TestOrchestratorE2E(HubCase): - def setUp(self): - super().setUp() - OUT.mkdir(parents=True, exist_ok=True) - self.seed() - - def seed(self) -> None: - now = time.time() - self.root = self.write_tree() - feature = f"{self.root}/worktrees/github.com/me/demo/feature" - self.claim("s1", "Skills session") - self.write_council({ - "work/s2/claim.json": {"office": "work/s2", "session": "s2", "runtime": "claude", "name": "Stage", "since": iso(now - 7200), "beat": now - 2000, "work": "x"}, - "chair/claim.json": {"office": "chair", "session": "s1", "runtime": "claude", "name": "Skills session", "since": iso(now - 7200), "beat": now, "work": "allocate"}, - "identity/oidc/claim.json": {"office": "identity/oidc", "session": "s2", "runtime": "claude", "name": "Stage", "since": iso(now - 7200), "beat": now - 2000, "work": "oidc line"}, - "rasci.json": { - "work/stage": {"title": "Stage line", "status": "running", "worker": "Stage (this session)", "roles": {"Stage (this session)": "RA"}}, - "work/feature": { - "title": "Show the merge flow in the hub", "status": "running", "worker": "Skills session", "objective": "The operator sees where a branch flows", "workdir": feature, "prio": 1, - "roles": {"Skills session": "RA", "Operator": "C", "Docs": "I"}, "key_results": [{"text": "Flow in the tree", "met": True}, {"text": "Flow in Tasks", "met": False}], - "estimates": {"Skills": {"value": 8, "complexity": 3, "at": iso(now - 600)}}, - }, - "work/docs": {"title": "Update the README", "status": "blocked", "worker": "Docs", "branch": "main", "roles": {"Docs": "R", "Maintainer": "A", "Skills": "S"}, "estimates": {"Docs": {"value": 3, "complexity": 2}}}, - "work/old": {"title": "Old line", "status": "done", "worker": "Stage", "end": iso(now - 86400), "roles": {"Stage": "RA"}}, - "operator/push": {"title": "git push", "workdir": "/repo", "status": "done", "roles": {"Operator": "R"}}, - }, - "queue.json": {"seq": 3, "entries": [{"id": "gate-3", "kind": "gate", "task": "work/feature", "workdir": feature, "session": "s1", "name": "Skills", "status": "waiting", "enqueued": now - 120, "cmd": "make test"}]}, - "radio-silence.json": {"since": now - 60, "until": now + 3600, "by": "Docs", "text": "disk full"}, - "news.jsonl": self.jsonl([ - {"ts": now - 600, "from": "Skills", "to": ["Stage"], "text": "rebase please", "class": "post", "v": 2}, - {"ts": now - 500, "from": "Stage", "to": ["Skills"], "text": "gate red", "class": "call", "v": 2}, - {"ts": now - 400, "from": "Maintainer", "to": [], "text": "main is green", "class": "newsletter", "v": 2}, - {"ts": now - 300, "from": "Maintainer", "to": [], "text": "rotate keys", "class": "security", "v": 2}, - {"ts": now - 60, "from": "Docs", "to": [], "text": "MAYDAY disk full", "class": "mayday", "v": 2}, - ]), - }) - self.subagents(now) - self.request("feat: orchestrator", "") - self.create_ask({**ASK, "timeout": 3600}) - self.base = f"http://{self.host}/" - - def subagents(self, now: float) -> None: - def line(ts: float) -> dict: - return {"type": "user", "sessionId": "s1", "timestamp": iso(ts), "message": {"role": "user", "content": "x"}} - - folder = self.projects / "-repo" / "s1" / "subagents" - folder.mkdir(parents=True) - (self.projects / "-repo" / "s1.jsonl").write_text(self.jsonl([line(now - 3600), line(now - 30)]), encoding="utf-8") - for ident, finished in (("abc", True), ("def", False)): - (folder / f"agent-{ident}.meta.json").write_text(json.dumps({"agentType": "Explore", "description": f"look {ident}", "spawnDepth": 1, "finished": finished}), encoding="utf-8") - (folder / f"agent-{ident}.jsonl").write_text(self.jsonl([line(now - 1800), line(now - 60)]), encoding="utf-8") - - def drive(self, steps: list[dict], authenticator: dict | None, driver: str = "cdp.mjs", binary: str = os.environ.get("CHROMIUM", "chromium"), init: str | None = None) -> dict: - with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as handle: - json.dump({"steps": steps, "authenticator": authenticator, "init": init}, handle) - self.addCleanup(os.unlink, handle.name) - done = subprocess.run(["node", str(HERE / driver), binary, handle.name], capture_output=True, text=True, timeout=900, check=False) - self.assertEqual(done.returncode, 0, done.stderr[-2000:]) - return json.loads(done.stdout) - - def beside(self, work: Callable[[], None]) -> None: - stop = threading.Event() - - def loop() -> None: - while not stop.wait(0.2): - work() - - thread = threading.Thread(target=loop, daemon=True) - thread.start() - self.addCleanup(thread.join, 10) - self.addCleanup(stop.set) - - def shot(self, name: str) -> str: - return str(OUT / f"chromium-{name}.png") - - def authenticator(self) -> dict: - signer = self.pin() - private = "".join(line for line in signer.pem.read_text(encoding="utf-8").splitlines() if not line.startswith("-----")) - return {"credentialId": base64.b64encode(signer.raw_id).decode(), "privateKey": private, "rpId": "localhost"} - - def speaks(self, cues: tuple[str, ...]) -> None: - hub = self.httpd.hub - spoken = tone(6, 8000) - - def synthesize(body: bytes, admit: Callable[[str], None]) -> bytes: - word = json.loads(body)["text"] - if word in cues: - row = {"ts": time.time(), "from": "Stage", "to": [], "text": f"Disk almost full ({word})\nsecond line", "class": "security", "v": 2} - with (self.council / "news.jsonl").open("a", encoding="utf-8") as handle: - handle.write(self.jsonl([row])) - return spoken - - patch = mock.patch.object(hub.speech, "synthesize", synthesize) - patch.start() - self.addCleanup(patch.stop) - - def station(self, tls: ssl.SSLContext | None = None, moved: str | None = None) -> str: - """Args: - tls: serves https with this context instead of plain http. - moved: answers every request with a 302 to this URL instead of - the tone. - """ - httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Station) - httpd.body, httpd.moved = tone(30, 22050), moved - if tls: - httpd.socket = tls.wrap_socket(httpd.socket, server_side=True) - thread = threading.Thread(target=httpd.serve_forever, args=(0.05,), daemon=True) - thread.start() - self.addCleanup(httpd.server_close) - self.addCleanup(thread.join, 10) - self.addCleanup(httpd.shutdown) - return f"{'https' if tls else 'http'}://127.0.0.1:{httpd.server_address[1]}{DLF_PATH if moved else '/tone.wav'}" - - def redirected(self) -> tuple[str, list[str]]: - """Returns: - A station that replays the recorded Deutschlandfunk chain, a 302 - from st01.sslstream.dlf.de to an f111.rndfnk.com node, as a 302 to - a second https origin, and that origin as its released via. - """ - folder = Path(tempfile.mkdtemp()) - self.addCleanup(shutil.rmtree, folder) - key, cert = folder / "key.pem", folder / "cert.pem" - subprocess.run([ - "openssl", "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes", "-subj", "/CN=127.0.0.1", - "-addext", "subjectAltName=IP:127.0.0.1", "-days", "1", "-keyout", str(key), "-out", str(cert), - ], capture_output=True, timeout=60, check=True) - tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) - tls.load_cert_chain(cert, key) - node = urlsplit(self.station(tls)) - origin = f"https://{node.netloc}" - return self.station(tls, f"{origin}{DLF_NODE}"), [origin] - +class TestOrchestratorE2E(base.OrchestratorE2ECase): def check_overlaps(self, browser: str, driver: str, binary: str) -> None: steps = [] for width, height in WIDTHS: @@ -1744,60 +59,6 @@ class TestOrchestratorE2E(HubCase): self.assertIn("Directory (glob)", rules["review"]["labels"]) self.assertEqual(settings, {"found": [], "outside": []}) - def check_radio(self, browser: str, driver: str, binary: str, redirected: bool = False) -> dict: - """Args: - driver: cdp.mjs saves the station through the settings form and - signs its new origin with a virtual passkey; bidi.mjs has no - virtual authenticator, so the station is saved before the page - loads. - redirected: plays the recorded Deutschlandfunk redirect chain, - saved before the page loads with its resolved via. - """ - station, via = self.redirected() if redirected else (self.station(), []) - browser = f"{browser}-dlf" if redirected else browser - signs = driver == "cdp.mjs" and not redirected - if signs: - first = {"width": 1366, "height": 768, "url": f"http://localhost:{self.port}/#stream", "wait": 900, "probe": ADD_STATION.replace("@STATION@", station).replace("@NAME@", STATION_NAME), "shot": None, "gesture": True} - else: - hub = self.httpd.hub - hub.settings.put({**hub.settings.get(), "streams": [{"name": STATION_NAME, "url": station, "from": "00:00", "to": "24:00", "days": list(range(7)), "on": True, "via": via}]}, hub.settings.get()) - first = {"width": 1366, "height": 768, "url": f"{self.base}#stream", "wait": 900, "probe": None, "shot": None} - steps = [ - first, - {"width": 390, "height": 844, "url": None, "wait": 3000, "probe": RADIO_VIEW, "shot": str(OUT / f"{browser}-390-radio-station.png")}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": RADIO_CLICK, "shot": str(OUT / f"{browser}-1366-radio-playing.png"), "gesture": True}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": RADIO_STOP, "shot": str(OUT / f"{browser}-1366-radio-stopped.png")}, - ] - data = self.drive(steps, self.authenticator() if signs else None, driver, binary, MEDIA_LOG) - (OUT / f"{browser}-radio.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - saved, view, click, stopped = data["results"] - if signs: - self.assertTrue(any(toast.startswith("New station") for toast in saved["toasts"]), saved) - self.assertNotIn("error", view) - self.assertEqual(view["title"], STATION_NAME) - self.assertEqual(view["line"], ["nowrap", "ellipsis", True, True]) - blocked = [entry for entry in view["log"] if entry.get("play") == "NotAllowedError"] - if not view["media"]["playing"]: - self.assertTrue(blocked, view) - self.assertEqual(view["state"], "blocked", view) - self.assertIn("Click", view["note"]) - self.assertTrue(any("blocked" in toast for toast in view["toasts"]), view["toasts"]) - self.assertTrue(click["clicked"], click) - self.assertNotIn("error", click) - self.assertTrue(click["media"]["playing"], click) - self.assertEqual(click["state"], "playing", click) - self.assertEqual([entry for entry in click["log"] if entry.get("csp") == "media-src"], []) - with self.subTest(browser=browser, part="station stop"): - self.assertNotIn("error", stopped, stopped) - self.assertEqual(stopped["button"], ["Stop", f"Stop: pause {STATION_NAME}", "", True]) - self.assertTrue(stopped["paused"], stopped) - self.assertFalse(stopped["media"]["playing"], stopped) - self.assertEqual((stopped["media"]["second"]["paused"], stopped["media"]["second"]["src"]), (True, None), stopped) - self.assertEqual((stopped["state"], stopped["note"], stopped["action"]), ("stopped", "stopped", ["play", "Play"]), stopped) - self.assertGreater(stopped["tracked"], 0, stopped) - self.assertEqual(stopped["playing"], [], "an audio element still plays after Stop") - return data - def popped(self, result: dict, title: str) -> None: before, shown, gone = result["before"], result["shown"], result["gone"] self.assertEqual((before["picked"], before["red"]), (False, False)) @@ -1864,20 +125,6 @@ class TestOrchestratorE2E(HubCase): def test_firefox_form_controls_never_overlap(self): self.check_overlaps("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox")) - def test_chromium_plays_a_saved_station(self): - self.check_radio("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium")) - - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_plays_a_saved_station(self): - self.check_radio("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox")) - - def test_chromium_plays_deutschlandfunk_through_its_redirect(self): - self.check_radio("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium"), redirected=True) - - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_plays_deutschlandfunk_through_its_redirect(self): - self.check_radio("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox"), redirected=True) - def test_chromium_walks_every_screen_at_three_widths(self): steps = [{"width": width, "height": height, "url": f"{self.base}#{screen}", "wait": 900, "probe": PROBE, "shot": self.shot(f"{width}-{screen.replace('/', '-')}")} for width, height in WIDTHS for screen in SCREENS] steps += [{"width": 1366, "height": 768, "url": f"{self.base}#{old}", "wait": 600, "probe": PROBE, "shot": None} for old in ("graph", "graph/chord", "tree")] @@ -1970,219 +217,6 @@ class TestOrchestratorE2E(HubCase): self.assertGreaterEqual(chips["inbox"]["items"], 1) self.assertEqual(chips["back"], {"hash": "#tasks/list", "rows": [["queue/gate-3", "Queue job"]]}) - def test_chromium_sends_a_call_from_the_agent_panel_and_shows_its_receipt(self): - handled = [] - - def answer() -> None: - for script, args in self.scripts.calls[len(handled) :]: - handled.append(script) - if script.endswith("radio.py") and args[:2] == ["send", "call"]: - to, text, now = args[args.index("--to") + 1], args[-1], time.time() - rows = [{"ts": now, "from": "Operator", "to": [to], "text": text, "class": "call", "v": 2}, {"ts": now + 0.5, "from": to, "to": ["Operator"], "text": text, "class": "receipt", "v": 2, "call": now}] - self.write_council({"radio-seen/e2e-callee.json": {"radio": now + 0.5}}) - (self.state / "agent-sessions.json").write_text(json.dumps({"written": now, "sessions": {"e2e-callee": {"name": to, "running": True}}}), encoding="utf-8") - with (self.council / "news.jsonl").open("a", encoding="utf-8") as handle: - handle.write(self.jsonl(rows)) - - self.beside(answer) - local = f"http://localhost:{self.port}/" - data = self.drive([{"width": 1366, "height": 768, "url": f"{local}#stream", "wait": 900, "probe": CALL, "shot": self.shot("1366-call-receipt")}], self.authenticator()) - self.assertEqual(data["errors"], []) - result = data["results"][0] - self.assertNotIn("error", result) - self.assertIsNotNone(result["receipt"], result) - self.assertTrue(" · read " in result["receipt"] and result["receipt"].endswith(" · acknowledged"), result) - self.assertEqual(result["read"], 0, result) - - def test_chromium_shows_who_speaks_while_a_message_is_read(self): - self.speaks(("e2e-cue-1", "e2e-cue-2")) - steps = [ - {"width": 1366, "height": 768, "url": f"{self.base}#stream/radio", "wait": 900, "probe": SPEAK.replace("@CUE@", "e2e-cue-1"), "shot": self.shot("1366-radio-speaking"), "gesture": True}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": SPEAK_GRAPH, "shot": self.shot("1366-agents-speaking")}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": SPEAK_END, "shot": None}, - {"width": 390, "height": 844, "url": None, "wait": 0, "probe": SPEAK.replace("@CUE@", "e2e-cue-2"), "shot": self.shot("390-radio-speaking-reduced-motion"), "gesture": True, "media": [{"name": "prefers-reduced-motion", "value": "reduce"}]}, - ] - data = self.drive(steps, None) - (OUT / "chromium-speaking.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - self.assertEqual(data["errors"], []) - speaking, graph, ended, calm = data["results"] - self.talks(speaking, graph) - self.assertEqual(ended, {"ended": True, "caption": False, "faces": 0}) - self.assertEqual((calm["who"], calm["line"], calm["ring"]), ("Stage speaking", "Disk almost full (e2e-cue-2)", "none"), calm) - self.assertEqual(calm["faces"]["speaking"], [True, "none"], calm) - - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_shows_who_speaks_and_moves_only_the_speakers_mouth(self): - self.speaks(("e2e-cue-1",)) - steps = [ - {"width": 1366, "height": 768, "url": f"{self.base}#stream/radio", "wait": 900, "probe": SPEAK.replace("@CUE@", "e2e-cue-1"), "shot": str(OUT / "firefox-1366-radio-speaking.png"), "gesture": True}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": SPEAK_GRAPH, "shot": str(OUT / "firefox-1366-agents-speaking.png")}, - ] - data = self.drive(steps, None, "bidi.mjs", os.environ.get("FIREFOX", "firefox")) - (OUT / "firefox-speaking.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) - self.talks(*data["results"]) - - def talks(self, speaking: dict, graph: dict) -> None: - """Args: - speaking: the SPEAK probe while Stage (s2) is read aloud. - graph: the SPEAK_GRAPH probe on #agents/orbit right after it. - """ - self.assertEqual((speaking["who"], speaking["line"], speaking["chip"], speaking["ring"]), ("Stage speaking", "Disk almost full (e2e-cue-1)", "s2", "speaking"), speaking) - self.assertEqual(speaking["faces"], {"speaking": [True, "talk"], "silent": [False, "none"], "keys": ["s2"]}, speaking) - self.assertEqual((graph["node"] or "").split(",")[0], "Stage", graph) - self.assertEqual((graph["ring"], graph["mouth"], graph["silent"]), ("speaking-node", "talk", "none"), graph) - - def test_chromium_records_transcribes_and_sends_a_signed_call_with_voice(self): - local = f"http://localhost:{self.port}/" - steps = [ - {"width": 1366, "height": 768, "url": f"{local}#agents/orbit", "wait": 1200, "probe": COMPOSE.replace("@TO@", "Stage"), "shot": self.shot("1366-radio-spot-composer"), "gesture": True}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": COMPOSE_SEND.replace("@ATTACH@", "false"), "shot": None}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": COMPOSE.replace("@TO@", "Stage"), "shot": None, "gesture": True}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": COMPOSE_SEND.replace("@ATTACH@", "true"), "shot": self.shot("1366-radio-spot-composer-sent")}, - ] - data = self.drive(steps, self.authenticator()) - (OUT / "chromium-composer.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - self.assertEqual(data["errors"], []) - composed, plain, again, sent = data["results"] - self.assertNotIn("error", composed) - self.assertEqual(composed["channels"], ["post", "call", "newsletter", "broadcast", "pan-pan", "security", "mayday"]) - self.assertIn("Stage", composed["recipients"]) - self.assertEqual(composed["recording"], "true") - self.assertEqual(composed["text"], "hello from the mic second line", composed) - self.assertRegex(composed["replay"] or "", r"^/api/voice/[0-9a-f]{16}\.wav$") - self.assertEqual(composed["attach"], ["Attach recording", False]) - self.assertEqual(composed["clashes"], {"found": [], "outside": []}) - self.assertEqual(again["attach"], ["Attach recording", False]) - note = again["replay"].removeprefix("/api/voice/").removesuffix(".wav") - for result in (plain, sent): - self.assertEqual((result["left"], result["voice"]), ("", False), result) - self.assertTrue(result["sent"].startswith("Call to Stage: sent"), result) - calls = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO] - self.assertEqual(len(calls), 2, self.scripts.calls) - self.assertEqual([call[:4] for call in calls], [["send", "call", "--to", "Stage"]] * 2) - self.assertTrue(calls[0][-1].endswith("] hello from the mic second line please"), calls[0]) - self.assertTrue(calls[1][-1].endswith(f"] hello from the mic second line please voice: {HOST_STATE}/voice/{note}.wav"), calls[1]) - status, _, body = self.get(f"/api/voice/{note}.wav") - self.assertEqual((status, body[:4]), (200, b"RIFF")) - - def test_chromium_clears_the_mayday_from_the_radio_spot_only_after_confirmation_and_passkey_at_three_widths(self): - local = f"http://localhost:{self.port}/" - steps = [{"width": width, "height": height, "url": f"{local}?{width}#agents/orbit", "wait": 1200, "probe": CLEAR_MAYDAY, "shot": self.shot(f"{width}-radio-spot-mayday-cleared")} for width, height in WIDTHS] - data = self.drive(steps, self.authenticator()) - (OUT / "chromium-mayday.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - self.assertEqual(data["errors"], []) - question = "Lift the radio silence of the active mayday?" - for result, (width, _) in zip(data["results"], WIDTHS, strict=True): - with self.subTest(width=width): - self.assertNotIn("error", result) - self.assertEqual(result["toolbar"], ["Priority", "Day/Night", "Drain", "Suspend", "Resume", "Status"]) - self.assertEqual((result["title"], result["shown"]), ("Cancel mayday: lift the radio silence so the agents write again; your passkey signs it", "")) - self.assertEqual(result["declined"], {"question": [question], "posted": [], "toasts": []}) - self.assertEqual(result["accepted"], {"question": [question], "posted": ["/api/board/sign", "/api/board/clear-mayday"]}) - self.assertTrue((result["done"] or "").startswith("Cancel mayday: done"), result) - self.assertEqual(self.scripts.calls, [(skill_scripts.RADIO, ["clear", "--force", "--session", "Operator"])] * len(WIDTHS)) - - def test_chromium_sends_every_class_from_the_radio_spot_and_keeps_its_gear_settings_through_a_reload_at_three_widths(self): - local = f"http://localhost:{self.port}/" - values = {1920: ("0.35", "false", "true"), 1366: ("0.45", "true", "false"), 390: ("0.55", "false", "true")} - steps = [{"width": width, "height": height, "url": f"{local}?{width}-jump#stream/radio", "wait": 1200, "probe": RADIO_JUMP, "shot": self.shot(f"{width}-radio-header-spot-every-tab")} for width, height in WIDTHS] - for width, height in WIDTHS: - squelch, tone, post = values[width] - gear = GEAR_SAVE.replace("@SQUELCH@", squelch).replace("@TONE@", tone).replace("@POST@", post) - steps += [ - {"width": width, "height": height, "url": f"{local}?{width}#agents/orbit", "wait": 1200, "probe": SPOT_SEND.replace("@TEXT@", f"spot {width}"), "shot": self.shot(f"{width}-radio-spot-sent")}, - {"width": width, "height": height, "url": None, "wait": 0, "probe": gear, "shot": None}, - {"width": width, "height": height, "url": f"{local}?{width}-reloaded#agents/orbit", "wait": 1200, "probe": GEAR_READ, "shot": self.shot(f"{width}-radio-spot-gear")}, - ] - data = self.drive(steps, self.authenticator()) - (OUT / "chromium-radio-spot.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - self.assertEqual(data["errors"], []) - labels = dict(zip(CHOICE_CHANNELS, ["Post", "Call", "Newsletter", "Broadcast", "Pan-Pan", "Sécurité", "Mayday"], strict=True)) - mayday = "Send a mayday to all? All agents pause writing steps until you cancel it." - jumps, walked = data["results"][: len(WIDTHS)], data["results"][len(WIDTHS) :] - for jump, (width, _) in zip(jumps, WIDTHS, strict=True): - with self.subTest(width=width, part="radio spot on every tab"): - self.assertEqual(jump, JUMPED) - for index, (width, _) in enumerate(WIDTHS): - sent, saved, read = walked[3 * index : 3 * (index + 1)] - squelch, tone, post = values[width] - with self.subTest(width=width): - for probe in (sent, saved, read): - self.assertNotIn("error", probe) - self.assertEqual((sent["closed"], sent["open"]), ([True, "false"], [False, "true", True])) - self.assertEqual(sent["inline"], ["static", True, True]) - self.assertEqual((sent["toolbar"], sent["channels"], sent["record"]), (["Priority", "Day/Night", "Status"], CHOICE_CHANNELS, ["Record"])) - self.assertEqual(sent["heads"], [["Read aloud", "Read aloud: the classes and agents the radio sounds for"], ["Cancel mayday", "Cancel mayday: lift the radio silence so the agents write again; your passkey signs it"]]) - self.assertEqual((sent["tall"], sent["wide"]), (width == 390, False)) - self.assertEqual([run["cls"] for run in sent["runs"]], CHOICE_CHANNELS) - for run in sent["runs"]: - direct = run["cls"] in ("post", "call") - self.assertEqual((run["direct"], run["question"], run["left"]), (direct, [mayday] if run["cls"] == "mayday" else [], ""), run) - self.assertTrue((run["toast"] or "").startswith(f"{labels[run['cls']]} to {'Stage' if direct else 'all'}: sent"), run) - self.assertEqual((saved["expanded"], saved["clashes"]), ("true", [{"found": [], "outside": []}] * 2)) - self.assertEqual(saved["tones"], ["MAYDAY / PAN-PAN", "Reviews, asks, decisions", "Post and calls to you", "All radio", "Squelch", "Threshold"]) - self.assertEqual([entry[0] for entry in saved["classes"]], ["Post", "Call", "Newsletter", "Broadcast", "MAYDAY", "PAN-PAN", "Sécurité"]) - self.assertEqual([entry[1:] for entry in saved["classes"] if entry[0] == "MAYDAY"], [["true", True]]) - self.assertEqual((saved["kept"], saved["after"]), ([float(squelch), tone == "true", post == "true"], ["false", False])) - self.assertEqual(saved["general"], {"sections": ["Ambience", "Location", "Appearance", "Music", "Notifications", "Passkey"], "radio": 0}) - self.assertEqual((saved["tall"], saved["wide"]), (width == 390, False)) - self.assertEqual(read, {"squelch": float(squelch), "tone": tone == "true", "post": post == "true", "tall": width == 390, "wide": False}) - heads = {"post": ["post", "--to", "Stage"], "call": ["send", "call", "--to", "Stage"], "newsletter": ["post"]} - radio = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO] - sends = [(width, cls) for width, _ in WIDTHS for cls in CHOICE_CHANNELS] - self.assertEqual([args[:-1] for args in radio], [[*heads.get(cls, ["send", cls]), "--session", "Operator"] for _, cls in sends]) - for args, (width, cls) in zip(radio, sends, strict=True): - with self.subTest(width=width, cls=cls): - self.assertTrue(args[-1].endswith(f"] spot {width} {cls}"), args) - self.assertEqual(self.httpd.hub.settings.get()["speech"], {"threshold": 50}) - - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_opens_the_radio_spot_on_every_tab_and_asks_the_passkey_for_every_class_and_cancel_mayday_sending_nothing_unsigned_at_three_widths(self): - self.pin() - local = f"http://localhost:{self.port}/" - steps = [] - for width, height in WIDTHS: - shot = str(OUT / f"firefox-{width}-radio-spot") - steps += [ - {"width": width, "height": height, "url": f"{local}?{width}-jump#stream/radio", "wait": 1200, "probe": RADIO_JUMP, "shot": f"{shot}-every-tab.png"}, - {"width": width, "height": height, "url": f"{local}?{width}#agents/orbit", "wait": 1200, "probe": SPOT_SEND.replace("@TEXT@", f"spot {width}"), "shot": f"{shot}-unsigned.png"}, - {"width": width, "height": height, "url": f"{local}?{width}-mayday#agents/orbit", "wait": 1200, "probe": CLEAR_MAYDAY, "shot": f"{shot}-mayday-kept.png"}, - ] - data = self.drive(steps, None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), CANCELED) - (OUT / "firefox-radio-spot.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], []) - labels = dict(zip(CHOICE_CHANNELS, ["Post", "Call", "Newsletter", "Broadcast", "Pan-Pan", "Sécurité", "Mayday"], strict=True)) - mayday = "Send a mayday to all? All agents pause writing steps until you cancel it." - question = "Lift the radio silence of the active mayday?" - hint = "Cancel mayday: lift the radio silence so the agents write again; your passkey signs it" - results = iter(data["results"]) - for width, _ in WIDTHS: - jump, sent, cleared = next(results), next(results), next(results) - with self.subTest(browser="firefox", width=width, part="radio spot on every tab"): - self.assertEqual(jump, JUMPED) - with self.subTest(browser="firefox", width=width, part="every class unsigned"): - self.assertNotIn("error", sent, sent) - self.assertEqual((sent["closed"], sent["open"], sent["inline"]), ([True, "false"], [False, "true", True], ["static", True, True])) - self.assertEqual((sent["toolbar"], sent["channels"], sent["record"]), (["Priority", "Day/Night", "Status"], CHOICE_CHANNELS, ["Record"])) - self.assertEqual(sent["heads"], [["Read aloud", "Read aloud: the classes and agents the radio sounds for"], ["Cancel mayday", hint]]) - self.assertEqual((sent["tall"], sent["wide"]), (width == 390, False)) - self.assertEqual([run["cls"] for run in sent["runs"]], CHOICE_CHANNELS) - for run in sent["runs"]: - direct = run["cls"] in ("post", "call") - self.assertEqual((run["direct"], run["question"], run["left"]), (direct, [mayday] if run["cls"] == "mayday" else [], f"spot {width} {run['cls']}"), run) - self.assertTrue((run["toast"] or "").startswith(f"{labels[run['cls']]} to {'Stage' if direct else 'all'}: not signed"), run) - self.assertIn("NotAllowedError", run["toast"], run) - with self.subTest(browser="firefox", width=width, part="icon-only cancel mayday unsigned"): - self.assertNotIn("error", cleared, cleared) - self.assertEqual(cleared["toolbar"], ["Priority", "Day/Night", "Drain", "Suspend", "Resume", "Status"]) - self.assertEqual((cleared["title"], cleared["shown"]), (hint, "")) - self.assertEqual(cleared["declined"], {"question": [question], "posted": [], "toasts": []}) - self.assertEqual(cleared["accepted"], {"question": [question], "posted": ["/api/board/sign"]}) - self.assertTrue((cleared["done"] or "").startswith("Cancel mayday: not signed"), cleared) - self.assertEqual(self.scripts.calls, []) - self.assertTrue((self.council / "radio-silence.json").exists()) - def test_chromium_keeps_the_3d_camera_through_two_state_refreshes_at_three_widths(self): steps = [{"width": width, "height": height, "url": f"{self.base}?{width}#agents/3d", "wait": 900, "probe": CAMERA, "shot": self.shot(f"{width}-agents-3d-steady-camera")} for width, height in WIDTHS] data = self.drive(steps, None, init=GRAPH_HOOK) @@ -2198,752 +232,6 @@ class TestOrchestratorE2E(HubCase): self.assertLess(math.dist(refresh["camera"], result["moved"]), 0.01, result) self.assertGreater(math.dist(result["reset"], result["moved"]), 1, result) - def check_night_menu(self, browser: str, driver: str, binary: str, signs: bool) -> None: - """Args: - signs: cdp.mjs signs every prompt with its virtual passkey; bidi.mjs - has no virtual authenticator, so the probe answers each prompt - the way a canceled passkey dialog does. - """ - authenticator = self.authenticator() - probe = NIGHT_MENU.replace("@SIGNS@", "true" if signs else "false") - looks = [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}#agents/orbit", "wait": 1200, "probe": NIGHT_LOOK, "shot": str(OUT / f"{browser}-{width}-night-menu-tooltips.png")} for width, height in WIDTHS] - step = {"width": 1366, "height": 768, "url": f"http://localhost:{self.port}/#agents/orbit", "wait": 1200, "probe": probe, "shot": str(OUT / f"{browser}-1366-night-menu.png")} - data = self.drive([*looks, step], authenticator if signs else None, driver, binary) - (OUT / f"{browser}-night-menu.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], []) - *seen, found = data["results"] - for look, (width, _) in zip(seen, WIDTHS, strict=True): - with self.subTest(browser=browser, width=width): - self.assertNotIn("error", look) - self.assertEqual(look["children"], [["span", ""], ["div", "night-picks"], ["div", "actions"]]) - self.assertEqual((look["badge"], look["paragraphs"], look["wide"]), (["Day"], 0, False)) - self.assertEqual(look["picks"], [["All", True], ["Skills", True], ["Stage", True]]) - self.assertEqual(look["buttons"], [list(entry) for entry in NIGHT_HINTS]) - self.assertNotIn("error", found) - self.assertEqual(found["labels"], ["Drain", "Suspend", "Resume"]) - for run, action in zip(found["runs"], ("drain", "suspend", "resume"), strict=True): - with self.subTest(browser=browser, action=action): - self.assertEqual(run["asked"], 1, run) - self.assertEqual(len(run["question"]), 1, run) - self.assertIn(f"kvb-agent-{action}", run["question"][0]) - signed = [["/api/board/sign", ["action"], action]] - if signs: - self.assertEqual(run["posted"], [*signed, [f"/api/board/{action}", ["proof"], None]]) - self.assertTrue((run["toast"] or "").startswith(f"{run['label']}: done"), run) - else: - self.assertEqual(run["posted"], signed) - self.assertTrue((run["toast"] or "").startswith(f"{run['label']}: not signed"), run) - nights = [args for script, args in self.scripts.calls if script == skill_scripts.NIGHT] - self.assertEqual(nights, [[action, "--session", "Operator"] for action in ("drain", "suspend", "resume")] if signs else []) - if not signs: - self.assertEqual(self.scripts.calls, []) - - def test_chromium_runs_drain_suspend_and_resume_only_after_the_passkey_signs(self): - self.check_night_menu("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium"), signs=True) - - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_asks_the_passkey_for_drain_suspend_and_resume_and_runs_nothing_unsigned(self): - self.check_night_menu("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox"), signs=False) - - def check_night_picks(self, browser: str, driver: str, binary: str, signs: bool) -> None: - """Args: - signs: as in check_night_menu. - """ - self.write_council({"night.json": {"parts": {"s2": "drain"}}}) - probe = NIGHT_PICK.replace("@SIGNS@", "true" if signs else "false") - steps = [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}#agents/orbit", "wait": 1200, "probe": probe, "shot": str(OUT / f"{browser}-{width}-night-picks.png")} for width, height in WIDTHS] - data = self.drive(steps, self.authenticator() if signs else None, driver, binary) - (OUT / f"{browser}-night-picks.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], []) - everyone, one, nobody = [["All", True], ["Skills", True], ["Stage", True]], [["All", False], ["Skills", False], ["Stage", True]], [["All", False], ["Skills", False], ["Stage", False]] - for found, (width, _) in zip(data["results"], WIDTHS, strict=True): - with self.subTest(browser=browser, width=width): - 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": ["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]) - self.assertEqual([found["drain"].split("$")[0].split()[1], found["suspend"].split("$")[0].split()[1]], ["done", "done"] if signs else ["not", "not"]) - nights = [args for script, args in self.scripts.calls if script == skill_scripts.NIGHT] - self.assertEqual(nights, [[action, "--session", "Operator", "--target=s2"] for _ in WIDTHS for action in ("drain", "suspend")] if signs else []) - calls = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO] - self.assertEqual(calls, [["send", "call", "--to", "Stage", "--session", "Operator", messaging.ALONE[action]] for _ in WIDTHS for action in ("drain", "suspend")] if signs else []) - - def test_chromium_drains_and_suspends_chosen_agents_from_the_menu_and_the_agent_panel_at_three_widths(self): - self.check_night_picks("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium"), signs=True) - - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_asks_the_passkey_for_chosen_agents_and_runs_nothing_unsigned_at_three_widths(self): - self.check_night_picks("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox"), signs=False) - - def test_chromium_deletes_a_merged_branch_after_dry_run_and_signature(self): - tree = json.loads(self.tree_file.read_text(encoding="utf-8")) - tree["delete_ready"], tree["delete_reason"] = True, "" - next(item for item in tree["repos"][0]["items"] if item["branch"] == "feature/done").update(worktree=None, worktree_state=None, actions=["local-branch", "remote-branch"], compose_projects=[], images=[], merged_by="ancestor") - self.tree_file.write_text(json.dumps(tree), encoding="utf-8") - self.write_local_plan(tree, {}) - demo = f"{self.root}/repos/github.com/me/demo" - Path(demo).mkdir(parents=True) - fake = self.outside / "bin" / "pkgmgr" - fake.parent.mkdir() - fake.write_text(FAKE_PKGMGR.format(python=sys.executable), encoding="utf-8") - fake.chmod(0o755) - (fake.parent / "plan.json").write_text(json.dumps([{"branch": "feature/done", "worktree": None, "local_sha": DONE_TIP, "head": DONE_TIP, "state": "merged-clean", "merged_by": "ancestor", "skip": None, "actions": ["local-branch"]}]), encoding="utf-8") - following = json.loads(json.dumps(tree)) - following["repos"][0]["items"] = [item for item in following["repos"][0]["items"] if item["branch"] != "feature/done"] - (fake.parent / "next-tree.json").write_text(json.dumps(following), encoding="utf-8") - authenticator = self.authenticator() - trust = verifier.Trust(approvers=self.approvers, replay=self.replay / "cleanup.json", origin=self.origin) - runner = host.Cleanup(trust, self.tree_file, fake) - jobs, results = self.cleanup / "jobs", self.cleanup / "results" - self.beside(lambda: any(jobs.iterdir()) and host.cycle(jobs, results, runner)) - local = f"http://localhost:{self.port}/" - steps = [ - {"width": 1366, "height": 768, "url": f"{local}#artifacts/tree", "wait": 1200, "probe": OPEN_DELETE, "shot": self.shot("1366-delete-dry-run")}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": CONFIRM, "shot": self.shot("1366-delete-result")}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": AFTER, "shot": self.shot("1366-delete-tree-after")}, - ] - data = self.drive(steps, authenticator) - (OUT / "chromium-delete.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - self.assertEqual(data["errors"], []) - opened, confirmed, after = data["results"] - self.assertNotIn("error", opened) - self.assertEqual(opened["every"], [False, "Delete all merged: 1 branches after dry run and signature"]) - self.assertEqual(opened["buttons"], [[False, "Delete: remove feature/done locally, after dry run and signature"]]) - self.assertEqual(opened["title"], "Delete feature/done") - self.assertEqual(len(opened["dry"]), 1) - self.assertTrue(opened["dry"][0].startswith("feature/done @ 5b1e6fd3a7c0: merged-clean, merged by ancestor"), opened["dry"]) - self.assertIn("stays: remote-branch (local only; the host refuses a plan that deletes it)", opened["dry"][0]) - self.assertEqual((confirmed["result"], confirmed["text"]), ("done", "feature/donedeleted"), confirmed) - self.assertEqual(confirmed["toasts"], ["Delete: donefeature/done: deleted"]) - self.assertEqual(after["past"], ["done", "deleted"]) - self.assertNotIn("feature/done", after["branches"]) - written = [json.loads(path.read_text(encoding="utf-8")) for path in results.glob("*.json")] - self.assertEqual([[(item["branch"], item["status"]) for item in result["items"]] for result in written], [[("feature/done", "done")]]) - calls = [json.loads(line)["argv"] for line in (fake.parent / "calls.jsonl").read_text(encoding="utf-8").splitlines()] - self.assertEqual(calls, [ - ["branch", "cleanup", "--local", "--json", "--branch", "feature/done"], - ["branch", "cleanup", "--apply", "--local", "--json", "--branch", "feature/done"], - ["branch", "tree", "--format", "json", "--output", str(self.tree_file)], - ]) - - def test_chromium_shows_a_branch_the_local_dry_run_keeps_without_delete_and_offers_one_whose_local_tip_it_deletes(self): - squashed_tip, cherry_tip, cherry_remote = "9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b", "8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c", "7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d" - tree = json.loads(self.tree_file.read_text(encoding="utf-8")) - tree["delete_ready"], tree["delete_reason"] = True, "" - items = tree["repos"][0]["items"] - kept = next(item for item in items if item["branch"] == "feature/kept") - kept["skip"] = None - items.append({**kept, "branch": "feature/squashed", "local_sha": squashed_tip, "upstream": "origin/feature/squashed", "ahead": 0, "behind": 0, "remotes": {"origin": squashed_tip}, - "merged_by": "pr#7", "actions": ["local-branch", "remote-branch:origin"], "reason": "merged by pr#7"}) - items.append({**kept, "branch": "feature/cherry", "local_sha": cherry_tip, "upstream": "origin/feature/cherry", "ahead": 0, "behind": 1, "remotes": {"origin": cherry_remote}, - "merged_by": "patch", "actions": ["local-branch", "remote-branch:origin"], "reason": "merged by patch"}) - self.tree_file.write_text(json.dumps(tree), encoding="utf-8") - self.write_local_plan(tree, {"feature/cherry": {"skip": None, "actions": ["local-branch"]}}) - demo = f"{self.root}/repos/github.com/me/demo" - local = f"http://localhost:{self.port}/" - steps = [ - {"width": 1366, "height": 768, "url": f"{local}#artifacts/tree", "wait": 1200, "probe": KEPT_TREE, "shot": self.shot("1366-kept-tree")}, - {"width": 1366, "height": 768, "url": f"{local}?kept#artifacts/orbit", "wait": 1200, "probe": KEPT_POPUP.replace("@REPO@", json.dumps(demo)), "shot": self.shot("1366-kept-popup")}, - ] - data = self.drive(steps, None) - (OUT / "chromium-kept.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], []) - shown, popup = data["results"] - self.assertNotIn("error", shown, shown) - self.assertNotIn("error", popup, popup) - kept_line = "pkgmgr branch cleanup --local keeps it: merged by pr#7, tip is no ancestor of refs/remotes/origin/main; use branch gc (kvb-git-gc, pkgmgr gc)" - plan = f"feature/squashed @ {squashed_tip[:12]}: merged-clean, merged by pr#7\n{kept_line}\nbranch gc would delete the local branch feature/squashed\nbranch gc would delete remote-branch:origin" - self.assertEqual((shown["kept"], shown["rowDeletes"], shown["deletes"]), ([kept_line, kept_line], 0, ["feature/kept", "feature/cherry"])) - self.assertIn("1 kept by the --local dry run: see each dry run", shown["header"]) - self.assertEqual([row[:3] for row in shown["rows"]], [["feature/kept", None, 0], ["feature/cherry", None, 0], ["feature/done", "held", 0], ["feature/squashed", "kept", 0]]) - self.assertEqual(shown["rows"][1][3], f"feature/cherry @ {cherry_tip[:12]}: merged-clean, merged by patch\ndeletes the local branch feature/cherry\nstays: remote-branch:origin (local only; the host refuses a plan that deletes it)") - self.assertEqual(shown["rows"][3][3], plan) - self.assertEqual((shown["confirms"], shown["title"]), (1, "Delete 2 merged branches")) - self.assertEqual((popup["title"], popup["heading"], popup["dry"], popup["deletes"], popup["kept"]), ("feature/squashed", "Dry run", plan, 0, kept_line)) - status, _, body = self.post_json("/api/sign", {"items": [{"kind": "cleanup", "repository": demo, "branch": "feature/squashed", "worktree": "", "tip": squashed_tip}]}, self.guard(self.host)) - self.assertEqual((status, body.decode()), (400, f"feature/squashed in {demo} is no merged-clean branch without skip reason that the --local dry run deletes at that tip\n")) - self.assertEqual(list((self.cleanup / "jobs").glob("*.json")), []) - - def test_chromium_folds_the_hierarchy_by_keyboard_reorders_agents_and_hands_an_office_over_with_a_signature(self): - signer = self.pin() - trust = verifier.Trust(approvers=self.approvers, replay=self.replay / "offices.json", origin=self.origin) - runner = office_host.Offices(trust, self.council, COUNCIL_SCRIPT, self.outside / "home") - jobs, results = self.offices / "jobs", self.offices / "results" - self.beside(lambda: any(jobs.iterdir()) and office_host.cycle(jobs, results, runner)) - private = "".join(line for line in signer.pem.read_text(encoding="utf-8").splitlines() if not line.startswith("-----")) - authenticator = {"credentialId": base64.b64encode(signer.raw_id).decode(), "privateKey": private, "rpId": "localhost"} - local = f"http://localhost:{self.port}/" - steps = [ - {"width": 1366, "height": 768, "url": f"{local}#agents/hierarchy", "wait": 1200, "probe": ORG_OPEN, "shot": self.shot("1366-hierarchy-open")}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "keys": ["Enter"], "probe": ORG_FOLDED, "shot": None}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "keys": ["Enter"], "probe": ORDER_MOVED, "shot": self.shot("1366-hierarchy-order")}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": OPEN_TAKEOVER, "shot": self.shot("1366-hierarchy-takeover")}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": CONFIRM_TAKEOVER, "shot": self.shot("1366-hierarchy-takeover-result")}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": AFTER_TAKEOVER, "shot": self.shot("1366-hierarchy-after")}, - ] - data = self.drive(steps, authenticator) - (OUT / "chromium-hierarchy.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - self.assertEqual(data["errors"], []) - opened, folded, moved, sheet, confirmed, after = data["results"] - self.assertNotIn("error", opened) - self.assertEqual(opened["focused"], "toggle:dimension:identity") - self.assertEqual((folded["focused"], folded["expanded"], folded["label"], folded["hidden"], folded["again"]), ("toggle:dimension:identity", "false", "Expand: identity", True, "true")) - self.assertNotIn("identity/oidc", folded["seen"]) - before = folded["before"] - self.assertEqual(moved["after"], [before[1], before[0], *before[2:]]) - self.assertEqual((moved["focused"], moved["disabled"]), (f"down:{before[1]}", False)) - self.assertTrue(moved["toast"].startswith("Priority"), moved) - self.assertIn(("rasci.py", ["agents", "order", ",".join(moved["after"])]), [(Path(script).name, args) for script, args in self.scripts.calls]) - self.assertEqual((sheet["title"], sheet["options"], sheet["work"], sheet["focused"]), ("identity/oidc: Hand over", ["s1"], "oidc line", "SELECT")) - self.assertEqual((confirmed["result"], confirmed["text"]), ("done", "identity/oidcdone"), confirmed) - self.assertIn("Hand over: doneidentity/oidc: done", confirmed["toasts"]) - self.assertNotIn("error", after) - claim = json.loads((self.council / "identity" / "oidc" / "claim.json").read_text(encoding="utf-8")) - self.assertEqual((claim["session"], claim["work"]), ("s1", "oidc line")) - written = [json.loads(path.read_text(encoding="utf-8")) for path in results.glob("*.json")] - self.assertEqual([[(item["office"], item["action"], item["status"]) for item in result["items"]] for result in written], [[("identity/oidc", "takeover", "done")]]) - - def inbox_work(self) -> None: - stage = {"title": "Stage line", "status": "running", "worker": "Stage (this session)", "roles": {"Stage (this session)": "RA"}} - greet = {"title": SLOW, "workdir": str(self.outside), "description": "counts", "check": "manual", "status": "queued", "roles": {"Operator": "R", "Skills session": "A"}} - push = {"title": "git push", "workdir": "/repo", "description": "ship", "check": "manual", "status": "queued", "roles": {"Operator": "R", "Skills session": "A"}} - self.write_council({"rasci.json": {"work/stage": stage, "operator/greet": greet, "operator/push": push}}) - arguments = {"kind": "ask", "tool": "Bash", "pattern": "make deploy", "scope": "/repo*", "expires": int(time.time()) + 7 * 86400, "agent": "Skills", "why": "deploy runs after every green gate"} - self.assertFalse(self.tool("rule_request", arguments)["isError"]) - - def layout(self, probe: dict) -> None: - self.assertNotIn("error", probe) - self.assertEqual(sorted(probe["kinds"]), ["Ask", "Operator", "Operator", "Review", "Rule request"]) - self.assertIn(["Deny", "Deny via …"], probe["splits"]) - self.assertEqual(len(probe["splits"]), 4) - self.assertEqual(probe["fields"], ["Kind", "Tool (glob)", "Pattern (glob)", "Directory (glob)", "Expires on"]) - self.assertEqual(probe["dry"], "Dry run: the rule would have granted 1 of 1 asks from the last 7 days.") - self.assertEqual(probe["accept"], 1) - self.assertTrue(probe["fits"] and probe["followed"], probe) - self.assertEqual((probe["unlabelled"], probe["wide"]), ([], False)) - - def test_chromium_runs_a_command_into_its_console_denies_by_call_and_accepts_a_rule(self): - self.inbox_work() - signer = self.pin() - trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "runner.json")] - - def run_jobs() -> None: - if any(job["status"] == "queued" for job in self.httpd.hub.jobs.listed()): - subprocess.run([sys.executable, str(RUNNER), "--port", str(self.port), "--interval", "0.1", *trust, "--once"], capture_output=True, timeout=120, check=False) - - self.beside(run_jobs) - private = "".join(line for line in signer.pem.read_text(encoding="utf-8").splitlines() if not line.startswith("-----")) - authenticator = {"credentialId": base64.b64encode(signer.raw_id).decode(), "privateKey": private, "rpId": "localhost"} - inbox = f"http://localhost:{self.port}/#stream/inbox" - steps = [ - {"width": 1366, "height": 768, "url": inbox, "wait": 1200, "probe": RUN_START, "shot": self.shot("1366-inbox-console-running")}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": RUN_HELD, "shot": self.shot("1366-inbox-console-scrolled-up")}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": RUN_DONE, "shot": self.shot("1366-inbox-console-done")}, - ] - for width, height in WIDTHS: - fresh = f"http://localhost:{self.port}/?{width}#stream/inbox" - steps.append({"width": width, "height": height, "url": fresh, "wait": 1200, "probe": LAYOUT, "shot": self.shot(f"{width}-inbox-console")}) - steps.append({"width": width, "height": height, "url": None, "wait": 0, "probe": DENY_SHEET, "shot": self.shot(f"{width}-inbox-deny-sheet")}) - steps += [ - {"width": 1366, "height": 768, "url": inbox, "wait": 1200, "probe": DENY, "shot": self.shot("1366-inbox-deny-undo")}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": DENIED, "shot": None}, - {"width": 1366, "height": 768, "url": None, "wait": 0, "probe": ACCEPT, "shot": self.shot("1366-inbox-rule-accepted")}, - ] - data = self.drive(steps, authenticator) - (OUT / "chromium-inbox.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - self.assertEqual(data["errors"], []) - started, held, done, *rest = data["results"] - self.assertNotIn("error", started) - self.assertIn("takes effect in", started["toast"]) - self.assertTrue(started["running"].startswith("running"), started) - self.assertTrue(started["overflows"] and started["followed"], started) - self.assertLess(held["held"], 50, held) - self.assertEqual((done["last"], done["lines"], done["followed"]), ("finished", 81, True)) - self.assertRegex(done["done"], r"^doneExit code 0 after \d+ s$") - self.assertIn("Close", done["actions"]) - layouts, sheets = rest[0:6:2], rest[1:6:2] - for probe, sheet, (width, _) in zip(layouts, sheets, WIDTHS, strict=True): - with self.subTest(width=width): - self.layout(probe) - self.assertTrue(probe["console"].startswith("doneExit code 0"), probe) - self.assertEqual(sheet["title"], "Deny") - self.assertEqual(sheet["channels"], [["post", True], ["call", False], ["newsletter", False], ["broadcast", False], ["pan-pan", False], ["security", False]]) - self.assertEqual(sheet["hints"][:3], ["to Skills, when its turn ends", "to Skills, at once, wakes it", "to all, when their turn ends"]) - self.assertEqual((sheet["reason"], sheet["unlabelled"], sheet["wide"]), (True, [], False)) - denied, gone, accepted = rest[6:] - self.assertNotIn("error", denied, denied) - self.assertTrue(denied["undo"].startswith("Denial (Call): Bash: make deploy"), denied) - self.assertFalse(denied["sheet"]) - self.assertTrue(gone["gone"]) - self.assertEqual((accepted["toast"], accepted["left"]), ("Created: Rule: ask Bash make deploy in /repo*", False)) - ask = self.httpd.hub.asks.listed()[0] - self.assertEqual((ask["status"], ask["reason"], ask["channel"]), ("denied", "make the gate green first", "call")) - calls = [args for script, args in self.scripts.calls if script.endswith("radio.py")] - self.assertEqual(calls[-1][:4], ["send", "call", "--to", "Skills session"]) - self.assertTrue(calls[-1][-1].endswith("Reason: make the gate green first"), calls[-1]) - self.assertEqual([(rule["kind"], rule["pattern"], rule["proof"] is not None) for rule in self.httpd.hub.rules.listed()], [("ask", "make deploy", True)]) - self.assertEqual([(job["status"], job["code"]) for job in self.httpd.hub.jobs.listed()], [("done", 0)]) - - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_draws_the_inbox_console_and_the_rule_request_at_three_widths(self): - self.inbox_work() - now = time.time() - fields = {"task": "operator/greet", "command": SLOW, "directory": str(self.outside), "sha256": "", "status": "done", "proof": None} - output = "".join(f"Row {number}\n" for number in range(1, 81)) + "finished\n" - self.httpd.hub.jobs.add({**fields, "code": 0, "output": output, "created_ts": now - 20, "started": now - 19, "finished": now - 10, "dismissed": False}) - shots = [(width, height, OUT / f"firefox-{width}-inbox-console.png") for width, height in WIDTHS] - steps = [{"width": width, "height": height, "url": f"{self.base}#stream/inbox", "wait": 1200, "probe": LAYOUT, "shot": str(shot)} for width, height, shot in shots] - data = self.drive(steps, None, "bidi.mjs", os.environ.get("FIREFOX", "firefox")) - (OUT / "firefox-inbox.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], []) - for probe, (width, _, shot) in zip(data["results"], shots, strict=True): - with self.subTest(width=width): - self.layout(probe) - self.assertEqual(probe["console"], "doneExit code 0 after 9 s") - self.assertTrue(shot.is_file() and shot.stat().st_size > 1000, shot) - - def check_inbox_picks(self, browser: str, driver: str, binary: str, signs: bool) -> None: - """Args: - signs: as in check_night_menu. - """ - fill = {"description": "fill", "workdir": "/repo", "status": "queued", "roles": {"Operator": "R", "Skills session": "A"}} - rows = {f"operator/row-{n:02}": {**fill, "title": f"echo row {n:02}", "check": "manual", "seq": n} for n in range(1, 15)} - rows["operator/name"] = {**fill, "title": "pick a name", "check": "decision", "seq": 15} - self.write_council({"rasci.json": rows}) - probe = INBOX_PICK.replace("@SIGNS@", "true" if signs else "false") - steps = [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}#stream/inbox", "wait": 1200, "probe": probe, "shot": str(OUT / f"{browser}-{width}-inbox-deny-selection.png")} for width, height in WIDTHS] - stops = [] - with mock.patch.object(batches, "UNDO", 0.3): - data = self.drive(steps, self.authenticator() if signs else None, driver, binary) - if signs: - self.settle(lambda: len([call for call in self.scripts.calls if call[0] == skill_scripts.RASCI]) >= 2 * len(WIDTHS)) - stops = [args for script, args in self.scripts.calls if script == skill_scripts.RASCI] - (OUT / f"{browser}-inbox-deny-selection.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], []) - denied = [] - for found, (width, _) in zip(data["results"], WIDTHS, strict=True): - with self.subTest(browser=browser, width=width): - self.assertNotIn("error", found) - self.assertGreater(found["before"], 0, found) - self.assertEqual((found["moved"], found["focused"], found["wide"]), (0, True, False), found) - self.assertTrue({"Grant selection (1)", "Deny selection (2)"} <= set(found["buttons"]), found["buttons"]) - self.assertEqual((sorted(found["listed"]), found["label"]), (sorted([found["title"], "pick a name"]), "Deny 2")) - task = f"operator/row-{found['title'][-2:]}" - items = sorted([[task, "reject", "post"], ["operator/name", "reject", "post"]]) - self.assertEqual([[path, sorted(entries)] for path, entries in found["posted"]], [["/api/sign", items], *([["/api/inbox/approve", items]] if signs else [])]) - self.assertIn("takes effect" if signs else "not signed", found["toast"]) - denied += [task, "operator/name"] - self.assertEqual(sorted(stops), sorted([["set", task, "--status", "stopped"] for task in denied]) if signs else []) - - def test_chromium_keeps_the_inbox_scroll_on_a_tick_and_denies_a_selection_with_one_signature_at_three_widths(self): - self.check_inbox_picks("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium"), signs=True) - - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_keeps_the_inbox_scroll_on_a_tick_and_denies_nothing_unsigned_at_three_widths(self): - self.check_inbox_picks("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox"), signs=False) - - def choice_steps(self, browser: str, signs: bool, questions: dict[int, str]) -> list[dict]: - flag = "true" if signs else "false" - local = f"http://localhost:{self.port}/" - steps = [] - for index, (width, height) in enumerate(WIDTHS): - cards = len(WIDTHS) - index if signs else len(WIDTHS) - steps += [ - {"width": width, "height": height, "url": f"{local}?{width}#stream/inbox", "wait": 1200, "probe": CHOICE_VIEW.replace("@CARDS@", str(cards)), "shot": str(OUT / f"{browser}-{width}-tasks-choices.png")}, - {"width": width, "height": height, "url": None, "wait": 0, "probe": CHOICE_SEND.replace("@SIGNS@", flag), "shot": str(OUT / f"{browser}-{width}-choice-request.png")}, - {"width": width, "height": height, "url": None, "wait": 0, "probe": CHOICE_ANSWER.replace("@SIGNS@", flag).replace("@QUESTION@", questions[width]), "shot": str(OUT / f"{browser}-{width}-choice-answer.png")}, - *({"width": width, "height": height, "url": f"{local}?{width}#tasks/{view}", "wait": 900, "probe": TASKS_FIT, "shot": str(OUT / f"{browser}-{width}-tasks-{view}-fit.png")} for view in TASK_VIEWS), - ] - return steps - - def requested(self, sent: dict, signs: bool) -> None: - """Args: - sent: the CHOICE_SEND probe: two agents ticked, then every channel - button pressed once. - """ - labels = dict(zip(CHOICE_CHANNELS, ["Post", "Call", "Newsletter", "Broadcast", "Pan-Pan", "Sécurité", "Mayday"], strict=True)) - self.assertEqual(len(sent["picked"]), 2, sent) - self.assertEqual((sent["counted"], sent["fields"], sent["tall"], sent["wide"]), ("2", 0, False, False)) - self.assertEqual(sent["opened"], [True, len(CHOICE_CHANNELS)]) - self.assertEqual([run["channel"] for run in sent["runs"]], CHOICE_CHANNELS) - for run in sent["runs"]: - with self.subTest(channel=run["channel"]): - to = sent["picked"] if run["channel"] in ("post", "call") else ["*"] - signed = [["/api/choices/sign", ["class", "to"], run["channel"], to]] - self.assertEqual((run["disabled"], run["asked"], len(run["question"])), (False, 1, int(run["channel"] == "mayday")), run) - title = f"Choice request ({labels[run['channel']]}) to {', '.join(to) if to != ['*'] else 'all'}" - self.assertEqual(run["posted"], [*signed, ["/api/choices", ["class", "proof", "to"], run["channel"], to]] if signs else signed) - self.assertTrue((run["toast"] or "").startswith(f"{title}: {'sent' if signs else 'not signed'}"), run) - - def answered(self, result: dict, signs: bool) -> None: - self.assertNotIn("error", result) - self.assertEqual((result["title"], result["asked"], result["closed"], result["tall"], result["wide"]), ("Wait: your passkey signs this answer, a post to Stage", 1, [False, 0], False, False)) - signed = [["/api/sign", ["items"], None, None]] - self.assertEqual(result["posted"], [*signed, ["/api/inbox/approve", ["items", "proof"], None, None]] if signs else signed) - self.assertTrue((result["toast"] or "").startswith("Choice: Wait" + ("" if signs else ": not signed")), result) - self.assertEqual(result["gone"], True if signs else None) - - def check_choices(self, browser: str, driver: str, binary: str, signs: bool) -> None: - """Args: - signs: cdp.mjs signs every prompt with its virtual passkey; bidi.mjs - has no virtual authenticator, so the probes answer each prompt - the way a canceled passkey dialog does. - """ - self.inbox_work() - self.create_ask({**ASK, "command": "make choices", "timeout": 3600}) - authenticator = self.authenticator() - questions = {width: f"Pick a name at {width} px?" for width, _ in WIDTHS} - decisions = {width: self.tool("decision_request", {"question": question, "options": OPTIONS, "agent": "Stage", "recommended": ""})["structuredContent"]["id"] for width, question in questions.items()} - data = self.drive(self.choice_steps(browser, signs, questions), authenticator if signs else None, driver, binary) - (OUT / f"{browser}-choices.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], []) - per = 3 + len(TASK_VIEWS) - for index, (width, _) in enumerate(WIDTHS): - view, sent, answer, *fitted = data["results"][per * index : per * (index + 1)] - with self.subTest(browser=browser, width=width): - self.assertNotIn("error", view) - self.assertEqual(view["kinds"], ["Ask", "Choice", "Operator", "Review", "Rule request"]) - self.assertEqual(view["filter"], ["Waits on Operator", "true"]) - self.assertEqual(view["channels"], [[channel, label, channel in ("post", "call")] for channel, label in zip(CHOICE_CHANNELS, ["Post", "Call", "Newsletter", "Broadcast", "Pan-Pan", "Sécurité", "Mayday"], strict=True)]) - self.assertEqual((view["fields"], view["choices"], view["multi"], view["unlabelled"], view["tall"], view["wide"]), (0, 0, ["Request choices", False, 0, "0", 0], [], False, False)) - self.assertEqual(view["bar"], ["Tasks", view["bar"][1], ["toolbar", "chips", "body"]]) - self.assertEqual(view["bar"][1] == 1, width != 390, view["bar"]) - self.assertGreaterEqual(len(view["agents"]), 2, view) - self.assertIn(["Choice", ["Merge now", "Wait"]], view["cards"]) - self.requested(sent, signs) - self.answered(answer, signs) - for fit, name in zip(fitted, TASK_VIEWS, strict=True): - self.assertEqual((fit["hash"], fit["bar"], fit["choices"], fit["tall"], fit["wide"]), (f"#tasks/{name}", CHOICE_CHANNELS, 0, False, False), fit) - self.assertEqual((fit["rows"] == 1, fit["layout"]), (width != 390, ["toolbar", "chips", "body"]), fit) - if name == "board": - self.assertEqual(fit["columns"], ["queued", "running", "done"]) - hub = self.httpd.hub - if not signs: - self.assertEqual((self.scripts.calls, hub.messages.listed()), ([], [])) - self.assertEqual([hub.decisions.get(decision)["status"] for decision in decisions.values()], ["pending"] * len(WIDTHS)) - return - requests = [record for record in hub.messages.listed() if record["text"] == CHOICE_REQUEST] - self.assertEqual((len(requests), sorted({record["class"] for record in requests})), (len(WIDTHS) * 9, sorted(CHOICE_CHANNELS))) - for record in requests: - self.assertTrue(self.tool("operator_message", {"id": record["id"], "text": CHOICE_REQUEST, "to": record["to"]})["structuredContent"]["match"], record["id"]) - radio = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO] - self.assertEqual(len(radio), len(requests) + len(WIDTHS)) - for width, decision in decisions.items(): - with self.subTest(width=width): - state = self.tool("decision_wait", {"id": decision, "timeout_seconds": 0})["structuredContent"] - self.assertEqual((state["status"], state["choice"], state["answer"]), ("decided", "Wait", f"Choice for decision {decision} ({questions[width]}): Wait")) - found = self.tool("operator_message", {"id": state["message"], "text": state["answer"], "to": "Stage"})["structuredContent"] - self.assertEqual((found["match"], found["class"], found["to"]), (True, "post", "Stage")) - self.assertIn(["post", "--to", "Stage", "--session", "Operator", f"[kvb-orchestrator msg {state['message']}] {state['answer']}"], radio) - - def test_chromium_requests_choices_on_every_channel_and_signs_a_choice_at_three_widths(self): - self.check_choices("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium"), signs=True) - - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_asks_the_passkey_for_every_choice_request_and_answer_and_sends_nothing_unsigned(self): - self.check_choices("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox"), signs=False) - - def plan_work(self, now: float) -> None: - register = json.loads((self.council / "rasci.json").read_text(encoding="utf-8")) - register["work/feature"]["start"] = iso(now - 1800) - register["work/stage"]["start"] = iso(now - 900) - register.update({ - "work/done-a": {"title": "Done A", "status": "done", "worker": "Stage", "branch": "feature/base", "start": iso(now - 36000), "end": iso(now - 28800), "roles": {"Stage": "RA"}, "estimates": {"Stage": {"value": 5, "complexity": 2}}}, - "work/done-b": {"title": "Done B", "status": "done", "worker": "Docs", "start": iso(now - 25200), "end": iso(now - 10800), "roles": {"Docs": "RA"}, "estimates": {"Docs": {"value": 3, "complexity": 2}}}, - "work/done-c": {"title": "Done C", "status": "done", "worker": "Docs", "start": iso(now - 14400), "end": iso(now - 10800), "roles": {"Docs": "RA"}}, - "work/next": {"title": "Next step", "status": "queued", "after": ["work/feature"], "roles": {"Skills": "R", "Maintainer": "A"}, "estimates": {"Skills": {"value": 8, "complexity": 3}}}, - "work/child": {"title": "Child of the base", "status": "queued", "base": "feature/base", "roles": {"Docs": "RA"}}, - }) - queue = json.loads((self.council / "queue.json").read_text(encoding="utf-8")) - queue["entries"] += [ - {"id": "deploy-4", "seq": 4, "kind": "deploy", "task": "work/stage", "workdir": "/repo", "session": "s2", "name": "Stage", "hotfix": None, "status": "active", "enqueued": now - 400, "granted": now - 300, "cmd": "make deploy"}, - {"id": "test-5", "seq": 5, "kind": "test", "task": "work/docs", "workdir": "/repo", "session": "s2", "name": "Docs", "hotfix": None, "status": "waiting", "enqueued": now - 60, "granted": None, "cmd": "make test"}, - ] - self.write_council({"rasci.json": register, "queue.json": queue}) - - def plan_steps(self, browser: str, signs: bool) -> list[dict]: - local = f"http://localhost:{self.port}/" - flag = "true" if signs else "false" - steps = [] - for width, height in WIDTHS: - bulk = BULK.replace("@SIGNS@", flag).replace("@VALUE@", PLAN_VALUES[width]) - steps += [ - {"width": width, "height": height, "url": f"{local}?{width}#tasks/gantt", "wait": 1200, "probe": GANTT, "shot": str(OUT / f"{browser}-{width}-tasks-gantt.png")}, - {"width": width, "height": height, "url": f"{local}?{width}#tasks/burn", "wait": 900, "probe": BURN, "shot": str(OUT / f"{browser}-{width}-tasks-burn.png")}, - {"width": width, "height": height, "url": None, "wait": 0, "probe": POINTS_ON, "shot": None}, - {"width": width, "height": height, "url": f"{local}?{width}-reloaded#tasks/burn", "wait": 1200, "probe": REQUEST, "shot": str(OUT / f"{browser}-{width}-tasks-burn-points.png")}, - {"width": width, "height": height, "url": f"{local}?{width}-points#tasks/gantt", "wait": 1200, "probe": GANTT, "shot": str(OUT / f"{browser}-{width}-tasks-gantt-points.png")}, - {"width": width, "height": height, "url": f"{local}?{width}-list#tasks/list", "wait": 1200, "probe": bulk, "shot": str(OUT / f"{browser}-{width}-tasks-business-value.png")}, - ] - return steps - - def planned(self, probe: dict, points: bool) -> None: - hour = 3600 - edges = [["after", "work/feature", "work/next"], ["base", "work/done-a", "work/child"], ["queue", "queue/deploy-4", "queue/gate-3"], ["queue", "queue/gate-3", "queue/test-5"]] - self.assertEqual(probe["forecast"], ["always", [["always", "always"], ["points", "points only"], ["real", "real only"]]]) - self.assertEqual(probe["modes"], [["none", str(not points).lower()], ["points", str(points).lower()]]) - self.assertEqual((probe["request"], probe["inner"]), (points, True)) - self.assertEqual(sorted([kind, start, end] for kind, start, end, _ in probe["edges"]), sorted(edges)) - self.assertEqual({tip for *_, tip in probe["edges"]}, {"url(#gantt-tip)"}) - bars = {task: (forecast, start, end, tag) for task, forecast, start, end, tag in probe["bars"]} - self.assertNotIn("operator/push", bars) - self.assertEqual((bars["work/old"][0], bars["work/old"][3]), (False, "circle")) - self.assertEqual([bars[task][0] for task in ("work/feature", "work/stage", "queue/deploy-4", "work/done-a")], [False] * 4) - self.assertGreaterEqual(bars["work/feature"][2] - bars["work/feature"][1], 1800) - forecasts = ("work/next", "work/docs", "work/child", "queue/gate-3", "queue/test-5") - lengths = {task: round(bars[task][2] - bars[task][1], 3) for task in forecasts} - self.assertEqual(lengths, {"work/next": (4.5 if points else 2) * hour, "work/docs": (3 if points else 2) * hour, "work/child": 2 * hour, "queue/gate-3": 2 * hour, "queue/test-5": 2 * hour}) - self.assertTrue(all(bars[task][0] for task in forecasts)) - self.assertEqual((bars["work/next"][1], bars["queue/test-5"][1]), (bars["work/feature"][2], bars["queue/gate-3"][2])) - self.assertTrue(probe["hatched"] and all(probe["hatched"]), probe["hatched"]) - self.assertEqual(probe["real"], 0) - only = {task: (round(length, 3), tag) for task, length, tag in probe["pointsOnly"]} - dot = (0, "circle") - self.assertEqual(only, {"work/next": (4.5 * hour, "rect") if points else dot, "work/docs": (3 * hour, "rect") if points else dot, "work/child": dot, "queue/gate-3": dot, "queue/test-5": dot}) - - def check_plan(self, browser: str, driver: str, binary: str, signs: bool) -> None: - """Args: - signs: cdp.mjs signs the bulk business value with its virtual - passkey; bidi.mjs has no virtual authenticator, so the probe - answers the prompt the way a canceled passkey dialog does. - """ - self.plan_work(time.time()) - authenticator = self.authenticator() - data = self.drive(self.plan_steps(browser, signs), authenticator if signs else None, driver, binary) - (OUT / f"{browser}-plan.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], []) - rows = self.snapshot()["tasks"] - ranked = list(enumerate(rows)) - status_up = [row["task"] for _, row in sorted(ranked, key=lambda pair: (STATUS_ORDER.index(pair[1]["status"]), pair[0]))] - status_down = [row["task"] for _, row in sorted(ranked, key=lambda pair: (-STATUS_ORDER.index(pair[1]["status"]), pair[0]))] - for index, (width, _) in enumerate(WIDTHS): - gantt, burn, points_on, request, gantt_points, bulk = data["results"][6 * index : 6 * (index + 1)] - value = PLAN_VALUES[width] - items = [["work/next", f"estimate work/next Operator --value {value}"], ["work/child", f"estimate work/child Operator --value {value}"]] - with self.subTest(browser=browser, width=width): - for probe in (gantt, burn, points_on, request, gantt_points, bulk): - self.assertNotIn("error", probe) - self.assertEqual((probe["tall"], probe["wide"], probe["layout"]), (False, False, ["toolbar", "chips", "body"]), probe) - self.assertEqual(probe["rows"] == 1, width != 390, probe) - self.planned(gantt, points=False) - self.planned(gantt_points, points=True) - self.assertEqual((burn["modes"], burn["request"]), ([["none", "true"], ["points", "false"]], False)) - self.assertEqual(burn["scope"][0], "all") - self.assertEqual(burn["scope"][1][:2], ["all", "filter"]) - self.assertIn("agent:Docs", burn["scope"][1]) - self.assertIn("line:identity/oidc", burn["scope"][1]) - self.assertEqual(burn["series"], [["scope", 9], ["done", 4], ["remaining", 5]]) - self.assertEqual(burn["agent"], [["scope", 5], ["done", 2], ["remaining", 3]]) - self.assertEqual(points_on["before"], {"modes": [["none", "true"], ["points", "false"]], "request": False}) - self.assertEqual((points_on["modes"], points_on["request"]), ([["none", "false"], ["points", "true"]], True)) - self.assertEqual(request["modes"], [["none", "false"], ["points", "true"]]) - self.assertEqual(request["series"], [["scope", 12], ["done", 4], ["remaining", 8], ["unestimated", 2]]) - self.assertTrue(request["toast"].startswith(f"Request estimates: {'done' if signs else 'not signed'}"), request["toast"]) - self.assertEqual(bulk["sorts"], ["prio", "wsjf", "value", "complexity", "status", "start", "end", "agent", "title"]) - self.assertEqual((bulk["prio"], bulk["status"], bulk["statusDown"]), ([row["task"] for row in rows], status_up, [status_down, "Descending"])) - self.assertEqual((bulk["picks"], bulk["armed"]), (["work/feature", "work/next", "work/docs", "work/child", "work/stage"], [False, "2"])) - self.assertTrue(bulk["toast"].startswith(f"Business value {value} for 2 tasks: {'handed to the runner' if signs else 'not signed'}"), bulk["toast"]) - signed = [["/api/sign", ["items"], items]] - self.assertEqual((bulk["asked"], bulk["posted"]), (1, [*signed, ["/api/tasks", ["items", "proof"], items]] if signs else signed)) - self.assertEqual((bulk["after"], bulk["reset"]), ([True, 0] if signs else [False, 2], True)) - self.assertEqual([args for script, args in self.scripts.calls if script == skill_scripts.ESTIMATE], [["request", "--session", "Operator"]] * (len(WIDTHS) if signs else 0)) - self.assertEqual(self.httpd.hub.settings.get()["estimation"], "none") - jobs = self.runner_jobs() - if not signs: - self.assertEqual(jobs, []) - register = json.loads((self.council / "rasci.json").read_text(encoding="utf-8")) - self.assertEqual([task for task, row in register.items() if "Operator" in row.get("estimates", {})], []) - return - self.assertEqual([job["argv"][-1] for job in jobs], [PLAN_VALUES[width] for width, _ in WIDTHS for _ in range(2)]) - self.run_runner() - register = json.loads((self.council / "rasci.json").read_text(encoding="utf-8")) - self.assertEqual({task: register[task]["estimates"]["Operator"] for task in ("work/next", "work/child")}, {"work/next": {"value": 34, "at": register["work/next"]["estimates"]["Operator"]["at"]}, "work/child": {"value": 34, "at": register["work/child"]["estimates"]["Operator"]["at"]}}) - rows = {row["task"]: row for row in self.snapshot()["tasks"]} - self.assertEqual((rows["work/next"]["wsjf"], rows["work/child"]["wsjf"], rows["work/child"]["value"]), ({"value": 34, "complexity": 3, "score": 11.33}, None, 34)) - - def test_chromium_draws_the_gantt_and_burn_switches_the_estimation_requests_estimates_and_signs_a_bulk_business_value_at_three_widths(self): - self.check_plan("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium"), signs=True) - - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_draws_the_gantt_and_burn_and_asks_the_passkey_for_a_bulk_business_value_storing_nothing_unsigned(self): - self.check_plan("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox"), signs=False) - - def trend_work(self, now: float) -> None: - day = 86400 - register = { - "work/t1": {"title": "First", "status": "done", "worker": "Stage", "start": iso(now - 10 * day), "end": iso(now - 8 * day), "roles": {"Stage": "RA"}, "estimates": {"Stage": {"value": 5, "complexity": 1}}}, - "work/t2": {"title": "Second", "status": "done", "worker": "Docs", "start": iso(now - 10 * day), "end": iso(now - 6 * day), "roles": {"Docs": "RA"}, "estimates": {"Docs": {"value": 3, "complexity": 2}}}, - "work/t3": {"title": "Third", "status": "done", "worker": "Docs", "branch": "feature/t3", "start": iso(now - 10 * day), "end": iso(now - 4 * day), "roles": {"Docs": "RA"}, "estimates": {"Docs": {"value": 3, "complexity": 3}}}, - "work/t4": {"title": "Fourth", "status": "running", "worker": "Stage", "start": iso(now - day), "roles": {"Stage": "RA"}, "estimates": {"Stage": {"value": 8, "complexity": 5}}}, - "work/t5": {"title": "Fifth", "status": "queued", "after": ["work/t4"], "roles": {"Skills": "R"}, "estimates": {"Skills": {"value": 8, "complexity": 3}}}, - "work/t6": {"title": "Sixth", "status": "queued", "base": "feature/t3", "roles": {"Docs": "RA"}}, - } - queue = {"seq": 2, "entries": [ - {"id": "deploy-1", "seq": 1, "kind": "deploy", "task": "work/t4", "workdir": "/repo", "session": "s2", "name": "Stage", "hotfix": None, "status": "active", "enqueued": now - 400, "granted": now - 300, "cmd": "make deploy"}, - {"id": "test-2", "seq": 2, "kind": "test", "task": "work/t5", "workdir": "/repo", "session": "s2", "name": "Docs", "hotfix": None, "status": "waiting", "enqueued": now - 60, "granted": None, "cmd": "make test"}, - ]} - self.write_council({"rasci.json": register, "queue.json": queue}) - - def trend_steps(self, browser: str) -> list[dict]: - local = f"http://localhost:{self.port}/" - steps = [] - for width, height in WIDTHS: - days = str(TREND_DAYS[width]) - steps += [ - {"width": width, "height": height, "url": f"{local}?{width}#tasks/list", "wait": 1200, "probe": ETA_LIST, "shot": str(OUT / f"{browser}-{width}-tasks-eta.png")}, - {"width": width, "height": height, "url": f"{local}?{width}#tasks/burn", "wait": 900, "probe": TREND_SET.replace("@MODE@", "regression").replace("@DAYS@", days), "shot": str(OUT / f"{browser}-{width}-tasks-burn-regression.png")}, - {"width": width, "height": height, "url": f"{local}?{width}-regression#tasks/burn", "wait": 1200, "probe": TREND_RELOADED, "shot": None}, - {"width": width, "height": height, "url": None, "wait": 0, "probe": TREND_SET.replace("@MODE@", "velocity").replace("@DAYS@", days), "shot": str(OUT / f"{browser}-{width}-tasks-burn-velocity.png")}, - {"width": width, "height": height, "url": f"{local}?{width}-velocity#tasks/burn", "wait": 1200, "probe": TREND_RELOADED, "shot": None}, - {"width": width, "height": height, "url": None, "wait": 0, "probe": STEP_TIPS, "shot": str(OUT / f"{browser}-{width}-tasks-burn-steps.png")}, - {"width": width, "height": height, "url": f"{local}?{width}-3d#tasks/3d", "wait": 1200, "probe": TASKS_3D, "shot": str(OUT / f"{browser}-{width}-tasks-3d.png")}, - {"width": width, "height": height, "url": f"{local}?{width}-camera#tasks/3d", "wait": 900, "probe": CAMERA, "shot": str(OUT / f"{browser}-{width}-tasks-3d-steady-camera.png")}, - ] - return steps - - def eta_checked(self, probe: dict, mode: str, rows: dict, edges: list[dict], window: tuple[float, float]) -> None: - """Args: - probe: task -> [start, eta, forecast, text, title] as the list shows it. - mode: the estimation mode the list was drawn in. - rows: the snapshot's task rows by task. - edges: the snapshot's task edges. - window: the earliest and latest time the page can have taken as now. - """ - day = 86400 - points = {"none": {}, "points": {"work/t4": 10 * day, "work/t5": 6 * day}}[mode] - self.assertEqual(sorted(probe), sorted(rows)) - for task, (start, eta, forecast, words, title) in probe.items(): - with self.subTest(mode=mode, task=task): - row = rows[task] - self.assertTrue(words.startswith("ETA ") and words != "ETA –", words) - if row["ended"]: - self.assertEqual((eta, forecast, title), (row["end"], False, "ETA: the end of the ended task")) - continue - self.assertTrue(forecast) - self.assertAlmostEqual(eta - start, points.get(task, 4 * day), delta=0.01) - ahead = [probe[edge["from"]][1] for edge in edges if edge["to"] == task and edge["from"] in probe and edge["from"] != task] - if row["start"] is not None: - self.assertEqual(start, row["start"]) - elif ahead and max(ahead) > window[1]: - self.assertAlmostEqual(start, max(ahead), delta=0.01) - else: - self.assertTrue(window[0] <= start <= window[1], (start, window)) - - def trend_forecast(self, points: list[list[float]], mode: str, days: int) -> tuple[float, float | None]: - """Args: - points: [t, remaining] of the drawn burndown points. - - Returns: - The trend's start and the time its remaining line reaches 0 - (None when it never falls), computed here independently of plan.js. - """ - last_t, last_y = points[-1] - if mode == "regression": - mean_t = sum(t for t, _ in points) / len(points) - mean_y = sum(y for _, y in points) / len(points) - slope = sum((t - mean_t) * (y - mean_y) for t, y in points) / sum((t - mean_t) ** 2 for t, _ in points) - return points[0][0], (mean_t - mean_y / slope if slope < 0 else None) - start = max(points[0][0], last_t - days * 86400) - before = [y for t, y in points if t <= start][-1] - slope = (last_y - before) / (last_t - start) - return start, (last_t - last_y / slope if slope < 0 else None) - - def trended(self, probe: dict, mode: str, days: int) -> None: - start, forecast = self.trend_forecast(probe["points"], mode, days) - self.assertEqual(probe["value"], mode) - self.assertEqual(probe["days"], [days, mode == "velocity"]) - self.assertEqual(sorted(series for series, *_ in probe["lines"]), ["done", "remaining", "scope"]) - for _, begin, end in probe["lines"]: - self.assertAlmostEqual(begin, start, delta=0.01) - self.assertAlmostEqual(end, forecast if forecast is not None else probe["points"][-1][0], delta=0.01) - if forecast is None: - self.assertEqual((probe["note"], probe["marker"]), ([None, "∞"], None)) - return - self.assertAlmostEqual(probe["note"][0], forecast, delta=0.01) - self.assertAlmostEqual(probe["marker"], forecast, delta=0.01) - self.assertNotEqual(probe["note"][1], "∞", probe["note"]) - - def check_trend_eta_3d(self, browser: str, driver: str, binary: str) -> None: - self.trend_work(time.time()) - begun = time.time() - data = self.drive(self.trend_steps(browser), None, driver, binary, init=GRAPH_HOOK) - ended = time.time() - (OUT / f"{browser}-trend-eta-3d.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], []) - snapshot = self.snapshot() - rows = {row["task"]: row for row in snapshot["tasks"]} - edges = snapshot["task_edges"] - self.assertEqual(sorted([edge["kind"], edge["from"], edge["to"]] for edge in edges), [["after", "work/t4", "work/t5"], ["base", "work/t3", "work/t6"], ["queue", "queue/deploy-1", "queue/test-2"]]) - trends = [["off", "off"], ["regression", "linear regression"], ["velocity", "velocity"]] - per = 8 - for index, (width, _) in enumerate(WIDTHS): - eta, regression, reloaded, velocity, again, tips, shown, camera = data["results"][per * index : per * (index + 1)] - days = TREND_DAYS[width] - kept = TREND_DAYS[WIDTHS[index - 1][0]] if index else 7 - with self.subTest(browser=browser, width=width): - for probe in (eta, regression, reloaded, velocity, again, tips, shown): - self.assertNotIn("error", probe) - self.assertEqual((probe["tall"], probe["wide"], probe["layout"]), (False, False, ["toolbar", "chips", "body"]), probe) - self.assertEqual(probe["rows"] == 1, width != 390, probe["rows"]) - for mode in ("none", "points", "back"): - self.eta_checked(eta[mode], "points" if mode == "points" else "none", rows, edges, (begun - 1, ended + 1)) - self.assertEqual(eta["modes"], [["none", "true"], ["points", "false"]]) - self.assertEqual((regression["before"]["value"], regression["before"]["options"], regression["before"]["note"], regression["before"]["lines"]), ("off", trends, None, [])) - self.assertEqual(regression["before"]["days"], [kept, False]) - self.assertEqual(regression["toasts"], ["Trend: linear regression"]) - self.trended(regression["after"], "regression", kept) - self.trended(reloaded, "regression", kept) - self.assertEqual(velocity["toasts"], [f"Trend: velocity over {kept} days", f"Trend: velocity over {days} days"]) - self.trended(velocity["after"], "velocity", days) - self.trended(again, "velocity", days) - self.assertEqual([step["t"] for step in tips["steps"]], [t for t, _ in again["points"]]) - listed = [[sorted(filter(None, step[key].split(" "))) for key in ("started", "ended", "joined")] for step in tips["steps"]] - self.assertEqual(listed, [[["work/t1", "work/t2", "work/t3"], [], ["work/t5", "work/t6"]], [[], ["work/t1"], []], [[], ["work/t2"], []], [[], ["work/t3"], []], [["work/t4"], [], []], [[], [], []]]) - self.assertEqual([step["series"] for step in tips["steps"]], [["scope", "done", "remaining"]] * len(tips["steps"])) - self.assertIn("Ended: work/t1", tips["steps"][1]["tip"]) - self.assertIn("No work package started, ended or joined the scope here", tips["steps"][-1]["tip"]) - self.assertEqual((tips["reset"], tips["note"], tips["lines"]), ("Trend: off", False, 0)) - self.tasks_3d(shown, snapshot) - self.assertTrue(camera["hooked"], camera) - self.assertGreater(math.dist(camera["built"], camera["moved"]), 1, camera) - for refresh in camera["refreshes"]: - self.assertEqual((refresh["rebuilt"], refresh["settled"]), (True, True), camera) - self.assertLess(math.dist(refresh["camera"], camera["moved"]), 0.01, camera) - self.assertEqual(self.httpd.hub.settings.get()["trend"], {"mode": "off", "days": TREND_DAYS[WIDTHS[-1][0]]}) - - def tasks_3d(self, shown: dict, snapshot: dict) -> None: - tasks = sorted(row["task"] for row in snapshot["tasks"]) - colors = {"after": shown["palette"]["violet"], "base": shown["palette"]["info"], "queue": shown["palette"]["warn"]} - edges = sorted([edge["from"], edge["to"], edge["kind"], colors[edge["kind"]]] for edge in snapshot["task_edges"]) - self.assertEqual(len(set(colors.values())), 3, colors) - for layout, word in (("force", "Force"), ("time", "Time")): - drawn = shown[layout] - with self.subTest(layout=layout): - self.assertEqual(drawn["note"], f"{len(tasks)} nodes · {len(edges)} edges · {word}") - self.assertEqual(drawn["layouts"], [["none", str(layout == "force").lower()], ["time", str(layout == "time").lower()]]) - self.assertEqual(sorted(node for node, *_ in drawn["nodes"]), tasks) - self.assertEqual(sorted(drawn["links"]), edges) - self.assertEqual(drawn["label"], "work/t5 · Fifth") - self.assertEqual([fz for _, fz, _ in shown["force"]["nodes"]], [None] * len(tasks)) - timed = sorted(shown["time"]["nodes"], key=lambda node: node[2]) - self.assertTrue(all(fz is not None for _, fz, _ in timed), timed) - self.assertEqual([fz for _, fz, _ in timed], sorted(fz for _, fz, _ in timed)) - self.assertLess(timed[0][1], timed[-1][1]) - popup = shown["popup"] - self.assertEqual((popup["open"], popup["title"], popup["id"], popup["picked"], popup["open_button"], popup["line"]), (True, "Fifth", "work/t5", "work/t5", "Open task", True), popup) - self.assertTrue(popup["eta"], popup) - self.assertEqual((popup["closed"], shown["back"]), ([False, None], f"{len(tasks)} nodes · {len(edges)} edges · Force")) - - def test_chromium_draws_the_trend_forecast_point_tips_eta_and_tasks_3d_at_three_widths(self): - self.check_trend_eta_3d("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium")) - - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_draws_the_trend_forecast_point_tips_eta_and_tasks_3d_at_three_widths(self): - self.check_trend_eta_3d("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox")) - def check_presence(self, browser: str, driver: str, binary: str) -> None: """Args: browser: the file name prefix of the screenshots and the result. @@ -2984,25 +272,6 @@ class TestOrchestratorE2E(HubCase): def test_firefox_shows_agent_states_and_3d_faces_switchable_through_a_reload_at_three_widths(self): self.check_presence("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox")) - def test_chromium_pins_a_task_priority_after_signature_and_the_runner_applies_it(self): - signer = self.pin() - private = "".join(line for line in signer.pem.read_text(encoding="utf-8").splitlines() if not line.startswith("-----")) - authenticator = {"credentialId": base64.b64encode(signer.raw_id).decode(), "privateKey": private, "rpId": "localhost"} - local = f"http://localhost:{self.port}/" - data = self.drive([{"width": 1366, "height": 768, "url": f"{local}#tasks/list", "wait": 1200, "probe": PIN, "shot": self.shot("1366-tasks-priority-signed")}], authenticator) - (OUT / "chromium-task-priority.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - self.assertEqual(data["errors"], []) - pinned = data["results"][0] - self.assertNotIn("error", pinned) - self.assertEqual((pinned["title"], pinned["preview"][0]), ("work/docs", "rasci.py set work/docs --prio 2")) - self.assertEqual(pinned["toasts"], ["Priority work/docs: handed to the runnerrasci.py set work/docs --prio 2"]) - jobs = self.runner_jobs() - self.assertEqual([(job["id"], job["kind"], job["argv"]) for job in jobs], [(pinned["jobs"], "task", ["set", "work/docs", "--prio", "2"])]) - self.run_runner() - register = json.loads((self.council / "rasci.json").read_text(encoding="utf-8")) - self.assertEqual((register["work/docs"]["prio"], register["work/feature"]["prio"]), (2, 1)) - self.assertEqual([(row["task"], row["prio"]) for row in self.snapshot()["tasks"][:2]], [("work/feature", 1), ("work/docs", 2)]) - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") def test_firefox_walks_every_screen_at_three_widths(self): shots = [(width, height, screen, OUT / f"firefox-{width}-{screen.replace('/', '-')}.png") for width, height in WIDTHS for screen in SCREENS] diff --git a/tests/e2e/test_queue_overlay_e2e.py b/tests/e2e/test_queue_overlay_e2e.py index c6afa63..728e7f1 100644 --- a/tests/e2e/test_queue_overlay_e2e.py +++ b/tests/e2e/test_queue_overlay_e2e.py @@ -11,7 +11,7 @@ from pathlib import Path HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase from test_hub_queue_overlay import ( HUB_ORDER, @@ -143,7 +143,7 @@ def jobs_shown() -> dict: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestQueueOverlay(HubCase): - drive = base.TestOrchestratorE2E.drive + drive = base.OrchestratorE2ECase.drive def setUp(self): super().setUp() diff --git a/tests/e2e/test_radio_focus_e2e.py b/tests/e2e/test_radio_focus_e2e.py new file mode 100644 index 0000000..1fb73d1 --- /dev/null +++ b/tests/e2e/test_radio_focus_e2e.py @@ -0,0 +1,213 @@ +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 radio_layout_kit as kit +from kvb_orchestrator import skill_scripts +from radio_layout_focus_probes import ( + BANNER, + COMPOSE_HOME, + FOCUS, + KEYS, + POP, + REPLY_HOME, + ROWS, +) +from radio_layout_kit import ( + ALARMS, + DUPS, + FOCUS_SIZES, + HOME_RADIO, + NEW_ALARM, + OUT, + POPOVER_SIZES, + probe, +) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestRadioFocus(kit.RadioLayoutCase): + def popover_steps(self, browser: str) -> list[dict]: + self.stations() + tiles = json.dumps([f'#main .home-tile[data-pin="panel:{part}"]' for part in ("radio-device", "radio")]) + places = (("spot", "#stream", "[]", '["#radio-spot"]', "true"), ("home", "#home", json.dumps(HOME_RADIO), tiles, "false"), ("home-spot", "#home", json.dumps(HOME_RADIO), tiles, "true")) + return [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}-pop#stream" if name == "spot" else None, "wait": 1500 if name == "spot" else 0, + "probe": probe(POP.replace("@VIEW@", view).replace("@PINS@", pins).replace("@ROOTS@", roots).replace("@SPOT@", spot)), "shot": str(OUT / f"{browser}-{width}-pop-{name}.png")} + for width, height in POPOVER_SIZES for name, view, pins, roots, spot in places] + + def check_popover(self, data: dict, browser: str) -> None: + results = iter(data["results"]) + for width, _ in POPOVER_SIZES: + for place in ("spot", "home", "home-spot"): + found = next(results) + self.assertEqual(len(found), 1 if place == "spot" else 2, found) + for fold in found: + with self.subTest(browser=browser, width=width, place=place, root=fold["selector"]): + self.assertNotIn("error", fold, fold) + self.assertEqual((fold["opened"]["open"], fold["opened"]["outside"]), (True, []), fold) + self.assertGreaterEqual(fold["opened"]["whole"], 1, fold) + self.assertEqual(fold["escape"], [False, True], fold) + self.assertEqual(fold["again"], {"open": True, "outside": []}, fold) + self.assertEqual(fold["click"], [False, False, True], fold) + + def focus_steps(self, browser: str) -> list[dict]: + self.stations() + return [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}-focus#stream", "wait": 1500, "probe": probe(FOCUS), "shot": str(OUT / f"{browser}-{width}-focus.png")} + for width, height in FOCUS_SIZES] + + def check_focus(self, data: dict, browser: str) -> None: + for (width, _), cases in zip(FOCUS_SIZES, data["results"], strict=True): + for key, found in cases.items(): + with self.subTest(browser=browser, width=width, case=key): + if key == "escape": + self.assertEqual(found, {"closed": True, "toggle": True}, found) + continue + self.assertEqual((found["opened"], found["closed"], found["summary"]), (True, True, False), found) + self.assertTrue(found["history"] if key.endswith("tab") else found["body"], found) + + def watch(self, browser: str, kind: str, template: str) -> dict: + width, height = FOCUS_SIZES[0] + step = {"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}-{kind}#stream", "wait": 1500, "probe": probe(template), "shot": str(OUT / f"{browser}-{width}-{kind}.png")} + driver = ("bidi.mjs", os.environ.get("FIREFOX", "firefox")) if browser == "firefox" else () + data = self.drive([step], None, *driver) + (OUT / f"{browser}-radio-{kind}.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], []) + return data["results"][0] + + def check_rows(self, found: dict, browser: str) -> None: + want = {"same": True, "key": found["start"].pop("want"), "pick": True, "body": False} + for moment, done in (("start", None), ("fresh", "delivered"), ("tick", "ticked")): + with self.subTest(browser=browser, moment=moment): + if done: + self.assertTrue(found[moment].pop(done), found) + self.assertEqual(found[moment], want, found) + with self.subTest(browser=browser, moment="tabs"): + self.assertIsNotNone(found["tabs"].pop("tab"), found) + self.assertEqual(found["tabs"], {"delivered": [True, True, True], "focusins": 0, "same": True}, found) + + def twins(self) -> None: + now = time.time() + with (self.council / "news.jsonl").open("a", encoding="utf-8") as handle: + handle.write(self.jsonl([{"ts": now - 50, "from": "Docs", "to": [], "text": words, "class": "broadcast", "v": 2} for words in DUPS])) + + def check_keys(self, found: dict, browser: str) -> None: + with self.subTest(browser=browser, case="keys"): + self.assertEqual(len(set(found["keys"])), len(DUPS), found) + for words in DUPS: + with self.subTest(browser=browser, case=words): + self.assertEqual(found[words], {"delivered": True, "same": True, "line": words, "popup": words}, found) + with self.subTest(browser=browser, case="filtered"): + self.assertEqual(found["filtered"], {"gone": True, "pick": True, "class": "call"}, found) + with self.subTest(browser=browser, case="emptied"): + self.assertEqual(found["emptied"], {"gone": True, "list": True}, found) + + def check_banner(self, found: dict, browser: str) -> None: + with self.subTest(browser=browser, moment="steady"): + self.assertEqual(found["steady"], {"polled": True, "mutations": 0, "focus": True, "body": False}, found) + with self.subTest(browser=browser, moment="changed"): + self.assertTrue(found["changed"].pop("text").endswith(NEW_ALARM), found) + self.assertEqual(found["changed"], {"polled": True, "added": 1, "shown": True, "cancel": True}, found) + + def test_chromium_leaves_the_focus_where_a_click_lands_and_returns_it_to_the_toggle_only_on_escape(self): + data = self.drive(self.focus_steps("chromium"), None) + (OUT / "chromium-radio-focus.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + self.check_focus(data, "chromium") + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_leaves_the_focus_where_a_click_lands_and_returns_it_to_the_toggle_only_on_escape(self): + data = self.drive(self.focus_steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox")) + (OUT / "firefox-radio-focus.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + self.check_focus(data, "firefox") + + def test_chromium_holds_the_focus_on_a_history_row_and_its_tab_across_new_rows_and_the_minute_tick(self): + self.check_rows(self.watch("chromium", "rows", ROWS), "chromium") + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_holds_the_focus_on_a_history_row_and_its_tab_across_new_rows_and_the_minute_tick(self): + self.check_rows(self.watch("firefox", "rows", ROWS), "firefox") + + def test_chromium_keys_twin_rows_apart_and_moves_the_focus_of_a_filtered_out_row_to_the_nearest_row_or_the_list(self): + self.twins() + self.check_keys(self.watch("chromium", "keys", KEYS), "chromium") + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_keys_twin_rows_apart_and_moves_the_focus_of_a_filtered_out_row_to_the_nearest_row_or_the_list(self): + self.twins() + self.check_keys(self.watch("firefox", "keys", KEYS), "firefox") + + def test_chromium_redraws_the_mayday_banner_only_when_the_silence_changes(self): + self.silence(ALARMS["mayday"]) + self.check_banner(self.watch("chromium", "banner", BANNER), "chromium") + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_redraws_the_mayday_banner_only_when_the_silence_changes(self): + self.silence(ALARMS["mayday"]) + self.check_banner(self.watch("firefox", "banner", BANNER), "firefox") + + def test_chromium_places_the_station_popover_inside_every_clip_and_closes_it_on_escape_and_outside_clicks_in_the_spot_and_on_home(self): + data = self.drive(self.popover_steps("chromium"), None) + (OUT / "chromium-radio-popover.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + self.check_popover(data, "chromium") + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_places_the_station_popover_inside_every_clip_and_closes_it_on_escape_and_outside_clicks_in_the_spot_and_on_home(self): + data = self.drive(self.popover_steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox")) + (OUT / "firefox-radio-popover.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + self.check_popover(data, "firefox") + + def test_chromium_home_copies_keep_their_own_composer_record_reply_and_cancel_the_mayday(self): + now = time.time() + self.write_council({"radio-silence.json": {"since": now - 60, "until": now + 3600, "by": "Docs", "text": "disk full"}}) + steps = [] + for width, height in ((1366, 768), (390, 844)): + shot = str(OUT / f"chromium-{width}") + steps += [ + {"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}-copies#stream", "wait": 1500, "probe": probe(COMPOSE_HOME), "shot": f"{shot}-home-composers.png", "gesture": True}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(REPLY_HOME), "shot": f"{shot}-home-reply.png"}, + ] + data = self.drive(steps, self.authenticator()) + (OUT / "chromium-radio-home-copies.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + results = iter(data["results"]) + question = "Lift the radio silence of the active mayday?" + for width in (1366, 390): + composed, replied = next(results), next(results) + with self.subTest(width=width, part="own composer state"): + self.assertEqual(composed["drafts"], ["draft kept in the spot", "", ""], composed) + self.assertEqual((composed["first"], composed["handed"]), ("true", ["false", "true"]), composed) + self.assertIn("hello from the mic", composed["spotHeard"] or "", composed) + self.assertNotIn("hello from the mic", composed["homeBefore"], composed) + self.assertIn("hello from the mic", composed["homeHeard"] or "", composed) + self.assertTrue(all(composed["notes"]) and composed["notes"][0] != composed["notes"][1], composed) + self.assertTrue((composed["spotSent"] or "").startswith("Post to Stage: sent"), composed) + self.assertTrue(composed["homeAttach"], composed) + self.assertTrue((composed["homeSent"] or "").startswith("Post to Docs: sent"), composed) + self.assertEqual(composed["bodies"], [["Stage", "plain text from the spot", ""], ["Docs", "voice from the Home tile", composed["notes"][1]]], composed) + with self.subTest(width=width, part="reply and mayday from Home"): + self.assertEqual(replied["fromLog"], {"spot": "false", "popup": False, "speak": {"channel": "post", "recipient": "Stage", "toShown": True, "focused": True}, + "whole": {"channel": "post", "recipient": replied["fromLog"]["whole"]["recipient"], "toShown": True, "focused": False}}, replied) + self.assertEqual(replied["fromWhole"], {"spot": "false", "whole": {"channel": "post", "recipient": "Stage", "toShown": True, "focused": True}}, replied) + self.assertTrue((replied["sent"] or "").startswith("Post to Stage: sent"), replied) + self.assertEqual((replied["enabled"], replied["questions"]), (True, [question]), replied) + self.assertTrue((replied["lifted"] or "").startswith("Cancel mayday: done"), replied) + self.assertEqual(replied["spot"], "false", replied) + radio = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO] + self.assertEqual([args[:3] for args in radio if args[0] == "post"], [["post", "--to", "Stage"], ["post", "--to", "Docs"], ["post", "--to", "Stage"]] * 2, radio) + self.assertEqual([args for args in radio if args[0] == "clear"], [["clear", "--force", "--session", "Operator"]] * 2, radio) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_radio_layout_e2e.py b/tests/e2e/test_radio_layout_e2e.py index a4a0771..c5508ed 100644 --- a/tests/e2e/test_radio_layout_e2e.py +++ b/tests/e2e/test_radio_layout_e2e.py @@ -4,854 +4,38 @@ 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 test_orchestrator_e2e as base -from hub_case import HubCase -from kvb_orchestrator import receipts, skill_scripts -from kvb_orchestrator.presence import SNAPSHOT -from kvb_orchestrator.view import RADIO_WINDOW - -OUT = Path(os.environ.get("E2E_OUT", "/tmp/radio-layout-shots")) -LIVE = "f000000000000001" -SILENCE = "f000000000000002" -NEW_ALARM = "disk full again: the cleanup freed too little" -NAMES = ["Skills", "Stage", "Docs", "Atlas", "Beacon", "Comet", "Delta", "Echo", "Falcon", "Harbor"] -SESSIONS = {f"s{index}": name for index, name in enumerate(NAMES, start=1)} -LONG = "Disk at ninety percent on the build host: " + "the gate keeps the swarm waiting while the cache, the images and the logs keep growing; " * 4 -FILLERS = 24 -WIDTHS = (*base.WIDTHS, (960, 800)) -NARROW = (390, 960) -STAGE_SHARE = 0.12 -BANDS = ((1280, 720), (976, 744), (768, 976)) -SHORT = ((800, 600), (1024, 600), (1280, 600), (1366, 657)) -ABOVE = ((800, 976), (960, 976), (976, 744), (1024, 744), (1366, 720)) -LAPTOPS = ((1280, 720), (1366, 768), (1440, 900), (1536, 864), (1920, 1080), (1024, 768), (1680, 1050), (820, 1180), (768, 1024), *ABOVE, *SHORT) -DUPS = ("dup first", "dup second") -VIEWS = ("#stream", "#agents/orbit") -STATES = ("idle", "stations", "voice", "speech", "mayday", "mayday-long") -ALARMS = { - "mayday": "disk full", - "mayday-long": "disk full on the build host: every agent pauses its writing steps until the operator frees space under /var/lib/docker and confirms the cleanup " - "on the radio; the gate queue stays frozen, the deploy of the production worktree waits, and every held test run restarts after the clear of this mayday", -} -BANNER_MAX = 48 -FOCUS_SIZES = ((1366, 768), (390, 844)) -MAIN_SHARE = 0.54 -PLAY_MIN = {"BUTTON": (24, 24), "AUDIO": (200, 30)} -POPOVER_SIZES = ((1366, 768), (1280, 720), (390, 844)) -HOME_RADIO = [{"kind": "panel", "id": "radio-device", "w": 6, "h": 6}, {"kind": "panel", "id": "radio", "w": 12, "h": 7}] -STREAMS = [{"name": f"Station {index}", "url": f"https://radio.example/{index}.mp3", "from": "00:00", "to": "24:00", "days": list(range(7)), "on": False, "via": []} for index in (1, 2, 3)] -PARTS = ["radio", "radio-device", "radio-speak", "radio-log"] -DEFAULTS = {"radio": [12, 7], "radio-device": [6, 6], "radio-speak": [6, 5], "radio-log": [6, 5]} -SIZES = {"radio": [12, 9], "radio-device": [5, 7], "radio-speak": [7, 6], "radio-log": [8, 6]} -LISTED = {"radio-log"} -SCROLLER = {"radio": "radio-log", "radio-device": None, "radio-speak": None, "radio-log": "radio-log"} -PROBES = """ - const transitions = window.e2eTransitions || (window.e2eTransitions = []); - if (document.startViewTransition && !transitions.wrapped) { - const start = document.startViewTransition.bind(document); - document.startViewTransition = (update) => { - const run = start(update); - transitions.push(run); - return run; - }; - transitions.wrapped = true; - } - const settle = () => Promise.all(transitions.map((run) => run.finished.catch(() => null))); - const press = (node) => { - node.dispatchEvent(new MouseEvent("mousedown", {bubbles: true, cancelable: true, view: window})); - if (node.matches('button, input, select, textarea, summary, a[href], [tabindex]')) { - node.focus(); - } else if (document.activeElement) { - document.activeElement.blur(); - } - node.dispatchEvent(new MouseEvent("mouseup", {bubbles: true, cancelable: true, view: window})); - node.click(); - }; - const box = (node) => node.getBoundingClientRect(); - const ownStar = (owner) => all(".star", owner).find((node) => node.closest("[data-panel], [data-item]") === owner) || null; - const openSpot = async () => { - await until(() => typeof Nav === "object" && document.getElementById("radio-spot"), 8000); - const toggle = document.getElementById("radio-open"); - if (toggle.getAttribute("aria-expanded") !== "true") { - toggle.click(); - await sleep(300); - } - return document.getElementById("radio-spot"); - }; - const closeSpot = async () => { - const toggle = document.getElementById("radio-open"); - if (toggle.getAttribute("aria-expanded") === "true") { - toggle.click(); - await sleep(200); - } - }; - const longRow = (root) => all(".radio-row", root).find((item) => text(item.querySelector(".radio-line")).startsWith("Disk at ninety")); - const popup = () => document.getElementById("popup"); - const openRow = async (row) => { - row.querySelector(".radio-pick").click(); - return until(() => popup().open && popup().querySelector(".radio-full") ? popup() : null, 4000); - }; - const shown = (node) => node.getClientRects().length > 0; - const scrolls = (node) => { - const look = getComputedStyle(node); - return (node.scrollHeight > node.clientHeight + 1 && ["auto", "scroll"].includes(look.overflowY)) || (node.scrollWidth > node.clientWidth + 1 && ["auto", "scroll"].includes(look.overflowX)); - }; - const scrollersIn = (root) => [root, ...all("*", root)].filter((node) => node instanceof HTMLElement && node.tagName !== "SELECT" && node.tagName !== "TEXTAREA" && shown(node) && scrolls(node)).map((node) => [...node.classList].at(-1) || node.tagName); - const tile = (id) => document.querySelector(`#main .home-tile[data-pin="panel:${id}"]`); - const pick = (root) => { - const [channel, recipient] = all("select", root.querySelector("form.composer")); - return {channel: channel.value, recipient: recipient.value, toShown: !recipient.closest("label").hidden, focused: document.activeElement === root.querySelector("form.composer textarea")}; - }; -""" -LAYOUT = """(async () => {@HELPERS@@PROBES@ - await ViewStore.update("home.pins", () => []); - const spot = await openSpot(); - spot.querySelector('.radio-tabs [data-tab="all"]').click(); - await until(() => all(".radio-row .reader", spot).length > 20 && longRow(spot), 20000); - await sleep(300); - window.scrollTo(0, 0); - const cardOf = (node) => (node.parentElement && node.parentElement.closest(".radio-card")) || spot; - const wider = all("*", spot).filter((node) => node.tagName !== "OPTION" && shown(node) && box(node).width > 0).filter((node) => { - const own = box(node); - const card = box(cardOf(node)); - return own.left < card.left - 1 || own.right > card.right + 1; - }).map((node) => `${node.tagName}.${node.getAttribute("class")}`); - const list = spot.querySelector(".radio-log"); - const listLook = getComputedStyle(list); - const rows = all(".radio-row", spot); - const lineHeight = parseFloat(getComputedStyle(rows[0].querySelector(".radio-line")).lineHeight); - const lines = rows.map((row) => { - const line = row.querySelector(".radio-line"); - const look = getComputedStyle(line); - return {height: Math.round(box(row).height), nowrap: look.whiteSpace === "nowrap", ellipsis: look.textOverflow === "ellipsis", flat: line.scrollHeight <= line.clientHeight + 1 && row.scrollHeight <= row.clientHeight + 1, fits: row.scrollWidth <= row.clientWidth + 1 && box(row).right <= box(list).right + 1, width: line.clientWidth}; - }); - const long = longRow(spot).querySelector(".radio-line"); - const avatars = rows.filter((row) => row.querySelector(".reader")).map((row) => { - const edge = box(row); - const line = box(row.querySelector(".radio-line")); - const faces = all(".reader .avatar", row).filter(shown).map(box); - return { - total: Number((row.querySelector(".readers").getAttribute("aria-label").match(/\\d+/) || ["0"])[0]), - count: faces.length, - more: all(".readers-more", row).filter(shown).map(text), - inside: faces.every((face) => face.left >= edge.left - 1 && face.right <= edge.right + 1 && face.top >= edge.top - 1 && face.bottom <= edge.bottom + 1), - after: faces.every((face) => face.left >= line.right - 1), - stacked: faces.slice(1).every((face, index) => face.left < faces[index].right), - sliver: faces.length ? Math.min(...faces.map((face, index) => (index + 1 < faces.length ? faces[index + 1].left : face.right) - face.left)) : null, - }; - }); - 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)], - wider, scrollers: scrollersIn(spot), - list: {overflowY: listLook.overflowY, scrollbar: [listLook.scrollbarWidth, listLook.scrollbarColor], scrolls: list.scrollHeight > list.clientHeight + 1}, - main: getComputedStyle(document.getElementById("main")).scrollbarColor, - heights: [...new Set(lines.map((line) => line.height))], lineHeight, rows: rows.length, - single: lines.every((line) => line.nowrap && line.ellipsis && line.flat && line.fits), - narrowest: Math.min(...lines.map((line) => line.width)), - long: [long.scrollWidth > long.clientWidth, getComputedStyle(long).textOverflow], - avatars: {rows: avatars.length, most: Math.max(...avatars.map((row) => row.count)), inside: avatars.every((row) => row.inside), after: avatars.every((row) => row.after), stacked: avatars.filter((row) => row.count > 1).every((row) => row.stacked)}, - folds: avatars.map((row) => [row.total, row.count, row.more]), - 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, - stations: [Boolean(spot.querySelector("details.radio-station")), spot.querySelector("details.radio-station").open], - }; -})()""" -POPUP = """(async () => {@HELPERS@@PROBES@ - const spot = document.getElementById("radio-spot"); - const copied = []; - navigator.clipboard.writeText = (value) => { - copied.push(value); - return Promise.resolve(); - }; - const row = longRow(spot); - row.scrollIntoView({block: "center"}); - await sleep(200); - const dialog = await openRow(row); - if (!dialog) { - return {error: "no popup"}; - } - const card = dialog.querySelector(".popup-box"); - const fields = Object.fromEntries(all("dl.meta > div", card).map((pair) => [text(pair.querySelector("dt")), text(pair.querySelector("dd"))])); - const readers = all(".popup-reader", card).map((item) => ({session: item.dataset.session, name: text(item.querySelector("strong")), time: text(item.querySelector(".muted")), acked: item.dataset.acked})); - const copy = card.querySelector(".radio-copy"); - const said = card.querySelector(".radio-said"); - const heard = () => [copy.getAttribute("aria-label"), said ? text(said) : null]; - const region = said ? [said.getAttribute("role"), said.getAttribute("aria-live"), card.contains(said), shown(said) && box(said).width <= 1] : null; - copy.click(); - const done = await until(() => (copy.dataset.copied === "true" ? text(copy) : null), 3000); - const success = heard(); - const buttons = all(".radio-actions button", card).map(text); - await until(() => copy.getAttribute("aria-label") === "Copy" && copy.dataset.copied === "", 4000); - const reset = heard(); - navigator.clipboard.writeText = () => Promise.reject(new DOMException("Denied", "NotAllowedError")); - copy.click(); - await until(() => copy.dataset.copied === "false", 3000); - const failure = heard(); - return { - open: dialog.open, title: text(card.querySelector(".popup-head h2")), fields, full: dialog.querySelector(".radio-full").textContent, readers, - heading: text(card.querySelector("h3")), buttons, copied, shown: done, region, success, reset, failure, - stray: [...card.childNodes].filter((node) => node.nodeType === 3).map((node) => node.textContent), - inView: (() => { - const edge = box(card); - return edge.left >= 0 && edge.top >= 0 && edge.right <= innerWidth + 1 && edge.bottom <= innerHeight + 1; - })(), - }; -})()""" -CLOSE_REPLY = """(async () => {@HELPERS@@PROBES@ - const spot = document.getElementById("radio-spot"); - (document.activeElement || document.body).dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); - await sleep(200); - const escaped = !popup().open; - const dialog = await openRow(longRow(spot)); - const card = box(dialog.querySelector(".popup-box")); - const x = card.left > 8 ? Math.floor(card.left / 2) : Math.ceil((card.right + document.documentElement.clientWidth) / 2); - const hit = document.elementFromPoint(x, Math.round(innerHeight / 2)); - hit.click(); - await sleep(200); - const outside = [hit === popup(), !popup().open]; - await openRow(longRow(spot)); - all(".radio-actions button", popup()).find((button) => text(button) === "Reply").click(); - await sleep(300); - return {escaped, outside, reply: {open: popup().open, ...pick(spot)}}; -})()""" -HOME = """(async () => {@HELPERS@@PROBES@ - const spot = await openSpot(); - 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"); - } - 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]); - await closeSpot(); - location.hash = "#home"; - await screenShown(8000); - await until(() => @PARTS@.every((id) => tile(id)) && tile("radio-log").querySelector(".radio-row") && tile("radio").querySelector(".radio-row"), 10000); - await sleep(400); - const measure = () => Object.fromEntries(@PARTS@.map((id) => { - const body = tile(id).querySelector(".home-body"); - const list = tile(id).querySelector(".radio-log"); - const edge = box(body); - const rows = list ? all(".radio-row", list).filter((row) => box(row).top >= box(list).top - 1 && box(row).bottom <= box(list).bottom + 1).length : null; - return [id, {scrollers: scrollersIn(tile(id)), rows, inside: list ? box(list).bottom <= edge.bottom + 1 && box(list).top >= edge.top - 1 : null, filled: Math.abs(box(tile(id).querySelector(".radio-home")).height - body.clientHeight + parseFloat(getComputedStyle(body).paddingTop) + parseFloat(getComputedStyle(body).paddingBottom)) <= 2}]; - })); - const fresh = measure(); - const whole = tile("radio"); - const bar = whole.querySelector(".spot-head"); - const gear = bar ? all("button", bar).find((button) => button.getAttribute("aria-label") === "Read aloud") : null; - const clear = bar ? all("button", bar).find((button) => button.getAttribute("aria-label") === "Cancel mayday") : null; - if (gear) { - gear.click(); - await sleep(200); - } - const filters = whole.querySelector(".radio-gear .radio-read"); - const tools = { - gear: gear ? [gear.getAttribute("aria-expanded"), Boolean(filters), filters ? box(filters).bottom <= box(whole).bottom + 1 : null] : null, - clear: clear ? [clear.disabled, clear.title] : null, - }; - if (gear) { - gear.click(); - } - const content = { - tiles: all("#main .home-tile").map((node) => node.dataset.pin), - radio: [".radio-device", ".radio-speak", ".radio-logbox"].map((selector) => Boolean(tile("radio").querySelector(selector))), - device: [text(tile("radio-device").querySelector('[data-field="mode"]')), all(".radio-knobs input[type=range]", tile("radio-device")).length], - 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, - ids: all("#main .home-tile .home-body [id]").map((node) => node.id), - }; - const count = (id) => tile(id).querySelectorAll(".radio-row").length; - const before = [count("radio-log"), count("radio")]; - await fetch("/api/voice/@LIVE@", {cache: "no-store"}); - window.dispatchEvent(new Event("focus")); - const first = (id) => text(tile(id).querySelector(".radio-row .radio-line")); - const live = await until(() => (count("radio-log") > before[0] && count("radio") > before[1] && first("radio-log").startsWith("live row") ? [first("radio-log"), first("radio")] : null), 20000); - tile("radio-device").querySelector('.radio-modes button[data-mode="quiet"]').click(); - await sleep(200); - const mode = [text(tile("radio").querySelector('[data-field="mode"]')), text(document.querySelector('#radio-spot [data-field="mode"]'))]; - tile("radio-device").querySelector('.radio-modes button[data-mode="auto"]').click(); - await sleep(200); - const sizes = @SIZES@; - await ViewStore.update("home.pins", (pins) => (pins || []).map((pin) => ({...pin, w: sizes[pin.id][0], h: sizes[pin.id][1]}))); - await until(() => @PARTS@.every((id) => tile(id).dataset.w === String(sizes[id][0]) && tile(id).dataset.h === String(sizes[id][1])), 5000); - await sleep(400); - const resized = measure(); - window.scrollTo(0, 0); - return {pressed, stored, fresh, resized, tools, content, live, mode, wide: document.documentElement.scrollWidth > innerWidth + 1}; -})()""" -FIT = """(async () => {@HELPERS@@PROBES@ - await ViewStore.update("home.pins", () => []); - location.hash = "#agents/orbit"; - await screenShown(8000); - const spot = await openSpot(); - await until(() => spot.querySelector(".radio-row"), 8000); - await sleep(500); - const stage = document.querySelector("#main .stage svg"); - const list = spot.querySelector(".radio-log"); - const result = { - fit: document.body.classList.contains("fit"), tall: document.documentElement.scrollHeight > innerHeight, wide: document.documentElement.scrollWidth > innerWidth + 1, - stage: stage ? Math.round(box(stage).height) : 0, height: innerHeight, scrollers: scrollersIn(spot), - list: list.clientHeight, speak: (() => { - const card = spot.querySelector(".radio-speak"); - return card.scrollHeight <= card.clientHeight + 1; - })(), - }; - await closeSpot(); - await sleep(300); - const after = document.querySelector("#main .stage svg"); - result.closed = {boxes: spot.getClientRects().length, tall: document.documentElement.scrollHeight > innerHeight, stage: after ? Math.round(box(after).height) : 0}; - return result; -})()""" -SPOT = """(async () => {@HELPERS@@PROBES@@SPEAKING@ - await ViewStore.update("home.pins", () => []); - location.hash = "@VIEW@"; - await screenShown(8000); - const spot = await openSpot(); - await until(() => spot.querySelector(".radio-row") && spot.querySelectorAll(".radio-device .station").length === 3, 8000); - await settle(); - await sleep(500); - window.scrollTo(0, 0); - const fits = (node) => node.scrollHeight <= node.clientHeight + 1; - const list = spot.querySelector(".radio-log"); - const fold = spot.querySelector("details.radio-station"); - const form = spot.querySelector(".radio-speak form.composer"); - const note = form.querySelector(".voice-note"); - const display = spot.querySelector(".radio-caption"); - const named = (node) => node.getAttribute("aria-label") || text(node) || node.getAttribute("title") || `${node.tagName}.${node.getAttribute("class")}`; - const blocked = () => { - const layer = spot.querySelector(".radio-station[open] > .station-body"); - const marks = [spot.querySelector(".radio-lamp"), spot.querySelector('[data-field="cpu"]'), spot.querySelector(".radio-device .group-title")]; - const folded = (node) => Boolean(node.closest("details:not([open])")) && !node.closest("summary"); - const found = []; - for (const node of [...all('button, input, select, textarea, summary, audio, [role="tab"]', spot), ...marks].filter((item) => shown(item) && !folded(item) && box(item).width > 0 && box(item).height > 0)) { - window.scrollTo(0, 0); - const seen = box(node); - if (seen.bottom > innerHeight) { - window.scrollBy(0, seen.top + seen.height / 2 - innerHeight / 2); - } - const edge = box(node); - const [x, y] = [edge.left + edge.width / 2, edge.top + edge.height / 2]; - const hit = document.elementFromPoint(x, y); - if (!(list.contains(node) && (y < box(list).top || y > box(list).bottom)) && !(hit === node || node.contains(hit) || (layer && hit && layer.contains(hit) && !layer.contains(node)))) { - found.push(`${named(node)} <- ${hit ? `${hit.tagName}.${hit.getAttribute("class")}#${hit.id}` : "null"}`); - } - } - window.scrollTo(0, 0); - return found; - }; - const stack = () => { - const card = spot.querySelector(".radio-logbox"); - const head = [card.querySelector(".radio-tabs"), card.querySelector('input[type="search"]')].map(box); - const chips = all(".chip-select, .radio-filters > button", card).map(box); - return {head: Math.round(Math.max(...head.map((edge) => edge.bottom))), chips: [Math.round(Math.min(...chips.map((edge) => edge.top))), Math.round(Math.max(...chips.map((edge) => edge.bottom)))], list: Math.round(box(list).top)}; - }; - const measure = () => { - window.scrollTo(0, 0); - const [device, speak, history] = ["radio-device", "radio-speak", "radio-log"].map((id) => box(spot.querySelector(`[data-panel="${id}"]`))); - const svg = document.querySelector("#main .stage svg"); - return { - fit: document.body.classList.contains("fit"), - page: [document.documentElement.scrollWidth, document.documentElement.scrollHeight, innerWidth, innerHeight], - scrollers: scrollersIn(spot), cards: [fits(spot.querySelector(".radio-device")), fits(spot.querySelector(".radio-speak"))], - main: Math.round(box(document.getElementById("main")).height), floor: Math.round(innerHeight * @MAIN@ - box(document.getElementById("spot-host")).top), - full: Math.round(innerHeight - document.getElementById("head").offsetHeight - 16), stack: stack(), beneath: box(document.getElementById("main")).top >= box(spot).bottom - 1, - stage: svg ? Math.round(box(svg).height) : null, - list: list.clientHeight, rows: all(".radio-row", list).filter((row) => box(row).top >= box(list).top - 1 && box(row).bottom <= box(list).bottom + 1).length, - order: device.right <= speak.left && device.right <= history.left && speak.bottom <= history.top + 1 && Math.abs(speak.left - history.left) < 2, - active: {stations: fold.open ? all(".station", fold).filter(shown).length : 0, voice: !note.hidden && shown(note), speech: !display.hidden && shown(display)}, - blocked: blocked(), - banner: (() => { - const node = document.getElementById("mayday"); - if (node.hidden || !shown(node)) { - return null; - } - const words = node.querySelector(".text"); - const cancel = node.querySelector("button"); - const edge = box(cancel); - const hit = document.elementFromPoint(edge.left + edge.width / 2, edge.top + edge.height / 2); - return {height: Math.round(box(node).height), title: words.title, full: words.textContent, cut: words.scrollWidth > words.clientWidth + 1, cancel: Boolean(hit && cancel.contains(hit))}; - })(), - play: [note.querySelector(".voice-play"), note.querySelector("audio")].filter((node) => node && shown(node) && box(node).width > 0).map((node) => [node.tagName, Math.round(box(node).width), Math.round(box(node).height)]), - line: (() => { - const node = display.querySelector(".caption-line"); - return node && shown(node) ? [Math.round(node.clientWidth), text(node).length] : null; - })(), - rem: parseFloat(getComputedStyle(document.documentElement).fontSize), - }; - }; - const wanted = @STATES@; - const states = {}; - for (const name of wanted.filter((state) => state === "idle" || state.startsWith("mayday"))) { - states[name] = measure(); - } - if (wanted.includes("stations")) { - const summary = fold.querySelector("summary"); - summary.focus(); - summary.click(); - await sleep(300); - states.stations = measure(); - document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); - await sleep(200); - states.stations.closed = [fold.open, document.activeElement === summary]; - } - if (wanted.includes("voice")) { - const record = all("button", form).find((button) => button.hasAttribute("aria-pressed")); - record.click(); - await sleep(1300); - record.click(); - const heard = await until(() => !note.hidden && note.querySelector("audio") && form.querySelector("textarea").value, 30000); - await sleep(300); - states.voice = {...measure(), heard: Boolean(heard)}; - const toggle = note.querySelector(".voice-play"); - if (toggle && shown(toggle)) { - toggle.click(); - states.voice.played = Boolean(await until(() => !note.querySelector("audio").paused && toggle.getAttribute("aria-label") === "Pause voice message", 4000)); - toggle.click(); - states.voice.paused = Boolean(await until(() => note.querySelector("audio").paused && toggle.getAttribute("aria-label") === "Play voice message", 4000)); - } - const trash = all("button", note).find((button) => button.getAttribute("aria-label") === "Remove recording"); - if (trash) { - trash.click(); - } - await sleep(200); - } - if (wanted.includes("speech")) { - const found = await cue("@CUE@"); - await sleep(300); - states.speech = {...measure(), who: found && !found.error ? found.who : found}; - const stop = display.querySelector("button"); - if (stop) { - stop.click(); - } - await until(() => display.hidden, 8000); - } - return states; -})()""" -POP = """(async () => {@HELPERS@@PROBES@ - await ViewStore.update("home.pins", () => @PINS@); - location.hash = "@VIEW@"; - await screenShown(8000); - if (@SPOT@) { - await openSpot(); - } else { - await closeSpot(); - } - await settle(); - await sleep(500); - const outside = (layer) => { - const edge = box(layer); - const clips = [["viewport", {top: 0, bottom: innerHeight, left: 0, right: innerWidth}]]; - for (let node = layer.parentElement; node && node !== document.documentElement; node = node.parentElement) { - const look = getComputedStyle(node); - if (look.overflowX !== "visible" || look.overflowY !== "visible") { - clips.push([`${node.tagName}.${node.getAttribute("class")}`, box(node)]); - } - } - return clips.filter(([, clip]) => edge.top < clip.top - 1 || edge.bottom > clip.bottom + 1 || edge.left < clip.left - 1 || edge.right > clip.right + 1) - .map(([name, clip]) => `${name} [${Math.round(clip.top)},${Math.round(clip.bottom)}] vs [${Math.round(edge.top)},${Math.round(edge.bottom)}]`); - }; - const out = []; - for (const selector of @ROOTS@) { - const root = document.querySelector(selector); - if (!root || !(await until(() => root.querySelectorAll(".station").length === 3, 8000))) { - out.push({selector, error: "no stations"}); - continue; - } - const fold = root.querySelector("details.radio-station"); - const summary = fold.querySelector("summary"); - const layer = fold.querySelector(".station-body"); - fold.scrollIntoView({block: "center"}); - await sleep(200); - summary.focus(); - summary.click(); - await sleep(300); - const whole = all(".station", layer).filter((row) => box(row).top >= box(layer).top - 1 && box(row).bottom <= box(layer).bottom + 1).length; - const opened = {open: fold.open, side: fold.dataset.side, height: Math.round(box(layer).height), outside: outside(layer), whole}; - layer.querySelector(".station button").focus(); - document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); - await sleep(200); - const escape = [fold.open, document.activeElement === summary]; - summary.click(); - await sleep(300); - const again = {open: fold.open, outside: outside(layer)}; - press(document.getElementById("main")); - await sleep(200); - out.push({selector, opened, escape, again, click: [fold.open, document.activeElement === summary, document.activeElement === document.body]}); - } - return out; -})()""" -FOCUS = """(async () => {@HELPERS@@PROBES@ - await ViewStore.update("home.pins", () => []); - location.hash = "#agents/orbit"; - await screenShown(8000); - const spot = await openSpot(); - await until(() => spot.querySelectorAll(".station").length === 3 && spot.querySelector(".radio-row"), 8000); - await settle(); - await sleep(300); - const fold = spot.querySelector("details.radio-station"); - const night = await until(() => all("details.menu").find((menu) => menu.querySelector("summary").getAttribute("aria-label") === "Day/Night"), 8000); - const label = (node) => (node ? `${node.tagName}.${node.getAttribute("class")}[${node.getAttribute("aria-label") || text(node).slice(0, 24)}]` : "null"); - const tab = () => spot.querySelector('.radio-tabs [role="tab"]:not([aria-selected="true"])'); - const cases = {}; - const run = async (key, menu, target) => { - press(menu.querySelector("summary")); - await sleep(250); - const opened = menu.open; - const node = target(); - press(node); - await sleep(400); - const active = document.activeElement; - cases[key] = {opened, closed: !menu.open, active: label(active), summary: Boolean(active && active.matches("summary")), history: Boolean(active && active.closest(".radio-logbox")), body: active === document.body}; - menu.open = false; - await sleep(150); - }; - await run("night-tab", night, tab); - await run("fold-tab", fold, tab); - await run("night-main", night, () => document.getElementById("main")); - await run("fold-main", fold, () => document.getElementById("main")); - press(fold.querySelector("summary")); - await sleep(250); - fold.querySelector(".station button").focus(); - document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); - await sleep(200); - cases.escape = {closed: !fold.open, toggle: document.activeElement === fold.querySelector("summary")}; - return cases; -})()""" -LOADS = """ - const loads = {count: 0}; - const send = window.fetch.bind(window); - window.fetch = async (path, init) => { - const response = await send(path, init); - if (String(path).startsWith("/api/state")) { - const json = response.json.bind(response); - response.json = () => json().then((value) => { - loads.count += 1; - return value; - }); - } - return response; - }; - const loaded = async (more, ms) => { - const goal = loads.count + more; - const done = await until(() => loads.count >= goal, ms); - await sleep(300); - return Boolean(done); - }; -""" -ROWS = """(async () => {@HELPERS@@PROBES@@LOADS@ - await ViewStore.update("home.pins", () => []); - location.hash = "#agents/orbit"; - await screenShown(8000); - const spot = await openSpot(); - await until(() => spot.querySelectorAll(".radio-row").length > 2, 8000); - await settle(); - await sleep(300); - const rows = () => spot.querySelectorAll(".radio-row").length; - const deliver = async () => { - const before = rows(); - await fetch("/api/voice/@LIVE@", {cache: "no-store"}); - window.dispatchEvent(new Event("focus")); - const done = await until(() => rows() > before, 20000); - await sleep(300); - return Boolean(done); - }; - const row = spot.querySelectorAll(".radio-row")[1]; - const button = row.querySelector(".radio-pick"); - const held = () => { - const active = document.activeElement; - const owner = active ? active.closest(".radio-row") : null; - return {same: active === button, key: owner ? owner.dataset.key : null, pick: Boolean(active && active.matches(".radio-pick")), body: active === document.body}; - }; - button.focus(); - const start = {...held(), want: row.dataset.key}; - const fresh = {...held(), delivered: await deliver()}; - const real = Date.now; - Date.now = () => real.call(Date) + 60000; - window.dispatchEvent(new Event("focus")); - const tick = {...held(), ticked: await loaded(1, 20000)}; - Date.now = real; - const tab = spot.querySelector('.radio-tabs [role="tab"][aria-selected="true"]'); - tab.focus(); - let focusins = 0; - document.addEventListener("focusin", () => { - focusins += 1; - }, true); - const delivered = [await deliver(), await deliver(), await deliver()]; - return {start, fresh, tick, tabs: {delivered, focusins, same: document.activeElement === tab, tab: document.activeElement.getAttribute("data-tab")}}; -})()""" -KEYS = """(async () => {@HELPERS@@PROBES@ - await ViewStore.update("home.pins", () => []); - location.hash = "#agents/orbit"; - await screenShown(8000); - const spot = await openSpot(); - spot.querySelector('.radio-tabs [role="tab"][data-tab="all"]').click(); - const dups = () => all(".radio-row", spot).filter((node) => text(node.querySelector(".radio-line")).startsWith("dup ")); - await until(() => dups().length === 2, 8000); - await settle(); - await sleep(300); - const rows = () => spot.querySelectorAll(".radio-row").length; - const deliver = async () => { - const before = rows(); - await fetch("/api/voice/@LIVE@", {cache: "no-store"}); - window.dispatchEvent(new Event("focus")); - const done = await until(() => rows() > before, 20000); - await sleep(300); - return Boolean(done); - }; - const line = (node) => (node && node.closest(".radio-row") ? text(node.closest(".radio-row").querySelector(".radio-line")) : null); - const out = {keys: dups().map((node) => node.dataset.key)}; - for (const word of @DUPS@) { - const button = dups().find((node) => text(node.querySelector(".radio-line")) === word).querySelector(".radio-pick"); - button.focus(); - const delivered = await deliver(); - const active = document.activeElement; - const result = {delivered, same: active === button, line: line(active), popup: null}; - if (active && active.matches(".radio-pick")) { - active.click(); - result.popup = await until(() => (popup().open && popup().querySelector(".radio-full") ? popup().querySelector(".radio-full").textContent : null), 4000); - (document.activeElement || document.body).dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); - await until(() => !popup().open, 2000); - } - out[word] = result; - } - const victim = all(".radio-row", spot).find((node) => node.dataset.class === "newsletter"); - victim.querySelector(".radio-pick").focus(); - const chip = spot.querySelector('.chip-select[data-chip="class"] select'); - chip.value = "call"; - chip.dispatchEvent(new Event("change", {bubbles: true})); - await sleep(500); - const near = document.activeElement; - out.filtered = {gone: !victim.isConnected, pick: Boolean(near && near.matches(".radio-pick")), class: near && near.closest(".radio-row") ? near.closest(".radio-row").dataset.class : null}; - const search = spot.querySelector('.radio-logbox input[type="search"]'); - search.value = "no radio row says this"; - search.dispatchEvent(new Event("input", {bubbles: true})); - await sleep(500); - out.emptied = {gone: !spot.querySelector(".radio-row"), list: document.activeElement === spot.querySelector("ul.radio-log")}; - search.value = ""; - search.dispatchEvent(new Event("input", {bubbles: true})); - chip.value = ""; - chip.dispatchEvent(new Event("change", {bubbles: true})); - await sleep(300); - return out; -})()""" -BANNER = """(async () => {@HELPERS@@PROBES@@LOADS@ - await ViewStore.update("home.pins", () => []); - location.hash = "#agents/orbit"; - await screenShown(8000); - const banner = document.getElementById("mayday"); - await until(() => !banner.hidden && banner.querySelector("button"), 8000); - await settle(); - await sleep(300); - const records = []; - new MutationObserver((list) => records.push(...list)).observe(banner, {childList: true, subtree: true, characterData: true, attributes: true}); - const cancel = banner.querySelector("button"); - cancel.focus(); - const polled = await loaded(2, 30000); - const steady = {polled, mutations: records.length, focus: document.activeElement === cancel, body: document.activeElement === document.body}; - records.length = 0; - await fetch("/api/voice/@SILENCE@", {cache: "no-store"}); - const again = await loaded(3, 45000); - const added = records.filter((record) => record.type === "childList" && record.addedNodes.length > 0).length; - return {steady, changed: {polled: again, text: text(banner.querySelector(".text")), added, shown: !banner.hidden, cancel: Boolean(banner.querySelector("button"))}}; -})()""" -COMPOSE_HOME = """(async () => {@HELPERS@@PROBES@ - const bodies = []; - const send = window.fetch.bind(window); - window.fetch = (path, init) => { - if (String(path) === "/api/messages") { - bodies.push(JSON.parse(init.body)); - } - return send(path, init); - }; - window.confirm = () => true; - const spot = await openSpot(); - const spotText = spot.querySelector("form.composer textarea"); - spotText.value = "draft kept in the spot"; - spotText.dispatchEvent(new Event("input", {bubbles: true})); - await ViewStore.update("home.pins", () => [{kind: "panel", id: "radio", w: 12, h: 7}, {kind: "panel", id: "radio-speak", w: 6, h: 5}, {kind: "panel", id: "radio-log", w: 6, h: 5}]); - location.hash = "#home"; - await screenShown(8000); - await until(() => tile("radio-speak") && tile("radio-log") && tile("radio") && tile("radio-log").querySelector(".radio-row"), 10000); - await sleep(400); - const homeSpeak = tile("radio-speak"); - const form = (root) => root.querySelector("form.composer"); - const area = (root) => form(root).querySelector("textarea"); - const record = (root) => all("button", form(root)).find((button) => button.hasAttribute("aria-pressed")); - const note = (root) => { - const audio = form(root).querySelector(".voice-note audio"); - return audio ? audio.getAttribute("src").replace("/api/voice/", "").replace(".wav", "") : null; - }; - const drafts = [area(spot).value, area(homeSpeak).value, area(tile("radio")).value]; - record(spot).click(); - await sleep(1200); - const first = record(spot).getAttribute("aria-pressed"); - record(homeSpeak).click(); - const handed = await until(() => (record(homeSpeak).getAttribute("aria-pressed") === "true" ? [record(spot).getAttribute("aria-pressed"), "true"] : null), 5000); - const spotHeard = await until(() => (note(spot) && area(spot).value.includes("hello from the mic") ? area(spot).value : null), 30000); - const homeBefore = area(homeSpeak).value; - await sleep(800); - record(homeSpeak).click(); - const homeHeard = await until(() => (note(homeSpeak) && area(homeSpeak).value.includes("hello from the mic") ? area(homeSpeak).value : null), 30000); - const notes = [note(spot), note(homeSpeak)]; - const sendFrom = async (root, to, words, attach) => { - const [channel, recipient] = all("select", form(root)); - channel.value = "post"; - channel.dispatchEvent(new Event("change", {bubbles: true})); - await until(() => [...recipient.options].some((option) => option.value === to), 8000); - recipient.value = to; - area(root).value = words; - area(root).dispatchEvent(new Event("input", {bubbles: true})); - const box = form(root).querySelector('.voice-note input[type="checkbox"]'); - if (box) { - box.checked = attach; - } - const shownBefore = new Set(all("#toasts .toast")); - form(root).querySelector('button[type="submit"]').click(); - return until(() => all("#toasts .toast").filter((node) => !shownBefore.has(node)).map(text).find((entry) => entry.startsWith("Post to")), 20000); - }; - const spotSent = await sendFrom(spot, "Stage", "plain text from the spot", false); - const homeAttach = Boolean(form(homeSpeak).querySelector('.voice-note input[type="checkbox"]')); - const homeSent = await sendFrom(homeSpeak, "Docs", "voice from the Home tile", true); - await closeSpot(); - document.getElementById("toasts").replaceChildren(); - return {drafts, first, handed, spotHeard, homeBefore, homeHeard, notes, spotSent, homeAttach, homeSent, bodies: bodies.map((body) => [body.to, body.text, body.voice])}; -})()""" -REPLY_HOME = """(async () => {@HELPERS@@PROBES@ - const spotOpen = () => document.getElementById("radio-open").getAttribute("aria-expanded"); - const reply = async (root) => { - const row = longRow(root); - row.scrollIntoView({block: "center"}); - await sleep(200); - await openRow(row); - all(".radio-actions button", popup()).find((button) => text(button) === "Reply").click(); - await sleep(300); - }; - await reply(tile("radio-log")); - const fromLog = {spot: spotOpen(), popup: popup().open, speak: pick(tile("radio-speak")), whole: pick(tile("radio"))}; - await reply(tile("radio")); - const fromWhole = {spot: spotOpen(), whole: pick(tile("radio"))}; - const sendFrom = async (root, words) => { - const area = root.querySelector("form.composer textarea"); - area.value = words; - area.dispatchEvent(new Event("input", {bubbles: true})); - const shownBefore = new Set(all("#toasts .toast")); - root.querySelector('form.composer button[type="submit"]').click(); - return until(() => all("#toasts .toast").filter((node) => !shownBefore.has(node)).map(text).find((entry) => entry.startsWith("Post to")), 20000); - }; - const sent = await sendFrom(tile("radio"), "reply from the Home radio"); - const questions = []; - window.confirm = (question) => { - questions.push(question); - return true; - }; - const clear = all(".spot-head button", tile("radio")).find((button) => button.getAttribute("aria-label") === "Cancel mayday"); - const enabled = clear ? !clear.disabled : null; - const shownBefore = new Set(all("#toasts .toast")); - if (clear) { - clear.click(); - } - const lifted = await until(() => all("#toasts .toast").filter((node) => !shownBefore.has(node)).map(text).find((entry) => entry.startsWith("Cancel mayday")), 15000); - document.getElementById("toasts").replaceChildren(); - return {fromLog, fromWhole, sent, enabled, questions, lifted, spot: spotOpen()}; -})()""" - - -def columns(width: int, height: int) -> bool: - return any(width >= low and height >= tall for low, tall in BANDS) - - -def probe(template: str) -> str: - return (template.replace("@HELPERS@", base.HELPERS).replace("@PROBES@", PROBES).replace("@LOADS@", LOADS).replace("@SPEAKING@", base.SPEAKING).replace("@PARTS@", json.dumps(PARTS)) - .replace("@SIZES@", json.dumps(SIZES)).replace("@LIVE@", LIVE).replace("@SILENCE@", SILENCE).replace("@DUPS@", json.dumps(DUPS)).replace("@MAIN@", str(MAIN_SHARE))) +import radio_layout_kit as kit +from radio_layout_kit import ( + ALARMS, + BANNER_MAX, + DEFAULTS, + FILLERS, + LAPTOPS, + LONG, + NAMES, + NARROW, + OUT, + PARTS, + PLAY_MIN, + SCROLLER, + STAGE_SHARE, + STATES, + VIEWS, + WIDTHS, + columns, + probe, +) +from radio_layout_probes import CLOSE_REPLY, FIT, HOME, LAYOUT, POPUP, SPOT @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") -class TestRadioLayout(HubCase): - drive = base.TestOrchestratorE2E.drive - beside = base.TestOrchestratorE2E.beside - authenticator = base.TestOrchestratorE2E.authenticator - speaks = base.TestOrchestratorE2E.speaks - - def setUp(self): - super().setUp() - OUT.mkdir(parents=True, exist_ok=True) - now = time.time() - self.claim("s1", "Skills session") - rows = [{"ts": now - 1200 + index * 30, "from": NAMES[index % len(NAMES)], "to": [], "text": f"status line {index}: build {index} green", "class": "newsletter", "v": 2} for index in range(FILLERS)] - self.call = now - 400 - self.long = now - 300 - rows += [ - {"ts": self.call, "from": "Skills", "to": ["Stage", "Docs"], "text": "gate red on main", "class": "call", "v": 2}, - {"ts": self.call + 5, "from": "Stage", "to": ["Skills"], "text": "gate red on main", "class": "receipt", "v": 2, "call": self.call}, - {"ts": self.long, "from": "Stage", "to": [], "text": LONG, "class": "broadcast", "v": 2}, - ] - self.write_council({"news.jsonl": self.jsonl(rows)}) - for sid in SESSIONS: - self.mark(sid, now - 100) - self.sessions() - self.beside(self.sessions) - self.httpd.hub.receipt_reads.times[("s5", self.long)] = self.long + 40 - self.sight() - self.live = 0 - hub = self.httpd.hub - heard = hub.voice_notes.get - - def get(note_id: str) -> dict: - if note_id == SILENCE: - self.silence(NEW_ALARM) - return {"id": note_id, "status": "done", "text": "", "error": "", "seconds": None, "created_ts": None} - if note_id != LIVE: - return heard(note_id) - self.live += 1 - row = {"ts": time.time(), "from": "Docs", "to": [], "text": f"live row {self.live} for Home", "class": "broadcast", "v": 2} - with (self.council / "news.jsonl").open("a", encoding="utf-8") as handle: - handle.write(self.jsonl([row])) - return {"id": note_id, "status": "done", "text": "", "error": "", "seconds": None, "created_ts": None} - - patch = mock.patch.object(hub.voice_notes, "get", get) - patch.start() - self.addCleanup(patch.stop) - - def sessions(self) -> None: - payload = {"written": time.time(), "sessions": {sid: {"name": name, "running": True} for sid, name in SESSIONS.items()}} - written = self.state / f".{SNAPSHOT}.e2e" - written.write_text(json.dumps(payload), encoding="utf-8") - os.replace(written, self.state / SNAPSHOT) - - def sight(self) -> None: - hub = self.httpd.hub - receipts.sighting_pass(hub.scripts.skills, hub.council, hub.receipt_names, hub.receipt_reads, hub.agent_sessions, RADIO_WINDOW, time.time()) - - def mark(self, sid: str, ts: float) -> None: - folder = self.council / receipts.SEEN - folder.mkdir(parents=True, exist_ok=True) - written = folder / f".{sid}.e2e" - written.write_text(json.dumps({"radio": ts}), encoding="utf-8") - os.replace(written, folder / f"{sid}.json") - +class TestRadioLayout(kit.RadioLayoutCase): def steps(self, browser: str) -> list[dict]: steps = [] for width, height in WIDTHS: @@ -961,14 +145,6 @@ class TestRadioLayout(HubCase): self.assertGreaterEqual(fit["stage"], STAGE_SHARE * fit["height"], fit) self.assertGreaterEqual(fit["list"], 60, fit) - def silence(self, words: str) -> None: - now = time.time() - self.write_council({"radio-silence.json": {"since": now - 60, "until": now + 3600, "by": "Docs", "text": words}}) - - def stations(self) -> None: - hub = self.httpd.hub - hub.settings.put({**hub.settings.get(), "streams": STREAMS}, hub.settings.get()) - def laptop_steps(self, browser: str, states: list[str]) -> list[dict]: places = [(width, height, view) for width, height in LAPTOPS for view in VIEWS] return [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}x{height}-{states[-1]}#stream" if view == VIEWS[0] else None, "wait": 1500 if view == VIEWS[0] else 0, "gesture": True, @@ -1038,87 +214,6 @@ class TestRadioLayout(HubCase): self.assertGreaterEqual(found["list"], 60, found) self.assertGreaterEqual(found["rows"], 2, found) - def popover_steps(self, browser: str) -> list[dict]: - self.stations() - tiles = json.dumps([f'#main .home-tile[data-pin="panel:{part}"]' for part in ("radio-device", "radio")]) - places = (("spot", "#stream", "[]", '["#radio-spot"]', "true"), ("home", "#home", json.dumps(HOME_RADIO), tiles, "false"), ("home-spot", "#home", json.dumps(HOME_RADIO), tiles, "true")) - return [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}-pop#stream" if name == "spot" else None, "wait": 1500 if name == "spot" else 0, - "probe": probe(POP.replace("@VIEW@", view).replace("@PINS@", pins).replace("@ROOTS@", roots).replace("@SPOT@", spot)), "shot": str(OUT / f"{browser}-{width}-pop-{name}.png")} - for width, height in POPOVER_SIZES for name, view, pins, roots, spot in places] - - def check_popover(self, data: dict, browser: str) -> None: - results = iter(data["results"]) - for width, _ in POPOVER_SIZES: - for place in ("spot", "home", "home-spot"): - found = next(results) - self.assertEqual(len(found), 1 if place == "spot" else 2, found) - for fold in found: - with self.subTest(browser=browser, width=width, place=place, root=fold["selector"]): - self.assertNotIn("error", fold, fold) - self.assertEqual((fold["opened"]["open"], fold["opened"]["outside"]), (True, []), fold) - self.assertGreaterEqual(fold["opened"]["whole"], 1, fold) - self.assertEqual(fold["escape"], [False, True], fold) - self.assertEqual(fold["again"], {"open": True, "outside": []}, fold) - self.assertEqual(fold["click"], [False, False, True], fold) - - def focus_steps(self, browser: str) -> list[dict]: - self.stations() - return [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}-focus#stream", "wait": 1500, "probe": probe(FOCUS), "shot": str(OUT / f"{browser}-{width}-focus.png")} - for width, height in FOCUS_SIZES] - - def check_focus(self, data: dict, browser: str) -> None: - for (width, _), cases in zip(FOCUS_SIZES, data["results"], strict=True): - for key, found in cases.items(): - with self.subTest(browser=browser, width=width, case=key): - if key == "escape": - self.assertEqual(found, {"closed": True, "toggle": True}, found) - continue - self.assertEqual((found["opened"], found["closed"], found["summary"]), (True, True, False), found) - self.assertTrue(found["history"] if key.endswith("tab") else found["body"], found) - - def watch(self, browser: str, kind: str, template: str) -> dict: - width, height = FOCUS_SIZES[0] - step = {"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}-{kind}#stream", "wait": 1500, "probe": probe(template), "shot": str(OUT / f"{browser}-{width}-{kind}.png")} - driver = ("bidi.mjs", os.environ.get("FIREFOX", "firefox")) if browser == "firefox" else () - data = self.drive([step], None, *driver) - (OUT / f"{browser}-radio-{kind}.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], []) - return data["results"][0] - - def check_rows(self, found: dict, browser: str) -> None: - want = {"same": True, "key": found["start"].pop("want"), "pick": True, "body": False} - for moment, done in (("start", None), ("fresh", "delivered"), ("tick", "ticked")): - with self.subTest(browser=browser, moment=moment): - if done: - self.assertTrue(found[moment].pop(done), found) - self.assertEqual(found[moment], want, found) - with self.subTest(browser=browser, moment="tabs"): - self.assertIsNotNone(found["tabs"].pop("tab"), found) - self.assertEqual(found["tabs"], {"delivered": [True, True, True], "focusins": 0, "same": True}, found) - - def twins(self) -> None: - now = time.time() - with (self.council / "news.jsonl").open("a", encoding="utf-8") as handle: - handle.write(self.jsonl([{"ts": now - 50, "from": "Docs", "to": [], "text": words, "class": "broadcast", "v": 2} for words in DUPS])) - - def check_keys(self, found: dict, browser: str) -> None: - with self.subTest(browser=browser, case="keys"): - self.assertEqual(len(set(found["keys"])), len(DUPS), found) - for words in DUPS: - with self.subTest(browser=browser, case=words): - self.assertEqual(found[words], {"delivered": True, "same": True, "line": words, "popup": words}, found) - with self.subTest(browser=browser, case="filtered"): - self.assertEqual(found["filtered"], {"gone": True, "pick": True, "class": "call"}, found) - with self.subTest(browser=browser, case="emptied"): - self.assertEqual(found["emptied"], {"gone": True, "list": True}, found) - - def check_banner(self, found: dict, browser: str) -> None: - with self.subTest(browser=browser, moment="steady"): - self.assertEqual(found["steady"], {"polled": True, "mutations": 0, "focus": True, "body": False}, found) - with self.subTest(browser=browser, moment="changed"): - self.assertTrue(found["changed"].pop("text").endswith(NEW_ALARM), found) - self.assertEqual(found["changed"], {"polled": True, "added": 1, "shown": True, "cancel": True}, found) - def check(self, data: dict, browser: str) -> None: results = iter(data["results"]) for index, (width, height) in enumerate(WIDTHS): @@ -1149,44 +244,6 @@ class TestRadioLayout(HubCase): self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) self.check(data, "firefox") - def test_chromium_leaves_the_focus_where_a_click_lands_and_returns_it_to_the_toggle_only_on_escape(self): - data = self.drive(self.focus_steps("chromium"), None) - (OUT / "chromium-radio-focus.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - self.assertEqual(data["errors"], []) - self.check_focus(data, "chromium") - - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_leaves_the_focus_where_a_click_lands_and_returns_it_to_the_toggle_only_on_escape(self): - data = self.drive(self.focus_steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox")) - (OUT / "firefox-radio-focus.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) - self.check_focus(data, "firefox") - - def test_chromium_holds_the_focus_on_a_history_row_and_its_tab_across_new_rows_and_the_minute_tick(self): - self.check_rows(self.watch("chromium", "rows", ROWS), "chromium") - - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_holds_the_focus_on_a_history_row_and_its_tab_across_new_rows_and_the_minute_tick(self): - self.check_rows(self.watch("firefox", "rows", ROWS), "firefox") - - def test_chromium_keys_twin_rows_apart_and_moves_the_focus_of_a_filtered_out_row_to_the_nearest_row_or_the_list(self): - self.twins() - self.check_keys(self.watch("chromium", "keys", KEYS), "chromium") - - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_keys_twin_rows_apart_and_moves_the_focus_of_a_filtered_out_row_to_the_nearest_row_or_the_list(self): - self.twins() - self.check_keys(self.watch("firefox", "keys", KEYS), "firefox") - - def test_chromium_redraws_the_mayday_banner_only_when_the_silence_changes(self): - self.silence(ALARMS["mayday"]) - self.check_banner(self.watch("chromium", "banner", BANNER), "chromium") - - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_redraws_the_mayday_banner_only_when_the_silence_changes(self): - self.silence(ALARMS["mayday"]) - self.check_banner(self.watch("firefox", "banner", BANNER), "firefox") - def test_chromium_keeps_the_main_floor_and_reachable_radio_controls_in_six_states_on_both_sides_of_the_height_threshold(self): data = self.laptops("chromium") (OUT / "chromium-radio-laptops.json").write_text(json.dumps(data, indent=1), encoding="utf-8") @@ -1200,59 +257,6 @@ class TestRadioLayout(HubCase): self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) self.check_laptops(data, "firefox") - def test_chromium_places_the_station_popover_inside_every_clip_and_closes_it_on_escape_and_outside_clicks_in_the_spot_and_on_home(self): - data = self.drive(self.popover_steps("chromium"), None) - (OUT / "chromium-radio-popover.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - self.assertEqual(data["errors"], []) - self.check_popover(data, "chromium") - - @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") - def test_firefox_places_the_station_popover_inside_every_clip_and_closes_it_on_escape_and_outside_clicks_in_the_spot_and_on_home(self): - data = self.drive(self.popover_steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox")) - (OUT / "firefox-radio-popover.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) - self.check_popover(data, "firefox") - - def test_chromium_home_copies_keep_their_own_composer_record_reply_and_cancel_the_mayday(self): - now = time.time() - self.write_council({"radio-silence.json": {"since": now - 60, "until": now + 3600, "by": "Docs", "text": "disk full"}}) - steps = [] - for width, height in ((1366, 768), (390, 844)): - shot = str(OUT / f"chromium-{width}") - steps += [ - {"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}-copies#stream", "wait": 1500, "probe": probe(COMPOSE_HOME), "shot": f"{shot}-home-composers.png", "gesture": True}, - {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(REPLY_HOME), "shot": f"{shot}-home-reply.png"}, - ] - data = self.drive(steps, self.authenticator()) - (OUT / "chromium-radio-home-copies.json").write_text(json.dumps(data, indent=1), encoding="utf-8") - self.assertEqual(data["errors"], []) - results = iter(data["results"]) - question = "Lift the radio silence of the active mayday?" - for width in (1366, 390): - composed, replied = next(results), next(results) - with self.subTest(width=width, part="own composer state"): - self.assertEqual(composed["drafts"], ["draft kept in the spot", "", ""], composed) - self.assertEqual((composed["first"], composed["handed"]), ("true", ["false", "true"]), composed) - self.assertIn("hello from the mic", composed["spotHeard"] or "", composed) - self.assertNotIn("hello from the mic", composed["homeBefore"], composed) - self.assertIn("hello from the mic", composed["homeHeard"] or "", composed) - self.assertTrue(all(composed["notes"]) and composed["notes"][0] != composed["notes"][1], composed) - self.assertTrue((composed["spotSent"] or "").startswith("Post to Stage: sent"), composed) - self.assertTrue(composed["homeAttach"], composed) - self.assertTrue((composed["homeSent"] or "").startswith("Post to Docs: sent"), composed) - self.assertEqual(composed["bodies"], [["Stage", "plain text from the spot", ""], ["Docs", "voice from the Home tile", composed["notes"][1]]], composed) - with self.subTest(width=width, part="reply and mayday from Home"): - self.assertEqual(replied["fromLog"], {"spot": "false", "popup": False, "speak": {"channel": "post", "recipient": "Stage", "toShown": True, "focused": True}, - "whole": {"channel": "post", "recipient": replied["fromLog"]["whole"]["recipient"], "toShown": True, "focused": False}}, replied) - self.assertEqual(replied["fromWhole"], {"spot": "false", "whole": {"channel": "post", "recipient": "Stage", "toShown": True, "focused": True}}, replied) - self.assertTrue((replied["sent"] or "").startswith("Post to Stage: sent"), replied) - self.assertEqual((replied["enabled"], replied["questions"]), (True, [question]), replied) - self.assertTrue((replied["lifted"] or "").startswith("Cancel mayday: done"), replied) - self.assertEqual(replied["spot"], "false", replied) - radio = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO] - self.assertEqual([args[:3] for args in radio if args[0] == "post"], [["post", "--to", "Stage"], ["post", "--to", "Docs"], ["post", "--to", "Stage"]] * 2, radio) - self.assertEqual([args for args in radio if args[0] == "clear"], [["clear", "--force", "--session", "Operator"]] * 2, radio) - if __name__ == "__main__": unittest.main() diff --git a/tests/e2e/test_radio_receipts_e2e.py b/tests/e2e/test_radio_receipts_e2e.py index 3cbee50..72e13b5 100644 --- a/tests/e2e/test_radio_receipts_e2e.py +++ b/tests/e2e/test_radio_receipts_e2e.py @@ -12,7 +12,7 @@ from unittest import mock HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase from kvb_orchestrator import receipts from kvb_orchestrator.presence import SNAPSHOT @@ -74,9 +74,9 @@ PROBE = """(async () => {@HELPERS@ @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestRadioReceipts(HubCase): - drive = base.TestOrchestratorE2E.drive - authenticator = base.TestOrchestratorE2E.authenticator - beside = base.TestOrchestratorE2E.beside + drive = base.OrchestratorE2ECase.drive + authenticator = base.OrchestratorE2ECase.authenticator + beside = base.OrchestratorE2ECase.beside def setUp(self): super().setUp() diff --git a/tests/e2e/test_radio_set_e2e.py b/tests/e2e/test_radio_set_e2e.py index 9e2da1c..4bd781d 100644 --- a/tests/e2e/test_radio_set_e2e.py +++ b/tests/e2e/test_radio_set_e2e.py @@ -12,294 +12,36 @@ from unittest import mock HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase from hub_engines import log_rows from hub_support import iso from kvb_orchestrator import errors, phrasing, speechgate - -OUT = Path(os.environ.get("E2E_OUT", "/tmp/radio-set-shots")) -WORD = phrasing.procedure("security") -CUES = {"low": "c000000000000001", "high": "c000000000000002", "hold": "c000000000000003", "free": "c000000000000004", "alarm": "a000000000000001", "call": "a000000000000002", "dark": "d000000000000001", "light": "d000000000000002"} -THRESHOLDS = {1920: 60, 1366: 70, 390: 80} -FIXTURE = [ - {"ago": 600, "from": "Operator", "to": ["Stage"], "class": "post", "text": "rebase please"}, - {"ago": 500, "from": "Stage", "to": ["Operator"], "class": "call", "text": "gate red on main"}, - {"ago": 400, "from": "Docs", "to": [], "class": "newsletter", "text": "docs are green"}, - {"ago": 350, "from": "Stage", "to": ["Skills session"], "class": "post", "text": "rebase done\nsecond line of the full message"}, - {"ago": 320, "from": "Operator", "to": [], "class": "broadcast", "text": "deploy now"}, -] -SPY = """() => { - window.e2eViolations = []; - document.addEventListener("securitypolicyviolation", (event) => window.e2eViolations.push(`${event.violatedDirective} ${event.blockedURI}`)); - const log = window.e2eAudio = {tts: [], requests: [], filters: [], starts: [], oscillators: 0, levels: [], passkeys: 0}; - const fetched = window.fetch.bind(window); - window.fetch = (input, init) => { - const url = String(input && input.url ? input.url : input); - const entry = url.includes("/api/tts") ? {body: JSON.parse(init.body), status: 0} : null; - log.requests.push(url); - if (entry) { - log.tts.push(entry); - } - return fetched(input, init).then((response) => { - if (entry) { - entry.status = response.status; - } - return response; - }); - }; - const filter = AudioContext.prototype.createBiquadFilter; - AudioContext.prototype.createBiquadFilter = function created() { - const node = filter.call(this); - log.filters.push(node); - return node; - }; - const start = AudioBufferSourceNode.prototype.start; - AudioBufferSourceNode.prototype.start = function started(...args) { - log.starts.push({seconds: this.buffer ? Math.round(this.buffer.duration * 1000) / 1000 : null, channels: this.buffer ? this.buffer.numberOfChannels : null}); - return start.apply(this, args); - }; - const tone = OscillatorNode.prototype.start; - OscillatorNode.prototype.start = function toned(...args) { - log.oscillators += 1; - return tone.apply(this, args); - }; - const level = AudioParam.prototype.setValueAtTime; - AudioParam.prototype.setValueAtTime = function levelled(value, at) { - log.levels.push(Math.round(value * 1000) / 1000); - return level.call(this, value, at); - }; - if (navigator.credentials) { - const get = navigator.credentials.get.bind(navigator.credentials); - navigator.credentials.get = (options) => { - log.passkeys += 1; - return get(options); - }; - } -}""" -RADIO = """ - const spotToggle = document.getElementById("radio-open"); - await until(() => typeof Nav === "object" && document.getElementById("radio-spot"), 8000); - if (spotToggle.getAttribute("aria-expanded") !== "true") { - spotToggle.click(); - await sleep(300); - } - const spot = document.getElementById("radio-spot"); - const audio = () => window.e2eAudio; - const cue = (name) => fetch(`/api/voice/${{@CUES@}[name]}`, {cache: "no-store"}); - const refreshNow = () => window.dispatchEvent(new Event("focus")); - const field = (name) => text(spot.querySelector(`.radio-display [data-field="${name}"]`)); - const lamp = () => spot.querySelector(".radio-lamp"); - const fits = () => ({page: document.documentElement.scrollWidth <= innerWidth + 1, panel: spot.scrollWidth <= spot.clientWidth + 1}); - const press = (mode) => spot.querySelector(`.radio-modes button[data-mode="${mode}"]`).click(); - const pressed = () => all(".radio-modes button", spot).filter((button) => button.getAttribute("aria-pressed") === "true").map((button) => button.dataset.mode); - const mark = () => ({tts: audio().tts.length, starts: audio().starts.length, filters: audio().filters.length, oscillators: audio().oscillators, levels: audio().levels.length, requests: audio().requests.length}); - const since = (at) => ({ - tts: audio().tts.slice(at.tts).map((entry) => [entry.body.text, entry.status]), - starts: audio().starts.slice(at.starts), - filters: audio().filters.slice(at.filters).map((node) => [node.type, node.frequency.value]), - oscillators: audio().oscillators - at.oscillators, - levels: audio().levels.slice(at.levels), - requests: audio().requests.slice(at.requests).filter((url) => !/\\/api\\/(state|stream|events|tts|tree|subagents|voice\\/[a-d]0)/.test(url)), - }); - const cpuShown = async (label) => { - refreshNow(); - return Boolean(await until(() => field("cpu") === label, 12000)); - }; - const transmit = async (names, count) => { - const at = mark(); - for (const name of names) { - await cue(name); - } - refreshNow(); - await until(() => audio().tts.length >= at.tts + count && audio().tts.slice(at.tts).every((entry) => entry.status), 20000); - await sleep(1500); - await until(() => lamp().dataset.lit === "false", 4000); - return since(at); - }; - const tabs = () => Object.fromEntries(all('.radio-tabs [role="tab"]', spot).map((tab) => [tab.dataset.tab, Number(text(tab.querySelector(".count")))])); - const selected = () => (spot.querySelector('.radio-tabs [aria-selected="true"]') || {dataset: {}}).dataset.tab || null; - const rows = () => all(".radio-row", spot).map((item) => ({dir: item.dataset.dir, cls: item.dataset.class, route: text(item.querySelector(".radio-route")), line: text(item.querySelector(".radio-line")), ts: Number(item.querySelector("time").dataset.ts)})); - const chip = async (name, value) => { - const select = spot.querySelector(`.chip-select[data-chip="${name}"] select`); - select.value = value; - select.dispatchEvent(new Event("change", {bubbles: true})); - await sleep(150); - }; - const chips = () => Object.fromEntries(all(".chip-select", spot).map((box) => [box.dataset.chip, box.querySelector("select").value])); - const search = () => spot.querySelector('.radio-logbox input[type="search"]'); - const tab = async (id) => { - spot.querySelector(`.radio-tabs [data-tab="${id}"]`).click(); - await sleep(150); - }; - const unlabelled = () => all(".radio-face :is(button, select, input), #radio-gear :is(button, select, input), .radio-logbox :is(button, select, input), .radio-station button", spot).filter((node) => node.getClientRects().length && !node.getAttribute("aria-label") && !text(node)).length; -""".replace("@CUES@", ", ".join(f'"{name}": "{ident}"' for name, ident in CUES.items())) -FACE = """(async () => {@HELPERS@@RADIO@ - await cpuShown("CPU 10 %"); - const display = {lamp: [text(lamp()), lamp().dataset.lit], cls: field("class"), mode: field("mode"), cpu: field("cpu"), title: spot.querySelector('[data-field="cpu"]').title}; - const modes = all(".radio-modes button", spot).map((button) => [text(button), button.getAttribute("aria-pressed"), Boolean(button.title && button.getAttribute("aria-label")), Boolean(button.querySelector("svg.bi"))]); - const knobs = all(".radio-knobs input[type=range]", spot).map((input) => [input.getAttribute("aria-label"), input.min, input.max, input.step, input.value]); - const toneToggles = all(".radio-knobs button[aria-pressed]", spot).map((button) => [button.getAttribute("aria-label"), button.getAttribute("aria-pressed")]); - const labels = all(".radio-knobs .knob-row", spot).filter((row) => row.querySelector(".knob-label")).map((row) => { - const label = row.querySelector(".knob-label"); - return {text: text(label), title: label.title, whole: label.scrollWidth <= label.clientWidth + 1, row: row.scrollWidth <= row.clientWidth + 1}; - }); - const gear = all(".spot-head button", spot).find((button) => name(button) === "Read aloud"); - gear.click(); - await sleep(200); - const groups = Object.fromEntries(all("#radio-gear .chips", spot).map((group) => [group.getAttribute("aria-label"), all(".chip", group).map((chipNode) => [text(chipNode), chipNode.getAttribute("aria-pressed"), chipNode.disabled])])); - const stationsHead = text(spot.querySelector(".radio-station .group-title")); - const ptt = spot.querySelector('form.composer button[type="submit"]'); - const pageFits = fits(); - document.getElementById("settings-open").click(); - await until(() => document.querySelector("#sheet .sheet-box"), 4000); - const sections = all("#sheet .settings h3").map(text); - all("#sheet .sheet-head button").find((button) => name(button) === "Close").click(); - await sleep(200); - all(".radio-station button", spot).find((button) => text(button) === "Edit stations").click(); - await until(() => document.querySelector("#sheet .sheet-box"), 4000); - const stations = [document.querySelector("#sheet .sheet-box").getAttribute("aria-label"), all("#sheet .settings h3").map(text)]; - all("#sheet .sheet-head button").find((button) => name(button) === "Close").click(); - await sleep(200); - return {display, modes, knobs, toneToggles, labels, groups, stationsHead, ptt: [text(ptt), ptt.title], sections, stations, fits: pageFits, unlabelled: unlabelled(), palette: getComputedStyle(document.documentElement).getPropertyValue("--panel").trim(), violations: window.e2eViolations}; -})()""" -LOG = """(async () => {@HELPERS@@RADIO@ - await until(() => rows().length, 8000); - const counts = tabs(); - await tab("sent"); - const sent = rows(); - await tab("received"); - const received = rows(); - await tab("all"); - const every = rows(); - await chip("class", "post"); - const posts = rows(); - await chip("from", "Stage"); - const fromStage = rows(); - search().value = "second"; - search().dispatchEvent(new Event("input", {bubbles: true})); - await sleep(150); - const narrowed = rows(); - search().value = "please"; - search().dispatchEvent(new Event("input", {bubbles: true})); - await sleep(150); - const none = [rows().length, text(spot.querySelector(".radio-log li.muted"))]; - all(".radio-filters button", spot).find((button) => name(button) === "Clear filters").click(); - await sleep(150); - const clearedChips = [chips(), search().value, rows().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)]; - all("#popup .popup-head button").find((button) => name(button) === "Close").click(); - await sleep(150); - await tab("received"); - await chip("agent", "Stage"); - search().value = "gate"; - search().dispatchEvent(new Event("input", {bubbles: true})); - await sleep(200); - spot.querySelector(".radio-logbox").scrollIntoView({block: "start"}); - await sleep(200); - return {counts, sent, received, every, posts, fromStage, narrowed, none, clearedChips, opened, kept: rows(), fits: fits()}; -})()""" -LOG_KEPT = """(async () => {@HELPERS@@RADIO@ - await until(() => spot.querySelector(".radio-tabs [role=tab]"), 8000); - await sleep(300); - const kept = {tab: selected(), chips: chips(), q: search().value, rows: rows()}; - all(".radio-filters button", spot).find((button) => name(button) === "Clear filters").click(); - await tab("all"); - const list = spot.querySelector(".radio-log"); - list.scrollIntoView({block: "start"}); - await sleep(300); - const top = Math.max(list.getBoundingClientRect().top, spot.getBoundingClientRect().top, document.querySelector(".head").getBoundingClientRect().bottom); - const bottom = Math.min(list.getBoundingClientRect().bottom, spot.getBoundingClientRect().bottom, innerHeight); - const shown = all(".radio-row", list).filter((item) => item.getBoundingClientRect().top >= top - 1 && item.getBoundingClientRect().bottom <= bottom + 1).length; - return {...kept, shown, total: all(".radio-row", list).length, fits: fits()}; -})()""" -SOUND = """(async () => {@HELPERS@@RADIO@ - const found = {}; - press("auto"); - await cue("free"); - await cue("low"); - found.low = await cpuShown("CPU 10 %"); - found.auto = await transmit(["alarm"], 2); - await cue("hold"); - found.held = await transmit(["alarm"], 2); - const heldCount = audio().tts.length; - await sleep(2500); - found.retries = audio().tts.length - heldCount; - await cue("free"); - press("quiet"); - found.quiet = await transmit(["alarm", "call"], 1); - press("silence"); - found.silence = await transmit(["alarm", "call"], 1); - found.pressed = pressed(); - found.mode = field("mode"); - return found; -})()""" -SOUND_KEPT = """(async () => {@HELPERS@@RADIO@ - await sleep(300); - const kept = [pressed(), field("mode")]; - press("auto"); - return {kept, pressed: pressed()}; -})()""" -BURST = """(async () => {@HELPERS@@RADIO@ - const squelch = all(".radio-knobs input[type=range]", spot).find((input) => input.getAttribute("aria-label") === "Squelch"); - squelch.value = "0.6"; - squelch.dispatchEvent(new Event("input", {bubbles: true})); - await cue("high"); - const high = await cpuShown("CPU 95 %"); - const at = mark(); - await cue("alarm"); - refreshNow(); - const lit = Boolean(await until(() => lamp().dataset.lit === "true" && audio().filters.length > at.filters, 20000)); - return {high, lit, lamp: [text(lamp()), lamp().getAttribute("aria-label")], open: spot.querySelector('[data-field="cpu"]').dataset.open, heard: since(at)}; -})()""" -BURST_DONE = """(async () => {@HELPERS@@RADIO@ - await until(() => lamp().dataset.lit === "false", 6000); - await sleep(800); - const squelch = all(".radio-knobs input[type=range]", spot).find((input) => input.getAttribute("aria-label") === "Squelch"); - squelch.value = "1"; - squelch.dispatchEvent(new Event("input", {bubbles: true})); - await cue("low"); - return {tts: audio().tts.slice(-2).map((entry) => [entry.body.text, entry.status]), low: await cpuShown("CPU 10 %")}; -})()""" -THRESHOLD = """(async () => {@HELPERS@@RADIO@ - const knob = all(".radio-knobs input[type=range]", spot).find((input) => input.getAttribute("aria-label") === "Threshold"); - const before = [knob.value, audio().passkeys]; - knob.value = "@VALUE@"; - knob.dispatchEvent(new Event("input", {bubbles: true})); - knob.dispatchEvent(new Event("change", {bubbles: true})); - await until(() => all("#toasts .toast").length, 15000); - await sleep(600); - refreshNow(); - await sleep(800); - await cue("dark"); - refreshNow(); - const light = getComputedStyle(document.documentElement).getPropertyValue("--panel").trim(); - const dark = await until(() => { - const now = getComputedStyle(document.documentElement).getPropertyValue("--panel").trim(); - return now !== light ? now : null; - }, 12000); - await sleep(400); - return {before, after: [knob.value, audio().passkeys], shown: text(knob.parentElement.querySelector(".knob-value")), title: spot.querySelector('[data-field="cpu"]').title, toasts: all("#toasts .toast strong").map(text), dark: [light, dark], fits: fits()}; -})()""" -LIGHT = """(async () => {@HELPERS@@RADIO@ - await cue("light"); - refreshNow(); - await sleep(1500); - return {violations: window.e2eViolations}; -})()""" - - -def probe(template: str) -> str: - return template.replace("@HELPERS@", base.HELPERS).replace("@RADIO@", RADIO) +from radio_set_kit import ( + BURST, + BURST_DONE, + CUES, + FACE, + FIXTURE, + LIGHT, + LOG, + LOG_KEPT, + OUT, + SOUND, + SOUND_KEPT, + SPY, + THRESHOLD, + THRESHOLDS, + WORD, + probe, +) @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestRadioSet(HubCase): - drive = base.TestOrchestratorE2E.drive - authenticator = base.TestOrchestratorE2E.authenticator - beside = base.TestOrchestratorE2E.beside + drive = base.OrchestratorE2ECase.drive + authenticator = base.OrchestratorE2ECase.authenticator + beside = base.OrchestratorE2ECase.beside def setUp(self): super().setUp() diff --git a/tests/e2e/test_rates_chip_e2e.py b/tests/e2e/test_rates_chip_e2e.py index 5569cab..8b31cda 100644 --- a/tests/e2e/test_rates_chip_e2e.py +++ b/tests/e2e/test_rates_chip_e2e.py @@ -11,7 +11,7 @@ from pathlib import Path HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base import test_workbench_w4_e2e as w4 from hub_case import HubCase from hub_support import iso @@ -119,7 +119,7 @@ def sample(t: int) -> dict: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestRatesChip(HubCase): - drive = base.TestOrchestratorE2E.drive + drive = base.OrchestratorE2ECase.drive def setUp(self): super().setUp() diff --git a/tests/e2e/test_resources_view_e2e.py b/tests/e2e/test_resources_view_e2e.py index c6c5fd4..a68e35b 100644 --- a/tests/e2e/test_resources_view_e2e.py +++ b/tests/e2e/test_resources_view_e2e.py @@ -11,7 +11,7 @@ from pathlib import Path HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base import test_workbench_w4_e2e as w4 from hub_case import HubCase from hub_support import iso @@ -93,7 +93,7 @@ def probe(template: str) -> str: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestResourcesView(HubCase): - drive = base.TestOrchestratorE2E.drive + drive = base.OrchestratorE2ECase.drive sample = w4.TestWorkbenchResources.sample def setUp(self): diff --git a/tests/e2e/test_voice_input_e2e.py b/tests/e2e/test_voice_input_e2e.py index c455d32..4677ba9 100644 --- a/tests/e2e/test_voice_input_e2e.py +++ b/tests/e2e/test_voice_input_e2e.py @@ -13,7 +13,7 @@ from unittest import mock HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase from kvb_orchestrator import engines @@ -151,7 +151,7 @@ def fake_mic() -> str: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestVoiceInputE2E(HubCase): - drive = base.TestOrchestratorE2E.drive + drive = base.OrchestratorE2ECase.drive def setUp(self): super().setUp() diff --git a/tests/e2e/test_workbench_w1_e2e.py b/tests/e2e/test_workbench_w1_e2e.py index 7daeb09..bb43fd6 100644 --- a/tests/e2e/test_workbench_w1_e2e.py +++ b/tests/e2e/test_workbench_w1_e2e.py @@ -11,7 +11,7 @@ from unittest import mock HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase from hub_support import ASK, PAGE from kvb_orchestrator import batches, skill_scripts @@ -105,9 +105,12 @@ FEEDBACK = """(async () => {@HELPERS@@UNLABELLED@ const nearby = Boolean(floating && !floating.hidden); rows[1].querySelector("td.code").dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, clientX: box.left + 4, clientY: box.top + 4})); await sleep(200); - const menu = floating && floating.getAttribute("role"); - const labels = {float: floating ? unlabelled(floating) : null}; - floating.querySelector("button").click(); + const context = document.querySelector(".ctx-menu:not([hidden])"); + const menu = context && context.getAttribute("role"); + const labels = {float: floating ? unlabelled(floating) : null, menu: context ? unlabelled(context) : null}; + const first = context && context.querySelector('[role="menuitem"]'); + const item = first ? text(first.querySelector(".ctx-label")) : null; + first.click(); const sheet = await until(() => document.querySelector(".sheet-box textarea"), 4000); const writing = document.querySelector("#sheet .sheet-box"); labels.sheet = writing ? unlabelled(writing) : null; @@ -132,7 +135,7 @@ FEEDBACK = """(async () => {@HELPERS@@UNLABELLED@ keyed.value = "key f note"; all(".sheet-box button").find((button) => name(button) === "Send feedback").click(); await sleep(1500); - return {nearby, menu, title, range, keyRange, labels, shown: shown || "", posted: window.e2eFeedback, wide: document.documentElement.scrollWidth > window.innerWidth + 1}; + return {nearby, menu, item, title, range, keyRange, labels, shown: shown || "", posted: window.e2eFeedback, wide: document.documentElement.scrollWidth > window.innerWidth + 1}; })()""" @@ -142,8 +145,8 @@ def probe(template: str, tag: str, signs: bool) -> str: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestWorkbenchOperatorTasks(HubCase): - drive = base.TestOrchestratorE2E.drive - authenticator = base.TestOrchestratorE2E.authenticator + drive = base.OrchestratorE2ECase.drive + authenticator = base.OrchestratorE2ECase.authenticator def setUp(self): super().setUp() @@ -183,7 +186,7 @@ class TestWorkbenchOperatorTasks(HubCase): self.assertNotIn("error", tasks, tasks) self.assertNotIn("error", feedback, feedback) self.assertEqual(tasks["unlabelled"], {"main": [], "sheet": []}) - self.assertEqual(feedback["labels"], {"float": [], "sheet": []}) + self.assertEqual(feedback["labels"], {"float": [], "menu": [], "sheet": []}) with self.subTest(browser=browser, width=width): self.assertNotIn("error", tasks, tasks) self.assertEqual((tasks["hash"], tasks["tabs"], tasks["subs"], tasks["streamInbox"], tasks["current"]), ("#tasks/operator", base.TABS, ["Firewall"], False, ["Tasks"])) @@ -202,7 +205,7 @@ class TestWorkbenchOperatorTasks(HubCase): self.assertEqual(tasks["posted"], [["/api/sign", kinds], *([["/api/inbox/approve", kinds]] if signs else [])]) self.assertFalse(tasks["wide"]) self.assertNotIn("error", feedback, feedback) - self.assertEqual((feedback["nearby"], feedback["menu"], feedback["title"]), (True, "menu", "Feedback")) + self.assertEqual((feedback["nearby"], feedback["menu"], feedback["item"], feedback["title"]), (True, "menu", "Feedback", "Feedback")) self.assertEqual((feedback["range"], feedback["keyRange"]), ("src/app.py:2-2", "/repo:1-1")) ref = f"review:{self.reviews[(tag, 'second')]}" texts = [text for path, text in feedback["posted"] if path == "/api/messages/sign"] diff --git a/tests/e2e/test_workbench_w2_e2e.py b/tests/e2e/test_workbench_w2_e2e.py index c93e773..d3b646f 100644 --- a/tests/e2e/test_workbench_w2_e2e.py +++ b/tests/e2e/test_workbench_w2_e2e.py @@ -11,7 +11,7 @@ from pathlib import Path HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase from hub_support import iso from kvb_orchestrator import skill_scripts, tasking @@ -183,8 +183,8 @@ def finishes(points: dict) -> dict: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestWorkbenchKanban(HubCase): - drive = base.TestOrchestratorE2E.drive - authenticator = base.TestOrchestratorE2E.authenticator + drive = base.OrchestratorE2ECase.drive + authenticator = base.OrchestratorE2ECase.authenticator def setUp(self): super().setUp() diff --git a/tests/e2e/test_workbench_w3_e2e.py b/tests/e2e/test_workbench_w3_e2e.py index 5ef3427..230a949 100644 --- a/tests/e2e/test_workbench_w3_e2e.py +++ b/tests/e2e/test_workbench_w3_e2e.py @@ -12,7 +12,7 @@ from pathlib import Path HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase from hub_support import REPO_ROOT, iso @@ -213,9 +213,9 @@ def probe(template: str) -> str: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestWorkbenchArtifacts(HubCase): - drive = base.TestOrchestratorE2E.drive - authenticator = base.TestOrchestratorE2E.authenticator - subagents = base.TestOrchestratorE2E.subagents + drive = base.OrchestratorE2ECase.drive + authenticator = base.OrchestratorE2ECase.authenticator + subagents = base.OrchestratorE2ECase.subagents def setUp(self): super().setUp() diff --git a/tests/e2e/test_workbench_w4_e2e.py b/tests/e2e/test_workbench_w4_e2e.py index a0e7e52..85685fc 100644 --- a/tests/e2e/test_workbench_w4_e2e.py +++ b/tests/e2e/test_workbench_w4_e2e.py @@ -11,7 +11,7 @@ from pathlib import Path HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase OUT = Path(os.environ.get("E2E_OUT", "/tmp/workbench-w4-shots")) @@ -81,7 +81,7 @@ def quiet(found: list[str] | None) -> list[str] | None: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestWorkbenchResources(HubCase): - drive = base.TestOrchestratorE2E.drive + drive = base.OrchestratorE2ECase.drive def setUp(self): super().setUp() diff --git a/tests/e2e/test_workbench_w6_e2e.py b/tests/e2e/test_workbench_w6_e2e.py index eb093ee..61b535b 100644 --- a/tests/e2e/test_workbench_w6_e2e.py +++ b/tests/e2e/test_workbench_w6_e2e.py @@ -13,7 +13,7 @@ from unittest import mock HERE = Path(__file__).resolve().parent sys.path[:0] = [str(HERE.parent), str(HERE)] -import test_orchestrator_e2e as base +import hub_e2e_kit as base from hub_case import HubCase from hub_support import iso @@ -224,7 +224,7 @@ def quiet(found: dict) -> dict: @unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") class TestWorkbenchBubbles(HubCase): - drive = base.TestOrchestratorE2E.drive + drive = base.OrchestratorE2ECase.drive def setUp(self): super().setUp() diff --git a/tests/test_hub_context_menu.py b/tests/test_hub_context_menu.py new file mode 100644 index 0000000..0e4f810 --- /dev/null +++ b/tests/test_hub_context_menu.py @@ -0,0 +1,175 @@ +from __future__ import annotations + +import json +import subprocess +import unittest + +from hub_support import HUB + +TEMPLATES = HUB / "templates" +SOURCES = ["page-constants.js", "page-diff.js", "page-palette.js", "page-context.js"] +GENERAL = [ + "View: Home", "View: Stream", "View: Agents", "View: Artifacts", "View: Tasks", "View: Resources", "Radio …", "Cancel mayday", "Drain", "Suspend", "Resume", + "Settings …", "Music on", "Look at the sky", "Toggle control room", "Enable notifications", "Keyboard shortcuts", +] +TASKS_TAB = ["Tasks: List", "Tasks: Board", "Tasks: RASCI", "Tasks: Gantt", "Tasks: Burndown and burnup", "Tasks: 3D"] +AGENTS_TAB = ["Agents: Orbit", "Agents: Chord", "Agents: Swimlane", "Agents: Tree", "Agents: 3D", "Agents: Hierarchy", "Priority …"] +TABS = ["home", "stream", "agents", "artifacts", "tasks", "resources"] +PROBE = r""" +const fs = require("fs"); +const vm = require("vm"); +const [dir, names] = [process.argv[1], JSON.parse(process.argv[2])]; +const Nav = require(`${dir}/nav.js`); +const Panels = require(`${dir}/panels.js`); +class Element { + constructor(tag, attrs, parent) { + Object.assign(this, {tagName: tag.toUpperCase(), attrs: {...attrs}, parentElement: parent || null, rect: null}); + } + getAttribute(name) { return Object.hasOwn(this.attrs, name) ? this.attrs[name] : null; } + hasAttribute(name) { return Object.hasOwn(this.attrs, name); } + matches(selector) { return selector.split(",").map((part) => part.trim()).some((part) => (part.startsWith("[") ? this.hasAttribute(part.slice(1, -1)) : this.tagName === part.toUpperCase())); } + closest(selector) { return this.matches(selector) ? this : this.parentElement && this.parentElement.closest(selector); } + contains(node) { return Boolean(node) && (node === this || this.contains(node.parentElement)); } + getBoundingClientRect() { return this.rect; } +} +Panels.item("task", (id) => `Task ${id}`, () => null); +const KEYS_OF = {Stage: "s2", Docs: "s3"}; +const NAMES = {s2: "Stage", s3: "Docs"}; +const calls = {tasks: [], pins: [], feedback: [], shown: [], closed: 0}; +const context = { + console, Nav, Panels, Element, JSON, Math, Object, Array, String, Number, Boolean, Promise, Map, Set, Intl, + document: {activeElement: null, currentScript: null}, window: {innerWidth: 1366, innerHeight: 768, matchMedia: () => ({matches: false})}, navigator: {}, + state: {views: {"fuer-dich": {label: "For you"}}, tasks: [{task: "work/feature"}], inbox: [{kind: "review", id: "r1", title: "feat: x"}], graph: {nodes: []}}, + ui: {screen: "tasks"}, tree: {model: null}, settings: {music: {on: false}}, space: {look: false}, userViews: [{name: "Mine"}], + palette: {plan: null, input: {value: ""}, index: 0, items: [], list: {replaceChildren: () => {}, children: []}}, + h: (tag, attrs, ...children) => ({tag, attrs, children}), face: () => null, revealed: (text) => text, + agentNames: () => ["Docs", "Stage"], agentKey: (who) => KEYS_OF[who] || who, nameOf: (key) => NAMES[key] || key, labelOf: (key) => NAMES[key] || key, keyOf: (item) => `${item.kind}:${item.id}`, + go: () => {}, useView: () => {}, useSaved: () => {}, openAgent: () => {}, openRadio: () => {}, confirmAct: () => {}, openAgentOrder: () => {}, settingsSheet: () => {}, + toggleMusic: () => {}, skyLook: () => {}, toggleLeitstand: () => {}, askNotify: () => {}, helpSheet: () => {}, micButton: () => null, + taskSheet: (id) => calls.tasks.push(id), artSelect: () => {}, select: () => {}, openItem: () => {}, openSheet: () => {}, glossarySections: () => [], toast: () => {}, + homePins: () => [], homePress: (kind, id) => calls.pins.push(`${kind}:${id}`), HOME_OPENERS: {task: (id) => calls.tasks.push(`home ${id}`)}, + closeMenus: () => { calls.closed += 1; }, calls, +}; +const probe = ` +ctxShow = (sections, at) => calls.shown.push({at, sections: labels(sections)}); +selectionFeedback = () => null; +feedbackSheet = (picked) => calls.feedback.push(picked.path); +const labels = (sections) => sections.map((section) => [section.scope, section.title, section.items.map((item) => item.label)]); +const out = {}; +const panel = new Element("div", {"data-panel": "tasks/list"}); +const card = new Element("li", {"data-task": "work/feature", "data-item": "task:work/feature"}, panel); +const inside = new Element("span", {}, card); +const taskSections = ctxSections(inside); +out.task = labels(taskSections); +taskSections[0].items.forEach((item) => item.label !== "Copy task id" && item.run()); +out.ran = {tasks: calls.tasks, pins: calls.pins}; +ui.screen = "agents"; +out.agent = labels(ctxSections(new Element("g", {"data-face": "s2", "data-pick": "s2"}))); +out.operator = labels(ctxSections(new Element("span", {"data-face": "Operator"})))[0][0]; +ui.screen = "rules"; +out.rules = labels(ctxSections(new Element("main", {}))); +ui.screen = "tasks"; +const fire = (target, extra) => { + let prevented = false; + const before = calls.shown.length; + ctxContextMenu({target, clientX: 12, clientY: 34, shiftKey: false, defaultPrevented: false, ...extra, preventDefault: () => { prevented = true; }}); + const last = calls.shown.length > before ? calls.shown[calls.shown.length - 1] : null; + return {prevented, at: last && last.at, sections: last && last.sections}; +}; +out.mouse = {plain: fire(inside, {}), shift: fire(inside, {shiftKey: true}), handled: fire(inside, {defaultPrevented: true}), field: fire(new Element("textarea", {}, card), {})}; +out.closed = calls.closed; +const key = (target, extra) => { + document.activeElement = target; + let prevented = false; + const before = calls.shown.length; + ctxKeydown({key: "ContextMenu", shiftKey: false, ctrlKey: false, altKey: false, metaKey: false, ...extra, preventDefault: () => { prevented = true; }}); + const last = calls.shown.length > before ? calls.shown[calls.shown.length - 1] : null; + return {prevented, at: last && last.at, element: last && last.sections[0][1]}; +}; +const focused = new Element("article", {"data-task": "work/feature", tabindex: "0"}); +focused.rect = {left: 30, top: 40, right: 230, bottom: 90, width: 200, height: 50}; +out.keys = {menu: key(focused, {}), shiftF10: key(focused, {key: "F10", shiftKey: true}), f10: key(focused, {key: "F10"}), ctrl: key(focused, {ctrlKey: true}), field: key(new Element("input", {}), {})}; +ui.screen = "inbox"; +const entry = new Element("li", {"data-ref": "review:r1", "data-to": "Skills"}); +const file = new Element("section", {"data-path": "src/app.py"}, entry); +const cell = new Element("td", {}, file); +out.unselected = labels(ctxSections(cell))[0]; +selectionFeedback = () => ({ref: "review:r1", to: "Skills", path: "src/app.py", from: 2, until: 3, quote: "new"}); +out.selected = fire(cell, {}); +ctxSections(cell)[0].items[0].run(); +out.feedback = calls.feedback; +out.palette = paletteItems().map((item) => [item.label, item.scope, item.id === undefined ? null : item.id]); +drawPalette(); +out.paletteShown = palette.items.length; +out.keysHelp = KEYS.map(([name]) => name); +console.log(JSON.stringify(out)); +`; +const source = names.map((name) => fs.readFileSync(`${dir}/${name}`, "utf8")).join("\n"); +vm.runInNewContext(`${source}\n${probe}`, context); +""" + + +class TestHubContextMenu(unittest.TestCase): + @classmethod + def setUpClass(cls): + done = subprocess.run(["node", "-e", PROBE, str(TEMPLATES), json.dumps(SOURCES)], capture_output=True, text=True, timeout=60, check=False) + if done.returncode != 0: + raise AssertionError(done.stderr.strip()[:1200]) + cls.data = json.loads(done.stdout) + + def test_the_element_items_come_first_then_the_tab_then_the_general_ones(self): + self.assertEqual(self.data["task"], [ + ["element", "Task work/feature", ["Open task", "Copy task id", "Pin to Home"]], + ["tasks", "Tasks", TASKS_TAB], + ["general", "General", GENERAL], + ]) + + def test_the_element_items_act_on_the_clicked_element(self): + self.assertEqual(self.data["ran"], {"tasks": ["work/feature"], "pins": ["task:work/feature"]}) + + def test_an_agent_scoped_palette_item_shows_only_on_its_own_agent(self): + self.assertEqual(self.data["agent"], [["element", "Stage", ["Stage", "Copy name"]], ["agents", "Agents", AGENTS_TAB], ["general", "General", GENERAL]]) + self.assertEqual(self.data["operator"], "agents") + + def test_a_sub_screen_takes_the_items_of_its_tab(self): + self.assertEqual(self.data["rules"], [["stream", "Stream", ["View: Stream › Firewall", "Stream: For you", "Stream: Mine", "Firewall …"]], ["general", "General", GENERAL]]) + + def test_every_palette_item_has_a_scope_and_the_palette_still_lists_them_all(self): + palette = self.data["palette"] + self.assertLessEqual({scope for _, scope, _ in palette}, {"general", "agent", *TABS}) + self.assertEqual([[label, key] for label, scope, key in palette if scope == "agent"], [["Docs", "s3"], ["Stage", "s2"]]) + self.assertEqual([key for _, scope, key in palette if scope != "agent"], [None] * (len(palette) - 2)) + self.assertEqual([label for label, scope, _ in palette if scope == "general"], GENERAL) + self.assertEqual(self.data["paletteShown"], len(palette)) + + def test_a_right_click_opens_the_menu_at_the_pointer_and_shift_or_a_handled_event_or_a_text_field_keep_the_native_one(self): + mouse = self.data["mouse"] + self.assertEqual((mouse["plain"]["prevented"], mouse["plain"]["at"]), (True, {"x": 12, "y": 34})) + self.assertEqual(mouse["plain"]["sections"], self.data["task"]) + for case in ("shift", "handled", "field"): + with self.subTest(case=case): + self.assertEqual(mouse[case], {"prevented": False, "at": None, "sections": None}) + self.assertEqual(self.data["closed"], 1) + + def test_the_menu_key_and_shift_f10_open_the_menu_of_the_focused_element_at_its_rect(self): + keys = self.data["keys"] + opened = {"prevented": True, "at": {"x": 30, "y": 90}, "element": "Task work/feature"} + self.assertEqual((keys["menu"], keys["shiftF10"]), (opened, opened)) + for case in ("f10", "ctrl", "field"): + with self.subTest(case=case): + self.assertEqual(keys[case], {"prevented": False, "at": None, "element": None}) + + def test_a_selection_in_a_diff_makes_feedback_the_first_item_of_the_menu(self): + self.assertEqual(self.data["unselected"], ["element", "src/app.py", ["Copy path", "Open entry", "Copy id"]]) + selected = self.data["selected"] + self.assertTrue(selected["prevented"]) + self.assertEqual(selected["sections"][0], ["element", "src/app.py", ["Feedback", "Copy path", "Open entry", "Copy id"]]) + self.assertEqual(self.data["feedback"], ["src/app.py"]) + + def test_the_shortcuts_sheet_names_the_context_menu_keys(self): + keys = self.data["keysHelp"] + self.assertEqual(keys[:4], ["Ctrl+K", "Right-click", "Shift+right-click", "Menu key · Shift+F10"]) + + +if __name__ == "__main__": + unittest.main()