Skip to content

app: ScrollPositionKeeper.handleScroll() runs apply(), capture(), and notifyLists() twice per detached scroll event #8496

Backlog

Description

@Tiberriver256

Summary

In apps/app/src/components/ui/scroll-position-keeper.ts, the detached (position.kind !== "bottom") branch of handleScroll() performs duplicate layout reads, writes, anchor captures, and list notifications on every single scroll event (60–120 Hz while scrolled up in a thread):

    } else {
      if (position.kind === "anchor") this.apply(scrollElement, false);
      const current = this.position;
      if (current.kind !== "anchor" || !this.isInView(scrollElement, current)) {
        this.setPosition(this.capture(scrollElement) ?? FREE);
      }
      this.notifyLists();
      if (this.position.kind === "anchor") this.apply(scrollElement, false);
      this.setPosition(this.capture(scrollElement) ?? FREE);
    }
    if (this.deferred !== 0) this.scheduleDeferredWrite();
    this.attachIfAtEnd(scrollElement);
    this.notifyLists();

On every detached scroll event:

  1. Line 532: this.apply(scrollElement, false) reads scroll geometry and may write scrollTop / style.transform.
  2. Line 534–535: this.isInView(...) forces a layout read (getBoundingClientRect()), and this.capture(scrollElement) runs querySelectorAll + binary-search getBoundingClientRect() + up to 8 neighbor getBoundingClientRect() reads.
  3. Line 537: this.notifyLists() invokes TimelineWindowedItems.syncWindow(true).
  4. Line 538: 2nd this.apply(scrollElement, false) repeats the geometry read/write pass.
  5. Line 539: Unconditional 2nd this.capture(scrollElement) repeats querySelectorAll + binary-search getBoundingClientRect() and unconditionally overwrites the anchor captured on line 535.
  6. Line 542–543: this.attachIfAtEnd(scrollElement) followed by a 2nd this.notifyLists().

Environment

  • Commit: bdd066bc5076b5bdcc6d37ecec52c17ad59e9493
  • Chromium headless (1440×900, Linux x64)

Measured Impact (Headless Chromium)

Benchmarking 120 detached scroll events over a 300-row timeline (~15 DOM nodes/row) in headless Chromium comparing the current double apply/capture/notifyLists sequence against a single pass:

{
  "before": { "totalMs": 51.6, "meanMs": 0.43,  "p50Ms": 0.4, "p95Ms": 0.8, "maxMs": 1.5 },
  "after":  { "totalMs": 21.9, "meanMs": 0.182, "p50Ms": 0.2, "p95Ms": 0.3, "maxMs": 0.9 },
  "speedup": 2.36
}

On heavier real threads with code blocks, diffs, and nested tool cards, forced reflow cost scales linearly with DOM size.

Expected Behavior

Avoid redundant apply(), capture(), and notifyLists() passes inside handleScroll()'s detached branch so each scroll event does at most one capture/reconcile pass unless the first notifyLists() actually mutated the DOM/window, while preserving all invariants covered by scroll-position-keeper.test.ts and scroll-position-keeper.model.test.ts.

AGENT GENERATED

Activity

  1. Tiberriver256 commented on Dec 2, 2026

    @Tiberriver256
    Author

    Adding a minimal runnable Vitest repro against ScrollPositionKeeper on f5af70c9c5 (same harness as apps/app/src/components/ui/scroll-position-keeper.test.ts):

    // @vitest-environment jsdom
    import { describe, it, vi } from "vitest";
    import { installFakeFlowLayout, setFakeHeight } from "@/test/fake-flow-layout";
    import { ScrollPositionKeeper } from "./scroll-position-keeper";
    
    describe("repro #8496", () => {
      it("counts duplicate passes per detached scroll event", () => {
        const scrollElement = document.createElement("div");
        const content = document.createElement("div");
        const list = document.createElement("div");
        list.setAttribute("data-timeline-row-list", "top-level");
        const items = document.createElement("div");
        items.setAttribute("data-timeline-items", "");
        list.append(items);
        content.append(list);
        scrollElement.append(content);
        document.body.append(scrollElement);
        const layout = installFakeFlowLayout({ scrollElement, viewportHeight: 500 });
    
        for (let i = 0; i < 30; i++) {
          const el = document.createElement("div");
          el.setAttribute("data-timeline-row-id", `row-${i}`);
          setFakeHeight(el, 200);
          items.append(el);
        }
    
        const getTopLevelRows = vi.fn(() =>
          items.querySelectorAll<HTMLElement>(":scope > [data-timeline-row-id]"),
        );
        const onPositionChange = vi.fn();
    
        const keeper = new ScrollPositionKeeper({
          bottomThresholdPx: 4,
          deferWritesWhileScrolling: false,
          getContentElement: () => content,
          getFloorElement: () => null,
          getFooterElement: () => null,
          getScrollElement: () => scrollElement,
          getTopLevelRows,
          initiallyAttached: false,
        });
        const disconnect = keeper.connect(scrollElement);
        keeper.registerList({ itemAt: () => null, onPositionChange });
    
        layout.userScrollTo(2000);
        getTopLevelRows.mockClear();
        onPositionChange.mockClear();
    
        for (let i = 1; i <= 10; i++) {
          layout.userScrollTo(2000 - i * 100);
        }
        console.log("REPRO_8496:", JSON.stringify({
          scrollEvents: 10,
          getTopLevelRowsCalls: getTopLevelRows.mock.calls.length,
          onPositionChangeCalls: onPositionChange.mock.calls.length,
        }));
    
        disconnect();
        layout.restore();
      });
    });

    Observed output (npx vitest run --silent=false):

    REPRO_8496: {"scrollEvents":10,"getTopLevelRowsCalls":10,"onPositionChangeCalls":20}
    

    Every detached scroll event fires onPositionChange (notifyLists) 2× (and calls capture() / getTopLevelRows 2× whenever the previous anchor scrolls out of view).

    AGENT GENERATED

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions