feat(orchestrator): open the source view from every Home tile
Each Home tile header gets an open button that jumps to the screen, panel or item the tile shows, restoring its scroll and selection. Tests run once on unify/skills-20261114 after the merge (operator order 2026-11-14). 🎯 Fix: 85 % 💥 Break: 10 % 💸 Tokens: 100 % ⏱️ Velocity: 100 % 🛡️ Security: 100 % 🏆 Score: 77 🚦 Gate: ⛔ fix 85 % < 90, break 10 % > 5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
48f26b678a
commit
dae4d7b38d
7 files changed
+606
-13
No files matched your search
@@ -28,11 +28,20 @@ const Nav = (() => {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param hash - the location hash.
|
||||
* @param hash - the location hash, optionally ending in ?open=<kind>:<id>, a Home pin key the screen opens.
|
||||
* @param pinned - how many pins Home holds; an empty hash opens Home once it holds one, else Stream.
|
||||
* @returns {screen, view, redirect, spot}, plus open, the pin key, when the hash names one; a hash with open
|
||||
* redirects to itself without it.
|
||||
*/
|
||||
function route(hash, pinned) {
|
||||
const [head, sub] = decodeURIComponent(String(hash).replace(/^#/, "")).split("/");
|
||||
const [path, query] = String(hash).replace(/^#/, "").split("?");
|
||||
const found = place(path, pinned);
|
||||
const open = new URLSearchParams(query || "").get("open");
|
||||
return open ? {...found, open, redirect: found.redirect || `#${path}`} : found;
|
||||
}
|
||||
|
||||
function place(path, pinned) {
|
||||
const [head, sub] = decodeURIComponent(path).split("/");
|
||||
if (!head && pinned > 0) {
|
||||
return {screen: "home", view: null, redirect: "#home"};
|
||||
}
|
||||
|
||||
@@ -39,7 +39,11 @@
|
||||
drawHome();
|
||||
}
|
||||
|
||||
function homeMessage(key) {
|
||||
/**
|
||||
* @param key - a message pin's raw id, <ts>/<entry id>.
|
||||
* @returns the stream entry, null when it no longer exists or the key is malformed, undefined while it loads.
|
||||
*/
|
||||
function homeEntry(key) {
|
||||
const cut = key.indexOf("/");
|
||||
const ts = Number(key.slice(0, cut));
|
||||
const id = key.slice(cut + 1);
|
||||
@@ -51,7 +55,11 @@
|
||||
if (!shown && (!known || (!known.busy && Date.now() - known.at > HOME_MESSAGE))) {
|
||||
homeLoadMessage(key, ts, id);
|
||||
}
|
||||
const entry = shown || (known ? known.entry : undefined);
|
||||
return shown || (known ? known.entry : undefined);
|
||||
}
|
||||
|
||||
function homeMessage(key) {
|
||||
const entry = homeEntry(key);
|
||||
if (entry === undefined) {
|
||||
return homeWait("Loading …");
|
||||
}
|
||||
@@ -229,6 +237,119 @@
|
||||
legend.replaceChildren(...drawn.series.map((line) => h("span", {class: `legend-chip ${line.tone}`, "data-series": line.id}, line.label)));
|
||||
}
|
||||
|
||||
const HOME_RETRY = 150;
|
||||
const HOME_TRIES = 60;
|
||||
const HOME_LINKS = {"radio-log": "#stream/radio", "agents/order": "#agents/hierarchy?open=panel:agents/order"};
|
||||
const HOME_SCREENS = {task: "#tasks/list", message: "#stream", artifact: "#artifacts/orbit", agent: "#agents/orbit", ancestry: "#artifacts/tree", metric: "#resources"};
|
||||
const homeItemOf = (item) => [...document.querySelectorAll("#main [data-item]")].find((node) => node.dataset.item === item) || null;
|
||||
|
||||
/**
|
||||
* @param pin - a Home pin.
|
||||
* @returns the hash of the full view of its panel or item: the panel's own tab and view, or the item's tab and view
|
||||
* with ?open=<pin key>; null for a kind without a full view.
|
||||
*/
|
||||
function homeLink(pin) {
|
||||
if (pin.kind === Panels.PANEL) {
|
||||
return Object.hasOwn(HOME_LINKS, pin.id) ? HOME_LINKS[pin.id] : `#${pin.id}`;
|
||||
}
|
||||
return Object.hasOwn(HOME_SCREENS, pin.kind) ? `${HOME_SCREENS[pin.kind]}?open=${Panels.keyOf(pin)}` : null;
|
||||
}
|
||||
|
||||
function homeOpenPanel(id) {
|
||||
const found = document.querySelector(`#main [data-panel="${id}"]`);
|
||||
if (found) {
|
||||
found.scrollIntoView({block: "start"});
|
||||
const title = found.querySelector('[tabindex="-1"]');
|
||||
if (title) {
|
||||
title.focus({preventScroll: true});
|
||||
}
|
||||
}
|
||||
return Boolean(found);
|
||||
}
|
||||
|
||||
function homeOpenMessage(key) {
|
||||
const entry = homeEntry(key);
|
||||
if (entry) {
|
||||
openPopup("Message", [popupHead(icon(Nav.ICONS.stream), "Message", h("span", {class: "muted"}, when(entry.ts))),
|
||||
h("div", {class: "popup-body"}, h("ol", {class: "feed"}, eventRow(entry)))], () => homeItemOf(`message:${key}`));
|
||||
}
|
||||
return entry !== undefined;
|
||||
}
|
||||
|
||||
function homeOpenArtifact(ref) {
|
||||
const node = artifactNode(ref);
|
||||
if (!node) {
|
||||
return Boolean(tree.model);
|
||||
}
|
||||
if (node.repo && node.repo !== art.repo) {
|
||||
art.repo = node.repo;
|
||||
drawArtifacts();
|
||||
}
|
||||
artSelect(node.id);
|
||||
return true;
|
||||
}
|
||||
|
||||
function homeOpenAncestry(path) {
|
||||
if (!tree.data || tree.busy || !tree.dom || tree.dom.view !== "tree") {
|
||||
return false;
|
||||
}
|
||||
tree.open.add(path);
|
||||
drawArtifacts();
|
||||
const frame = homeItemOf(`ancestry:${path}`);
|
||||
if (frame) {
|
||||
frame.scrollIntoView({block: "center"});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function homeOpenMetric(id) {
|
||||
const pin = homePins().find((entry) => entry.kind === "metric" && entry.id === id);
|
||||
if (!pin || !homeMetricView(pin.view)) {
|
||||
return true;
|
||||
}
|
||||
if (!resourceRestore(pin.view)) {
|
||||
return false;
|
||||
}
|
||||
const panel = document.querySelector(`#main [data-panel="resources-${pin.view.chart}"]`);
|
||||
if (panel) {
|
||||
panel.scrollIntoView({block: "nearest"});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const HOME_OPENERS = {
|
||||
panel: homeOpenPanel,
|
||||
task: (id) => {
|
||||
taskSheet(id);
|
||||
return true;
|
||||
},
|
||||
message: homeOpenMessage,
|
||||
artifact: homeOpenArtifact,
|
||||
agent: (key) => {
|
||||
openAgent(key, pickOf(key));
|
||||
return true;
|
||||
},
|
||||
ancestry: homeOpenAncestry,
|
||||
metric: (raw, id) => homeOpenMetric(id),
|
||||
};
|
||||
|
||||
/**
|
||||
* @param open - the pin key a hash names after ?open=, such as agent:s1 or panel:agents/order.
|
||||
* @param screen - the screen the hash shows.
|
||||
* @param tries - how many more times to wait HOME_RETRY ms for data the item needs, such as the tree or the samples.
|
||||
*/
|
||||
function homeOpen(open, screen, tries) {
|
||||
const cut = open.indexOf(":");
|
||||
const kind = open.slice(0, cut);
|
||||
const id = open.slice(cut + 1);
|
||||
if (cut < 1 || !Object.hasOwn(HOME_OPENERS, kind) || !Panels.ID.test(id) || ui.screen !== screen) {
|
||||
return;
|
||||
}
|
||||
if (!HOME_OPENERS[kind](kind === Panels.PANEL ? id : Panels.raw(id), id) && tries > 0) {
|
||||
window.setTimeout(() => homeOpen(open, screen, tries - 1), HOME_RETRY);
|
||||
}
|
||||
}
|
||||
|
||||
function homeRefused(why) {
|
||||
homeView.pins = homeStore.read();
|
||||
drawHome();
|
||||
@@ -373,8 +494,9 @@
|
||||
const body = h("div", {class: "home-body"});
|
||||
const grip = iconBtn("bi-grip-vertical", "Move", "btn small ghost home-grip", null, "Move: drag to another tile, or focus the tile and press the arrow keys");
|
||||
const handle = iconBtn("bi-arrow-down-right", "Resize", "btn small ghost home-resize", null, "Resize: drag, or the arrow keys, 1 to 12 columns wide and rows high");
|
||||
const open = h("a", {class: "btn small ghost icon-only home-open", "aria-label": "Open", hidden: true}, icon("bi-arrows-angle-expand"));
|
||||
const tile = h("article", {class: "home-tile", tabindex: 0, role: "listitem", "data-pin": key, on: {keydown: (event) => homeKeys(event, key)}},
|
||||
h("header", {class: "home-head"}, grip, title, iconBtn("bi-x-lg", "Unpin", "btn small ghost home-unpin", () => homeUnpin(key), "Unpin: remove the tile from Home")), body, handle);
|
||||
h("header", {class: "home-head"}, grip, title, open, iconBtn("bi-x-lg", "Unpin", "btn small ghost home-unpin", () => homeUnpin(key), "Unpin: remove the tile from Home")), body, handle);
|
||||
grip.addEventListener("pointerdown", (event) => homeGrab(event, key, "move"));
|
||||
handle.addEventListener("pointerdown", (event) => homeGrab(event, key, "size"));
|
||||
handle.addEventListener("keydown", (event) => homeSizeKeys(event, key));
|
||||
@@ -382,6 +504,16 @@
|
||||
return tile;
|
||||
}
|
||||
|
||||
function homeOpenLink(open, link, name) {
|
||||
open.hidden = !link;
|
||||
if (link) {
|
||||
open.setAttribute("href", link);
|
||||
open.setAttribute("title", `Open: show ${name} in full view`);
|
||||
} else {
|
||||
open.removeAttribute("href");
|
||||
}
|
||||
}
|
||||
|
||||
function homeContent(entry, pin) {
|
||||
try {
|
||||
return entry.render({w: pin.w, h: pin.h});
|
||||
@@ -401,6 +533,7 @@
|
||||
tile.setAttribute("aria-label", `${name}, ${pin.w} by ${pin.h}, tile ${index + 1} of ${count}`);
|
||||
homeSpan(tile, pin);
|
||||
tile.querySelector(".home-title").textContent = name;
|
||||
homeOpenLink(tile.querySelector(".home-open"), content ? homeLink(pin) : null, name);
|
||||
const body = tile.querySelector(".home-body");
|
||||
const shown = content || homeGone(pin, key);
|
||||
if (body.childNodes.length !== 1 || body.firstChild !== shown) {
|
||||
|
||||
@@ -269,16 +269,37 @@
|
||||
* plot is too small, and those series for a legend.
|
||||
*/
|
||||
function metricChart(view, size) {
|
||||
const data = resourceView.data;
|
||||
const span = {from: data.since, to: Math.max(data.until, data.since + 60)};
|
||||
const parts = resourceParts(data, {tokens: view.tokens, hidden: [], combinedHidden: [], combined: view.chart === "combined"}, span);
|
||||
const series = RESOURCE_SERIES[view.chart](parts);
|
||||
const hidden = new Set(view.shown === null ? [] : series.map((line) => line.id).filter((id) => !view.shown.includes(id)));
|
||||
const {span, parts, series, hidden} = metricParts(resourceView.data, view);
|
||||
const [, , label] = RESOURCE_PANELS.find(([kind]) => kind === view.chart);
|
||||
const drawn = RESOURCE_CHARTS[view.chart]({kind: view.chart, label}, {...parts, hidden, combinedHidden: hidden}, span, size);
|
||||
return {svg: resourceSmall(size) ? null : drawn.svg, series: series.filter((line) => !hidden.has(line.id))};
|
||||
}
|
||||
|
||||
function metricParts(data, view) {
|
||||
const span = {from: data.since, to: Math.max(data.until, data.since + 60)};
|
||||
const parts = resourceParts(data, {tokens: view.tokens, hidden: [], combinedHidden: [], combined: view.chart === "combined"}, span);
|
||||
const series = RESOURCE_SERIES[view.chart](parts);
|
||||
return {span, parts, series, hidden: new Set(view.shown === null ? [] : series.map((line) => line.id).filter((id) => !view.shown.includes(id)))};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param view - a metric pin's view: {chart, tokens, shown}.
|
||||
* @returns false while no samples are loaded; else true.
|
||||
*/
|
||||
function resourceRestore(view) {
|
||||
if (resourceView.data === null) {
|
||||
return false;
|
||||
}
|
||||
const {series, hidden} = metricParts(resourceView.data, view);
|
||||
const ids = new Set(series.map((line) => line.id));
|
||||
ViewStore.update(view.chart === "combined" ? "resources.combinedHidden" : "resources.hidden", (list) => [...list.filter((id) => !ids.has(id)), ...hidden]);
|
||||
ViewStore.set("resources.combined", view.chart === "combined");
|
||||
if (view.chart !== "hardware") {
|
||||
ViewStore.set("resources.tokens", view.tokens);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function resourceParts(data, view, span) {
|
||||
return {
|
||||
hardware: hardwareSeries(data.samples),
|
||||
|
||||
@@ -36,14 +36,20 @@
|
||||
if (route.view) {
|
||||
ui.views[route.screen] = route.view;
|
||||
}
|
||||
const show = () => {
|
||||
render(true);
|
||||
if (route.open) {
|
||||
window.setTimeout(() => homeOpen(route.open, route.screen, HOME_TRIES), 0);
|
||||
}
|
||||
};
|
||||
if (document.startViewTransition && drawn.screen && !calm.matches) {
|
||||
document.startViewTransition(() => render(true)).ready.catch((error) => {
|
||||
document.startViewTransition(show).ready.catch((error) => {
|
||||
if (error.name !== "AbortError") {
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
render(true);
|
||||
show();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,9 @@
|
||||
.home-body svg.chart { display: block; width: 100%; height: auto; max-height: 100%; }
|
||||
.home-body .stage, .home-body .graph3d { height: 100%; min-height: 0; }
|
||||
.home-grip { cursor: grab; touch-action: none; }
|
||||
.home-open[hidden] { display: none; }
|
||||
.home-tile[data-w="1"] .home-head { gap: 2px; padding-inline: 2px; }
|
||||
.home-tile[data-w="1"] .home-head .icon-only { min-width: 24px; padding-inline: 4px; }
|
||||
.home-resize { position: absolute; right: 2px; bottom: 2px; z-index: 3; cursor: nwse-resize; touch-action: none; }
|
||||
.home-gone { display: grid; place-content: center; justify-items: center; gap: var(--sp-2); height: 100%; text-align: center; }
|
||||
.home-gone-word { color: var(--bad); font-size: var(--fs-lg); text-transform: uppercase; letter-spacing: .06em; }
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
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 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
|
||||
|
||||
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-home-tile-open-shots"))
|
||||
GONE = "task:work/none-such"
|
||||
PANELS = ["agents/orbit", "tasks/3d", "tasks/operator", "agents/order", "radio-log", "stream", "artifacts/tree"]
|
||||
LANDINGS = {
|
||||
"panel:agents/orbit": ("#agents/orbit", "tab-agents"),
|
||||
"panel:tasks/3d": ("#tasks/3d", "tab-tasks"),
|
||||
"panel:tasks/operator": ("#tasks/operator", "tab-inbox"),
|
||||
"panel:agents/order": ("#agents/hierarchy", "tab-agents"),
|
||||
"panel:radio-log": ("#stream", "tab-stream"),
|
||||
"panel:stream": ("#stream", "tab-stream"),
|
||||
"panel:artifacts/tree": ("#artifacts/tree", "tab-artifacts"),
|
||||
"task": ("#tasks/list", "tab-tasks"),
|
||||
"message": ("#stream", "tab-stream"),
|
||||
"artifact": ("#artifacts/orbit", "tab-artifacts"),
|
||||
"agent": ("#agents/orbit", "tab-agents"),
|
||||
"ancestry": ("#artifacts/tree", "tab-artifacts"),
|
||||
"metric": ("#resources", "tab-resources"),
|
||||
}
|
||||
KIT = """
|
||||
const lineIds = (root) => (root ? [...new Set(all("path.res-line", root).map((path) => path.dataset.id))] : []);
|
||||
const itemOf = (selector, value) => all(selector).find((node) => node.dataset.item === value) || null;
|
||||
const closeAll = async () => {
|
||||
const popup = document.getElementById("popup");
|
||||
if (popup.open) {
|
||||
popup.querySelector('.popup-head button[aria-label="Close"]').click();
|
||||
}
|
||||
const sheet = document.querySelector('#sheet:not([hidden]) .sheet-head button[aria-label="Close"]');
|
||||
if (sheet) {
|
||||
sheet.click();
|
||||
}
|
||||
if (!document.getElementById("radio-spot").hidden) {
|
||||
document.getElementById("radio-open").click();
|
||||
}
|
||||
await sleep(100);
|
||||
};
|
||||
const landed = async (key) => {
|
||||
const cut = key.indexOf(":");
|
||||
const kind = key.slice(0, cut);
|
||||
const id = key.slice(cut + 1);
|
||||
const raw = Panels.raw(id);
|
||||
await screenShown(8000);
|
||||
let found = null;
|
||||
if (kind === "panel") {
|
||||
found = await until(() => (id === "radio-log" ? document.querySelector('#radio-spot:not([hidden]) [data-panel="radio-log"]') : document.querySelector(`#main [data-panel="${id}"]`)), 8000);
|
||||
} else if (kind === "task") {
|
||||
found = await until(() => all('#sheet:not([hidden]) [role="dialog"]').find((node) => node.getAttribute("aria-label") === raw), 8000);
|
||||
} else if (kind === "ancestry") {
|
||||
found = await until(() => itemOf("#main details[open] [data-item]", `ancestry:${raw}`), 8000);
|
||||
} else if (kind === "metric") {
|
||||
found = await until(() => lineIds(document.querySelector('#main [data-panel="resources-hardware"]')).join() === "@CPU@", 15000);
|
||||
} else {
|
||||
found = await until(() => itemOf("#popup[open] [data-item]", `${kind}:${raw}`), 10000);
|
||||
}
|
||||
await sleep(150);
|
||||
const box = found instanceof Element ? found.getBoundingClientRect() : null;
|
||||
return {
|
||||
key, found: Boolean(found), hash: location.hash, screen: document.getElementById("main").getAttribute("aria-labelledby"),
|
||||
inView: box ? box.bottom > 0 && box.top < innerHeight : null, focused: document.activeElement ? document.activeElement.id || null : null,
|
||||
chips: kind === "metric" ? all('#main [data-panel="resources-hardware"] .legend-chip[aria-pressed="true"]').map((chip) => chip.dataset.chip) : null,
|
||||
picked: kind === "artifact" ? all("#main .picked[data-pick]").map((node) => node.dataset.pick) : null,
|
||||
};
|
||||
};
|
||||
"""
|
||||
SEED = """(async () => {@HELPERS@@HOME@@KIT@
|
||||
await go("agents/orbit");
|
||||
const agent = await until(() => document.querySelector("#main svg .node.k-session[data-pick]"), 8000);
|
||||
await go("stream");
|
||||
const message = await until(() => document.querySelector('#main [data-item^="message:"]'), 8000);
|
||||
await go("artifacts/tree");
|
||||
const branch = await until(() => document.querySelector('#main .branch-row[data-item^="artifact:"]'), 8000);
|
||||
const ancestry = document.querySelector('#main [data-item^="ancestry:"]');
|
||||
const token = (node, attr) => Panels.token(node.getAttribute(attr).slice(node.getAttribute(attr).indexOf(":") + 1));
|
||||
const narrow = innerWidth > 640 ? 1 : 4;
|
||||
const pins = [
|
||||
...@PANELS@.map((id) => ({kind: "panel", id, w: 4, h: 3})),
|
||||
{kind: "task", id: "work/feature", w: 4, h: 3},
|
||||
{kind: "message", id: token(message, "data-item"), w: 4, h: 3},
|
||||
{kind: "artifact", id: token(branch, "data-item"), w: narrow, h: 3},
|
||||
{kind: "agent", id: Panels.token(agent.dataset.pick), w: 4, h: 3},
|
||||
{kind: "ancestry", id: token(ancestry, "data-item"), w: 4, h: 3},
|
||||
{kind: "metric", id: `hardware/${Panels.digest("@CPU@")}`, w: 4, h: 3, view: {chart: "hardware", tokens: "interval", shown: ["@CPU@"]}},
|
||||
{kind: "task", id: "@GONE@".slice(5), w: 4, h: 3},
|
||||
];
|
||||
await ViewStore.update("home.pins", () => pins);
|
||||
return {keys: pins.map((pin) => `${pin.kind}:${pin.id}`)};
|
||||
})()"""
|
||||
HEADERS = """(async () => {@HELPERS@@HOME@@KIT@
|
||||
await go("home");
|
||||
await until(() => !all("#main .home-tile .empty h2").some((title) => text(title).endsWith("…")), 8000);
|
||||
await sleep(600);
|
||||
const rect = (node) => {
|
||||
const box = node.getBoundingClientRect();
|
||||
return [Math.round(box.width), Math.round(box.height)];
|
||||
};
|
||||
const heads = all("#main .home-tile").map((node) => {
|
||||
const head = node.querySelector(".home-head");
|
||||
const box = head.getBoundingClientRect();
|
||||
const shown = [...head.children].filter((child) => child.getClientRects().length);
|
||||
const title = head.querySelector(".home-title");
|
||||
const open = head.querySelector(".home-open");
|
||||
open.focus();
|
||||
const focused = document.activeElement === open;
|
||||
return {
|
||||
key: node.dataset.pin, w: Number(node.dataset.w), gone: node.classList.contains("gone"), overflow: head.scrollWidth > head.clientWidth + 1,
|
||||
outside: shown.filter((child) => child.getBoundingClientRect().left < box.left - 0.5 || child.getBoundingClientRect().right > box.right + 0.5).map((child) => child.className),
|
||||
order: shown.map((child) => [...child.classList].find((name) => name.startsWith("home-"))),
|
||||
ellipsis: [getComputedStyle(title).textOverflow, getComputedStyle(title).whiteSpace, title.scrollWidth > title.clientWidth],
|
||||
open: open.hidden ? null : {href: open.getAttribute("href"), title: open.getAttribute("title"), label: open.getAttribute("aria-label"), tag: open.tagName, focused, tabIndex: open.tabIndex, size: rect(open), unpin: rect(head.querySelector(".home-unpin")), glyph: open.querySelector("use").getAttribute("href")},
|
||||
};
|
||||
});
|
||||
document.activeElement.blur();
|
||||
window.scrollTo(0, 0);
|
||||
const first = document.querySelector("#main .home-tile .home-open:not([hidden])");
|
||||
first.focus();
|
||||
await sleep(200);
|
||||
return {heads};
|
||||
})()"""
|
||||
NARROW = """(async () => {@HELPERS@@HOME@
|
||||
const found = all("#main .home-tile").find((node) => node.dataset.pin.startsWith("artifact:"));
|
||||
found.scrollIntoView({block: "center"});
|
||||
found.querySelector(".home-open").focus();
|
||||
await sleep(300);
|
||||
return {key: found.dataset.pin};
|
||||
})()"""
|
||||
CLICKS = """(async () => {@HELPERS@@HOME@@KIT@
|
||||
const results = [];
|
||||
for (const key of @KEYS@) {
|
||||
await ViewStore.update("resources.hidden", () => []);
|
||||
await go("home");
|
||||
const open = await until(() => tile(key) && tile(key).querySelector(".home-open:not([hidden])"), 8000);
|
||||
if (!open) {
|
||||
results.push({key, found: false, missing: true});
|
||||
continue;
|
||||
}
|
||||
open.scrollIntoView({block: "center"});
|
||||
open.click();
|
||||
results.push(await landed(key));
|
||||
await closeAll();
|
||||
}
|
||||
await ViewStore.update("resources.hidden", () => []);
|
||||
return {results};
|
||||
})()"""
|
||||
LANDED = """(async () => {@HELPERS@@HOME@@KIT@
|
||||
return landed("@KEY@");
|
||||
})()"""
|
||||
|
||||
|
||||
def probe(template: str, **names: str) -> str:
|
||||
fills = {"@HELPERS@": base.HELPERS, "@HOME@": dash.HOME, "@KIT@": KIT, "@CPU@": res.CPU, "@GONE@": GONE, "@PANELS@": json.dumps(PANELS)}
|
||||
fills.update({f"@{key.upper()}@": value for key, value in names.items()})
|
||||
for key, value in fills.items():
|
||||
template = template.replace(key, value)
|
||||
return template
|
||||
|
||||
|
||||
def landing(key: str) -> tuple[str, str]:
|
||||
return LANDINGS[key] if key in LANDINGS else LANDINGS[key.split(":", 1)[0]]
|
||||
|
||||
|
||||
@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
|
||||
sample = w4.TestWorkbenchResources.sample
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
self.seed()
|
||||
now = int(time.time())
|
||||
self.start = now - now % 60 - w4.ROWS * 60
|
||||
folder = self.kept / "resources"
|
||||
folder.mkdir()
|
||||
(folder / "samples.jsonl").write_text(self.jsonl([self.sample(index) for index in range(w4.ROWS)]), encoding="utf-8")
|
||||
|
||||
def pinned(self, browser: str) -> list[dict]:
|
||||
steps = []
|
||||
for width, height in base.WIDTHS:
|
||||
page = f"{self.base}?{width}"
|
||||
shot = str(OUT / f"{browser}-{width}")
|
||||
steps += [
|
||||
{"width": width, "height": height, "url": f"{page}-clear#stream", "wait": 600, "probe": bm.CLEAR, "shot": None},
|
||||
{"width": width, "height": height, "url": f"{page}-seed#stream", "wait": 1200, "probe": probe(SEED), "shot": None},
|
||||
{"width": width, "height": height, "url": f"{page}-home#home", "wait": 1500, "probe": probe(HEADERS), "shot": f"{shot}-home-headers.png"},
|
||||
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(NARROW), "shot": f"{shot}-home-narrow.png"},
|
||||
]
|
||||
return steps
|
||||
|
||||
def clicks(self, keys: list[str]) -> list[dict]:
|
||||
steps = []
|
||||
for width, height in base.WIDTHS:
|
||||
steps.append({"width": width, "height": height, "url": f"{self.base}?{width}-clicks#home", "wait": 1500, "probe": probe(CLICKS, keys=json.dumps(keys)), "shot": None})
|
||||
return steps
|
||||
|
||||
def tabs(self, links: dict[int, dict[str, str]]) -> list[dict]:
|
||||
steps = []
|
||||
for width, height in base.WIDTHS:
|
||||
for index, (key, href) in enumerate(sorted(links[width].items())):
|
||||
steps.append({"width": width, "height": height, "url": f"{self.base}?{width}-tab-{index}{href}", "wait": 1500, "probe": probe(LANDED, key=key), "shot": None})
|
||||
return steps
|
||||
|
||||
def check_heads(self, heads: list[dict], width: int) -> dict[str, str]:
|
||||
links = {}
|
||||
for head in heads:
|
||||
with self.subTest(width=width, key=head["key"]):
|
||||
self.assertFalse(head["overflow"], head)
|
||||
self.assertEqual(head["outside"], [], head)
|
||||
self.assertEqual(head["ellipsis"][:2], ["ellipsis", "nowrap"], head)
|
||||
if head["key"] == GONE:
|
||||
self.assertTrue(head["gone"], head)
|
||||
self.assertIsNone(head["open"], head)
|
||||
self.assertEqual(head["order"], ["home-grip", "home-title", "home-unpin"], head)
|
||||
continue
|
||||
self.assertFalse(head["gone"], head)
|
||||
self.assertEqual(head["order"], ["home-grip", "home-title", "home-open", "home-unpin"], head)
|
||||
found = head["open"]
|
||||
self.assertEqual((found["tag"], found["label"], found["focused"], found["tabIndex"], found["glyph"]), ("A", "Open", True, 0, "#bi-arrows-angle-expand"), found)
|
||||
self.assertTrue(found["title"].startswith("Open: show ") and found["title"].endswith(" in full view"), found)
|
||||
self.assertEqual(found["size"], found["unpin"], found)
|
||||
hash_, _ = landing(head["key"])
|
||||
if head["key"].startswith("panel:"):
|
||||
self.assertEqual(found["href"], {"panel:agents/order": "#agents/hierarchy?open=panel:agents/order", "panel:radio-log": "#stream/radio"}.get(head["key"], f"#{head['key'][6:]}"), found)
|
||||
else:
|
||||
self.assertEqual(found["href"], f"{hash_}?open={head['key']}", found)
|
||||
links[head["key"]] = found["href"]
|
||||
narrow = [head for head in heads if head["key"].startswith("artifact:")]
|
||||
self.assertEqual(len(narrow), 1, heads)
|
||||
if width != 390:
|
||||
self.assertEqual(narrow[0]["w"], 1, narrow)
|
||||
self.assertTrue(narrow[0]["ellipsis"][2], narrow)
|
||||
return links
|
||||
|
||||
def check_landed(self, found: dict, where: str) -> None:
|
||||
with self.subTest(where=where, key=found["key"]):
|
||||
hash_, screen = landing(found["key"])
|
||||
self.assertEqual((found["found"], found["hash"], found["screen"]), (True, hash_, screen), found)
|
||||
kind = found["key"].split(":", 1)[0]
|
||||
if kind == "ancestry":
|
||||
self.assertTrue(found["inView"], found)
|
||||
if found["key"] == "panel:agents/order":
|
||||
self.assertEqual(found["focused"], "agent-order-title", found)
|
||||
if kind == "metric":
|
||||
self.assertEqual(found["chips"], [res.CPU], found)
|
||||
if kind == "artifact":
|
||||
self.assertEqual(len(found["picked"]), 1, found)
|
||||
|
||||
def run_browser(self, browser: str, driver: str, binary: str) -> None:
|
||||
first = self.drive(self.pinned(browser), None, driver, binary, init=w4.GUARD)
|
||||
(OUT / f"{browser}-pinned.json").write_text(json.dumps(first, indent=1), encoding="utf-8")
|
||||
self.assertEqual([error for error in first["errors"] if "/favicon.ico" not in error], [])
|
||||
results = iter(first["results"])
|
||||
links = {}
|
||||
keys = []
|
||||
for width, _ in base.WIDTHS:
|
||||
next(results)
|
||||
keys = next(results)["keys"]
|
||||
self.assertEqual(len(keys), len(PANELS) + 7, keys)
|
||||
links[width] = self.check_heads(next(results)["heads"], width)
|
||||
self.assertEqual(sorted(links[width]), sorted(key for key in keys if key != GONE))
|
||||
self.assertTrue(next(results)["key"].startswith("artifact:"))
|
||||
clicked = self.drive(self.clicks([key for key in keys if key != GONE]), None, driver, binary, init=w4.GUARD)
|
||||
(OUT / f"{browser}-clicks.json").write_text(json.dumps(clicked, indent=1), encoding="utf-8")
|
||||
self.assertEqual([error for error in clicked["errors"] if "/favicon.ico" not in error], [])
|
||||
for (width, _), result in zip(base.WIDTHS, clicked["results"], strict=True):
|
||||
for found in result["results"]:
|
||||
self.check_landed(found, f"{browser} click {width}")
|
||||
tabs = self.drive(self.tabs(links), None, driver, binary, init=w4.GUARD)
|
||||
(OUT / f"{browser}-tabs.json").write_text(json.dumps(tabs, indent=1), encoding="utf-8")
|
||||
self.assertEqual([error for error in tabs["errors"] if "/favicon.ico" not in error], [])
|
||||
for found in tabs["results"]:
|
||||
self.check_landed(found, f"{browser} new tab")
|
||||
|
||||
def test_chromium_opens_every_tile_kind_in_its_full_view_by_click_and_by_link_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_opens_every_tile_kind_in_its_full_view_by_click_and_by_link_at_three_widths(self):
|
||||
self.run_browser("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+119
-1
@@ -573,6 +573,71 @@ console.log(JSON.stringify({pinned, glance, empty, gone}));
|
||||
"""
|
||||
|
||||
|
||||
LINK_PROBE = """
|
||||
const fs = require("fs");
|
||||
const vm = require("vm");
|
||||
const [navFile, panelsFile, homeFile] = process.argv.slice(1);
|
||||
const context = vm.createContext({labelOf: (key) => key, toast: () => null, tree: {data: null, model: null}, URLSearchParams, console});
|
||||
[navFile, panelsFile].forEach((file) => vm.runInContext(fs.readFileSync(file, "utf8"), context));
|
||||
vm.runInContext(`${fs.readFileSync(homeFile, "utf8")}
|
||||
globalThis.probe = {homeLink, Panels, Nav};`, context);
|
||||
const {homeLink, Panels, Nav} = context.probe;
|
||||
const panels = JSON.parse(process.argv[4]);
|
||||
const items = [["task", "work/a"], ["message", "1763000000.5/radio:abc"], ["artifact", "branch:/repo\\u0000feature x"], ["agent", "s1"], ["ancestry", "/repo"], ["metric", "hardware/0123456789abcdef"]];
|
||||
const link = (pin) => {
|
||||
const href = homeLink(pin);
|
||||
return {href, route: href === null ? null : Nav.route(href, 1)};
|
||||
};
|
||||
console.log(JSON.stringify({
|
||||
panels: Object.fromEntries(panels.map((id) => [id, Panels.lookup("panel", id) ? link({kind: "panel", id, w: 6, h: 4}) : null])),
|
||||
items: Object.fromEntries(items.map(([kind, raw]) => [kind, Panels.lookup(kind, Panels.token(raw)) ? link({kind, id: Panels.token(raw), w: 4, h: 3}) : null])),
|
||||
unknown: homeLink({kind: "nope", id: "x", w: 1, h: 1}),
|
||||
}));
|
||||
"""
|
||||
OPEN_PROBE = """
|
||||
const fs = require("fs");
|
||||
const vm = require("vm");
|
||||
const [panelsFile, homeFile] = process.argv.slice(1);
|
||||
const calls = [];
|
||||
const context = vm.createContext({
|
||||
labelOf: (key) => key, toast: () => null, ui: {screen: "artifacts"}, art: {repo: ""}, tree: {data: null, model: null, dom: null}, window: {setTimeout}, console,
|
||||
artSelect: (id) => calls.push(["artSelect", id]), drawArtifacts: () => calls.push(["drawArtifacts"]), taskSheet: (id) => calls.push(["taskSheet", id]),
|
||||
openAgent: (key, anchor) => calls.push(["openAgent", key, typeof anchor]), pickOf: (id) => () => id,
|
||||
});
|
||||
vm.runInContext(fs.readFileSync(panelsFile, "utf8"), context);
|
||||
vm.runInContext(`${fs.readFileSync(homeFile, "utf8")}
|
||||
globalThis.probe = {homeOpen, HOME_RETRY};`, context);
|
||||
const {homeOpen, HOME_RETRY} = context.probe;
|
||||
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
(async () => {
|
||||
["nokind", ":x", "task:", "task:bad id", "nope:x", "artifact"].forEach((open) => homeOpen(open, "artifacts", 3));
|
||||
const refused = calls.splice(0);
|
||||
homeOpen("task:work/a", "tasks", 3);
|
||||
const elsewhere = calls.splice(0);
|
||||
context.ui.screen = "tasks";
|
||||
homeOpen("task:work/a", "tasks", 3);
|
||||
homeOpen("agent:name_3a_Stage", "tasks", 3);
|
||||
const direct = calls.splice(0);
|
||||
context.ui.screen = "artifacts";
|
||||
homeOpen("artifact:wt_3a_/r/w", "artifacts", 3);
|
||||
await wait(HOME_RETRY / 2);
|
||||
const waiting = calls.splice(0);
|
||||
context.tree.model = {byRef: new Map([["wt:/r/w", {id: "wt:/r/w", repo: "/r"}]])};
|
||||
await wait(HOME_RETRY * 2);
|
||||
const opened = [calls.splice(0), context.art.repo];
|
||||
context.tree.model = null;
|
||||
homeOpen("artifact:wt_3a_/r/w", "artifacts", 1);
|
||||
context.ui.screen = "stream";
|
||||
await wait(HOME_RETRY * 3);
|
||||
context.ui.screen = "artifacts";
|
||||
context.tree.model = {byRef: new Map()};
|
||||
homeOpen("artifact:wt_3a_/r/gone", "artifacts", 3);
|
||||
await wait(HOME_RETRY * 2);
|
||||
console.log(JSON.stringify({refused, elsewhere, direct, waiting, opened, left: calls}));
|
||||
})();
|
||||
"""
|
||||
|
||||
|
||||
def node(probe: str, *args: str) -> dict:
|
||||
done = subprocess.run(["node", "-e", probe, *args], capture_output=True, text=True, timeout=60, check=True)
|
||||
return json.loads(done.stdout)
|
||||
@@ -830,13 +895,66 @@ class TestHomeMessage(unittest.TestCase):
|
||||
self.assertEqual(len(data["urls"]), data["fetches"])
|
||||
|
||||
|
||||
class TestHomeOpen(unittest.TestCase):
|
||||
PANEL_IDS = (
|
||||
"stream", "radio-log", "agents/orbit", "agents/chord", "agents/swimlane", "agents/3d", "agents/tree", "agents/hierarchy", "agents/order",
|
||||
"artifacts/orbit", "artifacts/chord", "artifacts/swimlane", "artifacts/tree", "artifacts/3d",
|
||||
"tasks/list", "tasks/board", "tasks/rasci", "tasks/gantt", "tasks/burn", "tasks/3d", "tasks/operator",
|
||||
)
|
||||
ITEMS: ClassVar[dict] = {
|
||||
"task": ("#tasks/list", "task:work/a", "tasks", "list"),
|
||||
"message": ("#stream", "message:1763000000.5/radio_3a_abc", "stream", None),
|
||||
"artifact": ("#artifacts/orbit", "artifact:branch_3a_/repo_0_feature_20_x", "artifacts", "orbit"),
|
||||
"agent": ("#agents/orbit", "agent:s1", "agents", "orbit"),
|
||||
"ancestry": ("#artifacts/tree", "ancestry:/repo", "artifacts", "tree"),
|
||||
"metric": ("#resources", "metric:hardware/0123456789abcdef", "resources", None),
|
||||
}
|
||||
|
||||
def test_a_hash_may_name_a_pin_to_open_and_then_redirects_to_its_screen_without_it(self):
|
||||
hashes = ["#agents/orbit?open=agent:s1", "#stream/radio?open=x:y", "#tasks/operator?open=panel:tasks/operator", "#agents/orbit?other=1", "#resources?open=metric:hardware/x", "#?open=task:a"]
|
||||
probe = "const N = require(process.argv[1]); console.log(JSON.stringify(JSON.parse(process.argv[2]).map((hash) => N.route(hash, 1))));"
|
||||
done = subprocess.run(["node", "-e", probe, str(NAV), json.dumps(hashes)], capture_output=True, text=True, timeout=60, check=True)
|
||||
self.assertEqual(json.loads(done.stdout), [
|
||||
{"screen": "agents", "view": "orbit", "redirect": "#agents/orbit", "open": "agent:s1"},
|
||||
{"screen": "stream", "view": None, "redirect": "#stream", "spot": True, "open": "x:y"},
|
||||
{"screen": "inbox", "view": None, "redirect": "#tasks/operator", "open": "panel:tasks/operator"},
|
||||
{"screen": "agents", "view": "orbit", "redirect": None},
|
||||
{"screen": "resources", "view": None, "redirect": "#resources", "open": "metric:hardware/x"},
|
||||
{"screen": "home", "view": None, "redirect": "#home", "open": "task:a"},
|
||||
])
|
||||
|
||||
def test_every_panel_and_item_kind_links_to_its_own_tab_and_view_and_an_item_names_itself_to_open(self):
|
||||
data = node(LINK_PROBE, str(NAV), str(PANELS), str(HOME), json.dumps(self.PANEL_IDS))
|
||||
special = {"stream": ("stream", None), "radio-log": ("stream", None), "agents/order": ("agents", "hierarchy"), "tasks/operator": ("inbox", None)}
|
||||
for panel in self.PANEL_IDS:
|
||||
with self.subTest(panel=panel):
|
||||
found = data["panels"][panel]
|
||||
self.assertIsNotNone(found)
|
||||
screen, view = special.get(panel, tuple(panel.split("/")))
|
||||
self.assertEqual((found["route"]["screen"], found["route"]["view"]), (screen, view), found)
|
||||
self.assertEqual(data["panels"]["radio-log"], {"href": "#stream/radio", "route": {"screen": "stream", "view": None, "redirect": "#stream", "spot": True}})
|
||||
self.assertEqual(data["panels"]["agents/order"]["href"], "#agents/hierarchy?open=panel:agents/order")
|
||||
self.assertEqual(data["panels"]["agents/order"]["route"]["open"], "panel:agents/order")
|
||||
self.assertEqual({panel: found["href"] for panel, found in data["panels"].items() if panel not in ("radio-log", "agents/order")}, {panel: f"#{panel}" for panel in self.PANEL_IDS if panel not in ("radio-log", "agents/order")})
|
||||
for kind, (hash_, key, screen, view) in self.ITEMS.items():
|
||||
with self.subTest(kind=kind):
|
||||
self.assertEqual(data["items"][kind], {"href": f"{hash_}?open={key}", "route": {"screen": screen, "view": view, "redirect": hash_, "open": key}})
|
||||
self.assertIsNone(data["unknown"])
|
||||
|
||||
def test_an_opened_item_waits_for_its_data_gives_up_on_a_gone_one_and_stops_once_another_screen_shows(self):
|
||||
data = node(OPEN_PROBE, str(PANELS), str(HOME))
|
||||
self.assertEqual((data["refused"], data["elsewhere"], data["waiting"], data["left"]), ([], [], [], []), data)
|
||||
self.assertEqual(data["direct"], [["taskSheet", "work/a"], ["openAgent", "name:Stage", "function"]])
|
||||
self.assertEqual(data["opened"], [[["drawArtifacts"], ["artSelect", "wt:/r/w"]], "/r"])
|
||||
|
||||
|
||||
class TestHomeIndex(HubCase):
|
||||
def test_the_index_embeds_the_registry_the_home_page_and_its_styles(self):
|
||||
html = self.index()
|
||||
for name in ("panels.js", "page-home.js", "style-home.css"):
|
||||
with self.subTest(name=name):
|
||||
self.assertIn((TEMPLATES / name).read_text(encoding="utf-8").strip(), html)
|
||||
for glyph in ("bi-star", "bi-star-fill", "bi-house-door", "bi-grip-vertical", "bi-arrow-down-right"):
|
||||
for glyph in ("bi-star", "bi-star-fill", "bi-house-door", "bi-grip-vertical", "bi-arrow-down-right", "bi-arrows-angle-expand"):
|
||||
with self.subTest(glyph=glyph):
|
||||
self.assertIn(f'<symbol id="{glyph}"', html)
|
||||
|
||||
|
||||
Reference in new issue
Block a user