Skip to content

[browser,ui] visual-QA capture API, settle-on-read, element discovery and DSL additions - #1671

Merged
fwbrasil merged 1 commit into
mainfrom
browser-ui
Jun 14, 2026
Merged

fwbrasil merged 1 commit into
mainfrom
browser-ui

Conversation

@fwbrasil

Copy link
Copy Markdown
Collaborator

Problem

kyo-browser

Browser.screenshot captured a hard-coded 1280x720 crop and offered no way to target a region, capture the full scrollable page in bands, or record frames over a live animation. The legacy scrollTo(selector) scroll-to-element overload conflated coordinate scrolling and element scrolling under one name. setViewport and resetViewport were private[kyo], giving tests no public way to set the device pixel ratio or to override and restore the viewport in a scoped block. withEmulation (CSS media / color scheme emulation) and withHighlights (annotated overlay boxes) did not exist.

Geometry and style reads (boundingBox, now renamed boundingRect) performed a direct CDP DOM.getBoxModel read without waiting for layout to stabilize, so they returned stale coordinates for elements still animating or reflecting a pending re-layout. There was no settled read for computed styles, viewport intersection, scroll position, or element discovery.

Browser.ConsoleMessage carried an Instant timestamp and a single message: String field. The timestamp was wall-clock absolute rather than relative to the recording start, and the decoder covered only the three synthetic console.* overrides injected by the tab setup, not the 18 CDP Runtime.consoleAPICalled types. onConsole existed; recordConsole (collect-and-return) did not. The capture methods that needed hold-still behavior (freeze animations, await fonts, loop to two byte-identical frames) had to be coded ad hoc or were absent.

BrowserException had no exception type for capture operations that exceeded a configured unit cap (band count, mark count, frame count).

kyo-browser/CONTRIBUTING.md did not exist.

kyo-ui

Style had no Display.flex/inlineFlex, no reverse flex directions (rowReverse, columnReverse), no Position.fixed, no TextWrap.balance/pretty, no strokeDashoffset, no animationDelay, no scrollbar properties (scrollbarWidth, scrollbarColor, scrollbarGutter), no backgroundClip, and no OKLCH/OKLAB gradient color-space support.

Svg.PathData had no raw escape for pre-built path strings. SMIL animation elements had no fill attribute (the AnimFill enum controlling freeze-vs-remove behavior). Svg.Path had no pathLength attribute.

There was no document-level Stylesheet type (selector-targeted rules, @media queries including prefers-reduced-motion, @keyframes, @font-face, CSS variables). Selector as a kyo-ui type did not exist. UI.runRenderPage (full-document SSR streaming), UI.PageHead (head configuration), UI.dataIsland / UI.DataIsland (<script type="..."> JSON payloads), UI.blockquote, UI.rawHtml, and UI.cssClass did not exist.

UIWindow lacked prefersColorScheme (a Signal[Boolean] backed by a matchMedia listener), onClick (document-level capture-phase click subscription returning UI.MouseEvent), clipboard write, local-storage get/set, setTitle, scrollToTop, and scrollIntoViewById. UILocation.assign did not exist. ElementRef (an opaque handle over a DOM element, built by UI.MouseEvent.targetClosest) was absent, making it impossible to walk the DOM from a document-level click target into rawHtml-injected content.

On the JS mount path, a structural re-render of a reactive region replaced the region's outerHTML without capturing and restoring the focused element and its caret position, causing a focused, caret-positioned input to lose both focus and selection whenever a surrounding reactive region re-rendered.

Solution

kyo-browser: capture API

Browser.screenshot drops the 1280x720 crop; it now captures the live viewport with no clip. Two new methods cover the removed behaviors: screenshotRegion(x, y, width, height) for an explicit clip region (aborts BrowserInvalidArgumentException before any CDP call on non-positive dimensions), and screenshotFullPage(maxBands) for full-scroll band capture (aborts BrowserCaptureLimitExceededException before any capture when the page exceeds maxBands). A screenshotMarks(marks, maxMarks) method overlays Browser.Annotation highlight boxes then captures, used with withHighlights for annotated QA shots. screenshotFrames records CDP screencast frames for the duration of a scoped body, returning (Chunk[ScreenshotFrame], result).

All capture methods use the HoldStill protocol: settleForCapture (best-effort DOM quiescence), document.fonts.ready, a tokenized freeze stylesheet (data-kyo-internal/data-kyo-token) injected via Scope.acquireRelease, and a loop comparing consecutive frame hashes until two frames are byte-identical or captureHoldStillTimeout elapses. Multi-band captures use withFrozenPage + holdStillFrame directly so the freeze stylesheet is injected once for the whole band sequence. The freeze stylesheet is tagged with a monotonic per-page token so nested or interleaved withHoldStill calls each tear down only their own node.

kyo-browser: settle-on-read

SettleRead.settle is a new internal primitive that re-samples a JS expression through StabilitySampler.sampleWindow until the value is stable across assertionStabilityWindow, then decodes it. A settled-absent element produces a stable sentinel that decode maps to the read's Absent/false/empty twin return without raising a stability timeout. All new geometry and element reads use it: boundingRect (renamed from boundingBox, now stable-settled before the authoritative DOM.getBoxModel CDP read), computedStyles, computedStyle, inViewport, scrollPosition, element, elements, and elementAt.

Browser.waitForStable(timeout) is a new public method delegating to MutationSettlement.waitForStable: a strict quiescence wait that aborts BrowserAssertionTimedOutException on timeout. MutationSettlement.settleForCapture is the best-effort variant that swallows the timeout and proceeds.

kyo-browser: element discovery

DiscoverJs injects window.__kyoDiscoverProbe and window.__kyoUniqueSelector idempotently (gated by window.__kyoDiscoverInstalled). Browser.element(selector), Browser.elements(selector), and Browser.elementAt(x, y) use it to return Browser.ElementInfo records carrying bounding geometry, visibility, viewport membership, interactivity, role, classes, id, and a stable unique CSS path. elements fast-paths the empty case via BrowserEval.locateCount before any stability wait.

kyo-browser: renamed and reshaped types

BoundingBox is renamed to Browser.Bounds (shared with ElementInfo). Browser.ScrollPosition is new. Browser.ScreenshotFrame carries image, offsetMs, and scrollOffset. Browser.ConsoleMessage replaces message: String and timestamp: Instant with text: String, location: Maybe[String], and offsetMs: Long (milliseconds from the recording start). The console decoder now covers the 18 CDP Runtime.consoleAPICalled types, folded onto five ConsoleLevel severities. recordConsole collects all console events during a body into a Chunk[ConsoleMessage] using onConsole internally. BrowserCaptureLimitExceededException is a new leaf of BrowserReadException.

kyo-browser: viewport, scroll, emulation, highlight

setViewport and resetViewport are now public and accept deviceScaleFactor: Double. withViewport gains the same parameter. withEmulation applies a CSS media type and prefers-color-scheme override for the duration of a scoped body. withHighlights draws tokenized dashed-box overlays over elements for the body's duration. scrollTo(x, y) takes integer coordinates; scrollToElement(selector) is the new selector-targeting scroll (the old scrollTo(selector) is removed). kyo-browser/CONTRIBUTING.md documents the settlement model, capture conventions, extension recipes, and the decision checklist for new methods.

kyo-ui: Style and DSL additions

Display gains flex and inlineFlex. Style.rowReverse and columnReverse are added alongside the existing row/column. Position.fixed is added to the existing position enum. TextWrap gains balance and pretty. Style.strokeDashoffset, Style.animationDelay, Style.scrollbarWidth, Style.scrollbarColor, Style.scrollbarGutter, and Style.backgroundClip are new. Gradient color-space interpolation is added: GradientColorSpace.oklch and oklab allow bgGradient to interpolate in perceptually uniform spaces rather than sRGB.

Svg.PathData.raw(d) accepts a pre-built path string. Svg.Path.pathLength(v) sets the pathLength SVG attribute for dash reparameterization. SMIL animation elements (Animate, AnimateTransform, AnimateMotion, SetAnim) gain a fill(AnimFill) method covering freeze and remove.

kyo-ui: Stylesheet and Selector

Stylesheet is a new pure-value document-level stylesheet type: ordered rules (rule), @media blocks (media), :root and scoped CSS variables (vars, scopedVars), @font-face (fontFace), and @keyframes (keyframes). Stylesheet.MediaQuery provides typed media query values including prefersDark, prefersReducedMotion, and prefersReducedMotionNoPreference. Selector is a new pure-value CSS selector type with cls, id, data, tag, pseudo, pseudoElement, descendant, and child combinators.

kyo-ui: document rendering and data islands

UI.runRenderPage(head)(ui) streams a complete HTML document. UI.PageHead configures the <head>: title, viewport meta, base CSS, per-page CSS, links, an optional ESModule script, an optional JSON-LD data island, and a body-end data-island list. UI.dataIsland(scriptType, id, json) builds a <script type="..."> block (JSON special characters escaped) for placement in PageHead. UI.cssClass(name) attaches a CSS class hook for Stylesheet class selectors. UI.runStylesheet(sheet) injects a stylesheet into the DOM client-side. UI.blockquote and UI.rawHtml are new element kinds.

kyo-ui: browser-interop additions (JS/WASM)

UIWindow gains prefersColorScheme (a Signal[Boolean]), onClick (document-level capture-phase click subscription delivering UI.MouseEvent), writeClipboard, storageGet, storageSet, setTitle, scrollToTop, scrollIntoViewById, and onIntersectById. UILocation.assign navigates to a URI. ElementRef is a new opaque type over dom.Element, built only by UI.MouseEvent.targetClosest, exposing closest, querySelector, getAttribute, setAttribute, removeAttribute, and textContent with Maybe-returning signatures. UIMouseEventOps maintains a bounded per-click side table associating each UI.MouseEvent instance with its native dom.MouseEvent for the duration of the handler, used by targetClosest to walk the DOM without a dom.* field on the shared platform-neutral type.

kyo-ui: reactive input focus fix

On the JS mount path, DomBackend now captures the focused element and its caret position (via selectionStart) before replacing a reactive region's outerHTML, then re-focuses and restores the caret on the new node. The guard distinguishes whether the region wrapper itself carries the focus (common: a value-bound input inside a reactive region) from a deeply focused descendant, and handles setSelectionRange InvalidStateError on input types that do not support it (date, file, etc.). UITestSpaReactiveInputFocusTest is the regression guard: a focused, caret-positioned input nested inside an OUTER reactive region survives a structural re-render triggered by bumping the outer signal.

kyo-ui: kyo-browser API migration

Existing kyo-ui integration tests that called Browser.scrollTo(Selector.id(...)) are migrated to Browser.scrollToElement(Selector.id(...)).

Notes

Browser.ConsoleMessage is a breaking change: the timestamp: Instant and message: String fields are replaced by offsetMs: Long, text: String, and location: Maybe[String]. Any caller that pattern-matched on the old shape must update.

BoundingBox is removed; callers use Browser.Bounds. Browser.scrollTo(selector: Selector) is removed; callers use Browser.scrollToElement(selector).

setViewport and resetViewport moving from private[kyo] to public is not a binary-incompatible change but was a deliberate visibility promotion: they were previously accessible only within the module.

The hold-still freeze stylesheet produces one unfiltered childList DOM mutation because its insertion targets document.head rather than a data-kyo-internal-tagged node. settleForCapture runs before the injection; the HoldStill convergence loop is frame-hash based, so the injection mutation does not break convergence.

UIMouseEventOps uses a js.WrappedMap keyed by reference identity on each UI.MouseEvent instance. Entries are inserted before the handler runs and removed via Sync.ensure after it completes, so the table is bounded by concurrently in-flight click handlers and does not leak.

UI.DataIsland does not extend UI: a data island is a PageHead payload emitted only from the renderer, never a tree node the diff algorithm sees.

…, and DSL additions

## Problem

**kyo-browser**

`Browser.screenshot` captured a hard-coded `1280x720` crop and offered no way to target a region, capture the full scrollable page in bands, or record frames over a live animation. The legacy `scrollTo(selector)` scroll-to-element overload conflated coordinate scrolling and element scrolling under one name. `setViewport` and `resetViewport` were `private[kyo]`, giving tests no public way to set the device pixel ratio or to override and restore the viewport in a scoped block. `withEmulation` (CSS media / color scheme emulation) and `withHighlights` (annotated overlay boxes) did not exist.

Geometry and style reads (`boundingBox`, now renamed `boundingRect`) performed a direct CDP `DOM.getBoxModel` read without waiting for layout to stabilize, so they returned stale coordinates for elements still animating or reflecting a pending re-layout. There was no settled read for computed styles, viewport intersection, scroll position, or element discovery.

`Browser.ConsoleMessage` carried an `Instant` timestamp and a single `message: String` field. The timestamp was wall-clock absolute rather than relative to the recording start, and the decoder covered only the three synthetic `console.*` overrides injected by the tab setup, not the 18 CDP `Runtime.consoleAPICalled` types. `onConsole` existed; `recordConsole` (collect-and-return) did not. The capture methods that needed hold-still behavior (freeze animations, await fonts, loop to two byte-identical frames) had to be coded ad hoc or were absent.

`BrowserException` had no exception type for capture operations that exceeded a configured unit cap (band count, mark count, frame count).

`kyo-browser/CONTRIBUTING.md` did not exist.

**kyo-ui**

`Style` had no `Display.flex`/`inlineFlex`, no reverse flex directions (`rowReverse`, `columnReverse`), no `Position.fixed`, no `TextWrap.balance`/`pretty`, no `strokeDashoffset`, no `animationDelay`, no scrollbar properties (`scrollbarWidth`, `scrollbarColor`, `scrollbarGutter`), no `backgroundClip`, and no OKLCH/OKLAB gradient color-space support.

`Svg.PathData` had no `raw` escape for pre-built path strings. SMIL animation elements had no `fill` attribute (the `AnimFill` enum controlling freeze-vs-remove behavior). `Svg.Path` had no `pathLength` attribute.

There was no document-level `Stylesheet` type (selector-targeted rules, `@media` queries including `prefers-reduced-motion`, `@keyframes`, `@font-face`, CSS variables). `Selector` as a kyo-ui type did not exist. `UI.runRenderPage` (full-document SSR streaming), `UI.PageHead` (head configuration), `UI.dataIsland` / `UI.DataIsland` (`<script type="...">` JSON payloads), `UI.blockquote`, `UI.rawHtml`, and `UI.cssClass` did not exist.

`UIWindow` lacked `prefersColorScheme` (a `Signal[Boolean]` backed by a `matchMedia` listener), `onClick` (document-level capture-phase click subscription returning `UI.MouseEvent`), clipboard write, local-storage get/set, `setTitle`, `scrollToTop`, and `scrollIntoViewById`. `UILocation.assign` did not exist. `ElementRef` (an opaque handle over a DOM element, built by `UI.MouseEvent.targetClosest`) was absent, making it impossible to walk the DOM from a document-level click target into `rawHtml`-injected content.

On the JS mount path, a structural re-render of a reactive region replaced the region's `outerHTML` without capturing and restoring the focused element and its caret position, causing a focused, caret-positioned input to lose both focus and selection whenever a surrounding reactive region re-rendered.

## Solution

**kyo-browser: capture API**

`Browser.screenshot` drops the `1280x720` crop; it now captures the live viewport with no clip. Two new methods cover the removed behaviors: `screenshotRegion(x, y, width, height)` for an explicit clip region (aborts `BrowserInvalidArgumentException` before any CDP call on non-positive dimensions), and `screenshotFullPage(maxBands)` for full-scroll band capture (aborts `BrowserCaptureLimitExceededException` before any capture when the page exceeds `maxBands`). A `screenshotMarks(marks, maxMarks)` method overlays `Browser.Annotation` highlight boxes then captures, used with `withHighlights` for annotated QA shots. `screenshotFrames` records CDP screencast frames for the duration of a scoped body, returning `(Chunk[ScreenshotFrame], result)`.

All capture methods use the `HoldStill` protocol: `settleForCapture` (best-effort DOM quiescence), `document.fonts.ready`, a tokenized freeze stylesheet (`data-kyo-internal`/`data-kyo-token`) injected via `Scope.acquireRelease`, and a loop comparing consecutive frame hashes until two frames are byte-identical or `captureHoldStillTimeout` elapses. Multi-band captures use `withFrozenPage` + `holdStillFrame` directly so the freeze stylesheet is injected once for the whole band sequence. The freeze stylesheet is tagged with a monotonic per-page token so nested or interleaved `withHoldStill` calls each tear down only their own node.

**kyo-browser: settle-on-read**

`SettleRead.settle` is a new internal primitive that re-samples a JS expression through `StabilitySampler.sampleWindow` until the value is stable across `assertionStabilityWindow`, then decodes it. A settled-absent element produces a stable sentinel that `decode` maps to the read's `Absent`/`false`/empty twin return without raising a stability timeout. All new geometry and element reads use it: `boundingRect` (renamed from `boundingBox`, now stable-settled before the authoritative `DOM.getBoxModel` CDP read), `computedStyles`, `computedStyle`, `inViewport`, `scrollPosition`, `element`, `elements`, and `elementAt`.

`Browser.waitForStable(timeout)` is a new public method delegating to `MutationSettlement.waitForStable`: a strict quiescence wait that aborts `BrowserAssertionTimedOutException` on timeout. `MutationSettlement.settleForCapture` is the best-effort variant that swallows the timeout and proceeds.

**kyo-browser: element discovery**

`DiscoverJs` injects `window.__kyoDiscoverProbe` and `window.__kyoUniqueSelector` idempotently (gated by `window.__kyoDiscoverInstalled`). `Browser.element(selector)`, `Browser.elements(selector)`, and `Browser.elementAt(x, y)` use it to return `Browser.ElementInfo` records carrying bounding geometry, visibility, viewport membership, interactivity, role, classes, id, and a stable unique CSS path. `elements` fast-paths the empty case via `BrowserEval.locateCount` before any stability wait.

**kyo-browser: renamed and reshaped types**

`BoundingBox` is renamed to `Browser.Bounds` (shared with `ElementInfo`). `Browser.ScrollPosition` is new. `Browser.ScreenshotFrame` carries `image`, `offsetMs`, and `scrollOffset`. `Browser.ConsoleMessage` replaces `message: String` and `timestamp: Instant` with `text: String`, `location: Maybe[String]`, and `offsetMs: Long` (milliseconds from the recording start). The console decoder now covers the 18 CDP `Runtime.consoleAPICalled` types, folded onto five `ConsoleLevel` severities. `recordConsole` collects all console events during a body into a `Chunk[ConsoleMessage]` using `onConsole` internally. `BrowserCaptureLimitExceededException` is a new leaf of `BrowserReadException`.

**kyo-browser: viewport, scroll, emulation, highlight**

`setViewport` and `resetViewport` are now public and accept `deviceScaleFactor: Double`. `withViewport` gains the same parameter. `withEmulation` applies a CSS media type and `prefers-color-scheme` override for the duration of a scoped body. `withHighlights` draws tokenized dashed-box overlays over elements for the body's duration. `scrollTo(x, y)` takes integer coordinates; `scrollToElement(selector)` is the new selector-targeting scroll (the old `scrollTo(selector)` is removed). `kyo-browser/CONTRIBUTING.md` documents the settlement model, capture conventions, extension recipes, and the decision checklist for new methods.

**kyo-ui: Style and DSL additions**

`Display` gains `flex` and `inlineFlex`. `Style.rowReverse` and `columnReverse` are added alongside the existing `row`/`column`. `Position.fixed` is added to the existing position enum. `TextWrap` gains `balance` and `pretty`. `Style.strokeDashoffset`, `Style.animationDelay`, `Style.scrollbarWidth`, `Style.scrollbarColor`, `Style.scrollbarGutter`, and `Style.backgroundClip` are new. Gradient color-space interpolation is added: `GradientColorSpace.oklch` and `oklab` allow `bgGradient` to interpolate in perceptually uniform spaces rather than sRGB.

`Svg.PathData.raw(d)` accepts a pre-built path string. `Svg.Path.pathLength(v)` sets the `pathLength` SVG attribute for dash reparameterization. SMIL animation elements (`Animate`, `AnimateTransform`, `AnimateMotion`, `SetAnim`) gain a `fill(AnimFill)` method covering `freeze` and `remove`.

**kyo-ui: Stylesheet and Selector**

`Stylesheet` is a new pure-value document-level stylesheet type: ordered rules (`rule`), `@media` blocks (`media`), `:root` and scoped CSS variables (`vars`, `scopedVars`), `@font-face` (`fontFace`), and `@keyframes` (`keyframes`). `Stylesheet.MediaQuery` provides typed media query values including `prefersDark`, `prefersReducedMotion`, and `prefersReducedMotionNoPreference`. `Selector` is a new pure-value CSS selector type with `cls`, `id`, `data`, `tag`, `pseudo`, `pseudoElement`, `descendant`, and `child` combinators.

**kyo-ui: document rendering and data islands**

`UI.runRenderPage(head)(ui)` streams a complete HTML document. `UI.PageHead` configures the `<head>`: title, viewport meta, base CSS, per-page CSS, links, an optional ESModule script, an optional JSON-LD data island, and a body-end data-island list. `UI.dataIsland(scriptType, id, json)` builds a `<script type="...">` block (JSON special characters escaped) for placement in `PageHead`. `UI.cssClass(name)` attaches a CSS class hook for `Stylesheet` class selectors. `UI.runStylesheet(sheet)` injects a stylesheet into the DOM client-side. `UI.blockquote` and `UI.rawHtml` are new element kinds.

**kyo-ui: browser-interop additions (JS/WASM)**

`UIWindow` gains `prefersColorScheme` (a `Signal[Boolean]`), `onClick` (document-level capture-phase click subscription delivering `UI.MouseEvent`), `writeClipboard`, `storageGet`, `storageSet`, `setTitle`, `scrollToTop`, `scrollIntoViewById`, and `onIntersectById`. `UILocation.assign` navigates to a URI. `ElementRef` is a new opaque type over `dom.Element`, built only by `UI.MouseEvent.targetClosest`, exposing `closest`, `querySelector`, `getAttribute`, `setAttribute`, `removeAttribute`, and `textContent` with `Maybe`-returning signatures. `UIMouseEventOps` maintains a bounded per-click side table associating each `UI.MouseEvent` instance with its native `dom.MouseEvent` for the duration of the handler, used by `targetClosest` to walk the DOM without a `dom.*` field on the shared platform-neutral type.

**kyo-ui: reactive input focus fix**

On the JS mount path, `DomBackend` now captures the focused element and its caret position (via `selectionStart`) before replacing a reactive region's `outerHTML`, then re-focuses and restores the caret on the new node. The guard distinguishes whether the region wrapper itself carries the focus (common: a value-bound input inside a reactive region) from a deeply focused descendant, and handles `setSelectionRange` `InvalidStateError` on input types that do not support it (date, file, etc.). `UITestSpaReactiveInputFocusTest` is the regression guard: a focused, caret-positioned input nested inside an OUTER reactive region survives a structural re-render triggered by bumping the outer signal.

**kyo-ui: kyo-browser API migration**

Existing kyo-ui integration tests that called `Browser.scrollTo(Selector.id(...))` are migrated to `Browser.scrollToElement(Selector.id(...))`.

## Notes

`Browser.ConsoleMessage` is a breaking change: the `timestamp: Instant` and `message: String` fields are replaced by `offsetMs: Long`, `text: String`, and `location: Maybe[String]`. Any caller that pattern-matched on the old shape must update.

`BoundingBox` is removed; callers use `Browser.Bounds`. `Browser.scrollTo(selector: Selector)` is removed; callers use `Browser.scrollToElement(selector)`.

`setViewport` and `resetViewport` moving from `private[kyo]` to public is not a binary-incompatible change but was a deliberate visibility promotion: they were previously accessible only within the module.

The hold-still freeze stylesheet produces one unfiltered `childList` DOM mutation because its insertion targets `document.head` rather than a `data-kyo-internal`-tagged node. `settleForCapture` runs before the injection; the HoldStill convergence loop is frame-hash based, so the injection mutation does not break convergence.

`UIMouseEventOps` uses a `js.WrappedMap` keyed by reference identity on each `UI.MouseEvent` instance. Entries are inserted before the handler runs and removed via `Sync.ensure` after it completes, so the table is bounded by concurrently in-flight click handlers and does not leak.

`UI.DataIsland` does not extend `UI`: a data island is a `PageHead` payload emitted only from the renderer, never a tree node the diff algorithm sees.
@fwbrasil
fwbrasil merged commit 0bf34ff into main Jun 14, 2026
9 of 14 checks passed
@fwbrasil
fwbrasil deleted the browser-ui branch June 14, 2026 19:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant