Skip to content

Halve a Tab's cost on every page by reading the keyboard once and restyling less - #5479

Merged
max-sixty merged 12 commits into
mainfrom
per-input-fixed-cost
Nov 5, 2026
Merged

max-sixty merged 12 commits into
mainfrom
per-input-fixed-cost

Conversation

@max-sixty

Copy link
Copy Markdown
Owner

On pages of the size people use (a median 298 elements on this machine), most of an input's cost is work every page pays rather than growth with the page, so the growth tests don't see it. Profiling Tab, keystroke and click on the generated asks page at 8 and 64 sections found a Tab spending about 18 ms of main thread, half of it asking the keyboard the same questions again and half restyling. This halves a Tab and takes up to 3 ms off a click; a keystroke and a wheel step were already small and are unchanged.

Main-thread ms per input in Chromium, b5f5c5d43 against this branch, least of five interleaved rounds:

input 8 sections 64 sections
Tab 17.5 → 9.3 17.2 → 10.4
click, browser side 16.3 → 13.5 26.6 → 23.6

Reading the keyboard once. perVocabulary (registry.js) read the registry's widgets and the awaiting-widget selector on every call; it now reads them once per vocabulary. A contextual scope rebuilt an obligation's rows on every read and now keeps them for one walk, and claimsEsc matches Escape before checking liveness (scopes.js). The comment key's destination is answered once per repaint rather than twice per frame (surface.js). Together these cut calls per Tab from 324k to 113k.

Restyling less. Ten ::highlight() rules for text documents and suggestions matched every element; they now name the elements their ranges paint (base.css, text-document.css), and highlight paint is pixel-identical in Chromium, Firefox and WebKit. Four :has() rules keyed on native :focus/:focus-visible made every focus move restyle most of the page; they now read Leaf's data-lf-focus* marks, and rowWalk lands after the focus paint so the ring is drawn on the row the walk lands on. A page control's group is read only when a menu asks, so a click's panel paint no longer forces style (page-controls.js).

The layout box. layoutBox searched all of main with :scope > queries and read computed style for every child of a main with no Layout. layouts.css's rule that already marks a shell holding a Layout child now also declares --lf-layout-shell, and layoutBox reads only the children of a shell, so a main of plain sections costs one read per lookup instead of one per section (0.23–0.41 → 0.05 ms at 500 sections, looked up about 23 times per click).

Focus at startup. Because the focus rules now read Leaf's marks, focus.js seeds its paint from whatever holds focus when it loads, so an autofocused choice keeps its ring. A frame focused before the runtime loaded starts without a keyboard ring, as a press into one does, until it reports an input.

Checked: pnpm run test:runtime (816 pass, with new cases for the seed in focus.test.mjs), pnpm run check:browser, and 34 browser tests covering highlights, focus rings, key hints, the page map, page controls and pages of parts, run by node id after merging main. Three rounds of independent Codex review; the second found the autofocus and frame-modality cases fixed here, and the third found nothing outstanding.

Left for later: publishing the page's state on a click rebuilds unchanged subtrees (about 3 ms at 8 sections, 6 at 64); each keystroke asks for every key hint on the page to be painted again; the :has() rules on Leaf's own focus marks still cost about 1.6 ms of a Tab's restyle.

Ref #5194

This was written by Claude Code on behalf of max-sixty

A `::highlight()` rule with no originating element makes Chromium resolve one
more style for every element it restyles, on every page, whether or not the
highlight has a range there. Ten such rules, eight for a text document's syntax
colours and two for a suggestion's moved words, made every restyle pay for them
on a page holding neither widget.

Each rule now names the elements its ranges land on: a listing's rows, whose text
is all a token range covers, and `lf-old` and `lf-new` with their descendants.

Keeps: the paint. On a page with a text document and two suggestions, one with
nested words, screenshots match the previous rules pixel for pixel in Chromium
156, Firefox 157 and WebKit 27.2, and deleting the rules changes each shot, so
the check saw real paint. The comment marks' five rules stay universal, since
their ranges land on any text and Firefox inherits no highlight style.

Style recalculation per Tab on the 8-section `asks` page, deleting rules through
the CSSOM within one run, least of four rounds: 7.64 ms to 4.61 ms. Least-of-four
A/B with the base: a Tab's main thread 25.9 to 21.4 ms, loading 314 to 298 ms at
8 sections and 822 to 695 ms at 64.
…abulary

`elementDeclarations` filtered the whole registry on each call, and
`ownedObligationControl` asked it for its selector once per command an obligation
holds. A Tab on an ask read the vocabulary about 1,100 times, in calls that had
nothing to do with what the Tab changed.

`perVocabulary` keeps a reading until `$layer.generation`, a content fingerprint,
changes, as `indexedState` and `pageText` already do. `elementDeclarations` and
the selector of awaiting widgets read through it. A vocabulary with no generation,
which only a test states, is read afresh each time.

Keeps: every answer, since a generation names one vocabulary's content. A runtime
test that adopted a second vocabulary with the first's generation now states its
own, as `registry-state-index.test.mjs` says every test vocabulary should.

Function calls per input, counted by V8's precise coverage on the 8-section `asks`
page: a Tab 324,441 to 198,261, a keystroke 48,627 to 34,118, a click 161,984 to
158,030.
…ocus marks

Four rules named `:focus` or `:focus-visible` inside `:has()`: an option row's ring
carrier, a choice's ring, the video bar's reveal and a diff fold's instant toggle.
While any does, a focus change on any element makes the browser invalidate the
ancestors a `:has()` tested, and a focus move forces a restyle for its blur and
another for its focus, so every Tab on every page paid for two restyles of its
widget and ancestors. They now read `data-lf-focus` and `data-lf-focus-visible`,
which `focus.js` writes once a move in the focus task.

The option row's rule named native focus for one reader: `rowWalk` lands in the
focus task, before those marks are painted, and read the row as its ring's carrier.
It now lands after the paint its move queued, still before the frame.

Keeps: a Tab, End and Home showing the row's ring at a scroller's edge (with the
walk landing early again, the End case fails in Firefox); the video bar showing on
keyboard focus and a choice wearing its ring, checked in Chromium and Firefox. A
choice's input drops its own outline only once it is marked, so before the runtime
loads it keeps the browser's ring.
A repaint asked dispatch which key opens a comment twice, for the field's hint and
then for the box resting beside its target, and each answer walks every scope and
row on the page's keyboard stack. `restFab` now reads the key `commentHint` read
moments before: repaint.js calls the two in that order, and nothing runs between
them.

Keeps: the box at rest and the hint, which show the same key from the same walk at
the same moment, as `test_where_c_goes_shows_before_the_press` and
`test_a_press_on_the_box_at_rest_opens_it_beside_its_target` check.

Function calls per Tab on the 8-section `asks` page, V8's precise coverage: 198,261
to 152,138.
…iveness

`contextScopes` built a scope whose `rows` getter re-derived its rows on every read:
it walked the obligation's widget for its command declarations and compiled them.
One keyboard walk reads a scope's rows many times over, about 175 reads for the 31
scopes a Tab builds, and `claimsEsc` asked `live(row)` of every row before asking
whether the row binds Escape at all.

A scope object now keeps the rows it first read. `scopesFor` builds a fresh one for
each walk, so the reading is as new as the walk. `claimsEsc` matches the key first,
as `resolveKey` already does.

Keeps: the routes a walk answers. Nothing writes between the reads of one walk, and
the contextual rows `contextRows` returns keep their identities across walks through
its own map. `test_the_obligation_itself_binds_each_contributed_action` and the
Escape ladder's tests pass.

Function calls per Tab on the 8-section `asks` page, V8's precise coverage: 152,138
to 113,224.
`pageControls()` read every field of every row whenever the floating panel drew,
and the panel draws its field's way out on each paint, which asks only whether a
row is an exit. The Page Map row's group asks `railStands()`, which reads the
layout box's computed style and so forces a style recalculation partway through a
click's paint. Each row's `group` is now a getter, read when a menu sorts the rows
into its groups.

Keeps: every group a menu shows, read at the moment it asks, so the Page Map still
moves between Navigate and the keys group as the rail comes and goes. The menu's
tests pass; `test_the_menu_s_search_finds_rows_threads_and_commands` fails on its
base too, with the same unchanged write and accessible name.

Least of four interleaved rounds, a click's main thread on the `asks` page, with
style recalculation in brackets: 20.9 (3.7) to 21.3 (2.4) ms at 8 sections, 34.4
(3.5) to 28.4 (2.2) ms at 64.
`layoutBox` and `layoutParts` found a page of parts with
`main.querySelector(':scope > [data-lf-views="parts"]')`, and the document layout
found the Layout's header with `:scope > header`. Each walks every element under
the box to find one of its children, and the layout box is read about four times a
keystroke and twenty times a click. Both now read the box's children.

Keeps: the same element, since both selectors only ever matched a child of the box.
The page-of-parts, part and fixed-box tests pass.

On the 64-section `asks` page in Chromium, one read of the parts took 0.016 ms by
`:scope >` and 0.001 ms by the children. Firefox's profiles at 512 sections put the
two reads at about 3 ms a keystroke.
…ing box reads

The browser/AGENTS.md paragraphs on `:has()` with native focus and on universal
`::highlight()` rules now say what the traces showed (a focus move restyling most of
the page twice; every restyle paying for the highlight rules) rather than a guess at
the engine's mechanism. repaint.js says, where it orders the painters, that the
resting box shows the comment key the input hint has just read (`restFab`,
composing/surface.js), so a reorder sees the dependency.

No behavior changes.
focus.js painted its marks only for focus it heard move, so a control focused
before the module loaded, as `autofocus` does, wore no `data-lf-focus` or
`data-lf-focus-visible` until the next move. A choice's ring is drawn from those
marks alone since d353bb5, so the ring the native selector drew there was lost.
The module now starts its paint from the focus it finds.

Keeps: every later paint, which still follows the moves it hears. On a served page
the arrival lets go of that early focus soon after (`releaseFocus` through
user-intent.js's handoff), on the base too, so this covers the time before that,
and any document that keeps it.

Tested by focus.test.mjs, which focuses an input before importing the module: the
test fails without this change and passes with it.
When `main` carries no Layout, `layoutBox` read the visibility and computed style
of each of `main`'s children to find the one that does, so a page of 500 sections
written straight into `main` made 501 style reads per lookup, and the runtime looks
the box up about four times a keystroke and twenty times a click. layouts.css
already marks the shell holding a layout box, for its container size; the same rule
now also declares `--lf-layout-shell`, and `layoutBox` reads only the children of
`main` or of a part that says it is a shell.

Keeps: the box found. The new lookup answered the same element as the old on pages
of 9 and 501 plain sections and on a `layout-sidebar` article, and the Layout and
page-of-parts tests pass. With the lookup never finding a shell,
`test_each_part_of_a_page_of_parts_is_laid_out_as_a_page_of_its_own` fails.

One lookup in Chromium, least of 50: 0.028 to 0.006 ms with 65 children of `main`,
0.23 to 0.05 ms with 501.
ebcbc20 paints the focus the document held when focus.js loaded, and an element's
ring then follows the platform's `:focus-visible`. A frame never matches it, so its
ring follows the input that put the user there (`visibleFocus`), and the module had
heard none: a frame the user clicked into while the modules loaded wore a keyboard
ring they never asked for, where before ebcbc20 it wore no mark. The seeded frame
now starts as a press into it leaves it (`inputInFrame`), and the next input it
reports decides.

Keeps: an element seeded with focus wearing exactly the ring `:focus-visible` gives
it. A frame entered by Tab before the runtime loaded also starts without a ring, as
it did before ebcbc20, since no input reached the module to say otherwise.

focus.test.mjs now seeds a frame, which wears `data-lf-focus` and no
`data-lf-focus-visible`; it fails without this change. happy-dom matches
`:focus-visible` on a frame's host, which no browser does, so the test answers that
selector as a browser would.
@max-sixty
max-sixty merged commit 018fc25 into main Nov 5, 2026
4 checks passed
@max-sixty
max-sixty deleted the per-input-fixed-cost branch November 5, 2026 12:13
max-sixty added a commit that referenced this pull request Nov 5, 2026
… map restyling the page (#5493)

A click was the input closest to its budget on a page of real size (root
`AGENTS.md`, "Responsiveness": the server's reading on screen within 100
ms), and most of its browser time went to the margin redrawing entries
the click didn't change: every render re-presented all of the margin's
clusters and renamed every marker. Now the margin redraws only the
entries whose inputs changed, and removing or adding a margin row no
longer restyles most of the page.

Main-thread ms per click in Chromium, `b5f5c5d43` against this branch,
least of three interleaved rounds:

| sections | ticking an option | answering an ask (a marker goes, a row
comes) |
|---|---|---|
| 8 | 15.8 → 15.4 | 26.6 → 25.9 |
| 64 | 28.2 → 24.7 | 74.9 → 66.4 |
| 512 | 97.1 → 74.4 | 441.6 → 328.2 |

**The inventory owns whether an entry changed.** `keptEntry`
(`annotation-inventory.js`) keeps a margin entry as the same object
while everything it is built from is unchanged, compared against the
previous collection with the existing `share`; `marginInventory` becomes
`marginEntry`, which builds one entry from one group
(`margin-model.js`). Change entries record `cardOpen`, since the entry's
relation reads it.

**The renderer compares identities only.** `renderNow`
(`margin-projection.js`) presents a cluster again only when its entry
object or its own inputs change (the expanded owner, the forced card
row, the fold, the agent's name), and a marker whose position number
changed only gets its new name. Page-wide margin reads (the rail's tab
stop, key reflections, label placement) run only after a row changed.

**The contents map's spine.** `toc.css`'s `lf-toc + *` matched whatever
followed the map, Leaf's own boxes included, so a row coming or going
restyled 27,630 of 28,336 elements at 512 sections. It is now `lf-toc +
:not(.lf-ui)`, which clears the same authored blocks and restyles 8,212;
this is most of the answering click's gain at 512.

An earlier commit here also skipped the second full layout pass a new
row runs (ResizeObserver's first report for boxes the first pass starts
watching). Review found it could drop real size changes (a content box
narrowing under a classic scrollbar, an SVG target resized under a
compensating transform, a writing-mode switch), so it is reverted and
both passes run as on main; the test for the scrollbar case stays.

Checked: `pnpm run test:runtime` (817 pass, with a new
`annotation-inventory.test.mjs`), `pnpm run check:browser`, and 77
browser tests by node id across margin, comparison, version, thread
surface, scrollers, pins, rail, cards and the contents map, on the tree
merged with main. Independent Codex review of each commit; the inventory
and renderer change and the `toc.css` selector came back sound.
`aria-expanded` is now asserted in
`test_a_change_s_card_reads_it_in_order`, which fails without
`cardOpen`.

Left for later, measured at 512 sections: a row's arrival still runs two
layout passes (about 150 ms each); every render still reads every
eligible target's rect (`readSpokenPositions`, 512 reads) and collects
the whole inventory (10–15 ms); `::highlight()` rules that match every
element still restyle the margin's rows (#5479 scopes the text
document's and suggestions'; the comment marks' stay universal, since
Firefox paints nothing nested under a scoped form); publishing the
page's state takes about 25 ms per click.

Ref #5194

> _This was written by Claude Code on behalf of max-sixty_
max-sixty added a commit that referenced this pull request Nov 5, 2026
…5515)

The daily scaling test fails a cost that grows faster than the page, and
nothing else, and each run's readings left with its temporary directory.
A change that slowed pages of every size alike passed unseen: the Tab
cost #5479 halved was 17.5 ms on a page of any size, and no test saw it.
Max chose to keep the readings and chart them.

- `tests/journeys/test_scaling.py` now takes each size's lower reading
once and uses it for both jobs: the growth check, as before, and a file
per axis under `.tmp/test-results/scaling/`, holding the readings at 64
sections (the size of the largest real pages) in
github-action-benchmark's `customSmallerIsBetter` form. The `test` job's
existing artifact upload carries them.
- The test now measures the page a user gets, through
`browser.unwatched`, as `leaf-dev scaling` does. Until now it measured
the suite's watched page, whose watches instrument every timer, write
and input: this PR's first CI run read a keystroke at 64 sections as 404
ms on the asks page and 167 on prose, and the prose page read 49 ms
watched against 7 unwatched on this Mac. The growth check's exponents
carried that overhead too.
- A new `scaling-chart` job in `ci.yaml` runs after `test` on the daily
schedule only. It downloads that artifact, merges the four axes' files
with `jq`, and hands them to
[github-action-benchmark](https://github.com/benchmark-action/github-action-benchmark),
which appends them to `dev/bench/data.js` on the `gh-pages` branch,
keeps a chart of each reading there, and comments on the commit whose
run reads 50% above the run before. It has its own checkout because the
action switches the checkout to `gh-pages`, and `contents: write` for
that push and the comment.
- Each run's job summary also shows its readings beside the run before
(`summary-always`).
- The `gh-pages` branch exists, empty, so the first run has somewhere to
write. GitHub Pages doesn't serve it: the repo's Pages settings still
name leaf.page, which Cloudflare serves, and no workflow deploys Pages.
The chart is `dev/bench/index.html` on the branch, which
https://raw.githack.com/max-sixty/leaf/gh-pages/dev/bench/index.html
renders once the first run has written it.
- The action compares a reading with the last one from another commit,
so a day with no merge compares with the day before it, and could repeat
an alert or miss the first day's.

50% is a first guess at CI's run-to-run spread on CPU time; tighten it
once a few weeks of the chart show the real spread.

This pull request runs the edited test, which writes the readings in its
artifact; the chart job itself first runs on the next daily schedule
after merge.

> _This was written by Claude Code on behalf of max-sixty_
leaf-agent added a commit that referenced this pull request Nov 7, 2026
…ld skips its motion (#5688)

#5479 moved the diff package's rule that a fold closed from the keyboard
skips its motion (`packages/diff/styles/disclosure.css`) from native
`:focus-visible` to Leaf's `data-lf-focus-visible` mark, to cut restyle
cost. But `focus.js` repainted that mark only in a `setTimeout` after a
keydown. A summary focused by a click and then closed with Enter has no
focus event; native `:focus-visible` switches on at the key, while the
mark arrived a task later. So the fold had already started its full
transition, and dropping the duration to `0s` afterwards didn't stop the
running transition. The test's stretched timeline then held the fold at
its halfway height (`85.95 == 85.95` in the failure).

The keydown listener now also queues the focus paint, so the mark lands
when the listener ends, before the key's default action runs. That is
the same moment native `:focus-visible` changes. #5479's intent stays as
it was (rules read Leaf's marks, not native focus), and keyboard closes
are instant again. A repaint with unchanged focus walks only the focused
node's ancestry, so a keystroke pays nothing that grows with the page.

Verified locally:
- `test_evidence_close_folds_room_but_retires_controls_immediately`:
`[browser-call]` and `[browser-file]` fail on main and pass with this
change. The two Firefox cases also pass.
- `pnpm run test:runtime`: 896 pass.
- 167 browser tests matching `ring` / `focus_ring` / `focus_visible`
pass.

Closes #5659 — automated triage

Co-authored-by: leaf-agent <[email protected]>
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.

2 participants