Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(desktop): keep an issue tab's scroll position across tab switches (MUL-9959) (#11296)
Bohan Jiang5f7cd898afbf
diff --git a/packages/views/inbox/components/inbox-list.tsx b/packages/views/inbox/components/inbox-list.tsxindex 3c74ee7d44..109013843d 100644--- a/packages/views/inbox/components/inbox-list.tsx+++ b/packages/views/inbox/components/inbox-list.tsx@@ -15,7 +15,7 @@ import type { InboxItem } from "@multica/core/types";import type { InboxView } from "./inbox-view";import { InboxListItem } from "./inbox-list-item";import { VirtuosoSeed, VIRTUOSO_SEED_COUNT } from "../../common/virtuoso-seed";-import { useRestoredScrollOffset, useRestoredScrollRef } from "../../platform";+import { useRestoredScrollRef } from "../../platform";import { useT } from "../../i18n";// Sizing only (like the board's card estimate): the seed's trailing spacer@@ -81,11 +81,10 @@ export function InboxList({const [scrollEl, setScrollEl] = useState<HTMLDivElement | null>(null);// Pull-based scroll restoration (MUL-4741): assign the saved offset at// ref-attach (the seed's estimate spacer gives the container a truthful- // height on the first commit, so the assignment sticks pre-paint) and feed- // the same offset into the Virtuoso as its initial position.- const savedScrollTop = useRestoredScrollOffset("list");+ // height on the first commit, so the assignment sticks pre-paint). The+ // Virtuoso reads its first range from that scroll position; see+ // board-column.tsx for why it gets no `initialScrollTop`.const restoreScrollRef = useRestoredScrollRef("list");- const restoredScrollTop = scrollRestoration ? savedScrollTop : undefined;const attachScrollEl = useCallback((el: HTMLDivElement | null) => {setScrollEl(el);@@ -229,7 +228,6 @@ export function InboxList({data={items}endReached={loadMore}computeItemKey={computeItemKey}- initialScrollTop={restoredScrollTop}initialItemCount={Math.min(items.length, VIRTUOSO_SEED_COUNT)}defaultItemHeight={INBOX_ROW_ESTIMATED_HEIGHT}increaseViewportBy={{ top: 400, bottom: 400 }}diff --git a/packages/views/issues/components/board-column.tsx b/packages/views/issues/components/board-column.tsxindex 4915017e7b..31c778fadf 100644--- a/packages/views/issues/components/board-column.tsx+++ b/packages/views/issues/components/board-column.tsx@@ -29,7 +29,7 @@ import type { ChildProgress } from "./list-row";import { useT } from "../../i18n";import { ActorAvatar } from "../../common/actor-avatar";import { ProjectIcon } from "../../projects/components/project-icon";-import { useRestoredScrollOffset, useRestoredScrollRef } from "../../platform";+import { useRestoredScrollRef } from "../../platform";import { DeferredPopup } from "../../common/deferred-popup";import { DeferredTooltip } from "../../common/deferred-tooltip";import { VirtuosoSeed } from "../../common/virtuoso-seed";@@ -161,10 +161,12 @@ export const BoardColumn = memo(function BoardColumn({const [scrollEl, setScrollEl] = useState<HTMLDivElement | null>(null);// Pull-based scroll restoration (MUL-4741): assign the saved offset at// ref-attach (the seed + estimate spacer give the column a truthful height- // on its first commit, so the assignment sticks pre-paint) and feed the- // same offset into the Virtuoso as its initial position.+ // on its first commit, so the assignment sticks pre-paint). The Virtuoso+ // reads its first range from that scroll position. It must not also get+ // the offset as `initialScrollTop`: with `customScrollParent` Virtuoso+ // counts it from the list's top, so the column's padding was added to the+ // offset on every return.const scrollMementoKey = `board:${group.id}`;- const restoredScrollTop = useRestoredScrollOffset(scrollMementoKey);const restoreScrollRef = useRestoredScrollRef(scrollMementoKey);const mergedRef = useCallback((el: HTMLDivElement | null) => {@@ -360,7 +362,6 @@ export const BoardColumn = memo(function BoardColumn({customScrollParent={scrollEl}data={resolvedIssues}computeItemKey={computeItemKey}- initialScrollTop={restoredScrollTop}initialItemCount={Math.min(resolvedIssues.length, BOARD_SEED_COUNT)}defaultItemHeight={BOARD_CARD_ESTIMATED_HEIGHT}increaseViewportBy={{ top: 300, bottom: 300 }}diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsxindex 6d6d725c6f..b951fca4c0 100644--- a/packages/views/issues/components/comment-card.tsx+++ b/packages/views/issues/components/comment-card.tsx@@ -1537,7 +1537,7 @@ function CommentCardImpl({size="icon-sm"aria-label={toggleLabel}aria-expanded={open}- aria-controls={open ? `comment-body-${entry.id}` : undefined}+ aria-controls={open ? `root-comment-body-${entry.id}` : undefined}onClick={handleToggle}className={commentActionClassName}>@@ -1551,9 +1551,12 @@ function CommentCardImpl({{/* Root comment body. Avoid Base UI's Panel here: every mounted panelprobes computed styles to detect animations, forcing a style- recalculation across long issue-detail documents. */}+ recalculation across long issue-detail documents. Its id must not+ start with "comment-": timeline lookups resolve the nearest+ `[id^="comment-"]` ancestor to a comment id, so a reading anchor+ taken inside the body would name a comment that does not exist. */}{open && !deleted && (- <div id={`comment-body-${entry.id}`} className="px-4 max-md:px-3 pb-3">+ <div id={`root-comment-body-${entry.id}`} className="px-4 max-md:px-3 pb-3">{edit.editing ? (<div{...edit.dropZoneProps}diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex 05597096a4..d7512e2a16 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -510,16 +510,25 @@ const mockVirtualWindow = vi.hoisted(() => ({vi.mock("react-virtuoso", () => ({Virtuoso: forwardRef(function MockVirtuoso(- { data, itemContent, computeItemKey, customScrollParent, totalListHeightChanged }: {+ { data, itemContent, computeItemKey, customScrollParent, initialScrollTop, totalListHeightChanged }: {data: unknown[];itemContent: (i: number, item: unknown) => unknown;computeItemKey: (i: number, item: unknown) => React.Key;customScrollParent?: HTMLElement;+ initialScrollTop?: number;totalListHeightChanged?: (height: number) => void;},ref: any,) {const [windowStart, setWindowStart] = useState(0);+ // Like Virtuoso, scroll to `initialScrollTop` once the rows are in, counted+ // from the list's own top: under `customScrollParent` that adds whatever+ // sits above the list (here a description 500px tall).+ useEffect(() => {+ if (initialScrollTop === undefined || !customScrollParent) return;+ const timer = window.setTimeout(() => { customScrollParent.scrollTop = initialScrollTop + 500; }, 100);+ return () => window.clearTimeout(timer);+ }, [initialScrollTop, customScrollParent]);const correctionTimer = useRef<ReturnType<typeof setInterval> | null>(null);useEffect(() => {if (!mockVirtualWindow.holdAtIndex || !customScrollParent) return;@@ -1785,7 +1794,7 @@ describe("IssueDetail (shared)", () => {mockApiObj.listTimeline.mockResolvedValue([root]);act(() => client.setQueryData(issueKeys.timeline("issue-1"), [root]));await screen.findByText("Waiting for an available agent.");- const userBlock = container.querySelector(`#comment-body-${root.id}`)!.parentElement!;+ const userBlock = container.querySelector(`#root-comment-body-${root.id}`)!.parentElement!;const agentBlock = container.querySelector(`[data-run-comment-id="${taskId}"]`)!;expect(agentBlock).not.toBeNull();expect(userBlock.contains(agentBlock)).toBe(false);@@ -3024,6 +3033,71 @@ describe("IssueDetail (shared)", () => {});});+ // MUL-9959: the reading position is the comment at the viewport's centre,+ // found as its nearest `[id^="comment-"]` ancestor. The root comment's+ // body sat in between with id `comment-body-<id>`, so a reader in the+ // middle of a comment's text saved "body-<id>", which matches no comment,+ // and the tab came back at the top.+ it("saves the reading position against the comment whose body is at the viewport's centre", async () => {+ mockApiObj.listTasksByIssue.mockResolvedValue([]);+ const anchors: string[] = [];+ const adapter: ScrollRestorationAdapter = {+ get: () => undefined,+ getViewState: () => undefined,+ setViewState: (key, value) => {+ if (key === "timeline-anchor:main:issue-1" && value) anchors.push(value);+ },+ };+ const rect = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {+ return this.hasAttribute("data-tab-scroll-root") ? new DOMRect(0, 0, 400, 200) : new DOMRect(0, 0, 0, 0);+ });+ const hadElementFromPoint = "elementFromPoint" in document;+ const originalElementFromPoint = document.elementFromPoint;+ let centre: Element | null = null;+ document.elementFromPoint = () => centre;+ try {+ render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <QueryClientProvider client={createTestQueryClient()}>+ <ScrollRestorationProvider adapter={adapter}>+ <IssueDetail issueId="issue-1" />+ </ScrollRestorationProvider>+ </QueryClientProvider>+ </I18nProvider>,+ );+ centre = await screen.findByText("Started working on this");+ fireEvent.scroll(centre.closest("[data-tab-scroll-root]")!);+ await waitFor(() => expect(anchors.length).toBeGreaterThan(0));+ expect(JSON.parse(anchors.at(-1)!)).toMatchObject({ commentId: "comment-1" });+ } finally {+ rect.mockRestore();+ if (hadElementFromPoint) document.elementFromPoint = originalElementFromPoint;+ else delete (document as { elementFromPoint?: unknown }).elementFromPoint;+ }+ });++ // MUL-9959: the timeline's Virtuoso took the page's saved offset as its+ // `initialScrollTop`, which it counts from the list's top, so a reader in+ // the description came back a description's height further down.+ it("returns to the saved offset of a page scrolled in the description", async () => {+ mockApiObj.listTasksByIssue.mockResolvedValue([]);+ const adapter: ScrollRestorationAdapter = {+ get: (key) => (key === "main:issue-1" ? { top: 300, height: 2000 } : undefined),+ };+ render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <QueryClientProvider client={createTestQueryClient()}>+ <ScrollRestorationProvider adapter={adapter}>+ <IssueDetail issueId="issue-1" />+ </ScrollRestorationProvider>+ </QueryClientProvider>+ </I18nProvider>,+ );+ const comment = await screen.findByText("Started working on this");+ await act(async () => { await new Promise((resolve) => window.setTimeout(resolve, 200)); });+ expect(comment.closest<HTMLElement>("[data-tab-scroll-root]")!.scrollTop).toBe(300);+ });+it("restarts a comment landing that a timeline update cancels while it is still aligning", async () => {mockApiObj.listTasksByIssue.mockResolvedValue([]);// The anchor keeps moving for 300ms, like reply heights settling, so thediff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 5b49e64d42..3df1cd1c43 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -1543,9 +1543,11 @@ export function IssueDetail({ issueId, onDelete, inbox, defaultSidebarOpen = truconst composerRef = useRef<HTMLDivElement | null>(null);// Pull-based scroll restoration (MUL-4741): the platform serves the offset// captured when this route was last left. The ref-attach assignment covers- // the flat render modes (real heights at commit); the virtualized browsing- // mode feeds the offset into Virtuoso's initialScrollTop below so the- // list's first render already materializes the rows around it.+ // content that is already there; useIssueDetailScrollRestore applies it+ // again once the timeline has loaded. The timeline's Virtuoso must not get+ // it as `initialScrollTop`: with `customScrollParent` Virtuoso counts that+ // from the list's top, which sits below the description, so the page came+ // back a description's height further down.//// The container key carries the issue id: on the issue route that is// redundant with the route scoping, but in the inbox the selection lives@@ -4577,7 +4579,6 @@ export function IssueDetail({ issueId, onDelete, inbox, defaultSidebarOpen = truref={virtuosoRef}customScrollParent={scrollContainerEl}data={items}- initialScrollTop={ownsTimelineScroll ? undefined : restoredScrollTop}heightEstimates={timelineHeightEstimates}increaseViewportBy={timelineOverscan}totalListHeightChanged={handleTimelineHeightChange}diff --git a/packages/views/platform/scroll-restoration.tsx b/packages/views/platform/scroll-restoration.tsxindex 2899bb6e76..0baf2857f0 100644--- a/packages/views/platform/scroll-restoration.tsx+++ b/packages/views/platform/scroll-restoration.tsx@@ -19,12 +19,13 @@ import {* mounts again. Restoration is an INPUT to the view, not a post-hoc DOM* mutation from outside:*- * - virtualized lists feed the offset into `initialScrollTop`, so the- * list's first render already materializes the rows around the saved- * offset — no "start at top, then jump" and no fighting the list's own- * height model;- * - plain scroll containers assign the offset in their ref callback at- * attach time (pre-paint).+ * - virtualized lists that own their scroll element feed the offset into+ * their initial offset, so the list's first render already materializes+ * the rows around the saved offset — no "start at top, then jump" and no+ * fighting the list's own height model;+ * - plain scroll containers, including the custom scroll parent of a+ * Virtuoso, assign the offset in their ref callback at attach time+ * (pre-paint).** Container keys mirror the `data-tab-scroll-root` attribute values the* capture side scans for; the platform scopes them per route + tab. On web@@ -141,9 +142,12 @@ export function useRestoredScrollEntry(/*** The saved vertical scroll offset for a container key on the current route,* or undefined when there is none (an entry saved only for its horizontal- * offset counts as none). Read it once at mount (e.g. into a Virtuoso- * `initialScrollTop`) — it reflects the state captured when this route was- * last left.+ * offset counts as none). Read it once at mount (e.g. into a virtualizer+ * that owns its scroll element, as its initial offset) — it reflects the+ * state captured when this route was last left. Do not pass it to a+ * Virtuoso with `customScrollParent` as `initialScrollTop`: Virtuoso counts+ * that from the list's own top, not the container's, so any content above+ * the list is added to the restored offset.*/export function useRestoredScrollOffset(containerKey: string): number | undefined {const top = useRestoredScrollEntry(containerKey)?.top;