Skip to content

perf(web): equations no longer force a layout when a thread opens - #37639

Closed
zhaoshenzhai wants to merge 3 commits into
pingdotgg:mainfrom
zhaoshenzhai:fix/math-overflow-commit-layout
Closed

zhaoshenzhai wants to merge 3 commits into
pingdotgg:mainfrom
zhaoshenzhai:fix/math-overflow-commit-layout

Conversation

@zhaoshenzhai

Copy link
Copy Markdown

Problem

Switching to a thread with math is slow. Every MarkdownMath checked whether it overflows in a layout effect, reading scrollWidth mid-commit. That read forces a layout of everything the commit inserted, which on a thread switch is the whole new thread. The timeline list's layout effect then moves its rows (sortContainerElements) and reads getBoundingClientRect, so the browser lays the thread out again. With math rendering on, that layout is the most expensive one in a switch.

Change

The layout effect no longer measures. It already observes the viewport and content through observeResize, whose first delivery comes after layout and is flushed before paint, so overflows is still correct in the first painted frame. overflows only sets tabIndex and an aria-label, so nothing about layout depends on it.

Scope

A small fix for a real performance problem, with no behavior change. It needs no issue.

Verification

Test. MarkdownMath.browser.test.tsx gains a case that mounts a short and an overflowing equation. It counts scrollWidth reads before a later sibling's ref attaches, and checks that the overflowing equation still becomes keyboard scrollable. On main it fails with expected 2 to be +0; here it passes, with the existing keyboard-scroll case. vp run check:changed passes.

Measurement. I found this by profiling thread.next (mod+shift+]) in a production build of the web client (vp build, served in place of the dev client's assets). The server was a scenario home (start-app.ts) with six Replay threads of six turns each, using a recording whose reply has about 50 inline and display formulas, plus mathRenderingEnabled. Instrumenting the layout reads showed three forced full layouts per switch, each about 80 ms on this machine, in this order: MarkdownMath scrollWidth (≈90 ms), legend-list measureContainersInLayoutEffect (≈82 ms) and the scroll area's scrollHeight (≈74 ms). With this change the first one is gone.

Median from keydown to the next thread's history on screen and painted (5 switches per phase, 2 runs each, alternating base and head, headless Chromium on an Apple Silicon Mac):

Thread being opened main This PR
Never opened in this page 382 / 370 ms 293 / 289 ms
Visited, page reloaded (persisted cache) 348 / 351 ms 270 / 265 ms
Visited in this page: keydown event duration 112 / 108 ms 88 / 80 ms

Not checked: the desktop app itself, and threads without math (no formulas means no reads, so nothing changes there).

Built by Claude Opus 5.5 in Claude Code, running in T3 Code.

🤖 Generated with Claude Code

Every equation measured whether it overflows in a layout effect, which read
scrollWidth mid-commit and forced a layout of everything the commit inserted.
On a thread switch that is the whole new thread, and the timeline list's own
layout effect writes to the DOM right after, so that layout was thrown away
and done again. The equation already observes its viewport and content, and
the observer's first delivery comes after layout and is applied before paint,
so the extra measure is removed.

Built by Claude Opus 5.5 in Claude Code, running in T3 Code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added vouch:unvouched Author is not yet trusted in the VOUCHED list. size:S 10-29 changed lines (additions + deletions). labels Nov 16, 2026
@macroscopeapp

macroscopeapp Bot commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

Approvability

Verdict: Approved at 214a8ce

Macroscope's review found this PR approvable — Equation overflow measurement now waits for the existing resize observer rather than forcing layout when a thread opens. The change is limited to UI measurement timing, with existing overflow handling and cleanup retained.

You can add or adjust custom eligibility rules. Learn more.

@coderabbitai

coderabbitai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

MarkdownMath now updates equation overflow state through the resize observer callback instead of measuring overflow immediately. A browser test checks that no scrollWidth read occurs during ref attachment and that the overflowing equation's scroller has tabindex="0".

Changes: Equation overflow handling

Layer / File(s) Summary
Resize-based overflow state
apps/web/src/components/chat/MarkdownMath.tsx, apps/web/src/components/chat/MarkdownMath.browser.test.tsx
MarkdownMath updates overflow state through the resize observer callback. The browser test checks measurement timing and confirms that the overflowing equation's scroller has tabindex="0".

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Refactor

Possibly related PRs

  • pingdotgg/t3code#23954: Changes the same MarkdownMath overflow logic and uses the shared observeResize helper.

Suggested reviewers: only21mil

Merge Risk: Minimal · up to a29a5

This change avoids a forced layout when a thread with equations opens. Overflow state now updates just after layout instead of synchronously, and it only affects focusability and an accessibility label. No merge-blocking risk was found.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: MarkdownMath no longer forces a layout (reads scrollWidth) when a thread opens. It matches the raw summary, which says the layout effect no longer measures overflow sy…
Description check Passed The description follows the template's sections: Problem, Change, Scope, and Verification. The Problem section explains the forced layout during thread switches with reproduction context. The Change s…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: MarkdownMath no longer forces a layout (reads scrollWidth) when a thread opens. It matches the raw summary, which says the layout effect no longer measures overflow synchronously, and the PR objectives, which describe removing overflow measurement from the layout effect. The title follows the conventional commit style the template recommends.

Full details: Description check

Explanation

The description follows the template's sections: Problem, Change, Scope, and Verification. The Problem section explains the forced layout during thread switches with reproduction context. The Change section explains why the removed measurement is safe, since observeResize delivers the first overflow state before paint. The Scope section states this is a small bug fix that needs no issue. The Verification section names the new browser test, the failing and passing results, the vp run check:changed run, and profiling and timing tables. It also states what was not checked. The description does not include before/after screenshots, but the change is a performance fix with no visual change, so the template's UI screenshot requirement does not apply. It also includes the required model and harness attribution.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 214a8ce and a29a5c5.

Files selected for processing: 2

  • apps/web/src/components/chat/MarkdownMath.browser.test.tsx
  • apps/web/src/components/chat/MarkdownMath.tsx

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

@juliusmarminge juliusmarminge added the takeover:in-progress A takeover lead is working on this PR label Nov 16, 2026
@github-actions github-actions Bot added size:XS 0-9 changed lines (additions + deletions). and removed size:S 10-29 changed lines (additions + deletions). labels Nov 16, 2026
@juliusmarminge

Copy link
Copy Markdown
Member

The automated pipeline stopped on this pull request and will not merge it:

the fix is written and reviewed, but proving it needs something no worker has:

  • Permanent blocker: The requested proof requires Chromium on an Apple Silicon Mac, which is unavailable under this job's VM-only access rules; macOS access outside the device pool is explicitly unavailable. Linux measurements cannot establish the required same-platform performance result.
  • Neither the base slowness nor a head improvement exceeding run-to-run spread was measured. Preservation of keyboard scrolling was not verified.

It stays open for a person to finish or close.

@juliusmarminge juliusmarminge added takeover:blocked Takeover blocked; reason in the PR body and removed takeover:in-progress A takeover lead is working on this PR labels Nov 16, 2026
@zhaoshenzhai

Copy link
Copy Markdown
Author

Here are the measurements the pipeline couldn't take, from an Apple M4 on macOS 27.0.1 with Playwright 1.64.1's headless Chromium. Base is d427894 (this PR's merge base) and head is a29a5c5, both production builds (vp build).

Setup. A scenario home from start-app.ts with six Replay threads of six turns each. Each turn replays a recording whose reply has about 50 inline and display formulas and one display equation wide enough to overflow. mathRenderingEnabled is on. The page loads the built client in place of the dev client's assets, and the API and socket still go through the dev server. Each run times five thread.next (mod+shift+]) presses per phase, measuring keydown to the next thread's last message on screen and painted. For threads already in memory it uses the Event Timing duration of the keydown, since those render inside the keydown. Base and head runs alternate.

Run medians, four runs each:

Thread being opened base runs head runs
Never opened in this page 678, 702, 710, 697 ms 504, 493, 505, 492 ms
Visited, page reloaded (persisted cache) 678, 669, 672, 661 ms 470, 466, 474, 473 ms
Visited in this page (keydown duration) 192, 200, 184, 184 ms 144, 152, 152, 152 ms

Base spread is at most 32, 17 and 16 ms, and head spread at most 13, 8 and 8 ms. The medians of the run medians differ by 201, 199 and 36 ms, and every head run is faster than every base run. These numbers are higher than the ones in the description because this recording adds the wide equation.

Keyboard scrolling. In every run, base and head behaved the same. After a switch opened the thread, six equations had the "Scroll display equation" scroller. Clicking the text before the last one and pressing Tab reached that scroller (10 presses on both, with tabindex=0). Five ArrowRight presses moved its scrollLeft from 0 to 200. On the same Mac, MarkdownMath.browser.test.tsx passes on head, including the existing "keeps keyboard scrolling available as a streamed equation outgrows its viewport". On base the new case fails with expected 2 to be +0.

Harness (local only, not part of this PR)

apps/server/scripts/dev-replay-agent.ts gets one more SCENARIOS entry:

  { id: "heavy", name: "Heavy", file: "./dev-replay/heavy_transcript.ndjson" },

apps/server/scripts/dev-replay/heavy_transcript.ndjson:

{"type": "transcript_start", "provider": "acpRegistry", "protocol": "acp.ndjson-jsonrpc", "version": "1", "scenario": "dev_replay_heavy", "metadata": {"generatedBy": "local measurement"}}
{"type": "expect_outbound", "frame": {"kind": "request", "method": "session/prompt", "params": "<any>"}}
{"type": "emit_inbound", "frame": {"kind": "notification", "method": "session/update", "params": {"sessionId": "dev-replay-session", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "## Lifting the factorization\n\nLet $G$ be a finite group and $H \\le G$ a subgroup of index $n$. The transfer $V \\colon G \\to H^{ab}$ is defined by\n$$V(g) = \\prod_{i=1}^{n} h_i(g) \\, [H,H],$$\nwhere $g t_i = t_{\\sigma(i)} h_i(g)$ for a transversal $t_1, \\dots, t_n$.\n\n1. **Independence.** The class of $V(g)$ does not depend on the transversal, since replacing $t_i$ by $t_i k_i$ changes each factor by $k_{\\sigma(i)}^{-1} h_i(g) k_i$.\n2. **Homomorphism.** For $g, g' \\in G$ we get $V(gg') = V(g) V(g')$ because $\\sigma_{gg'} = \\sigma_g \\sigma_{g'}$.\n3. **Evaluation.** If $g$ is central then $V(g) = g^n [H,H]$.\n\n```python\ndef transfer(G, H, g):\n    reps = G.transversal(H)\n    acc = H.identity()\n    for t in reps:\n        s = G.coset_rep(H, g * t)\n        acc = acc * (s.inverse() * g * t)\n    return acc.abelianize()\n```\n\n| Step | Claim | Uses |\n| --- | --- | --- |\n| 1 | well defined | $k_i \\in H$ |\n| 2 | homomorphism | $\\sigma_{gg'} = \\sigma_g\\sigma_{g'}$ |\n| 3 | central case | $Z(G)$ |\n\nBy Burnside's theorem, if a Sylow $p$-subgroup $P$ satisfies $P \\le Z(N_G(P))$ then $G$ has a normal $p$-complement, so $G \\cong N \\rtimes P$ with $|N| = |G|/|P|$ and $\\gcd(|N|, p) = 1$.\n## Lifting the factorization\n\nLet $G$ be a finite group and $H \\le G$ a subgroup of index $n$. The transfer $V \\colon G \\to H^{ab}$ is defined by\n$$V(g) = \\prod_{i=1}^{n} h_i(g) \\, [H,H],$$\nwhere $g t_i = t_{\\sigma(i)} h_i(g)$ for a transversal $t_1, \\dots, t_n$.\n\n1. **Independence.** The class of $V(g)$ does not depend on the transversal, since replacing $t_i$ by $t_i k_i$ changes each factor by $k_{\\sigma(i)}^{-1} h_i(g) k_i$.\n2. **Homomorphism.** For $g, g' \\in G$ we get $V(gg') = V(g) V(g')$ because $\\sigma_{gg'} = \\sigma_g \\sigma_{g'}$.\n3. **Evaluation.** If $g$ is central then $V(g) = g^n [H,H]$.\n\n```python\ndef transfer(G, H, g):\n    reps = G.transversal(H)\n    acc = H.identity()\n    for t in reps:\n        s = G.coset_rep(H, g * t)\n        acc = acc * (s.inverse() * g * t)\n    return acc.abelianize()\n```\n\n| Step | Claim | Uses |\n| --- | --- | --- |\n| 1 | well defined | $k_i \\in H$ |\n| 2 | homomorphism | $\\sigma_{gg'} = \\sigma_g\\sigma_{g'}$ |\n| 3 | central case | $Z(G)$ |\n\nBy Burnside's theorem, if a Sylow $p$-subgroup $P$ satisfies $P \\le Z(N_G(P))$ then $G$ has a normal $p$-complement, so $G \\cong N \\rtimes P$ with $|N| = |G|/|P|$ and $\\gcd(|N|, p) = 1$.\n\n\nThe full expansion is\n$$a_{1} b_{1} \\cdot \\frac{x^{1}}{1!} + a_{2} b_{2} \\cdot \\frac{x^{2}}{2!} + a_{3} b_{3} \\cdot \\frac{x^{3}}{3!} + a_{4} b_{4} \\cdot \\frac{x^{4}}{4!} + a_{5} b_{5} \\cdot \\frac{x^{5}}{5!} + a_{6} b_{6} \\cdot \\frac{x^{6}}{6!} + a_{7} b_{7} \\cdot \\frac{x^{7}}{7!} + a_{8} b_{8} \\cdot \\frac{x^{8}}{8!} + a_{9} b_{9} \\cdot \\frac{x^{9}}{9!} + a_{10} b_{10} \\cdot \\frac{x^{10}}{10!} + a_{11} b_{11} \\cdot \\frac{x^{11}}{11!} + a_{12} b_{12} \\cdot \\frac{x^{12}}{12!} + a_{13} b_{13} \\cdot \\frac{x^{13}}{13!} + a_{14} b_{14} \\cdot \\frac{x^{14}}{14!} + a_{15} b_{15} \\cdot \\frac{x^{15}}{15!} + a_{16} b_{16} \\cdot \\frac{x^{16}}{16!} + a_{17} b_{17} \\cdot \\frac{x^{17}}{17!} + a_{18} b_{18} \\cdot \\frac{x^{18}}{18!} + a_{19} b_{19} \\cdot \\frac{x^{19}}{19!} + a_{20} b_{20} \\cdot \\frac{x^{20}}{20!} + a_{21} b_{21} \\cdot \\frac{x^{21}}{21!} + a_{22} b_{22} \\cdot \\frac{x^{22}}{22!} + a_{23} b_{23} \\cdot \\frac{x^{23}}{23!} + a_{24} b_{24} \\cdot \\frac{x^{24}}{24!} + a_{25} b_{25} \\cdot \\frac{x^{25}}{25!} + a_{26} b_{26} \\cdot \\frac{x^{26}}{26!} + a_{27} b_{27} \\cdot \\frac{x^{27}}{27!} + a_{28} b_{28} \\cdot \\frac{x^{28}}{28!} + a_{29} b_{29} \\cdot \\frac{x^{29}}{29!} + a_{30} b_{30} \\cdot \\frac{x^{30}}{30!} + a_{31} b_{31} \\cdot \\frac{x^{31}}{31!} + a_{32} b_{32} \\cdot \\frac{x^{32}}{32!} + a_{33} b_{33} \\cdot \\frac{x^{33}}{33!} + a_{34} b_{34} \\cdot \\frac{x^{34}}{34!} + a_{35} b_{35} \\cdot \\frac{x^{35}}{35!} + a_{36} b_{36} \\cdot \\frac{x^{36}}{36!} + a_{37} b_{37} \\cdot \\frac{x^{37}}{37!} + a_{38} b_{38} \\cdot \\frac{x^{38}}{38!} + a_{39} b_{39} \\cdot \\frac{x^{39}}{39!} + a_{40} b_{40} \\cdot \\frac{x^{40}}{40!}$$\n"}}}}}
{"type": "emit_inbound", "frame": {"kind": "response", "method": "session/prompt", "result": {"stopReason": "end_turn"}}}

scripts/scenarios/zz-thread-switch-paths.e2e.ts, run as SWITCH_MODEL=heavy SWITCH_MATH=1 SWITCH_DIST=<built apps/web dist> SWITCH_OUT=<prefix> T3_SCENARIO_INHERIT_ENV='SWITCH_*' pnpm exec e2e run scenarios/zz-thread-switch-paths.e2e.ts --target web from scripts:

// Disposable measurement, not a proof: times thread.next from keydown to the next thread's
// history on screen, for never-opened, persisted-cache and in-memory threads.
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";

import { chromium, type Page } from "playwright-core";

import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const THREADS = Number(process.env.SWITCH_THREADS ?? 6);
const TURNS = Number(process.env.SWITCH_TURNS ?? 6);
const OUT = process.env.SWITCH_OUT ?? "/tmp/switch";
const PROFILE = process.env.SWITCH_PROFILE === "1";

const instrument = (page: Page, markers: Record<string, string>) =>
  page.evaluate((markerMap) => {
    const w = window as unknown as { __m: { samples: Array<any>; events: Array<any> }; __hooked?: boolean };
    w.__m = { samples: [], events: [] };
    if (w.__hooked) return;
    w.__hooked = true;
    new PerformanceObserver((list) => {
      for (const e of list.getEntries() as Array<PerformanceEventTiming>) {
        if (e.name === "keydown") {
          w.__m.events.push({ start: e.startTime, duration: e.duration });
        }
      }
    }).observe({ type: "event", durationThreshold: 16 });
    window.addEventListener(
      "keydown",
      (event) => {
        if (event.key !== "}" && event.key !== "{") return;
        const sample: any = { t0: event.timeStamp, from: location.pathname };
        w.__m.samples.push(sample);
        const check = () => {
          if (location.pathname === sample.from) return false;
          sample.tUrl ??= performance.now();
          const id = decodeURIComponent(location.pathname.split("/").pop() ?? "");
          const marker = markerMap[id];
          if (!marker || !document.body.textContent?.includes(marker)) return false;
          sample.tDom = performance.now();
          requestAnimationFrame(() => {
            setTimeout(() => {
              sample.tPaint = performance.now();
            }, 0);
          });
          return true;
        };
        const observer = new MutationObserver(() => {
          if (check()) observer.disconnect();
        });
        observer.observe(document.body, { childList: true, subtree: true, characterData: true });
        // A thread in memory renders inside this keydown, before the URL changes, so poll too.
        const poll = () => {
          if (sample.tDom !== undefined) return;
          if (check()) observer.disconnect();
          else if (performance.now() - sample.t0 < 3000) requestAnimationFrame(poll);
        };
        requestAnimationFrame(poll);
      },
      { capture: true },
    );
  }, markers);

const collect = (page: Page) =>
  page.evaluate(() => (window as unknown as { __m: unknown }).__m);

test("thread.next paths", { ...WEB, timeout: 900_000 }, async ({ t3, app }) => {
  const project = await t3.project("demo");
  for (let i = 0; i < Number(process.env.SWITCH_FILLER ?? 0); i++) {
    await t3.thread({ project, title: `Filler ${i}`, messages: [`filler ${i}`] });
  }
  const ids: Array<string> = [];
  const markers: Record<string, string> = {};
  for (let i = 0; i < THREADS; i++) {
    const messages = Array.from({ length: TURNS }, (_, j) => `marker-t${i}-m${j}`);
    const thread = await t3.thread({
      project,
      title: `Thread ${i}`,
      messages,
      ...(process.env.SWITCH_MODEL ? { model: process.env.SWITCH_MODEL } : {}),
    });
    ids.push(thread.threadId);
    markers[thread.threadId] = `marker-t${i}-m${TURNS - 1}`;
  }
  const base = app.baseUrl ?? "";
  const environment = (
    (await (await fetch(`${base}/.well-known/t3/environment`)).json()) as { environmentId: string }
  ).environmentId;
  const pairing = NodeFS.readFileSync(NodePath.join(T3_HOME, "pairing-path"), "utf8");

  const browser = await chromium.launch({
    headless: true,
    args: ["--disable-features=LocalNetworkAccessChecks,BlockInsecurePrivateNetworkRequests"],
  });
  const results: Record<string, unknown> = {};
  try {
    const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
    if (process.env.SWITCH_MATH === "1") {
      await page.addInitScript(() => {
        const key = "t3code:client-settings:v1";
        const current = JSON.parse(localStorage.getItem(key) ?? "{}");
        localStorage.setItem(key, JSON.stringify({ ...current, mathRenderingEnabled: true }));
      });
    }
    if (process.env.SWITCH_COUNT === "1") {
      await page.addInitScript(() => {
        const stats: Record<string, { n: number; ms: number; slow: number }> = {};
        (window as unknown as { __layoutStats: unknown }).__layoutStats = stats;
        const wrap = (proto: object, prop: string, kind: "method" | "getter") => {
          const desc = Object.getOwnPropertyDescriptor(proto, prop)!;
          const original = (kind === "method" ? desc.value : desc.get) as (...a: Array<unknown>) => unknown;
          const timed = function (this: unknown, ...args: Array<unknown>) {
            const t = performance.now();
            const r = original.apply(this, args);
            const d = performance.now() - t;
            const s = (stats[prop] ??= { n: 0, ms: 0, slow: 0 });
            s.n++;
            s.ms += d;
            if (d > 1) {
              s.slow++;
              const log = ((stats as any).__slow ??= []) as Array<unknown>;
              log.push([prop, Math.round(t), Math.round(d), (new Error().stack ?? "").split("\n").slice(2, 7).map((l) => l.trim().replace(/\(.*\/assets\//, "(").replace(/^at /, "")).join(" < ")]);
            }
            return r;
          };
          Object.defineProperty(proto, prop, kind === "method" ? { ...desc, value: timed } : { ...desc, get: timed });
        };
        wrap(Element.prototype, "getBoundingClientRect", "method");
        wrap(Element.prototype, "getClientRects", "method");
        wrap(Element.prototype, "scrollWidth", "getter");
        wrap(Element.prototype, "clientWidth", "getter");
        wrap(Element.prototype, "scrollHeight", "getter");
        wrap(Element.prototype, "clientHeight", "getter");
        wrap(HTMLElement.prototype, "offsetHeight", "getter");
        wrap(HTMLElement.prototype, "offsetWidth", "getter");
        wrap(Element.prototype, "scrollIntoView", "method");
      });
    }
    const dist = process.env.SWITCH_DIST;
    if (dist) {
      await page.route(`${base}/**`, async (route) => {
        const request = route.request();
        const url = new URL(request.url());
        if (request.resourceType() === "document") {
          return route.fulfill({ path: NodePath.join(dist, "index.html") });
        }
        const file = NodePath.join(dist, decodeURIComponent(url.pathname));
        if (url.pathname !== "/" && NodeFS.existsSync(file) && NodeFS.statSync(file).isFile()) {
          return route.fulfill({ path: file });
        }
        return route.continue();
      });
    }
    const last = ids[ids.length - 1]!;
    const openLast = async () => {
      await page.goto(`${base}/${environment}/${last}`);
      await page.getByText(markers[last]!).first().waitFor({ timeout: 30_000 });
      await page.waitForTimeout(2500);
      await instrument(page, markers);
    };
    const pass = async (key: string) => {
      for (let i = 0; i < THREADS - 1; i++) {
        await page.keyboard.press(key);
        await page.waitForTimeout(1000);
      }
    };
    await page.goto(`${base}${pairing}`);
    await page.waitForURL((url) => !/\/pair(?:[?#]|$)/.test(url.pathname), { timeout: 60_000 });

    // Never opened in this browser: nothing cached.
    await openLast();
    await pass("Meta+Shift+BracketRight");
    results.fresh = await collect(page);

    // Visited before, page reloaded: the persisted cache holds them, memory does not.
    await page.goto(`${base}/`);
    await page.waitForTimeout(1500);
    await openLast();
    const pcdp = process.env.SWITCH_PROFILE === "persisted" ? await page.context().newCDPSession(page) : null;
    if (pcdp) {
      await pcdp.send("Profiler.enable");
      await pcdp.send("Profiler.setSamplingInterval", { interval: 100 });
      await pcdp.send("Profiler.start");
    }
    const resetStats = () =>
      page.evaluate(() => {
        const s = (window as unknown as { __layoutStats?: Record<string, unknown> }).__layoutStats;
        if (s) for (const k of Object.keys(s)) delete s[k];
      });
    await resetStats();
    await pass("Meta+Shift+BracketRight");
    results.persistedLayout = await page.evaluate(
      () => (window as unknown as { __layoutStats?: unknown }).__layoutStats ?? null,
    );
    if (pcdp) {
      const { profile } = await pcdp.send("Profiler.stop");
      NodeFS.writeFileSync(`${OUT}-persisted.cpuprofile`, JSON.stringify(profile));
    }
    results.persisted = await collect(page);

    // Keyboard scrolling of the wide equation in the thread the last switch opened.
    {
      await page.waitForTimeout(1500);
      const lead = page.getByText("The full expansion is", { exact: true }).last();
      await lead.click();
      let tabs = 0;
      let label: string | null = null;
      while (tabs < 30 && label !== "Scroll display equation") {
        await page.keyboard.press("Tab");
        tabs++;
        label = await page.evaluate(() => document.activeElement?.getAttribute("aria-label") ?? null);
      }
      const focused = { label, tabs };
      const before = await page.evaluate(() => (document.activeElement as HTMLElement).scrollLeft);
      for (let i = 0; i < 5; i++) await page.keyboard.press("ArrowRight");
      await page.waitForTimeout(500);
      const after = await page.evaluate(() => (document.activeElement as HTMLElement).scrollLeft);
      const scrollers = await page.getByLabel("Scroll display equation").count();
      results.keyboard = { focused, scrollLeftBefore: before, scrollLeftAfter: after, scrollers };
      await page.screenshot({ path: `${OUT}-keyboard.png` });
    }

    // Just visited: retained in memory.
    await pass("Meta+Shift+BracketLeft");
    await instrument(page, markers);
    const cdp = PROFILE ? await page.context().newCDPSession(page) : null;
    if (cdp) {
      await cdp.send("Profiler.enable");
      await cdp.send("Profiler.setSamplingInterval", { interval: 100 });
      await cdp.send("Profiler.start");
    }
    await pass("Meta+Shift+BracketRight");
    await pass("Meta+Shift+BracketLeft");
    if (cdp) {
      const { profile } = await cdp.send("Profiler.stop");
      NodeFS.writeFileSync(`${OUT}.cpuprofile`, JSON.stringify(profile));
    }
    results.warm = await collect(page);
    NodeFS.writeFileSync(`${OUT}.json`, JSON.stringify(results));
  } finally {
    await browser.close();
  }
});

Measured by Claude Opus 5.5 in Claude Code, running in T3 Code.

@github-actions

Copy link
Copy Markdown
Contributor

This PR conflicts with main. Rebase it or merge main into it. If it still conflicts after 7 days with no activity, it will be closed automatically.

See the conflict window.

@github-actions github-actions Bot added the needs-rebase Conflicts with its base branch. Closes after 7 days with no activity. label Nov 23, 2026
@juliusmarminge

Copy link
Copy Markdown
Member

Thanks for this. Main already has the change, as of 0fb6ac6.

Main already removes the forced layout this change targets. The renderer replacement in 0fb6ac6e65 deleted MarkdownMath and renders equations as static SVG with CSS scrolling, so there is no equation layout effect left to defer.

Your profiling identified a real cost in the previous renderer. The later measurements remain useful evidence, but this patch now targets code that has been removed.

Closing as superseded.

@zhaoshenzhai
zhaoshenzhai deleted the fix/math-overflow-commit-layout branch November 24, 2026 17:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-rebase Conflicts with its base branch. Closes after 7 days with no activity. size:XS 0-9 changed lines (additions + deletions). takeover:blocked Takeover blocked; reason in the PR body vouch:unvouched Author is not yet trusted in the VOUCHED list.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants