From 94bf0b418a04b90dd7513d0aea02baac41625788 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 17 Nov 2026 14:13:29 +0000 Subject: [PATCH] feat(orchestrator): legend toggle per panel and Home tile (017) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every view panel and Home tile that holds a legend gets an info button beside its star that hides or shows the legend. The pick is kept in the view store under legend.views per panel and legend.tiles per pin key; the store validates both maps and drops the state of a tile whose pin left Home. Unit tests for the store, E2E in Chromium and Firefox at 1920, 1366 and 390. 🎯 Fix: 94 % 💥 Break: 4 % 💸 Tokens: 100 % ⏱️ Velocity: 100 % 🛡️ Security: 100 % 🏆 Score: 90 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 --- orchestrator/kvb_orchestrator/viewstore.py | 36 ++- orchestrator/templates/index.html.j2 | 1 + orchestrator/templates/page-boot.js | 1 + orchestrator/templates/page-legend.js | 85 +++++++ orchestrator/templates/style-legend-chips.css | 1 + tests/e2e/test_legend_toggle_e2e.py | 230 ++++++++++++++++++ tests/test_hub_view.py | 34 ++- 7 files changed, 385 insertions(+), 3 deletions(-) create mode 100644 orchestrator/templates/page-legend.js create mode 100644 tests/e2e/test_legend_toggle_e2e.py diff --git a/orchestrator/kvb_orchestrator/viewstore.py b/orchestrator/kvb_orchestrator/viewstore.py index e4c7650..9871643 100644 --- a/orchestrator/kvb_orchestrator/viewstore.py +++ b/orchestrator/kvb_orchestrator/viewstore.py @@ -4,6 +4,7 @@ import copy import json import re import threading +from collections.abc import Callable from pathlib import Path from .errors import Conflict, ToolError @@ -18,7 +19,13 @@ VIEW = { "burn": {"overlays": []}, "home": {"pins": []}, "kanban": {"hidden": []}, + "legend": {"views": {}, "tiles": {}}, } +LEGEND_PANELS = ( + "agents/orbit", "agents/chord", "agents/swimlane", "artifacts/orbit", "artifacts/chord", "artifacts/swimlane", + "tasks/rasci", "tasks/gantt", "tasks/burn", "resources-hardware", "resources-tokens", "resources-combined", +) +PIN_KEY = re.compile(r"[A-Za-z0-9:_./-]{1,32}:[A-Za-z0-9:_./-]{1,200}") VIEW_PATH = re.compile(r"[A-Za-z]{1,32}(?:\.[A-Za-z]{1,32})?") SERIES_ID = re.compile(r"[A-Za-z0-9:_./-]{1,200}") PIN_KIND = re.compile(r"[A-Za-z0-9:_./-]{1,32}") @@ -136,21 +143,42 @@ def pins(value: object) -> list[dict]: return found +def legend_flags(value: object, name: str, known: Callable[[str], object], what: str) -> dict[str, bool]: + """Args: + value: a map of legend owners to whether their legend shows. + name: where the map sits, for the error message. + known: true for a key that may own a legend. + what: the keys known accepts, for the error message. + + Returns: + The map; a key known refuses or a value other than true or false + raises ToolError. + """ + if not isinstance(value, dict) or not all(isinstance(key, str) and known(key) for key in value): + raise ToolError(f"{name} must map {what} to true or false") + return {key: flag(shown, f"{name}.{key}") for key, shown in value.items()} + + def valid_view(raw: object) -> dict: """Args: raw: the whole view document as the page sent it. Returns: The document with every key of VIEW and nothing else; any other - key, a missing one or a malformed value raises ToolError. + key, a missing one or a malformed value raises ToolError. The + legend state of a tile whose pin left Home is dropped. """ data = section(raw, "view", tuple(VIEW)) resources = section(data["resources"], "resources", tuple(VIEW["resources"])) burn = section(data["burn"], "burn", tuple(VIEW["burn"])) home = section(data["home"], "home", tuple(VIEW["home"])) kanban = section(data["kanban"], "kanban", tuple(VIEW["kanban"])) + legend = section(data["legend"], "legend", tuple(VIEW["legend"])) if not isinstance(resources["tokens"], str) or resources["tokens"] not in TOKEN_MODES: raise ToolError(f"resources.tokens must be one of {', '.join(TOKEN_MODES)}") + pinned = pins(home["pins"]) + keys = {f"{pin['kind']}:{pin['id']}" for pin in pinned} + tiles = legend_flags(legend["tiles"], "legend.tiles", PIN_KEY.fullmatch, "pin keys kind:id") return { "resources": { "hidden": series_ids(resources["hidden"], "resources.hidden"), @@ -159,8 +187,12 @@ def valid_view(raw: object) -> dict: "combinedHidden": series_ids(resources["combinedHidden"], "resources.combinedHidden"), }, "burn": {"overlays": members(burn["overlays"], "burn.overlays", "metrics", OVERLAYS)}, - "home": {"pins": pins(home["pins"])}, + "home": {"pins": pinned}, "kanban": {"hidden": members(kanban["hidden"], "kanban.hidden", "layers", KANBAN_LAYERS)}, + "legend": { + "views": legend_flags(legend["views"], "legend.views", LEGEND_PANELS.__contains__, f"panels of {', '.join(LEGEND_PANELS)}"), + "tiles": {key: shown for key, shown in tiles.items() if key in keys}, + }, } diff --git a/orchestrator/templates/index.html.j2 b/orchestrator/templates/index.html.j2 index 3e92753..967b2ae 100644 --- a/orchestrator/templates/index.html.j2 +++ b/orchestrator/templates/index.html.j2 @@ -643,6 +643,7 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi {% include "page-home.js" %} +{% include "page-legend.js" %} {% include "page-rules.js" %} {% include "page-firewall.js" %} diff --git a/orchestrator/templates/page-boot.js b/orchestrator/templates/page-boot.js index b64c127..72f9cc7 100644 --- a/orchestrator/templates/page-boot.js +++ b/orchestrator/templates/page-boot.js @@ -53,6 +53,7 @@ announce(); measure(); homeBoot(); + legendBoot(); apply(); drawTime(); motion.asOf = ui.asOf; diff --git a/orchestrator/templates/page-legend.js b/orchestrator/templates/page-legend.js new file mode 100644 index 0000000..d8ad782 --- /dev/null +++ b/orchestrator/templates/page-legend.js @@ -0,0 +1,85 @@ + const LEGEND_PARTS = ".legend, .res-legend, .home-metric > .legend-chips"; + const LEGEND_PATHS = {view: "legend.views", tile: "legend.tiles"}; + const legendView = {buttons: new WeakMap()}; + + const legendShown = (path, key) => ViewStore.get(path)[key] !== false; + + function legendToggle(path, key) { + const show = !legendShown(path, key); + ViewStore.update(path, (flags) => { + const next = {...flags}; + delete next[key]; + return show ? next : {...next, [key]: false}; + }); + } + + function legendButton(path, key) { + const button = iconBtn("bi-info-circle", "Legend", "btn small ghost legend-toggle", (event) => { + event.stopPropagation(); + legendToggle(path, key); + }); + button.dataset.legendKey = key; + button.addEventListener("pointerdown", (event) => event.stopPropagation()); + return button; + } + + function paintLegend(owner, button, shown) { + const state = shown ? "shown" : "hidden"; + if (owner.dataset.legend !== state) { + owner.dataset.legend = state; + } + if (button.getAttribute("aria-pressed") !== String(shown)) { + button.setAttribute("aria-pressed", String(shown)); + button.title = `Legend: ${shown ? "shown, press to hide it" : "hidden, press to show it"}`; + } + } + + /** + * @param owner - a panel of a view or a Home tile. + * @param path - the view-store key of its kind, legend.views or legend.tiles. + * @param key - its panel id or pin key there. + * @param place - (button) => void putting the button in its spot, or null when the owner holds no legend. + */ + function legendFor(owner, path, key, place) { + const made = legendView.buttons.get(owner); + if (!place) { + if (made) { + made.remove(); + legendView.buttons.delete(owner); + } + if (owner.dataset.legend) { + delete owner.dataset.legend; + } + return; + } + const button = made && made.dataset.legendKey === key ? made : legendButton(path, key); + legendView.buttons.set(owner, button); + place(button); + paintLegend(owner, button, legendShown(path, key)); + } + + const ownOf = (host, selector) => [...host.querySelectorAll(selector)].find((node) => node.closest(Panels.HOSTS) === host) || null; + + function markLegends() { + for (const host of document.querySelectorAll("#main [data-panel]")) { + if (host.closest(".home-tile")) { + continue; + } + const star = ownOf(host, ".star"); + legendFor(host, LEGEND_PATHS.view, host.dataset.panel, star && ownOf(host, LEGEND_PARTS) ? (button) => star.nextElementSibling !== button && star.after(button) : null); + } + for (const tile of document.querySelectorAll(".home-tile[data-pin]")) { + const open = tile.querySelector(".home-open"); + legendFor(tile, LEGEND_PATHS.tile, tile.dataset.pin, tile.querySelector(`.home-body :is(${LEGEND_PARTS})`) ? (button) => open.previousElementSibling !== button && open.before(button) : null); + } + } + + function legendBoot() { + new MutationObserver(markLegends).observe(document.body, {childList: true, subtree: true}); + ViewStore.on("legend", () => { + markLegends(); + drawHome(); + drawResources(); + }); + markLegends(); + } diff --git a/orchestrator/templates/style-legend-chips.css b/orchestrator/templates/style-legend-chips.css index edf9969..763839c 100644 --- a/orchestrator/templates/style-legend-chips.css +++ b/orchestrator/templates/style-legend-chips.css @@ -5,3 +5,4 @@ .legend-chip:hover { border-color: var(--line-strong); } .legend-chip:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } .legend-chip[aria-pressed="false"] { color: var(--muted); text-decoration: line-through; opacity: 0.5; } +[data-legend="hidden"] :is(.res-legend, .home-metric > .legend-chips), [data-legend="hidden"] .legend:not(:has(> .star)), [data-legend="hidden"] .legend > :not(.star, .legend-toggle) { display: none; } diff --git a/tests/e2e/test_legend_toggle_e2e.py b/tests/e2e/test_legend_toggle_e2e.py new file mode 100644 index 0000000..96c949f --- /dev/null +++ b/tests/e2e/test_legend_toggle_e2e.py @@ -0,0 +1,230 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import time +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import test_workbench_w4_e2e as w4 +from hub_case import HubCase + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/legend-toggle-shots")) +TILE = "metric:tokens/interval/all" +PINS = [ + {"kind": "metric", "id": "tokens/interval/all", "w": 6, "h": 4, "view": {"chart": "tokens", "tokens": "interval", "shown": None}}, + {"kind": "panel", "id": "tasks/burn", "w": 6, "h": 4}, + {"kind": "panel", "id": "stream", "w": 6, "h": 4}, +] +OWN = ("agents/orbit", "agents/chord", "agents/swimlane", "artifacts/orbit", "artifacts/chord", "artifacts/swimlane", "tasks/rasci", "tasks/gantt", "tasks/burn") +EXPECTED = { + **{screen: [] for screen in base.SCREENS}, + **{screen: [screen] for screen in OWN}, + "home": sorted([TILE, "panel:tasks/burn"]), + "resources": ["resources-hardware", "resources-tokens"], +} +READ = """ + const PARTS = ".legend > :not(.star, .legend-toggle), .res-legend, .home-metric > .legend-chips"; + const owners = () => [...all("#main [data-panel]").filter((host) => !host.closest(".home-tile")), ...all(".home-tile[data-pin]")]; + const keyOf = (owner) => owner.dataset.pin || owner.dataset.panel; + const ownerOf = (key) => owners().find((node) => keyOf(node) === key) || null; + const toggleOf = (owner) => (owner ? owner.querySelector(`.legend-toggle[data-legend-key="${keyOf(owner)}"]`) : null); + const infoKeys = () => owners().filter((owner) => owner.getClientRects().length && toggleOf(owner)).map(keyOf).sort(); + const shownParts = (owner) => all(PARTS, owner).filter((node) => node.getClientRects().length).length; + const stored = async () => (await (await fetch("/api/view", {cache: "no-store"})).json()); + const storedUntil = async (test, ms) => { + const end = Date.now() + ms; + while (Date.now() < end) { + const found = await stored(); + if (test(found)) { + return found; + } + await sleep(200); + } + return null; + }; + const go = async (hash) => { + location.hash = hash; + return screenShown(8000); + }; + const tile = () => document.querySelector(`.home-tile[data-pin="@TILE@"]`); + const plot = () => tile() && tile().querySelector(".res-plot svg"); + const tokens = () => document.querySelector('#main [data-panel="resources-tokens"]'); + const agents = () => [...new Set(all("svg [data-agent]", tokens()).map((node) => node.dataset.agent))].sort(); + const wide = () => document.documentElement.scrollWidth > innerWidth + 1; +""" +SCAN = """(async () => {@HELPERS@@READ@ + const flip = async (key) => { + const path = ownerOf(key).dataset.pin ? "tiles" : "views"; + const button = () => toggleOf(ownerOf(key)); + const placed = path === "tiles" ? button().nextElementSibling.classList.contains("home-open") : button().previousElementSibling.classList.contains("star"); + const before = shownParts(ownerOf(key)); + button().click(); + const hidden = Boolean(await until(() => ownerOf(key) && ownerOf(key).dataset.legend === "hidden" && shownParts(ownerOf(key)) === 0 && button().getAttribute("aria-pressed") === "false", 4000)); + const kept = Boolean(await storedUntil((view) => view.legend[path][key] === false, 4000)); + button().click(); + const back = Boolean(await until(() => ownerOf(key) && ownerOf(key).dataset.legend === "shown" && shownParts(ownerOf(key)) > 0 && button().getAttribute("aria-pressed") === "true", 4000)); + const cleared = Boolean(await storedUntil((view) => !Object.hasOwn(view.legend[path], key), 4000)); + return {key, placed, before: before > 0, hidden, kept, back, cleared}; + }; + await Promise.all([ViewStore.update("legend.views", () => ({})), ViewStore.update("legend.tiles", () => ({}))]); + const seen = {}; + const flips = []; + for (const [screen, expected] of Object.entries(@EXPECTED@)) { + await go(`#${screen}`); + const keys = await until(() => (JSON.stringify(infoKeys()) === JSON.stringify(expected) ? infoKeys() : null), 8000); + seen[screen] = keys || infoKeys(); + for (const key of keys || []) { + flips.push(await flip(key)); + } + } + return {seen, flips, wide: wide(), violations: window.e2eViolations || null}; +})()""" +ROOM = """(async () => {@HELPERS@@READ@ + await Promise.all([ViewStore.update("legend.views", () => ({})), ViewStore.update("legend.tiles", () => ({})), ViewStore.update("resources.hidden", () => [])]); + await go("#home"); + if (!(await until(() => plot() && tile().querySelector(".legend-chip"), 15000))) { + return {error: text(document.getElementById("main"))}; + } + await sleep(600); + const tall = () => plot().getBoundingClientRect().height; + const before = tall(); + toggleOf(tile()).click(); + const grown = Boolean(await until(() => plot() && tall() > before + 4, 6000)); + const tileHidden = shownParts(tile()) === 0; + await go("#resources"); + const chip = () => tokens() && tokens().querySelector('.legend-chip[data-chip="agent:IAM"]'); + if (!(await until(chip, 15000))) { + return {error: text(document.getElementById("main"))}; + } + const viewShown = shownParts(tokens()) > 0 && toggleOf(tokens()).getAttribute("aria-pressed") === "true"; + chip().click(); + await storedUntil((view) => view.resources.hidden.includes("agent:IAM"), 4000); + toggleOf(tokens()).click(); + await until(() => tokens().dataset.legend === "hidden" && shownParts(tokens()) === 0, 4000); + await sleep(800); + const chart = agents(); + await go("#home"); + await until(plot, 8000); + const tileStill = tile().dataset.legend === "hidden"; + toggleOf(tile()).click(); + const tileBack = Boolean(await until(() => shownParts(tile()) > 0, 4000)); + const legend = await storedUntil((view) => view.legend.views["resources-tokens"] === false && !Object.hasOwn(view.legend.tiles, "@TILE@"), 4000); + await sleep(600); + return {grown, tileHidden, viewShown, chart, tileStill, tileBack, legend: legend && legend.legend, wide: wide(), violations: window.e2eViolations || null}; +})()""" +HIDE = """(async () => {@HELPERS@@READ@ + await go("#home"); + await until(() => plot() && toggleOf(tile()), 15000); + toggleOf(tile()).click(); + const hidden = Boolean(await until(() => shownParts(tile()) === 0, 4000)); + await storedUntil((view) => view.legend.tiles["@TILE@"] === false, 4000); + await sleep(600); + return {hidden, wide: wide()}; +})()""" +KEPT = """(async () => {@HELPERS@@READ@ + if (!(await screenShown(8000)) || !(await until(() => tokens() && toggleOf(tokens()) && agents().length, 15000))) { + return {error: text(document.getElementById("main"))}; + } + await sleep(600); + const view = {legend: tokens().dataset.legend, pressed: toggleOf(tokens()).getAttribute("aria-pressed"), parts: shownParts(tokens()), chart: agents()}; + const found = await stored(); + return {view, stored: found.legend, hidden: found.resources.hidden, wide: wide(), violations: window.e2eViolations || null}; +})()""" + + +def probe(template: str) -> str: + names = {"@HELPERS@": base.HELPERS, "@READ@": READ, "@EXPECTED@": json.dumps(EXPECTED), "@TILE@": TILE} + for key, value in names.items(): + template = template.replace(key, value) + return template + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestLegendToggle(HubCase): + seed = base.OrchestratorE2ECase.seed + subagents = base.OrchestratorE2ECase.subagents + drive = base.OrchestratorE2ECase.drive + sample = w4.TestWorkbenchResources.sample + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.seed() + now = int(time.time()) + self.start = now - now % 60 - w4.ROWS * 60 + hour = self.start - self.start % 3600 + tokens = [{"t": hour + step * 3600, "agent": agent, "model": "claude-opus-5-5", "input": 1000 * (step + 1), "output": 500, "cache_read": 20000, "cache_write": 1000} for step in range(7) for agent in ("Skills", "IAM")] + folder = self.kept / "resources" + folder.mkdir() + (folder / "samples.jsonl").write_text(self.jsonl([self.sample(index) for index in range(w4.ROWS)]), encoding="utf-8") + (folder / "tokens.jsonl").write_text(self.jsonl([row for row in tokens if row["t"] <= now]), encoding="utf-8") + status, _, body = self.call("PATCH", "/api/view", json.dumps({"set": {"home.pins": PINS}, "expect": {"home.pins": []}}).encode(), {**self.guard(self.host), "Content-Type": "application/json"}) + self.assertEqual(status, 200, body) + + def steps(self, browser: str) -> list[dict]: + steps = [] + for width, height in base.WIDTHS: + shot = OUT / f"{browser}-{width}" + steps += [ + {"width": width, "height": height, "url": f"{self.base}?{width}-scan#home", "wait": 1200, "probe": probe(SCAN), "shot": None}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(ROOM), "shot": f"{shot}-home-shown.png"}, + {"width": width, "height": height, "url": f"{self.base}?{width}-kept#resources", "wait": 1200, "probe": probe(KEPT), "shot": f"{shot}-resources-hidden.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(HIDE), "shot": f"{shot}-home-hidden.png"}, + ] + return steps + + def check(self, data: dict, browser: str) -> None: + results = iter(data["results"]) + for width, _ in base.WIDTHS: + scan, room, kept, hide = (next(results) for _ in range(4)) + with self.subTest(browser=browser, width=width): + self.assertEqual(scan["seen"], EXPECTED) + self.assertEqual([flip for flip in scan["flips"] if set(flip.values()) != {flip["key"], True}], []) + self.assertEqual(len(scan["flips"]), sum(len(keys) for keys in EXPECTED.values())) + self.assertEqual((scan["wide"], w4.quiet(scan["violations"])), (False, [])) + self.assertNotIn("error", room, room) + self.assertEqual({key: room[key] for key in ("grown", "tileHidden", "viewShown", "tileStill", "tileBack")}, dict.fromkeys(("grown", "tileHidden", "viewShown", "tileStill", "tileBack"), True), room) + self.assertEqual(room["chart"], ["Skills"]) + self.assertEqual(room["legend"], {"views": {"resources-tokens": False}, "tiles": {}}) + self.assertEqual((room["wide"], w4.quiet(room["violations"])), (False, [])) + self.held(kept, {"views": {"resources-tokens": False}, "tiles": {}}) + self.assertEqual((hide["hidden"], hide["wide"]), (True, False)) + + def held(self, kept: dict, legend: dict) -> None: + self.assertNotIn("error", kept, kept) + self.assertEqual(kept["view"], {"legend": "hidden", "pressed": "false", "parts": 0, "chart": ["Skills"]}) + self.assertEqual((kept["stored"], kept["hidden"]), (legend, ["agent:IAM"])) + self.assertEqual((kept["wide"], w4.quiet(kept["violations"])), (False, [])) + + def other(self, driver: str, binary: str) -> None: + width, height = base.WIDTHS[0] + data = self.drive([{"width": width, "height": height, "url": f"{self.base}?other#resources", "wait": 1200, "probe": probe(KEPT), "shot": None}], None, driver, binary, init=w4.GUARD) + self.held(data["results"][0], {"views": {"resources-tokens": False}, "tiles": {TILE: False}}) + + def test_chromium_hides_and_shows_legends_per_tile_and_view_and_firefox_sees_the_state(self): + data = self.drive(self.steps("chromium"), None, init=w4.GUARD) + (OUT / "chromium-legend.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + self.check(data, "chromium") + firefox = shutil.which(os.environ.get("FIREFOX", "firefox")) + if firefox: + self.other("bidi.mjs", firefox) + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_hides_and_shows_legends_per_tile_and_view_and_chromium_sees_the_state(self): + data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=w4.GUARD) + (OUT / "firefox-legend.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, "firefox") + self.other("cdp.mjs", os.environ.get("CHROMIUM", "chromium")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hub_view.py b/tests/test_hub_view.py index 740f45a..1b6b88b 100644 --- a/tests/test_hub_view.py +++ b/tests/test_hub_view.py @@ -16,6 +16,7 @@ from kvb_orchestrator.errors import Conflict, ToolError from kvb_orchestrator.handler import BODY_LIMIT from kvb_orchestrator.viewstore import ( CHANGE_LIMIT, + LEGEND_PANELS, VIEW, VIEW_LIMIT, ViewStore, @@ -33,6 +34,7 @@ FULL = { "burn": {"overlays": ["fix", "score"]}, "home": {"pins": [{"kind": "panel", "id": "resources-hardware", "w": 12, "h": 4}, {"kind": "task", "id": "work/feature", "w": 1, "h": 12}]}, "kanban": {"hidden": ["line"]}, + "legend": {"views": {"resources-tokens": False, "tasks/burn": True}, "tiles": {"panel:resources-hardware": False}}, } PIN ={"kind": "panel", "id": "resources-hardware", "w": 6, "h": 3} EMBEDDED = re.compile(r'') @@ -289,7 +291,7 @@ class TestViewDocument(unittest.TestCase): def test_the_defaults_and_a_full_document_pass_unchanged(self): self.assertEqual(valid_view(copy.deepcopy(VIEW)), VIEW) self.assertEqual(valid_view(copy.deepcopy(FULL)), FULL) - self.assertEqual(VIEW, {"resources": {"hidden": [], "tokens": "interval", "combined": False, "combinedHidden": []}, "burn": {"overlays": []}, "home": {"pins": []}, "kanban": {"hidden": []}}) + self.assertEqual(VIEW, {"resources": {"hidden": [], "tokens": "interval", "combined": False, "combinedHidden": []}, "burn": {"overlays": []}, "home": {"pins": []}, "kanban": {"hidden": []}, "legend": {"views": {}, "tiles": {}}}) def test_unknown_or_missing_keys_and_malformed_values_are_refused(self): def changed(section: str | None, key: str | None, value: object) -> dict: @@ -331,11 +333,28 @@ class TestViewDocument(unittest.TestCase): "pin id too long": changed("home", "pins", [{**pin, "id": "i" * 201}]), "pin unknown key": changed("home", "pins", [{**pin, "x": 1}]), "pin twice": changed("home", "pins", [pin, dict(pin)]), + "legend section missing": {key: value for key, value in FULL.items() if key != "legend"}, + "legend unknown key": changed("legend", "pins", {}), + "legend views not a map": changed("legend", "views", ["tasks/burn"]), + "legend of an unknown panel": changed("legend", "views", {"stream": False}), + "legend of a panel without one": changed("legend", "views", {"agents/3d": False}), + "legend shown as a number": changed("legend", "views", {"tasks/burn": 0}), + "legend shown as text": changed("legend", "tiles", {"panel:resources-hardware": "false"}), + "legend tile key without kind": changed("legend", "tiles", {"resources-hardware": False}), + "legend tile key with a space": changed("legend", "tiles", {"panel:resources hardware": False}), } for name, doc in cases.items(): with self.subTest(case=name), self.assertRaises(ToolError): valid_view(doc) + def test_every_legend_panel_keeps_its_flag_and_a_tile_flag_leaves_with_its_pin(self): + doc = copy.deepcopy(FULL) + doc["legend"]["views"] = dict.fromkeys(LEGEND_PANELS, False) + doc["legend"]["tiles"] = {"panel:resources-hardware": False, "task:work/feature": True, "panel:stream": False} + self.assertEqual(valid_view(doc)["legend"], {"views": dict.fromkeys(LEGEND_PANELS, False), "tiles": {"panel:resources-hardware": False, "task:work/feature": True}}) + doc["home"]["pins"] = doc["home"]["pins"][1:] + self.assertEqual(valid_view(doc)["legend"]["tiles"], {"task:work/feature": True}) + def test_the_hub_digests_a_selection_exactly_as_panels_js_does(self): texts = ["", "host:CPU", "burn:done\nhost:CPU", "agent:\N{LATIN CAPITAL LETTER A WITH DIAERESIS}\N{EURO SIGN}\U0001f600", "x" * 5000] self.assertEqual([viewstore.digest(text) for text in texts], client_digests(*texts)) @@ -716,6 +735,19 @@ class TestHubView(HubCase): self.assertIsNotNone(embedded) self.assertEqual(json.loads(embedded.group(1)), FULL) + def test_legend_flags_answer_400_for_an_unknown_panel_or_a_non_boolean_and_a_tile_flag_leaves_with_its_pin(self): + for views in ({"stream": False}, {"tasks/burn": "hidden"}, {"tasks/burn": None}): + with self.subTest(views=views): + status, body = self.write({"legend.views": views}) + self.assertEqual(status, 400, body) + self.assertEqual(self.view(), VIEW) + self.assertEqual(self.write({"home.pins": [PIN], "legend.views": {"tasks/burn": False}})[0], 200) + self.assertEqual(self.write({"legend.tiles": {"panel:resources-hardware": False}})[0], 200) + self.reopen() + self.assertEqual(self.view()["legend"], {"views": {"tasks/burn": False}, "tiles": {"panel:resources-hardware": False}}) + self.assertEqual(self.write({"home.pins": []})[0], 200) + self.assertEqual(self.view()["legend"], {"views": {"tasks/burn": False}, "tiles": {}}) + def test_a_broken_stored_file_falls_back_to_the_defaults(self): (self.state / "view.json").write_text('{"resources": {"hidden": ["bad id"]}}', encoding="utf-8") self.reopen()