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(md): navigate to comment notifications on the first click (#7199)
gbirmandaed468ad4c0
diff --git a/apps/web/src/features/block-md/comments/MessageCommentsProvider.test.tsx b/apps/web/src/features/block-md/comments/MessageCommentsProvider.test.tsxnew file mode 100644index 0000000000..e33f6e25c2--- /dev/null+++ b/apps/web/src/features/block-md/comments/MessageCommentsProvider.test.tsx@@ -0,0 +1,246 @@+import {+ LexicalWrapperContext,+ type LexicalWrapperWithMapping,+} from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';+import type { PluginManager } from '@core/component/LexicalMarkdown/plugins';+import type { LoroManager } from '@macro-inc/collaboration/collab/manager';+import { $createCommentNode, CommentNode } from '@macro-inc/lexical-core';+import type { MessageListItem } from '@service-storage/messages';+import { cleanup, render } from '@solidjs/testing-library';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ createEditor,+ type LexicalEditor,+} from 'lexical';+import { batch, createSignal, onCleanup, onMount } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createMarkdownDocumentState } from '../context/markdown-document-state';+import { MessageCommentsProvider } from './MessageCommentsProvider';++const mocks = vi.hoisted(() => ({+ state: undefined as+ | ReturnType<typeof createMarkdownDocumentState>+ | undefined,+ threads: (): MessageListItem[] => [],+ rootId: (): string | null => 'root',+ navigationCount: (): number => 0,+}));++vi.mock('../context/markdown-document-context', () => ({+ useMarkdownDocument: () => ({+ documentId: () => 'document',+ state: mocks.state,+ permissions: { canEdit: () => false, canComment: () => true },+ }),+}));+vi.mock('@core/context/user', () => ({+ useUserId: () => () => 'macro|[email protected]',+}));+vi.mock('@core/component/LexicalMarkdown/plugins', () => ({+ autoRegister: (...disposers: (() => void)[]) => disposers.forEach(onCleanup),+}));+vi.mock('@core/component/ParamsProvider', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useParamNavigationCount: () => () => mocks.navigationCount(),+}));+vi.mock('@queries/messages/document-messages', () => ({+ useMessageRootsQuery: () => ({+ isSuccess: true,+ get data() {+ return mocks.threads();+ },+ }),+ useMessageLink: (_parent: unknown, target: () => string | undefined) => ({+ messageId: target,+ rootId: () => mocks.rootId(),+ }),+}));+vi.mock('@queries/messages/mutations', () => ({+ usePatchThreadMutation: () => ({ mutate: vi.fn() }),+}));+vi.mock('@queries/messages/sync', () => ({+ onThreadStateUpdated: () => () => {},+}));+vi.mock('./commentOperations', () => ({+ useDeleteNewComments: () => () => {},+}));++const thread: MessageListItem = {+ id: 'root',+ parent: { type: 'document', id: 'document' },+ sender_id: 'macro|[email protected]',+ content: 'Root comment',+ mentions: [],+ attachments: [],+ reactions: [],+ created_at: '2026-09-29T00:00:00Z',+ updated_at: '2026-09-29T00:00:00Z',+ state: {+ root_id: 'root',+ user_id: 'macro|[email protected]',+ resolved: false,+ created_at: '2026-09-29T00:00:00Z',+ updated_at: '2026-09-29T00:00:00Z',+ anchor: { type: 'markdown', mark_id: 'mark' },+ },+ thread: { reply_count: 1, preview: [], latest_reply_at: null },+};++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++function setup() {+ const state = createMarkdownDocumentState();+ mocks.state = state;+ const [threads, setThreads] = createSignal<MessageListItem[]>([]);+ const [rootId, setRootId] = createSignal<string | null>(null);+ const [navigationCount, setNavigationCount] = createSignal(0);+ const [activeComment, setActiveComment] = createSignal<string | undefined>(+ 'reply',+ { equals: false }+ );+ mocks.threads = threads;+ mocks.rootId = rootId;+ mocks.navigationCount = navigationCount;+ const scroll = vi.fn();+ Element.prototype.scrollIntoView = scroll;+ const editor = createEditor({+ namespace: 'comment-link',+ nodes: [CommentNode],+ onError: (error) => {+ throw error;+ },+ });+ const wrapper: LexicalWrapperWithMapping = {+ type: 'markdown',+ owner: null,+ editor,+ cleanup: () => {},+ isInteractable: () => true,+ mapping: { idToNodeKeyMap: new Map(), nodeKeyToIdMap: new Map() },+ plugins: {+ use: (plugin: (editor: LexicalEditor) => () => void) =>+ onCleanup(plugin(editor)),+ } as unknown as PluginManager,+ };+ render(() => (+ <LexicalWrapperContext.Provider value={wrapper}>+ <div+ ref={(el) => {+ onMount(() => editor.setRootElement(el));+ onCleanup(() => editor.setRootElement(null));+ }}+ />+ <MessageCommentsProvider+ activeComment={activeComment}+ loroManager={{ peerIdStr: '1' } as unknown as LoroManager}+ />+ </LexicalWrapperContext.Provider>+ ));+ return {+ state,+ scroll,+ loadComments: () =>+ batch(() => {+ setRootId('root');+ setThreads([thread]);+ }),+ loadMarks: () =>+ editor.update(+ () => {+ const mark = $createCommentNode({ ids: ['mark'], isDraft: false });+ mark.append($createTextNode('Commented text'));+ $getRoot().append($createParagraphNode().append(mark));+ },+ { discrete: true }+ ),+ finishLoading: () => state.editor.setMd('locationReady', true),+ detachEditor: () => {+ const root = editor.getRootElement()!;+ const parent = root.parentElement!;+ root.remove();+ return () => parent.append(root);+ },+ navigateAgain: () =>+ batch(() => {+ setNavigationCount((count) => count + 1);+ setActiveComment('reply');+ }),+ };+}++describe('inline comment link navigation', () => {+ it('waits for editor initialization even when comments and marks arrive first', () => {+ const f = setup();+ f.loadComments();+ f.loadMarks();+ expect(f.state.comments.commentMarksInitialized).toBe(true);+ expect(f.scroll).not.toHaveBeenCalled();+ expect(f.state.comments.activeCommentThread).toBeNull();++ f.finishLoading();+ expect(f.scroll).toHaveBeenCalledOnce();+ expect(f.state.comments.activeCommentThread).toBe('root');+ expect(f.state.comments.highlightedCommentId).toBe('reply');+ });++ it('waits for comment data when the editor loads first', () => {+ const f = setup();+ f.loadMarks();+ f.finishLoading();+ expect(f.scroll).not.toHaveBeenCalled();+ f.loadComments();+ expect(f.scroll).toHaveBeenCalledOnce();+ expect(f.state.comments.highlightedCommentId).toBe('reply');+ });++ it('does not steal focus after handling a link, but allows another click', () => {+ const f = setup();+ f.loadComments();+ f.loadMarks();+ f.finishLoading();+ f.state.setCommentState('activeCommentThread', null);+ f.state.setCommentState('highlightedCommentId', null);+ f.loadComments();+ expect(f.scroll).toHaveBeenCalledOnce();+ expect(f.state.comments.highlightedCommentId).toBeNull();++ f.navigateAgain();+ expect(f.scroll).toHaveBeenCalledTimes(2);+ expect(f.state.comments.highlightedCommentId).toBe('reply');+ });++ it('keeps the navigation pending while the editor is detached', () => {+ const callbacks = new Set<() => void>();+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ constructor(private callback: () => void) {}+ observe() {+ callbacks.add(this.callback);+ }+ disconnect() {+ callbacks.delete(this.callback);+ }+ }+ );+ const f = setup();+ const reattach = f.detachEditor();+ f.loadComments();+ f.loadMarks();+ f.finishLoading();+ expect(f.scroll).not.toHaveBeenCalled();++ reattach();+ for (const callback of callbacks) callback();+ expect(f.scroll).toHaveBeenCalledOnce();+ expect(f.state.comments.activeCommentThread).toBe('root');+ expect(f.state.comments.highlightedCommentId).toBe('reply');+ expect(callbacks.size).toBe(0);+ });+});diff --git a/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx b/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsxindex 45ce46ef7b..95059ced4e 100644--- a/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx+++ b/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx@@ -29,6 +29,7 @@ import {import { usePatchThreadMutation } from '@queries/messages/mutations';import { onThreadStateUpdated } from '@queries/messages/sync';import type { MessageThread } from '@service-storage/messages';+import { onElementConnect } from '@solid-primitives/lifecycle';import {$getNodeByKey,COMMAND_PRIORITY_LOW,@@ -535,6 +536,10 @@ export const MessageCommentsProvider: VoidComponent<{const commentId = target.messageId() ?? undefined;if (!commentId) return;if (!commentState.commentMarksInitialized) return;+ // Marks are published during Lexical initialization, before its initial+ // selection and layout have settled. Keep the navigation pending until+ // the editor is ready to honor it.+ if (!state.editor.md.locationReady) return;const commentThreads = commentThreadsData() ?? [];const targetThread = commentThreads.find(@@ -554,14 +559,17 @@ export const MessageCommentsProvider: VoidComponent<{const comment =commentsStore.get[commentId] ?? commentsStore.get[target.rootId() ?? ''];if (!comment) return;- setHighlightedId(commentId);const mark = marks[comment.anchorId];- if (mark) {- const firstEl = Object.values(mark.markNodes)[0];- firstEl?.scrollIntoView({ behavior: 'smooth', block: 'center' });- }- activeCommentThreadSignal.set(comment.threadId);- handledNavigation = navigation;+ const firstEl = Object.values(mark?.markNodes ?? {}).find(+ (element) => element !== undefined+ );+ if (!firstEl) return;+ onElementConnect(firstEl, () => {+ handledNavigation = navigation;+ setHighlightedId(commentId);+ firstEl.scrollIntoView({ behavior: 'smooth', block: 'center' });+ activeCommentThreadSignal.set(comment.threadId);+ });});autoRegister(diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.mdindex 490db147eb..39f0ddacab 100644--- a/docs/AGENT_GUIDE/documents.md+++ b/docs/AGENT_GUIDE/documents.md@@ -519,6 +519,13 @@ keeps at least 16px ofbottom clearance above the drawer's curve, including while the keyboard is open,and accounts for the home-indicator safe area when the keyboard is closed.+An inline-comment notification or `/app/md/<id>?comment_id=<comment-id>` link+should scroll to the anchor and open its thread on the first click, including+when the document has not loaded yet. Verify both comments arriving before the+editor and comments arriving after it. Once loaded, click elsewhere in the+document, then click the same notification again: it should revisit the comment,+while background comment refreshes should leave the user's position alone.+When checking desktop margin placement, scroll a long document while an embedor image above the highlighted text changes height. Scroll anchoring may keepthe text at the same screen position; its comment card should stay aligned