Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(comments): finish first-click discussion navigation
gbirman61726ec24dec
diff --git a/CLAUDE.md b/CLAUDE.mdindex 3750073193..c412ca8c46 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -73,6 +73,8 @@ Real files live in `.agents/`; tool-specific directories only symlink to it.- Do only what was asked. Questions get answers, not code changes.- Commit as you go, in small logical commits on a feature branch, withoutasking. Never commit to `main`. Push or open a PR only when asked.+ Once authorized, finish in-scope review fixes and follow-up pushes without+ per-fix confirmation.- Flag real risks; once the user decides, act on it.- Disagree when they're wrong. No flattery.- Answer simple questions directly.diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex e113d6e546..2510ac0e3c 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -22,6 +22,9 @@ Split dragging and composer reflow have a backend-free browser regression:`bunx playwright test --config src/lib/core/component/Resize/browser-test/playwright.config.ts`.It exercises the real resize solver, scroll container, and Lexical layout primitive.+Discussion link scrolling has a backend-free browser regression:+`bunx playwright test --config src/lib/core/messages/browser-test/playwright.config.ts`.+A frontend dev server runs against the **dev** backend, so this needs no local stack, Docker, Rust build, or `sudo`:```sh@@ -128,6 +131,7 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.- Inline agent steps reuse the session code-execution query for live SDK operationnames; completed step snapshots come from the shared fold of the tool receipt.- All API/network calls live in service-clients.+- Bound Discussion comment readiness waits to ten seconds; recover from initial layout interruptions until the message is visible, and release the target on user input (including scrollbar pointer-down), timeout, or successful arrival.- Keep early DOCX opens loading while exports return processing (409); retry onlythat response, with a bounded wait. See the Word editor walkthrough in`docs/agent-guide/documents.md` at the repository root.diff --git a/apps/web/src/features/block-md/component/DocumentDiscussion.test.tsx b/apps/web/src/features/block-md/component/DocumentDiscussion.test.tsxindex dfb8993ad3..7febde726e 100644--- a/apps/web/src/features/block-md/component/DocumentDiscussion.test.tsx+++ b/apps/web/src/features/block-md/component/DocumentDiscussion.test.tsx@@ -26,11 +26,15 @@ const mocks = vi.hoisted(() => ({const [authenticated, setAuthenticated] = createSignal<boolean | undefined>(true);+const [locationReady, setLocationReady] = createSignal(true);vi.mock('@core/context/user', () => ({useIsAuthenticated: () => authenticated,}));-beforeEach(() => setAuthenticated(true));+beforeEach(() => {+ setAuthenticated(true);+ setLocationReady(true);+});vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => true }));vi.mock('@components/app/split-layout/layoutUtils', () => ({@@ -40,6 +44,15 @@ vi.mock('../context/markdown-document-context', () => ({useMarkdownDocument: () => ({documentId: () => 'document',kind: () => 'task',+ state: {+ editor: {+ md: {+ get locationReady() {+ return locationReady();+ },+ },+ },+ },permissions: {canComment: () => true,isOwner: () => false,@@ -203,6 +216,7 @@ describe('scrolling to a linked Discussion message', () => {afterEach(() => {scrollIntoView.mockReset();+ vi.useRealTimers();});const navigate = (id: string) =>@@ -222,6 +236,69 @@ describe('scrolling to a linked Discussion message', () => {expect(scrolledIds()).toEqual(['m2']);});+ it('loads the linked discussion but waits for the document before scrolling', async () => {+ setLocationReady(false);+ setCommentId('m2');+ setup();+ expect(mocks.conversation).toHaveBeenCalledWith(+ expect.objectContaining({ targetId: 'm2' })+ );++ setRenderedMessageIds(['m1', 'm2']);+ await flushMutations();+ expect(scrolledIds()).toEqual([]);++ setLocationReady(true);+ expect(scrolledIds()).toEqual(['m2']);++ setRenderedMessageIds(['m1', 'm2', 'm3']);+ await flushMutations();+ expect(scrolledIds()).toEqual(['m2']);+ });++ it('resumes a pending navigation after the editor temporarily becomes unready', async () => {+ setCommentId('m2');+ setup();+ setLocationReady(false);+ setLocationReady(true);++ setRenderedMessageIds(['m2']);+ await flushMutations();+ expect(scrolledIds()).toEqual(['m2']);+ });++ it('expires a navigation when the editor never becomes ready', () => {+ vi.useFakeTimers();+ setLocationReady(false);+ setCommentId('m2');+ setRenderedMessageIds(['m2']);+ setup();++ vi.advanceTimersByTime(10_000);+ setLocationReady(true);+ expect(scrolledIds()).toEqual([]);++ navigate('m2');+ expect(scrolledIds()).toEqual(['m2']);+ });++ it.each(['wheel', 'touchmove', 'keydown', 'pointerdown'])(+ 'lets %s cancel a navigation while the editor is still loading',+ async (type) => {+ setLocationReady(false);+ setCommentId('m2');+ setup();+ window.dispatchEvent(new Event(type));+ setRenderedMessageIds(['m2']);+ setLocationReady(true);+ await flushMutations();+ expect(scrolledIds()).toEqual([]);++ navigate('m2');+ expect(scrolledIds()).toEqual(['m2']);+ }+ );+it('leaves margin comment links to the margin without targeting Discussion', async () => {mocks.anchor = { type: 'markdown', mark_id: 'mark' };setCommentId('margin-reply');diff --git a/apps/web/src/features/block-md/component/DocumentDiscussion.tsx b/apps/web/src/features/block-md/component/DocumentDiscussion.tsxindex b9ac149726..4c5aef8f04 100644--- a/apps/web/src/features/block-md/component/DocumentDiscussion.tsx+++ b/apps/web/src/features/block-md/component/DocumentDiscussion.tsx@@ -34,7 +34,7 @@ export function DocumentDiscussion(props: DocumentDiscussionProps) {}function AuthenticatedDocumentDiscussion(props: DocumentDiscussionProps) {- const { documentId, kind, permissions } = useMarkdownDocument();+ const { documentId, kind, permissions, state } = useMarkdownDocument();const id = documentId();const documentKind = kind();const blockName = documentKind === 'document' ? 'md' : documentKind;@@ -52,6 +52,7 @@ function AuthenticatedDocumentDiscussion(props: DocumentDiscussionProps) {<EntityDiscussionparent={parent()}targetId={discussionTarget()}+ scrollReady={state.editor.md.locationReady === true}canWrite={permissions.canComment()}canModerate={permissions.isOwner()}link={{ type: blockName, id }}diff --git a/apps/web/src/lib/core/messages/EntityConversation.test.tsx b/apps/web/src/lib/core/messages/EntityConversation.test.tsxindex 66845d0f5d..ef9e9b69ea 100644--- a/apps/web/src/lib/core/messages/EntityConversation.test.tsx+++ b/apps/web/src/lib/core/messages/EntityConversation.test.tsx@@ -24,7 +24,8 @@ vi.mock('@core/component/ParamsProvider', () => ({useParamNavigationCount: () => () => 0,}));vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));-vi.mock('./scroll-to-rendered-target', () => ({+vi.mock('./scroll-to-rendered-target', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./scroll-to-rendered-target')>()),scrollToRenderedTarget: mocks.scroll,}));@@ -192,7 +193,8 @@ describe('EntityDiscussion target ownership', () => {expect(view.getByRole('article').dataset.target).toBe('workbook-reply');expect(mocks.scroll).toHaveBeenCalledWith(expect.any(HTMLElement),- 'workbook-reply'+ 'workbook-reply',+ { onSettled: expect.any(Function) });});diff --git a/apps/web/src/lib/core/messages/EntityDiscussion.tsx b/apps/web/src/lib/core/messages/EntityDiscussion.tsxindex ed12667823..b832df7319 100644--- a/apps/web/src/lib/core/messages/EntityDiscussion.tsx+++ b/apps/web/src/lib/core/messages/EntityDiscussion.tsx@@ -22,7 +22,10 @@ import {EntityConversation,EntityConversationComposer,} from './EntityConversation';-import { scrollToRenderedTarget } from './scroll-to-rendered-target';+import {+ scrollToRenderedTarget,+ USER_SCROLL_EVENTS,+} from './scroll-to-rendered-target';function MobileMessageComposer(props: {parent: MessageParent;@@ -56,6 +59,8 @@ export function EntityDiscussion(props: {label?: string;/** Override the URL target; null leaves this discussion untargeted. */targetId?: string | null;+ /** Defer scrolling while the host is still laying out content above the discussion. */+ scrollReady?: boolean;/*** On touch devices, move the composer to the floating accessory region and* show the conversation only once it has roots, as the editor page does.@@ -96,11 +101,38 @@ export function EntityDiscussion(props: {};let scrolledKey: string | undefined;createEffect(- on(scrollRequest, (request) => {- if (!request || !container || request.key === scrolledKey) return;- scrolledKey = request.key;- onCleanup(scrollToRenderedTarget(container, request.commentId));- })+ on(+ [scrollRequest, () => props.scrollReady !== false],+ ([request, ready]) => {+ if (!request || !container || request.key === scrolledKey) return;+ const onSettled = () => {+ scrolledKey = request.key;+ };+ if (!ready) {+ // A reader can take over even before the editor is ready to scroll.+ const stopWaiting = () => {+ clearTimeout(timer);+ for (const type of USER_SCROLL_EVENTS)+ window.removeEventListener(type, settleWaiting, true);+ };+ const settleWaiting = () => {+ onSettled();+ stopWaiting();+ };+ const timer = setTimeout(settleWaiting, 10_000);+ for (const type of USER_SCROLL_EVENTS)+ window.addEventListener(type, settleWaiting, {+ capture: true,+ passive: true,+ });+ onCleanup(stopWaiting);+ return;+ }+ onCleanup(+ scrollToRenderedTarget(container, request.commentId, { onSettled })+ );+ }+ ));return (<>diff --git a/apps/web/src/lib/core/messages/browser-test/comment-navigation.browser.e2e.ts b/apps/web/src/lib/core/messages/browser-test/comment-navigation.browser.e2e.tsnew file mode 100644index 0000000000..c4c107ae33--- /dev/null+++ b/apps/web/src/lib/core/messages/browser-test/comment-navigation.browser.e2e.ts@@ -0,0 +1,43 @@+import { expect, test } from '@playwright/test';++test('reaches a comment when loading layout interrupts the first smooth scroll', async ({+ page,+}) => {+ await page.goto('/');+ await page.evaluate(() => {+ const viewport = document.querySelector<HTMLElement>('#viewport')!;+ const content = document.querySelector<HTMLElement>('#content')!;+ // Preserve the current text position across a loading reflow, as an+ // editor's layout anchoring does. Writing scrollTop interrupts Chromium's+ // native smooth animation even though the linked comment is still below.+ const interrupt = () => {+ if (viewport.scrollTop < 150) return;+ viewport.removeEventListener('scroll', interrupt);+ const top = viewport.scrollTop;+ content.style.paddingTop = '200px';+ viewport.scrollTop = top + 200;+ content.dataset.reflowed = 'true';+ };+ viewport.addEventListener('scroll', interrupt);+ });++ await page.getByRole('button', { name: 'Open comment' }).click();+ await expect(page.locator('#content')).toHaveAttribute(+ 'data-reflowed',+ 'true'+ );+ const target = page.locator('[data-message-id="target"]');+ await expect(target).toBeInViewport({ ratio: 1 });++ // Once reached, unrelated layout refreshes must not reclaim the scroll.+ await page.locator('#viewport').evaluate((viewport) => {+ viewport.scrollTo({ top: 0, behavior: 'instant' });+ const spacer = document.createElement('div');+ spacer.style.height = '100px';+ document.querySelector('#discussion')!.append(spacer);+ });+ await expect(target).not.toBeInViewport();++ await page.getByRole('button', { name: 'Open comment' }).click();+ await expect(target).toBeInViewport({ ratio: 1 });+});diff --git a/apps/web/src/lib/core/messages/browser-test/fixture.ts b/apps/web/src/lib/core/messages/browser-test/fixture.tsnew file mode 100644index 0000000000..df8b1d2171--- /dev/null+++ b/apps/web/src/lib/core/messages/browser-test/fixture.ts@@ -0,0 +1,8 @@+import { scrollToRenderedTarget } from '../scroll-to-rendered-target';++const discussion = document.querySelector<HTMLElement>('#discussion')!;+let cancel: (() => void) | undefined;+document.querySelector('#navigate')!.addEventListener('click', () => {+ cancel?.();+ cancel = scrollToRenderedTarget(discussion, 'target');+});diff --git a/apps/web/src/lib/core/messages/browser-test/index.html b/apps/web/src/lib/core/messages/browser-test/index.htmlnew file mode 100644index 0000000000..465cdf7fcc--- /dev/null+++ b/apps/web/src/lib/core/messages/browser-test/index.html@@ -0,0 +1,17 @@+<!doctype html>+<html lang="en">+ <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Comment navigation regression</title></head>+ <body>+ <button id="navigate">Open comment</button>+ <div id="viewport" style="height: 400px; width: 100%; max-width: 600px; overflow-y: auto">+ <div id="content">+ <div style="height: 2400px">Document body</div>+ <div id="discussion">+ <div data-message-id="target" style="height: 120px">Linked comment</div>+ </div>+ <div style="height: 400px"></div>+ </div>+ </div>+ <script type="module" src="./fixture.ts"></script>+ </body>+</html>diff --git a/apps/web/src/lib/core/messages/browser-test/playwright.config.ts b/apps/web/src/lib/core/messages/browser-test/playwright.config.tsnew file mode 100644index 0000000000..36019479c0--- /dev/null+++ b/apps/web/src/lib/core/messages/browser-test/playwright.config.ts@@ -0,0 +1,32 @@+import { fileURLToPath } from 'node:url';+import { defineConfig } from '@playwright/test';++const directory = fileURLToPath(new URL('.', import.meta.url));+const webDirectory = fileURLToPath(new URL('../../../../../', import.meta.url));+const port = Number(process.env.COMMENT_BROWSER_PORT ?? 3068);++export default defineConfig({+ testDir: directory,+ testMatch: '*.browser.e2e.ts',+ outputDir: `${directory}/test-results`,+ workers: 1,+ reporter: 'line',+ use: { baseURL: `http://127.0.0.1:${port}` },+ webServer: {+ command: `bunx vite --config src/lib/core/messages/browser-test/vite.config.ts --port ${port}`,+ cwd: webDirectory,+ url: `http://127.0.0.1:${port}`,+ },+ projects: [+ { name: 'chromium', use: { browserName: 'chromium' } },+ {+ name: 'mobile-chromium',+ use: {+ browserName: 'chromium',+ viewport: { width: 390, height: 844 },+ isMobile: true,+ hasTouch: true,+ },+ },+ ],+});diff --git a/apps/web/src/lib/core/messages/browser-test/vite.config.ts b/apps/web/src/lib/core/messages/browser-test/vite.config.tsnew file mode 100644index 0000000000..ce4d64b0e5--- /dev/null+++ b/apps/web/src/lib/core/messages/browser-test/vite.config.ts@@ -0,0 +1,7 @@+import { fileURLToPath } from 'node:url';+import { defineConfig } from 'vite';++export default defineConfig({+ root: fileURLToPath(new URL('.', import.meta.url)),+ server: { host: '127.0.0.1', strictPort: true },+});diff --git a/apps/web/src/lib/core/messages/scroll-to-rendered-target.test.ts b/apps/web/src/lib/core/messages/scroll-to-rendered-target.test.tsindex de376a57b7..a35fa83126 100644--- a/apps/web/src/lib/core/messages/scroll-to-rendered-target.test.ts+++ b/apps/web/src/lib/core/messages/scroll-to-rendered-target.test.ts@@ -10,6 +10,7 @@ beforeEach(() => {afterEach(() => {vi.useRealTimers();+ vi.unstubAllGlobals();scrollIntoView.mockReset();document.body.innerHTML = '';});@@ -25,13 +26,17 @@ function renderTarget(root: HTMLElement, id: string) {describe('scrollToRenderedTarget', () => {it('scrolls a target that is already rendered', () => {+ const onSettled = vi.fn();const root = document.body.appendChild(document.createElement('div'));const target = renderTarget(root, 'm1');- scrollToRenderedTarget(root, 'm1');+ const cancel = scrollToRenderedTarget(root, 'm1', { onSettled });expect(scrollIntoView).toHaveBeenCalledOnce();expect(scrollIntoView.mock.contexts[0]).toBe(target);+ expect(onSettled).toHaveBeenCalledOnce();+ cancel();+ expect(onSettled).toHaveBeenCalledOnce();});it('waits for the target to render, then scrolls once', async () => {@@ -51,20 +56,24 @@ describe('scrollToRenderedTarget', () => {});it('never scrolls after the user starts scrolling', async () => {+ const onSettled = vi.fn();const root = document.body.appendChild(document.createElement('div'));- scrollToRenderedTarget(root, 'm1');+ scrollToRenderedTarget(root, 'm1', { onSettled });window.dispatchEvent(new WheelEvent('wheel'));renderTarget(root, 'm1');await flushMutations();expect(scrollIntoView).not.toHaveBeenCalled();+ expect(onSettled).toHaveBeenCalledOnce();});it('gives up after the timeout', async () => {+ const onSettled = vi.fn();const root = document.body.appendChild(document.createElement('div'));scrollToRenderedTarget(root, 'm1', {timeoutMs: 100,+ onSettled,});vi.advanceTimersByTime(100);@@ -72,6 +81,7 @@ describe('scrollToRenderedTarget', () => {await flushMutations();expect(scrollIntoView).not.toHaveBeenCalled();+ expect(onSettled).toHaveBeenCalledOnce();});it('matches an id with selector metacharacters literally', () => {@@ -86,13 +96,83 @@ describe('scrollToRenderedTarget', () => {});it('stops waiting when cancelled', async () => {+ const onSettled = vi.fn();const root = document.body.appendChild(document.createElement('div'));- const cancel = scrollToRenderedTarget(root, 'm1');+ const cancel = scrollToRenderedTarget(root, 'm1', { onSettled });cancel();renderTarget(root, 'm1');await flushMutations();expect(scrollIntoView).not.toHaveBeenCalled();+ expect(onSettled).not.toHaveBeenCalled();});++ it('finishes an interrupted scroll after the document reflows, then leaves refreshes alone', () => {+ let resized: () => void = () => {};+ const disconnect = vi.fn();+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ constructor(callback: () => void) {+ resized = callback;+ }+ observe() {}+ disconnect = disconnect;+ }+ );+ const viewport = document.body.appendChild(document.createElement('div'));+ viewport.style.overflowY = 'auto';+ viewport.getBoundingClientRect = () => new DOMRect(0, 0, 600, 400);+ const root = viewport.appendChild(document.createElement('div'));+ const target = renderTarget(root, 'm1');+ let top = 2000;+ target.getBoundingClientRect = () => new DOMRect(0, top, 600, 100);++ scrollToRenderedTarget(root, 'm1');+ expect(scrollIntoView).toHaveBeenCalledOnce();++ // Layout interrupts the native animation before the comment is visible.+ top = 1200;+ viewport.dispatchEvent(new Event('scrollend'));+ expect(scrollIntoView).toHaveBeenCalledTimes(2);+ // A resize notification with unchanged geometry must not restart motion.+ resized();+ expect(scrollIntoView).toHaveBeenCalledTimes(2);+ top = 1400;+ resized();+ expect(scrollIntoView).toHaveBeenCalledTimes(3);++ top = 150;+ viewport.dispatchEvent(new Event('scrollend'));+ expect(disconnect).toHaveBeenCalledOnce();++ top = 1600;+ resized();+ viewport.dispatchEvent(new Event('scrollend'));+ expect(scrollIntoView).toHaveBeenCalledTimes(3);+ });++ it.each(['wheel', 'touchmove', 'keydown', 'pointerdown'])(+ 'does not retry an interrupted animation after %s',+ (type) => {+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ disconnect() {}+ }+ );+ const viewport = document.body.appendChild(document.createElement('div'));+ viewport.style.overflowY = 'auto';+ viewport.getBoundingClientRect = () => new DOMRect(0, 0, 600, 400);+ const target = renderTarget(viewport, 'm1');+ target.getBoundingClientRect = () => new DOMRect(0, 2000, 600, 100);++ scrollToRenderedTarget(viewport, 'm1');+ window.dispatchEvent(new Event(type));+ viewport.dispatchEvent(new Event('scrollend'));+ expect(scrollIntoView).toHaveBeenCalledOnce();+ }+ );});diff --git a/apps/web/src/lib/core/messages/scroll-to-rendered-target.ts b/apps/web/src/lib/core/messages/scroll-to-rendered-target.tsindex 6624fc9065..17ebf4833a 100644--- a/apps/web/src/lib/core/messages/scroll-to-rendered-target.ts+++ b/apps/web/src/lib/core/messages/scroll-to-rendered-target.ts@@ -1,6 +1,13 @@+import { getScrollParentElement } from '../util/scrollParent';+const DEFAULT_TIMEOUT_MS = 10_000;-const USER_SCROLL_EVENTS = ['wheel', 'touchmove', 'keydown'] as const;+export const USER_SCROLL_EVENTS = [+ 'wheel',+ 'touchmove',+ 'keydown',+ 'pointerdown',+] as const;/*** Scrolls the message element under `root` whose `data-message-id` is@@ -12,41 +19,126 @@ const USER_SCROLL_EVENTS = ['wheel', 'touchmove', 'keydown'] as const;export function scrollToRenderedTarget(root: HTMLElement,messageId: string,- options?: { timeoutMs?: number }+ options?: { timeoutMs?: number; onSettled?: () => void }): () => void {let done = false;let observer: MutationObserver | undefined;+ let resizeObserver: ResizeObserver | undefined;+ let scroller: HTMLElement | null = null;+ let target: HTMLElement | undefined;+ let lastPlacement:+ | {+ element: HTMLElement;+ top: number;+ height: number;+ viewportHeight: number;+ }+ | undefined;let timer: ReturnType<typeof setTimeout> | undefined;const cancel = () => {if (done) return;done = true;observer?.disconnect();+ resizeObserver?.disconnect();+ scroller?.removeEventListener('scroll', onScroll);+ scroller?.removeEventListener('scrollend', onScrollEnd);if (timer !== undefined) clearTimeout(timer);for (const type of USER_SCROLL_EVENTS)- window.removeEventListener(type, cancel, true);+ window.removeEventListener(type, settle, true);};- const tryScroll = () => {+ // Effect cleanup can pause a request while the editor loads again. Only+ // arrival, user takeover, or timeout consumes the navigation.+ function settle() {+ if (done) return;+ cancel();+ options?.onSettled?.();+ }++ const isPositioned = () => {+ if (!target?.isConnected || !scroller?.isConnected) return false;+ const message = target.getBoundingClientRect();+ const viewport = scroller.getBoundingClientRect();+ if (message.height <= 0 || viewport.height <= 0) return false;+ return message.height <= viewport.height+ ? message.top >= viewport.top - 1 && message.bottom <= viewport.bottom + 1+ : message.top <= viewport.top + 1 &&+ message.bottom >= viewport.bottom - 1;+ };++ function onScrollEnd() {+ if (isPositioned()) settle();+ else tryScroll(true);+ }++ function onScroll() {+ if (isPositioned()) settle();+ }++ const tryScroll = (interrupted = false) => {+ if (done) return false;// Compared, not interpolated into a selector: the id comes from the URL.- const target = Array.from(+ target = Array.from(root.querySelectorAll<HTMLElement>('[data-message-id]')).find((element) => element.dataset.messageId === messageId);- if (!target) return false;- cancel();+ if (!target?.isConnected) return false;+ if (!scroller) {+ scroller = getScrollParentElement(root);+ if (scroller) {+ scroller.addEventListener('scroll', onScroll, { passive: true });+ scroller.addEventListener('scrollend', onScrollEnd);+ resizeObserver = new ResizeObserver(() => tryScroll());+ // The discussion's wrapper is display:contents. Observe its laid-out+ // ancestors too: loading or suspending the editor changes the target's+ // position without necessarily resizing the message itself.+ for (+ let element: HTMLElement | null = target;+ element;+ element = element.parentElement+ ) {+ resizeObserver.observe(element);+ if (element === scroller) break;+ }+ }+ }+ if (scroller) {+ const rect = target.getBoundingClientRect();+ const viewport = scroller.getBoundingClientRect();+ const top = rect.top - viewport.top + scroller.scrollTop;+ if (+ !interrupted &&+ lastPlacement?.element === target &&+ lastPlacement.top === top &&+ lastPlacement.height === rect.height &&+ lastPlacement.viewportHeight === viewport.height+ )+ return true;+ lastPlacement = {+ element: target,+ top,+ height: rect.height,+ viewportHeight: viewport.height,+ };+ }target.scrollIntoView({ behavior: 'smooth', block: 'center' });+ // A smooth scroll can be interrupted by layout during the first open.+ // Keep the navigation pending until it lands, rather than consuming it as+ // soon as the message exists. Later refreshes must not restart it.+ if (!scroller || isPositioned()) settle();return true;};- if (tryScroll()) return cancel;+ tryScroll();+ if (done) return cancel;observer = new MutationObserver(() => {tryScroll();});observer.observe(root, { childList: true, subtree: true });- timer = setTimeout(cancel, options?.timeoutMs ?? DEFAULT_TIMEOUT_MS);+ timer = setTimeout(settle, options?.timeoutMs ?? DEFAULT_TIMEOUT_MS);for (const type of USER_SCROLL_EVENTS)- window.addEventListener(type, cancel, { capture: true, passive: true });+ window.addEventListener(type, settle, { capture: true, passive: true });return cancel;}diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.mdindex 351d56b5b6..69c2ffa191 100644--- a/docs/agent-guide/documents.md+++ b/docs/agent-guide/documents.md@@ -2597,6 +2597,16 @@ editor and comments arriving after it. Once loaded, click elsewhere in thedocument, then click the same notification again: it should revisit the comment,while background comment refreshes should leave the user's position alone.+Verify bottom Discussion links from Home too:+`/app/home/md/<id>?s0.drive.commentId=<comment-id>`. Open a long document from+another Home item with its caches cold. The first click should reach the comment+even when its messages arrive before the editor or loading content interrupts+the initial scroll. Repeat the click after scrolling away. Wheel, touch,+keyboard input, or dragging the scrollbar during navigation should take control+immediately; later background refreshes must not pull the reader back. If the+editor never becomes ready, its pending comment jump expires after ten seconds;+subsequent recovery must not revive it without a new navigation.+A document row keeps pointing at its newest comment notification until thatnotification is done, so on desktop the row opens the document at that comment.On touch the thread is a drawer over the whole page rather than a margin card,