"""Drive a UI review of the web client from an albedo python kernel. Each review run copies the home seed.py built, starts the fake model, a private daemon, `albedo web` and a Chrome page, and hands back a Review whose methods click, type, drag, read the board and take screenshots:: import sys; sys.path.insert(0, "test/manual/ux"); import kit ui = await kit.start("unique-run-name") try: await ui.load("sections") show_image(await ui.shot("sections")) finally: await ui.stop() Windows are named w0, w1, ... in the order the active board first opened them, the same names layout() prints. Coordinates are page CSS pixels. """ from __future__ import annotations import asyncio import base64 import hashlib import importlib import inspect import json import os import re import shutil import time from collections.abc import Awaitable, Callable from dataclasses import dataclass, field from pathlib import Path from typing import Any, BinaryIO from seed import ROOT, daemon_env, fake_model_argv, web_build from lifecycle_support import acquire_base, reserve_run from lifecycle_support import processes as home_processes, reap as reap_home BASE = Path(os.environ.get("ALBEDO_UX", "/tmp/albedo-review")).resolve() CLI = str(ROOT / "cli/bin/albedo") # The kernel's own bindings (run, browser, show_image); this module is not a cell. tools: Any = importlib.import_module("albedo") ALT, CTRL, META, SHIFT = 1, 2, 4, 8 LEAST = 160 # Scenario minimum, not a refusal rule for every production drop. BOARD = """const active = JSON.parse(localStorage.getItem('albedo.boards.v1') ?? '{}').active; const board = JSON.parse(localStorage.getItem('albedo.board.v3:' + active) ?? 'null'); const ids = Object.keys(board?.windows ?? {}); const label = (id) => 'w' + ids.indexOf(id);""" WINDOWS = ( "() => {" + BOARD + """ return [...document.querySelectorAll('.board-view .window-slot')].filter((s) => !s.closest('.window-parking')).map((s) => { const h = s.querySelector('.window-handle h2') ?? s.querySelector('header h2'); const hr = h?.getBoundingClientRect(); const r = s.getBoundingClientRect(); return { w: label(s.dataset.id), id: s.dataset.id, type: s.dataset.type, place: s.dataset.place, shown: s.checkVisibility() && r.width > 0, selected: s.classList.contains('selected'), head: hr ? [Math.round(hr.x + 20), Math.round(hr.y + hr.height / 2)] : null, box: [r.x, r.y, r.width, r.height].map(Math.round) }; }); }""" ) LAYOUT = ( "() => {" + BOARD + """ if (!board) return null; const show = (t) => (t.name ? JSON.stringify(t.name) + ':' : '') + (t.kind === 'leaf' ? label(t.window) : t.kind + (t.kind === 'split' ? '-' + t.axis : '') + '(' + t.children.map((c) => show(c.tile ?? c)).join(',') + ')'); return show(board.root); }""" ) CANVAS_TILES = """() => [...document.querySelectorAll('.canvas-tile.nested')].map((c) => { const r = c.getBoundingClientRect(); return [r.x, r.y, r.width, r.height].map(Math.round); })""" OVERLAY = """() => { const p = document.querySelector('.docking .preview')?.getBoundingClientRect(); return { hint: document.querySelector('.docking .hint')?.textContent.trim() ?? null, preview: p ? [p.x, p.y, p.width, p.height].map(Math.round) : null }; }""" FOCUSED = """() => { const a = document.activeElement; const r = a.getBoundingClientRect(); return { tag: a.tagName, cls: String(a.className).slice(0, 60), label: a.getAttribute('aria-label') ?? a.title ?? '', window: a.closest('.window-slot')?.dataset.id ?? null, box: [r.x, r.y, r.width, r.height].map(Math.round) }; }""" # Collects page errors on every document, so a reload keeps listening. ERRORS = """window.__albedoAudit = true; window.__errs = []; addEventListener('error', (e) => __errs.push(String(e.message))); addEventListener('unhandledrejection', (e) => __errs.push('unhandled: ' + String(e.reason))); const consoleError = console.error; console.error = (...a) => { __errs.push(a.map(String).join(' ')); consoleError(...a); };""" SHIFTED = dict(zip("1234567890-=[]\\;',./`", '!@#$%^&*()_+{}|:"<>?~')) UNSHIFTED = {v: k for k, v in SHIFTED.items()} PUNCTUATION = { "-": ("Minus", 189), "=": ("Equal", 187), "[": ("BracketLeft", 219), "]": ("BracketRight", 221), "\\": ("Backslash", 220), ";": ("Semicolon", 186), "'": ("Quote", 222), ",": ("Comma", 188), ".": ("Period", 190), "/": ("Slash", 191), "`": ("Backquote", 192), " ": ("Space", 32), } NAMED = { "ArrowLeft": 37, "ArrowUp": 38, "ArrowRight": 39, "ArrowDown": 40, "Backspace": 8, "Tab": 9, "Enter": 13, "Escape": 27, "Delete": 46, "Home": 36, "End": 35, "PageUp": 33, "PageDown": 34, } # Chrome on a Mac runs Cmd-A only as an editor command; the key alone selects nothing. COMMANDS = {("a", META): "selectAll"} def key_event(k: str, mods: int = 0, text: str | None = None) -> dict: """The CDP keyDown for k with modifiers, as a US keyboard sends it: a shifted symbol carries Shift and its own text, so key('1', SHIFT) is '!'.""" if k in UNSHIFTED: mods |= SHIFT elif mods & SHIFT and k in SHIFTED: k = SHIFTED[k] elif mods & SHIFT and len(k) == 1: k = k.upper() base = UNSHIFTED.get(k, k) if k in NAMED: code, vk = k, NAMED[k] elif base.isdigit(): code, vk = f"Digit{base}", ord(base) elif base.isalpha() and len(base) == 1: code, vk = f"Key{base.upper()}", ord(base.upper()) elif base in PUNCTUATION: code, vk = PUNCTUATION[base] else: raise ValueError(f"no key code for {k!r}") if text is None and not mods & (ALT | CTRL | META): text = "\r" if k == "Enter" else k if len(k) == 1 else None event: dict[str, Any] = { "key": k, "code": code, "windowsVirtualKeyCode": vk, "modifiers": mods, } if text: event |= {"type": "keyDown", "text": text, "unmodifiedText": text} else: event["type"] = "rawKeyDown" command = COMMANDS.get((k.lower() if len(k) == 1 else k, mods & ~SHIFT)) if command: event["commands"] = [command] return event def slug(label: str) -> str: return re.sub(r"[^a-z0-9]+", "-", label.lower()).strip("-")[:50] or "shot" @dataclass class Review: """One review run: its home, its processes, and the Chrome page on it.""" name: str run: Path env: dict[str, str] url: str = "" page: Any = None browser: Any = None jobs: list[Any] = field(default_factory=list) _at: tuple[float, float] = (0, 0) lease: BinaryIO | None = None @property def home(self) -> Path: return self.run / "home" async def js(self, source: str, *args: Any) -> Any: """Evaluate a function source on the page, passing args as JSON.""" if args: source = f"() => ({source})(...{json.dumps(list(args))})" return await self.page.evaluate(source) # the page async def size(self, width: int, height: int) -> None: """Set the viewport; 760 px or less is the phone layout.""" await self.page.cdp.send( "Emulation.setDeviceMetricsOverride", { "width": width, "height": height, "deviceScaleFactor": 1, "mobile": width <= 760, }, ) async def media(self, *, dark: bool = False, reduced_motion: bool = False) -> None: """Emulate prefers-color-scheme and prefers-reduced-motion. A theme chosen in settings or with palette('theme: …') is saved and wins over this until palette('theme: system').""" features = [ {"name": "prefers-color-scheme", "value": "dark" if dark else "light"}, { "name": "prefers-reduced-motion", "value": "reduce" if reduced_motion else "no-preference", }, ] await self.page.cdp.send("Emulation.setEmulatedMedia", {"features": features}) async def reload(self) -> None: await self.page.goto(self.url) await asyncio.sleep(2.5) async def errors(self) -> list[str]: """Errors and rejections the page threw since it last loaded, and 'stale tether: …' for each line the tethers' audit found drawn wrong at rest (see Tethers.svelte).""" return await self.page.evaluate( """() => [...(window.__errs ?? []), ...(window.__albedoStale ?? []).map((s) => `stale tether: ${s.differ.join(',')} at ${s.at}ms after ${s.reason}`)]""" ) async def storage(self) -> dict[str, str]: return await self.page.evaluate( "() => Object.fromEntries(Object.keys(localStorage).map((k) => [k, localStorage.getItem(k)]))" ) async def restore(self, saved: dict[str, str]) -> None: """Replace localStorage with saved and reload.""" await self.js( "(s) => { localStorage.clear(); for (const [k, v] of Object.entries(s)) localStorage.setItem(k, v); }", saved, ) await self.reload() async def fresh(self, layout: str | None = "tiles") -> None: """An empty board, in the layout given ('tiles' or 'canvas').""" await self.restore({}) if layout: await self.palette(f"layout: {layout}") async def load(self, scenario: str) -> None: """Put the page on a prepared board (see SCENARIOS). It replaces the localStorage, including unsent board notes. Daemon history remains. Preference cookies are separate; use a new run for a fresh home.""" await self.restore(await self.built(scenario)) async def built(self, scenario: str) -> dict[str, str]: """The localStorage a scenario builds, cached per seed, web build and scenario source.""" _, build = SCENARIOS[scenario] stamp = hashlib.sha256() stamp.update(str((BASE / "seed/albedo.sqlite").stat().st_mtime_ns).encode()) stamp.update(Path(self.env["ALBEDO_WEB_DIST"], "index.html").read_bytes()) stamp.update(inspect.getsource(build).encode()) cache = BASE / "cache" / f"{scenario}.json" if cache.exists(): saved = json.loads(cache.read_text()) if saved["stamp"] == stamp.hexdigest(): return saved["storage"] viewport = await self.page.evaluate("() => [innerWidth, innerHeight]") await self.size(1440, 900) await build(self) await asyncio.sleep(0.6) cramped = [ w for w in await self.windows() if w["shown"] and w["place"] == "tile" and min(w["box"][2:]) < LEAST ] cramped += [ box for box in await self.page.evaluate(CANVAS_TILES) if min(box[2:]) < LEAST ] saved = await self.storage() await self.size(*viewport) if cramped: raise AssertionError( f"{scenario}: scenario tiles below the {LEAST}px minimum: {cramped}" ) cache.parent.mkdir(exist_ok=True) cache.write_text(json.dumps({"stamp": stamp.hexdigest(), "storage": saved})) return saved # reading the board async def windows(self) -> list[dict]: """Every window on the active board: w (its name), id, type, place (tile, tab, group, canvas, float), shown (false for a hidden tab), selected, box [x, y, w, h] and head, a point on its title bar to drag by.""" return await self.page.evaluate(WINDOWS) async def window(self, w: str) -> dict: return next(x for x in await self.windows() if x["w"] == w) async def layout(self) -> str | None: """The active board's tree, e.g. split-row(tabs(w1,w0),"research":split-row(w2,canvas(),w3)).""" return await self.page.evaluate(LAYOUT) async def overlay(self) -> dict: """What a drag shows: the dock's hint and its preview box.""" return await self.page.evaluate(OVERLAY) async def focused(self) -> dict: """The focused element: tag, class, label, the window it is in, box.""" return await self.page.evaluate(FOCUSED) async def toast(self) -> str | None: """The board's status line (what the last command said) or its close note, if showing.""" return await self.page.evaluate( "() => document.querySelector('.say, .close-note')?.textContent.trim() ?? null" ) async def mark(self) -> None: """Tag every mounted window, so remounted() can tell which were made again.""" await self.page.evaluate( "() => document.querySelectorAll('.window-host').forEach((h) => { if (h.firstElementChild) h.firstElementChild.__mark = true; })" ) async def remounted(self) -> list[str]: """Windows mounted since mark(): moves should leave this empty.""" return await self.page.evaluate( "() => [...document.querySelectorAll('.window-host')].filter((h) => !h.firstElementChild?.__mark).map((h) => h.dataset.window)" ) # input async def raw( self, kind: str, x: float, y: float, *, buttons: int = 1, mods: int = 0, count: int = 1, ) -> None: """One CDP mouse event: mousePressed, mouseMoved or mouseReleased.""" await self.page.cdp.send( "Input.dispatchMouseEvent", { "type": kind, "x": x, "y": y, "button": "left", "buttons": buttons, "clickCount": count, "modifiers": mods, }, ) async def click(self, x: float, y: float, *, mods: int = 0, count: int = 1) -> None: """Hover, then press and release like a hand: some controls ignore a click with no hover first or no gap between press and release. count=2 is a double click.""" await self.raw("mouseMoved", x, y, buttons=0, mods=mods) await asyncio.sleep(0.1) for n in range(1, count + 1): await self.raw("mousePressed", x, y, mods=mods, count=n) await asyncio.sleep(0.08) await self.raw("mouseReleased", x, y, buttons=0, mods=mods, count=n) await asyncio.sleep(0.4) async def pick(self, w: str) -> None: """Cmd-click a window's title bar, adding it to the picked set.""" head = (await self.window(w))["head"] await self.click(*head, mods=META) async def drag( self, a: tuple[float, float], b: tuple[float, float], *, steps: int = 15, mods: int = 0, hold: float = 0.3, ) -> dict: """Press at a, glide to b, wait, release. Returns the overlay seen just before release.""" await self.hold(a, mods=mods) seen = await self.probe(*b, steps=steps, mods=mods, wait=hold) await self.release(*b, mods=mods) return seen async def hold(self, a: tuple[float, float], *, mods: int = 0) -> None: """Press at a and start a carry. Then probe() to look and release() to drop.""" await self.raw("mouseMoved", *a, buttons=0, mods=mods) await self.raw("mousePressed", *a, mods=mods) for n in range(1, 6): await self.raw("mouseMoved", a[0] + 2 * n, a[1] + 2 * n, mods=mods) await asyncio.sleep(0.03) self._at = (a[0] + 10, a[1] + 10) async def probe( self, x: float, y: float, *, steps: int = 6, mods: int = 0, wait: float = 0.35 ) -> dict: """While holding: glide to (x, y) and return the overlay there.""" x0, y0 = self._at for n in range(1, steps + 1): await self.raw( "mouseMoved", x0 + (x - x0) * n / steps, y0 + (y - y0) * n / steps, mods=mods, ) await asyncio.sleep(0.03) self._at = (x, y) await asyncio.sleep(wait) return await self.overlay() async def release(self, x: float, y: float, *, mods: int = 0) -> None: await self.raw("mouseReleased", x, y, buttons=0, mods=mods) await asyncio.sleep(0.6) async def wheel( self, x: float, y: float, dx: float, dy: float, *, mods: int = 0 ) -> None: """Scroll at a point; on a canvas plain wheel pans and Ctrl zooms.""" await self.page.cdp.send( "Input.dispatchMouseEvent", { "type": "mouseWheel", "x": x, "y": y, "deltaX": dx, "deltaY": dy, "modifiers": mods, }, ) await asyncio.sleep(0.4) async def key(self, k: str, mods: int = 0, *, text: str | None = None) -> None: """Press one key. key('k', META) is Cmd-K, key('ArrowRight', ALT | SHIFT), key('!') or key('1', SHIFT) is ⇧1. Enter clicks a focused button.""" down = key_event(k, mods, text) await self.page.cdp.send("Input.dispatchKeyEvent", down) up = { "type": "keyUp", **{ n: down[n] for n in ("key", "code", "windowsVirtualKeyCode", "modifiers") }, } await self.page.cdp.send("Input.dispatchKeyEvent", up) await asyncio.sleep(0.05) async def type(self, text: str) -> None: """Insert text at the focus, as a paste or an IME does.""" await self.page.cdp.send("Input.insertText", {"text": text}) async def blur(self) -> None: await self.page.evaluate("() => document.activeElement?.blur()") async def palette(self, command: str) -> str | None: """Run a command palette entry: Cmd-K, type, Enter. Returns what the board said back, if anything. palette('layout: canvas'), palette('theme: dark').""" await self.blur() await self.key("k", META) await asyncio.sleep(0.4) await self.type(command) await asyncio.sleep(0.3) await self.key("Enter") await asyncio.sleep(0.9) return await self.toast() async def palette_items(self, query: str) -> list[str]: """The palette entries a query shows, without running one.""" await self.blur() await self.key("k", META) await asyncio.sleep(0.4) await self.type(query) await asyncio.sleep(0.3) items = await self.page.evaluate( "() => [...document.querySelectorAll('.item .label')].map((e) => e.textContent.trim())" ) await self.key("Escape") return items async def open_chat(self, name: str) -> None: """Click a chat's row in the sidebar by its name.""" point = await self.js( """(name) => { const b = [...document.querySelectorAll('aside .row .main')] .find((b) => b.querySelector('.name').textContent.replace('★', '').trim() === name); if (!b) return null; b.scrollIntoView({ block: 'center' }); const r = b.getBoundingClientRect(); return [r.x + 40, r.y + r.height / 2]; }""", name, ) if point is None: raise LookupError(f"no sidebar row named {name!r}") await self.click(*point) await asyncio.sleep(0.8) async def say(self, w: str, text: str) -> None: """Type into a chat window's composer and send it.""" window = await self.window(w) await self.js( '(id) => document.querySelector(`.window-slot[data-id="${CSS.escape(id)}"] .editor`).focus()', window["id"], ) await self.type(text) await self.key("Enter") await asyncio.sleep(0.5) async def rename_at(self, x: float, y: float, name: str) -> None: """Double-click a name (a section, a tab, a group) and type a new one; '' clears it.""" await self.click(x, y, count=2) await self.key("a", META) if name: await self.type(name) else: await self.key("Backspace") await self.key("Enter") await asyncio.sleep(0.5) async def group(self, name: str = "") -> None: """Alt-G: make the picked windows a section, named name.""" await self.key("g", ALT) await asyncio.sleep(0.6) if name: await self.type(name) await self.key("Enter") await asyncio.sleep(0.5) await self.blur() async def scroll(self, w: str, top: float | None = None) -> list[int]: """A chat window's [scrollTop, scrollHeight, clientHeight]; sets scrollTop first when given.""" window = await self.window(w) return await self.js( """(id, top) => { const e = document.querySelector(`.window-slot[data-id="${CSS.escape(id)}"] .scroller`); if (top !== null) e.scrollTop = top; return [e.scrollTop, e.scrollHeight, e.clientHeight].map(Math.round); }""", window["id"], top, ) async def note(self, passage: str, body: str, *, nth: int = 0) -> str: """Select the nth passage of chat text that contains passage, leave a note on it with body, and return the new note's window name.""" await self.blur() # a focused composer reads as typing, and selecting elsewhere there offers no note found = await self.js( """(passage, nth) => { let seen = 0; for (const sc of document.querySelectorAll('.window-slot[data-type=session] .scroller')) { const walk = document.createTreeWalker(sc, NodeFilter.SHOW_TEXT); let n; while ((n = walk.nextNode())) { const i = n.textContent.indexOf(passage); if (i < 0 || seen++ !== nth) continue; n.parentElement.scrollIntoView({ block: 'center' }); const r = document.createRange(); r.setStart(n, i); r.setEnd(n, i + passage.length); getSelection().removeAllRanges(); getSelection().addRange(r); return true; } } return false; }""", passage, nth, ) if not found: raise LookupError(f"no chat text {passage!r}") await asyncio.sleep(0.9) button = await self.page.evaluate( "() => { const b = document.querySelector('.selection-note')?.getBoundingClientRect(); return b ? [b.x + b.width / 2, b.y + b.height / 2] : null; }" ) if button is None: raise LookupError("selecting chat text offered no note button") before = {w["w"] for w in await self.windows()} await self.click(*button) await asyncio.sleep(0.6) await self.type(body) await self.key("Escape") await self.blur() return next(w["w"] for w in await self.windows() if w["w"] not in before) async def dock_note(self, w: str, x: float, y: float) -> str | None: """Carry a floating note by its header to (x, y); let go over a canvas and it joins it. Another float under the point takes the drop instead. Returns where it ended up (float, canvas).""" window = await self.window(w) grip = await self.js( """(id) => { const n = document.querySelector(`.window-slot[data-id="${CSS.escape(id)}"]`); const a = n.querySelector('.about').getBoundingClientRect(), d = n.querySelector('.dismiss').getBoundingClientRect(); return [(a.right + d.left) / 2, d.y + d.height / 2]; }""", window["id"], ) await self.drag(tuple(grip), (x, y), steps=12) return (await self.window(w))["place"] # pictures async def shot(self, label: str, *, show: bool = False) -> str: """Save a screenshot under the run's shots/ and return its path; show_image(path) to look.""" return await self.clip(None, label, show=show) async def clip( self, box: list[float] | tuple[float, ...] | None, label: str, *, scale: float = 1, show: bool = False, ) -> str: """Save a region [x, y, w, h] (None: the viewport) at scale, return its path.""" params: dict[str, Any] = {"format": "png"} if box is not None: x, y, w, h = box params["clip"] = {"x": x, "y": y, "width": w, "height": h, "scale": scale} data = await self.page.cdp.send("Page.captureScreenshot", params) path = self.run / "shots" / f"{int(time.time() * 1000)}-{slug(label)}.png" path.write_bytes(base64.b64decode(data["data"])) if show: tools.show_image(str(path)) return str(path) # ending async def stop(self) -> list[str]: """Attempt every cleanup stage. Raise on failure or observed leftovers. An empty result means owned handles closed and the home scan was empty, not that the scan independently discovered browser processes. """ cleanup = asyncio.create_task(self._stop()) try: return await asyncio.shield(cleanup) except asyncio.CancelledError: await cleanup raise async def _stop(self) -> list[str]: failures: list[Exception] = [] if self.browser is not None: try: await self.browser.close() except Exception as error: failures.append(error) for command in ("web", "daemon"): try: await tools.run(CLI, command, "--stop", env=self.env, timeout=60).text( check=True ) except Exception as error: failures.append(error) for job in self.jobs: try: ending = await job.stop() if not ending.gone: failures.append(RuntimeError(ending.report())) except Exception as error: failures.append(error) remaining: list[str] = [] try: remaining = await reap(self.home) if remaining: failures.append( RuntimeError(f"home-matching processes remain: {remaining}") ) except Exception as error: failures.append(error) if failures: raise ExceptionGroup(f"review cleanup incomplete: {self.run}", failures) (self.run / ".active").unlink(missing_ok=True) if self.lease is not None: self.lease.close() self.lease = None return remaining async def processes(home: Path) -> list[str]: """Home-matching process observations. Scan failure raises.""" return await asyncio.to_thread(home_processes, home) async def reap(home: Path) -> list[str]: return await asyncio.to_thread(reap_home, home) async def build(dist: Path | str = BASE / "dist") -> Path: """Build the web client into dist (never web/dist, which `albedo web` serves to dawn).""" dist = Path(dist) if dist.resolve() == (ROOT / "web/dist").resolve(): raise ValueError("build into a directory of your own, not web/dist") job = tools.run(*web_build(dist), timeout=600) await job.text(check=True) return dist async def start( name: str, *, width: int = 1440, height: int = 900, dark: bool = False, reduced_motion: bool = False, dist: Path | None = None, ) -> Review: """Start a review run named name on a fresh copy of the seed home: the fake model, `albedo web` (which boots the daemon) and a Chrome page on it. dist is the web build to serve; seed.py's when None.""" seed = BASE / "seed" if not (seed / "albedo.sqlite").exists(): raise FileNotFoundError( f"no seed home in {seed}: python3 test/manual/ux/seed.py" ) lease = acquire_base(BASE, exclusive=False) try: run = reserve_run(BASE, name) except BaseException: lease.close() raise env = { **daemon_env(run / "home", str(BASE / "daemon/albedo-daemon"), os.getpid()), "ALBEDO_WEB_DIST": str(dist or BASE / "dist"), } ui = Review(name, run, env, lease=lease) try: (run / "shots").mkdir() shutil.copytree( seed, run / "home", ignore=shutil.ignore_patterns( "daemon.*", "launcher.lock", "web*", "run", "backups", "*.sock" ), ) argv, extra = fake_model_argv() fake = tools.run("python3", *argv, env={**env, **extra}, timeout=86400) ui.jobs.append(fake) url = re.search(r"http://\S+", await fake.wait_for("http://", timeout=30)) assert url # the seed's fake model is gone; point the home at this run's config = json.loads((seed / "config.json").read_text()) old = config["providers"]["ux"]["baseUrl"] for file in ("config.json", "creds.json"): path = ui.home / file path.write_text(path.read_text().replace(old, url.group(0))) web = tools.run(CLI, "web", "--no-open", "--port", "0", env=env, timeout=86400) ui.jobs.append(web) line = await web.wait_for(re.compile(r"https?://"), timeout=180) link = re.search(r"https?://\S+", line) assert link ui.url = link.group(0) ui.browser = await tools.browser.spawn() ui.page = await ui.browser.new_page() await ui.page.cdp.send( "Page.addScriptToEvaluateOnNewDocument", {"source": ERRORS} ) await ui.size(width, height) await ui.media(dark=dark, reduced_motion=reduced_motion) await ui.reload() return ui except BaseException as error: try: await ui.stop() except Exception as cleanup_error: error.add_note(f"Cleanup also failed for {run}: {cleanup_error}") raise Build = Callable[[Review], Awaitable[None]] SCENARIOS: dict[str, tuple[str, Build]] = {} def scenario(name: str, description: str) -> Callable[[Build], Build]: """Register a board that load(name) builds through the UI, like a person would.""" def register(build: Build) -> Build: SCENARIOS[name] = (description, build) return build return register def scenarios() -> dict[str, str]: """Each scenario's name and what its board holds.""" return {name: description for name, (description, _) in SCENARIOS.items()} @scenario( "tiles-basic", "tiles: w0 markdown, code and tables, w1 a very long chat, w2 tools and file edits, w3 a terminal.", ) async def tiles_basic(ui: Review) -> None: await ui.fresh() for name in ( "markdown, code and tables", "a very long chat", "tools and file edits", ): await ui.open_chat(name) await ui.blur() await ui.key("t") await asyncio.sleep(1.5) @scenario( "sections", "tiles: tabs (w1 hello chat, w0 markdown) over a section named 'research' holding" " w2 a very long chat, an empty canvas tile and w3 tools and file edits.", ) async def sections(ui: Review) -> None: await ui.fresh() for name in ( "markdown, code and tables", "hello chat", "a very long chat", "tools and file edits", ): await ui.open_chat(name) await ui.blur() await ui.pick("w2") await ui.pick("w3") await ui.group("research") w0, w1 = await ui.window("w0"), await ui.window("w1") await ui.drag(tuple(w1["head"]), (w0["head"][0] + 60, w0["head"][1])) await ui.click(*(await ui.window("w2"))["head"]) await ui.palette("new canvas beside this window") await ui.blur() @scenario( "canvas-groups", "canvas: a group named 'pair' (w0 markdown, w1 hello chat), w2 a very long chat and" " w3 tools alone, and w4 a note tied to a passage in w2, placed over the group.", ) async def canvas_groups(ui: Review) -> None: await ui.fresh("canvas") for name in ( "markdown, code and tables", "hello chat", "a very long chat", "tools and file edits", ): await ui.open_chat(name) await ui.blur() await ui.key("!") await asyncio.sleep(0.8) await ui.pick("w0") await ui.pick("w1") await ui.group("pair") await ui.note("passages can scroll far", "is this the right place for it?") await ui.key("!") await asyncio.sleep(0.8) @scenario( "notes-long", "tiles: w0 a very long chat beside a canvas tile with four notes on it, tied to" " parts 1, 2, 15 and 30 of w0; scrolled to the end, all four lines pile up at w0's edge.", ) async def notes_long(ui: Review) -> None: await ui.fresh() await ui.open_chat("a very long chat") await ui.blur() await ui.click(*(await ui.window("w0"))["head"]) await ui.palette("new canvas beside this window") await ui.blur() x, y, width, height = (await ui.page.evaluate(CANVAS_TILES))[0] for n, part in enumerate(("part 1", "part 2", "part 15", "part 30")): note = await ui.note(part, f"note on {part}") # the grip sits near a note's right edge; clear of the floats still waiting await ui.dock_note(note, x + width - 40, y + height * (0.15 + 0.22 * n)) await ui.scroll("w0", 10**6) @scenario( "dense", "tiles, crowded: w0-w6 seven chats (hello, markdown, long, tools, failing, short one," " short two) and w7 a terminal, opened one after another.", ) async def dense(ui: Review) -> None: await ui.fresh() for name in ( "hello chat", "markdown, code and tables", "a very long chat", "tools and file edits", "a failing turn", "short one", "short two", ): await ui.open_chat(name) await ui.blur() await ui.key("t") await asyncio.sleep(1.5) @scenario( "boards-and-empty", "three boards: board 1 empty tiles, board 2 with w0 hello chat, board 3 an empty canvas (the active one).", ) async def boards_and_empty(ui: Review) -> None: await ui.fresh() await ui.palette("new board") await ui.open_chat("hello chat") await ui.blur() await ui.palette("new board") await ui.palette("layout: canvas")