From 4451eecc0b5d591732f7ab49dece73333244ebff Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 13 Nov 2026 12:51:20 +0000 Subject: [PATCH] feat(orchestrator): Home tab with pinned panels on a 12-column grid (008) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Home tab left of Stream shows every panel and item the operator starred: a star on every panel and item pins it, tiles sit on a 12-column grid, resize in width and height, reorder by drag, render live, and a pinned item that no longer exists shows a gone tile with an unpin button. Home becomes the start tab once something is pinned. The layout lives in 007's view store, changed only through update() so two tabs never overwrite each other's pins. Committed below the 90/5 bar on the operator's word so the unify e2e proves it before master moves. ๐ŸŽฏ Fix: 88 % ๐Ÿ’ฅ Break: 6 % ๐Ÿ’ธ Cost: 100 % โฑ๏ธ Time: 100 % ๐Ÿ›ก๏ธ Security: 100 % ๐Ÿ† Score: 83 ๐Ÿšฆ Gate: โ›” fix 88 % < 90, break 6 % > 5 Co-Authored-By: Claude Opus 5.5 --- orchestrator/templates/index.html.j2 | 6 + orchestrator/templates/nav.js | 13 +- orchestrator/templates/page-agent.js | 2 +- orchestrator/templates/page-ancestry.js | 3 +- orchestrator/templates/page-artifacts.js | 4 +- orchestrator/templates/page-boot.js | 1 + orchestrator/templates/page-graph-charts.js | 2 +- orchestrator/templates/page-hierarchy.js | 4 +- orchestrator/templates/page-home.js | 403 +++++++++++++++ orchestrator/templates/page-kanban.js | 4 +- orchestrator/templates/page-screens.js | 5 +- orchestrator/templates/page-spawn.js | 4 +- orchestrator/templates/page-stream.js | 6 +- orchestrator/templates/page-tasks.js | 6 +- orchestrator/templates/panels.js | 316 ++++++++++++ orchestrator/templates/style-home.css | 23 + tests/e2e/test_home_dashboard_e2e.py | 390 +++++++++++++++ tests/e2e/test_orchestrator_e2e.py | 2 +- tests/e2e/test_workbench_w4_e2e.py | 2 +- tests/test_hub_home.py | 528 ++++++++++++++++++++ tests/test_hub_nav.py | 6 +- 21 files changed, 1703 insertions(+), 27 deletions(-) create mode 100644 orchestrator/templates/page-home.js create mode 100644 orchestrator/templates/panels.js create mode 100644 orchestrator/templates/style-home.css create mode 100644 tests/e2e/test_home_dashboard_e2e.py create mode 100644 tests/test_hub_home.py diff --git a/orchestrator/templates/index.html.j2 b/orchestrator/templates/index.html.j2 index 80b799d..b167913 100644 --- a/orchestrator/templates/index.html.j2 +++ b/orchestrator/templates/index.html.j2 @@ -421,6 +421,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi {% include "style-diff.css" %} {% include "style-ancestry.css" %} + +{% include "style-home.css" %} @@ -469,6 +471,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi {% include "nav.js" %} +{% include "panels.js" %} + {% include "ancestry.js" %} {% include "popup.js" %} @@ -584,6 +588,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi {% include "page-resources.js" %} +{% include "page-home.js" %} + {% include "page-rules.js" %} {% include "page-keyboard.js" %} diff --git a/orchestrator/templates/nav.js b/orchestrator/templates/nav.js index 0887a7d..325055f 100644 --- a/orchestrator/templates/nav.js +++ b/orchestrator/templates/nav.js @@ -1,13 +1,13 @@ const Nav = (() => { "use strict"; - const TABS = [["stream", "Stream"], ["agents", "Agents"], ["artifacts", "Artifacts"], ["tasks", "Tasks"], ["resources", "Resources"]]; + const TABS = [["home", "Home"], ["stream", "Stream"], ["agents", "Agents"], ["artifacts", "Artifacts"], ["tasks", "Tasks"], ["resources", "Resources"]]; const SUBS = {stream: [["rules", "Firewall"]]}; const PANES = {inbox: ["tasks", "operator"]}; const VIEWS = [["orbit", "Orbit"], ["chord", "Chord"], ["swimlane", "Swimlane"], ["tree", "Tree"], ["3d", "3D"]]; const TASK_VIEWS = [["list", "List"], ["board", "Board"], ["rasci", "RASCI"], ["gantt", "Gantt"], ["burn", "Burndown and burnup"], ["3d", "3D"]]; const OWN = {agents: [["hierarchy", "Hierarchy"]]}; const ICONS = { - stream: "bi-activity", inbox: "bi-inbox", rules: "bi-card-checklist", agents: "bi-people", artifacts: "bi-git", tasks: "bi-list-check", + home: "bi-house-door", stream: "bi-activity", inbox: "bi-inbox", rules: "bi-card-checklist", agents: "bi-people", artifacts: "bi-git", tasks: "bi-list-check", orbit: "bi-globe2", chord: "bi-bezier2", swimlane: "bi-bar-chart-steps", tree: "bi-diagram-3", "3d": "bi-badge-3d", hierarchy: "bi-diagram-2", list: "bi-list-task", board: "bi-kanban", rasci: "bi-grid-3x3", gantt: "bi-calendar-range", burn: "bi-graph-down-arrow", resources: "bi-speedometer2", @@ -27,8 +27,15 @@ const Nav = (() => { return tabOf(screen) === screen ? (view ? `#${screen}/${view}` : `#${screen}`) : `#${tabOf(screen)}/${screen}`; } - function route(hash) { + /** + * @param hash - the location hash. + * @param pinned - how many pins Home holds; an empty hash opens Home once it holds one, else Stream. + */ + function route(hash, pinned) { const [head, sub] = decodeURIComponent(String(hash).replace(/^#/, "")).split("/"); + if (!head && pinned > 0) { + return {screen: "home", view: null, redirect: "#home"}; + } if (head === "stream" && sub === "radio") { return {screen: "stream", view: null, redirect: "#stream", spot: true}; } diff --git a/orchestrator/templates/page-agent.js b/orchestrator/templates/page-agent.js index fcf31c3..4aa3d44 100644 --- a/orchestrator/templates/page-agent.js +++ b/orchestrator/templates/page-agent.js @@ -118,7 +118,7 @@ const former = (people()[key] || {names: []}).names.filter((entry) => entry !== name); openPopup(name, [ popupHead(face(name, true), name, h("span", {class: "muted"}, former.length ? `Agent ยท formerly ${former.join(", ")}` : "Agent"), " ", life), - h("div", {class: "popup-body"}, nightRow, info, h("h3", {}, "Subagents"), subs, h("h3", {}, "History"), log), + h("div", {class: "popup-body", "data-item": `agent:${key}`}, nightRow, info, h("h3", {}, "Subagents"), subs, h("h3", {}, "History"), log), form, ], anchor, () => { agentDom = null; diff --git a/orchestrator/templates/page-ancestry.js b/orchestrator/templates/page-ancestry.js index 9a19e40..2ee0685 100644 --- a/orchestrator/templates/page-ancestry.js +++ b/orchestrator/templates/page-ancestry.js @@ -81,7 +81,7 @@ const svg = s("svg", {viewBox: `0 0 ${width} ${plan.height}`, width, height: plan.height, class: "chart ancestry", role: "group", "aria-label": label}); const curve = (link) => `M${fixed(link.x1)},${fixed(link.y1)} C${fixed(link.x1)},${fixed((link.y1 + link.y2) / 2)} ${fixed(link.x2)},${fixed((link.y1 + link.y2) / 2)} ${fixed(link.x2)},${fixed(link.y2)}`; svg.append(s("g", {}, plan.links.map((link) => mark.edge(link, curve(link)))), s("g", {}, plan.nodes.map((node) => mark.node(node)))); - return h("div", {class: "ancestry-frame"}, svg); + return h("div", {class: "ancestry-frame", "data-item": mark.item || null}, svg); } function branchAncestry(repo) { @@ -103,6 +103,7 @@ const plan = Ancestry.layout(repo.branches.map((entry) => ({id: entry.name, label: entry.name})), edges); const dropping = (link) => staged.some((item) => item.drop && item.branch === link.child && item.parent === link.parent); return ancestryChart(plan, `Ancestry of ${repo.name}`, { + item: `ancestry:${repo.path}`, edge: (link, d) => s("path", { class: ["ancestry-edge", link.derived ? "derived" : "", link.source === "staged" ? "pending" : "", dropping(link) ? "dropping" : ""].filter(Boolean).join(" "), d, "data-child": link.child, "data-parent": link.parent, "data-source": link.source, diff --git a/orchestrator/templates/page-artifacts.js b/orchestrator/templates/page-artifacts.js index 3766876..72ebd14 100644 --- a/orchestrator/templates/page-artifacts.js +++ b/orchestrator/templates/page-artifacts.js @@ -237,7 +237,7 @@ } else { body.push(meta([["Title", data.title], ["Status", data.status]])); } - return [popupHead(icon(kindIcon), node.label, h("span", {class: "muted"}, kindName)), h("div", {class: "popup-body"}, body)]; + return [popupHead(icon(kindIcon), node.label, h("span", {class: "muted"}, kindName)), h("div", {class: "popup-body", "data-item": `artifact:${node.id}`}, body)]; } function artifactsScreen() { @@ -264,7 +264,7 @@ }, 0); const controls = h("div", {class: "card controls"}, viewSwitch("artifacts"), view === "3d" ? layoutTools("artifacts") : view === "tree" ? null : picker, h("div", {class: "toolbar", role: "toolbar", "aria-label": "Artifacts"}, search, reload, removeAll, apply), count); - const body = view === "tree" ? list : h("div", {class: "card stage-card"}, stageBox, legendBox); + const body = view === "tree" ? list : h("div", {class: "card stage-card", "data-panel": `artifacts/${view}`}, stageBox, legendBox); return h("div", {class: "graph"}, controls, body); } diff --git a/orchestrator/templates/page-boot.js b/orchestrator/templates/page-boot.js index dd99b0d..04f7b7b 100644 --- a/orchestrator/templates/page-boot.js +++ b/orchestrator/templates/page-boot.js @@ -48,6 +48,7 @@ notifyLabel(); announce(); measure(); + homeBoot(); apply(); drawTime(); motion.asOf = ui.asOf; diff --git a/orchestrator/templates/page-graph-charts.js b/orchestrator/templates/page-graph-charts.js index 97ab0f1..e428cc4 100644 --- a/orchestrator/templates/page-graph-charts.js +++ b/orchestrator/templates/page-graph-charts.js @@ -185,6 +185,6 @@ const stageBox = h("div", {class: "stage"}); const toolbar = agentsToolbar(); graphDom = {stage: stageBox, pulses: null, toolbar}; - const body = view === "tree" ? spawnScreen() : view === "hierarchy" ? hierarchyScreen() : h("div", {class: "card stage-card"}, stageBox, view === "3d" ? null : legend()); + const body = view === "tree" ? spawnScreen() : view === "hierarchy" ? hierarchyScreen() : h("div", {class: "card stage-card", "data-panel": `agents/${view}`}, stageBox, view === "3d" ? null : legend()); return h("div", {class: "graph"}, toolbar.bar, h("div", {class: "card controls"}, viewSwitch("agents"), view === "3d" ? layoutTools("agents") : null), body); } diff --git a/orchestrator/templates/page-hierarchy.js b/orchestrator/templates/page-hierarchy.js index bd6def1..5c9764f 100644 --- a/orchestrator/templates/page-hierarchy.js +++ b/orchestrator/templates/page-hierarchy.js @@ -3,7 +3,7 @@ const OFFICE_GROUPS = [["cluster", "Organizers", "Organizer"], ["work", "Presidents", "President"], ["other", "Other offices", "Office"]]; function hierarchyScreen() { - hier.chart = h("section", {class: "card org-chart", "aria-labelledby": "org-title"}); + hier.chart = h("section", {class: "card org-chart", "data-panel": "agents/hierarchy", "aria-labelledby": "org-title"}); orderDom.box = h("section", {class: "card agent-order", id: "agent-order", "aria-labelledby": "agent-order-title"}); hier.sig = ""; return h("div", {class: "hierarchy-body"}, hier.chart, orderDom.box); @@ -120,7 +120,7 @@ hier.ids = 0; const count = state.claims.length; hier.chart.replaceChildren( - h("div", {class: "inbox-head"}, h("h2", {class: "group-title", id: "org-title"}, "Hierarchy", counter(count)), + h("div", {class: "inbox-head", "data-star-slot": ""}, h("h2", {class: "group-title", id: "org-title"}, "Hierarchy", counter(count)), h("span", {class: "muted"}, "Formal offices from the council: Operator โ†’ Chair โ†’ dimensions โ†’ lines, plus organizers and presidents"), h("span", {class: "spacer"}), h("button", {type: "button", class: "btn small soft", "data-focus": "appoint:new", ...named("New office", "New office: give a free office to a session, with a passkey signature"), on: {click: () => officeSheet("appoint", null)}}, icon("bi-person-plus"), "New office")), diff --git a/orchestrator/templates/page-home.js b/orchestrator/templates/page-home.js new file mode 100644 index 0000000..6ab341a --- /dev/null +++ b/orchestrator/templates/page-home.js @@ -0,0 +1,403 @@ + const HOME_PATH = "home.pins"; + const HOME_FETCH = 3000; + const HOME_MESSAGE = 30000; + const HOME_RADIO = 12; + const HOME_MARKS = [['section[aria-label="Radio log"]', "radio-log"], ['section[aria-label="Recently sent"]', "radio-log"]]; + const homeView = {dom: null, pins: [], tiles: new Map(), hosts: new Map(), messages: new Map(), drag: null, mark: () => null, touched: false, fetched: {}}; + const homeStore = Panels.store(typeof ViewStore === "object" && ViewStore ? ViewStore : Panels.memory(), HOME_PATH); + const homePins = () => homeView.pins; + const homeIndex = (key) => homePins().findIndex((pin) => Panels.keyOf(pin) === key); + const homeWait = (title) => emptyState(title, "The tile fills in on the next poll."); + + function homeFetch(name, work) { + if (Date.now() - (homeView.fetched[name] || 0) > HOME_FETCH) { + homeView.fetched[name] = Date.now(); + Promise.resolve(work()).then(() => drawHome()); + } + } + + function homeStream(size) { + homeFetch("events", fetchEvents); + const rows = [...stream.events, ...stream.entries].sort((a, b) => b.ts - a.ts).slice(0, Math.max(3, size.h * 2)); + return rows.length ? h("ol", {class: "feed"}, rows.map(eventRow)) : homeWait(stream.key ? "No entries" : "Loading โ€ฆ"); + } + + async function homeLoadMessage(key, ts, id) { + const known = homeView.messages.get(key) || {entry: undefined}; + homeView.messages.set(key, {...known, busy: true, at: Date.now()}); + let entry = known.entry; + try { + const response = await fetch(`/api/events?from=${Math.floor(ts) - 1}&to=${Math.ceil(ts) + 1}&after=0`, {cache: "no-store"}); + if (response.ok) { + const data = await response.json(); + entry = [...data.events, ...data.entries].find((row) => String(row.id) === id) || null; + } + } catch { + ui.offline = true; + } + homeView.messages.set(key, {entry, busy: false, at: Date.now()}); + drawHome(); + } + + function homeMessage(key) { + const cut = key.indexOf("/"); + const ts = Number(key.slice(0, cut)); + const id = key.slice(cut + 1); + if (cut < 1 || !Number.isFinite(ts)) { + return null; + } + const shown = [...stream.events, ...stream.entries].find((row) => String(row.id) === id); + const known = homeView.messages.get(key); + if (!shown && (!known || (!known.busy && Date.now() - known.at > HOME_MESSAGE))) { + homeLoadMessage(key, ts, id); + } + const entry = shown || (known ? known.entry : undefined); + if (entry === undefined) { + return homeWait("Loading โ€ฆ"); + } + return entry ? h("ol", {class: "feed"}, eventRow(entry)) : null; + } + + function homeRadio() { + const rows = state.radio.slice(-HOME_RADIO).reverse(); + return rows.length ? h("ul", {class: "mini"}, rows.map((row) => h("li", {}, + h("div", {class: "row"}, klass(row.class), when(row.ts)), + h("span", {class: "muted"}, `${dash(row.from)} โ†’ ${targetsOf(row)}`), + h("span", {}, short(row.text))))) : h("p", {class: "muted"}, "No radio in the chosen time range yet."); + } + + function homeTree(draw) { + if (!tree.data) { + homeFetch("tree", fetchTree); + return homeWait("Reading repositories โ€ฆ"); + } + return tree.data.error ? emptyState("No tree", tree.data.error) : draw(); + } + + function homeArt(view) { + return homeTree(() => { + const repo = chosenRepo(); + return repo ? {orbit: artOrbit, chord: artChord, swimlane: artSwimlane}[view](repo, tree.model) : emptyState("No repository", "pkgmgr names no repository."); + }); + } + + function homeArtifact(id) { + return homeTree(() => { + const node = tree.model.byId.get(id); + return node ? h("div", {class: "home-popup"}, artPopup(node)) : null; + }); + } + + function homeAncestry(path) { + return homeTree(() => { + const repo = tree.data.repos.find((entry) => entry.path === path); + return repo ? branchAncestry(repo) : null; + }); + } + + function homeOrbit() { + const kept = [graphDom, positions]; + graphDom = {pulses: null}; + try { + return orbit(); + } finally { + [graphDom, positions] = kept; + } + } + + function home3d(tab) { + const id = `${tab}/3d`; + const pin = homePins().find((entry) => entry.kind === Panels.PANEL && entry.id === id); + if (pin && !Panels.firstOfGroup(homePins(), pin)) { + return emptyState("One 3D tile at a time", "Another 3D tile already runs live on Home; unpin it to bring this one to life."); + } + const host = homeView.hosts.get(id) || h("div", {class: "stage home-stage"}); + homeView.hosts.set(id, host); + window.setTimeout(() => host.isConnected && stage3d(tab, host), 0); + return host; + } + + function agentTile(key) { + const node = state.graph.nodes.find((entry) => entry.id === key); + if (!node && !Object.hasOwn(people(), key)) { + return null; + } + const tasks = node ? node.tasks : []; + const claims = node ? node.claims : []; + return h("div", {class: "home-agent"}, + h("div", {class: "who"}, face(key, true), person(nameOf(key)), presenceMark(key, true)), + h("p", {class: "muted"}, claims.length ? `Offices: ${claims.map((claim) => claim.office).join(", ")}` : "No office"), + tasks.length ? h("ul", {class: "mini"}, tasks.map((task) => h("li", {}, h("div", {class: "row"}, h("code", {}, task.task), status(task.status)), h("span", {}, dash(task.title))))) + : h("p", {class: "muted"}, "No open tasks.")); + } + + function homeTask(id) { + const row = state.tasks.find((entry) => entry.task === id); + return row ? h("ol", {class: "task-list"}, taskItem(row, etaOf().get(row.task))) : null; + } + + function homeTaskList() { + const etas = etaOf(); + return h("ol", {class: "task-list"}, Plan.sortRows(shownTasks(), taskView.sort, taskView.descending).map((row) => taskItem(row, etas.get(row.task)))); + } + + Panels.panel("stream", "Stream", homeStream); + Panels.panel("radio-log", "Radio log", homeRadio); + Panels.panel("agents/orbit", "Agents: Orbit", homeOrbit); + Panels.panel("agents/chord", "Agents: Chord", () => chord()); + Panels.panel("agents/swimlane", "Agents: Swimlane", () => swimlane()); + Panels.panel("agents/3d", "Agents: 3D", () => home3d("agents"), "3d"); + Panels.panel("agents/tree", "Agents: spawn tree", () => h("ul", {class: "spawn-tree root"}, spawnItem(spawnTree()))); + Panels.panel("agents/hierarchy", "Agents: hierarchy", () => chartTree()); + Panels.panel("artifacts/orbit", "Artifacts: Orbit", () => homeArt("orbit")); + Panels.panel("artifacts/chord", "Artifacts: Chord", () => homeArt("chord")); + Panels.panel("artifacts/swimlane", "Artifacts: Swimlane", () => homeArt("swimlane")); + Panels.panel("artifacts/3d", "Artifacts: 3D", () => homeTree(() => home3d("artifacts")), "3d"); + Panels.panel("tasks/list", "Tasks: list", homeTaskList); + Panels.panel("tasks/board", "Tasks: kanban", () => kanbanBoard(shownTasks())); + Panels.panel("tasks/rasci", "Tasks: RASCI", () => taskMatrix(shownTasks())); + Panels.panel("tasks/gantt", "Tasks: Gantt", () => ganttChart(shownTasks())); + Panels.panel("tasks/burn", "Tasks: burndown and burnup", () => burnChart(state.tasks, shownTasks())); + Panels.panel("tasks/3d", "Tasks: 3D", () => home3d("tasks"), "3d"); + Panels.item("task", (id) => `Task ${id}`, (size, id) => homeTask(id)); + Panels.item("message", "Message", (size, id) => homeMessage(id)); + Panels.item("artifact", (id) => `Artifact ${id.replace(/\u0000/g, " ")}`, (size, id) => homeArtifact(id)); + Panels.item("agent", (id) => `Agent ${labelOf(id)}`, (size, id) => agentTile(id)); + Panels.item("ancestry", (id) => `Ancestry ${id}`, (size, id) => homeAncestry(id)); + + function homeRefused(why) { + homeView.pins = homeStore.read(); + drawHome(); + homeView.mark(); + toast("Home not saved", [why], false); + } + + function homeSave(change) { + const done = homeStore.change(change); + homeView.pins = homeStore.read(); + drawHome(); + homeView.mark(); + return done.then((stored) => { + if (stored === false) { + homeRefused(homeStore.error() || "The view store refused the layout."); + } + return stored !== false; + }, (error) => { + homeRefused(String(error.message || error)); + return false; + }); + } + + function homeRefusal(refused, holder, title) { + if (refused === "full") { + toast("Home is full", [`At most ${Panels.MAX} pins: unpin one before you pin ${title}.`], false); + } else if (refused === "group") { + const other = Panels.lookup(holder.kind, holder.id); + toast("One 3D tile at a time", [`Home already holds ${other ? other.title : holder.id}: unpin it before you pin ${title}.`], false); + } + } + + function homePress(kind, id, title) { + homeView.touched = true; + if (Panels.has(homePins(), kind, id)) { + homeSave((pins) => Panels.remove(pins, kind, id)); + return; + } + const {refused, holder} = Panels.add(homePins(), kind, id); + if (refused) { + homeRefusal(refused, holder, title); + return; + } + homeSave((pins) => Panels.add(pins, kind, id).pins).then((stored) => { + const now = homeStore.read(); + if (stored && !Panels.has(now, kind, id)) { + const late = Panels.add(now, kind, id); + homeRefusal(late.refused, late.holder, title); + } + }); + } + + function homeUnpin(key) { + homeView.touched = true; + homeSave((pins) => pins.filter((pin) => Panels.keyOf(pin) !== key)); + } + + function homeSpan(tile, size) { + tile.style.setProperty("--w", String(size.w)); + tile.style.setProperty("--h", String(size.h)); + tile.dataset.w = String(size.w); + tile.dataset.h = String(size.h); + } + + function homeGrab(event, key, mode) { + if (event.button !== 0 || homeIndex(key) < 0) { + return; + } + event.preventDefault(); + const pin = homePins()[homeIndex(key)]; + const grid = homeView.dom.grid; + const look = getComputedStyle(grid); + const gap = parseFloat(look.columnGap) || 0; + const column = (grid.clientWidth - gap * (Panels.SPAN - 1)) / Panels.SPAN + gap; + const row = (parseFloat(look.gridAutoRows) || 1) + (parseFloat(look.rowGap) || 0); + homeView.drag = {mode, key, x: event.clientX, y: event.clientY, start: {w: pin.w, h: pin.h}, next: {w: pin.w, h: pin.h}, column, row, over: null}; + homeView.tiles.get(key).classList.add("dragging"); + } + + function homeDragMove(event) { + const drag = homeView.drag; + if (!drag) { + return; + } + const tile = homeView.tiles.get(drag.key); + if (drag.mode === "size") { + drag.next = Panels.stretch(drag.start, event.clientX - drag.x, event.clientY - drag.y, drag.column, drag.row); + homeSpan(tile, drag.next); + return; + } + const under = document.elementFromPoint(event.clientX, event.clientY); + const into = under ? under.closest(".home-tile") : null; + drag.over = into && into !== tile ? into.dataset.pin : null; + homeView.tiles.forEach((other) => other.classList.toggle("drop", other.dataset.pin === drag.over)); + } + + function homeDragEnd() { + const drag = homeView.drag; + if (!drag) { + return; + } + homeView.drag = null; + homeView.tiles.forEach((tile) => tile.classList.remove("drop", "dragging")); + const {key, next, over} = drag; + if (drag.mode === "size" && (next.w !== drag.start.w || next.h !== drag.start.h)) { + homeSave((pins) => Panels.resizeKey(pins, key, next.w, next.h)); + } else if (drag.mode === "move" && over) { + homeSave((pins) => Panels.placeKey(pins, key, over)); + } else { + drawHome(); + } + } + + function homeKeys(event, key) { + const steps = {ArrowLeft: -1, ArrowUp: -1, ArrowRight: 1, ArrowDown: 1}; + if (event.target !== event.currentTarget || !Object.hasOwn(steps, event.key) || event.altKey || event.ctrlKey || event.metaKey) { + return; + } + event.preventDefault(); + homeSave((pins) => Panels.moveKey(pins, key, steps[event.key])); + } + + function homeSizeKeys(event, key) { + const steps = {ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1]}; + if (!Object.hasOwn(steps, event.key)) { + return; + } + event.preventDefault(); + event.stopPropagation(); + const [dw, dh] = steps[event.key]; + homeSave((pins) => Panels.resizeBy(pins, key, dw, dh)); + } + + function homeGone(pin, key) { + return h("div", {class: "home-gone"}, h("strong", {class: "home-gone-word"}, "gone"), + h("p", {class: "muted"}, `This ${pin.kind} no longer exists: ${Panels.raw(pin.id).replace(/\u0000/g, " ")}`), + btn("Unpin", "btn small danger home-gone-unpin", () => homeUnpin(key))); + } + + function homeTile(key) { + const title = h("h3", {class: "home-title"}); + 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 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); + grip.addEventListener("pointerdown", (event) => homeGrab(event, key, "move")); + handle.addEventListener("pointerdown", (event) => homeGrab(event, key, "size")); + handle.addEventListener("keydown", (event) => homeSizeKeys(event, key)); + homeView.tiles.set(key, tile); + return tile; + } + + function homeContent(entry, pin) { + try { + return entry.render({w: pin.w, h: pin.h}); + } catch (error) { + return h("p", {class: "muted home-error"}, `Not drawable: ${error.message || error}`); + } + } + + function homeFill(tile, pin, index, count) { + const key = Panels.keyOf(pin); + const entry = Panels.lookup(pin.kind, pin.id); + const content = entry ? homeContent(entry, pin) : null; + const name = entry ? entry.title : `${pin.kind} ${pin.id}`; + tile.classList.toggle("gone", !content); + tile.dataset.kind = pin.kind; + tile.dataset.id = pin.id; + tile.setAttribute("aria-label", `${name}, ${pin.w} by ${pin.h}, tile ${index + 1} of ${count}`); + homeSpan(tile, pin); + tile.querySelector(".home-title").textContent = name; + const body = tile.querySelector(".home-body"); + const shown = content || homeGone(pin, key); + if (body.childNodes.length !== 1 || body.firstChild !== shown) { + body.replaceChildren(shown); + } + } + + function drawHome() { + const dom = homeView.dom; + if (!dom || !dom.grid.isConnected) { + homeView.dom = null; + return; + } + if (homeView.drag) { + return; + } + const pins = homePins(); + const keys = new Set(pins.map(Panels.keyOf)); + for (const [key, tile] of homeView.tiles) { + if (!keys.has(key)) { + tile.remove(); + homeView.tiles.delete(key); + } + } + const focused = document.activeElement; + pins.forEach((pin, index) => { + const key = Panels.keyOf(pin); + const tile = homeView.tiles.get(key) || homeTile(key); + homeFill(tile, pin, index, pins.length); + if (dom.grid.children[index] !== tile) { + dom.grid.insertBefore(tile, dom.grid.children[index] || null); + } + }); + if (focused instanceof HTMLElement && focused.isConnected && document.activeElement !== focused) { + focused.focus(); + } + dom.empty.hidden = pins.length > 0; + } + + function homeScreen() { + const grid = h("div", {class: "home-grid", role: "list", "aria-label": "Pinned panels and items"}); + const empty = emptyState("Nothing pinned yet", "Press the star on any panel or item to pin it here; pins, sizes and order are kept for every browser."); + homeView.dom = {grid, empty}; + homeView.tiles = new Map(); + return h("div", {class: "home"}, empty, grid); + } + + function homeBoot() { + homeView.pins = homeStore.read(); + const opened = homePins().length; + homeStore.watch((pins) => { + homeView.pins = pins; + if (!homeView.touched && !opened && pins.length && ui.screen === "stream" && !window.location.hash.replace(/^#/, "")) { + apply(); + return; + } + drawHome(); + homeView.mark(); + }); + homeView.mark = Panels.decorate(document.body, {pinned: (kind, id) => Panels.has(homePins(), kind, id), press: homePress, marks: HOME_MARKS}); + window.addEventListener("pointermove", homeDragMove); + window.addEventListener("pointerup", homeDragEnd); + window.addEventListener("pointercancel", homeDragEnd); + } diff --git a/orchestrator/templates/page-kanban.js b/orchestrator/templates/page-kanban.js index 6445ff4..8f90a8e 100644 --- a/orchestrator/templates/page-kanban.js +++ b/orchestrator/templates/page-kanban.js @@ -86,7 +86,7 @@ const own = (event) => !event.target.closest("button, summary, details, select, .kanban-handle"); const after = () => kanban.dragging && kanban.dragging.mode === "after" && kanban.dragging.task !== row.task; return h("li", { - class: ["task-card", "kanban-card", row.pending ? "pending" : ""].filter(Boolean).join(" "), "data-task": row.task, "data-lane": lane, "data-column": column, tabindex: 0, + class: ["task-card", "kanban-card", row.pending ? "pending" : ""].filter(Boolean).join(" "), "data-task": row.task, "data-item": `task:${row.task}`, "data-lane": lane, "data-column": column, tabindex: 0, "data-pending": row.pending ? row.pending.map((argv) => argv.join(" ")).join("\n") : null, draggable: row.movable ? "true" : null, on: { click: (event) => own(event) && open(), @@ -112,7 +112,7 @@ }, }, }, - h("div", {class: "head-row"}, h("code", {class: "task-id"}, row.task), cardLabels(row), h("span", {class: "spacer"}), + h("div", {class: "head-row", "data-star-slot": ""}, h("code", {class: "task-id"}, row.task), cardLabels(row), h("span", {class: "spacer"}), row.pending ? h("span", {class: "kanban-pending", role: "img", ...named("Staged", row.pending.map(shownArgv).join("\n"))}, icon("bi-pencil")) : null, openJobs(row.task).length ? h("span", {class: "kanban-wait", role: "img", ...named("At the runner", `${row.task}: a signed change waits for the runner`)}, icon("bi-hourglass-split")) : null, row.editable ? h("span", {class: "kanban-handle", role: "img", draggable: "true", ...named("Follows", `Drag onto the card that waits for ${row.task}`), on: {dragstart: dragFrom(row.task, "after"), dragend: () => { diff --git a/orchestrator/templates/page-screens.js b/orchestrator/templates/page-screens.js index 04f6550..f22d583 100644 --- a/orchestrator/templates/page-screens.js +++ b/orchestrator/templates/page-screens.js @@ -25,7 +25,7 @@ } function apply() { - const route = Nav.route(window.location.hash); + const route = Nav.route(window.location.hash, homePins().length); if (route.redirect) { window.history.replaceState(null, "", route.redirect); } @@ -55,7 +55,7 @@ } function screenOf() { - return {stream: streamScreen, inbox: tasksScreen, rules: rulesScreen, agents: agentsScreen, artifacts: artifactsScreen, tasks: tasksScreen, resources: resourcesScreen}[ui.screen](); + return {home: homeScreen, stream: streamScreen, inbox: tasksScreen, rules: rulesScreen, agents: agentsScreen, artifacts: artifactsScreen, tasks: tasksScreen, resources: resourcesScreen}[ui.screen](); } function render(force) { @@ -82,6 +82,7 @@ } stage(); drawSpawn(); + drawHome(); drawHierarchy(force); drawToolbar(); drawInbox(); diff --git a/orchestrator/templates/page-spawn.js b/orchestrator/templates/page-spawn.js index 7ccb75b..9c0748b 100644 --- a/orchestrator/templates/page-spawn.js +++ b/orchestrator/templates/page-spawn.js @@ -98,7 +98,7 @@ } function spawnScreen() { - const list = h("div", {class: "card spawn"}); + const list = h("div", {class: "card spawn", "data-panel": "agents/tree"}); spawn.dom = {list}; window.setTimeout(() => { drawSpawn(); @@ -116,7 +116,7 @@ const all = spawnFlat(root).map(({entry}) => entry).filter((entry) => entry.running !== null); const running = all.filter((entry) => entry.running).length; spawn.dom.list.replaceChildren( - h("div", {class: "inbox-head"}, h("h2", {class: "group-title"}, "Spawn tree", counter(all.length)), h("span", {class: "muted"}, `${running} running ยท ${all.length - running} finished ยท Operator โ†’ Chair โ†’ Sessions โ†’ Subagents`)), + h("div", {class: "inbox-head", "data-star-slot": ""}, h("h2", {class: "group-title"}, "Spawn tree", counter(all.length)), h("span", {class: "muted"}, `${running} running ยท ${all.length - running} finished ยท Operator โ†’ Chair โ†’ Sessions โ†’ Subagents`)), agentAncestry(root), h("ul", {class: "spawn-tree root"}, spawnItem(root))); } diff --git a/orchestrator/templates/page-stream.js b/orchestrator/templates/page-stream.js index 73f40a4..780c2a2 100644 --- a/orchestrator/templates/page-stream.js +++ b/orchestrator/templates/page-stream.js @@ -134,10 +134,10 @@ const renamed = entry.now && entry.now !== entry.agent ? h("span", {title: `now: ${entry.now}`}, person(entry.agent)) : person(entry.agent); const who = entry.agent ? [face(entry.agent, false), renamed] : entry.session ? h("strong", {title: entry.session}, entry.session.slice(0, 8)) : null; const headline = entry.kind === "transcript" || entry.kind === "ask" || entry.kind === "operator" ? null : h("span", {class: "headline"}, entry.title); - return h("li", {class: `entry k-${entry.kind}${entry.waiting ? " waiting" : ""}${alarm ? " alarm" : ""}`, "data-ref": item ? keyOf(item) : null, "data-to": item && item.to ? item.to : null}, + return h("li", {class: `entry k-${entry.kind}${entry.waiting ? " waiting" : ""}${alarm ? " alarm" : ""}`, "data-ref": item ? keyOf(item) : null, "data-item": `message:${entry.ts}/${entry.id}`, "data-to": item && item.to ? item.to : null}, h("div", {class: "msg-meta"}, when(entry.ts), kindPill(entry), extras(entry)), h("div", {}, - h("div", {class: "route"}, who, entry.sub ? h("button", {type: "button", class: "linkish muted", on: {click: () => focusSub(entry.session, entry.sub)}}, `โ€บ Subagent ${entry.sub.slice(0, 12)}`) : null, entry.kind === "ask" ? h("strong", {}, entry.title) : null, headline), + h("div", {class: "route", "data-star-slot": ""}, who, entry.sub ? h("button", {type: "button", class: "linkish muted", on: {click: () => focusSub(entry.session, entry.sub)}}, `โ€บ Subagent ${entry.sub.slice(0, 12)}`) : null, entry.kind === "ask" ? h("strong", {}, entry.title) : null, headline), body(entry), item ? diffBlocks(item) : null, item ? feedbackList(keyOf(item)) : null, @@ -175,7 +175,7 @@ const parts = h("div", {class: "chips", role: "group", "aria-label": "Transcript parts"}); const saved = h("div", {class: "chips", role: "group", "aria-label": "Saved views"}); const focus = h("div", {class: "chips"}); - const list = h("div", {}); + const list = h("div", {"data-panel": "stream"}); const more = h("details", {class: "menu"}, h("summary", named("Filter", "Filter: kinds, transcript parts, saved views, custom time range"), icon("bi-funnel"), caret()), h("div", {class: "menu-box end"}, h("h3", {}, "Kinds"), kinds, h("h3", {}, "Transcript parts"), parts, h("h3", {}, "Saved views"), saved, h("h3", {}, "Custom time range"), customRange())); stream.dom = {search, count, categories, kinds, parts, saved, focus, list}; diff --git a/orchestrator/templates/page-tasks.js b/orchestrator/templates/page-tasks.js index 9f85940..8c08d69 100644 --- a/orchestrator/templates/page-tasks.js +++ b/orchestrator/templates/page-tasks.js @@ -69,8 +69,8 @@ function taskItem(row, eta) { const classes = ["task-row", row.open_work.length ? "open-work" : "", row.ended ? "ended" : ""].filter(Boolean).join(" "); const pick = row.editable ? h("input", {type: "checkbox", class: "task-pick", "aria-label": `Select ${row.task}`, title: `Select ${row.task} for a bulk business value`, checked: taskView.picked.has(row.task), on: {change: (event) => pickTask(row.task, event.target.checked)}}) : null; - return h("li", {class: classes, "data-task": row.task, "data-kind": row.kind, "data-status": row.status}, - h("div", {class: "head-row"}, pick, h("code", {class: "task-id"}, row.task), taskBadges(row, true), h("span", {class: "spacer"}), etaMark(eta), + return h("li", {class: classes, "data-task": row.task, "data-item": `task:${row.task}`, "data-kind": row.kind, "data-status": row.status}, + h("div", {class: "head-row", "data-star-slot": ""}, pick, h("code", {class: "task-id"}, row.task), taskBadges(row, true), h("span", {class: "spacer"}), etaMark(eta), row.editable ? iconBtn("bi-sort-numeric-down", "Priority", "btn small soft", () => taskSheet(row.task), `Priority and WSJF of ${row.task}: pin or estimate, signed with the passkey`) : null), opener(row), row.objective !== "-" ? h("div", {class: "muted"}, `Objective: ${row.objective}`) : null, @@ -165,7 +165,7 @@ drawTasks(); }}}); const stage = !inbox && view === "3d" ? h("div", {class: "stage"}) : null; - const body = inbox ? inboxScreen() : stage ? h("div", {class: "card stage-card tasks-body"}, layoutTools("tasks"), stage) : h("div", {class: "tasks-body"}); + const body = inbox ? inboxScreen() : stage ? h("div", {class: "card stage-card tasks-body", "data-panel": "tasks/3d"}, layoutTools("tasks"), stage) : h("div", {class: "tasks-body", "data-panel": `tasks/${view}`}); taskView.dom = {chips, count, body, inbox, view, stage}; taskView.sig = ""; taskView.plan = null; diff --git a/orchestrator/templates/panels.js b/orchestrator/templates/panels.js new file mode 100644 index 0000000..4711c92 --- /dev/null +++ b/orchestrator/templates/panels.js @@ -0,0 +1,316 @@ +const Panels = (() => { + "use strict"; + const MAX = 64; + const SPAN = 12; + const ID_MAX = 200; + const ID = /^[A-Za-z0-9:_./-]{1,200}$/; + const KIND = /^[A-Za-z0-9:_./-]{1,32}$/; + const ESCAPE = /[^A-Za-z0-9./-]/gu; + const ESCAPED = /_([0-9a-f]+)_/g; + const PANEL = "panel"; + const SIZES = {panel: [6, 4], item: [4, 3]}; + const HOSTS = "[data-panel], [data-item]"; + const XHTML = "http://www.w3.org/1999/xhtml"; + const SVG = "http://www.w3.org/2000/svg"; + const panels = new Map(); + const items = new Map(); + const placed = new WeakMap(); + + const keyOf = (pin) => `${pin.kind}:${pin.id}`; + const span = (value) => Number.isInteger(value) && value >= 1 && value <= SPAN; + const clamp = (value) => Math.min(Math.max(Math.round(value), 1), SPAN); + + /** + * @param raw - an item's own id, any text. + * @returns the pin id in the view store grammar of ViewStore.id: each character outside A-Z, a-z, 0-9 and ./- as + * __; null when that runs past 200 characters, as such an id would lose its way back to the item. + */ + function token(raw) { + const text = String(raw).replace(ESCAPE, (char) => `_${char.codePointAt(0).toString(16)}_`); + return text.length <= ID_MAX ? text : null; + } + + const raw = (id) => id.replace(ESCAPED, (_, hex) => String.fromCodePoint(parseInt(hex, 16))); + + function valid(pin) { + return Boolean(pin) && typeof pin === "object" && !Array.isArray(pin) && Object.keys(pin).sort().join(",") === "h,id,kind,w" + && typeof pin.kind === "string" && KIND.test(pin.kind) && typeof pin.id === "string" && ID.test(pin.id) && span(pin.w) && span(pin.h); + } + + function validLayout(pins) { + return Array.isArray(pins) && pins.length <= MAX && pins.every(valid) && new Set(pins.map(keyOf)).size === pins.length; + } + + function clean(pins) { + if (!Array.isArray(pins)) { + return []; + } + const seen = new Set(); + return pins.filter((pin) => valid(pin) && !seen.has(keyOf(pin)) && Boolean(seen.add(keyOf(pin)))).slice(0, MAX).map(({kind, id, w, h}) => ({kind, id, w, h})); + } + + /** + * @param id - the panel id, the value of the source element's data-panel. + * @param title - the tile title. + * @param render - (size) => Node, size being {w, h} in grid cells. + * @param group - optional name of a group of which Home holds one pin at most, such as the 3D views. + */ + function panel(id, title, render, group) { + panels.set(id, {title, render, group: group || ""}); + } + + /** + * @param kind - the item kind, the part of data-item before the first colon. + * @param title - the tile title, or (id) => title. + * @param render - (size, id) => Node, or null once the item no longer exists. + */ + function item(kind, title, render) { + items.set(kind, {title, render, group: ""}); + } + + function lookup(kind, id) { + const entry = kind === PANEL ? panels.get(id) : items.get(kind); + if (!entry) { + return null; + } + const plain = kind === PANEL ? id : raw(id); + return {kind, id, group: entry.group, title: typeof entry.title === "function" ? entry.title(plain) : entry.title, render: (size) => entry.render(size, plain)}; + } + + function targetOf(element) { + if (element.hasAttribute("data-panel")) { + return {kind: PANEL, id: element.getAttribute("data-panel")}; + } + const value = element.getAttribute("data-item") || ""; + const cut = value.indexOf(":"); + return cut > 0 ? {kind: value.slice(0, cut), id: token(value.slice(cut + 1))} : null; + } + + const has = (pins, kind, id) => pins.some((pin) => pin.kind === kind && pin.id === id); + const groupOf = (pin) => (lookup(pin.kind, pin.id) || {group: ""}).group; + + /** + * @returns {pins, refused, holder}: pins unchanged when the pin is already there or refused; refused is "" when the + * pin is there, "full" at 64 pins and "group" when holder, a pin of the same single-instance group, is on Home. + */ + function add(pins, kind, id) { + if (has(pins, kind, id)) { + return {pins, refused: "", holder: null}; + } + if (pins.length >= MAX) { + return {pins, refused: "full", holder: null}; + } + const group = groupOf({kind, id}); + const holder = group ? pins.find((pin) => groupOf(pin) === group) || null : null; + if (holder) { + return {pins, refused: "group", holder}; + } + const [w, h] = kind === PANEL ? SIZES.panel : SIZES.item; + return {pins: [...pins, {kind, id, w, h}], refused: "", holder: null}; + } + + const firstOfGroup = (pins, pin) => !groupOf(pin) || pins.find((other) => groupOf(other) === groupOf(pin)) === pin; + + const remove = (pins, kind, id) => pins.filter((pin) => !(pin.kind === kind && pin.id === id)); + const indexOf = (pins, key) => pins.findIndex((pin) => keyOf(pin) === key); + + function place(pins, from, to) { + if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 || from >= pins.length || to < 0 || to >= pins.length || from === to) { + return pins; + } + const next = [...pins]; + const [moved] = next.splice(from, 1); + next.splice(to, 0, moved); + return next; + } + + const move = (pins, index, step) => (index < 0 ? pins : place(pins, index, Math.min(Math.max(index + step, 0), pins.length - 1))); + const resize = (pins, index, w, h) => pins.map((pin, at) => (at === index ? {...pin, w: clamp(w), h: clamp(h)} : pin)); + const placeKey = (pins, from, to) => place(pins, indexOf(pins, from), indexOf(pins, to)); + const moveKey = (pins, key, step) => move(pins, indexOf(pins, key), step); + const resizeKey = (pins, key, w, h) => resize(pins, indexOf(pins, key), w, h); + + function resizeBy(pins, key, dw, dh) { + const pin = pins[indexOf(pins, key)]; + return pin ? resize(pins, indexOf(pins, key), pin.w + dw, pin.h + dh) : pins; + } + + /** + * @param start - the tile's {w, h} when the gesture began. + * @param dx - the pointer's horizontal travel in px. + * @param dy - the pointer's vertical travel in px. + * @param column - one column plus its gap in px. + * @param row - one row plus its gap in px. + * @returns the new {w, h}, each rounded to whole cells and held in 1 to 12. + */ + function stretch(start, dx, dy, column, row) { + return {w: clamp(start.w + dx / column), h: clamp(start.h + dy / row)}; + } + + function memory() { + const values = new Map(); + const listeners = new Map(); + return { + get: (path) => values.get(path), + update: (path, change) => { + const value = change(values.get(path)); + values.set(path, value); + (listeners.get(path) || []).forEach((listen) => listen(value)); + return Promise.resolve(true); + }, + on: (path, listen) => listeners.set(path, [...(listeners.get(path) || []), listen]), + }; + } + + /** + * @param backend - an object with get(path), update(path, change) and on(path, cb), as ViewStore offers; get and + * on may throw for a path the store does not know, update re-runs change on the stored list after a conflict. + * @param path - the view store path of the pins. + * @returns {read, change, watch, error}: read() gives the cleaned pins, change(fn) hands fn, a pure function from + * the stored pins to the new ones, to backend.update and gives a promise of its true or false, refused before the + * store when fn makes an invalid layout of the shown pins; watch(cb) calls cb with the cleaned pins on every change + * and error() gives the store's reason for its last refusal. + */ + function store(backend, path) { + const read = () => { + try { + return clean(backend.get(path)); + } catch { + return []; + } + }; + return { + read, + change: (fn) => { + if (!validLayout(fn(read()))) { + return Promise.reject(new Error("invalid layout")); + } + return new Promise((resolve) => resolve(backend.update(path, (stored) => { + const before = clean(stored); + const after = fn(before); + return validLayout(after) ? after : before; + }))); + }, + watch: (listen) => { + try { + backend.on(path, (value) => listen(clean(value))); + return true; + } catch { + return false; + } + }, + error: () => (typeof backend.error === "function" ? backend.error() : ""), + }; + } + + function glyph(name) { + const svg = document.createElementNS(SVG, "svg"); + svg.setAttribute("class", "bi"); + svg.setAttribute("aria-hidden", "true"); + svg.setAttribute("focusable", "false"); + const use = document.createElementNS(SVG, "use"); + use.setAttribute("href", `#${name}`); + svg.append(use); + return svg; + } + + function paint(button, on, title) { + const label = on ? "Unpin from Home" : "Pin to Home"; + if (button.getAttribute("aria-pressed") !== String(on)) { + button.setAttribute("aria-pressed", String(on)); + button.replaceChildren(glyph(on ? "bi-star-fill" : "bi-star")); + } + if (button.getAttribute("aria-label") !== label) { + button.setAttribute("aria-label", label); + } + const hint = `${label}: ${title}`; + if (button.getAttribute("title") !== hint) { + button.setAttribute("title", hint); + } + } + + function slotOf(element) { + const own = [...element.querySelectorAll("[data-star-slot]")].find((slot) => slot.closest(HOSTS) === element); + if (own) { + return own; + } + const found = [...element.children].find((child) => child.classList.contains("star-row")); + if (found) { + return found; + } + const row = document.createElement("div"); + row.setAttribute("class", "star-row"); + element.prepend(row); + return row; + } + + function button(element, options, enabled) { + const made = document.createElement("button"); + made.setAttribute("type", "button"); + made.setAttribute("class", "star btn small ghost icon-only"); + if (!enabled) { + made.setAttribute("disabled", ""); + made.setAttribute("aria-label", "Pin to Home"); + made.setAttribute("title", "Pin to Home: not possible, the id runs past 200 characters"); + made.append(glyph("bi-star")); + return made; + } + made.addEventListener("pointerdown", (event) => event.stopPropagation()); + made.addEventListener("click", (event) => { + event.preventDefault(); + event.stopPropagation(); + const now = targetOf(element); + const entry = now && now.id ? lookup(now.kind, now.id) : null; + if (entry) { + options.press(now.kind, now.id, entry.title); + } + }); + return made; + } + + function star(element, options) { + if (element.namespaceURI !== XHTML) { + return; + } + const target = targetOf(element); + const entry = target && target.id ? lookup(target.kind, target.id) : null; + if (!target || (target.id && !entry)) { + return; + } + let made = placed.get(element); + if (!made || !element.contains(made)) { + made = button(element, options, Boolean(entry)); + placed.set(element, made); + slotOf(element).append(made); + } + if (entry) { + paint(made, options.pinned(target.kind, target.id), entry.title); + } + } + + /** + * @param root - the element whose subtree gets a star on every element with data-panel or data-item; the star goes + * into the element's own data-star-slot descendant, else into a star row the element gets as its first child. + * @param options - {pinned(kind, id) => boolean, press(kind, id, title), marks: [[selector, panel id], ...]}, marks + * naming source elements whose page carries no data-panel of its own. + * @returns mark(): tags the marks, stars what lacks one and repaints the pressed state of all. + */ + function decorate(root, options) { + const marks = options.marks || []; + const mark = () => { + marks.forEach(([selector, id]) => root.querySelectorAll(selector).forEach((element) => element.hasAttribute("data-panel") || element.setAttribute("data-panel", id))); + root.querySelectorAll(HOSTS).forEach((element) => star(element, options)); + }; + mark(); + new MutationObserver(mark).observe(root, {childList: true, subtree: true}); + return mark; + } + + return { + MAX, SPAN, PANEL, ID, HOSTS, keyOf, token, raw, valid, validLayout, clean, panel, item, lookup, targetOf, has, add, remove, firstOfGroup, + place, move, resize, placeKey, moveKey, resizeKey, resizeBy, stretch, memory, store, decorate, + }; +})(); +if (typeof module === "object" && module.exports) { + module.exports = Panels; +} diff --git a/orchestrator/templates/style-home.css b/orchestrator/templates/style-home.css new file mode 100644 index 0000000..e476f0e --- /dev/null +++ b/orchestrator/templates/style-home.css @@ -0,0 +1,23 @@ +.star-row { display: flex; flex: none; grid-column: 1 / -1; justify-content: flex-end; min-width: 0; } +.star { flex: none; margin-inline-start: auto; color: var(--muted); } +.star[aria-pressed="true"] { color: var(--warn); } +.home { display: grid; gap: var(--sp-4); } +.home .empty[hidden] { display: none; } +.home-grid { display: grid; grid-template-columns: repeat(12, minmax(0, 1fr)); grid-auto-rows: 72px; gap: var(--sp-3); } +.home-tile { position: relative; display: flex; flex-direction: column; grid-column: span var(--w, 6); grid-row: span var(--h, 4); min-width: 0; min-height: 0; overflow: hidden; background: var(--glass-card); border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow); } +.home-tile.gone { border-style: dashed; } +.home-tile.dragging { opacity: .6; } +.home-tile.drop { outline: 2px dashed var(--accent); outline-offset: 2px; } +.home-head { display: flex; flex: none; align-items: center; gap: 6px; padding: 4px 6px 4px 4px; border-bottom: 1px solid var(--line); } +.home-title { flex: 1; min-width: 0; margin: 0; overflow: hidden; font-size: var(--fs-sm); text-overflow: ellipsis; white-space: nowrap; } +.home-body { flex: 1; min-height: 0; padding: var(--sp-2); overflow: auto; } +.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-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; } +.home-agent { display: grid; gap: var(--sp-2); } +@media (max-width: 640px) { + .home-tile { grid-column: 1 / -1; } +} diff --git a/tests/e2e/test_home_dashboard_e2e.py b/tests/e2e/test_home_dashboard_e2e.py new file mode 100644 index 0000000..aa3187b --- /dev/null +++ b/tests/e2e/test_home_dashboard_e2e.py @@ -0,0 +1,390 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import time +import unittest +from pathlib import Path +from unittest import mock + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import test_orchestrator_e2e as base +from hub_case import HubCase +from hub_support import HUB, iso + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-008-shots")) +REAL_STORE = (HUB / "templates" / "view-store.js").exists() +CUE = "e2e-home-change" +SCREENS = [ + "stream", "agents/orbit", "agents/chord", "agents/swimlane", "agents/3d", "agents/tree", "agents/hierarchy", + "artifacts/orbit", "artifacts/chord", "artifacts/swimlane", "artifacts/tree", "artifacts/3d", + "tasks/list", "tasks/board", "tasks/rasci", "tasks/gantt", "tasks/burn", "tasks/3d", +] +STUB = """() => { + const KEY = "e2e-view-store"; + const read = () => JSON.parse(sessionStorage.getItem(KEY) || "{}"); + const listeners = {}; + window.ViewStore = { + get: (path) => read()[path], + update: (path, change) => { + const all = read(); + all[path] = change(all[path]); + sessionStorage.setItem(KEY, JSON.stringify(all)); + (listeners[path] || []).forEach((listen) => listen(all[path])); + return Promise.resolve(true); + }, + set: (path) => { + throw new Error(`${path} holds a list: use update()`); + }, + on: (path, listen) => { + listeners[path] = [...(listeners[path] || []), listen]; + }, + }; +}""" +HOME = """ + const go = async (hash) => { + location.hash = hash; + await screenShown(8000); + await sleep(500); + }; + const ownStar = (owner) => [...owner.querySelectorAll(".star")].find((node) => node.closest("[data-panel], [data-item]") === owner) || null; + const starOf = (selector) => { + const owner = document.querySelector(selector); + return owner ? ownStar(owner) : null; + }; + const press = async (selector) => { + const button = await until(() => starOf(selector), 8000); + if (!button) { + return null; + } + button.click(); + await sleep(200); + return button.getAttribute("aria-pressed"); + }; + const tiles = () => all("#main .home-tile").map((tile) => tile.dataset.pin); + const tile = (key) => document.querySelector(`#main .home-tile[data-pin="${key}"]`); + const centre = (node) => { + const box = node.getBoundingClientRect(); + return {clientX: box.left + box.width / 2, clientY: box.top + box.height / 2}; + }; + const pointer = (node, type, at) => node.dispatchEvent(new PointerEvent(type, {bubbles: true, cancelable: true, pointerId: 1, button: 0, isPrimary: true, ...at})); + const dragBy = async (handle, dx, dy) => { + handle.scrollIntoView({block: "center"}); + const from = centre(handle); + pointer(handle, "pointerdown", from); + pointer(document, "pointermove", {clientX: from.clientX + dx, clientY: from.clientY + dy}); + pointer(document, "pointerup", {clientX: from.clientX + dx, clientY: from.clientY + dy}); + await sleep(300); + }; + const sizeOf = (key) => { + const found = tile(key); + return found ? [Number(found.dataset.w), Number(found.dataset.h)] : null; + }; + const grid = () => document.querySelector("#main .home-grid"); + const cell = () => { + const look = getComputedStyle(grid()); + const gap = parseFloat(look.columnGap); + return {column: (grid().clientWidth - gap * 11) / 12 + gap, row: parseFloat(look.gridAutoRows) + parseFloat(look.rowGap)}; + }; + const stored = () => (ViewStore.get("home.pins") || []).map((pin) => `${pin.kind}:${pin.id}`); +""" +CLEAR = """(async () => { + sessionStorage.clear(); + await ViewStore.update("home.pins", () => []); + sessionStorage.clear(); + return true; +})()""" +START_EMPTY = """(async () => {@HELPERS@ + await screenShown(8000); + return {hash: location.hash, screen: document.getElementById("main").getAttribute("aria-labelledby"), first: name(document.querySelector("#tabs > .tab-group > button"))}; +})()""" +STARS = """(async () => {@HELPERS@@HOME@ + const seen = []; + const missing = []; + const covered = []; + const CONTROLS = 'button, a[href], input, select, textarea, summary, [role="button"], [role="tab"], [tabindex]:not([tabindex="-1"])'; + const shown = (node) => node.getClientRects().length > 0 && getComputedStyle(node).visibility !== "hidden"; + 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 count = (where) => { + const owners = all("[data-panel], [data-item]").filter((node) => node.namespaceURI === "http://www.w3.org/1999/xhtml"); + seen.push([where, owners.length]); + missing.push(...owners.filter((node) => !ownStar(node)).map((node) => `${where}: ${node.outerHTML.slice(0, 120)}`)); + const controls = all(CONTROLS).filter(shown); + for (const star of all(".star").filter(shown)) { + const box = star.getBoundingClientRect(); + for (const other of controls) { + if (other !== star && !other.contains(star) && !star.contains(other) && overlap(box, other.getBoundingClientRect()) > 1) { + covered.push(`${where}: ${star.title} over ${other.outerHTML.slice(0, 100)}`); + } + } + } + }; + for (const hash of @SCREENS@) { + await go(hash); + await sleep(hash.endsWith("3d") || hash.startsWith("artifacts") ? 1500 : 300); + count(hash); + } + await go("agents/orbit"); + const agent = document.querySelector('#main svg .node.k-session[data-pick]'); + if (agent) { + agent.dispatchEvent(new MouseEvent("click", {bubbles: true})); + await until(() => document.querySelector('#popup[open] [data-item^="agent:"]'), 5000); + count("agent card"); + document.getElementById("popup").close(); + } + document.getElementById("radio-open").click(); + await until(() => document.querySelector('[data-panel="radio-log"]'), 5000); + count("radio spot"); + document.getElementById("radio-open").click(); + return {seen, missing, covered, total: seen.reduce((sum, [, size]) => sum + size, 0)}; +})()""" +PIN = """(async () => {@HELPERS@@HOME@ + await go("tasks/gantt"); + const gantt = await press('#main [data-panel="tasks/gantt"]'); + await go("tasks/list"); + const feature = await press('#main li.task-row[data-task="work/feature"]'); + const docs = await press('#main li.task-row[data-task="work/docs"]'); + await go("stream"); + const streamed = await press('#main [data-panel="stream"]'); + await go("home"); + const pinned = tiles(); + const chart = Boolean(tile("panel:tasks/gantt") && tile("panel:tasks/gantt").querySelector("svg.chart.gantt")); + await go("tasks/gantt"); + const off = await press('#main [data-panel="tasks/gantt"]'); + await go("home"); + const unpinned = tiles(); + await go("tasks/gantt"); + const again = await press('#main [data-panel="tasks/gantt"]'); + await go("home"); + return {gantt, feature, docs, streamed, pinned, chart, off, unpinned, again, final: tiles(), stored: stored()}; +})()""" +RESIZE = """(async () => {@HELPERS@@HOME@ + await go("home"); + const key = "panel:tasks/gantt"; + const handle = () => tile(key).querySelector(".home-resize"); + const before = sizeOf(key); + const {column, row} = cell(); + await dragBy(handle(), column * 3, row * 2); + const grown = sizeOf(key); + await dragBy(handle(), column * 40, row * 40); + const most = sizeOf(key); + const wide = [Math.round(tile(key).getBoundingClientRect().width), Math.round(grid().getBoundingClientRect().width)]; + await dragBy(handle(), -column * 40, -row * 40); + const least = sizeOf(key); + handle().focus(); + for (const key of ["ArrowRight", "ArrowRight", "ArrowDown"]) { + document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {key, bubbles: true, cancelable: true})); + await sleep(100); + } + const keyed = sizeOf(key); + await dragBy(handle(), column * 5, row * 3); + const span = getComputedStyle(tile(key)).gridColumnEnd; + return {before, grown, most, wide, least, keyed, final: sizeOf(key), span, stored: (ViewStore.get("home.pins") || []).find((pin) => pin.id === "tasks/gantt")}; +})()""" +REORDER = """(async () => {@HELPERS@@HOME@ + await go("home"); + const before = tiles(); + const grip = tile(before[0]).querySelector(".home-grip"); + grip.scrollIntoView({block: "center"}); + const from = centre(grip); + const target = tile(before[2]); + target.scrollIntoView({block: "center"}); + const to = centre(target); + pointer(grip, "pointerdown", centre(grip)); + pointer(document, "pointermove", to); + pointer(document, "pointerup", to); + await sleep(300); + const dragged = tiles(); + const moving = tile(dragged[2]); + moving.focus(); + moving.dispatchEvent(new KeyboardEvent("keydown", {key: "ArrowLeft", bubbles: true, cancelable: true})); + await sleep(200); + const keyed = tiles(); + const focused = document.activeElement === tile(keyed[1]); + document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {key: "ArrowDown", bubbles: true, cancelable: true})); + await sleep(200); + return {from: Boolean(from), before, dragged, keyed, focused, down: tiles(), stored: stored()}; +})()""" +RELOADED = """(async () => {@HELPERS@@HOME@ + await screenShown(8000); + await sleep(500); + const narrow = all("#main .home-tile").map((node) => Math.round(node.getBoundingClientRect().width)); + return {hash: location.hash, screen: document.getElementById("main").getAttribute("aria-labelledby"), tiles: tiles(), widths: [...new Set(narrow)], grid: Math.round(grid().getBoundingClientRect().width), errors: all("#main .home-error").map(text)}; +})()""" +CHANGE = """(async () => {@HELPERS@@HOME@ + await go("home"); + const lanes = () => all('#main .home-tile[data-pin="panel:tasks/gantt"] text.lane-label').map((node) => node.dataset.task); + const before = lanes(); + await fetch("/api/tts", {method: "POST", headers: {"X-Kvb-Orchestrator": "1", "Content-Type": "application/json"}, body: JSON.stringify({text: "@CUE@", voice: ""}), cache: "no-store"}); + const grown = await until(() => lanes().includes("work/new") && tile("task:work/docs").classList.contains("gone"), 25000); + const gone = tile("task:work/docs"); + const result = { + before, after: lanes(), grown: Boolean(grown), goneWord: gone ? text(gone.querySelector(".home-gone-word")) : null, + unpin: gone ? name(gone.querySelector(".home-gone .home-gone-unpin")) : null, + }; + await go("tasks/gantt"); + result.source = all('#main [data-panel="tasks/gantt"] text.lane-label').map((node) => node.dataset.task); + await go("home"); + return result; +})()""" +GONE_UNPIN = """(async () => {@HELPERS@@HOME@ + await go("home"); + const button = tile("task:work/docs").querySelector(".home-gone-unpin"); + button.click(); + await sleep(300); + return {tiles: tiles(), stored: stored()}; +})()""" +FULL = """(async () => {@HELPERS@@HOME@ + await ViewStore.update("home.pins", () => Array.from({length: 64}, (_, index) => ({kind: "task", id: `work/seed-${index}`, w: 2, h: 1}))); + await go("tasks/gantt"); + const before = all("#toasts .toast").length; + const pressed = await press('#main [data-panel="tasks/gantt"]'); + const toast = await until(() => all("#toasts .toast").slice(before).map(text).find((words) => words.startsWith("Home is full")), 5000); + return {pressed, toast, count: (ViewStore.get("home.pins") || []).length}; +})()""" +START_PINNED = """(async () => {@HELPERS@ + await screenShown(8000); + await sleep(300); + return {hash: location.hash, screen: document.getElementById("main").getAttribute("aria-labelledby")}; +})()""" + + +def probe(template: str) -> str: + return template.replace("@HELPERS@", base.HELPERS).replace("@HOME@", HOME).replace("@SCREENS@", json.dumps(SCREENS)).replace("@CUE@", CUE) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestHomeDashboard(HubCase): + setUp = base.TestOrchestratorE2E.setUp + subagents = base.TestOrchestratorE2E.subagents + drive = base.TestOrchestratorE2E.drive + + def cue(self) -> None: + hub = self.httpd.hub + spoken = base.tone(1, 8000) + + def synthesize(body: bytes) -> bytes: + if json.loads(body)["text"] == CUE: + path = self.council / "rasci.json" + register = json.loads(path.read_text(encoding="utf-8")) + register.pop("work/docs", None) + register["work/new"] = {"title": "New line", "status": "running", "worker": "Skills session", "start": iso(time.time() - 1800), "roles": {"Skills session": "RA"}} + path.write_text(json.dumps(register), encoding="utf-8") + return spoken + + patch = mock.patch.object(hub.speech, "synthesize", synthesize) + patch.start() + self.addCleanup(patch.stop) + + def steps(self, browser: str) -> list[dict]: + OUT.mkdir(parents=True, exist_ok=True) + self.cue() + steps = [] + for index, (width, height) in enumerate(base.WIDTHS): + shot = str(OUT / f"{browser}-{width}") + page = f"{self.base}?{width}" + steps += [ + {"width": width, "height": height, "url": f"{page}-clear#stream", "wait": 600, "probe": CLEAR, "shot": None}, + {"width": width, "height": height, "url": f"{page}-empty", "wait": 1500, "probe": probe(START_EMPTY), "shot": f"{shot}-start-empty.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(STARS), "shot": f"{shot}-stars.png"}, + {"width": width, "height": height, "url": f"{page}-pin#stream", "wait": 1200, "probe": probe(PIN), "shot": f"{shot}-pinned.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(RESIZE), "shot": f"{shot}-resized.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(REORDER), "shot": f"{shot}-reordered.png"}, + {"width": width, "height": height, "url": f"{page}-reloaded", "wait": 1500, "probe": probe(RELOADED), "shot": f"{shot}-reloaded.png"}, + ] + if index == 0: + steps += [ + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(CHANGE), "shot": f"{shot}-gone.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(GONE_UNPIN), "shot": None}, + ] + steps += [ + {"width": width, "height": height, "url": f"{page}-full#stream", "wait": 1200, "probe": probe(FULL), "shot": f"{shot}-full.png"}, + {"width": width, "height": height, "url": f"{page}-start-pinned", "wait": 1500, "probe": probe(START_PINNED), "shot": None}, + {"width": width, "height": height, "url": f"{page}-explicit#tasks", "wait": 1500, "probe": probe(START_PINNED), "shot": None}, + ] + return steps + + def check(self, data: dict) -> None: + results = iter(data["results"]) + for index, (width, _) in enumerate(base.WIDTHS): + with self.subTest(width=width): + next(results) + empty = next(results) + self.assertEqual((empty["hash"], empty["screen"], empty["first"]), ("", "tab-stream", "Home"), empty) + stars = next(results) + self.assertEqual(stars["missing"], [], stars) + self.assertEqual(stars["covered"], [], stars) + self.assertGreater(stars["total"], 20, stars) + pinned = next(results) + self.assertEqual((pinned["gantt"], pinned["feature"], pinned["docs"], pinned["streamed"], pinned["chart"], pinned["off"], pinned["again"]), ("true", "true", "true", "true", True, "false", "true"), pinned) + self.assertEqual(pinned["pinned"], ["panel:tasks/gantt", "task:work/feature", "task:work/docs", "panel:stream"]) + self.assertEqual(pinned["unpinned"], ["task:work/feature", "task:work/docs", "panel:stream"]) + self.assertEqual(pinned["final"], ["task:work/feature", "task:work/docs", "panel:stream", "panel:tasks/gantt"]) + self.assertEqual(pinned["stored"], pinned["final"]) + resized = next(results) + self.assertEqual((resized["before"], resized["grown"], resized["most"], resized["least"], resized["keyed"], resized["final"]), ([6, 4], [9, 6], [12, 12], [1, 1], [3, 2], [8, 5]), resized) + self.assertEqual(resized["wide"][0], resized["wide"][1], resized) + self.assertEqual(resized["span"], "-1" if width == 390 else "span 8", resized) + self.assertEqual((resized["stored"]["w"], resized["stored"]["h"]), (8, 5)) + order = next(results) + start = ["task:work/feature", "task:work/docs", "panel:stream", "panel:tasks/gantt"] + self.assertEqual(order["before"], start) + self.assertEqual(order["dragged"], ["task:work/docs", "panel:stream", "task:work/feature", "panel:tasks/gantt"], order) + self.assertEqual(order["keyed"], ["task:work/docs", "task:work/feature", "panel:stream", "panel:tasks/gantt"], order) + self.assertTrue(order["focused"], order) + self.assertEqual(order["down"], ["task:work/docs", "panel:stream", "task:work/feature", "panel:tasks/gantt"], order) + self.assertEqual(order["stored"], order["down"]) + reloaded = next(results) + self.assertEqual((reloaded["hash"], reloaded["screen"], reloaded["tiles"], reloaded["errors"]), ("#home", "tab-home", order["down"], []), reloaded) + if width == 390: + self.assertEqual(reloaded["widths"], [reloaded["grid"]], reloaded) + else: + self.assertGreater(len(reloaded["widths"]), 1, reloaded) + if index == 0: + change = next(results) + self.assertTrue(change["grown"], change) + self.assertNotIn("work/new", change["before"]) + self.assertIn("work/new", change["after"]) + self.assertEqual(sorted(change["after"]), sorted(change["source"]), change) + self.assertEqual((change["goneWord"], change["unpin"]), ("gone", "Unpin"), change) + unpinned = next(results) + self.assertNotIn("task:work/docs", unpinned["tiles"]) + self.assertNotIn("task:work/docs", unpinned["stored"]) + full = next(results) + self.assertEqual((full["pressed"], full["count"]), ("false", 64), full) + self.assertTrue(full["toast"] and "At most 64 pins" in full["toast"], full) + pinned_start = next(results) + self.assertEqual((pinned_start["hash"], pinned_start["screen"]), ("#home", "tab-home"), pinned_start) + explicit = next(results) + self.assertEqual((explicit["hash"], explicit["screen"]), ("#tasks", "tab-tasks"), explicit) + + def init(self) -> str | None: + return None if REAL_STORE else STUB + + def test_chromium_stars_pins_resizes_reorders_and_marks_gone_tiles_at_three_widths(self): + data = self.drive(self.steps("chromium"), None, init=self.init()) + (OUT / "chromium-home.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + self.check(data) + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_stars_pins_resizes_reorders_and_marks_gone_tiles_at_three_widths(self): + data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=self.init()) + (OUT / "firefox-home.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + self.check(data) + + @unittest.skipUnless(REAL_STORE, "waits on 007: view-store.js and /api/view are not on this branch yet") + def test_a_second_browser_shows_the_same_layout(self): + first = self.drive([step for step in self.steps("chromium")[:6] if step["probe"] != probe(STARS)], None) + second = self.drive([{"width": 1366, "height": 768, "url": f"{self.base}?second", "wait": 2000, "probe": probe(RELOADED), "shot": str(OUT / "chromium-second.png")}], None) + self.assertEqual(second["results"][0]["tiles"], first["results"][-1]["down"]) + self.assertEqual((second["results"][0]["hash"], second["results"][0]["screen"]), ("#home", "tab-home")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_orchestrator_e2e.py b/tests/e2e/test_orchestrator_e2e.py index 61e2b78..dd5d847 100644 --- a/tests/e2e/test_orchestrator_e2e.py +++ b/tests/e2e/test_orchestrator_e2e.py @@ -37,7 +37,7 @@ VIEWS = ("orbit", "chord", "swimlane", "tree", "3d") TASK_VIEWS = ("list", "board", "rasci", "gantt", "burn", "3d") SCREENS = ["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 = ["Stream", "Agents", "Artifacts", "Tasks", "Resources"] +TABS = ["Home", "Stream", "Agents", "Artifacts", "Tasks", "Resources"] HELPERS = """ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const until = async (check, ms) => { diff --git a/tests/e2e/test_workbench_w4_e2e.py b/tests/e2e/test_workbench_w4_e2e.py index 17f9254..52550d3 100644 --- a/tests/e2e/test_workbench_w4_e2e.py +++ b/tests/e2e/test_workbench_w4_e2e.py @@ -128,7 +128,7 @@ class TestWorkbenchResources(HubCase): self.assertEqual(found["unknown"], [[self.start + UNREAD[0] * 60, self.start + UNREAD[1] * 60]]) self.assertEqual((found["agents"], found["bottoms"], found["stacked"]), (["Skills", "Stage"], ["Skills"], True)) self.assertEqual(found["legend"], ["CPU 60 %", "RAM 55 %", "Swap 5 %"]) - self.assertEqual(found["labels"], {"tab": ["Resources (key 5)", "Resources"], "reload": ["Reload: read the sampler files again", "Reload"], "titles": [[name, name] for name in PANELS.values()]}) + self.assertEqual(found["labels"], {"tab": ["Resources (key 6)", "Resources"], "reload": ["Reload: read the sampler files again", "Reload"], "titles": [[name, name] for name in PANELS.values()]}) self.assertEqual((found["unlabelled"], found["plots"]), (0, [True] * 4)) self.assertEqual((found["tall"], found["wide"]), (False, False), "the page scrolls") self.assertEqual(quiet(found["violations"]), []) diff --git a/tests/test_hub_home.py b/tests/test_hub_home.py new file mode 100644 index 0000000..1e67d8b --- /dev/null +++ b/tests/test_hub_home.py @@ -0,0 +1,528 @@ +from __future__ import annotations + +import json +import re +import subprocess +import unittest + +from hub_case import HubCase +from hub_support import HUB, NAV + +TEMPLATES = HUB / "templates" +PANELS = TEMPLATES / "panels.js" +HOME = TEMPLATES / "page-home.js" +PIN = {"kind": "panel", "id": "tasks/gantt", "w": 6, "h": 4} +LAYOUT_PROBE = """ +const P = require(process.argv[1]); +const pin = (id, extra) => ({kind: "task", id, w: 4, h: 3, ...extra}); +const many = (count) => Array.from({length: count}, (_, index) => pin(`work/t${index}`)); +const cases = { + ok: [pin("work/a"), {kind: "panel", id: "tasks/gantt", w: 12, h: 1}], + full: many(64), + over: many(65), + wide: [pin("work/a", {w: 13})], + flat: [pin("work/a", {h: 0})], + half: [pin("work/a", {w: 2.5})], + text: [pin("work/a", {w: "4"})], + space: [pin("work a")], + long: [pin("x".repeat(201))], + kind: [{kind: "k".repeat(33), id: "a", w: 1, h: 1}], + empty: [{kind: "", id: "a", w: 1, h: 1}], + extra: [pin("work/a", {x: 1})], + twice: [pin("work/a"), pin("work/a")], + object: {pins: []}, +}; +const valid = Object.fromEntries(Object.entries(cases).map(([name, value]) => [name, P.validLayout(value)])); +const cleaned = P.clean([pin("work/a"), pin("bad id"), pin("work/a"), null, pin("work/b", {extra: 1}), ...many(70)]); +console.log(JSON.stringify({valid, cleaned: [cleaned.length, cleaned[0], cleaned[1].id], notList: P.clean("x")})); +""" +REORDER_PROBE = """ +const P = require(process.argv[1]); +const pins = ["a", "b", "c", "d"].map((id) => ({kind: "task", id, w: 4, h: 3})); +const ids = (list) => list.map((pin) => pin.id).join(""); +const out = { + place: [ids(P.place(pins, 0, 2)), ids(P.place(pins, 3, 0)), ids(P.place(pins, 1, 1)), ids(P.place(pins, 5, 0)), ids(P.place(pins, 0, -1))], + move: [ids(P.move(pins, 0, -1)), ids(P.move(pins, 0, 1)), ids(P.move(pins, 3, 1)), ids(P.move(pins, 2, -1))], + resize: [P.resize(pins, 1, 0, 13)[1], P.resize(pins, 1, 12, 1)[1], P.resize(pins, 1, 7.4, 2.6)[1]], + stretch: [P.stretch({w: 4, h: 3}, 200, 0, 100, 80), P.stretch({w: 4, h: 3}, -1000, -1000, 100, 80), P.stretch({w: 4, h: 3}, 5000, 5000, 100, 80), P.stretch({w: 4, h: 3}, 140, 30, 100, 80)], + untouched: ids(pins), +}; +const full = Array.from({length: 64}, (_, index) => ({kind: "task", id: `t${index}`, w: 4, h: 3})); +const added = P.add(pins, "panel", "tasks/gantt"); +const removed = P.remove(added.pins, "panel", "tasks/gantt"); +out.add = [added.refused, added.pins.at(-1), P.add(added.pins, "panel", "tasks/gantt").pins.length, removed.length, P.remove(removed, "panel", "tasks/gantt").length, + P.add(full, "task", "t64").refused, P.add(full, "task", "t64").pins.length, P.add(full, "task", "t3").refused, P.add(full, "task", "t3").pins.length]; +out.keys = [ids(P.placeKey(pins, "task:a", "task:c")), ids(P.placeKey(pins, "task:x", "task:a")), ids(P.moveKey(pins, "task:b", 1)), ids(P.moveKey(pins, "task:x", 1)), + P.resizeKey(pins, "task:b", 5, 2)[1], P.resizeBy(pins, "task:b", 1, -1)[1], ids(P.resizeBy(pins, "task:x", 1, 1)), ids(P.resizeKey(pins, "task:x", 1, 1))]; +P.panel("agents/3d", "Agents: 3D", () => "a", "3d"); +P.panel("tasks/3d", "Tasks: 3D", () => "t", "3d"); +const one = P.add(pins, "panel", "agents/3d"); +const second = P.add(one.pins, "panel", "tasks/3d"); +const swapped = P.add(P.remove(one.pins, "panel", "agents/3d"), "panel", "tasks/3d"); +const both = [...one.pins, {kind: "panel", id: "tasks/3d", w: 6, h: 4}]; +out.group = [one.refused, second.refused, second.holder, second.pins.length, swapped.refused, swapped.pins.at(-1).id, P.add(one.pins, "panel", "tasks/gantt").refused, + P.firstOfGroup(both, both[4]), P.firstOfGroup(both, both[5]), P.firstOfGroup(both, both[0])]; +console.log(JSON.stringify(out)); +""" +REGISTRY_PROBE = """ +const P = require(process.argv[1]); +P.panel("tasks/gantt", "Tasks: Gantt", (size) => `gantt ${size.w}x${size.h}`); +P.item("task", (id) => `Task ${id}`, (size, id) => (id === "work/live" ? `task ${id} ${size.w}` : null)); +P.item("artifact", "Artifact", (size, id) => id); +const odd = "branch:/repo\\u0000feature x"; +const token = P.token(odd); +const gantt = P.lookup("panel", "tasks/gantt"); +const live = P.lookup("task", "work/live"); +const art = P.lookup("artifact", token); +console.log(JSON.stringify({ + gantt: [gantt.title, gantt.render({w: 6, h: 4})], + live: [live.title, live.render({w: 3, h: 2})], + gone: P.lookup("task", "work/deleted").render({w: 3, h: 2}), + unknownPanel: P.lookup("panel", "nope"), + unknownKind: P.lookup("nope", "x"), + token: [token, P.ID.test(token), P.raw(token) === odd, art.render({w: 1, h: 1}) === odd, P.token("work/plain"), P.token("a_b"), P.raw(P.token("a_b")), P.token("y".repeat(400)), P.token("1763.5/radio:work/x:9")], +})); +""" +STORE_PROBE = """ +const P = require(process.argv[1]); +const calls = []; +const listeners = []; +const pin = (id) => ({kind: "task", id, w: 1, h: 1}); +const backend = { + value: [{kind: "task", id: "work/a", w: 4, h: 3}, {kind: "task", id: "bad id", w: 1, h: 1}], + get(path) { calls.push(["get", path]); return this.value; }, + update(path, change) { this.value = change(this.value); calls.push(["update", path, this.value.map((one) => one.id)]); return Promise.resolve(true); }, + set(path) { throw new Error(`${path} holds a list: use update()`); }, + on(path, listen) { calls.push(["on", path]); listeners.push(listen); }, +}; +const store = P.store(backend, "home.pins"); +const seen = []; +store.watch((pins) => seen.push(pins.length)); +listeners.forEach((listen) => listen([{kind: "task", id: "work/b", w: 2, h: 2}, "junk"])); +(async () => { + const read = store.read(); + backend.value = [...backend.value, pin("work/other")]; + const wrote = await store.change((pins) => [...pins, pin("work/c")]); + const refused = await store.change(() => Array.from({length: 65}, (_, index) => pin(`t${index}`))).then(() => "stored", (error) => error.message); + backend.value = Array.from({length: 64}, (_, index) => pin(`t${index}`)); + backend.get = () => backend.value.slice(0, 63); + const late = await store.change((pins) => [...pins, pin("work/late")]); + const memory = P.memory(); + const heard = []; + memory.on("home.pins", (value) => heard.push(value.length)); + await memory.update("home.pins", () => [1, 2]); + const unknownPath = () => { throw new Error("unknown view path home.pins"); }; + const strict = P.store({get: unknownPath, update: unknownPath, on: unknownPath, error: () => "another browser kept changing home.pins; try again"}, "home.pins"); + const thrown = await strict.change(() => []).then(() => "stored", (error) => error.message); + const unknown = [strict.read(), strict.watch(() => null), thrown, strict.error(), P.store(backend, "home.pins").error()]; + console.log(JSON.stringify({read: read.map((one) => one.id), wrote, refused, late: [late, backend.value.length, calls.at(-1)[2].includes("work/late")], calls: calls.slice(0, 4), seen, + memory: [memory.get("home.pins").length, heard], unknown})); +})(); +""" +START_PROBE = """ +const N = require(process.argv[1]); +console.log(JSON.stringify({ + first: N.TABS[0], icon: N.ICONS.home, + routes: [["", 0], ["", 1], ["#", 3], ["#home", 0], ["#home", 2], ["#tasks/gantt", 2], ["#stream", 5], ["#bogus", 1], ["", undefined]].map(([hash, pinned]) => N.route(hash, pinned)), +})); +""" +TAB_KIT = """ +const fs = require("fs"); +const vm = require("vm"); +const [panelsFile, homeFile] = process.argv.slice(1); +const clone = (value) => JSON.parse(JSON.stringify(value)); +const settle = () => new Promise((resolve) => setTimeout(resolve, 5)); +const keys = (pins) => pins.map((pin) => `${pin.kind}:${pin.id}`); +function hub(value) { + return {value: clone(value), hostile: false, patches: 0, + patch(body) { + this.patches += 1; + if (this.hostile) { + this.value = this.value.map((pin, at) => (at ? pin : {...pin, w: (pin.w % 12) + 1})); + } + if (JSON.stringify(body.expect) !== JSON.stringify(this.value)) { + return {status: 409, view: clone(this.value)}; + } + this.value = clone(body.set); + return {status: 200, data: clone(this.value)}; + }}; +} +function viewStore(server) { + let saved = clone(server.value); + let error = ""; + const pending = []; + const fold = (changes, base) => changes.reduce((value, change) => clone(change(clone(value))), base); + const store = { + sent: [], + get: (path) => clone(fold(pending, saved)), + set(path) { throw new Error(`${path} holds a list: use update()`); }, + on() {}, + error: () => error, + update(path, change) { + store.sent.push(path); + pending.push(change); + return new Promise((resolve) => setTimeout(() => resolve(flush()), 0)); + }, + }; + function flush() { + const changes = pending.splice(0); + for (let attempt = 1; changes.length; attempt += 1) { + const answer = server.patch({set: fold(changes, saved), expect: saved}); + saved = answer.status === 200 ? answer.data : answer.view; + if (answer.status === 200) { + error = ""; + return true; + } + if (attempt === 3) { + error = "another browser kept changing home.pins; try again"; + return false; + } + } + return true; + } + return store; +} +function page(server) { + const store = viewStore(server); + const toasts = []; + const context = vm.createContext({ViewStore: store, labelOf: (key) => key, toast: (title, lines, good) => toasts.push([title, lines.join(" "), good]), console}); + vm.runInContext(fs.readFileSync(panelsFile, "utf8"), context); + vm.runInContext(`${fs.readFileSync(homeFile, "utf8")} +globalThis.probe = {homePress, homeUnpin, homeView, Panels};`, context); + const probe = context.probe; + probe.homeView.pins = probe.Panels.clean(store.get("home.pins")); + return {...probe, store, toasts}; +} +""" +PAGE_PROBE = TAB_KIT + """ +const server = hub([]); +const tab = page(server); +const {homePress, homeUnpin, homeView, Panels} = tab; +const ids = Object.fromEntries(["panel", "task", "message", "artifact", "agent", "ancestry", "nope"].map((kind) => [kind, Boolean(Panels.lookup(kind, kind === "panel" ? "stream" : "x"))])); +const panels = ["stream", "radio-log", "agents/orbit", "agents/chord", "agents/swimlane", "agents/3d", "agents/tree", "agents/hierarchy", "artifacts/orbit", "artifacts/chord", "artifacts/swimlane", "artifacts/3d", + "tasks/list", "tasks/board", "tasks/rasci", "tasks/gantt", "tasks/burn", "tasks/3d"].filter((id) => !Panels.lookup("panel", id)); +(async () => { + homePress("panel", "tasks/gantt", "Gantt"); + await settle(); + const one = keys(server.value); + homePress("panel", "tasks/gantt", "Gantt"); + await settle(); + const none = server.value.length; + homePress("panel", "agents/3d", "Agents: 3D"); + homePress("panel", "tasks/3d", "Tasks: 3D"); + await settle(); + const solid = keys(server.value); + homeUnpin("panel:agents/3d"); + await settle(); + Array.from({length: 64}, (_, index) => homePress("task", `work/t${index}`, `t${index}`)); + await settle(); + const sent = tab.store.sent.length; + homePress("task", "work/t64", "Task work/t64"); + await settle(); + const full = [server.value.length, tab.store.sent.length - sent]; + homeUnpin("task:work/t0"); + await settle(); + const after = server.value.length; + server.hostile = true; + const patches = server.patches; + homeUnpin("task:work/t1"); + const optimistic = homeView.pins.length; + await settle(); + console.log(JSON.stringify({ids, panels, one, none, solid, full, after, optimistic, reverted: homeView.pins.length, tries: server.patches - patches, + fellBack: JSON.stringify(homeView.pins) === JSON.stringify(Panels.clean(server.value)), paths: [...new Set(tab.store.sent)], toasts: tab.toasts})); +})(); +""" +RACE_PROBE = TAB_KIT + """ +(async () => { + const server = hub([]); + const one = page(server); + const other = page(server); + one.homePress("panel", "tasks/gantt", "Gantt"); + other.homePress("task", "work/b", "Task work/b"); + await settle(); + const pinned = [keys(server.value), server.patches, keys(other.store.get("home.pins"))]; + const seed = Array.from({length: 63}, (_, index) => ({kind: "task", id: `work/s${index}`, w: 2, h: 1})); + const crowded = hub(seed); + const first = page(crowded); + const late = page(crowded); + first.homePress("task", "work/c", "Task work/c"); + late.homePress("task", "work/d", "Task work/d"); + await settle(); + const ids = keys(crowded.value); + const stale = hub([{kind: "task", id: "work/a", w: 4, h: 3}, {kind: "task", id: "work/b", w: 4, h: 3}]); + const mover = page(stale); + const pinner = page(stale); + pinner.homePress("task", "work/c", "Task work/c"); + mover.homeUnpin("task:work/a"); + await settle(); + console.log(JSON.stringify({pinned, full: [ids.length, ids.includes("task:work/c"), ids.includes("task:work/d"), late.toasts, first.toasts], + unpinned: keys(stale.value), toasts: [...one.toasts, ...other.toasts, ...mover.toasts, ...pinner.toasts]})); +})(); +""" + + +STAR_PROBE = """ +const fs = require("fs"); +const vm = require("vm"); +const XHTML = "http://www.w3.org/1999/xhtml"; +const parts = (selector) => selector.split(",").map((part) => { + const found = /^\\s*([a-z]*)((?:\\[[^\\]]+\\])*)\\s*$/.exec(part); + return {tag: found[1], attrs: [...found[2].matchAll(/\\[([\\w-]+)(?:="([^"]*)")?\\]/g)].map(([, name, value]) => [name, value])}; +}); +const matches = (node, selector) => parts(selector).some(({tag, attrs}) => (!tag || node.tagName === tag.toUpperCase()) && attrs.every(([name, value]) => node.attrs.has(name) && (value === undefined || node.attrs.get(name) === value))); +class El { + constructor(tag, ns) { this.tagName = tag.toUpperCase(); this.namespaceURI = ns || XHTML; this.attrs = new Map(); this.children = []; this.parentNode = null; this.listeners = {}; } + setAttribute(name, value) { this.attrs.set(name, String(value)); } + getAttribute(name) { return this.attrs.has(name) ? this.attrs.get(name) : null; } + hasAttribute(name) { return this.attrs.has(name); } + get classList() { const list = (this.getAttribute("class") || "").split(/\\s+/); return {contains: (name) => list.includes(name)}; } + detach() { if (this.parentNode) { this.parentNode.children = this.parentNode.children.filter((child) => child !== this); this.parentNode = null; } } + append(...nodes) { nodes.forEach((child) => { child.detach(); child.parentNode = this; this.children.push(child); }); } + prepend(...nodes) { nodes.reverse().forEach((child) => { child.detach(); child.parentNode = this; this.children.unshift(child); }); } + replaceChildren(...nodes) { [...this.children].forEach((child) => child.detach()); this.append(...nodes); } + contains(node) { for (let at = node; at; at = at.parentNode) { if (at === this) { return true; } } return false; } + all() { return this.children.flatMap((child) => [child, ...child.all()]); } + querySelectorAll(selector) { return this.all().filter((child) => matches(child, selector)); } + closest(selector) { for (let at = this; at; at = at.parentNode) { if (matches(at, selector)) { return at; } } return null; } + addEventListener(name, listen) { (this.listeners[name] = this.listeners[name] || []).push(listen); } +} +const el = (tag, attrs, ...children) => { + const made = new El(tag); + Object.entries(attrs).forEach(([name, value]) => made.setAttribute(name, value)); + made.append(...children); + return made; +}; +const document = {createElement: (tag) => new El(tag), createElementNS: (ns, tag) => new El(tag, ns)}; +const context = vm.createContext({document, MutationObserver: class { observe() {} }, console}); +vm.runInContext(fs.readFileSync(process.argv[1], "utf8"), context); +const P = vm.runInContext("Panels", context); +P.panel("tasks/list", "Tasks: list", () => null); +P.panel("radio-log", "Radio log", () => null); +P.item("task", (id) => `Task ${id}`, () => null); +const slot = el("div", {class: "head-row", "data-star-slot": ""}, el("code", {}), el("button", {class: "priority"})); +const task = el("li", {"data-item": "task:work/a"}, slot, el("span", {})); +const bare = el("li", {"data-item": "task:work/b"}, el("span", {})); +const list = el("div", {"data-panel": "tasks/list"}, el("ol", {}, task, bare)); +const svg = new El("g", "http://www.w3.org/2000/svg"); +svg.setAttribute("data-item", "task:work/c"); +const radio = el("section", {"aria-label": "Radio log"}, el("ul", {"aria-label": "Radio log"})); +const root = el("main", {}, list, el("div", {}, svg), radio, el("div", {"data-panel": "nope"})); +const clicked = []; +const stars = () => root.querySelectorAll("[class]").filter((node) => node.classList.contains("star")); +const own = (host) => stars().filter((node) => node.closest("[data-panel], [data-item]") === host); +const mark = P.decorate(root, {pinned: (kind, id) => kind === "task" && id === "work/a", press: (...args) => clicked.push(args), marks: [['section[aria-label="Radio log"]', "radio-log"]]}); +const before = stars().length; +mark(); +const [panelStar] = own(list); +const [taskStar] = own(task); +const out = { + panel: {first: list.children[0].getAttribute("class"), stars: own(list).length, pressed: panelStar.getAttribute("aria-pressed"), title: panelStar.getAttribute("title")}, + task: {inSlot: taskStar.parentNode === slot, slotLast: slot.children.at(-1) === taskStar, rows: task.children.filter((child) => child.classList.contains("star-row")).length, + pressed: taskStar.getAttribute("aria-pressed"), label: taskStar.getAttribute("aria-label")}, + bare: {first: bare.children[0].getAttribute("class"), stars: own(bare).length}, + svg: svg.children.length, + radio: [radio.getAttribute("data-panel"), radio.children[0].getAttribute("class")], + again: [before, stars().length], +}; +taskStar.listeners.click[0]({preventDefault: () => null, stopPropagation: () => null}); +const fresh = el("div", {"data-star-slot": ""}); +task.replaceChildren(fresh, el("span", {})); +mark(); +out.redrawn = [own(task)[0].parentNode === fresh, stars().length]; +out.clicked = clicked; +console.log(JSON.stringify(out)); +""" +MESSAGE_PROBE = """ +const fs = require("fs"); +const vm = require("vm"); +const [panelsFile, homeFile] = process.argv.slice(1); +const urls = []; +const answers = {1762999999: {events: [{id: "radio:abc", ts: 1763000000.5}], entries: []}, 1762999899: {events: [], entries: [{id: "transcript:9", ts: 1762999900}]}}; +const fetch = async (url) => { + urls.push(url); + return {ok: true, json: async () => answers[new URL(url, "http://hub.invalid").searchParams.get("from")]}; +}; +const stream = {events: [], entries: [{id: "transcript:7", ts: 5}], key: "view=fuer-dich", busy: false}; +const context = vm.createContext({fetch, stream, filter: {view: "fuer-dich", waiting: true}, ui: {}, labelOf: (key) => key, toast: () => null, emptyState: () => "wait", + eventRow: (entry) => `row ${entry.id}`, h: (tag, attrs, child) => child, URL, console}); +vm.runInContext(fs.readFileSync(panelsFile, "utf8"), context); +vm.runInContext(fs.readFileSync(homeFile, "utf8"), context); +const P = vm.runInContext("Panels", context); +const tile = (raw) => P.lookup("message", P.token(raw)).render({w: 4, h: 3}); +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); +(async () => { + const first = tile("1763000000.5/radio:abc"); + await settle(); + await settle(); + const found = tile("1763000000.5/radio:abc"); + tile("1762999900/radio:gone"); + await settle(); + await settle(); + const gone = tile("1762999900/radio:gone"); + const cached = tile("5/transcript:7"); + const broken = tile("nonsense"); + console.log(JSON.stringify({first, found, gone, cached, broken, urls, fetches: urls.length})); +})(); +""" + + +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) + + +class TestHomeLayout(unittest.TestCase): + def test_the_layout_validation_takes_at_most_64_pins_of_kind_id_w_and_h_in_their_ranges(self): + data = node(LAYOUT_PROBE, str(PANELS)) + self.assertEqual(data["valid"], { + "ok": True, "full": True, "over": False, "wide": False, "flat": False, "half": False, "text": False, "space": False, "long": False, + "kind": False, "empty": False, "extra": False, "twice": False, "object": False, + }) + self.assertEqual(data["cleaned"], [64, {"kind": "task", "id": "work/a", "w": 4, "h": 3}, "work/t0"]) + self.assertEqual(data["notList"], []) + + +class TestHomeReorder(unittest.TestCase): + def test_reorder_resize_add_and_remove_are_idempotent_and_hold_their_bounds(self): + data = node(REORDER_PROBE, str(PANELS)) + self.assertEqual(data["place"], ["bcad", "dabc", "abcd", "abcd", "abcd"]) + self.assertEqual(data["move"], ["abcd", "bacd", "abcd", "acbd"]) + self.assertEqual([(pin["w"], pin["h"]) for pin in data["resize"]], [(1, 12), (12, 1), (7, 3)]) + self.assertEqual(data["stretch"], [{"w": 6, "h": 3}, {"w": 1, "h": 1}, {"w": 12, "h": 12}, {"w": 5, "h": 3}]) + self.assertEqual(data["untouched"], "abcd") + self.assertEqual(data["add"], ["", PIN, 5, 4, 4, "full", 64, "", 64]) + + def test_reorder_and_resize_find_their_pin_by_key_and_leave_the_list_alone_without_it(self): + data = node(REORDER_PROBE, str(PANELS)) + resized = {"kind": "task", "id": "b", "w": 5, "h": 2} + self.assertEqual(data["keys"], ["bcad", "abcd", "acbd", "abcd", resized, resized, "abcd", "abcd"]) + + def test_home_holds_one_3d_tile_and_refuses_a_second_with_its_holder(self): + data = node(REORDER_PROBE, str(PANELS)) + holder = {"kind": "panel", "id": "agents/3d", "w": 6, "h": 4} + self.assertEqual(data["group"], ["", "group", holder, 5, "", "tasks/3d", "", True, False, True]) + + +class TestHomeRegistry(unittest.TestCase): + def test_the_registry_finds_panels_and_item_kinds_and_a_missing_item_renders_none(self): + data = node(REGISTRY_PROBE, str(PANELS)) + self.assertEqual(data["gantt"], ["Tasks: Gantt", "gantt 6x4"]) + self.assertEqual(data["live"], ["Task work/live", "task work/live 3"]) + self.assertIsNone(data["gone"]) + self.assertIsNone(data["unknownPanel"]) + self.assertIsNone(data["unknownKind"]) + self.assertEqual(data["token"], ["branch_3a_/repo_0_feature_20_x", True, True, True, "work/plain", "a_5f_b", "a_b", None, "1763.5/radio_3a_work/x_3a_9"]) + + @unittest.skipUnless((TEMPLATES / "view-store.js").exists(), "waits on 007: view-store.js is not on this branch yet") + def test_pin_ids_follow_the_view_store_id_grammar(self): + probe = 'const P = require(process.argv[1]); const V = require(process.argv[2]); const ids = ["work/a", "branch:/r\\u0000x y", "a_b", "1763.5/radio:w:9"]; console.log(JSON.stringify(ids.map((id) => [P.token(id), V.id(id)])));' + done = subprocess.run(["node", "-e", probe, str(PANELS), str(TEMPLATES / "view-store.js")], capture_output=True, text=True, timeout=60, check=True) + for mine, theirs in json.loads(done.stdout): + self.assertEqual(mine, theirs) + + def test_the_store_changes_the_stored_pins_through_update_and_refuses_an_invalid_layout_before_the_backend(self): + data = node(STORE_PROBE, str(PANELS)) + self.assertEqual(data["read"], ["work/a"]) + self.assertTrue(data["wrote"]) + self.assertEqual(data["calls"], [["on", "home.pins"], ["get", "home.pins"], ["get", "home.pins"], ["update", "home.pins", ["work/a", "work/other", "work/c"]]]) + self.assertEqual(data["refused"], "invalid layout") + self.assertEqual(data["late"], [True, 64, False]) + self.assertEqual(data["unknown"], [[], False, "unknown view path home.pins", "another browser kept changing home.pins; try again", ""]) + self.assertEqual(data["seen"], [1]) + self.assertEqual(data["memory"], [2, [2]]) + + +class TestHomeStart(unittest.TestCase): + def test_home_is_the_first_tab_and_the_start_once_a_pin_exists_while_an_explicit_hash_wins(self): + data = node(START_PROBE, str(NAV)) + self.assertEqual((data["first"], data["icon"]), (["home", "Home"], "bi-house-door")) + stream = {"screen": "stream", "view": None, "redirect": None} + home = {"screen": "home", "view": None, "redirect": None} + self.assertEqual(data["routes"], [ + stream, {"screen": "home", "view": None, "redirect": "#home"}, {"screen": "home", "view": None, "redirect": "#home"}, home, home, + {"screen": "tasks", "view": "gantt", "redirect": None}, stream, stream, stream, + ]) + + +class TestHomePage(unittest.TestCase): + def test_the_page_registers_every_panel_and_item_kind_and_refuses_the_65th_pin_before_any_update(self): + data = node(PAGE_PROBE, str(PANELS), str(HOME)) + self.assertEqual(data["ids"], {"panel": True, "task": True, "message": True, "artifact": True, "agent": True, "ancestry": True, "nope": False}) + self.assertEqual(data["panels"], []) + self.assertEqual((data["one"], data["none"], data["solid"], data["full"], data["after"]), (["panel:tasks/gantt"], 0, ["panel:agents/3d"], [64, 0], 63)) + self.assertEqual(data["paths"], ["home.pins"]) + self.assertEqual(data["toasts"][:2], [ + ["One 3D tile at a time", "Home already holds Agents: 3D: unpin it before you pin Tasks: 3D.", False], + ["Home is full", "At most 64 pins: unpin one before you pin Task work/t64.", False], + ]) + + def test_a_refused_update_falls_back_to_the_stored_pins_and_shows_the_store_error(self): + data = node(PAGE_PROBE, str(PANELS), str(HOME)) + self.assertEqual((data["optimistic"], data["tries"], data["reverted"], data["fellBack"]), (62, 3, 63, True)) + self.assertEqual(data["toasts"][2:], [["Home not saved", "another browser kept changing home.pins; try again", False]]) + + def test_two_stale_tabs_keep_both_pins_and_a_late_65th_pin_is_refused_visibly(self): + data = node(RACE_PROBE, str(PANELS), str(HOME)) + both = ["panel:tasks/gantt", "task:work/b"] + self.assertEqual(data["pinned"], [both, 3, both]) + self.assertEqual(data["full"], [64, True, False, [["Home is full", "At most 64 pins: unpin one before you pin Task work/d.", False]], []]) + self.assertEqual(data["unpinned"], ["task:work/b", "task:work/c"]) + self.assertEqual(data["toasts"], []) + + def test_every_data_panel_and_data_item_kind_in_the_templates_is_registered(self): + home = HOME.read_text(encoding="utf-8") + registered = set(re.findall(r'Panels\.panel\("([^"]+)"', home)) + kinds = set(re.findall(r'Panels\.item\("([^"]+)"', home)) + sources = "\n".join(path.read_text(encoding="utf-8") for path in TEMPLATES.glob("page-*.js")) + literal = set(re.findall(r'"data-panel": "([^"]+)"', sources)) + views = {"agents": ["orbit", "chord", "swimlane", "3d"], "artifacts": ["orbit", "chord", "swimlane", "3d"], "tasks": ["list", "board", "rasci", "gantt", "burn"]} + dynamic = {f"{tab}/{view}" for tab in re.findall(r'"data-panel": `(\w+)/\$\{view\}`', sources) for view in views[tab]} + used = set(re.findall(r'(?:"data-item"|item): `(\w+):', sources)) + marked = set(re.findall(r"\['[^']+', \"([^\"]+)\"\]", home)) + self.assertEqual((len(literal), marked), (4, {"radio-log"})) + literal |= marked + self.assertEqual(len(dynamic), 13) + self.assertEqual(sorted(literal | dynamic), sorted(registered)) + self.assertEqual(sorted(used), sorted(kinds)) + + +class TestHomeStars(unittest.TestCase): + def test_a_star_sits_in_flow_in_its_own_hosts_slot_or_a_star_row_and_never_twice(self): + data = node(STAR_PROBE, str(PANELS)) + self.assertEqual(data["panel"], {"first": "star-row", "stars": 1, "pressed": "false", "title": "Pin to Home: Tasks: list"}) + self.assertEqual(data["task"], {"inSlot": True, "slotLast": True, "rows": 0, "pressed": "true", "label": "Unpin from Home"}) + self.assertEqual(data["bare"], {"first": "star-row", "stars": 1}) + self.assertEqual((data["svg"], data["radio"], data["again"], data["redrawn"]), (0, ["radio-log", "star-row"], [4, 4], [True, 4])) + self.assertEqual(data["clicked"], [["task", "work/a", "Task work/a"]]) + + def test_the_star_css_positions_nothing_and_leaves_the_starred_elements_alone(self): + css = (TEMPLATES / "style-home.css").read_text(encoding="utf-8") + star = re.findall(r"^\.star(?:-row)?(?:\[[^\]]+\])? \{([^}]*)\}", css, re.MULTILINE) + self.assertEqual(len(star), 3) + self.assertFalse(any("position" in rule for rule in star), star) + self.assertNotIn("[data-panel]", css) + self.assertNotIn("[data-item]", css) + + +class TestHomeMessage(unittest.TestCase): + def test_a_pinned_message_resolves_by_its_own_id_and_time_whatever_the_stream_shows(self): + data = node(MESSAGE_PROBE, str(PANELS), str(HOME)) + self.assertEqual(data["first"], "wait") + self.assertEqual(data["urls"], ["/api/events?from=1762999999&to=1763000002&after=0", "/api/events?from=1762999899&to=1762999901&after=0"]) + self.assertEqual((data["found"], data["gone"], data["cached"], data["broken"]), ("row radio:abc", None, "row transcript:7", None)) + self.assertEqual(len(data["urls"]), data["fetches"]) + + +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"): + with self.subTest(glyph=glyph): + self.assertIn(f' ({screen: "agents", view: "chord"})}, ui: {views: {}}, drawn: {screen: true}, calm: {matches: false}, h: () => null, + Nav: {TABS: [], route: () => ({screen: "agents", view: "chord"})}, homePins: () => [], ui: {views: {}}, drawn: {screen: true}, calm: {matches: false}, h: () => null, window: {location: {hash: "#agents/chord"}, history: {replaceState: () => null}}, document: {getElementById: () => ({append: () => null}), startViewTransition: (update) => { started.push(typeof update); @@ -65,9 +65,9 @@ class TestNavModule(unittest.TestCase): done = subprocess.run(["node", "-e", NAV_PROBE, str(NAV)], capture_output=True, text=True, timeout=60, check=True) cls.data = json.loads(done.stdout) - def test_the_navigation_has_five_entries_and_no_inbox_and_stream_keeps_only_the_firewall(self): + def test_the_navigation_has_six_entries_home_first_and_no_inbox_and_stream_keeps_only_the_firewall(self): stream = ["stream", "Stream", [["rules", "Firewall"]]] - self.assertEqual(self.data["tabs"], [stream, ["agents", "Agents", []], ["artifacts", "Artifacts", []], ["tasks", "Tasks", []], ["resources", "Resources", []]]) + self.assertEqual(self.data["tabs"], [["home", "Home", []], stream, ["agents", "Agents", []], ["artifacts", "Artifacts", []], ["tasks", "Tasks", []], ["resources", "Resources", []]]) self.assertNotIn("inbox", json.dumps(self.data["tabs"])) def test_agents_and_artifacts_offer_five_views_in_order_and_tasks_six(self):