Skip to content

perf(sdk): a re-render leaves unchanged hotkeys alone - #1187

Merged
allisonmahmood merged 1 commit into
mainfrom
hotkeys/bindings-cost-1162
Nov 4, 2026
Merged

allisonmahmood merged 1 commit into
mainfrom
hotkeys/bindings-cost-1162

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

What changed

useBindings updated every binding after every commit of the component that registers them. A whiteboard registers about 50 hotkeys from a component that re-renders on each collaborator's move. In Chromium on a fast, idle workstation, that cost p50 270 µs and p95 500 µs per commit, right at the issue's 0.5 ms bar. With the CPU throttled 2×, it was p50 1.7 ms and p95 4 ms. Now a re-render that changes nothing about the bindings leaves them alone, and each hotkey still runs its latest run.

Closes #1162

Look at

  • Where the time went. A CPU profile of the 50-binding component, re-rendering every few milliseconds, splits it in two:

    • TanStack's update took about 60%. It re-parses every hotkey on each call (normalizeHotkey), and detectPlatform() lower-cases the navigator's platform and user agent once per binding. That function alone was the largest self-time.
    • Our permitted() took about 30%: it normalized every hotkey again during render to look for the reserved Mod+Shift+K.

    TanStack's own equality check stops it from publishing unchanged options, but only after all of that work.

  • The change, in packages/patchy/src/hotkeys.ts and hotkeyRules.ts:

    • The update effect depends on each binding's shape: hotkey, label, group, enabled and whileTyping, plus the enclosing HotkeyScope. While that holds, the registrations aren't touched. When it changes, they update in place as before, so a sequence in progress isn't restarted.
    • Each registration's callback reads the binding from the latest commit through a ref, so run and repeat stay current without an update.
    • permitted() remembers, per hotkey string, whether it binds the reserved chord.
    • The duplicate warning now runs with the update, so it also notices a scope change.
  • Numbers. Per-commit cost of one 50-binding useHotkeys call in headless Chromium, re-rendering on an 8 ms timer. Each case ran 3 rounds of 2,000 commits, the first 300 of each round dropped. Bundles and cases alternated round by round. The page is cross-origin isolated, so performance.now() resolves to 5 µs. The window runs from just before the call in render to a layout effect just after it. memo reuses one binding table, as the whiteboard does with useMemo. fresh builds a new table with new closures on every render.

    main p50 main p95 this PR p50 this PR p95
    quiet machine (load ~2), memo 270 µs 500 µs 25 µs 60 µs
    quiet machine, fresh 270 µs 390 µs 20 µs 50 µs
    CPU throttled 2×, as a rough laptop, memo 1,690 µs 3,990 µs 65 µs 325 µs
    CPU throttled 2×, fresh 1,310 µs 2,960 µs 60 µs 315 µs
    loaded machine (load ~40), memo 370 µs 710 µs 25 µs 55 µs
    loaded machine, fresh 285 µs 570 µs 30 µs 75 µs
    the same component with no hotkeys 10–35 µs 30–245 µs

    On an idle, fast workstation, main's p95 sits right at the issue's 0.5 ms bar. With the CPU throttled, or other work on the machine, it is well over. With this PR, the hotkeys add about 15 µs to a commit, close to the no-hotkeys baseline in every case. Skipping the update alone, without remembering permitted()'s answer, left p50 at 100 µs and p95 at 175–360 µs on the loaded machine.

    The measured component
    function Board() {
      const [tick, setTick] = useState(0);
      useEffect(() => {
        const id = setInterval(() => setTick((t) => t + 1), interval);
        return () => clearInterval(id);
      }, []);
      const memo = useMemo(() => table(0), []);
      const bindings = mode === "fresh" ? table(tick) : memo;
      const start = performance.now();
      if (mode !== "baseline") useHotkeys(bindings);
      useLayoutEffect(() => {
        samples.push(performance.now() - start);
      });
      return h("p", null, String(tick));
    }
    // table(): 50 chords shaped like the whiteboard's (single keys, digits, Delete, Backspace,
    // Escape, Mod/Mod+Shift/Mod+Alt chords, arrows, ?), each with a label, a group and
    // whileTyping: false.
  • Callbacks stay fresh. A new browser step in the lifecycle test has a counter whose useHotkey("I", …) closes over the count it rendered with, so run changes every render while nothing else does. Pressing I three times must read 1, 2, 3. With the callback reading the binding captured at registration instead, the step fails:

    Error: expect(locator).toHaveText(expected) failed
    Expected: "2"
    Received: "1"
    

    With the change, all four hotkeys browser tests pass (4 passed), including the existing ones for sequences, scopes, remounts mid-press, conflict warnings and the sheet.

How it was verified

Locally, with CI on this PR as the judge for the full suite:

  • pnpm check: format, lint, typecheck and synth pass. Its offline tests failed only in suites this change doesn't touch: stray GET / requests to the CLI's local stub servers and timeouts on a heavily loaded shared machine.
  • vitest run on hotkeys.test.ts, hotkeyRules.test.ts, hotkeySheet.test.ts and pageImports.test.ts: 39 of 39 pass.
  • playwright test -c playwright.tier1.config.ts --project=chromium hotkeys: red then green, as above.
  • The benchmark and CPU profile above, run outside the repo against main and this branch's built package.
  • Not run locally: pnpm verify, which the machine's load ruled out.

Release impact

  • Breaking — requires action from anyone already running this
  • Not breaking — no action required

Internal to the patch-side SDK: the same hotkeys register with the same options, only less often.

  • What does a revert leave behind? Nothing: no schema, data or contract. Patches built with this SDK keep it until they refresh.
  • Does the release before it still work with that? Yes.

Built by Claude Opus 5.5 (claude-opus-5-5) in Claude Code, through T3 Code.

@github-actions github-actions Bot added area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area size:s Under 100 changed lines labels Nov 1, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Review (GPT 6.1 Sol, xhigh) on a163c6e: PASS, no findings.

  • What triggers an update: a change to the hotkey, label, group, enabled, whileTyping or scope. run and repeat read the latest committed binding, and a callback-only change skips TanStack's option update.
  • Still current: option changes, removed metadata, reordered tables, typing behaviour and scope changes.
  • Sequences and repeats: a sequence in progress survives an update and runs the latest callback. repeat: false still works across remounts.
  • Warnings and the list: duplicate warnings and useHotkeyList reflect the current registrations.
  • The test: the freshness test fails if the callback is captured at registration.
  • The benchmark: comparative runs reproduced the improvement.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Acceptance: PASS

Checked a163c6ed9cdf84c59d70cd838a2c7a5d2522a602 (base 1f187a9, main) on team, by Claude Opus 5.5 (claude-opus-5-5) in Claude Code, through T3 Code.

How: pnpm dev up team at the head, then patchy init a tier 1 repo with the environment's CLI. Its installed patchy release carried the change. The check patch is whiteboard-shaped: one useHotkeys call with 50 bindings, single keys, digits, Delete, Backspace, Escape, Mod, Mod+Shift and Mod+Alt chords, arrows and a G H sequence, plus a useHotkey and a <HotkeySheet />. The table is rebuilt with new closures on every render, and an 8 ms timer re-renders the board, about 125 commits a second in the published frame. I published it as Ada and drove it with real key presses in headless Chromium.

Done means

  • The PR reports p50 and p95 per commit for a 50-binding useHotkeys re-rendering on a timer, in Chromium: passed. I also measured it independently. I bundled the same kind of component against main's and the head's built patchy package and served it cross-origin isolated. Each case ran 3 rounds of 2,000 commits, the first 300 of each round dropped, in alternating order, on this shared machine at load ~3–4:

    µs per commit main p50 main p95 head p50 head p95
    memo table 280 410 20 50
    fresh table each render 285 600 25 55
    CPU throttled 2×, memo 535 825 25 240
    CPU throttled 2×, fresh 555 1,740 35 265
    no hotkeys, head 10 (2×: 10) 25 (2×: 40)

    main's p95 crosses the issue's 0.5 ms bar in three of the four cases. The head lands within 10–25 µs of the no-hotkeys baseline at p50. The direction and size match the PR's table; absolute numbers differ by machine.

  • Unchanged bindings skip the update while callbacks stay fresh: passed, in the published board while it re-renders:

    • 12 presses across the table each ran their binding once, with the tick of the latest commit (tick N committed N), and the tick advanced between presses. The keys were A, Q, 7, Delete, Mod+Z, Mod+Shift+Z, Mod+Alt+C, ArrowLeft, Shift+ArrowUp, the separate useHotkey("K"), and A twice.
    • Changing a label, enabled and a group updates the sheet, both while it's open and when it's reopened. Draw becomes Erase, a disabled Mod+D is absent and then listed once enabled, and Mod+G moves from Arrange to Layout. Enabled, Mod+D fires with a fresh tick; disabled again, it doesn't fire and leaves the sheet.
    • repeat isn't part of the shape, and the latest render's value is read anyway: holding R for 4 keydowns fires 4 times, and after a re-render sets repeat: false it fires once.
    • Flipping whileTyping to true makes W fire in a text field without being typed. By default it waits there and is typed.
    • A sequence survives a shape change: G, then a label change, then H fires G H once, fresh.
    • A duplicate added by a re-render warns once, naming both, and doesn't warn again while the board keeps re-rendering: patchy/hotkeys: "Tool X" and "Cross" both use X in the same scope, so both fire on each press. Removing it leaves only the original firing.
Key-press results in the published frame
PASS  50 bindings in one useHotkeys call  "50 bindings"
PASS  board re-renders often (commits per second)  125
PASS  each press ran its binding once, with the latest tick  ["A tick 131 committed 131","Q tick 159 committed 159","7 tick 189 committed 189","Delete tick 218 committed 218","Mod+Z tick 247 committed 247","Mod+Shift+Z tick 275 committed 275","Mod+Alt+C tick 305 committed 305","ArrowLeft tick 334 committed 334","Shift+ArrowUp tick 363 committed 363","K tick 392 committed 392","A tick 421 committed 421","A tick 449 committed 449"]
PASS  ticks advance between presses (closures were replaced)
PASS  G, then a label change, then H: G H still fires, fresh  ["G H tick 488 committed 488"]
PASS  sheet open: Draw listed, Mod+D (disabled) not, Mod+G under Arrange  {"groups":["Tools","Arrange","General"],"tools":47}
PASS  while open: label change shows Erase, not Draw  ["Erase"]
PASS  while open: enabling Mod+D lists it  ["Tool Mod+D"]
PASS  while open: group change moves Mod+G to Layout  ["Tools","Layout","General"]
PASS  enabled Mod+D fires, fresh  ["Mod+D tick 564 committed 564"]
PASS  disabled again: Mod+D doesn't fire  []
PASS  closed then reopened: Mod+D gone, Erase still listed
PASS  repeat on: holding R fires on each repeat  4
PASS  repeat: false after a re-render: holding R fires once  1
PASS  W waits in a field by default  [[],"w"]
PASS  after whileTyping: true, W fires in the field and isn't typed  [["W tick 677 committed 677"],"w"]
PASS  adding a second X warns once naming both labels
PASS  both X bindings fire  ["X tick 742 committed 742","Cross"]
PASS  no repeat warning while the board keeps re-rendering  1
PASS  removing it: only Tool X fires  ["X tick 824 committed 824"]
PASS  board still ticking at the end  "835"

CI on the head is green, including browser, which runs the PR's new lifecycle step.

Golden journeys

  • Publish a page: passed in part. The environment's CLI published the board as Ada, and it opened at its address with its frame. Ben's view wasn't checked: the change doesn't touch serving.
  • The others aren't touched: the diff is the patch-side hotkeys hook, the reserved-chord check and a browser test.

Rollback answers: they match the diff. A revert leaves no schema, data or contract. Patches built with this SDK keep the faster hook until they refresh, and the release before works with them.

Not run

  • Nothing Done means asks for. I didn't try macOS (⌘) or other browsers: the SDK targets Chromium desktop, and nothing in this change depends on the platform. CDP CPU throttling stood in for a slow laptop, as in the PR.

@allisonmahmood
allisonmahmood force-pushed the hotkeys/bindings-cost-1162 branch from a163c6e to 878dea3 Compare November 4, 2026 01:29
@allisonmahmood
allisonmahmood merged commit 399486d into main Nov 4, 2026
23 checks passed
@allisonmahmood
allisonmahmood deleted the hotkeys/bindings-cost-1162 branch November 4, 2026 01:42
allisonmahmood added a commit that referenced this pull request Nov 4, 2026
…ges publish (#1241)

## What changed

This adds release 36's What's new entry, written from `1acc968`. It
covers everything merged since release 35's `through` (`dd0e2ec`), and
sets the `patchy` release to `0.36.0` in `packages/patchy/package.json`
and `CURRENT_RELEASE`.

| Change | PRs |
| --- | --- |
| Improved: shortcuts work where you use them (keys for one part of a
patch, the closest wins, text boxes keep their typing keys) | #1231 |
| Improved: the shortcuts sheet shows what works where you are (Ctrl+/
and ⌘/ open it, its commands run, it opens from a patch's menu and in
view on a narrow screen, keeps the look, spells keys out away from a
Mac) | #1231, #1181, #1178, #1180, #1177 |
| Fixed: keys pressed while a patch opens reach it | #1183 |
| Fixed: pages styled with Tailwind 4 publish, and a look with the same
rule saves | #1191 |
| Fixed: an old copy of a patch no longer replaces newer work
(**Breaking** for such a copy: it needs `patchy pull` or one
`--allow-behind` publish) | #1179 |
| Improved: your agent can check a publish before sending it | #1188 |
| Improved: your agent hears what changed when it updates a patch |
#1186, #1185 |
| Fixed: your agent stops chasing false alarms (`pnpm install` exit
codes, `manifest.json` bytes, the description notice, a copied dev
record) | #1176, #1174, #1175 |
| Behind the scenes: fuller hotkeys instructions for agents; fewer
redraw costs for patches with many shortcuts | #1182, #1187 |

`patchChanges` has three sentences for the agent refreshing a patch
across this release:
- #1231's, from its PR: text fields keep their keys, `preventDefault()`,
and the sheet's Mod+/ and `.hotkey-row` buttons.
- The sheet's dialog renders in `document.body`, and element-only page
rules don't reach it (#1178, #1180). Its own row lists last (#1181). The
hotkey label helpers take only valid literals (#1177).
- Publish's `unknown_base_version` (#1179).

It also rewords release 33's "Press ? to see every shortcut a patch
has". That was true only for a patch that mounts the shortcuts sheet, so
it now says a patch *can* list its shortcuts.

The rest get no line:
- #1206, #1207, #1209 and #1220 are `pnpm dev eval` tooling.
- #1222 is release 35's own entry.

## Look at

- **The entry**, at the top of `releases` in
`packages/core/src/whatsNew.ts`, and release 33's reworded line.
- **Rollback safety, from the live commit `d28fdd0` (release 35) to
`1acc968`:**
- #1191 is labelled `one-way`. Its Release impact: a company look
published after this release with a nested `@supports` condition stays
stored after a revert. Release 35 refuses any bundle carrying it, so
repo publishes in that company would fail until an admin runs `patchy
look restore` to an earlier revision. Pages and Tailwind 4 repos already
published stay published.
- #1183 is the only change to what the server serves browsers: the
shell's script, under a digest-named URL. Its revert leaves nothing
behind.
- The hotkeys PRs change `patchy/hotkeys`, which patches bundle when
they are built. Published patches keep their copy.
- The CLI PRs change what a CLI writes and refuses. Release 35 reads
everything they leave behind: #1176's `allowBuilds` entry, #1174's
indented `manifest.json`, and the `version` recorded by an
`--allow-behind` publish.

**Rollback line:** If this release misbehaves, roll back to `d28fdd0`
(release 35). First check that no company's look has a nested
`@supports` condition, and `patchy look restore` an earlier revision
where one does (#1191).

## How it was verified

- **Tests.** `whatsNew.test.ts`, `WhatsNewPages.test.ts` and
`schemas.test.ts` pass (22 tests), and `bun fmt` passes on the changed
files.
- **Facts.** The sheet's new `document.body` home and its element-rule
reset were checked against `hotkeys.ts` and `hotkeySheet.ts` on main.
- **Deploy state.** I pinned the live commit from `/healthz/deep`:
`d28fdd0` (release 35). The Deploy run updated last succeeded, and none
is unfinished.

## Release impact

- [ ] **Breaking** — requires action from anyone already running this
- [x] **Not breaking** — no action required

Text and version numbers only. Like every release, the `0.36.0` bump
tells CLIs and patch repos installed before this deploy to upgrade.

- **What does a revert leave behind?** Nothing.
- **Does the release before it still work with that?** Yes.

Built by Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, through T3
Code.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area size:s Under 100 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Measure what re-applying every hotkey on each render costs

1 participant